You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
1.2 KiB
64 lines
1.2 KiB
3 years ago
|
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));
|
||
|
}
|
||
|
}
|