UNPKG

typeorm

Version:

Data-Mapper ORM for TypeScript, ES7, ES6, ES5. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, MongoDB databases.

859 lines • 139 kB
var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [0, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; import { TransactionAlreadyStartedError } from "../../error/TransactionAlreadyStartedError"; import { TransactionNotStartedError } from "../../error/TransactionNotStartedError"; import { TableColumn } from "../../schema-builder/table/TableColumn"; import { Table } from "../../schema-builder/table/Table"; import { TableIndex } from "../../schema-builder/table/TableIndex"; import { TableForeignKey } from "../../schema-builder/table/TableForeignKey"; import { QueryRunnerAlreadyReleasedError } from "../../error/QueryRunnerAlreadyReleasedError"; import { QueryFailedError } from "../../error/QueryFailedError"; import { Broadcaster } from "../../subscriber/Broadcaster"; import { TableUnique } from "../../schema-builder/table/TableUnique"; import { BaseQueryRunner } from "../../query-runner/BaseQueryRunner"; import { OrmUtils } from "../../util/OrmUtils"; import { PromiseUtils } from "../../"; import { TableCheck } from "../../schema-builder/table/TableCheck"; /** * Runs queries on a single postgres database connection. */ var PostgresQueryRunner = /** @class */ (function (_super) { __extends(PostgresQueryRunner, _super); // ------------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------------- function PostgresQueryRunner(driver, mode) { if (mode === void 0) { mode = "master"; } var _this = _super.call(this) || this; _this.driver = driver; _this.connection = driver.connection; _this.mode = mode; _this.broadcaster = new Broadcaster(_this); return _this; } // ------------------------------------------------------------------------- // Public Methods // ------------------------------------------------------------------------- /** * Creates/uses database connection from the connection pool to perform further operations. * Returns obtained database connection. */ PostgresQueryRunner.prototype.connect = function () { var _this = this; if (this.databaseConnection) return Promise.resolve(this.databaseConnection); if (this.databaseConnectionPromise) return this.databaseConnectionPromise; if (this.mode === "slave" && this.driver.isReplicated) { this.databaseConnectionPromise = this.driver.obtainSlaveConnection().then(function (_a) { var connection = _a[0], release = _a[1]; _this.driver.connectedQueryRunners.push(_this); _this.databaseConnection = connection; _this.releaseCallback = release; return _this.databaseConnection; }); } else { // master this.databaseConnectionPromise = this.driver.obtainMasterConnection().then(function (_a) { var connection = _a[0], release = _a[1]; _this.driver.connectedQueryRunners.push(_this); _this.databaseConnection = connection; _this.releaseCallback = release; return _this.databaseConnection; }); } return this.databaseConnectionPromise; }; /** * Releases used database connection. * You cannot use query runner methods once its released. */ PostgresQueryRunner.prototype.release = function () { this.isReleased = true; if (this.releaseCallback) this.releaseCallback(); var index = this.driver.connectedQueryRunners.indexOf(this); if (index !== -1) this.driver.connectedQueryRunners.splice(index); return Promise.resolve(); }; /** * Starts transaction. */ PostgresQueryRunner.prototype.startTransaction = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: if (this.isTransactionActive) throw new TransactionAlreadyStartedError(); this.isTransactionActive = true; return [4 /*yield*/, this.query("START TRANSACTION")]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Commits transaction. * Error will be thrown if transaction was not started. */ PostgresQueryRunner.prototype.commitTransaction = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this.isTransactionActive) throw new TransactionNotStartedError(); return [4 /*yield*/, this.query("COMMIT")]; case 1: _a.sent(); this.isTransactionActive = false; return [2 /*return*/]; } }); }); }; /** * Rollbacks transaction. * Error will be thrown if transaction was not started. */ PostgresQueryRunner.prototype.rollbackTransaction = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this.isTransactionActive) throw new TransactionNotStartedError(); return [4 /*yield*/, this.query("ROLLBACK")]; case 1: _a.sent(); this.isTransactionActive = false; return [2 /*return*/]; } }); }); }; /** * Executes a given SQL query. */ PostgresQueryRunner.prototype.query = function (query, parameters) { var _this = this; if (this.isReleased) throw new QueryRunnerAlreadyReleasedError(); return new Promise(function (ok, fail) { return __awaiter(_this, void 0, void 0, function () { var _this = this; var databaseConnection, queryStartTime_1, err_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.connect()]; case 1: databaseConnection = _a.sent(); this.driver.connection.logger.logQuery(query, parameters, this); queryStartTime_1 = +new Date(); databaseConnection.query(query, parameters, function (err, result) { // log slow queries if maxQueryExecution time is set var maxQueryExecutionTime = _this.driver.connection.options.maxQueryExecutionTime; var queryEndTime = +new Date(); var queryExecutionTime = queryEndTime - queryStartTime_1; if (maxQueryExecutionTime && queryExecutionTime > maxQueryExecutionTime) _this.driver.connection.logger.logQuerySlow(queryExecutionTime, query, parameters, _this); if (err) { _this.driver.connection.logger.logQueryError(err, query, parameters, _this); fail(new QueryFailedError(query, parameters, err)); } else { ok(result.rows); } }); return [3 /*break*/, 3]; case 2: err_1 = _a.sent(); fail(err_1); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }); }; /** * Returns raw data stream. */ PostgresQueryRunner.prototype.stream = function (query, parameters, onEnd, onError) { var _this = this; var QueryStream = this.driver.loadStreamDependency(); if (this.isReleased) throw new QueryRunnerAlreadyReleasedError(); return new Promise(function (ok, fail) { return __awaiter(_this, void 0, void 0, function () { var databaseConnection, stream, err_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, this.connect()]; case 1: databaseConnection = _a.sent(); this.driver.connection.logger.logQuery(query, parameters, this); stream = databaseConnection.query(new QueryStream(query, parameters)); if (onEnd) stream.on("end", onEnd); if (onError) stream.on("error", onError); ok(stream); return [3 /*break*/, 3]; case 2: err_2 = _a.sent(); fail(err_2); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); }); }; /** * Returns all available database names including system databases. */ PostgresQueryRunner.prototype.getDatabases = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, Promise.resolve([])]; }); }); }; /** * Returns all available schema names including system schemas. * If database parameter specified, returns schemas of that database. */ PostgresQueryRunner.prototype.getSchemas = function (database) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, Promise.resolve([])]; }); }); }; /** * Checks if database with the given name exist. */ PostgresQueryRunner.prototype.hasDatabase = function (database) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, Promise.resolve(false)]; }); }); }; /** * Checks if schema with the given name exist. */ PostgresQueryRunner.prototype.hasSchema = function (schema) { return __awaiter(this, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.query("SELECT * FROM \"information_schema\".\"schemata\" WHERE \"schema_name\" = '" + schema + "'")]; case 1: result = _a.sent(); return [2 /*return*/, result.length ? true : false]; } }); }); }; /** * Checks if table with the given name exist in the database. */ PostgresQueryRunner.prototype.hasTable = function (tableOrName) { return __awaiter(this, void 0, void 0, function () { var parsedTableName, sql, result; return __generator(this, function (_a) { switch (_a.label) { case 0: parsedTableName = this.parseTableName(tableOrName); sql = "SELECT * FROM \"information_schema\".\"tables\" WHERE \"table_schema\" = " + parsedTableName.schema + " AND \"table_name\" = " + parsedTableName.tableName; return [4 /*yield*/, this.query(sql)]; case 1: result = _a.sent(); return [2 /*return*/, result.length ? true : false]; } }); }); }; /** * Checks if column with the given name exist in the given table. */ PostgresQueryRunner.prototype.hasColumn = function (tableOrName, columnName) { return __awaiter(this, void 0, void 0, function () { var parsedTableName, sql, result; return __generator(this, function (_a) { switch (_a.label) { case 0: parsedTableName = this.parseTableName(tableOrName); sql = "SELECT * FROM \"information_schema\".\"columns\" WHERE \"table_schema\" = " + parsedTableName.schema + " AND \"table_name\" = " + parsedTableName.tableName + " AND \"column_name\" = '" + columnName + "'"; return [4 /*yield*/, this.query(sql)]; case 1: result = _a.sent(); return [2 /*return*/, result.length ? true : false]; } }); }); }; /** * Creates a new database. * Postgres does not supports database creation inside a transaction block. */ PostgresQueryRunner.prototype.createDatabase = function (database, ifNotExist) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, Promise.resolve()]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Drops database. * Postgres does not supports database drop inside a transaction block. */ PostgresQueryRunner.prototype.dropDatabase = function (database, ifExist) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, Promise.resolve()]; }); }); }; /** * Creates a new table schema. */ PostgresQueryRunner.prototype.createSchema = function (schema, ifNotExist) { return __awaiter(this, void 0, void 0, function () { var up, down; return __generator(this, function (_a) { switch (_a.label) { case 0: up = ifNotExist ? "CREATE SCHEMA IF NOT EXISTS \"" + schema + "\"" : "CREATE SCHEMA \"" + schema + "\""; down = "DROP SCHEMA \"" + schema + "\" CASCADE"; return [4 /*yield*/, this.executeQueries(up, down)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Drops table schema. */ PostgresQueryRunner.prototype.dropSchema = function (schemaPath, ifExist, isCascade) { return __awaiter(this, void 0, void 0, function () { var schema, up, down; return __generator(this, function (_a) { switch (_a.label) { case 0: schema = schemaPath.indexOf(".") === -1 ? schemaPath : schemaPath.split(".")[0]; up = ifExist ? "DROP SCHEMA IF EXISTS \"" + schema + "\" " + (isCascade ? "CASCADE" : "") : "DROP SCHEMA \"" + schema + "\" " + (isCascade ? "CASCADE" : ""); down = "CREATE SCHEMA \"" + schema + "\""; return [4 /*yield*/, this.executeQueries(up, down)]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Creates a new table. */ PostgresQueryRunner.prototype.createTable = function (table, ifNotExist, createForeignKeys, createIndices) { if (ifNotExist === void 0) { ifNotExist = false; } if (createForeignKeys === void 0) { createForeignKeys = true; } if (createIndices === void 0) { createIndices = true; } return __awaiter(this, void 0, void 0, function () { var _this = this; var isTableExist, upQueries, downQueries; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!ifNotExist) return [3 /*break*/, 2]; return [4 /*yield*/, this.hasTable(table)]; case 1: isTableExist = _a.sent(); if (isTableExist) return [2 /*return*/, Promise.resolve()]; _a.label = 2; case 2: upQueries = []; downQueries = []; // if table have column with ENUM type, we must create this type in postgres. return [4 /*yield*/, Promise.all(table.columns .filter(function (column) { return column.type === "enum"; }) .map(function (column) { return __awaiter(_this, void 0, void 0, function () { var hasEnum; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.hasEnumType(table, column)]; case 1: hasEnum = _a.sent(); if (!hasEnum) { upQueries.push(this.createEnumTypeSql(table, column)); downQueries.push(this.dropEnumTypeSql(table, column)); } return [2 /*return*/, Promise.resolve()]; } }); }); }))]; case 3: // if table have column with ENUM type, we must create this type in postgres. _a.sent(); upQueries.push(this.createTableSql(table, createForeignKeys)); downQueries.push(this.dropTableSql(table)); // if createForeignKeys is true, we must drop created foreign keys in down query. // createTable does not need separate method to create foreign keys, because it create fk's in the same query with table creation. if (createForeignKeys) table.foreignKeys.forEach(function (foreignKey) { return downQueries.push(_this.dropForeignKeySql(table, foreignKey)); }); if (createIndices) { table.indices.forEach(function (index) { // new index may be passed without name. In this case we generate index name manually. if (!index.name) index.name = _this.connection.namingStrategy.indexName(table.name, index.columnNames, index.where); upQueries.push(_this.createIndexSql(table, index)); downQueries.push(_this.dropIndexSql(table, index)); }); } return [4 /*yield*/, this.executeQueries(upQueries, downQueries)]; case 4: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Drops the table. */ PostgresQueryRunner.prototype.dropTable = function (target, ifExist, dropForeignKeys, dropIndices) { if (dropForeignKeys === void 0) { dropForeignKeys = true; } if (dropIndices === void 0) { dropIndices = true; } return __awaiter(this, void 0, void 0, function () { var _this = this; var isTableExist, createForeignKeys, tableName, table, upQueries, downQueries; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!ifExist) return [3 /*break*/, 2]; return [4 /*yield*/, this.hasTable(target)]; case 1: isTableExist = _a.sent(); if (!isTableExist) return [2 /*return*/, Promise.resolve()]; _a.label = 2; case 2: createForeignKeys = dropForeignKeys; tableName = target instanceof Table ? target.name : target; return [4 /*yield*/, this.getCachedTable(tableName)]; case 3: table = _a.sent(); upQueries = []; downQueries = []; if (dropIndices) { table.indices.forEach(function (index) { upQueries.push(_this.dropIndexSql(table, index)); downQueries.push(_this.createIndexSql(table, index)); }); } if (dropForeignKeys) table.foreignKeys.forEach(function (foreignKey) { return upQueries.push(_this.dropForeignKeySql(table, foreignKey)); }); upQueries.push(this.dropTableSql(table)); downQueries.push(this.createTableSql(table, createForeignKeys)); return [4 /*yield*/, this.executeQueries(upQueries, downQueries)]; case 4: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Renames the given table. */ PostgresQueryRunner.prototype.renameTable = function (oldTableOrName, newTableName) { return __awaiter(this, void 0, void 0, function () { var _this = this; var upQueries, downQueries, oldTable, _a, newTable, oldTableName, schemaName, columnNames, oldPkName, newPkName; return __generator(this, function (_b) { switch (_b.label) { case 0: upQueries = []; downQueries = []; if (!(oldTableOrName instanceof Table)) return [3 /*break*/, 1]; _a = oldTableOrName; return [3 /*break*/, 3]; case 1: return [4 /*yield*/, this.getCachedTable(oldTableOrName)]; case 2: _a = _b.sent(); _b.label = 3; case 3: oldTable = _a; newTable = oldTable.clone(); oldTableName = oldTable.name.indexOf(".") === -1 ? oldTable.name : oldTable.name.split(".")[1]; schemaName = oldTable.name.indexOf(".") === -1 ? undefined : oldTable.name.split(".")[0]; newTable.name = schemaName ? schemaName + "." + newTableName : newTableName; upQueries.push("ALTER TABLE " + this.escapeTableName(oldTable) + " RENAME TO \"" + newTableName + "\""); downQueries.push("ALTER TABLE " + this.escapeTableName(newTable) + " RENAME TO \"" + oldTableName + "\""); // rename column primary key constraint if (newTable.primaryColumns.length > 0) { columnNames = newTable.primaryColumns.map(function (column) { return column.name; }); oldPkName = this.connection.namingStrategy.primaryKeyName(oldTable, columnNames); newPkName = this.connection.namingStrategy.primaryKeyName(newTable, columnNames); upQueries.push("ALTER TABLE " + this.escapeTableName(newTable) + " RENAME CONSTRAINT \"" + oldPkName + "\" TO \"" + newPkName + "\""); downQueries.push("ALTER TABLE " + this.escapeTableName(newTable) + " RENAME CONSTRAINT \"" + newPkName + "\" TO \"" + oldPkName + "\""); } // rename unique constraints newTable.uniques.forEach(function (unique) { // build new constraint name var newUniqueName = _this.connection.namingStrategy.uniqueConstraintName(newTable, unique.columnNames); // build queries upQueries.push("ALTER TABLE " + _this.escapeTableName(newTable) + " RENAME CONSTRAINT \"" + unique.name + "\" TO \"" + newUniqueName + "\""); downQueries.push("ALTER TABLE " + _this.escapeTableName(newTable) + " RENAME CONSTRAINT \"" + newUniqueName + "\" TO \"" + unique.name + "\""); // replace constraint name unique.name = newUniqueName; }); // rename index constraints newTable.indices.forEach(function (index) { // build new constraint name var schema = _this.extractSchema(newTable); var newIndexName = _this.connection.namingStrategy.indexName(newTable, index.columnNames, index.where); // build queries var up = schema ? "ALTER INDEX \"" + schema + "\".\"" + index.name + "\" RENAME TO \"" + newIndexName + "\"" : "ALTER INDEX \"" + index.name + "\" RENAME TO \"" + newIndexName + "\""; var down = schema ? "ALTER INDEX \"" + schema + "\".\"" + newIndexName + "\" RENAME TO \"" + index.name + "\"" : "ALTER INDEX \"" + newIndexName + "\" RENAME TO \"" + index.name + "\""; upQueries.push(up); downQueries.push(down); // replace constraint name index.name = newIndexName; }); // rename foreign key constraints newTable.foreignKeys.forEach(function (foreignKey) { // build new constraint name var newForeignKeyName = _this.connection.namingStrategy.foreignKeyName(newTable, foreignKey.columnNames); // build queries upQueries.push("ALTER TABLE " + _this.escapeTableName(newTable) + " RENAME CONSTRAINT \"" + foreignKey.name + "\" TO \"" + newForeignKeyName + "\""); downQueries.push("ALTER TABLE " + _this.escapeTableName(newTable) + " RENAME CONSTRAINT \"" + newForeignKeyName + "\" TO \"" + foreignKey.name + "\""); // replace constraint name foreignKey.name = newForeignKeyName; }); // rename ENUM types newTable.columns .filter(function (column) { return column.type === "enum"; }) .forEach(function (column) { upQueries.push("ALTER TYPE " + _this.buildEnumName(oldTable, column) + " RENAME TO " + _this.buildEnumName(newTable, column, false)); downQueries.push("ALTER TYPE " + _this.buildEnumName(newTable, column) + " RENAME TO " + _this.buildEnumName(oldTable, column, false)); }); return [4 /*yield*/, this.executeQueries(upQueries, downQueries)]; case 4: _b.sent(); return [2 /*return*/]; } }); }); }; /** * Creates a new column from the column in the table. */ PostgresQueryRunner.prototype.addColumn = function (tableOrName, column) { return __awaiter(this, void 0, void 0, function () { var table, _a, clonedTable, upQueries, downQueries, hasEnum, primaryColumns, pkName_1, columnNames_1, pkName, columnNames, columnIndex, uniqueConstraint; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!(tableOrName instanceof Table)) return [3 /*break*/, 1]; _a = tableOrName; return [3 /*break*/, 3]; case 1: return [4 /*yield*/, this.getCachedTable(tableOrName)]; case 2: _a = _b.sent(); _b.label = 3; case 3: table = _a; clonedTable = table.clone(); upQueries = []; downQueries = []; if (!(column.type === "enum")) return [3 /*break*/, 5]; return [4 /*yield*/, this.hasEnumType(table, column)]; case 4: hasEnum = _b.sent(); if (!hasEnum) { upQueries.push(this.createEnumTypeSql(table, column)); downQueries.push(this.dropEnumTypeSql(table, column)); } _b.label = 5; case 5: upQueries.push("ALTER TABLE " + this.escapeTableName(table) + " ADD " + this.buildCreateColumnSql(table, column)); downQueries.push("ALTER TABLE " + this.escapeTableName(table) + " DROP COLUMN \"" + column.name + "\""); // create or update primary key constraint if (column.isPrimary) { primaryColumns = clonedTable.primaryColumns; // if table already have primary key, me must drop it and recreate again if (primaryColumns.length > 0) { pkName_1 = this.connection.namingStrategy.primaryKeyName(clonedTable.name, primaryColumns.map(function (column) { return column.name; })); columnNames_1 = primaryColumns.map(function (column) { return "\"" + column.name + "\""; }).join(", "); upQueries.push("ALTER TABLE " + this.escapeTableName(table) + " DROP CONSTRAINT \"" + pkName_1 + "\""); downQueries.push("ALTER TABLE " + this.escapeTableName(table) + " ADD CONSTRAINT \"" + pkName_1 + "\" PRIMARY KEY (" + columnNames_1 + ")"); } primaryColumns.push(column); pkName = this.connection.namingStrategy.primaryKeyName(clonedTable.name, primaryColumns.map(function (column) { return column.name; })); columnNames = primaryColumns.map(function (column) { return "\"" + column.name + "\""; }).join(", "); upQueries.push("ALTER TABLE " + this.escapeTableName(table) + " ADD CONSTRAINT \"" + pkName + "\" PRIMARY KEY (" + columnNames + ")"); downQueries.push("ALTER TABLE " + this.escapeTableName(table) + " DROP CONSTRAINT \"" + pkName + "\""); } columnIndex = clonedTable.indices.find(function (index) { return index.columnNames.length === 1 && index.columnNames[0] === column.name; }); if (columnIndex) { upQueries.push(this.createIndexSql(table, columnIndex)); downQueries.push(this.dropIndexSql(table, columnIndex)); } // create unique constraint if (column.isUnique) { uniqueConstraint = new TableUnique({ name: this.connection.namingStrategy.uniqueConstraintName(table.name, [column.name]), columnNames: [column.name] }); clonedTable.uniques.push(uniqueConstraint); upQueries.push("ALTER TABLE " + this.escapeTableName(table) + " ADD CONSTRAINT \"" + uniqueConstraint.name + "\" UNIQUE (\"" + column.name + "\")"); downQueries.push("ALTER TABLE " + this.escapeTableName(table) + " DROP CONSTRAINT \"" + uniqueConstraint.name + "\""); } return [4 /*yield*/, this.executeQueries(upQueries, downQueries)]; case 6: _b.sent(); clonedTable.addColumn(column); this.replaceCachedTable(table, clonedTable); return [2 /*return*/]; } }); }); }; /** * Creates a new columns from the column in the table. */ PostgresQueryRunner.prototype.addColumns = function (tableOrName, columns) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, PromiseUtils.runInSequence(columns, function (column) { return _this.addColumn(tableOrName, column); })]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Renames column in the given table. */ PostgresQueryRunner.prototype.renameColumn = function (tableOrName, oldTableColumnOrName, newTableColumnOrName) { return __awaiter(this, void 0, void 0, function () { var table, _a, oldColumn, newColumn; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!(tableOrName instanceof Table)) return [3 /*break*/, 1]; _a = tableOrName; return [3 /*break*/, 3]; case 1: return [4 /*yield*/, this.getCachedTable(tableOrName)]; case 2: _a = _b.sent(); _b.label = 3; case 3: table = _a; oldColumn = oldTableColumnOrName instanceof TableColumn ? oldTableColumnOrName : table.columns.find(function (c) { return c.name === oldTableColumnOrName; }); if (!oldColumn) throw new Error("Column \"" + oldTableColumnOrName + "\" was not found in the \"" + table.name + "\" table."); if (newTableColumnOrName instanceof TableColumn) { newColumn = newTableColumnOrName; } else { newColumn = oldColumn.clone(); newColumn.name = newTableColumnOrName; } return [2 /*return*/, this.changeColumn(table, oldColumn, newColumn)]; } }); }); }; /** * Changes a column in the table. */ PostgresQueryRunner.prototype.changeColumn = function (tableOrName, oldTableColumnOrName, newColumn) { return __awaiter(this, void 0, void 0, function () { var _this = this; var table, _a, clonedTable, upQueries, downQueries, oldColumn, primaryColumns, columnNames, oldPkName, newPkName, schema, seqName, newSeqName, up, down, oldTableColumn, enumName, enumNameWithoutSchema, oldEnumName, oldEnumNameWithoutSchema, upType, downType, primaryColumns, pkName, columnNames, column, pkName, columnNames, primaryColumn, column, pkName, columnNames, uniqueConstraint, uniqueConstraint; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!(tableOrName instanceof Table)) return [3 /*break*/, 1]; _a = tableOrName; return [3 /*break*/, 3]; case 1: return [4 /*yield*/, this.getCachedTable(tableOrName)]; case 2: _a = _b.sent(); _b.label = 3; case 3: table = _a; clonedTable = table.clone(); upQueries = []; downQueries = []; oldColumn = oldTableColumnOrName instanceof TableColumn ? oldTableColumnOrName : table.columns.find(function (column) { return column.name === oldTableColumnOrName; }); if (!oldColumn) throw new Error("Column \"" + oldTableColumnOrName + "\" was not found in the \"" + table.name + "\" table."); if (!(oldColumn.type !== newColumn.type || oldColumn.length !== newColumn.length)) return [3 /*break*/, 6]; // To avoid data conversion, we just recreate column return [4 /*yield*/, this.dropColumn(table, oldColumn)]; case 4: // To avoid data conversion, we just recreate column _b.sent(); return [4 /*yield*/, this.addColumn(table, newColumn)]; case 5: _b.sent(); // update cloned table clonedTable = table.clone(); return [3 /*break*/, 7]; case 6: if (oldColumn.name !== newColumn.name) { // rename column upQueries.push("ALTER TABLE " + this.escapeTableName(table) + " RENAME COLUMN \"" + oldColumn.name + "\" TO \"" + newColumn.name + "\""); downQueries.push("ALTER TABLE " + this.escapeTableName(table) + " RENAME COLUMN \"" + newColumn.name + "\" TO \"" + oldColumn.name + "\""); // rename ENUM type if (oldColumn.type === "enum") { upQueries.push("ALTER TYPE " + this.buildEnumName(table, oldColumn) + " RENAME TO " + this.buildEnumName(table, newColumn, false)); downQueries.push("ALTER TYPE " + this.buildEnumName(table, newColumn) + " RENAME TO " + this.buildEnumName(table, oldColumn, false)); } // rename column primary key constraint if (oldColumn.isPrimary === true) { primaryColumns = clonedTable.primaryColumns; columnNames = primaryColumns.map(function (column) { return column.name; }); oldPkName = this.connection.namingStrategy.primaryKeyName(clonedTable, columnNames); // replace old column name with new column name columnNames.splice(columnNames.indexOf(oldColumn.name), 1); columnNames.push(newColumn.name); newPkName = this.connection.namingStrategy.primaryKeyName(clonedTable, columnNames); upQueries.push("ALTER TABLE " + this.escapeTableName(table) + " RENAME CONSTRAINT \"" + oldPkName + "\" TO \"" + newPkName + "\""); downQueries.push("ALTER TABLE " + this.escapeTableName(table) + " RENAME CONSTRAINT \"" + newPkName + "\" TO \"" + oldPkName + "\""); } // rename column sequence if (oldColumn.isGenerated === true && newColumn.generationStrategy === "increment") { schema = this.extractSchema(table); seqName = this.buildSequenceName(table, oldColumn.name, undefined, true, true); newSeqName = this.buildSequenceName(table, newColumn.name, undefined, true, true); up = schema ? "ALTER SEQUENCE \"" + schema + "\".\"" + seqName + "\" RENAME TO \"" + newSeqName + "\"" : "ALTER SEQUENCE \"" + seqName + "\" RENAME TO \"" + newSeqName + "\""; down = schema ? "ALTER SEQUENCE \"" + schema + "\".\"" + newSeqName + "\" RENAME TO \"" + seqName + "\"" : "ALTER SEQUENCE \"" + newSeqName + "\" RENAME TO \"" + seqName + "\""; upQueries.push(up); downQueries.push(down); } // rename unique constraints clonedTable.findColumnUniques(oldColumn).forEach(function (unique) { // build new constraint name unique.columnNames.splice(unique.columnNames.indexOf(oldColumn.name), 1); unique.columnNames.push(newColumn.name); var newUniqueName = _this.connection.namingStrategy.uniqueConstraintName(clonedTable, unique.columnNames); // build queries upQueries.push("ALTER TABLE " + _this.escapeTableName(table) + " RENAME CONSTRAINT \"" + unique.name + "\" TO \"" + newUniqueName + "\""); downQueries.push("ALTER TABLE " + _this.escapeTableName(table) + " RENAME CONSTRAINT \"" + newUniqueName + "\" TO \"" + unique.name + "\""); // replace constraint name unique.name = newUniqueName; }); // rename index constraints clonedTable.findColumnIndices(oldColumn).forEach(function (index) { // build new constraint name index.columnNames.splice(index.columnNames.indexOf(oldColumn.name), 1); index.columnNames.push(newColumn.name); var schema = _this.extractSchema(table); var newIndexName = _this.connection.namingStrategy.indexName(clonedTable, index.columnNames, index.where); // build queries var up = schema ? "ALTER INDEX \"" + schema + "\".\"" + index.name + "\" RENAME TO \"" + newIndexName + "\"" : "ALTER INDEX \"" + index.name + "\" RENAME TO \"" + newIndexName + "\""; var down = schema ? "ALTER INDEX \"" + schema + "\".\"" + newIndexName + "\" RENAME TO \"" + index.name + "\"" : "ALTER INDEX \"" + newIndexName + "\" RENAME TO \"" + index.name + "\""; upQueries.push(up); downQueries.push(down); // replace constraint name index.name = newIndexName; }); // rename foreign key constraints clonedTable.findColumnForeignKeys(oldColumn).forEach(function (foreignKey) { // build new constraint name foreignKey.columnNames.splice(foreignKey.columnNames.indexOf(oldColumn.name), 1); foreignKey.columnNames.push(newColumn.name); var newForeignKeyName = _this.connection.namingStrategy.foreignKeyName(clonedTable, foreignKey.columnNames); // build queries upQueries.push("ALTER TABLE " + _this.escapeTableName(table) + " RENAME CONSTRAINT \"" + foreignKey.name + "\" TO \"" + newForeignKeyName + "\""); downQueries.push("ALTER TABLE " + _this.escapeTableName(table) + " RENAME CONSTRAINT \"" + newForeignKeyName + "\" TO \"" + foreignKey.name + "\""); // replace constraint name foreignKey.name = newForeignKeyName; }); oldTableColumn = clonedTable.columns.find(function (column) { return column.name === oldColumn.name; }); clonedTable.columns[clonedTable.columns.indexOf(oldTableColumn)].name = newColumn.name; oldColumn.name = newColumn.name; } if (newColumn.precision !== oldColumn.precision || newColumn.scale !== oldColumn.scale) { upQueries.push("ALTER TABLE " + this.escapeTableName(table) + " ALTER COLUMN \"" + newColumn.name + "\" TYPE " + this.driver.createFullType(newColumn)); downQueries.push("ALTER TABLE " + this.escapeTableName(table) + " ALTER COLUMN \"" + newColumn.name + "\" TYPE " + this.driver.createFullType(oldColumn)); } if (newColumn.type === "enum" && oldColumn.type === "enum" && !OrmUtils.isArraysEqual(newColumn.enum, oldColumn.enum)) { enumName = this.buildEnumName(table, newColumn); enumNameWithoutSchema = this.buildEnumName(table, newColumn, false); oldEnumName = this.buildEnumName(table, newColumn, true, false, true); oldEnumNameWithoutSchema = this.buildEnumName(table, newColumn, false, false, true); // rename old ENUM upQueries.push("ALTER TYPE " + enumName + " RENAME TO " + oldEnumNameWithoutSchema); downQueries.push("ALTER TYPE " + oldEnumName + " RENAME TO " + enumNameWithoutSchema); // create new ENUM upQueries.push(this.createEnumTypeSql(table, newColumn)); downQueries.push(this.dropEnumTypeSql(table, oldColumn)); // if column have default value, we must drop it to avoid issues with type casting if (newColumn.default !== nu