typeorm
Version:
Data-Mapper ORM for TypeScript, ES7, ES6, ES5. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, MongoDB databases.
869 lines (868 loc) • 158 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SapQueryRunner = void 0;
var tslib_1 = require("tslib");
var QueryRunnerAlreadyReleasedError_1 = require("../../error/QueryRunnerAlreadyReleasedError");
var TransactionAlreadyStartedError_1 = require("../../error/TransactionAlreadyStartedError");
var TransactionNotStartedError_1 = require("../../error/TransactionNotStartedError");
var index_1 = require("../../index");
var BaseQueryRunner_1 = require("../../query-runner/BaseQueryRunner");
var Table_1 = require("../../schema-builder/table/Table");
var TableCheck_1 = require("../../schema-builder/table/TableCheck");
var TableColumn_1 = require("../../schema-builder/table/TableColumn");
var TableForeignKey_1 = require("../../schema-builder/table/TableForeignKey");
var TableIndex_1 = require("../../schema-builder/table/TableIndex");
var TableUnique_1 = require("../../schema-builder/table/TableUnique");
var View_1 = require("../../schema-builder/view/View");
var Broadcaster_1 = require("../../subscriber/Broadcaster");
var OrmUtils_1 = require("../../util/OrmUtils");
var Query_1 = require("../Query");
var BroadcasterResult_1 = require("../../subscriber/BroadcasterResult");
/**
* Runs queries on a single SQL Server database connection.
*/
var SapQueryRunner = /** @class */ (function (_super) {
tslib_1.__extends(SapQueryRunner, _super);
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
function SapQueryRunner(driver, mode) {
var _this = _super.call(this) || this;
// -------------------------------------------------------------------------
// Protected Properties
// -------------------------------------------------------------------------
/**
* Last executed query in a transaction.
* This is needed because we cannot rely on parallel queries because we use second query
* to select CURRENT_IDENTITY_VALUE()
*/
_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.
*/
SapQueryRunner.prototype.connect = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var _a;
return tslib_1.__generator(this, function (_b) {
switch (_b.label) {
case 0:
if (this.databaseConnection)
return [2 /*return*/, this.databaseConnection];
_a = this;
return [4 /*yield*/, this.driver.obtainMasterConnection()];
case 1:
_a.databaseConnection = _b.sent();
return [2 /*return*/, this.databaseConnection];
}
});
});
};
/**
* Releases used database connection.
* You cannot use query runner methods once its released.
*/
SapQueryRunner.prototype.release = function () {
this.isReleased = true;
if (this.databaseConnection) {
return this.driver.master.release(this.databaseConnection);
}
return Promise.resolve();
};
/**
* Starts transaction.
*/
SapQueryRunner.prototype.startTransaction = function (isolationLevel) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var beforeBroadcastResult, afterBroadcastResult;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
if (this.isTransactionActive)
throw new TransactionAlreadyStartedError_1.TransactionAlreadyStartedError();
beforeBroadcastResult = new BroadcasterResult_1.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*/, 4];
return [4 /*yield*/, this.query("SET TRANSACTION ISOLATION LEVEL " + (isolationLevel || ""))];
case 3:
_a.sent();
_a.label = 4;
case 4:
afterBroadcastResult = new BroadcasterResult_1.BroadcasterResult();
this.broadcaster.broadcastAfterTransactionStartEvent(afterBroadcastResult);
if (!(afterBroadcastResult.promises.length > 0)) return [3 /*break*/, 6];
return [4 /*yield*/, Promise.all(afterBroadcastResult.promises)];
case 5:
_a.sent();
_a.label = 6;
case 6: return [2 /*return*/];
}
});
});
};
/**
* Commits transaction.
* Error will be thrown if transaction was not started.
*/
SapQueryRunner.prototype.commitTransaction = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var beforeBroadcastResult, afterBroadcastResult;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
if (!this.isTransactionActive)
throw new TransactionNotStartedError_1.TransactionNotStartedError();
beforeBroadcastResult = new BroadcasterResult_1.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_1.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.
*/
SapQueryRunner.prototype.rollbackTransaction = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var beforeBroadcastResult, afterBroadcastResult;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
if (!this.isTransactionActive)
throw new TransactionNotStartedError_1.TransactionNotStartedError();
beforeBroadcastResult = new BroadcasterResult_1.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_1.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 given SQL query.
*/
SapQueryRunner.prototype.query = function (query, parameters) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var waitingOkay, waitingPromise, otherWaitingPromises, promise;
var _this = this;
return tslib_1.__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 = tslib_1.__spreadArray([], tslib_1.__read(this.queryResponsibilityChain));
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 tslib_1.__awaiter(_this, void 0, void 0, function () {
var databaseConnection_1, queryStartTime_1, isInsertQuery_1, statement, err_1;
var _this = this;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.connect()];
case 1:
databaseConnection_1 = _a.sent();
// we disable autocommit because ROLLBACK does not work in autocommit mode
databaseConnection_1.setAutoCommit(!this.isTransactionActive);
this.driver.connection.logger.logQuery(query, parameters, this);
queryStartTime_1 = +new Date();
isInsertQuery_1 = query.substr(0, 11) === "INSERT INTO";
statement = databaseConnection_1.prepare(query);
statement.exec(parameters, function (err, result) {
// log slow queries if maxQueryExecution time is set
var maxQueryExecutionTime = _this.driver.connection.options.maxQueryExecutionTime;
var queryEndTime = +new Date();
var queryExecutionTime = queryEndTime - queryStartTime_1;
if (maxQueryExecutionTime && queryExecutionTime > maxQueryExecutionTime)
_this.driver.connection.logger.logQuerySlow(queryExecutionTime, query, parameters, _this);
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 index_1.QueryFailedError(query, parameters, err));
}
else {
if (isInsertQuery_1) {
var lastIdQuery_1 = "SELECT CURRENT_IDENTITY_VALUE() FROM \"SYS\".\"DUMMY\"";
_this.driver.connection.logger.logQuery(lastIdQuery_1, [], _this);
databaseConnection_1.exec(lastIdQuery_1, function (err, result) {
if (err) {
_this.driver.connection.logger.logQueryError(err, lastIdQuery_1, [], _this);
resolveChain();
fail(new index_1.QueryFailedError(lastIdQuery_1, [], err));
return;
}
ok(result[0]["CURRENT_IDENTITY_VALUE()"]);
resolveChain();
});
}
else {
ok(result);
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.
*/
SapQueryRunner.prototype.stream = function (query, parameters, onEnd, onError) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
return tslib_1.__generator(this, function (_a) {
throw new Error("Stream is not supported by SAP driver.");
});
});
};
/**
* Returns all available database names including system databases.
*/
SapQueryRunner.prototype.getDatabases = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var results;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.query("SELECT DATABASE_NAME FROM \"SYS\".\"M_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.
*/
SapQueryRunner.prototype.getSchemas = function (database) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var query, results;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
query = database ? "SELECT * FROM \"" + database + "\".\"SYS\".\"SCHEMAS\"" : "SELECT * FROM \"SYS\".\"SCHEMAS\"";
return [4 /*yield*/, this.query(query)];
case 1:
results = _a.sent();
return [2 /*return*/, results.map(function (result) { return result["SCHEMA_NAME"]; })];
}
});
});
};
/**
* Checks if database with the given name exist.
*/
SapQueryRunner.prototype.hasDatabase = function (database) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var databases;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getDatabases()];
case 1:
databases = _a.sent();
return [2 /*return*/, databases.indexOf(database) !== -1];
}
});
});
};
/**
* Returns current database.
*/
SapQueryRunner.prototype.getCurrentDatabase = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var currentDBQuery;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.query("SELECT \"VALUE\" AS \"db_name\" FROM \"SYS\".\"M_SYSTEM_OVERVIEW\" WHERE \"SECTION\" = 'System' and \"NAME\" = 'Instance ID'")];
case 1:
currentDBQuery = _a.sent();
return [2 /*return*/, currentDBQuery[0]["db_name"]];
}
});
});
};
/**
* Checks if schema with the given name exist.
*/
SapQueryRunner.prototype.hasSchema = function (schema) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var schemas;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getSchemas()];
case 1:
schemas = _a.sent();
return [2 /*return*/, schemas.indexOf(schema) !== -1];
}
});
});
};
/**
* Returns current schema.
*/
SapQueryRunner.prototype.getCurrentSchema = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var currentSchemaQuery;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.query("SELECT CURRENT_SCHEMA AS \"schema_name\" FROM \"SYS\".\"DUMMY\"")];
case 1:
currentSchemaQuery = _a.sent();
return [2 /*return*/, currentSchemaQuery[0]["schema_name"]];
}
});
});
};
/**
* Checks if table with the given name exist in the database.
*/
SapQueryRunner.prototype.hasTable = function (tableOrName) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var parsedTableName, sql, result;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
parsedTableName = this.parseTableName(tableOrName);
sql = "SELECT * FROM \"SYS\".\"TABLES\" WHERE \"SCHEMA_NAME\" = " + parsedTableName.schema + " AND \"TABLE_NAME\" = " + parsedTableName.tableName;
return [4 /*yield*/, this.query(sql)];
case 1:
result = _a.sent();
return [2 /*return*/, result.length ? true : false];
}
});
});
};
/**
* Checks if column with the given name exist in the given table.
*/
SapQueryRunner.prototype.hasColumn = function (tableOrName, columnName) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var parsedTableName, sql, result;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
parsedTableName = this.parseTableName(tableOrName);
sql = "SELECT * FROM \"SYS\".\"TABLE_COLUMNS\" WHERE \"SCHEMA_NAME\" = " + parsedTableName.schema + " AND \"TABLE_NAME\" = " + parsedTableName.tableName + " AND \"COLUMN_NAME\" = '" + columnName + "'";
return [4 /*yield*/, this.query(sql)];
case 1:
result = _a.sent();
return [2 /*return*/, result.length ? true : false];
}
});
});
};
/**
* Creates a new database.
*/
SapQueryRunner.prototype.createDatabase = function (database, ifNotExist) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
return tslib_1.__generator(this, function (_a) {
return [2 /*return*/, Promise.resolve()];
});
});
};
/**
* Drops database.
*/
SapQueryRunner.prototype.dropDatabase = function (database, ifExist) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
return tslib_1.__generator(this, function (_a) {
return [2 /*return*/, Promise.resolve()];
});
});
};
/**
* Creates a new table schema.
*/
SapQueryRunner.prototype.createSchema = function (schema, ifNotExist) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var exist, result, up, down;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
exist = false;
if (!ifNotExist) return [3 /*break*/, 2];
return [4 /*yield*/, this.query("SELECT * FROM \"SYS\".\"SCHEMAS\" WHERE \"SCHEMA_NAME\" = '" + schema + "'")];
case 1:
result = _a.sent();
exist = !!result.length;
_a.label = 2;
case 2:
if (!(!ifNotExist || (ifNotExist && !exist))) return [3 /*break*/, 4];
up = "CREATE SCHEMA \"" + schema + "\"";
down = "DROP SCHEMA \"" + schema + "\" CASCADE";
return [4 /*yield*/, this.executeQueries(new Query_1.Query(up), new Query_1.Query(down))];
case 3:
_a.sent();
_a.label = 4;
case 4: return [2 /*return*/];
}
});
});
};
/**
* Drops table schema
*/
SapQueryRunner.prototype.dropSchema = function (schemaPath, ifExist, isCascade) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var schema, exist, result, up, down;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
schema = schemaPath.indexOf(".") === -1 ? schemaPath : schemaPath.split(".")[0];
exist = false;
if (!ifExist) return [3 /*break*/, 2];
return [4 /*yield*/, this.query("SELECT * FROM \"SYS\".\"SCHEMAS\" WHERE \"SCHEMA_NAME\" = '" + schema + "'")];
case 1:
result = _a.sent();
exist = !!result.length;
_a.label = 2;
case 2:
if (!(!ifExist || (ifExist && exist))) return [3 /*break*/, 4];
up = "DROP SCHEMA \"" + schema + "\" " + (isCascade ? "CASCADE" : "");
down = "CREATE SCHEMA \"" + schema + "\"";
return [4 /*yield*/, this.executeQueries(new Query_1.Query(up), new Query_1.Query(down))];
case 3:
_a.sent();
_a.label = 4;
case 4: return [2 /*return*/];
}
});
});
};
/**
* Creates a new table.
*/
SapQueryRunner.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 tslib_1.__awaiter(this, void 0, void 0, function () {
var isTableExist, upQueries, downQueries;
var _this = this;
return tslib_1.__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.
*/
SapQueryRunner.prototype.dropTable = function (tableOrName, ifExist, dropForeignKeys, dropIndices) {
if (dropForeignKeys === void 0) { dropForeignKeys = true; }
if (dropIndices === void 0) { dropIndices = true; }
return tslib_1.__awaiter(this, void 0, void 0, function () {
var isTableExist, createForeignKeys, table, _a, upQueries, downQueries;
var _this = this;
return tslib_1.__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*/];
}
});
});
};
/**
* Creates a new view.
*/
SapQueryRunner.prototype.createView = function (view) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var upQueries, downQueries, _a, _b, _c, _d;
return tslib_1.__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.
*/
SapQueryRunner.prototype.dropView = function (target) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var viewName, view, upQueries, downQueries, _a, _b, _c, _d;
return tslib_1.__generator(this, function (_e) {
switch (_e.label) {
case 0:
viewName = target instanceof View_1.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.
*/
SapQueryRunner.prototype.renameTable = function (oldTableOrName, newTableName) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var upQueries, downQueries, oldTable, _a, newTable, oldTableName, schemaName, referencedForeignKeySql, dbForeignKeys, referencedForeignKeys, referencedForeignKeyTableMapping, columnNames, columnNamesString, oldPkName, newPkName;
var _this = this;
return tslib_1.__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();
oldTableName = oldTable.name.indexOf(".") === -1 ? oldTable.name : oldTable.name.split(".")[1];
schemaName = oldTable.name.indexOf(".") === -1 ? undefined : oldTable.name.split(".")[0];
newTable.name = schemaName ? schemaName + "." + newTableName : newTableName;
// rename table
upQueries.push(new Query_1.Query("RENAME TABLE " + this.escapePath(oldTable.name) + " TO " + this.escapePath(newTableName)));
downQueries.push(new Query_1.Query("RENAME TABLE " + this.escapePath(newTable.name) + " TO " + this.escapePath(oldTableName)));
// drop old FK's. Foreign keys must be dropped before the primary keys are dropped
newTable.foreignKeys.forEach(function (foreignKey) {
upQueries.push(_this.dropForeignKeySql(newTable, foreignKey));
downQueries.push(_this.createForeignKeySql(newTable, foreignKey));
});
referencedForeignKeySql = "SELECT * FROM \"SYS\".\"REFERENTIAL_CONSTRAINTS\" WHERE \"REFERENCED_SCHEMA_NAME\" = '" + schemaName + "' AND \"REFERENCED_TABLE_NAME\" = '" + oldTableName + "'";
return [4 /*yield*/, this.query(referencedForeignKeySql)];
case 4:
dbForeignKeys = _b.sent();
referencedForeignKeys = [];
referencedForeignKeyTableMapping = [];
if (dbForeignKeys.length > 0) {
referencedForeignKeys = dbForeignKeys.map(function (dbForeignKey) {
var foreignKeys = dbForeignKeys.filter(function (dbFk) { return dbFk["CONSTRAINT_NAME"] === dbForeignKey["CONSTRAINT_NAME"]; });
referencedForeignKeyTableMapping.push({ tableName: dbForeignKey["SCHEMA_NAME"] + "." + dbForeignKey["TABLE_NAME"], fkName: dbForeignKey["CONSTRAINT_NAME"] });
return new TableForeignKey_1.TableForeignKey({
name: dbForeignKey["CONSTRAINT_NAME"],
columnNames: foreignKeys.map(function (dbFk) { return dbFk["COLUMN_NAME"]; }),
referencedTableName: newTable.name,
referencedColumnNames: foreignKeys.map(function (dbFk) { return dbFk["REFERENCED_COLUMN_NAME"]; }),
onDelete: dbForeignKey["DELETE_RULE"] === "RESTRICT" ? "NO ACTION" : dbForeignKey["DELETE_RULE"],
onUpdate: dbForeignKey["UPDATE_RULE"] === "RESTRICT" ? "NO ACTION" : dbForeignKey["UPDATE_RULE"],
});
});
// drop referenced foreign keys
referencedForeignKeys.forEach(function (foreignKey) {
var mapping = referencedForeignKeyTableMapping.find(function (it) { return it.fkName === foreignKey.name; });
upQueries.push(_this.dropForeignKeySql(mapping.tableName, foreignKey));
downQueries.push(_this.createForeignKeySql(mapping.tableName, foreignKey));
});
}
// rename primary key constraint
if (newTable.primaryColumns.length > 0) {
columnNames = newTable.primaryColumns.map(function (column) { return column.name; });
columnNamesString = columnNames.map(function (columnName) { return "\"" + columnName + "\""; }).join(", ");
oldPkName = this.connection.namingStrategy.primaryKeyName(oldTable, columnNames);
newPkName = this.connection.namingStrategy.primaryKeyName(newTable, columnNames);
// drop old PK
upQueries.push(new Query_1.Query("ALTER TABLE " + this.escapePath(newTable) + " DROP CONSTRAINT \"" + oldPkName + "\""));
downQueries.push(new Query_1.Query("ALTER TABLE " + this.escapePath(newTable) + " ADD CONSTRAINT \"" + oldPkName + "\" PRIMARY KEY (" + columnNamesString + ")"));
// create new PK
upQueries.push(new Query_1.Query("ALTER TABLE " + this.escapePath(newTable) + " ADD CONSTRAINT \"" + newPkName + "\" PRIMARY KEY (" + columnNamesString + ")"));
downQueries.push(new Query_1.Query("ALTER TABLE " + this.escapePath(newTable) + " DROP CONSTRAINT \"" + newPkName + "\""));
}
// recreate foreign keys with new constraint names
newTable.foreignKeys.forEach(function (foreignKey) {
// replace constraint name
foreignKey.name = _this.connection.namingStrategy.foreignKeyName(newTable, foreignKey.columnNames, foreignKey.referencedTableName, foreignKey.referencedColumnNames);
// create new FK's
upQueries.push(_this.createForeignKeySql(newTable, foreignKey));
downQueries.push(_this.dropForeignKeySql(newTable, foreignKey));
});
// restore referenced foreign keys
referencedForeignKeys.forEach(function (foreignKey) {
var mapping = referencedForeignKeyTableMapping.find(function (it) { return it.fkName === foreignKey.name; });
upQueries.push(_this.createForeignKeySql(mapping.tableName, foreignKey));
downQueries.push(_this.dropForeignKeySql(mapping.tableName, foreignKey));
});
// rename index constraints
newTable.indices.forEach(function (index) {
// build new constraint name
var newIndexName = _this.connection.namingStrategy.indexName(newTable, index.columnNames, index.where);
// drop old index
upQueries.push(_this.dropIndexSql(newTable, index));
downQueries.push(_this.createIndexSql(newTable, index));
// replace constraint name
index.name = newIndexName;
// create new index
upQueries.push(_this.createIndexSql(newTable, index));
downQueries.push(_this.dropIndexSql(newTable, index));
});
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.
*/
SapQueryRunner.prototype.addColumn = function (tableOrName, column) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var table, _a, parsedTableName, clonedTable, upQueries, downQueries, primaryColumns, referencedForeignKeySql, dbForeignKeys_1, referencedForeignKeys, referencedForeignKeyTableMapping_1, pkName_1, columnNames_1, pkName, columnNames, columnIndex, uniqueIndex;
var _this = this;
return tslib_1.__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;
parsedTableName = this.parseTableName(table);
clonedTable = table.clone();
upQueries = [];
downQueries = [];
upQueries.push(new Query_1.Query(this.addColumnSql(table, column)));
downQueries.push(new Query_1.Query(this.dropColumnSql(table, column)));
if (!column.isPrimary) return [3 /*break*/, 6];
primaryColumns = clonedTable.primaryColumns;
if (!(primaryColumns.length > 0)) return [3 /*break*/, 5];
referencedForeignKeySql = "SELECT * FROM \"SYS\".\"REFERENTIAL_CONSTRAINTS\" WHERE \"REFERENCED_SCHEMA_NAME\" = " + parsedTableName.schema + " AND \"REFERENCED_TABLE_NAME\" = " + parsedTableName.tableName;
return [4 /*yield*/, this.query(referencedForeignKeySql)];
case 4:
dbForeignKeys_1 = _b.sent();
referencedForeignKeys = [];
referencedForeignKeyTableMapping_1 = [];
if (dbForeignKeys_1.length > 0) {
referencedForeignKeys = dbForeignKeys_1.map(function (dbForeignKey) {
var foreignKeys = dbForeignKeys_1.filter(function (dbFk) { return dbFk["CONSTRAINT_NAME"] === dbForeignKey["CONSTRAINT_NAME"]; });
referencedForeignKeyTableMapping_1.push({ tableName: dbForeignKey["SCHEMA_NAME"] + "." + dbForeignKey["TABLE_NAME"], fkName: dbForeignKey["CONSTRAINT_NAME"] });
return new TableForeignKey_1.TableForeignKey({
name: dbForeignKey["CONSTRAINT_NAME"],
columnNames: foreignKeys.map(function (dbFk) { return dbFk["COLUMN_NAME"]; }),
referencedTableName: table.name,
referencedColumnNames: foreignKeys.map(function (dbFk) { return dbFk["REFERENCED_COLUMN_NAME"]; }),
onDelete: dbForeignKey["DELETE_RULE"] === "RESTRICT" ? "NO ACTION" : dbForeignKey["DELETE_RULE"],
onUpdate: dbForeignKey["UPDATE_RULE"] === "RESTRICT" ? "NO ACTION" : dbForeignKey["UPDATE_RULE"],
});
});
// drop referenced foreign keys
referencedForeignKeys.forEach(function (foreignKey) {
var mapping = referencedForeignKeyTableMapping_1.find(function (it) { return it.fkName === foreignKey.name; });
upQueries.push(_this.dropForeignKeySql(mapping.tableName, foreignKey));
downQueries.push(_this.createForeignKeySql(mapping.tableName, foreignKey));
});
}
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(new Query_1.Query("ALTER TABLE " + this.escapePath(table) + " DROP CONSTRAINT \"" + pkName_1 + "\""));
downQueries.push(new Query_1.Query("ALTER TABLE " + this.escapePath(table) + " ADD CONSTRAINT \"" + pkName_1 + "\" PRIMARY KEY (" + columnNames_1 + ")"));
// restore referenced foreign keys
referencedForeignKeys.forEach(function (foreignKey) {
var mapping = referencedForeignKeyTableMapping_1.find(function (it) { return it.fkName === foreignKey.name; });
upQueries.push(_this.createForeignKeySql(mapping.tableName, foreignKey));
downQueries.push(_this.dropForeignKeySql(mapping.tableName, foreignKey));
});
_b.label = 5;
case 5:
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(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 + "\""));
_b.label = 6;
case 6:
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_1.TableIndex({