typeorm
Version:
Data-Mapper ORM for TypeScript, ES7, ES6, ES5. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, MongoDB databases.
861 lines • 149 kB
JavaScript
"use strict";
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 };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var TransactionAlreadyStartedError_1 = require("../../error/TransactionAlreadyStartedError");
var TransactionNotStartedError_1 = require("../../error/TransactionNotStartedError");
var TableColumn_1 = require("../../schema-builder/table/TableColumn");
var Table_1 = require("../../schema-builder/table/Table");
var TableForeignKey_1 = require("../../schema-builder/table/TableForeignKey");
var TableIndex_1 = require("../../schema-builder/table/TableIndex");
var QueryRunnerAlreadyReleasedError_1 = require("../../error/QueryRunnerAlreadyReleasedError");
var MssqlParameter_1 = require("./MssqlParameter");
var OrmUtils_1 = require("../../util/OrmUtils");
var QueryFailedError_1 = require("../../error/QueryFailedError");
var TableUnique_1 = require("../../schema-builder/table/TableUnique");
var TableCheck_1 = require("../../schema-builder/table/TableCheck");
var BaseQueryRunner_1 = require("../../query-runner/BaseQueryRunner");
var Broadcaster_1 = require("../../subscriber/Broadcaster");
var index_1 = require("../../index");
/**
* Runs queries on a single SQL Server database connection.
*/
var SqlServerQueryRunner = /** @class */ (function (_super) {
__extends(SqlServerQueryRunner, _super);
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
function SqlServerQueryRunner(driver, mode) {
if (mode === void 0) { mode = "master"; }
var _this = _super.call(this) || this;
// -------------------------------------------------------------------------
// Protected Properties
// -------------------------------------------------------------------------
/**
* Last executed query in a transaction.
* This is needed because in transaction mode mssql cannot execute parallel queries,
* that's why we store last executed query promise to wait it when we execute next query.
*
* @see https://github.com/patriksimek/node-mssql/issues/491
*/
_this.queryResponsibilityChain = [];
_this.driver = driver;
_this.connection = driver.connection;
_this.broadcaster = new Broadcaster_1.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.
*/
SqlServerQueryRunner.prototype.connect = function () {
return Promise.resolve();
};
/**
* Releases used database connection.
* You cannot use query runner methods once its released.
*/
SqlServerQueryRunner.prototype.release = function () {
this.isReleased = true;
return Promise.resolve();
};
/**
* Starts transaction.
*/
SqlServerQueryRunner.prototype.startTransaction = function () {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
if (this.isTransactionActive)
throw new TransactionAlreadyStartedError_1.TransactionAlreadyStartedError();
return [2 /*return*/, new Promise(function (ok, fail) { return __awaiter(_this, void 0, void 0, function () {
var _this = this;
var pool;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.isTransactionActive = true;
return [4 /*yield*/, (this.mode === "slave" ? this.driver.obtainSlaveConnection() : this.driver.obtainMasterConnection())];
case 1:
pool = _a.sent();
this.databaseConnection = pool.transaction();
this.databaseConnection.begin(function (err) {
if (err) {
_this.isTransactionActive = false;
return fail(err);
}
ok();
_this.connection.logger.logQuery("BEGIN TRANSACTION");
});
return [2 /*return*/];
}
});
}); })];
});
});
};
/**
* Commits transaction.
* Error will be thrown if transaction was not started.
*/
SqlServerQueryRunner.prototype.commitTransaction = function () {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
if (!this.isTransactionActive)
throw new TransactionNotStartedError_1.TransactionNotStartedError();
return [2 /*return*/, new Promise(function (ok, fail) {
_this.databaseConnection.commit(function (err) {
if (err)
return fail(err);
_this.isTransactionActive = false;
_this.databaseConnection = null;
ok();
_this.connection.logger.logQuery("COMMIT");
});
})];
});
});
};
/**
* Rollbacks transaction.
* Error will be thrown if transaction was not started.
*/
SqlServerQueryRunner.prototype.rollbackTransaction = function () {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
if (!this.isTransactionActive)
throw new TransactionNotStartedError_1.TransactionNotStartedError();
return [2 /*return*/, new Promise(function (ok, fail) {
_this.databaseConnection.rollback(function (err) {
if (err)
return fail(err);
_this.isTransactionActive = false;
_this.databaseConnection = null;
ok();
_this.connection.logger.logQuery("ROLLBACK");
});
})];
});
});
};
/**
* Executes a given SQL query.
*/
SqlServerQueryRunner.prototype.query = function (query, parameters) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
var waitingOkay, waitingPromise, otherWaitingPromises, promise;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
waitingPromise = new Promise(function (ok) { return waitingOkay = ok; });
if (!this.queryResponsibilityChain.length) return [3 /*break*/, 2];
otherWaitingPromises = this.queryResponsibilityChain.slice();
this.queryResponsibilityChain.push(waitingPromise);
return [4 /*yield*/, Promise.all(otherWaitingPromises)];
case 1:
_a.sent();
_a.label = 2;
case 2:
promise = new Promise(function (ok, fail) { return __awaiter(_this, void 0, void 0, function () {
var _this = this;
var pool, request_1, queryStartTime_1, err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
this.driver.connection.logger.logQuery(query, parameters, this);
return [4 /*yield*/, (this.mode === "slave" ? this.driver.obtainSlaveConnection() : this.driver.obtainMasterConnection())];
case 1:
pool = _a.sent();
request_1 = new this.driver.mssql.Request(this.isTransactionActive ? this.databaseConnection : pool);
if (parameters && parameters.length) {
parameters.forEach(function (parameter, index) {
if (parameter instanceof MssqlParameter_1.MssqlParameter) {
var mssqlParameter = _this.mssqlParameterToNativeParameter(parameter);
if (mssqlParameter) {
request_1.input(index, mssqlParameter, parameter.value);
}
else {
request_1.input(index, parameter.value);
}
}
else {
request_1.input(index, parameter);
}
});
}
queryStartTime_1 = +new Date();
request_1.query(query, 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);
var resolveChain = function () {
if (promiseIndex !== -1)
_this.queryResponsibilityChain.splice(promiseIndex, 1);
if (waitingPromiseIndex !== -1)
_this.queryResponsibilityChain.splice(waitingPromiseIndex, 1);
waitingOkay();
};
var promiseIndex = _this.queryResponsibilityChain.indexOf(promise);
var waitingPromiseIndex = _this.queryResponsibilityChain.indexOf(waitingPromise);
if (err) {
_this.driver.connection.logger.logQueryError(err, query, parameters, _this);
resolveChain();
return fail(new QueryFailedError_1.QueryFailedError(query, parameters, err));
}
ok(result.recordset);
resolveChain();
});
return [3 /*break*/, 3];
case 2:
err_1 = _a.sent();
fail(err_1);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); });
// with this condition, Promise.all causes unexpected behavior.
// if (this.isTransactionActive)
this.queryResponsibilityChain.push(promise);
return [2 /*return*/, promise];
}
});
});
};
/**
* Returns raw data stream.
*/
SqlServerQueryRunner.prototype.stream = function (query, parameters, onEnd, onError) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
var waitingOkay, waitingPromise, otherWaitingPromises, promise;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
waitingPromise = new Promise(function (ok) { return waitingOkay = ok; });
if (!this.queryResponsibilityChain.length) return [3 /*break*/, 2];
otherWaitingPromises = this.queryResponsibilityChain.slice();
this.queryResponsibilityChain.push(waitingPromise);
return [4 /*yield*/, Promise.all(otherWaitingPromises)];
case 1:
_a.sent();
_a.label = 2;
case 2:
promise = new Promise(function (ok, fail) { return __awaiter(_this, void 0, void 0, function () {
var _this = this;
var pool, request;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.driver.connection.logger.logQuery(query, parameters, this);
return [4 /*yield*/, (this.mode === "slave" ? this.driver.obtainSlaveConnection() : this.driver.obtainMasterConnection())];
case 1:
pool = _a.sent();
request = new this.driver.mssql.Request(this.isTransactionActive ? this.databaseConnection : pool);
request.stream = true;
if (parameters && parameters.length) {
parameters.forEach(function (parameter, index) {
if (parameter instanceof MssqlParameter_1.MssqlParameter) {
request.input(index, _this.mssqlParameterToNativeParameter(parameter), parameter.value);
}
else {
request.input(index, parameter);
}
});
}
request.query(query, function (err, result) {
var resolveChain = function () {
if (promiseIndex !== -1)
_this.queryResponsibilityChain.splice(promiseIndex, 1);
if (waitingPromiseIndex !== -1)
_this.queryResponsibilityChain.splice(waitingPromiseIndex, 1);
waitingOkay();
};
var promiseIndex = _this.queryResponsibilityChain.indexOf(promise);
var waitingPromiseIndex = _this.queryResponsibilityChain.indexOf(waitingPromise);
if (err) {
_this.driver.connection.logger.logQueryError(err, query, parameters, _this);
resolveChain();
return fail(err);
}
ok(result.recordset);
resolveChain();
});
if (onEnd)
request.on("done", onEnd);
if (onError)
request.on("error", onError);
ok(request);
return [2 /*return*/];
}
});
}); });
if (this.isTransactionActive)
this.queryResponsibilityChain.push(promise);
return [2 /*return*/, promise];
}
});
});
};
/**
* Returns all available database names including system databases.
*/
SqlServerQueryRunner.prototype.getDatabases = function () {
return __awaiter(this, void 0, void 0, function () {
var results;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.query("EXEC sp_databases")];
case 1:
results = _a.sent();
return [2 /*return*/, results.map(function (result) { return result["DATABASE_NAME"]; })];
}
});
});
};
/**
* Returns all available schema names including system schemas.
* If database parameter specified, returns schemas of that database.
*/
SqlServerQueryRunner.prototype.getSchemas = function (database) {
return __awaiter(this, void 0, void 0, function () {
var query, results;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
query = database ? "SELECT * FROM \"" + database + "\".\"sys\".\"schema\"" : "SELECT * FROM \"sys\".\"schemas\"";
return [4 /*yield*/, this.query(query)];
case 1:
results = _a.sent();
return [2 /*return*/, results.map(function (result) { return result["name"]; })];
}
});
});
};
/**
* Checks if database with the given name exist.
*/
SqlServerQueryRunner.prototype.hasDatabase = function (database) {
return __awaiter(this, void 0, void 0, function () {
var result, dbId;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.query("SELECT DB_ID('" + database + "') as \"db_id\"")];
case 1:
result = _a.sent();
dbId = result[0]["db_id"];
return [2 /*return*/, !!dbId];
}
});
});
};
/**
* Checks if schema with the given name exist.
*/
SqlServerQueryRunner.prototype.hasSchema = function (schema) {
return __awaiter(this, void 0, void 0, function () {
var result, schemaId;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.query("SELECT SCHEMA_ID('" + schema + "') as \"schema_id\"")];
case 1:
result = _a.sent();
schemaId = result[0]["schema_id"];
return [2 /*return*/, !!schemaId];
}
});
});
};
/**
* Checks if table with the given name exist in the database.
*/
SqlServerQueryRunner.prototype.hasTable = function (tableOrName) {
return __awaiter(this, void 0, void 0, function () {
var parsedTableName, schema, sql, result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
parsedTableName = this.parseTableName(tableOrName);
schema = parsedTableName.schema === "SCHEMA_NAME()" ? parsedTableName.schema : "'" + parsedTableName.schema + "'";
sql = "SELECT * FROM \"" + parsedTableName.database + "\".\"INFORMATION_SCHEMA\".\"TABLES\" WHERE \"TABLE_NAME\" = '" + parsedTableName.tableName + "' AND \"TABLE_SCHEMA\" = " + schema;
return [4 /*yield*/, this.query(sql)];
case 1:
result = _a.sent();
return [2 /*return*/, result.length ? true : false];
}
});
});
};
/**
* Checks if column exist in the table.
*/
SqlServerQueryRunner.prototype.hasColumn = function (tableOrName, columnName) {
return __awaiter(this, void 0, void 0, function () {
var parsedTableName, schema, sql, result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
parsedTableName = this.parseTableName(tableOrName);
schema = parsedTableName.schema === "SCHEMA_NAME()" ? parsedTableName.schema : "'" + parsedTableName.schema + "'";
sql = "SELECT * FROM \"" + parsedTableName.database + "\".\"INFORMATION_SCHEMA\".\"TABLES\" WHERE \"TABLE_NAME\" = '" + parsedTableName.tableName + "' AND \"COLUMN_NAME\" = '" + columnName + "' AND \"TABLE_SCHEMA\" = " + schema;
return [4 /*yield*/, this.query(sql)];
case 1:
result = _a.sent();
return [2 /*return*/, result.length ? true : false];
}
});
});
};
/**
* Creates a new database.
*/
SqlServerQueryRunner.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 ? "IF DB_ID('" + database + "') IS NULL CREATE DATABASE \"" + database + "\"" : "CREATE DATABASE \"" + database + "\"";
down = "DROP DATABASE \"" + database + "\"";
return [4 /*yield*/, this.executeQueries(up, down)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* Drops database.
*/
SqlServerQueryRunner.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 ? "IF DB_ID('" + database + "') IS NOT NULL DROP DATABASE \"" + database + "\"" : "DROP DATABASE \"" + database + "\"";
down = "CREATE DATABASE \"" + database + "\"";
return [4 /*yield*/, this.executeQueries(up, down)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* Creates table schema.
* If database name also specified (e.g. 'dbName.schemaName') schema will be created in specified database.
*/
SqlServerQueryRunner.prototype.createSchema = function (schemaPath, ifNotExist) {
return __awaiter(this, void 0, void 0, function () {
var upQueries, downQueries, upQuery, dbName, schema, currentDB, upQuery;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
upQueries = [];
downQueries = [];
if (!(schemaPath.indexOf(".") === -1)) return [3 /*break*/, 1];
upQuery = ifNotExist ? "IF SCHEMA_ID('" + schemaPath + "') IS NULL BEGIN EXEC ('CREATE SCHEMA \"" + schemaPath + "\"') END" : "CREATE SCHEMA \"" + schemaPath + "\"";
upQueries.push(upQuery);
downQueries.push("DROP SCHEMA \"" + schemaPath + "\"");
return [3 /*break*/, 3];
case 1:
dbName = schemaPath.split(".")[0];
schema = schemaPath.split(".")[1];
return [4 /*yield*/, this.getCurrentDatabase()];
case 2:
currentDB = _a.sent();
upQueries.push("USE \"" + dbName + "\"");
downQueries.push("USE \"" + currentDB + "\"");
upQuery = ifNotExist ? "IF SCHEMA_ID('" + schema + "') IS NULL BEGIN EXEC ('CREATE SCHEMA \"" + schema + "\"') END" : "CREATE SCHEMA \"" + schema + "\"";
upQueries.push(upQuery);
downQueries.push("DROP SCHEMA \"" + schema + "\"");
upQueries.push("USE \"" + currentDB + "\"");
downQueries.push("USE \"" + dbName + "\"");
_a.label = 3;
case 3: return [4 /*yield*/, this.executeQueries(upQueries, downQueries)];
case 4:
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* Drops table schema.
* If database name also specified (e.g. 'dbName.schemaName') schema will be dropped in specified database.
*/
SqlServerQueryRunner.prototype.dropSchema = function (schemaPath, ifExist) {
return __awaiter(this, void 0, void 0, function () {
var upQueries, downQueries, upQuery, dbName, schema, currentDB, upQuery;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
upQueries = [];
downQueries = [];
if (!(schemaPath.indexOf(".") === -1)) return [3 /*break*/, 1];
upQuery = ifExist ? "IF SCHEMA_ID('" + schemaPath + "') IS NULL BEGIN EXEC ('DROP SCHEMA \"" + schemaPath + "\"') END" : "DROP SCHEMA \"" + schemaPath + "\"";
upQueries.push(upQuery);
downQueries.push("CREATE SCHEMA \"" + schemaPath + "\"");
return [3 /*break*/, 3];
case 1:
dbName = schemaPath.split(".")[0];
schema = schemaPath.split(".")[1];
return [4 /*yield*/, this.getCurrentDatabase()];
case 2:
currentDB = _a.sent();
upQueries.push("USE \"" + dbName + "\"");
downQueries.push("USE \"" + currentDB + "\"");
upQuery = ifExist ? "IF SCHEMA_ID('" + schema + "') IS NULL BEGIN EXEC ('DROP SCHEMA \"" + schema + "\"') END" : "DROP SCHEMA \"" + schema + "\"";
upQueries.push(upQuery);
downQueries.push("CREATE SCHEMA \"" + schema + "\"");
upQueries.push("USE \"" + currentDB + "\"");
downQueries.push("USE \"" + dbName + "\"");
_a.label = 3;
case 3: return [4 /*yield*/, this.executeQueries(upQueries, downQueries)];
case 4:
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* Creates a new table.
*/
SqlServerQueryRunner.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 = [];
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 3:
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* Drops the table.
*/
SqlServerQueryRunner.prototype.dropTable = function (tableOrName, 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, table, _a, upQueries, downQueries;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!ifExist) return [3 /*break*/, 2];
return [4 /*yield*/, this.hasTable(tableOrName)];
case 1:
isTableExist = _b.sent();
if (!isTableExist)
return [2 /*return*/, Promise.resolve()];
_b.label = 2;
case 2:
createForeignKeys = dropForeignKeys;
if (!(tableOrName instanceof Table_1.Table)) return [3 /*break*/, 3];
_a = tableOrName;
return [3 /*break*/, 5];
case 3: return [4 /*yield*/, this.getCachedTable(tableOrName)];
case 4:
_a = _b.sent();
_b.label = 5;
case 5:
table = _a;
upQueries = [];
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(function (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(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 6:
_b.sent();
return [2 /*return*/];
}
});
});
};
/**
* Renames a table.
*/
SqlServerQueryRunner.prototype.renameTable = function (oldTableOrName, newTableName) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
var upQueries, downQueries, oldTable, _a, newTable, dbName, schemaName, oldTableName, splittedName, currentDB, columnNames, oldPkName, newPkName;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
upQueries = [];
downQueries = [];
if (!(oldTableOrName instanceof Table_1.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();
dbName = undefined;
schemaName = undefined;
oldTableName = oldTable.name;
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);
return [4 /*yield*/, this.getCurrentDatabase()];
case 4:
currentDB = _b.sent();
if (dbName && dbName !== currentDB) {
upQueries.push("USE \"" + dbName + "\"");
downQueries.push("USE \"" + currentDB + "\"");
}
// rename table
upQueries.push("EXEC sp_rename \"" + this.escapeTableName(oldTable, true) + "\", \"" + newTableName + "\"");
downQueries.push("EXEC sp_rename \"" + this.escapeTableName(newTable, true) + "\", \"" + oldTableName + "\"");
// rename 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);
// rename primary constraint
upQueries.push("EXEC sp_rename \"" + this.escapeTableName(newTable, true) + "." + oldPkName + "\", \"" + newPkName + "\"");
downQueries.push("EXEC sp_rename \"" + this.escapeTableName(newTable, true) + "." + newPkName + "\", \"" + 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("EXEC sp_rename \"" + _this.escapeTableName(newTable, true) + "." + unique.name + "\", \"" + newUniqueName + "\"");
downQueries.push("EXEC sp_rename \"" + _this.escapeTableName(newTable, true) + "." + newUniqueName + "\", \"" + unique.name + "\"");
// replace constraint name
unique.name = newUniqueName;
});
// rename index constraints
newTable.indices.forEach(function (index) {
// build new constraint name
var newIndexName = _this.connection.namingStrategy.indexName(newTable, index.columnNames, index.where);
// build queries
upQueries.push("EXEC sp_rename \"" + _this.escapeTableName(newTable, true) + "." + index.name + "\", \"" + newIndexName + "\", \"INDEX\"");
downQueries.push("EXEC sp_rename \"" + _this.escapeTableName(newTable, true) + "." + newIndexName + "\", \"" + index.name + "\", \"INDEX\"");
// 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("EXEC sp_rename \"" + _this.buildForeignKeyName(foreignKey.name, schemaName, dbName) + "\", \"" + newForeignKeyName + "\"");
downQueries.push("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("USE \"" + currentDB + "\"");
downQueries.push("USE \"" + dbName + "\"");
}
return [4 /*yield*/, this.executeQueries(upQueries, downQueries)];
case 5:
_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.
*/
SqlServerQueryRunner.prototype.addColumn = function (tableOrName, column) {
return __awaiter(this, void 0, void 0, function () {
var table, _a, clonedTable, upQueries, downQueries, primaryColumns, pkName_1, columnNames_1, pkName, columnNames, columnIndex, uniqueConstraint, defaultName;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!(tableOrName instanceof Table_1.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 = [];
upQueries.push("ALTER TABLE " + this.escapeTableName(table) + " ADD " + this.buildCreateColumnSql(table, column, false, false));
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_1.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 + "\"");
}
// create default constraint
if (column.default !== null && column.default !== undefined) {
defaultName = this.connection.namingStrategy.defaultConstraintName(table.name, column.name);
upQueries.push("ALTER TABLE " + this.escapeTableName(table) + " ADD CONSTRAINT \"" + defaultName + "\" DEFAULT " + column.default + " FOR \"" + column.name + "\"");
downQueries.push("ALTER TABLE " + this.escapeTableName(table) + " DROP CONSTRAINT \"" + defaultName + "\"");
}
return [4 /*yield*/, this.executeQueries(upQueries, downQueries)];
case 4:
_b.sent();
clonedTable.addColumn(column);
this.replaceCachedTable(table, clonedTable);
return [2 /*return*/];
}
});
});
};
/*