UNPKG

sqlite3orm

Version:

ORM for sqlite3 and TypeScript/JavaScript

128 lines 3.93 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SqlConnectionPoolDatabase = void 0; const tslib_1 = require("tslib"); const _dbg = tslib_1.__importStar(require("debug")); const sqlite3_1 = require("sqlite3"); const SqlDatabase_1 = require("./SqlDatabase"); const debug = _dbg.default('sqlite3orm:database'); class SqlConnectionPoolDatabase extends SqlDatabase_1.SqlDatabase { pool; close() { if (this.pool) { return this.pool.release(this); } else { return super.close(); } } async open(databaseFile, mode, settings) { /* istanbul ignore else */ if (this.isOpen()) { /* istanbul ignore else */ if (this.pool) { // stealing from pool // this connection should not be recycled by the pool // => temporary mark as dirty const oldDirty = this.dirty; this.dirty = true; await this.pool.release(this); this.dirty = oldDirty; } else { await super.close(); } } this.pool = undefined; return super.open(databaseFile, mode, settings); } /* @internal */ openByPool(pool, databaseFile, mode, settings) { return new Promise((resolve, reject) => { const db = new sqlite3_1.Database(databaseFile, mode || SqlDatabase_1.SQL_OPEN_DEFAULT, (err) => { if (err) { reject(err); } else { this.pool = pool; this.db = db; this.dbId = SqlDatabase_1.SqlDatabase.lastId++; this.databaseFile = databaseFile; debug(`${this.dbId}: opened`); resolve(); } }); }).then(() => { if (settings) { return this.applySettings(settings); } return Promise.resolve(); }); } /* @internal */ closeByPool() { this.pool = undefined; return new Promise((resolve, reject) => { /* istanbul ignore if */ if (!this.db) { resolve(); } else { const db = this.db; debug(`${this.dbId}: close`); this.db = undefined; this.dbId = undefined; this.databaseFile = undefined; db.close((err) => { db.removeAllListeners(); /* istanbul ignore if */ if (err) { reject(err); } else { resolve(); } }); } }); } /* @internal */ async recycleByPool(pool, sqldb, settings) { /* istanbul ignore else */ if (sqldb.db) { try { await sqldb.endTransaction(false); } catch (err) { /* empty */ } sqldb.db.removeAllListeners(); // move this.db = sqldb.db; this.dbId = sqldb.dbId; this.databaseFile = sqldb.databaseFile; this.pool = pool; // reapply default settings if (settings) { try { await this.applySettings(settings); } catch (err) { /* empty */ } } } sqldb.db = undefined; sqldb.dbId = undefined; sqldb.databaseFile = undefined; sqldb.pool = undefined; } } exports.SqlConnectionPoolDatabase = SqlConnectionPoolDatabase; //# sourceMappingURL=SqlConnectionPoolDatabase.js.map