"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BetterSqlite3QueryRunner = void 0;
const QueryFailedError_1 = require("../../error/QueryFailedError");
const QueryRunnerAlreadyReleasedError_1 = require("../../error/QueryRunnerAlreadyReleasedError");
const QueryResult_1 = require("../../query-runner/QueryResult");
const Broadcaster_1 = require("../../subscriber/Broadcaster");
const BroadcasterResult_1 = require("../../subscriber/BroadcasterResult");
const AbstractSqliteQueryRunner_1 = require("../sqlite-abstract/AbstractSqliteQueryRunner");
/**
 * 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.dataSource = driver.dataSource;
        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.
     * @param query
     * @param parameters
     * @param useStructuredResult
     */
    async query(query, parameters = [], useStructuredResult = false) {
        if (this.isReleased)
            throw new QueryRunnerAlreadyReleasedError_1.QueryRunnerAlreadyReleasedError();
        const dataSource = this.driver.dataSource;
        // better-sqlite3 cannot bind booleans, convert to 0/1
        const normalizedParameters = parameters.map((p) => typeof p === "boolean" ? (p ? 1 : 0) : p);
        const broadcasterResult = new BroadcasterResult_1.BroadcasterResult();
        this.driver.dataSource.logger.logQuery(query, normalizedParameters, this);
        this.broadcaster.broadcastBeforeQueryEvent(broadcasterResult, query, normalizedParameters);
        const queryStartTime = Date.now();
        const stmt = await this.getStmt(query);
        try {
            const result = new QueryResult_1.QueryResult();
            if (stmt.reader) {
                const raw = stmt.all(...normalizedParameters);
                result.raw = raw;
                if (Array.isArray(raw)) {
                    result.records = raw;
                }
            }
            else {
                const raw = stmt.run(...normalizedParameters);
                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)
                dataSource.logger.logQuerySlow(queryExecutionTime, query, normalizedParameters, this);
            this.broadcaster.broadcastAfterQueryEvent(broadcasterResult, query, normalizedParameters, true, queryExecutionTime, result.raw, undefined);
            if (!useStructuredResult) {
                return result.raw;
            }
            return result;
        }
        catch (err) {
            dataSource.logger.logQueryError(err, query, normalizedParameters, this);
            throw new QueryFailedError_1.QueryFailedError(query, normalizedParameters, err);
        }
    }
    // -------------------------------------------------------------------------
    // Protected Methods
    // -------------------------------------------------------------------------
    async loadTableRecords(tablePath, tableOrIndex) {
        const [database, tableName] = this.splitTablePath(tablePath);
        const relativePath = database
            ? this.driver.getAttachedDatabasePathRelativeByHandle(database)
            : undefined;
        const res = await this.query(`SELECT ${relativePath ? `'${relativePath}'` : 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