"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BetterSqlite3QueryRunner = void 0;
const QueryRunnerAlreadyReleasedError_1 = require("../../error/QueryRunnerAlreadyReleasedError");
const QueryFailedError_1 = require("../../error/QueryFailedError");
const AbstractSqliteQueryRunner_1 = require("../sqlite-abstract/AbstractSqliteQueryRunner");
const Broadcaster_1 = require("../../subscriber/Broadcaster");
const QueryResult_1 = require("../../query-runner/QueryResult");
const BroadcasterResult_1 = require("../../subscriber/BroadcasterResult");
/**
 * 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.
 */
class BetterSqlite3QueryRunner extends AbstractSqliteQueryRunner_1.AbstractSqliteQueryRunner {
    // -------------------------------------------------------------------------
    // Constructor
    // -------------------------------------------------------------------------
    constructor(driver) {
        super();
        this.stmtCache = new Map();
        this.driver = driver;
        this.connection = driver.connection;
        this.broadcaster = new Broadcaster_1.Broadcaster(this);
        if (typeof this.driver.options.statementCacheSize === "number") {
            this.cacheSize = this.driver.options.statementCacheSize;
        }
        else {
            this.cacheSize = 100;
        }
    }
    async getStmt(query) {
        if (this.cacheSize > 0) {
            let stmt = this.stmtCache.get(query);
            if (!stmt) {
                const databaseConnection = await this.connect();
                stmt = databaseConnection.prepare(query);
                this.stmtCache.set(query, stmt);
                while (this.stmtCache.size > this.cacheSize) {
                    // since es6 map keeps the insertion order,
                    // it comes to be FIFO cache
                    const key = this.stmtCache.keys().next().value;
                    this.stmtCache.delete(key);
                }
            }
            return stmt;
        }
        else {
            const databaseConnection = await this.connect();
            return databaseConnection.prepare(query);
        }
    }
    /**
     * Called before migrations are run.
     */
    async beforeMigration() {
        const databaseConnection = await this.connect();
        databaseConnection.pragma("foreign_keys = OFF");
    }
    /**
     * Called after migrations are run.
     */
    async afterMigration() {
        const databaseConnection = await this.connect();
        databaseConnection.pragma("foreign_keys = ON");
    }
    /**
     * Executes a given SQL query.
     */
    async query(query, parameters = [], useStructuredResult = false) {
        if (this.isReleased)
            throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
        const connection = this.driver.connection;
        const broadcasterResult = new BroadcasterResult_1.BroadcasterResult();
        this.driver.connection.logger.logQuery(query, parameters, this);
        this.broadcaster.broadcastBeforeQueryEvent(broadcasterResult, query, parameters);
        const queryStartTime = Date.now();
        const stmt = await this.getStmt(query);
        try {
            const result = new QueryResult_1.QueryResult();
            if (stmt.reader) {
                const raw = stmt.all(...parameters);
                result.raw = raw;
                if (Array.isArray(raw)) {
                    result.records = raw;
                }
            }
            else {
                const raw = stmt.run(...parameters);
                result.affected = raw.changes;
                result.raw = raw.lastInsertRowid;
            }
            // log slow queries if maxQueryExecution time is set
            const maxQueryExecutionTime = this.driver.options.maxQueryExecutionTime;
            const queryEndTime = Date.now();
            const queryExecutionTime = queryEndTime - queryStartTime;
            if (maxQueryExecutionTime &&
                queryExecutionTime > maxQueryExecutionTime)
                connection.logger.logQuerySlow(queryExecutionTime, query, parameters, this);
            this.broadcaster.broadcastAfterQueryEvent(broadcasterResult, query, parameters, true, queryExecutionTime, result.raw, undefined);
            if (!useStructuredResult) {
                return result.raw;
            }
            return result;
        }
        catch (err) {
            connection.logger.logQueryError(err, query, parameters, this);
            throw new QueryFailedError_1.QueryFailedError(query, parameters, err);
        }
    }
    // -------------------------------------------------------------------------
    // Protected Methods
    // -------------------------------------------------------------------------
    async loadTableRecords(tablePath, tableOrIndex) {
        const [database, tableName] = this.splitTablePath(tablePath);
        const res = await this.query(`SELECT ${database ? `'${database}'` : null} as database, * FROM ${this.escapePath(`${database ? `${database}.` : ""}sqlite_master`)} WHERE "type" = '${tableOrIndex}' AND "${tableOrIndex === "table" ? "name" : "tbl_name"}" IN ('${tableName}')`);
        return res;
    }
    async loadPragmaRecords(tablePath, pragma) {
        const [database, tableName] = this.splitTablePath(tablePath);
        const databaseConnection = await this.connect();
        const res = databaseConnection.pragma(`${database ? `"${database}".` : ""}${pragma}("${tableName}")`);
        return res;
    }
}
exports.BetterSqlite3QueryRunner = BetterSqlite3QueryRunner;

//# sourceMappingURL=BetterSqlite3QueryRunner.js.map
