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 };
    }
};
import { SqlInMemory } from "../driver/SqlInMemory";
import { PromiseUtils } from "../util/PromiseUtils";
var BaseQueryRunner = /** @class */ (function () {
    function BaseQueryRunner() {
        // -------------------------------------------------------------------------
        // Public Properties
        // -------------------------------------------------------------------------
        /**
         * Indicates if connection for this query runner is released.
         * Once its released, query runner cannot run queries anymore.
         */
        this.isReleased = false;
        /**
         * Indicates if transaction is in progress.
         */
        this.isTransactionActive = false;
        /**
         * Stores temporarily user data.
         * Useful for sharing data with subscribers.
         */
        this.data = {};
        /**
         * All synchronized tables in the database.
         */
        this.loadedTables = [];
        /**
         * Indicates if special query runner mode in which sql queries won't be executed is enabled.
         */
        this.sqlMemoryMode = false;
        /**
         * Sql-s stored if "sql in memory" mode is enabled.
         */
        this.sqlInMemory = new SqlInMemory();
    }
    // -------------------------------------------------------------------------
    // Public Methods
    // -------------------------------------------------------------------------
    /**
     * Loads given table's data from the database.
     */
    BaseQueryRunner.prototype.getTable = function (tablePath) {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this;
                        return [4 /*yield*/, this.loadTables([tablePath])];
                    case 1:
                        _a.loadedTables = _b.sent();
                        return [2 /*return*/, this.loadedTables.length > 0 ? this.loadedTables[0] : undefined];
                }
            });
        });
    };
    /**
     * Loads all tables (with given names) from the database.
     */
    BaseQueryRunner.prototype.getTables = function (tableNames) {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this;
                        return [4 /*yield*/, this.loadTables(tableNames)];
                    case 1:
                        _a.loadedTables = _b.sent();
                        return [2 /*return*/, this.loadedTables];
                }
            });
        });
    };
    /**
     * Enables special query runner mode in which sql queries won't be executed,
     * instead they will be memorized into a special variable inside query runner.
     * You can get memorized sql using getMemorySql() method.
     */
    BaseQueryRunner.prototype.enableSqlMemory = function () {
        this.sqlInMemory = new SqlInMemory();
        this.sqlMemoryMode = true;
    };
    /**
     * Disables special query runner mode in which sql queries won't be executed
     * started by calling enableSqlMemory() method.
     *
     * Previously memorized sql will be flushed.
     */
    BaseQueryRunner.prototype.disableSqlMemory = function () {
        this.sqlInMemory = new SqlInMemory();
        this.sqlMemoryMode = false;
    };
    /**
     * Flushes all memorized sqls.
     */
    BaseQueryRunner.prototype.clearSqlMemory = function () {
        this.sqlInMemory = new SqlInMemory();
    };
    /**
     * Gets sql stored in the memory. Parameters in the sql are already replaced.
     */
    BaseQueryRunner.prototype.getMemorySql = function () {
        return this.sqlInMemory;
    };
    /**
     * Executes up sql queries.
     */
    BaseQueryRunner.prototype.executeMemoryUpSql = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, PromiseUtils.runInSequence(this.sqlInMemory.upQueries, function (downQuery) { return _this.query(downQuery); })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Executes down sql queries.
     */
    BaseQueryRunner.prototype.executeMemoryDownSql = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, PromiseUtils.runInSequence(this.sqlInMemory.downQueries.reverse(), function (downQuery) { return _this.query(downQuery); })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    // -------------------------------------------------------------------------
    // Protected Methods
    // -------------------------------------------------------------------------
    /**
     * Gets table from previously loaded tables, otherwise loads it from database.
     */
    BaseQueryRunner.prototype.getCachedTable = function (tableName) {
        return __awaiter(this, void 0, void 0, function () {
            var table, foundTables;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        table = this.loadedTables.find(function (table) { return table.name === tableName; });
                        if (table)
                            return [2 /*return*/, table];
                        return [4 /*yield*/, this.loadTables([tableName])];
                    case 1:
                        foundTables = _a.sent();
                        if (foundTables.length > 0) {
                            this.loadedTables.push(foundTables[0]);
                            return [2 /*return*/, foundTables[0]];
                        }
                        else {
                            throw new Error("Table \"" + tableName + "\" does not exist.");
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Replaces loaded table with given changed table.
     */
    BaseQueryRunner.prototype.replaceCachedTable = function (table, changedTable) {
        var foundTable = this.loadedTables.find(function (loadedTable) { return loadedTable.name === table.name; });
        if (foundTable) {
            foundTable.name = changedTable.name;
            foundTable.columns = changedTable.columns;
            foundTable.indices = changedTable.indices;
            foundTable.foreignKeys = changedTable.foreignKeys;
            foundTable.uniques = changedTable.uniques;
            foundTable.checks = changedTable.checks;
            foundTable.justCreated = changedTable.justCreated;
            foundTable.engine = changedTable.engine;
        }
    };
    /**
     * Checks if at least one of column properties was changed.
     * Does not checks column type, length and autoincrement, because these properties changes separately.
     */
    BaseQueryRunner.prototype.isColumnChanged = function (oldColumn, newColumn, checkDefault, checkComment) {
        // this logs need to debug issues in column change detection. Do not delete it!
        // console.log("charset ---------------");
        // console.log(oldColumn.charset !== newColumn.charset);
        // console.log(oldColumn.charset, newColumn.charset);
        // console.log("collation ---------------");
        // console.log(oldColumn.collation !== newColumn.collation);
        // console.log(oldColumn.collation, newColumn.collation);
        // console.log("precision ---------------");
        // console.log(oldColumn.precision !== newColumn.precision);
        // console.log(oldColumn.precision, newColumn.precision);
        // console.log("scale ---------------");
        // console.log(oldColumn.scale !== newColumn.scale);
        // console.log(oldColumn.scale, newColumn.scale);
        // console.log("default ---------------");
        // console.log((checkDefault && oldColumn.default !== newColumn.default));
        // console.log(oldColumn.default, newColumn.default);
        // console.log("isNullable ---------------");
        // console.log(oldColumn.isNullable !== newColumn.isNullable);
        // console.log(oldColumn.isNullable, newColumn.isNullable);
        // console.log("comment ---------------");
        // console.log((checkComment && oldColumn.comment !== newColumn.comment));
        // console.log(oldColumn.comment, newColumn.comment);
        // console.log("enum ---------------");
        // console.log(oldColumn.enum !== newColumn.enum);
        // console.log(oldColumn.enum, newColumn.enum);
        return oldColumn.charset !== newColumn.charset
            || oldColumn.collation !== newColumn.collation
            || oldColumn.precision !== newColumn.precision
            || oldColumn.scale !== newColumn.scale
            || (checkDefault && oldColumn.default !== newColumn.default)
            || oldColumn.isNullable !== newColumn.isNullable
            || (checkComment && oldColumn.comment !== newColumn.comment)
            || oldColumn.enum !== newColumn.enum;
    };
    /**
     * Executes sql used special for schema build.
     */
    BaseQueryRunner.prototype.executeQueries = function (upQueries, downQueries) {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            var _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (typeof upQueries === "string")
                            upQueries = [upQueries];
                        if (typeof downQueries === "string")
                            downQueries = [downQueries];
                        (_a = this.sqlInMemory.upQueries).push.apply(_a, upQueries);
                        (_b = this.sqlInMemory.downQueries).push.apply(_b, downQueries);
                        // if sql-in-memory mode is enabled then simply store sql in memory and return
                        if (this.sqlMemoryMode === true)
                            return [2 /*return*/, Promise.resolve()];
                        return [4 /*yield*/, PromiseUtils.runInSequence(upQueries, function (upQuery) { return _this.query(upQuery); })];
                    case 1:
                        _c.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    return BaseQueryRunner;
}());
export { BaseQueryRunner };

//# sourceMappingURL=BaseQueryRunner.js.map
