UNPKG

typeorm

Version:

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

911 lines • 137 kB
import { __awaiter, __extends, __generator, __read, __spreadArray, __values } from "tslib"; import { QueryResult } from "../../query-runner/QueryResult"; 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 { TableForeignKey } from "../../schema-builder/table/TableForeignKey"; import { TableIndex } from "../../schema-builder/table/TableIndex"; import { QueryRunnerAlreadyReleasedError } from "../../error/QueryRunnerAlreadyReleasedError"; import { View } from "../../schema-builder/view/View"; import { Query } from "../Query"; import { OrmUtils } from "../../util/OrmUtils"; import { QueryFailedError } from "../../error/QueryFailedError"; import { TableUnique } from "../../schema-builder/table/TableUnique"; import { BaseQueryRunner } from "../../query-runner/BaseQueryRunner"; import { Broadcaster } from "../../subscriber/Broadcaster"; import { VersionUtils } from "../../util/VersionUtils"; import { BroadcasterResult } from "../../subscriber/BroadcasterResult"; import { TypeORMError } from "../../error"; /** * Runs queries on a single mysql database connection. */ var MysqlQueryRunner = /** @class */ (function (_super) { __extends(MysqlQueryRunner, _super); // ------------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------------- function MysqlQueryRunner(driver, mode) { var _this = _super.call(this) || this; _this.driver = driver; _this.connection = driver.connection; _this.broadcaster = new Broadcaster(_this); _this.mode = mode; return _this; } // ------------------------------------------------------------------------- // Public Methods // ------------------------------------------------------------------------- /** * Creates/uses database connection from the connection pool to perform further operations. * Returns obtained database connection. */ MysqlQueryRunner.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 (connection) { _this.databaseConnection = connection; return _this.databaseConnection; }); } else { // master this.databaseConnectionPromise = this.driver.obtainMasterConnection().then(function (connection) { _this.databaseConnection = connection; return _this.databaseConnection; }); } return this.databaseConnectionPromise; }; /** * Releases used database connection. * You cannot use query runner methods once its released. */ MysqlQueryRunner.prototype.release = function () { this.isReleased = true; if (this.databaseConnection) this.databaseConnection.release(); return Promise.resolve(); }; /** * Starts transaction on the current connection. */ MysqlQueryRunner.prototype.startTransaction = function (isolationLevel) { return __awaiter(this, void 0, void 0, function () { var beforeBroadcastResult, afterBroadcastResult; return __generator(this, function (_a) { switch (_a.label) { case 0: if (this.isTransactionActive) throw new TransactionAlreadyStartedError(); beforeBroadcastResult = new BroadcasterResult(); this.broadcaster.broadcastBeforeTransactionStartEvent(beforeBroadcastResult); if (!(beforeBroadcastResult.promises.length > 0)) return [3 /*break*/, 2]; return [4 /*yield*/, Promise.all(beforeBroadcastResult.promises)]; case 1: _a.sent(); _a.label = 2; case 2: this.isTransactionActive = true; if (!isolationLevel) return [3 /*break*/, 5]; return [4 /*yield*/, this.query("SET TRANSACTION ISOLATION LEVEL " + isolationLevel)]; case 3: _a.sent(); return [4 /*yield*/, this.query("START TRANSACTION")]; case 4: _a.sent(); return [3 /*break*/, 7]; case 5: return [4 /*yield*/, this.query("START TRANSACTION")]; case 6: _a.sent(); _a.label = 7; case 7: afterBroadcastResult = new BroadcasterResult(); this.broadcaster.broadcastAfterTransactionStartEvent(afterBroadcastResult); if (!(afterBroadcastResult.promises.length > 0)) return [3 /*break*/, 9]; return [4 /*yield*/, Promise.all(afterBroadcastResult.promises)]; case 8: _a.sent(); _a.label = 9; case 9: return [2 /*return*/]; } }); }); }; /** * Commits transaction. * Error will be thrown if transaction was not started. */ MysqlQueryRunner.prototype.commitTransaction = function () { return __awaiter(this, void 0, void 0, function () { var beforeBroadcastResult, afterBroadcastResult; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this.isTransactionActive) throw new TransactionNotStartedError(); beforeBroadcastResult = new BroadcasterResult(); this.broadcaster.broadcastBeforeTransactionCommitEvent(beforeBroadcastResult); if (!(beforeBroadcastResult.promises.length > 0)) return [3 /*break*/, 2]; return [4 /*yield*/, Promise.all(beforeBroadcastResult.promises)]; case 1: _a.sent(); _a.label = 2; case 2: return [4 /*yield*/, this.query("COMMIT")]; case 3: _a.sent(); this.isTransactionActive = false; afterBroadcastResult = new BroadcasterResult(); this.broadcaster.broadcastAfterTransactionCommitEvent(afterBroadcastResult); if (!(afterBroadcastResult.promises.length > 0)) return [3 /*break*/, 5]; return [4 /*yield*/, Promise.all(afterBroadcastResult.promises)]; case 4: _a.sent(); _a.label = 5; case 5: return [2 /*return*/]; } }); }); }; /** * Rollbacks transaction. * Error will be thrown if transaction was not started. */ MysqlQueryRunner.prototype.rollbackTransaction = function () { return __awaiter(this, void 0, void 0, function () { var beforeBroadcastResult, afterBroadcastResult; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this.isTransactionActive) throw new TransactionNotStartedError(); beforeBroadcastResult = new BroadcasterResult(); this.broadcaster.broadcastBeforeTransactionRollbackEvent(beforeBroadcastResult); if (!(beforeBroadcastResult.promises.length > 0)) return [3 /*break*/, 2]; return [4 /*yield*/, Promise.all(beforeBroadcastResult.promises)]; case 1: _a.sent(); _a.label = 2; case 2: return [4 /*yield*/, this.query("ROLLBACK")]; case 3: _a.sent(); this.isTransactionActive = false; afterBroadcastResult = new BroadcasterResult(); this.broadcaster.broadcastAfterTransactionRollbackEvent(afterBroadcastResult); if (!(afterBroadcastResult.promises.length > 0)) return [3 /*break*/, 5]; return [4 /*yield*/, Promise.all(afterBroadcastResult.promises)]; case 4: _a.sent(); _a.label = 5; case 5: return [2 /*return*/]; } }); }); }; /** * Executes a raw SQL query. */ MysqlQueryRunner.prototype.query = function (query, parameters, useStructuredResult) { if (useStructuredResult === void 0) { useStructuredResult = false; } return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { if (this.isReleased) throw new QueryRunnerAlreadyReleasedError(); return [2 /*return*/, new Promise(function (ok, fail) { return __awaiter(_this, void 0, void 0, function () { var databaseConnection, queryStartTime_1, err_1; var _this = this; 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, raw) { // log slow queries if maxQueryExecution time is set var maxQueryExecutionTime = _this.driver.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); return fail(new QueryFailedError(query, parameters, err)); } var result = new QueryResult(); result.raw = raw; try { result.records = Array.from(raw); } catch (_a) { // Do nothing. } if (raw === null || raw === void 0 ? void 0 : raw.hasOwnProperty('affectedRows')) { result.affected = raw.affectedRows; } if (useStructuredResult) { ok(result); } else { ok(result.raw); } }); 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. */ MysqlQueryRunner.prototype.stream = function (query, parameters, onEnd, onError) { var _this = this; if (this.isReleased) throw new QueryRunnerAlreadyReleasedError(); return new Promise(function (ok, fail) { return __awaiter(_this, void 0, void 0, function () { var databaseConnection, databaseQuery, 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); databaseQuery = databaseConnection.query(query, parameters); if (onEnd) databaseQuery.on("end", onEnd); if (onError) databaseQuery.on("error", onError); ok(databaseQuery.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. */ MysqlQueryRunner.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. */ MysqlQueryRunner.prototype.getSchemas = function (database) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { throw new TypeORMError("MySql driver does not support table schemas"); }); }); }; /** * Checks if database with the given name exist. */ MysqlQueryRunner.prototype.hasDatabase = function (database) { 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` = '" + database + "'")]; case 1: result = _a.sent(); return [2 /*return*/, result.length ? true : false]; } }); }); }; /** * Loads currently using database */ MysqlQueryRunner.prototype.getCurrentDatabase = function () { return __awaiter(this, void 0, void 0, function () { var query; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.query("SELECT DATABASE() AS `db_name`")]; case 1: query = _a.sent(); return [2 /*return*/, query[0]["db_name"]]; } }); }); }; /** * Checks if schema with the given name exist. */ MysqlQueryRunner.prototype.hasSchema = function (schema) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { throw new TypeORMError("MySql driver does not support table schemas"); }); }); }; /** * Loads currently using database schema */ MysqlQueryRunner.prototype.getCurrentSchema = function () { return __awaiter(this, void 0, void 0, function () { var query; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.query("SELECT SCHEMA() AS `schema_name`")]; case 1: query = _a.sent(); return [2 /*return*/, query[0]["schema_name"]]; } }); }); }; /** * Checks if table with the given name exist in the database. */ MysqlQueryRunner.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.driver.parseTableName(tableOrName); sql = "SELECT * FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = '" + parsedTableName.database + "' 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. */ MysqlQueryRunner.prototype.hasColumn = function (tableOrName, column) { return __awaiter(this, void 0, void 0, function () { var parsedTableName, columnName, sql, result; return __generator(this, function (_a) { switch (_a.label) { case 0: parsedTableName = this.driver.parseTableName(tableOrName); columnName = column instanceof TableColumn ? column.name : column; sql = "SELECT * FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = '" + parsedTableName.database + "' 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. */ MysqlQueryRunner.prototype.createDatabase = function (database, 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 DATABASE IF NOT EXISTS `" + database + "`" : "CREATE DATABASE `" + database + "`"; down = "DROP DATABASE `" + database + "`"; return [4 /*yield*/, this.executeQueries(new Query(up), new Query(down))]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Drops database. */ MysqlQueryRunner.prototype.dropDatabase = function (database, ifExist) { return __awaiter(this, void 0, void 0, function () { var up, down; return __generator(this, function (_a) { switch (_a.label) { case 0: up = ifExist ? "DROP DATABASE IF EXISTS `" + database + "`" : "DROP DATABASE `" + database + "`"; down = "CREATE DATABASE `" + database + "`"; return [4 /*yield*/, this.executeQueries(new Query(up), new Query(down))]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }; /** * Creates a new table schema. */ MysqlQueryRunner.prototype.createSchema = function (schemaPath, ifNotExist) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { throw new TypeORMError("Schema create queries are not supported by MySql driver."); }); }); }; /** * Drops table schema. */ MysqlQueryRunner.prototype.dropSchema = function (schemaPath, ifExist) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { throw new TypeORMError("Schema drop queries are not supported by MySql driver."); }); }); }; /** * Creates a new table. */ MysqlQueryRunner.prototype.createTable = function (table, ifNotExist, createForeignKeys) { if (ifNotExist === void 0) { ifNotExist = false; } if (createForeignKeys === void 0) { createForeignKeys = true; } return __awaiter(this, void 0, void 0, function () { var isTableExist, upQueries, downQueries; var _this = this; 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 = []; upQueries.push(this.createTableSql(table, createForeignKeys)); downQueries.push(this.dropTableSql(table)); // we must first drop indices, than drop foreign keys, because drop queries runs in reversed order // and foreign keys will be dropped first as indices. This order is very important, because we can't drop index // if it related to the foreign key. // createTable does not need separate method to create indices, because it create indices in the same query with table creation. table.indices.forEach(function (index) { return downQueries.push(_this.dropIndexSql(table, index)); }); // 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)); }); return [2 /*return*/, this.executeQueries(upQueries, downQueries)]; } }); }); }; /** * Drop the table. */ MysqlQueryRunner.prototype.dropTable = function (target, ifExist, dropForeignKeys) { if (dropForeignKeys === void 0) { dropForeignKeys = true; } return __awaiter(this, void 0, void 0, function () { var isTableExist, createForeignKeys, tablePath, table, upQueries, downQueries; var _this = this; 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; tablePath = this.getTablePath(target); return [4 /*yield*/, this.getCachedTable(tablePath)]; case 3: table = _a.sent(); upQueries = []; downQueries = []; if (dropForeignKeys) table.foreignKeys.forEach(function (foreignKey) { return upQueries.push(_this.dropForeignKeySql(table, foreignKey)); }); table.indices.forEach(function (index) { return upQueries.push(_this.dropIndexSql(table, index)); }); 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*/]; } }); }); }; /** * Creates a new view. */ MysqlQueryRunner.prototype.createView = function (view) { return __awaiter(this, void 0, void 0, function () { var upQueries, downQueries, _a, _b, _c, _d; return __generator(this, function (_e) { switch (_e.label) { case 0: upQueries = []; downQueries = []; upQueries.push(this.createViewSql(view)); _b = (_a = upQueries).push; return [4 /*yield*/, this.insertViewDefinitionSql(view)]; case 1: _b.apply(_a, [_e.sent()]); downQueries.push(this.dropViewSql(view)); _d = (_c = downQueries).push; return [4 /*yield*/, this.deleteViewDefinitionSql(view)]; case 2: _d.apply(_c, [_e.sent()]); return [4 /*yield*/, this.executeQueries(upQueries, downQueries)]; case 3: _e.sent(); return [2 /*return*/]; } }); }); }; /** * Drops the view. */ MysqlQueryRunner.prototype.dropView = function (target) { return __awaiter(this, void 0, void 0, function () { var viewName, view, upQueries, downQueries, _a, _b, _c, _d; return __generator(this, function (_e) { switch (_e.label) { case 0: viewName = target instanceof View ? target.name : target; return [4 /*yield*/, this.getCachedView(viewName)]; case 1: view = _e.sent(); upQueries = []; downQueries = []; _b = (_a = upQueries).push; return [4 /*yield*/, this.deleteViewDefinitionSql(view)]; case 2: _b.apply(_a, [_e.sent()]); upQueries.push(this.dropViewSql(view)); _d = (_c = downQueries).push; return [4 /*yield*/, this.insertViewDefinitionSql(view)]; case 3: _d.apply(_c, [_e.sent()]); downQueries.push(this.createViewSql(view)); return [4 /*yield*/, this.executeQueries(upQueries, downQueries)]; case 4: _e.sent(); return [2 /*return*/]; } }); }); }; /** * Renames a table. */ MysqlQueryRunner.prototype.renameTable = function (oldTableOrName, newTableName) { return __awaiter(this, void 0, void 0, function () { var upQueries, downQueries, oldTable, _a, newTable, database; var _this = this; 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(); database = this.driver.parseTableName(oldTable).database; newTable.name = database ? database + "." + newTableName : newTableName; // rename table upQueries.push(new Query("RENAME TABLE " + this.escapePath(oldTable) + " TO " + this.escapePath(newTable))); downQueries.push(new Query("RENAME TABLE " + this.escapePath(newTable) + " TO " + this.escapePath(oldTable))); // rename index constraints newTable.indices.forEach(function (index) { // build new constraint name var columnNames = index.columnNames.map(function (column) { return "`" + column + "`"; }).join(", "); var newIndexName = _this.connection.namingStrategy.indexName(newTable, index.columnNames, index.where); // build queries var indexType = ""; if (index.isUnique) indexType += "UNIQUE "; if (index.isSpatial) indexType += "SPATIAL "; if (index.isFulltext) indexType += "FULLTEXT "; var indexParser = index.isFulltext && index.parser ? " WITH PARSER " + index.parser : ""; upQueries.push(new Query("ALTER TABLE " + _this.escapePath(newTable) + " DROP INDEX `" + index.name + "`, ADD " + indexType + "INDEX `" + newIndexName + "` (" + columnNames + ")" + indexParser)); downQueries.push(new Query("ALTER TABLE " + _this.escapePath(newTable) + " DROP INDEX `" + newIndexName + "`, ADD " + indexType + "INDEX `" + index.name + "` (" + columnNames + ")" + indexParser)); // replace constraint name index.name = newIndexName; }); // rename foreign key constraint newTable.foreignKeys.forEach(function (foreignKey) { // build new constraint name var columnNames = foreignKey.columnNames.map(function (column) { return "`" + column + "`"; }).join(", "); var referencedColumnNames = foreignKey.referencedColumnNames.map(function (column) { return "`" + column + "`"; }).join(","); var newForeignKeyName = _this.connection.namingStrategy.foreignKeyName(newTable, foreignKey.columnNames, _this.getTablePath(foreignKey), foreignKey.referencedColumnNames); // build queries var up = "ALTER TABLE " + _this.escapePath(newTable) + " DROP FOREIGN KEY `" + foreignKey.name + "`, ADD CONSTRAINT `" + newForeignKeyName + "` FOREIGN KEY (" + columnNames + ") " + ("REFERENCES " + _this.escapePath(_this.getTablePath(foreignKey)) + "(" + referencedColumnNames + ")"); if (foreignKey.onDelete) up += " ON DELETE " + foreignKey.onDelete; if (foreignKey.onUpdate) up += " ON UPDATE " + foreignKey.onUpdate; var down = "ALTER TABLE " + _this.escapePath(newTable) + " DROP FOREIGN KEY `" + newForeignKeyName + "`, ADD CONSTRAINT `" + foreignKey.name + "` FOREIGN KEY (" + columnNames + ") " + ("REFERENCES " + _this.escapePath(_this.getTablePath(foreignKey)) + "(" + referencedColumnNames + ")"); if (foreignKey.onDelete) down += " ON DELETE " + foreignKey.onDelete; if (foreignKey.onUpdate) down += " ON UPDATE " + foreignKey.onUpdate; upQueries.push(new Query(up)); downQueries.push(new Query(down)); // replace constraint name foreignKey.name = newForeignKeyName; }); return [4 /*yield*/, this.executeQueries(upQueries, downQueries)]; case 4: _b.sent(); // rename old table and replace it in cached tabled; oldTable.name = newTable.name; this.replaceCachedTable(oldTable, newTable); return [2 /*return*/]; } }); }); }; /** * Creates a new column from the column in the table. */ MysqlQueryRunner.prototype.addColumn = function (tableOrName, column) { return __awaiter(this, void 0, void 0, function () { var table, _a, clonedTable, upQueries, downQueries, skipColumnLevelPrimary, generatedColumn, nonGeneratedColumn, primaryColumns, columnNames, nonGeneratedColumn, columnIndex, uniqueIndex; 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 = []; skipColumnLevelPrimary = clonedTable.primaryColumns.length > 0; upQueries.push(new Query("ALTER TABLE " + this.escapePath(table) + " ADD " + this.buildCreateColumnSql(column, skipColumnLevelPrimary, false))); downQueries.push(new Query("ALTER TABLE " + this.escapePath(table) + " DROP COLUMN `" + column.name + "`")); // create or update primary key constraint if (column.isPrimary && skipColumnLevelPrimary) { generatedColumn = clonedTable.columns.find(function (column) { return column.isGenerated && column.generationStrategy === "increment"; }); if (generatedColumn) { nonGeneratedColumn = generatedColumn.clone(); nonGeneratedColumn.isGenerated = false; nonGeneratedColumn.generationStrategy = undefined; upQueries.push(new Query("ALTER TABLE " + this.escapePath(table) + " CHANGE `" + column.name + "` " + this.buildCreateColumnSql(nonGeneratedColumn, true))); downQueries.push(new Query("ALTER TABLE " + this.escapePath(table) + " CHANGE `" + nonGeneratedColumn.name + "` " + this.buildCreateColumnSql(column, true))); } primaryColumns = clonedTable.primaryColumns; columnNames = primaryColumns.map(function (column) { return "`" + column.name + "`"; }).join(", "); upQueries.push(new Query("ALTER TABLE " + this.escapePath(table) + " DROP PRIMARY KEY")); downQueries.push(new Query("ALTER TABLE " + this.escapePath(table) + " ADD PRIMARY KEY (" + columnNames + ")")); primaryColumns.push(column); columnNames = primaryColumns.map(function (column) { return "`" + column.name + "`"; }).join(", "); upQueries.push(new Query("ALTER TABLE " + this.escapePath(table) + " ADD PRIMARY KEY (" + columnNames + ")")); downQueries.push(new Query("ALTER TABLE " + this.escapePath(table) + " DROP PRIMARY KEY")); // if we previously dropped AUTO_INCREMENT property, we must bring it back if (generatedColumn) { nonGeneratedColumn = generatedColumn.clone(); nonGeneratedColumn.isGenerated = false; nonGeneratedColumn.generationStrategy = undefined; upQueries.push(new Query("ALTER TABLE " + this.escapePath(table) + " CHANGE `" + nonGeneratedColumn.name + "` " + this.buildCreateColumnSql(column, true))); downQueries.push(new Query("ALTER TABLE " + this.escapePath(table) + " CHANGE `" + column.name + "` " + this.buildCreateColumnSql(nonGeneratedColumn, true))); } } 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)); } else if (column.isUnique) { uniqueIndex = new TableIndex({ name: this.connection.namingStrategy.indexName(table, [column.name]), columnNames: [column.name], isUnique: true }); clonedTable.indices.push(uniqueIndex); clonedTable.uniques.push(new TableUnique({ name: uniqueIndex.name, columnNames: uniqueIndex.columnNames })); upQueries.push(new Query("ALTER TABLE " + this.escapePath(table) + " ADD UNIQUE INDEX `" + uniqueIndex.name + "` (`" + column.name + "`)")); downQueries.push(new Query("ALTER TABLE " + this.escapePath(table) + " DROP INDEX `" + uniqueIndex.name + "`")); } return [4 /*yield*/, this.executeQueries(upQueries, downQueries)]; case 4: _b.sent(); clonedTable.addColumn(column); this.replaceCachedTable(table, clonedTable); return [2 /*return*/]; } }); }); }; /** * Creates a new columns from the column in the table. */ MysqlQueryRunner.prototype.addColumns = function (tableOrName, columns) { return __awaiter(this, void 0, void 0, function () { var columns_1, columns_1_1, column, e_1_1; var e_1, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _b.trys.push([0, 5, 6, 7]); columns_1 = __values(columns), columns_1_1 = columns_1.next(); _b.label = 1; case 1: if (!!columns_1_1.done) return [3 /*break*/, 4]; column = columns_1_1.value; return [4 /*yield*/, this.addColumn(tableOrName, column)]; case 2: _b.sent(); _b.label = 3; case 3: columns_1_1 = columns_1.next(); return [3 /*break*/, 1]; case 4: return [3 /*break*/, 7]; case 5: e_1_1 = _b.sent(); e_1 = { error: e_1_1 }; return [3 /*break*/, 7]; case 6: try { if (columns_1_1 && !columns_1_1.done && (_a = columns_1.return)) _a.call(columns_1); } finally { if (e_1) throw e_1.error; } return [7 /*endfinally*/]; case 7: return [2 /*return*/]; } }); }); }; /** * Renames column in the given table. */ MysqlQueryRunner.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 TypeORMError("Column \"" + oldTableColumnOrName + "\" was not found in the \"" + table.name + "\" table."); newColumn = undefined; if (newTableColumnOrName instanceof TableColumn) { newColumn = newTableColumnOrName; } else { newColumn = oldColumn.clone(); newColumn.name = newTableColumnOrName; } return [4 /*yield*/, this.changeColumn(table, oldColumn, newColumn)]; case 4: _b.sent(); return [2 /*return*/]; } }); }); }; /** * Changes a column in the table. */ MysqlQueryRunner.prototype.changeColumn = function (tableOrName, oldColumnOrName, newColumn) { return __awaiter(this, void 0, void 0, function () { var table, _a, clonedTable, upQueries, downQueries, oldColumn, oldTableColumn, generatedColumn, nonGeneratedColumn, primaryColumns, columnNames, column, columnNames, primaryColumn, column, columnNames, nonGeneratedColumn, uniqueIndex, uniqueIndex_1, tableUnique; var _this = this; 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 = oldColumnOrName instanceof TableColumn ? oldColumnOrName : table.columns.find(function (column) { return column.name === oldColumnOrName; }); if (!oldColumn) throw new TypeORMError("Column \"" + oldColumnOrName + "\" was not found in the \"" + table.name + "\" table."); if (!((newColumn.isGenerated !== oldColumn.isGenerated && newColumn.generationStrategy !== "uuid") || oldColumn.type !== newColumn.type || oldColumn.length !== newColumn.length || oldColumn.generatedType !== newColumn.generatedType)) return [3 /*break*/, 6]; return [4 /*yield*/, this.dropColumn(table, oldColumn)]; case 4: _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 (newColumn.name !== oldColumn.name) { // We don't change any column properties, just rename it. upQueries.push(new Query("ALTER TABLE " + this.escapePath(table) + " CHANGE `" + oldColumn.name + "` `" + newColumn.name + "` " + this.buildCreateColumnSql(oldColumn, true, true))); downQueries.push(new Query("ALTER TABLE " + this.escapePath(table) + " CHANGE `" + newColumn.name + "` `" + oldColumn.name + "` " + this.buildCreateColumnSql(oldColumn, true, true))); // 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 columnNames = index.columnNames.map(function (column) { return "`" + column + "`"; }).join(", "); var newIndexName = _this.connection.namingStrategy.indexName(clonedTable, index.columnNames, index.where); // build queries var indexType = ""; if (index.isUnique) indexType += "UNIQUE "; if (index.isSpatial) indexType += "SPATIAL "; if (index.isFulltext) indexType += "FULLTEXT "; var indexParser = index.isFulltext && index.parser ? " WITH PARSER " + index.parser : ""; upQueries.push(new Query("ALTER TABLE " + _this.escapePath(table) + " DROP INDEX `" + index.name + "`, ADD " + indexType + "INDEX `" + newIndexName + "` (" + columnNames + ")" + indexParser)); downQueries.push(new Query("ALTER TABLE " + _this.escapePath(table) + " DROP INDEX `" + newIndexName + "`, ADD " + indexType + "INDEX `" + index.name + "` (" + columnNames + ")" + indexParser)); // 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 columnNames = foreignKey.columnNames.map(function (column) { return "`" + column + "`"; }).join(", "); var referencedColumnNames = foreignKey.referencedColumnNames.map(function (column) { return "`" + column + "`"; }).join(","); var newForeignKeyName = _this.connection.namingStrategy.foreignKeyName(clonedTable, foreignKey.columnNames, _this.getTablePath(foreignKey), foreignKey.referencedColumnNames); // build queries var up = "ALTER TABLE " + _this.esca