/** * The one entry point that makes a database usable for skr: bind it, run the * versioned migrations (ts_migration/), then install every model's collection * and indexes — before anything opens a transaction, because index DDL inside * a running transaction on the same collection stalls until the deadline. */ import type * as plugins from './plugins.js'; import { connectDb } from './skr.database.js'; import { Account } from './skr.classes.account.js'; import { Transaction } from './skr.classes.transaction.js'; import { JournalEntry } from './skr.classes.journalentry.js'; import { LedgerSequence } from './skr.sequence.js'; import { LedgerPeriod } from './skr.period.js'; import { OposMeta } from './skr.opos.js'; import { runSkrMigrations, SkrMigrationRecord } from '../ts_migration/index.js'; import type { TDatabaseConfig } from './skr.types.js'; /** Every model skr persists; each is initialized once per database. */ const skrModels = [ SkrMigrationRecord, Account, Transaction, JournalEntry, LedgerSequence, LedgerPeriod, OposMeta, ] as const; const preparations = new WeakMap>(); const prepare = async (db: plugins.nosqldb.SmartdataDb): Promise => { // migrations first: they drop what the models no longer declare and refuse // data a declared unique index could not be created over await runSkrMigrations(db); for (const model of skrModels) { await model.ensureInitialized(); } }; /** * Binds skr to the configured database (first call) and prepares it once: * migrations, then every model's collection. A failed preparation is retried * by the next call. */ export const getDb = async (config?: TDatabaseConfig): Promise => { const db = await connectDb(config); let preparation = preparations.get(db); if (!preparation) { preparation = prepare(db); preparations.set(db, preparation); preparation.catch(() => { if (preparations.get(db) === preparation) preparations.delete(db); }); } await preparation; return db; };