typeorm
Version:
Data-Mapper ORM for TypeScript, ES7, ES6, ES5. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, MongoDB databases.
936 lines • 165 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CockroachQueryRunner = void 0;
var tslib_1 = require("tslib");
var QueryResult_1 = require("../../query-runner/QueryResult");
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 TableIndex_1 = require("../../schema-builder/table/TableIndex");
var TableForeignKey_1 = require("../../schema-builder/table/TableForeignKey");
var QueryRunnerAlreadyReleasedError_1 = require("../../error/QueryRunnerAlreadyReleasedError");
var View_1 = require("../../schema-builder/view/View");
var Query_1 = require("../Query");
var QueryFailedError_1 = require("../../error/QueryFailedError");
var Broadcaster_1 = require("../../subscriber/Broadcaster");
var TableUnique_1 = require("../../schema-builder/table/TableUnique");
var BaseQueryRunner_1 = require("../../query-runner/BaseQueryRunner");
var OrmUtils_1 = require("../../util/OrmUtils");
var TableCheck_1 = require("../../schema-builder/table/TableCheck");
var TableExclusion_1 = require("../../schema-builder/table/TableExclusion");
var BroadcasterResult_1 = require("../../subscriber/BroadcasterResult");
var error_1 = require("../../error");
/**
* Runs queries on a single postgres database connection.
*/
var CockroachQueryRunner = /** @class */ (function (_super) {
tslib_1.__extends(CockroachQueryRunner, _super);
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
function CockroachQueryRunner(driver, mode) {
var _this = _super.call(this) || this;
/**
* Stores all executed queries to be able to run them again if transaction fails.
*/
_this.queries = [];
/**
* Indicates if running queries must be stored
*/
_this.storeQueries = false;
_this.driver = driver;
_this.connection = driver.connection;
_this.mode = mode;
_this.broadcaster = new Broadcaster_1.Broadcaster(_this);
return _this;
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Creates/uses database connection from the connection pool to perform further operations.
* Returns obtained database connection.
*/
CockroachQueryRunner.prototype.connect = function () {
var _this = this;
if (this.databaseConnection)
return Promise.resolve(this.databaseConnection);
if (this.databaseConnectionPromise)
return this.databaseConnectionPromise;
if (this.mode === "slave" && this.driver.isReplicated) {
this.databaseConnectionPromise = this.driver.obtainSlaveConnection().then(function (_a) {
var _b = tslib_1.__read(_a, 2), connection = _b[0], release = _b[1];
_this.driver.connectedQueryRunners.push(_this);
_this.databaseConnection = connection;
_this.releaseCallback = release;
return _this.databaseConnection;
});
}
else { // master
this.databaseConnectionPromise = this.driver.obtainMasterConnection().then(function (_a) {
var _b = tslib_1.__read(_a, 2), connection = _b[0], release = _b[1];
_this.driver.connectedQueryRunners.push(_this);
_this.databaseConnection = connection;
_this.releaseCallback = release;
return _this.databaseConnection;
});
}
return this.databaseConnectionPromise;
};
/**
* Releases used database connection.
* You cannot use query runner methods once its released.
*/
CockroachQueryRunner.prototype.release = function () {
this.isReleased = true;
if (this.releaseCallback)
this.releaseCallback();
var index = this.driver.connectedQueryRunners.indexOf(this);
if (index !== -1)
this.driver.connectedQueryRunners.splice(index);
return Promise.resolve();
};
/**
* Starts transaction.
*/
CockroachQueryRunner.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.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;
return [4 /*yield*/, this.query("START TRANSACTION")];
case 3:
_a.sent();
return [4 /*yield*/, this.query("SAVEPOINT cockroach_restart")];
case 4:
_a.sent();
if (!isolationLevel) return [3 /*break*/, 6];
return [4 /*yield*/, this.query("SET TRANSACTION ISOLATION LEVEL " + isolationLevel)];
case 5:
_a.sent();
_a.label = 6;
case 6:
this.storeQueries = true;
afterBroadcastResult = new BroadcasterResult_1.BroadcasterResult();
this.broadcaster.broadcastAfterTransactionStartEvent(afterBroadcastResult);
if (!(afterBroadcastResult.promises.length > 0)) return [3 /*break*/, 8];
return [4 /*yield*/, Promise.all(afterBroadcastResult.promises)];
case 7:
_a.sent();
_a.label = 8;
case 8: return [2 /*return*/];
}
});
});
};
/**
* Commits transaction.
* Error will be thrown if transaction was not started.
*/
CockroachQueryRunner.prototype.commitTransaction = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var beforeBroadcastResult, e_1, _a, _b, q, e_2_1, afterBroadcastResult;
var e_2, _c;
return tslib_1.__generator(this, function (_d) {
switch (_d.label) {
case 0:
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:
_d.sent();
_d.label = 2;
case 2:
this.storeQueries = false;
_d.label = 3;
case 3:
_d.trys.push([3, 6, , 18]);
return [4 /*yield*/, this.query("RELEASE SAVEPOINT cockroach_restart")];
case 4:
_d.sent();
return [4 /*yield*/, this.query("COMMIT")];
case 5:
_d.sent();
this.queries = [];
this.isTransactionActive = false;
return [3 /*break*/, 18];
case 6:
e_1 = _d.sent();
if (!(e_1.code === "40001")) return [3 /*break*/, 17];
return [4 /*yield*/, this.query("ROLLBACK TO SAVEPOINT cockroach_restart")];
case 7:
_d.sent();
_d.label = 8;
case 8:
_d.trys.push([8, 13, 14, 15]);
_a = tslib_1.__values(this.queries), _b = _a.next();
_d.label = 9;
case 9:
if (!!_b.done) return [3 /*break*/, 12];
q = _b.value;
return [4 /*yield*/, this.query(q.query, q.parameters)];
case 10:
_d.sent();
_d.label = 11;
case 11:
_b = _a.next();
return [3 /*break*/, 9];
case 12: return [3 /*break*/, 15];
case 13:
e_2_1 = _d.sent();
e_2 = { error: e_2_1 };
return [3 /*break*/, 15];
case 14:
try {
if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
}
finally { if (e_2) throw e_2.error; }
return [7 /*endfinally*/];
case 15: return [4 /*yield*/, this.commitTransaction()];
case 16:
_d.sent();
_d.label = 17;
case 17: return [3 /*break*/, 18];
case 18:
afterBroadcastResult = new BroadcasterResult_1.BroadcasterResult();
this.broadcaster.broadcastAfterTransactionCommitEvent(afterBroadcastResult);
if (!(afterBroadcastResult.promises.length > 0)) return [3 /*break*/, 20];
return [4 /*yield*/, Promise.all(afterBroadcastResult.promises)];
case 19:
_d.sent();
_d.label = 20;
case 20: return [2 /*return*/];
}
});
});
};
/**
* Rollbacks transaction.
* Error will be thrown if transaction was not started.
*/
CockroachQueryRunner.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.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:
this.storeQueries = false;
return [4 /*yield*/, this.query("ROLLBACK")];
case 3:
_a.sent();
this.queries = [];
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.
*/
CockroachQueryRunner.prototype.query = function (query, parameters, useStructuredResult) {
var _this = this;
if (useStructuredResult === void 0) { useStructuredResult = false; }
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
return new Promise(function (ok, fail) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
var databaseConnection, queryStartTime_1, 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 = _a.sent();
this.driver.connection.logger.logQuery(query, parameters, this);
queryStartTime_1 = +new Date();
databaseConnection.query(query, parameters, function (err, raw) {
if (_this.isTransactionActive && _this.storeQueries)
_this.queries.push({ query: query, parameters: parameters });
// log slow queries if maxQueryExecution time is set
var maxQueryExecutionTime = _this.driver.options.maxQueryExecutionTime;
var queryEndTime = +new Date();
var queryExecutionTime = queryEndTime - queryStartTime_1;
if (maxQueryExecutionTime && queryExecutionTime > maxQueryExecutionTime)
_this.driver.connection.logger.logQuerySlow(queryExecutionTime, query, parameters, _this);
if (err) {
if (err.code !== "40001")
_this.driver.connection.logger.logQueryError(err, query, parameters, _this);
fail(new QueryFailedError_1.QueryFailedError(query, parameters, err));
}
else {
var result = new QueryResult_1.QueryResult();
if (raw.hasOwnProperty('rowCount')) {
result.affected = raw.rowCount;
}
if (raw.hasOwnProperty('rows')) {
result.records = raw.rows;
}
switch (raw.command) {
case "DELETE":
// for DELETE query additionally return number of affected rows
result.raw = [raw.rows, raw.rowCount];
break;
default:
result.raw = raw.rows;
}
if (useStructuredResult) {
ok(result);
}
else {
ok(result.raw);
}
}
});
return [3 /*break*/, 3];
case 2:
err_1 = _a.sent();
fail(err_1);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); });
};
/**
* Returns raw data stream.
*/
CockroachQueryRunner.prototype.stream = function (query, parameters, onEnd, onError) {
var _this = this;
var QueryStream = this.driver.loadStreamDependency();
if (this.isReleased)
throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
return new Promise(function (ok, fail) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
var databaseConnection, stream, err_2;
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 = _a.sent();
this.driver.connection.logger.logQuery(query, parameters, this);
stream = databaseConnection.query(new QueryStream(query, parameters));
if (onEnd)
stream.on("end", onEnd);
if (onError)
stream.on("error", onError);
ok(stream);
return [3 /*break*/, 3];
case 2:
err_2 = _a.sent();
fail(err_2);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
}); });
};
/**
* Returns all available database names including system databases.
*/
CockroachQueryRunner.prototype.getDatabases = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
return tslib_1.__generator(this, function (_a) {
return [2 /*return*/, Promise.resolve([])];
});
});
};
/**
* Returns all available schema names including system schemas.
* If database parameter specified, returns schemas of that database.
*/
CockroachQueryRunner.prototype.getSchemas = function (database) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
return tslib_1.__generator(this, function (_a) {
return [2 /*return*/, Promise.resolve([])];
});
});
};
/**
* Checks if database with the given name exist.
*/
CockroachQueryRunner.prototype.hasDatabase = function (database) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var result;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.query("SELECT * FROM \"pg_database\" WHERE \"datname\" = '" + database + "'")];
case 1:
result = _a.sent();
return [2 /*return*/, result.length ? true : false];
}
});
});
};
/**
* Loads currently using database
*/
CockroachQueryRunner.prototype.getCurrentDatabase = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var query;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.query("SELECT * FROM current_database()")];
case 1:
query = _a.sent();
return [2 /*return*/, query[0]["current_database"]];
}
});
});
};
/**
* Checks if schema with the given name exist.
*/
CockroachQueryRunner.prototype.hasSchema = function (schema) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var result;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.query("SELECT * FROM \"information_schema\".\"schemata\" WHERE \"schema_name\" = '" + schema + "'")];
case 1:
result = _a.sent();
return [2 /*return*/, result.length ? true : false];
}
});
});
};
/**
* Loads currently using database schema
*/
CockroachQueryRunner.prototype.getCurrentSchema = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var query;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.query("SELECT * FROM current_schema()")];
case 1:
query = _a.sent();
return [2 /*return*/, query[0]["current_schema"]];
}
});
});
};
/**
* Checks if table with the given name exist in the database.
*/
CockroachQueryRunner.prototype.hasTable = function (tableOrName) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var parsedTableName, _a, sql, result;
return tslib_1.__generator(this, function (_b) {
switch (_b.label) {
case 0:
parsedTableName = this.driver.parseTableName(tableOrName);
if (!!parsedTableName.schema) return [3 /*break*/, 2];
_a = parsedTableName;
return [4 /*yield*/, this.getCurrentSchema()];
case 1:
_a.schema = _b.sent();
_b.label = 2;
case 2:
sql = "SELECT * FROM \"information_schema\".\"tables\" WHERE \"table_schema\" = '" + parsedTableName.schema + "' AND \"table_name\" = '" + parsedTableName.tableName + "'";
return [4 /*yield*/, this.query(sql)];
case 3:
result = _b.sent();
return [2 /*return*/, result.length ? true : false];
}
});
});
};
/**
* Checks if column with the given name exist in the given table.
*/
CockroachQueryRunner.prototype.hasColumn = function (tableOrName, columnName) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var parsedTableName, _a, sql, result;
return tslib_1.__generator(this, function (_b) {
switch (_b.label) {
case 0:
parsedTableName = this.driver.parseTableName(tableOrName);
if (!!parsedTableName.schema) return [3 /*break*/, 2];
_a = parsedTableName;
return [4 /*yield*/, this.getCurrentSchema()];
case 1:
_a.schema = _b.sent();
_b.label = 2;
case 2:
sql = "SELECT * FROM \"information_schema\".\"columns\" WHERE \"table_schema\" = '" + parsedTableName.schema + "' AND \"table_name\" = '" + parsedTableName.tableName + "' AND \"column_name\" = '" + columnName + "'";
return [4 /*yield*/, this.query(sql)];
case 3:
result = _b.sent();
return [2 /*return*/, result.length ? true : false];
}
});
});
};
/**
* Creates a new database.
*/
CockroachQueryRunner.prototype.createDatabase = function (database, ifNotExist) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var up, down;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
up = "CREATE DATABASE " + (ifNotExist ? "IF NOT EXISTS " : "") + " \"" + database + "\"";
down = "DROP DATABASE \"" + database + "\"";
return [4 /*yield*/, this.executeQueries(new Query_1.Query(up), new Query_1.Query(down))];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* Drops database.
*/
CockroachQueryRunner.prototype.dropDatabase = function (database, ifExist) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var up, down;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
up = "DROP DATABASE " + (ifExist ? "IF EXISTS " : "") + " \"" + database + "\"";
down = "CREATE DATABASE \"" + database + "\"";
return [4 /*yield*/, this.executeQueries(new Query_1.Query(up), new Query_1.Query(down))];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* Creates a new table schema.
*/
CockroachQueryRunner.prototype.createSchema = function (schemaPath, ifNotExist) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var schema, up, down;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
schema = schemaPath.indexOf(".") === -1 ? schemaPath : schemaPath.split(".")[1];
up = ifNotExist ? "CREATE SCHEMA IF NOT EXISTS \"" + schema + "\"" : "CREATE SCHEMA \"" + schema + "\"";
down = "DROP SCHEMA \"" + schema + "\" CASCADE";
return [4 /*yield*/, this.executeQueries(new Query_1.Query(up), new Query_1.Query(down))];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* Drops table schema.
*/
CockroachQueryRunner.prototype.dropSchema = function (schemaPath, ifExist, isCascade) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var schema, up, down;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
schema = schemaPath.indexOf(".") === -1 ? schemaPath : schemaPath.split(".")[1];
up = ifExist ? "DROP SCHEMA IF EXISTS \"" + schema + "\" " + (isCascade ? "CASCADE" : "") : "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 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* Creates a new table.
*/
CockroachQueryRunner.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 = [];
table.columns
.filter(function (column) { return column.isGenerated && column.generationStrategy === "increment"; })
.forEach(function (column) {
upQueries.push(new Query_1.Query("CREATE SEQUENCE " + _this.escapePath(_this.buildSequencePath(table, column))));
downQueries.push(new Query_1.Query("DROP SEQUENCE " + _this.escapePath(_this.buildSequencePath(table, column))));
});
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
.filter(function (index) { return !index.isUnique; })
.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, 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.
*/
CockroachQueryRunner.prototype.dropTable = function (target, 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, tablePath, table, upQueries, downQueries;
var _this = this;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!ifExist) return [3 /*break*/, 2];
return [4 /*yield*/, this.hasTable(target)];
case 1:
isTableExist = _a.sent();
if (!isTableExist)
return [2 /*return*/, Promise.resolve()];
_a.label = 2;
case 2:
createForeignKeys = dropForeignKeys;
tablePath = this.getTablePath(target);
return [4 /*yield*/, this.getCachedTable(tablePath)];
case 3:
table = _a.sent();
upQueries = [];
downQueries = [];
// foreign keys must be dropped before indices, because fk's rely on indices
if (dropForeignKeys)
table.foreignKeys.forEach(function (foreignKey) { return upQueries.push(_this.dropForeignKeySql(table, foreignKey)); });
if (dropIndices) {
table.indices.forEach(function (index) {
upQueries.push(_this.dropIndexSql(table, index));
downQueries.push(_this.createIndexSql(table, index));
});
}
upQueries.push(this.dropTableSql(table));
downQueries.push(this.createTableSql(table, createForeignKeys));
table.columns
.filter(function (column) { return column.isGenerated && column.generationStrategy === "increment"; })
.forEach(function (column) {
upQueries.push(new Query_1.Query("DROP SEQUENCE " + _this.escapePath(_this.buildSequencePath(table, column))));
downQueries.push(new Query_1.Query("CREATE SEQUENCE " + _this.escapePath(_this.buildSequencePath(table, column))));
});
return [4 /*yield*/, this.executeQueries(upQueries, downQueries)];
case 4:
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* Creates a new view.
*/
CockroachQueryRunner.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.
*/
CockroachQueryRunner.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 the given table.
*/
CockroachQueryRunner.prototype.renameTable = function (oldTableOrName, newTableName) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var upQueries, downQueries, oldTable, _a, newTable, _b, schemaName, oldTableName, columnNames, oldPkName, newPkName;
var _this = this;
return tslib_1.__generator(this, function (_c) {
switch (_c.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 = _c.sent();
_c.label = 3;
case 3:
oldTable = _a;
newTable = oldTable.clone();
_b = this.driver.parseTableName(oldTable), schemaName = _b.schema, oldTableName = _b.tableName;
newTable.name = schemaName ? schemaName + "." + newTableName : newTableName;
upQueries.push(new Query_1.Query("ALTER TABLE " + this.escapePath(oldTable) + " RENAME TO \"" + newTableName + "\""));
downQueries.push(new Query_1.Query("ALTER TABLE " + this.escapePath(newTable) + " RENAME TO \"" + oldTableName + "\""));
// rename column primary key constraint
if (newTable.primaryColumns.length > 0) {
columnNames = newTable.primaryColumns.map(function (column) { return column.name; });
oldPkName = this.connection.namingStrategy.primaryKeyName(oldTable, columnNames);
newPkName = this.connection.namingStrategy.primaryKeyName(newTable, columnNames);
upQueries.push(new Query_1.Query("ALTER TABLE " + this.escapePath(newTable) + " RENAME CONSTRAINT \"" + oldPkName + "\" TO \"" + newPkName + "\""));
downQueries.push(new Query_1.Query("ALTER TABLE " + this.escapePath(newTable) + " RENAME CONSTRAINT \"" + newPkName + "\" TO \"" + oldPkName + "\""));
}
// rename unique constraints
newTable.uniques.forEach(function (unique) {
// build new constraint name
var newUniqueName = _this.connection.namingStrategy.uniqueConstraintName(newTable, unique.columnNames);
// build queries
upQueries.push(new Query_1.Query("ALTER TABLE " + _this.escapePath(newTable) + " RENAME CONSTRAINT \"" + unique.name + "\" TO \"" + newUniqueName + "\""));
downQueries.push(new Query_1.Query("ALTER TABLE " + _this.escapePath(newTable) + " RENAME CONSTRAINT \"" + newUniqueName + "\" TO \"" + unique.name + "\""));
// replace constraint name
unique.name = newUniqueName;
});
// rename index constraints
newTable.indices.forEach(function (index) {
// build new constraint name
var schema = _this.driver.parseTableName(newTable).schema;
var newIndexName = _this.connection.namingStrategy.indexName(newTable, index.columnNames, index.where);
// build queries
var up = schema ? "ALTER INDEX \"" + schema + "\".\"" + index.name + "\" RENAME TO \"" + newIndexName + "\"" : "ALTER INDEX \"" + index.name + "\" RENAME TO \"" + newIndexName + "\"";
var down = schema ? "ALTER INDEX \"" + schema + "\".\"" + newIndexName + "\" RENAME TO \"" + index.name + "\"" : "ALTER INDEX \"" + newIndexName + "\" RENAME TO \"" + index.name + "\"";
upQueries.push(new Query_1.Query(up));
downQueries.push(new Query_1.Query(down));
// replace constraint name
index.name = newIndexName;
});
// rename foreign key constraints
newTable.foreignKeys.forEach(function (foreignKey) {
// build new constraint name
var newForeignKeyName = _this.connection.namingStrategy.foreignKeyName(newTable, foreignKey.columnNames, _this.getTablePath(foreignKey), foreignKey.referencedColumnNames);
// build queries
upQueries.push(new Query_1.Query("ALTER TABLE " + _this.escapePath(newTable) + " RENAME CONSTRAINT \"" + foreignKey.name + "\" TO \"" + newForeignKeyName + "\""));
downQueries.push(new Query_1.Query("ALTER TABLE " + _this.escapePath(newTable) + " RENAME CONSTRAINT \"" + newForeignKeyName + "\" TO \"" + foreignKey.name + "\""));
// replace constraint name
foreignKey.name = newForeignKeyName;
});
return [4 /*yield*/, this.executeQueries(upQueries, downQueries)];
case 4:
_c.sent();
return [2 /*return*/];
}
});
});
};
/**
* Creates a new column from the column in the table.
*/
CockroachQueryRunner.prototype.addColumn = function (tableOrName, column) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var table, _a, clonedTable, upQueries, downQueries, primaryColumns, pkName_1, columnNames_1, pkName, columnNames, columnIndex, unique, uniqueConstraint;
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;
clonedTable = table.clone();
upQueries = [];
downQueries = [];
if (column.generationStrategy === "increment") {
throw new error_1.TypeORMError("Adding sequential generated columns into existing table is not supported");
}
upQueries.push(new Query_1.Query("ALTER TABLE " + this.escapePath(table) + " ADD " + this.buildCreateColumnSql(table, column)));
downQueries.push(new Query_1.Query("ALTER TABLE " + this.escapePath(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
// todo: altering pk is not supported yet https://github.com/cockroachdb/cockroach/issues/19141
if (primaryColumns.length > 0) {
pkName_1 = this.connection.namingStrategy.primaryKeyName(clonedTable, 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 + ")"));
}
primaryColumns.push(column);
pkName = this.connection.namingStrategy.primaryKeyName(clonedTable, 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 + "\""));
}
columnIndex = clonedTable.indices.find(function (index) { return index.columnNames.length === 1 && index.columnNames[0] === column.name; });
if (columnIndex) {
// CockroachDB stores unique indices as UNIQUE constraints
if (columnIndex.isUnique) {
unique = new TableUnique_1.TableUnique({
name: this.connection.namingStrategy.uniqueConstraintName(table, columnIndex.columnNames),
columnNames: columnIndex.columnNames
});
upQueries.push(this.createUniqueConstraintSql(table, unique));
downQueries.push(this.dropIndexSql(table, unique));
clonedTable.uniques.push(unique);
}
else {
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, [column.name]),
columnNames: [column.name]
});
clonedTable.uniques.push(uniqueConstraint);
upQueries.push(this.createUniqueConstraintSql(table, uniqueConstraint));
downQueries.push(this.dropIndexSql(table, uniqueConstraint.name)); // CockroachDB creates indices for unique constraints
}
// create column's comment
if (column.comment) {
upQueries.push(new Query_1.Query("COMMENT ON COLUMN " + this.escapePath(table) + ".\"" + column.name + "\" IS " + this.escapeComment(column.comment)));
downQueries.push(new Query_1.Query("COMMENT ON COLUMN " + this.escapePath(table) + ".\"" + column.name + "\" IS " + this.escapeComment(column.comment)));
}
return [4 /*yield*/, this.executeQueries(upQueries, downQueries)];
case 4:
_b.sent();
clonedTable.addColumn(column);
this.replaceCachedTable(table, clonedTable);
return [2 /*return*/];
}
});
});
};
/**
* Creates a new columns from the column in the table.
*/
CockroachQueryRunner.prototype.addColumns = function (tableOrName, columns) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var columns_1, columns_1_1, column, e_3_1;
var e_3, _a;
return tslib_1.__generator(this, function (_b) {
switch (_b.label) {
case 0:
_b.trys.push([0, 5, 6, 7]);
columns_1 = tslib_1.__values(columns), columns_1_1 = columns_1.next();
_b.label = 1;
case 1:
if (!!columns_1_1.done) return [3 /*break*/, 4];
column = columns_1_1.value;
return [4 /*yield*/, this.addColumn(tableOrName, column)];
case 2:
_b.sent();
_b.label = 3;
case 3:
columns_1_1 = columns_1.next();
return [3 /*break*/, 1];
case 4: return [3 /*break*/, 7];
case 5:
e_3_1 = _b.sent();
e_3 = { error: e_3_1 };
return [3 /*break*/, 7];
case 6:
try {
if (c