typeorm
Version:
Data-Mapper ORM for TypeScript and ES2021+. Supports MySQL/MariaDB, PostgreSQL, MS SQL Server, Oracle, SAP HANA, SQLite, MongoDB databases.
958 lines (957 loc) • 129 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SqlServerQueryRunner = void 0;
const error_1 = require("../../error");
const QueryFailedError_1 = require("../../error/QueryFailedError");
const QueryRunnerAlreadyReleasedError_1 = require("../../error/QueryRunnerAlreadyReleasedError");
const TransactionNotStartedError_1 = require("../../error/TransactionNotStartedError");
const BaseQueryRunner_1 = require("../../query-runner/BaseQueryRunner");
const QueryLock_1 = require("../../query-runner/QueryLock");
const QueryResult_1 = require("../../query-runner/QueryResult");
const Table_1 = require("../../schema-builder/table/Table");
const TableCheck_1 = require("../../schema-builder/table/TableCheck");
const TableColumn_1 = require("../../schema-builder/table/TableColumn");
const TableForeignKey_1 = require("../../schema-builder/table/TableForeignKey");
const TableIndex_1 = require("../../schema-builder/table/TableIndex");
const TableUnique_1 = require("../../schema-builder/table/TableUnique");
const View_1 = require("../../schema-builder/view/View");
const Broadcaster_1 = require("../../subscriber/Broadcaster");
const BroadcasterResult_1 = require("../../subscriber/BroadcasterResult");
const InstanceChecker_1 = require("../../util/InstanceChecker");
const OrmUtils_1 = require("../../util/OrmUtils");
const Query_1 = require("../Query");
const MetadataTableType_1 = require("../types/MetadataTableType");
/**
* Runs queries on a single SQL Server database connection.
*/
class SqlServerQueryRunner extends BaseQueryRunner_1.BaseQueryRunner {
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(driver, mode) {
super();
// -------------------------------------------------------------------------
// Private Properties
// -------------------------------------------------------------------------
this.lock = new QueryLock_1.QueryLock();
this.driver = driver;
this.connection = driver.connection;
this.broadcaster = new Broadcaster_1.Broadcaster(this);
this.mode = mode;
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Creates/uses database connection from the connection pool to perform further operations.
* Returns obtained database connection.
*/
connect() {
return Promise.resolve();
}
/**
* Releases used database connection.
* You cannot use query runner methods once its released.
*/
release() {
this.isReleased = true;
return Promise.resolve();
}
/**
* Starts transaction.
*/
async startTransaction(isolationLevel) {
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
this.isTransactionActive = true;
try {
await this.broadcaster.broadcast("BeforeTransactionStart");
}
catch (err) {
this.isTransactionActive = false;
throw err;
}
await new Promise(async (ok, fail) => {
const transactionCallback = (err) => {
if (err) {
this.isTransactionActive = false;
return fail(err);
}
ok();
};
if (this.transactionDepth === 0) {
const pool = await (this.mode === "slave"
? this.driver.obtainSlaveConnection()
: this.driver.obtainMasterConnection());
this.databaseConnection = pool.transaction();
this.connection.logger.logQuery("BEGIN TRANSACTION");
if (isolationLevel) {
this.databaseConnection.begin(this.convertIsolationLevel(isolationLevel), transactionCallback);
this.connection.logger.logQuery("SET TRANSACTION ISOLATION LEVEL " + isolationLevel);
}
else {
this.databaseConnection.begin(transactionCallback);
}
}
else {
await this.query(`SAVE TRANSACTION typeorm_${this.transactionDepth}`);
ok();
}
this.transactionDepth += 1;
});
await this.broadcaster.broadcast("AfterTransactionStart");
}
/**
* Commits transaction.
* Error will be thrown if transaction was not started.
*/
async commitTransaction() {
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
if (!this.isTransactionActive)
throw new TransactionNotStartedError_1.TransactionNotStartedError();
await this.broadcaster.broadcast("BeforeTransactionCommit");
if (this.transactionDepth === 1) {
return new Promise((ok, fail) => {
this.databaseConnection.commit(async (err) => {
if (err)
return fail(err);
this.isTransactionActive = false;
this.databaseConnection = null;
await this.broadcaster.broadcast("AfterTransactionCommit");
ok();
this.connection.logger.logQuery("COMMIT");
this.transactionDepth -= 1;
});
});
}
this.transactionDepth -= 1;
}
/**
* Rollbacks transaction.
* Error will be thrown if transaction was not started.
*/
async rollbackTransaction() {
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
if (!this.isTransactionActive)
throw new TransactionNotStartedError_1.TransactionNotStartedError();
await this.broadcaster.broadcast("BeforeTransactionRollback");
if (this.transactionDepth > 1) {
await this.query(`ROLLBACK TRANSACTION typeorm_${this.transactionDepth - 1}`);
this.transactionDepth -= 1;
}
else {
return new Promise((ok, fail) => {
this.databaseConnection.rollback(async (err) => {
if (err)
return fail(err);
this.isTransactionActive = false;
this.databaseConnection = null;
await this.broadcaster.broadcast("AfterTransactionRollback");
ok();
this.connection.logger.logQuery("ROLLBACK");
this.transactionDepth -= 1;
});
});
}
}
/**
* Executes a given SQL query.
*/
async query(query, parameters, useStructuredResult = false) {
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
const release = await this.lock.acquire();
this.driver.connection.logger.logQuery(query, parameters, this);
await this.broadcaster.broadcast("BeforeQuery", query, parameters);
const broadcasterResult = new BroadcasterResult_1.BroadcasterResult();
try {
const pool = await (this.mode === "slave"
? this.driver.obtainSlaveConnection()
: this.driver.obtainMasterConnection());
const request = new this.driver.mssql.Request(this.isTransactionActive ? this.databaseConnection : pool);
if (parameters && parameters.length) {
parameters.forEach((parameter, index) => {
const parameterName = index.toString();
if (InstanceChecker_1.InstanceChecker.isMssqlParameter(parameter)) {
const mssqlParameter = this.mssqlParameterToNativeParameter(parameter);
if (mssqlParameter) {
request.input(parameterName, mssqlParameter, parameter.value);
}
else {
request.input(parameterName, parameter.value);
}
}
else {
request.input(parameterName, parameter);
}
});
}
const queryStartTime = Date.now();
const raw = await new Promise((ok, fail) => {
request.query(query, (err, raw) => {
// log slow queries if maxQueryExecution time is set
const maxQueryExecutionTime = this.driver.options.maxQueryExecutionTime;
const queryEndTime = Date.now();
const queryExecutionTime = queryEndTime - queryStartTime;
this.broadcaster.broadcastAfterQueryEvent(broadcasterResult, query, parameters, true, queryExecutionTime, raw, undefined);
if (maxQueryExecutionTime &&
queryExecutionTime > maxQueryExecutionTime) {
this.driver.connection.logger.logQuerySlow(queryExecutionTime, query, parameters, this);
}
if (err) {
fail(new QueryFailedError_1.QueryFailedError(query, parameters, err));
}
ok(raw);
});
});
const result = new QueryResult_1.QueryResult();
if (raw?.hasOwnProperty("recordset")) {
result.records = raw.recordset;
}
if (raw?.hasOwnProperty("rowsAffected")) {
result.affected = raw.rowsAffected[0];
}
const queryType = query.slice(0, query.indexOf(" "));
switch (queryType) {
case "DELETE":
// for DELETE query additionally return number of affected rows
result.raw = [raw.recordset, raw.rowsAffected[0]];
break;
default:
result.raw = raw.recordset;
}
if (useStructuredResult) {
return result;
}
else {
return result.raw;
}
}
catch (err) {
this.driver.connection.logger.logQueryError(err, query, parameters, this);
this.broadcaster.broadcastAfterQueryEvent(broadcasterResult, query, parameters, false, undefined, undefined, err);
throw err;
}
finally {
await broadcasterResult.wait();
release();
}
}
/**
* Returns raw data stream.
*/
async stream(query, parameters, onEnd, onError) {
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
const release = await this.lock.acquire();
this.driver.connection.logger.logQuery(query, parameters, this);
const pool = await (this.mode === "slave"
? this.driver.obtainSlaveConnection()
: this.driver.obtainMasterConnection());
const request = new this.driver.mssql.Request(this.isTransactionActive ? this.databaseConnection : pool);
if (parameters && parameters.length) {
parameters.forEach((parameter, index) => {
const parameterName = index.toString();
if (InstanceChecker_1.InstanceChecker.isMssqlParameter(parameter)) {
request.input(parameterName, this.mssqlParameterToNativeParameter(parameter), parameter.value);
}
else {
request.input(parameterName, parameter);
}
});
}
request.query(query);
const streamRequest = request.toReadableStream();
streamRequest.on("error", (err) => {
release();
this.driver.connection.logger.logQueryError(err, query, parameters, this);
});
streamRequest.on("end", () => {
release();
});
if (onEnd) {
streamRequest.on("end", onEnd);
}
if (onError) {
streamRequest.on("error", onError);
}
return streamRequest;
}
/**
* Returns all available database names including system databases.
*/
async getDatabases() {
const results = await this.query(`EXEC sp_databases`);
return results.map((result) => result["DATABASE_NAME"]);
}
/**
* Returns all available schema names including system schemas.
* If database parameter specified, returns schemas of that database.
*/
async getSchemas(database) {
const query = database
? `SELECT * FROM "${database}"."sys"."schema"`
: `SELECT * FROM "sys"."schemas"`;
const results = await this.query(query);
return results.map((result) => result["name"]);
}
/**
* Checks if database with the given name exist.
*/
async hasDatabase(database) {
const result = await this.query(`SELECT DB_ID('${database}') as "db_id"`);
const dbId = result[0]["db_id"];
return !!dbId;
}
/**
* Loads currently using database
*/
async getCurrentDatabase() {
const currentDBQuery = await this.query(`SELECT DB_NAME() AS "db_name"`);
return currentDBQuery[0]["db_name"];
}
/**
* Checks if schema with the given name exist.
*/
async hasSchema(schema) {
const result = await this.query(`SELECT SCHEMA_ID('${schema}') as "schema_id"`);
const schemaId = result[0]["schema_id"];
return !!schemaId;
}
/**
* Loads currently using database schema
*/
async getCurrentSchema() {
const currentSchemaQuery = await this.query(`SELECT SCHEMA_NAME() AS "schema_name"`);
return currentSchemaQuery[0]["schema_name"];
}
/**
* Checks if table with the given name exist in the database.
*/
async hasTable(tableOrName) {
const parsedTableName = this.driver.parseTableName(tableOrName);
if (!parsedTableName.database) {
parsedTableName.database = await this.getCurrentDatabase();
}
if (!parsedTableName.schema) {
parsedTableName.schema = await this.getCurrentSchema();
}
const sql = `SELECT * FROM "${parsedTableName.database}"."INFORMATION_SCHEMA"."TABLES" WHERE "TABLE_NAME" = '${parsedTableName.tableName}' AND "TABLE_SCHEMA" = '${parsedTableName.schema}'`;
const result = await this.query(sql);
return result.length ? true : false;
}
/**
* Checks if column exist in the table.
*/
async hasColumn(tableOrName, columnName) {
const parsedTableName = this.driver.parseTableName(tableOrName);
if (!parsedTableName.database) {
parsedTableName.database = await this.getCurrentDatabase();
}
if (!parsedTableName.schema) {
parsedTableName.schema = await this.getCurrentSchema();
}
const sql = `SELECT * FROM "${parsedTableName.database}"."INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = '${parsedTableName.tableName}' AND "TABLE_SCHEMA" = '${parsedTableName.schema}' AND "COLUMN_NAME" = '${columnName}'`;
const result = await this.query(sql);
return result.length ? true : false;
}
/**
* Creates a new database.
*/
async createDatabase(database, ifNotExist) {
const up = ifNotExist
? `IF DB_ID('${database}') IS NULL CREATE DATABASE "${database}"`
: `CREATE DATABASE "${database}"`;
const down = `DROP DATABASE "${database}"`;
await this.executeQueries(new Query_1.Query(up), new Query_1.Query(down));
}
/**
* Drops database.
*/
async dropDatabase(database, ifExist) {
const up = ifExist
? `IF DB_ID('${database}') IS NOT NULL DROP DATABASE "${database}"`
: `DROP DATABASE "${database}"`;
const down = `CREATE DATABASE "${database}"`;
await this.executeQueries(new Query_1.Query(up), new Query_1.Query(down));
}
/**
* Creates table schema.
* If database name also specified (e.g. 'dbName.schemaName') schema will be created in specified database.
*/
async createSchema(schemaPath, ifNotExist) {
const upQueries = [];
const downQueries = [];
if (schemaPath.indexOf(".") === -1) {
const upQuery = ifNotExist
? `IF SCHEMA_ID('${schemaPath}') IS NULL BEGIN EXEC ('CREATE SCHEMA "${schemaPath}"') END`
: `CREATE SCHEMA "${schemaPath}"`;
upQueries.push(new Query_1.Query(upQuery));
downQueries.push(new Query_1.Query(`DROP SCHEMA "${schemaPath}"`));
}
else {
const dbName = schemaPath.split(".")[0];
const schema = schemaPath.split(".")[1];
const currentDB = await this.getCurrentDatabase();
upQueries.push(new Query_1.Query(`USE "${dbName}"`));
downQueries.push(new Query_1.Query(`USE "${currentDB}"`));
const upQuery = ifNotExist
? `IF SCHEMA_ID('${schema}') IS NULL BEGIN EXEC ('CREATE SCHEMA "${schema}"') END`
: `CREATE SCHEMA "${schema}"`;
upQueries.push(new Query_1.Query(upQuery));
downQueries.push(new Query_1.Query(`DROP SCHEMA "${schema}"`));
upQueries.push(new Query_1.Query(`USE "${currentDB}"`));
downQueries.push(new Query_1.Query(`USE "${dbName}"`));
}
await this.executeQueries(upQueries, downQueries);
}
/**
* Drops table schema.
* If database name also specified (e.g. 'dbName.schemaName') schema will be dropped in specified database.
*/
async dropSchema(schemaPath, ifExist) {
const upQueries = [];
const downQueries = [];
if (schemaPath.indexOf(".") === -1) {
const upQuery = ifExist
? `IF SCHEMA_ID('${schemaPath}') IS NULL BEGIN EXEC ('DROP SCHEMA "${schemaPath}"') END`
: `DROP SCHEMA "${schemaPath}"`;
upQueries.push(new Query_1.Query(upQuery));
downQueries.push(new Query_1.Query(`CREATE SCHEMA "${schemaPath}"`));
}
else {
const dbName = schemaPath.split(".")[0];
const schema = schemaPath.split(".")[1];
const currentDB = await this.getCurrentDatabase();
upQueries.push(new Query_1.Query(`USE "${dbName}"`));
downQueries.push(new Query_1.Query(`USE "${currentDB}"`));
const upQuery = ifExist
? `IF SCHEMA_ID('${schema}') IS NULL BEGIN EXEC ('DROP SCHEMA "${schema}"') END`
: `DROP SCHEMA "${schema}"`;
upQueries.push(new Query_1.Query(upQuery));
downQueries.push(new Query_1.Query(`CREATE SCHEMA "${schema}"`));
upQueries.push(new Query_1.Query(`USE "${currentDB}"`));
downQueries.push(new Query_1.Query(`USE "${dbName}"`));
}
await this.executeQueries(upQueries, downQueries);
}
/**
* Creates a new table.
*/
async createTable(table, ifNotExist = false, createForeignKeys = true, createIndices = true) {
if (ifNotExist) {
const isTableExist = await this.hasTable(table);
if (isTableExist)
return Promise.resolve();
}
const upQueries = [];
const downQueries = [];
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((foreignKey) => downQueries.push(this.dropForeignKeySql(table, foreignKey)));
if (createIndices) {
table.indices.forEach((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, index.columnNames, index.where);
upQueries.push(this.createIndexSql(table, index));
downQueries.push(this.dropIndexSql(table, index));
});
}
// if table have column with generated type, we must add the expression to the metadata table
const generatedColumns = table.columns.filter((column) => column.generatedType && column.asExpression);
for (const column of generatedColumns) {
const parsedTableName = this.driver.parseTableName(table);
if (!parsedTableName.schema) {
parsedTableName.schema = await this.getCurrentSchema();
}
const insertQuery = this.insertTypeormMetadataSql({
database: parsedTableName.database,
schema: parsedTableName.schema,
table: parsedTableName.tableName,
type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
name: column.name,
value: column.asExpression,
});
const deleteQuery = this.deleteTypeormMetadataSql({
database: parsedTableName.database,
schema: parsedTableName.schema,
table: parsedTableName.tableName,
type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
name: column.name,
});
upQueries.push(insertQuery);
downQueries.push(deleteQuery);
}
await this.executeQueries(upQueries, downQueries);
}
/**
* Drops the table.
*/
async dropTable(tableOrName, ifExist, dropForeignKeys = true, dropIndices = true) {
if (ifExist) {
const isTableExist = await this.hasTable(tableOrName);
if (!isTableExist)
return Promise.resolve();
}
// if dropTable called with dropForeignKeys = true, we must create foreign keys in down query.
const createForeignKeys = dropForeignKeys;
const table = InstanceChecker_1.InstanceChecker.isTable(tableOrName)
? tableOrName
: await this.getCachedTable(tableOrName);
const upQueries = [];
const downQueries = [];
// It needs because if table does not exist and dropForeignKeys or dropIndices is true, we don't need
// to perform drop queries for foreign keys and indices.
if (dropIndices) {
table.indices.forEach((index) => {
upQueries.push(this.dropIndexSql(table, index));
downQueries.push(this.createIndexSql(table, index));
});
}
// if dropForeignKeys is true, we just drop the table, otherwise we also drop table foreign keys.
// createTable does not need separate method to create foreign keys, because it create fk's in the same query with table creation.
if (dropForeignKeys)
table.foreignKeys.forEach((foreignKey) => upQueries.push(this.dropForeignKeySql(table, foreignKey)));
upQueries.push(this.dropTableSql(table));
downQueries.push(this.createTableSql(table, createForeignKeys));
// if table had columns with generated type, we must remove the expression from the metadata table
const generatedColumns = table.columns.filter((column) => column.generatedType && column.asExpression);
for (const column of generatedColumns) {
const parsedTableName = this.driver.parseTableName(table);
if (!parsedTableName.schema) {
parsedTableName.schema = await this.getCurrentSchema();
}
const deleteQuery = this.deleteTypeormMetadataSql({
database: parsedTableName.database,
schema: parsedTableName.schema,
table: parsedTableName.tableName,
type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
name: column.name,
});
const insertQuery = this.insertTypeormMetadataSql({
database: parsedTableName.database,
schema: parsedTableName.schema,
table: parsedTableName.tableName,
type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
name: column.name,
value: column.asExpression,
});
upQueries.push(deleteQuery);
downQueries.push(insertQuery);
}
await this.executeQueries(upQueries, downQueries);
}
/**
* Creates a new view.
*/
async createView(view, syncWithMetadata = false) {
const upQueries = [];
const downQueries = [];
upQueries.push(this.createViewSql(view));
if (syncWithMetadata)
upQueries.push(await this.insertViewDefinitionSql(view));
downQueries.push(this.dropViewSql(view));
if (syncWithMetadata)
downQueries.push(await this.deleteViewDefinitionSql(view));
await this.executeQueries(upQueries, downQueries);
}
/**
* Drops the view.
*/
async dropView(target) {
const viewName = InstanceChecker_1.InstanceChecker.isView(target) ? target.name : target;
const view = await this.getCachedView(viewName);
const upQueries = [];
const downQueries = [];
upQueries.push(await this.deleteViewDefinitionSql(view));
upQueries.push(this.dropViewSql(view));
downQueries.push(await this.insertViewDefinitionSql(view));
downQueries.push(this.createViewSql(view));
await this.executeQueries(upQueries, downQueries);
}
/**
* Renames a table.
*/
async renameTable(oldTableOrName, newTableName) {
const upQueries = [];
const downQueries = [];
const oldTable = InstanceChecker_1.InstanceChecker.isTable(oldTableOrName)
? oldTableOrName
: await this.getCachedTable(oldTableOrName);
const newTable = oldTable.clone();
// we need database name and schema name to rename FK constraints
let dbName = undefined;
let schemaName = undefined;
let oldTableName = oldTable.name;
const splittedName = oldTable.name.split(".");
if (splittedName.length === 3) {
dbName = splittedName[0];
oldTableName = splittedName[2];
if (splittedName[1] !== "")
schemaName = splittedName[1];
}
else if (splittedName.length === 2) {
schemaName = splittedName[0];
oldTableName = splittedName[1];
}
newTable.name = this.driver.buildTableName(newTableName, schemaName, dbName);
// if we have tables with database which differs from database specified in config, we must change currently used database.
// This need because we can not rename objects from another database.
const currentDB = await this.getCurrentDatabase();
if (dbName && dbName !== currentDB) {
upQueries.push(new Query_1.Query(`USE "${dbName}"`));
downQueries.push(new Query_1.Query(`USE "${currentDB}"`));
}
// rename table
upQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(oldTable)}", "${newTableName}"`));
downQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(newTable)}", "${oldTableName}"`));
// rename primary key constraint
if (newTable.primaryColumns.length > 0 &&
!newTable.primaryColumns[0].primaryKeyConstraintName) {
const columnNames = newTable.primaryColumns.map((column) => column.name);
const oldPkName = this.connection.namingStrategy.primaryKeyName(oldTable, columnNames);
const newPkName = this.connection.namingStrategy.primaryKeyName(newTable, columnNames);
// rename primary constraint
upQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(newTable)}.${oldPkName}", "${newPkName}"`));
downQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(newTable)}.${newPkName}", "${oldPkName}"`));
}
// rename unique constraints
newTable.uniques.forEach((unique) => {
const oldUniqueName = this.connection.namingStrategy.uniqueConstraintName(oldTable, unique.columnNames);
// Skip renaming if Unique has user defined constraint name
if (unique.name !== oldUniqueName)
return;
// build new constraint name
const newUniqueName = this.connection.namingStrategy.uniqueConstraintName(newTable, unique.columnNames);
// build queries
upQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(newTable)}.${unique.name}", "${newUniqueName}"`));
downQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(newTable)}.${newUniqueName}", "${unique.name}"`));
// replace constraint name
unique.name = newUniqueName;
});
// rename index constraints
newTable.indices.forEach((index) => {
const oldIndexName = this.connection.namingStrategy.indexName(oldTable, index.columnNames, index.where);
// Skip renaming if Index has user defined constraint name
if (index.name !== oldIndexName)
return;
// build new constraint name
const newIndexName = this.connection.namingStrategy.indexName(newTable, index.columnNames, index.where);
// build queries
upQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(newTable)}.${index.name}", "${newIndexName}", "INDEX"`));
downQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(newTable)}.${newIndexName}", "${index.name}", "INDEX"`));
// replace constraint name
index.name = newIndexName;
});
// rename foreign key constraints
newTable.foreignKeys.forEach((foreignKey) => {
const oldForeignKeyName = this.connection.namingStrategy.foreignKeyName(oldTable, foreignKey.columnNames, this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
// Skip renaming if foreign key has user defined constraint name
if (foreignKey.name !== oldForeignKeyName)
return;
// build new constraint name
const newForeignKeyName = this.connection.namingStrategy.foreignKeyName(newTable, foreignKey.columnNames, this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
// build queries
upQueries.push(new Query_1.Query(`EXEC sp_rename "${this.buildForeignKeyName(foreignKey.name, schemaName, dbName)}", "${newForeignKeyName}"`));
downQueries.push(new Query_1.Query(`EXEC sp_rename "${this.buildForeignKeyName(newForeignKeyName, schemaName, dbName)}", "${foreignKey.name}"`));
// replace constraint name
foreignKey.name = newForeignKeyName;
});
// change currently used database back to default db.
if (dbName && dbName !== currentDB) {
upQueries.push(new Query_1.Query(`USE "${currentDB}"`));
downQueries.push(new Query_1.Query(`USE "${dbName}"`));
}
await this.executeQueries(upQueries, downQueries);
// rename old table and replace it in cached tabled;
oldTable.name = newTable.name;
this.replaceCachedTable(oldTable, newTable);
}
/**
* Creates a new column from the column in the table.
*/
async addColumn(tableOrName, column) {
const table = InstanceChecker_1.InstanceChecker.isTable(tableOrName)
? tableOrName
: await this.getCachedTable(tableOrName);
const clonedTable = table.clone();
const upQueries = [];
const downQueries = [];
upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD ${this.buildCreateColumnSql(table, column, false, true)}`));
downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP COLUMN "${column.name}"`));
// create or update primary key constraint
if (column.isPrimary) {
const primaryColumns = clonedTable.primaryColumns;
// if table already have primary key, me must drop it and recreate again
if (primaryColumns.length > 0) {
const pkName = primaryColumns[0].primaryKeyConstraintName
? primaryColumns[0].primaryKeyConstraintName
: this.connection.namingStrategy.primaryKeyName(clonedTable, primaryColumns.map((column) => column.name));
const columnNames = primaryColumns
.map((column) => `"${column.name}"`)
.join(", ");
upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${pkName}"`));
downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`));
}
primaryColumns.push(column);
const pkName = primaryColumns[0].primaryKeyConstraintName
? primaryColumns[0].primaryKeyConstraintName
: this.connection.namingStrategy.primaryKeyName(clonedTable, primaryColumns.map((column) => column.name));
const columnNames = primaryColumns
.map((column) => `"${column.name}"`)
.join(", ");
upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${pkName}" PRIMARY KEY (${columnNames})`));
downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${pkName}"`));
}
// create column index
const columnIndex = clonedTable.indices.find((index) => 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) {
const uniqueConstraint = new TableUnique_1.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(table, [column.name]),
columnNames: [column.name],
});
clonedTable.uniques.push(uniqueConstraint);
upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${uniqueConstraint.name}" UNIQUE ("${column.name}")`));
downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${uniqueConstraint.name}"`));
}
// remove default constraint
if (column.default !== null && column.default !== undefined) {
const defaultName = this.connection.namingStrategy.defaultConstraintName(table, column.name);
downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${defaultName}"`));
}
if (column.generatedType && column.asExpression) {
const parsedTableName = this.driver.parseTableName(table);
if (!parsedTableName.schema) {
parsedTableName.schema = await this.getCurrentSchema();
}
const insertQuery = this.insertTypeormMetadataSql({
database: parsedTableName.database,
schema: parsedTableName.schema,
table: parsedTableName.tableName,
type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
name: column.name,
value: column.asExpression,
});
const deleteQuery = this.deleteTypeormMetadataSql({
database: parsedTableName.database,
schema: parsedTableName.schema,
table: parsedTableName.tableName,
type: MetadataTableType_1.MetadataTableType.GENERATED_COLUMN,
name: column.name,
});
upQueries.push(insertQuery);
downQueries.push(deleteQuery);
}
await this.executeQueries(upQueries, downQueries);
clonedTable.addColumn(column);
this.replaceCachedTable(table, clonedTable);
}
/**
* Creates a new columns from the column in the table.
*/
async addColumns(tableOrName, columns) {
for (const column of columns) {
await this.addColumn(tableOrName, column);
}
}
/**
* Renames column in the given table.
*/
async renameColumn(tableOrName, oldTableColumnOrName, newTableColumnOrName) {
const table = InstanceChecker_1.InstanceChecker.isTable(tableOrName)
? tableOrName
: await this.getCachedTable(tableOrName);
const oldColumn = InstanceChecker_1.InstanceChecker.isTableColumn(oldTableColumnOrName)
? oldTableColumnOrName
: table.columns.find((c) => c.name === oldTableColumnOrName);
if (!oldColumn)
throw new error_1.TypeORMError(`Column "${oldTableColumnOrName}" was not found in the "${table.name}" table.`);
let newColumn = undefined;
if (InstanceChecker_1.InstanceChecker.isTableColumn(newTableColumnOrName)) {
newColumn = newTableColumnOrName;
}
else {
newColumn = oldColumn.clone();
newColumn.name = newTableColumnOrName;
}
await this.changeColumn(table, oldColumn, newColumn);
}
/**
* Changes a column in the table.
*/
async changeColumn(tableOrName, oldTableColumnOrName, newColumn) {
const table = InstanceChecker_1.InstanceChecker.isTable(tableOrName)
? tableOrName
: await this.getCachedTable(tableOrName);
let clonedTable = table.clone();
const upQueries = [];
const downQueries = [];
const oldColumn = InstanceChecker_1.InstanceChecker.isTableColumn(oldTableColumnOrName)
? oldTableColumnOrName
: table.columns.find((column) => column.name === oldTableColumnOrName);
if (!oldColumn)
throw new error_1.TypeORMError(`Column "${oldTableColumnOrName}" was not found in the "${table.name}" table.`);
if ((newColumn.isGenerated !== oldColumn.isGenerated &&
newColumn.generationStrategy !== "uuid") ||
newColumn.type !== oldColumn.type ||
newColumn.length !== oldColumn.length ||
newColumn.asExpression !== oldColumn.asExpression ||
newColumn.generatedType !== oldColumn.generatedType) {
// SQL Server does not support changing of IDENTITY column, so we must drop column and recreate it again.
// Also, we recreate column if column type changed
await this.dropColumn(table, oldColumn);
await this.addColumn(table, newColumn);
// update cloned table
clonedTable = table.clone();
}
else {
if (newColumn.name !== oldColumn.name) {
// we need database name and schema name to rename FK constraints
let dbName = undefined;
let schemaName = undefined;
const splittedName = table.name.split(".");
if (splittedName.length === 3) {
dbName = splittedName[0];
if (splittedName[1] !== "")
schemaName = splittedName[1];
}
else if (splittedName.length === 2) {
schemaName = splittedName[0];
}
// if we have tables with database which differs from database specified in config, we must change currently used database.
// This need because we can not rename objects from another database.
const currentDB = await this.getCurrentDatabase();
if (dbName && dbName !== currentDB) {
upQueries.push(new Query_1.Query(`USE "${dbName}"`));
downQueries.push(new Query_1.Query(`USE "${currentDB}"`));
}
// rename the column
upQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(table)}.${oldColumn.name}", "${newColumn.name}"`));
downQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(table)}.${newColumn.name}", "${oldColumn.name}"`));
// rename column primary key constraint
if (oldColumn.isPrimary === true &&
!oldColumn.primaryKeyConstraintName) {
const primaryColumns = clonedTable.primaryColumns;
// build old primary constraint name
const columnNames = primaryColumns.map((column) => column.name);
const 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);
// build new primary constraint name
const newPkName = this.connection.namingStrategy.primaryKeyName(clonedTable, columnNames);
// rename primary constraint
upQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(clonedTable)}.${oldPkName}", "${newPkName}"`));
downQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(clonedTable)}.${newPkName}", "${oldPkName}"`));
}
// rename index constraints
clonedTable.findColumnIndices(oldColumn).forEach((index) => {
const oldIndexName = this.connection.namingStrategy.indexName(clonedTable, index.columnNames, index.where);
// Skip renaming if Index has user defined constraint name
if (index.name !== oldIndexName)
return;
// build new constraint name
index.columnNames.splice(index.columnNames.indexOf(oldColumn.name), 1);
index.columnNames.push(newColumn.name);
const newIndexName = this.connection.namingStrategy.indexName(clonedTable, index.columnNames, index.where);
// build queries
upQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(clonedTable)}.${index.name}", "${newIndexName}", "INDEX"`));
downQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(clonedTable)}.${newIndexName}", "${index.name}", "INDEX"`));
// replace constraint name
index.name = newIndexName;
});
// rename foreign key constraints
clonedTable
.findColumnForeignKeys(oldColumn)
.forEach((foreignKey) => {
const foreignKeyName = this.connection.namingStrategy.foreignKeyName(clonedTable, foreignKey.columnNames, this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
// Skip renaming if foreign key has user defined constraint name
if (foreignKey.name !== foreignKeyName)
return;
// build new constraint name
foreignKey.columnNames.splice(foreignKey.columnNames.indexOf(oldColumn.name), 1);
foreignKey.columnNames.push(newColumn.name);
const newForeignKeyName = this.connection.namingStrategy.foreignKeyName(clonedTable, foreignKey.columnNames, this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
// build queries
upQueries.push(new Query_1.Query(`EXEC sp_rename "${this.buildForeignKeyName(foreignKey.name, schemaName, dbName)}", "${newForeignKeyName}"`));
downQueries.push(new Query_1.Query(`EXEC sp_rename "${this.buildForeignKeyName(newForeignKeyName, schemaName, dbName)}", "${foreignKey.name}"`));
// replace constraint name
foreignKey.name = newForeignKeyName;
});
// rename check constraints
clonedTable.findColumnChecks(oldColumn).forEach((check) => {
// build new constraint name
check.columnNames.splice(check.columnNames.indexOf(oldColumn.name), 1);
check.columnNames.push(newColumn.name);
const newCheckName = this.connection.namingStrategy.checkConstraintName(clonedTable, check.expression);
// build queries
upQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(clonedTable)}.${check.name}", "${newCheckName}"`));
downQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(clonedTable)}.${newCheckName}", "${check.name}"`));
// replace constraint name
check.name = newCheckName;
});
// rename unique constraints
clonedTable.findColumnUniques(oldColumn).forEach((unique) => {
const oldUniqueName = this.connection.namingStrategy.uniqueConstraintName(clonedTable, unique.columnNames);
// Skip renaming if Unique has user defined constraint name
if (unique.name !== oldUniqueName)
return;
// build new constraint name
unique.columnNames.splice(unique.columnNames.indexOf(oldColumn.name), 1);
unique.columnNames.push(newColumn.name);
const newUniqueName = this.connection.namingStrategy.uniqueConstraintName(clonedTable, unique.columnNames);
// build queries
upQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(clonedTable)}.${unique.name}", "${newUniqueName}"`));
downQueries.push(new Query_1.Query(`EXEC sp_rename "${this.getTablePath(clonedTable)}.${newUniqueName}", "${unique.name}"`));
// replace constraint name
unique.name = newUniqueName;
});
// rename default constraints
if (oldColumn.default !== null &&
oldColumn.default !== undefined) {
const oldDefaultName = this.connection.namingStrategy.defaultConstraintName(table, oldColumn.name);
const newDefaultName = this.connection.namingStrategy.defaultConstraintName(table, newColumn.name);
upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${oldDefaultName}"`));
downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${oldDefaultName}" DEFAULT ${oldColumn.default} FOR "${newColumn.name}"`));
upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ADD CONSTRAINT "${newDefaultName}" DEFAULT ${oldColumn.default} FOR "${newColumn.name}"`));
downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} DROP CONSTRAINT "${newDefaultName}"`));
}
// change currently used database back to default db.
if (dbName && dbName !== currentDB) {
upQueries.push(new Query_1.Query(`USE "${currentDB}"`));
downQueries.push(new Query_1.Query(`USE "${dbName}"`));
}
// rename old column in the Table object
const oldTableColumn = clonedTable.columns.find((column) => column.name === oldColumn.name);
clonedTable.columns[clonedTable.columns.indexOf(oldTableColumn)].name = newColumn.name;
oldColumn.name = newColumn.name;
}
if (this.isColumnChanged(oldColumn, newColumn, false, false, false)) {
upQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN ${this.buildCreateColumnSql(table, newColumn, true, false, true)}`));
downQueries.push(new Query_1.Query(`ALTER TABLE ${this.escapePath(table)} ALTER COLUMN ${this.buildCreateColumnSql(table, oldColumn, true, false, true)}`));
}
if (this.isEnumChanged(oldColumn, newColumn)) {
const oldExpression = this.getEnumExpression(oldColumn);
const oldCheck = new TableCheck_1.TableCheck({
name: this.connection.namingStrategy.checkConstraintName(table, oldExpression, true),
expression: oldExpression,
});
const newExpression = this.getEnumExpression(newColumn);
const newCheck = new TableCheck_1.TableCheck({
name: this.connection.namingStrategy.checkConstraintName(table, newExpression, true),
expression: newExpression,
});
upQueries.push(this.dropCheckConstraintSql(table, oldCheck));
upQueries.push(this.createCheckConstraintSql(table, newCheck));