"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SqliteQueryRunner = void 0;
var tslib_1 = require("tslib");
var QueryRunnerAlreadyReleasedError_1 = require("../../error/QueryRunnerAlreadyReleasedError");
var QueryFailedError_1 = require("../../error/QueryFailedError");
var AbstractSqliteQueryRunner_1 = require("../sqlite-abstract/AbstractSqliteQueryRunner");
var Broadcaster_1 = require("../../subscriber/Broadcaster");
var ConnectionIsNotSetError_1 = require("../../error/ConnectionIsNotSetError");
var QueryResult_1 = require("../../query-runner/QueryResult");
/**
 * Runs queries on a single sqlite database connection.
 *
 * Does not support compose primary keys with autoincrement field.
 * todo: need to throw exception for this case.
 */
var SqliteQueryRunner = /** @class */ (function (_super) {
    (0, tslib_1.__extends)(SqliteQueryRunner, _super);
    // -------------------------------------------------------------------------
    // Constructor
    // -------------------------------------------------------------------------
    function SqliteQueryRunner(driver) {
        var _this = _super.call(this) || this;
        _this.driver = driver;
        _this.connection = driver.connection;
        _this.broadcaster = new Broadcaster_1.Broadcaster(_this);
        return _this;
    }
    /**
     * Executes a given SQL query.
     */
    SqliteQueryRunner.prototype.query = function (query, parameters, useStructuredResult) {
        var _this = this;
        if (useStructuredResult === void 0) { useStructuredResult = false; }
        if (this.isReleased)
            throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
        var connection = this.driver.connection;
        var options = connection.options;
        var maxQueryExecutionTime = this.driver.options.maxQueryExecutionTime;
        if (!connection.isConnected) {
            throw new ConnectionIsNotSetError_1.ConnectionIsNotSetError('sqlite');
        }
        return new Promise(function (ok, fail) { return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
            var databaseConnection, queryStartTime, isInsertQuery, isDeleteQuery, isUpdateQuery, execute, handler;
            var _this = this;
            return (0, tslib_1.__generator)(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.connect()];
                    case 1:
                        databaseConnection = _a.sent();
                        this.driver.connection.logger.logQuery(query, parameters, this);
                        queryStartTime = +new Date();
                        isInsertQuery = query.startsWith("INSERT ");
                        isDeleteQuery = query.startsWith("DELETE ");
                        isUpdateQuery = query.startsWith("UPDATE ");
                        execute = function () { return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {
                            return (0, tslib_1.__generator)(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        if (!(isInsertQuery || isDeleteQuery || isUpdateQuery)) return [3 /*break*/, 2];
                                        return [4 /*yield*/, databaseConnection.run(query, parameters, handler)];
                                    case 1:
                                        _a.sent();
                                        return [3 /*break*/, 4];
                                    case 2: return [4 /*yield*/, databaseConnection.all(query, parameters, handler)];
                                    case 3:
                                        _a.sent();
                                        _a.label = 4;
                                    case 4: return [2 /*return*/];
                                }
                            });
                        }); };
                        handler = function (err, rows) {
                            if (err && err.toString().indexOf("SQLITE_BUSY:") !== -1) {
                                if (typeof options.busyErrorRetry === "number" && options.busyErrorRetry > 0) {
                                    setTimeout(execute, options.busyErrorRetry);
                                    return;
                                }
                            }
                            // log slow queries if maxQueryExecution time is set
                            var queryEndTime = +new Date();
                            var queryExecutionTime = queryEndTime - queryStartTime;
                            if (maxQueryExecutionTime && queryExecutionTime > maxQueryExecutionTime)
                                connection.logger.logQuerySlow(queryExecutionTime, query, parameters, this);
                            if (err) {
                                connection.logger.logQueryError(err, query, parameters, this);
                                fail(new QueryFailedError_1.QueryFailedError(query, parameters, err));
                            }
                            else {
                                var result = new QueryResult_1.QueryResult();
                                if (isInsertQuery) {
                                    result.raw = this["lastID"];
                                }
                                else {
                                    result.raw = rows;
                                }
                                if (Array.isArray(rows)) {
                                    result.records = rows;
                                }
                                result.affected = this["changes"];
                                if (useStructuredResult) {
                                    ok(result);
                                }
                                else {
                                    ok(result.raw);
                                }
                            }
                        };
                        return [4 /*yield*/, execute()];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        }); });
    };
    return SqliteQueryRunner;
}(AbstractSqliteQueryRunner_1.AbstractSqliteQueryRunner));
exports.SqliteQueryRunner = SqliteQueryRunner;

//# sourceMappingURL=SqliteQueryRunner.js.map
