all files / lib/ PostgresDatabaseManager.js

97.25% Statements 106/109
65.63% Branches 21/32
100% Functions 36/36
97.25% Lines 106/109
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271                                                                         11× 11× 11×   11×                                                                                                                                                                                 22× 22×   22× 22×                                     22× 22× 22× 22×   22× 22×   18×                                      
var _ = require('lodash')
  , pg = require('pg')
  , escape = require('pg-escape')
  , Promise = require('bluebird')
  , classUtils = require('./class-utils')
  , DatabaseManager = require('./DatabaseManager').default;
 
/**
 * @constructor
 */
function PostgresDatabaseManager() {
  DatabaseManager.apply(this, arguments);
  this._masterClient = null;
  this._cachedTableNames = null;
  this._cachedIdSequences = null;
}
 
classUtils.inherits(PostgresDatabaseManager, DatabaseManager);
 
/**
 * @Override
 */
PostgresDatabaseManager.prototype.createDbOwnerIfNotExist = function() {
  return this._masterQuery("DO $body$ BEGIN CREATE ROLE %I LOGIN PASSWORD %L; EXCEPTION WHEN others THEN RAISE NOTICE 'User exists, not re-creating'; END $body$;", [this.config.knex.connection.user, this.config.knex.connection.password])
};
 
/** 
 * @Override
 */
PostgresDatabaseManager.prototype.createDb = function(databaseName) {
  databaseName = databaseName || this.config.knex.connection.database;
  var collate = this.config.dbManager.collate;
  var owner = this.config.knex.connection.user;
  var self = this;
  var promise = Promise.reject();
 
  if (_.isEmpty(collate)) {
    promise = promise.catch(function () {
      return self._masterQuery("CREATE DATABASE %I OWNER = %I ENCODING = 'UTF-8' TEMPLATE template1", [databaseName, owner]);
    });
  } else {
    // Try to create with each collate. Use the first one that works. This is kind of a hack
    // but seems to be the only reliable way to make this work with both windows and unix.
    _.each(collate, function(locale) {
      promise = promise.catch(function() {
        return self._masterQuery("CREATE DATABASE %I OWNER = %I ENCODING = 'UTF-8' LC_COLLATE = %L TEMPLATE template0", [databaseName, owner, locale]);
      });
    });
  }
 
  return promise ;
};
 
/**
 * Drops database with name if db exists.
 *
 * @Override
 */
PostgresDatabaseManager.prototype.dropDb = function(databaseName) {
  var self = this;
  databaseName = databaseName || this.config.knex.connection.database;
  return this.closeKnex()
    .then(function () {
      return self._masterQuery("DROP DATABASE IF EXISTS %I", [databaseName]);
    });
};
 
/**
 * @Override
 */
PostgresDatabaseManager.prototype.copyDb = function(fromDatabaseName, toDatabaseName) {
  var self = this;
  return this.closeKnex()
    .then(function () {
      return self._masterQuery("CREATE DATABASE %I template %I", [toDatabaseName, fromDatabaseName]);
    });
};
 
/**
 * @Override
 */
PostgresDatabaseManager.prototype.truncateDb = function(ignoreTables) {
  var knex = this.knexInstance();
  var config = this.config;
 
  Eif (!this._cachedTableNames) {
    this._updateTableNameCache(knex, config);
  }
 
  return this._cachedTableNames.then(function (tableNames) {
    var filteredTableNames = _.filter(tableNames, function (tableName) {
      return !_.includes(ignoreTables || [], tableName);
    });
    Eif (!_.isEmpty(filteredTableNames)) {
      return knex.raw('TRUNCATE TABLE "' + filteredTableNames.join('","') + '" RESTART IDENTITY');
    }
  });
};
 
/**
 * @Override
 */
PostgresDatabaseManager.prototype.updateIdSequences = function() {
  var knex = this.knexInstance();
  var config = this.config;
 
  Eif (!this._cachedIdSequences) {
    this._updateIdSequenceCache(knex, config);
  }
 
  // Set current value of id sequence for each table.
  // If there are no rows in the table, the value will be set to sequence's minimum constraint.
  // Otherwise, it will be set to max(id) + 1.
  return this._cachedIdSequences.then(function (result) {
    var query = _.map(result.rows, function (row) {
      return escape("SELECT setval('%s', GREATEST(coalesce(max(id),0) + 1, '%s'), false) FROM \"%I\"",
                    row.sequence, row.min, row.table);
    });
 
    query = query.join(' UNION ALL ') + ';';
    return knex.raw(query);
  });
};
 
/**
 * @private
 */
PostgresDatabaseManager.prototype._updateTableNameCache = function(knex, config) {
  this._cachedTableNames = knex('pg_tables').select('tablename').where('schemaname', 'public').then(function (tables) {
    return _.map(tables, 'tablename');
  });
};
 
/**
 * Id sequence cache holds a Promise, that returns following objects:
 * {
 *   table: String, // Table that rest of the values target
 *   sequence: String, // Sequence for the primary key (which is assumed to be id)
 *   min: String // Minimum allowed value for the sequence
 * }
 *
 * These values are cached because they are not expected to change often,
 * and finding them is slow.
 *
 * @private
 */
PostgresDatabaseManager.prototype._updateIdSequenceCache = function(knex, config) {
  Iif (!this._cachedTableNames) {
    this._updateTableNameCache(knex, config);
  }
 
  this._cachedIdSequences = this._cachedTableNames.then(function (tableNames) {
    // Skip tables without id column.
    return knex('information_schema.columns')
      .select('table_name')
      .where('column_name', 'id')
      .then(function (tables) {
        return _.intersection(_.map(tables, 'table_name'), tableNames);
      });
  // Find name of the id sequence for each table.
  // This is required for searching the minimum constraint for the sequence.
  }).then(function (idTableNames) {
    var query = _.map(idTableNames, function (tableName) {
      return escape("SELECT '%I' AS table, pg_get_serial_sequence('\"%I\"', 'id') AS sequence",
                    tableName, tableName);
    });
 
    query = query.join(' UNION ALL ') + ';';
    return knex.raw(query);
  // Find min constraint for each of the id sequences.
  }).then(function (result) {
    var query = _.map(result.rows, function (row) {
      return escape("SELECT '%I' AS table, '%s' AS sequence, min_value AS min FROM %s",
                    row.table, row.sequence, row.sequence);
    });
 
    query = query.join(' UNION ALL ') + ';';
    return knex.raw(query);
  });
};
 
/**
 * @Override
 */
PostgresDatabaseManager.prototype.close = function() {
  var disconnectAll = [this.closeKnex()];
  Eif (this._masterClient) {
    disconnectAll.push(this._masterClient.then(function(client) {
      client.end();
    }));
    this._masterClient = null;
  }
  return Promise.all(disconnectAll);
};
 
/**
 * @private
 * @returns {Promise}
 */
PostgresDatabaseManager.prototype._masterQuery = function(query, params) {
  var self = this;
  if (!this._masterClient) {
    this._masterClient = this.create_masterClient();
  }
  return this._masterClient.then(function(client) {
    return self.perform_masterQuery(client, query, params);
  });
};
 
/**
 * @private
 * @returns {Promise}
 */
PostgresDatabaseManager.prototype.create_masterClient = function() {
  var self = this;
  return new Promise(function(resolve, reject) {
    var client = new pg.Client(self._masterConnectionUrl());
    client.connect(function(err) {
      Iif (err) {
        reject(err);
      } else {
        resolve(client);
      }
    });
  });
};
 
/**
 * @private
 * @returns {Promise}
 */
PostgresDatabaseManager.prototype.perform_masterQuery = function(client, query, params) {
  return new Promise(function(resolve, reject) {
    Eif (params) {
      var args = [query].concat(params);
      query = escape.apply(global, args);
    }
    client.query(query, function(err, result) {
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
  });
};
 
/**
 * @private
 * @returns {String}
 */
PostgresDatabaseManager.prototype._masterConnectionUrl = function() {
  var url = 'postgres://';
  Eif (this.config.dbManager.superUser) {
    url += this.config.dbManager.superUser;
  } else {
    throw new Error('DatabaseManager: database config must have `superUser`');
  }
  Eif (this.config.dbManager.superPassword) {
    url += ':' + this.config.dbManager.superPassword
  }
  var port = this.config.knex.connection.port || 5432;
  url += '@' + this.config.knex.connection.host + ':' + port + '/postgres';
  return url;
};
 
module.exports = {
  default: PostgresDatabaseManager,
  PostgresDatabaseManager: PostgresDatabaseManager
};