@electric-sql/drivers
Version:
ElectricSQL database drivers.
70 lines • 2.23 kB
JavaScript
import SQLiteAsyncESMFactory from "wa-sqlite/dist/wa-sqlite-async.mjs";
import * as SQLite from "wa-sqlite";
import { IDBBatchAtomicVFS } from "wa-sqlite/src/examples/IDBBatchAtomicVFS.js";
import { Mutex } from "async-mutex";
import { resultToRows } from "../util/results.js";
class ElectricDatabase {
// Do not use this constructor directly.
// Create a Database instance using the static `init` method instead.
constructor(name, sqlite3, db) {
this.name = name;
this.sqlite3 = sqlite3;
this.db = db;
this.#mutex = new Mutex();
}
#mutex;
async exec(statement) {
const release = await this.#mutex.acquire();
try {
return await this.execSql(statement);
} finally {
release();
}
}
// Calls to this method must always be coordinated through the mutex
async execSql(statement) {
for await (const stmt of this.sqlite3.statements(this.db, statement.sql)) {
if (typeof statement.args !== "undefined") {
this.sqlite3.bind_collection(
stmt,
statement.args
);
}
const rows = [];
let cols = [];
while (await this.sqlite3.step(stmt) === SQLite.SQLITE_ROW) {
cols = cols.length === 0 ? this.sqlite3.column_names(stmt) : cols;
const row = this.sqlite3.row(stmt);
rows.push(row);
}
const res = {
columns: cols,
values: rows
};
return resultToRows(res);
}
return [];
}
getRowsModified() {
return this.sqlite3.changes(this.db);
}
// Creates and opens a DB backed by an IndexedDB filesystem
static async init(dbName, locateSqliteDist) {
const locateFile = typeof locateSqliteDist === "string" ? (path) => {
return locateSqliteDist + path;
} : locateSqliteDist;
const SQLiteAsyncModule = await SQLiteAsyncESMFactory({ locateFile });
const sqlite3 = SQLite.Factory(SQLiteAsyncModule);
sqlite3.vfs_register(new IDBBatchAtomicVFS(dbName));
const db = await sqlite3.open_v2(
dbName,
SQLite.SQLITE_OPEN_CREATE | SQLite.SQLITE_OPEN_READWRITE,
dbName
);
return new ElectricDatabase(dbName, sqlite3, db);
}
}
export {
ElectricDatabase
};
//# sourceMappingURL=database.js.map