import { TransactionManager } from "./transaction_manager.mjs"; export class Database { constructor(dbName, adapter) { this.dbName = dbName; this.adapter = adapter; this.version = null; this.path = null; this.transactionManager = new TransactionManager(dbName, this.adapter); } async open() { let response = await this.adapter.open(this.dbName); if (response) { if (response.hasOwnProperty('version')) { this.version = response.version; } if (response.hasOwnProperty('path')) { this.path = response.path; } } // Allow chaining return this; } close() { return this.adapter.close(this.dbName); } transaction() { return this.transactionManager.transaction(); } async autoTransaction(cb, inheritTx) { let tx = inheritTx || this.transaction(); let result; try { result = await cb(tx); } catch (e) { if (!inheritTx) { await tx.rollback(); } throw e; } if (!inheritTx) { await tx.commit(); } return result; } // Helper method to start a transaction and execute a single SQL statement sql(sql, ...args) { return this.autoTransaction((tx) => tx.sql(sql, ...args)); } }