sqlstack 3.7.1 → 3.7.2-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/cjs/adapters/execSqlite.d.ts +34 -0
  2. package/dist/cjs/adapters/execSqlite.d.ts.map +1 -0
  3. package/dist/cjs/adapters/execSqlite.js +36 -0
  4. package/dist/cjs/adapters/execSqlite.js.map +1 -0
  5. package/dist/cjs/adapters/index.d.ts +2 -0
  6. package/dist/cjs/adapters/index.d.ts.map +1 -1
  7. package/dist/cjs/adapters/index.js +3 -1
  8. package/dist/cjs/adapters/index.js.map +1 -1
  9. package/dist/cjs/core/errors.d.ts +13 -0
  10. package/dist/cjs/core/errors.d.ts.map +1 -1
  11. package/dist/cjs/core/errors.js +18 -1
  12. package/dist/cjs/core/errors.js.map +1 -1
  13. package/dist/cjs/family.d.ts +6 -0
  14. package/dist/cjs/family.d.ts.map +1 -1
  15. package/dist/cjs/family.js +126 -33
  16. package/dist/cjs/family.js.map +1 -1
  17. package/dist/cjs/familyBinding.d.ts +4 -0
  18. package/dist/cjs/familyBinding.d.ts.map +1 -1
  19. package/dist/cjs/familyBinding.js.map +1 -1
  20. package/dist/cjs/index.d.ts +1 -1
  21. package/dist/cjs/index.d.ts.map +1 -1
  22. package/dist/cjs/index.js.map +1 -1
  23. package/dist/cjs/registry.d.ts +26 -0
  24. package/dist/cjs/registry.d.ts.map +1 -1
  25. package/dist/cjs/registry.js.map +1 -1
  26. package/dist/cjs/stack.d.ts.map +1 -1
  27. package/dist/cjs/stack.js +29 -4
  28. package/dist/cjs/stack.js.map +1 -1
  29. package/dist/cjs/transactions.d.ts +66 -0
  30. package/dist/cjs/transactions.d.ts.map +1 -1
  31. package/dist/cjs/transactions.js +237 -40
  32. package/dist/cjs/transactions.js.map +1 -1
  33. package/dist/esm/adapters/execSqlite.js +33 -0
  34. package/dist/esm/adapters/execSqlite.js.map +1 -0
  35. package/dist/esm/adapters/index.js +1 -0
  36. package/dist/esm/adapters/index.js.map +1 -1
  37. package/dist/esm/core/errors.js +16 -0
  38. package/dist/esm/core/errors.js.map +1 -1
  39. package/dist/esm/family.js +127 -34
  40. package/dist/esm/family.js.map +1 -1
  41. package/dist/esm/familyBinding.js.map +1 -1
  42. package/dist/esm/index.js.map +1 -1
  43. package/dist/esm/registry.js.map +1 -1
  44. package/dist/esm/stack.js +29 -4
  45. package/dist/esm/stack.js.map +1 -1
  46. package/dist/esm/transactions.js +237 -40
  47. package/dist/esm/transactions.js.map +1 -1
  48. package/package.json +1 -1
  49. package/readme.md +33 -0
@@ -1 +1 @@
1
- {"version":3,"file":"transactions.js","sourceRoot":"","sources":["../../src/transactions.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AA+QA,gDAOC;AAOD,sDAEC;AAGD,sDAKC;AAED,0CAkBC;AA0ED,gDAKC;AAkLD,oDAaC;AAUD,sEAeC;AA6SD,oDAGC;AASD,0EAOC;AAl6BD,uDAAqD;AAErD,yCAAuD;AACvD,0CAAwE;AAExE,uCAA0D;AA6B1D,MAAM,GAAG,GAAG,IAAI,oCAAiB,EAAW,CAAC;AAE7C,SAAS,QAAQ;IACf,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;AACxB,CAAC;AAED,SAAS,gBAAgB;IACvB,MAAM,QAAQ,GAAG,QAAQ,EAAE,CAAC;IAC5B,IAAI,QAAQ;QAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;IACvD,OAAO,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;AACvD,CAAC;AAED,SAAS,0BAA0B,CAAC,GAAY;IAC9C,OAAO,GAAG,YAAY,iCAAwB,CAAC;AACjD,CAAC;AAED,SAAS,mBAAmB,CAAC,GAA6B;IACxD,OAAO,OAAO,GAAG,CAAC,KAAK,KAAK,WAAW,CAAC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AAK,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,CAAC;IAChE,CAAC,CAAC;AACJ,CAAC;AAMD,SAAgB,oBAAoB,CAAC,KAAoB;IACvD,MAAM,KAAK,GAAG,QAAQ,EAAE,CAAC;IACzB,OAAO,KAAK,EAAE,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AAClC,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,+BAA+B,CAAC,EAAU;IACxD,MAAM,KAAK,GAAG,QAAQ,EAAE,CAAC;IACzB,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC;QAC1C,IAAI,KAAK,CAAC,EAAE,KAAK,EAAE;YAAE,OAAO,KAAK,CAAC;IACpC,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Database, QueryResult } from './registry';\nimport { createPgDb, createMysqlDb } from './adapters';\nimport { RollbackTransactionError, SqlStackError } from './core/errors';\nimport type { DatabaseEntry } from './stack';\nimport { resolveExecution, legacyEntry } from './runtime';\n\nexport type TransactionOptions = {\n db?: string;\n lazy?: boolean;\n nested?: 'join';\n};\n\n/** Work registered with transaction.afterCommit / transaction.afterSettled. */\nexport type TransactionHook = () => unknown;\n\n/** Observable transaction events (see onTransactionEvent). */\nexport type TransactionEvent = {\n readonly type: 'sqlstack.transaction.multi_database';\n /** Names of the databases the scope has opened, in open order. */\n readonly databases: readonly string[];\n};\n\nexport type TransactionEventListener = (event: TransactionEvent) => void;\n\n// Keyed by concrete DatabaseEntry identity (owning stack + registration), so\n// two roots transacting on the same name (\"primary\") can never collide\n// (spec 16 §20, spec 17 §14). `scope` is the innermost @transaction scope of\n// this flow; the map is shared by every scope of one flow.\ntype TxStore = {\n txByDb: Map<DatabaseEntry, TxState>;\n scope?: TxScope;\n};\n\nconst als = new AsyncLocalStorage<TxStore>();\n\nfunction getStore(): TxStore | undefined {\n return als.getStore();\n}\n\nfunction getOrCreateStore(): { store: TxStore; isNew: boolean } {\n const existing = getStore();\n if (existing) return { store: existing, isNew: false };\n return { store: { txByDb: new Map() }, isNew: true };\n}\n\nfunction isRollbackTransactionError(err: unknown): err is RollbackTransactionError {\n return err instanceof RollbackTransactionError;\n}\n\nfunction unwrapRollbackCause(err: RollbackTransactionError): unknown {\n return typeof err.cause === 'undefined' ? err : err.cause;\n}\n\nexport class TransactionHandle {\n readonly entry: DatabaseEntry;\n #state: TxState;\n #owned: boolean;\n #finished = false;\n\n constructor(entry: DatabaseEntry, state: TxState, owned: boolean) {\n this.entry = entry;\n this.#state = state;\n this.#owned = owned;\n }\n\n get dbName(): string {\n return this.entry.name;\n }\n\n async ensureStarted() {\n await this.#state.ensureStarted();\n }\n\n rollbackOnly(errorToThrow?: unknown) {\n this.#state.rollbackOnly = true;\n if (typeof errorToThrow !== 'undefined') {\n this.#state.rollbackError = errorToThrow;\n }\n }\n\n async commit() {\n if (!this.#owned) return;\n await this.#state.commitIfStarted();\n }\n\n async rollback() {\n if (!this.#owned) return;\n await this.#state.rollbackIfStarted();\n }\n\n async release() {\n if (!this.#owned) return;\n await this.#state.release();\n }\n\n async finishOnSuccess() {\n if (!this.#owned || this.#finished) return;\n this.#finished = true;\n await this.#state.finishOnSuccess();\n }\n\n async finishOnError(err: unknown) {\n if (!this.#owned || this.#finished) return;\n this.#finished = true;\n await this.#state.finishOnError(err);\n }\n}\n\nclass TxState {\n readonly entry: DatabaseEntry;\n readonly db: Database;\n readonly options: Required<Pick<TransactionOptions, 'lazy'>> & Pick<TransactionOptions, 'nested'>;\n depth = 1;\n started = false;\n completed = false;\n rollbackOnly = false;\n rollbackError: unknown | undefined;\n /** SQLite opening statement: name-based transactions keep plain BEGIN. */\n sqliteBegin: 'BEGIN' | 'BEGIN IMMEDIATE' = 'BEGIN';\n /** Called once when the transaction releases its connection (SQLite queue turn). */\n onRelease: (() => void) | undefined;\n\n private txDb: Database | undefined;\n private releaseFn: (() => Promise<void>) | undefined;\n\n constructor(entry: DatabaseEntry, options: TransactionOptions | undefined) {\n this.entry = entry;\n this.db = entry.db;\n this.options = {\n lazy: options?.lazy ?? true,\n nested: options?.nested ?? 'join',\n };\n }\n\n get activeDb(): Database {\n return this.txDb ?? this.db;\n }\n\n async ensureStarted() {\n if (this.started) return;\n\n const dialect = this.db.dialect ?? 'sqlite';\n if (dialect === 'postgres') {\n const pool: any = this.db.conn;\n if (!pool || typeof pool.connect !== 'function') {\n throw new SqlStackError('Postgres transactions require a pg Pool with .connect() as Database.conn');\n }\n const client = await pool.connect();\n this.txDb = createPgDb(client);\n this.releaseFn = async () => {\n if (typeof client.release === 'function') client.release();\n };\n await this.txDb.query('BEGIN', []);\n this.started = true;\n return;\n }\n\n if (dialect === 'mysql') {\n const pool: any = this.db.conn;\n if (!pool || typeof pool.getConnection !== 'function') {\n throw new SqlStackError('MySQL transactions require a mysql2 Pool with .getConnection() as Database.conn');\n }\n const conn = await pool.getConnection();\n this.txDb = createMysqlDb(conn);\n this.releaseFn = async () => {\n if (typeof conn.release === 'function') conn.release();\n };\n await this.txDb.query('START TRANSACTION', []);\n this.started = true;\n return;\n }\n\n // sqlite: existing connection is already bound, unless the adapter hands\n // out a per-transaction handle (e.g. sqlego) to keep other flows out.\n if (typeof this.db.transactionHandle === 'function') {\n this.txDb = this.db.transactionHandle();\n }\n await this.activeDb.query(this.sqliteBegin, []);\n this.started = true;\n }\n\n async query(sql: string, params: unknown[]): Promise<QueryResult> {\n await this.ensureStarted();\n return await this.activeDb.query(sql, params);\n }\n\n async commitIfStarted() {\n if (this.completed) return;\n if (!this.started) {\n this.completed = true;\n return;\n }\n await this.activeDb.query('COMMIT', []);\n this.completed = true;\n }\n\n async rollbackIfStarted() {\n if (this.completed) return;\n if (!this.started) {\n this.completed = true;\n return;\n }\n await this.activeDb.query('ROLLBACK', []);\n this.completed = true;\n }\n\n async release() {\n try {\n if (this.releaseFn) await this.releaseFn();\n } finally {\n this.txDb = undefined;\n this.releaseFn = undefined;\n const onRelease = this.onRelease;\n this.onRelease = undefined;\n onRelease?.();\n }\n }\n\n async finishOnSuccess() {\n try {\n if (this.rollbackOnly) {\n await this.rollbackIfStarted();\n if (typeof this.rollbackError !== 'undefined') throw this.rollbackError;\n throw new RollbackTransactionError();\n }\n await this.commitIfStarted();\n } finally {\n await this.release();\n }\n }\n\n async finishOnError(err: unknown) {\n try {\n await this.rollbackIfStarted();\n } finally {\n await this.release();\n }\n if (isRollbackTransactionError(err)) {\n throw unwrapRollbackCause(err);\n }\n throw err;\n }\n}\n\nfunction enterTx(entry: DatabaseEntry, options?: TransactionOptions): { handle: TransactionHandle; store: TxStore; isNewStore: boolean } {\n const { store, isNew } = getOrCreateStore();\n const existing = store.txByDb.get(entry);\n if (existing) {\n existing.depth++;\n return { handle: new TransactionHandle(entry, existing, false), store, isNewStore: isNew };\n }\n const state = new TxState(entry, options);\n store.txByDb.set(entry, state);\n return { handle: new TransactionHandle(entry, state, true), store, isNewStore: isNew };\n}\n\nasync function exitTx(entry: DatabaseEntry, store: TxStore) {\n const state = store.txByDb.get(entry);\n if (!state) return;\n state.depth = Math.max(0, state.depth - 1);\n if (state.depth === 0) {\n store.txByDb.delete(entry);\n }\n}\n\n/**\n * @deprecated Synchronous lookup against the legacy global registry only.\n * Under an active IoC root, use `currentTransactionFor(entry)` with an entry\n * from the root's SqlStack (`stack.getEntry(name)`).\n */\nexport function currentTransaction(db?: string): TransactionHandle | undefined {\n const store = getStore();\n if (!store) return undefined;\n const entry = legacyEntry(db);\n const state = store.txByDb.get(entry);\n if (!state) return undefined;\n return new TransactionHandle(entry, state, false);\n}\n\n/**\n * Whether this async call carries any transaction records. This observation\n * never resolves a database, opens a connection, or consults legacy defaults.\n * It does not choose an owner: use currentTransactionFor(entry) for that.\n */\nexport function hasTransactionContext(): boolean {\n return (getStore()?.txByDb.size ?? 0) > 0;\n}\n\n/** Active transaction handle for a concrete database entry, if any. */\nexport function currentTransactionFor(entry: DatabaseEntry): TransactionHandle | undefined {\n const store = getStore();\n const state = store?.txByDb.get(entry);\n if (!state) return undefined;\n return new TransactionHandle(entry, state, false);\n}\n\nexport async function withTransaction<T>(fn: () => Promise<T>, options?: TransactionOptions): Promise<T> {\n const { entry } = await resolveExecution(options?.db);\n const { handle, store, isNewStore } = enterTx(entry, options);\n\n const run = async () => {\n try {\n const out = await fn();\n await handle.finishOnSuccess();\n return out;\n } catch (err) {\n await handle.finishOnError(err);\n throw err;\n } finally {\n await exitTx(entry, store);\n }\n };\n\n return isNewStore ? await als.run(store, run) : await run();\n}\n\n// ---------------------------------------------------------------------------\n// Scope-based @transaction (docs/transactions.md)\n// ---------------------------------------------------------------------------\n\n/**\n * One @transaction method invocation. The root scope (no parent) owns every\n * transaction opened in the flow and commits/rolls them back at its exit; a\n * nested scope is a piece of its parent, delimited by savepoints.\n */\nclass TxScope {\n readonly parent: TxScope | undefined;\n readonly root: TxScope;\n readonly depth: number;\n closed = false;\n markAll = false;\n readonly marked = new Set<TxState>();\n afterCommit: TransactionHook[] = [];\n afterSettled: TransactionHook[] = [];\n /** Nested scopes: the savepoint this scope holds on each open transaction. */\n readonly savepoints: Array<{ state: TxState; name: string }> = [];\n\n // Root-only bookkeeping.\n /** Transactions opened in this flow, in open order (root commits them). */\n readonly opened: TxState[] = [];\n readonly opening = new Map<DatabaseEntry, Promise<TxState>>();\n /** Databases this root has opened (multi_database event), with their reported names. */\n readonly seen: Array<{ entry: DatabaseEntry; name: string }> = [];\n savepointSeq = 0;\n\n /** Siblings share one savepoint stack; descendants queue on their own parent. */\n private childTail: Promise<void> = Promise.resolve();\n\n constructor(parent: TxScope | undefined) {\n this.parent = parent;\n this.root = parent ? parent.root : this;\n this.depth = parent ? parent.depth + 1 : 1;\n }\n\n get hasMarks(): boolean {\n return this.markAll || this.marked.size > 0;\n }\n\n isMarked(state: TxState): boolean {\n return this.markAll || this.marked.has(state);\n }\n\n reserveChild(): { ready: Promise<void>; release: () => void } {\n const ready = this.childTail;\n let release!: () => void;\n this.childTail = new Promise<void>((resolve) => {\n release = resolve;\n });\n return { ready, release };\n }\n\n async waitForChildren(): Promise<void> {\n let observed: Promise<void>;\n do {\n observed = this.childTail;\n await observed;\n } while (observed !== this.childTail);\n }\n}\n\nconst eventListeners = new Set<TransactionEventListener>();\n\n/**\n * Observe transaction trace events. Today the only event is\n * `sqlstack.transaction.multi_database`, emitted once per root scope the\n * moment it opens its second database. Returns an unsubscribe function.\n * Listener errors are ignored so observation never affects a transaction.\n */\nexport function onTransactionEvent(listener: TransactionEventListener): () => void {\n eventListeners.add(listener);\n return () => {\n eventListeners.delete(listener);\n };\n}\n\nfunction emitTransactionEvent(event: TransactionEvent): void {\n for (const listener of [...eventListeners]) {\n try {\n listener(event);\n } catch {\n // observation must never affect the transaction\n }\n }\n}\n\n/** Innermost scope of this flow that has not exited yet. */\nfunction activeScope(store: TxStore | undefined): TxScope | undefined {\n let scope = store?.scope;\n while (scope && scope.closed) scope = scope.parent;\n return scope;\n}\n\nfunction requireScope(api: string): TxScope {\n const scope = activeScope(getStore());\n if (!scope) {\n throw new SqlStackError(`transaction.${api}() called outside a @transaction method.`);\n }\n return scope;\n}\n\n// SQLite serialisation: one connection carries one transaction at a time, so\n// independent flows opening a scope transaction on the same connection wait\n// for the previous holder to release instead of failing with \"cannot start a\n// transaction within a transaction\". Keyed by the Database object (the\n// connection), which is the entry's database.\nconst sqliteTails = new WeakMap<object, Promise<void>>();\n\nasync function acquireSqliteTurn(db: object): Promise<() => void> {\n const previous = sqliteTails.get(db) ?? Promise.resolve();\n let release!: () => void;\n const mine = new Promise<void>((resolve) => {\n release = resolve;\n });\n sqliteTails.set(\n db,\n previous.then(() => mine)\n );\n await previous;\n let released = false;\n return () => {\n if (released) return;\n released = true;\n release();\n };\n}\n\nasync function issueSavepoint(scope: TxScope, state: TxState): Promise<void> {\n const name = `sqlstack_sp_${scope.depth}_${++scope.root.savepointSeq}`;\n await state.query(`SAVEPOINT ${name}`, []);\n scope.savepoints.push({ state, name });\n}\n\n// A Database handle given to run(db, ...) that a @transaction scope opens a\n// transaction on gets one synthetic entry per handle object, so the scope's\n// TxState is keyed by the handle itself. Never registered anywhere; the name is\n// a label only (excluded from name matching in transaction.rollback(name)).\nconst HANDLE_LABEL = 'handle';\nconst handleEntries = new WeakMap<object, DatabaseEntry>();\nconst syntheticEntries = new WeakSet<DatabaseEntry>();\n\nfunction handleEntryFor(db: object): DatabaseEntry {\n let entry = handleEntries.get(db);\n if (!entry) {\n entry = { name: HANDLE_LABEL, db: db as Database, owned: false, stack: undefined } as unknown as DatabaseEntry;\n handleEntries.set(db, entry);\n syntheticEntries.add(entry);\n }\n return entry;\n}\n\nfunction isHandleEntry(entry: DatabaseEntry): boolean {\n return syntheticEntries.has(entry);\n}\n\n/**\n * Whether a transaction keyed by `other` is the transaction `entry` must join:\n * the same entry, or — when either side was opened through a handle — the\n * same database object (identity). Two registered entries that merely share\n * a Database are left as they were.\n */\nfunction sameTransactionTarget(entry: DatabaseEntry, other: DatabaseEntry): boolean {\n if (entry === other) return true;\n return (isHandleEntry(entry) || isHandleEntry(other)) && entry.db === other.db;\n}\n\nfunction findOpenTransaction(store: TxStore, entry: DatabaseEntry): TxState | undefined {\n const direct = store.txByDb.get(entry);\n if (direct) return direct;\n for (const [key, state] of store.txByDb) {\n if (!state.completed && sameTransactionTarget(entry, key)) return state;\n }\n return undefined;\n}\n\nfunction findPendingOpen(root: TxScope, entry: DatabaseEntry): Promise<TxState> | undefined {\n const direct = root.opening.get(entry);\n if (direct) return direct;\n for (const [key, pending] of root.opening) {\n if (sameTransactionTarget(entry, key)) return pending;\n }\n return undefined;\n}\n\n/** Name reported for `entry` in the multi_database event. */\nfunction reportedName(store: TxStore, entry: DatabaseEntry): string {\n if (!isHandleEntry(entry)) return entry.name;\n // A handle that is the database of a registered entry this flow knows uses that name.\n for (const key of store.txByDb.keys()) {\n if (!isHandleEntry(key) && key.db === entry.db) return key.name;\n }\n return HANDLE_LABEL;\n}\n\nasync function openScopedTransaction(store: TxStore, scope: TxScope, entry: DatabaseEntry): Promise<TxState> {\n const existing = findOpenTransaction(store, entry);\n if (existing) return existing;\n const root = scope.root;\n const pending = findPendingOpen(root, entry);\n if (pending) return await pending;\n\n const open = (async () => {\n const state = new TxState(entry, undefined);\n state.sqliteBegin = 'BEGIN IMMEDIATE';\n const dialect = entry.db.dialect ?? 'sqlite';\n // A flow that already holds this connection must not wait on itself.\n const holdsConnection = root.opened.some((s) => s.db === entry.db && !s.completed);\n if (dialect === 'sqlite' && !holdsConnection) {\n state.onRelease = await acquireSqliteTurn(entry.db);\n }\n try {\n await state.ensureStarted();\n } catch (err) {\n await state.release();\n throw err;\n }\n store.txByDb.set(entry, state);\n root.opened.push(state);\n\n if (!root.seen.some((s) => sameTransactionTarget(entry, s.entry))) {\n root.seen.push({ entry, name: reportedName(store, entry) });\n if (root.seen.length === 2) {\n emitTransactionEvent({\n type: 'sqlstack.transaction.multi_database',\n databases: root.seen.map((s) => s.name),\n });\n }\n }\n\n // First opened inside a nested scope: every enclosing nested scope gets\n // its savepoint right after BEGIN, outermost first.\n const chain: TxScope[] = [];\n for (let s: TxScope | undefined = scope; s && s.parent; s = s.parent) chain.unshift(s);\n for (const s of chain) await issueSavepoint(s, state);\n return state;\n })();\n\n root.opening.set(entry, open);\n try {\n return await open;\n } finally {\n root.opening.delete(entry);\n }\n}\n\n/**\n * @internal The transaction a query on `entry` runs in: the one already open\n * in this flow (including one a handle of the same database opened), or —\n * while a @transaction scope is active — one opened on that entry by the\n * query itself (on first execution, not on resolution). Undefined means \"run\n * on the database directly\".\n */\nexport function getTransactionTarget(entry: DatabaseEntry): ActiveTransaction | undefined {\n const store = getStore();\n const open = store ? findOpenTransaction(store, entry) : undefined;\n if (open) return open;\n const scope = activeScope(store);\n if (!store || !scope) return undefined;\n return {\n async query(sql: string, params: unknown[]): Promise<QueryResult> {\n if (scope.root.closed) return await entry.db.query(sql, params);\n const state = await openScopedTransaction(store, scope, entry);\n return await state.query(sql, params);\n },\n };\n}\n\n/**\n * @internal The transaction a query on a Database handle (run(db, ...)) runs\n * in. A transaction already open in this flow on that exact object is joined\n * (identity; registered or handle-opened). Inside a @transaction scope with\n * none open, the query opens one on the handle on first execution, exactly as\n * the name-resolved path does. Outside any scope the behaviour is unchanged:\n * join by identity or run directly (undefined).\n */\nexport function getTransactionTargetForHandle(db: { query(sql: string, params: unknown[]): Promise<unknown> }): ActiveTransaction | undefined {\n const store = getStore();\n if (!store) return undefined;\n for (const state of store.txByDb.values()) {\n if (state.db === db) return state;\n }\n const scope = activeScope(store);\n if (!scope) return undefined;\n return {\n async query(sql: string, params: unknown[]): Promise<QueryResult> {\n if (scope.root.closed) return (await db.query(sql, params)) as QueryResult;\n const state = await openScopedTransaction(store, scope, handleEntryFor(db));\n return await state.query(sql, params);\n },\n };\n}\n\nfunction dropFromStore(store: TxStore, state: TxState): void {\n if (store.txByDb.get(state.entry) === state) store.txByDb.delete(state.entry);\n}\n\nasync function runHooks(hooks: TransactionHook[]): Promise<{ failed: boolean; error: unknown }> {\n let failed = false;\n let error: unknown;\n for (const hook of hooks) {\n try {\n // Outside every scope: a hook that is itself @transaction opens a fresh one.\n await als.exit(() => hook());\n } catch (err) {\n if (!failed) {\n failed = true;\n error = err;\n }\n }\n }\n return { failed, error };\n}\n\n/** Roll back and release every transaction the root owns. Returns the first failure. */\nasync function rollbackOwned(root: TxScope, store: TxStore): Promise<{ failed: boolean; error: unknown }> {\n let failed = false;\n let error: unknown;\n for (const state of root.opened) {\n try {\n await state.rollbackIfStarted();\n } catch (err) {\n if (!failed) {\n failed = true;\n error = err;\n }\n } finally {\n try {\n await state.release();\n } catch (err) {\n if (!failed) {\n failed = true;\n error = err;\n }\n }\n dropFromStore(store, state);\n }\n }\n root.opened.length = 0;\n return { failed, error };\n}\n\nasync function exitRootOnSuccess(root: TxScope, store: TxStore): Promise<void> {\n // Name-based API compatibility: currentTransaction()?.rollbackOnly(err)\n // rolls everything back and throws, exactly as it does for withTransaction.\n const legacyMarked = root.opened.find((s) => s.rollbackOnly);\n if (legacyMarked) {\n const err = typeof legacyMarked.rollbackError !== 'undefined' ? legacyMarked.rollbackError : new RollbackTransactionError();\n await rollbackOwned(root, store);\n await runHooks(root.afterSettled);\n throw err;\n }\n\n let failed = false;\n let error: unknown;\n for (const state of root.opened) {\n try {\n if (failed || root.isMarked(state)) await state.rollbackIfStarted();\n else await state.commitIfStarted();\n } catch (err) {\n if (!failed) {\n failed = true;\n error = err;\n }\n } finally {\n try {\n await state.release();\n } catch (err) {\n if (!failed) {\n failed = true;\n error = err;\n }\n }\n dropFromStore(store, state);\n }\n }\n root.opened.length = 0;\n\n const commitHooks = !failed && !root.hasMarks ? await runHooks(root.afterCommit) : { failed: false, error: undefined };\n const settledHooks = await runHooks(root.afterSettled);\n if (failed) throw error;\n if (commitHooks.failed) throw commitHooks.error;\n if (settledHooks.failed) throw settledHooks.error;\n}\n\nasync function exitRootOnError(root: TxScope, store: TxStore): Promise<void> {\n await rollbackOwned(root, store);\n await runHooks(root.afterSettled);\n}\n\nasync function exitNestedOnSuccess(scope: TxScope): Promise<void> {\n const parent = scope.parent!;\n try {\n for (const { state, name } of scope.savepoints) {\n if (state.completed) continue;\n if (scope.isMarked(state)) await state.query(`ROLLBACK TO SAVEPOINT ${name}`, []);\n await state.query(`RELEASE SAVEPOINT ${name}`, []);\n }\n if (!scope.hasMarks) parent.afterCommit.push(...scope.afterCommit);\n } finally {\n parent.afterSettled.push(...scope.afterSettled);\n }\n}\n\nasync function exitNestedOnError(scope: TxScope): Promise<void> {\n for (const { state, name } of scope.savepoints) {\n if (state.completed) continue;\n try {\n await state.query(`ROLLBACK TO SAVEPOINT ${name}`, []);\n await state.query(`RELEASE SAVEPOINT ${name}`, []);\n } catch {\n // the original error wins; the root rolls back everything if it propagates\n }\n }\n scope.parent!.afterSettled.push(...scope.afterSettled);\n}\n\nasync function runInScope<T>(fn: () => Promise<T>): Promise<T> {\n const outer = getStore();\n const parent = activeScope(outer);\n const scope = new TxScope(parent);\n const store: TxStore = { txByDb: outer?.txByDb ?? new Map(), scope };\n // Reserve synchronously, before yielding: a parent must see even queued children.\n const turn = parent?.reserveChild();\n\n try {\n if (turn) await turn.ready;\n return await als.run(store, async () => {\n let out: T;\n try {\n if (parent) {\n // Siblings enter one at a time, so releasing one cannot erase another's savepoint.\n for (const state of scope.root.opened) {\n if (!state.completed) await issueSavepoint(scope, state);\n }\n }\n out = await fn();\n } catch (err) {\n // Promise.all may reject while another child is still writing. Keep this\n // scope active until those children settle, then roll back their work too.\n await scope.waitForChildren();\n scope.closed = true;\n if (parent) {\n await exitNestedOnError(scope);\n throw err;\n }\n await exitRootOnError(scope, store);\n throw isRollbackTransactionError(err) ? unwrapRollbackCause(err) : err;\n }\n await scope.waitForChildren();\n scope.closed = true;\n if (parent) await exitNestedOnSuccess(scope);\n else await exitRootOnSuccess(scope, store);\n return out;\n });\n } finally {\n // Release only after savepoint cleanup and descendants, on success or failure.\n turn?.release();\n }\n}\n\nfunction matchOpenTransaction(scope: TxScope, target: string | object): TxState {\n const open = scope.root.opened.filter((s) => !s.completed);\n const state =\n typeof target === 'string'\n ? open.find((s) => !isHandleEntry(s.entry) && s.entry.name === target)\n : open.find((s) => s.db === target);\n if (!state) {\n throw new SqlStackError(\n typeof target === 'string'\n ? `transaction.rollback(\"${target}\"): no transaction is open on a database named \"${target}\" in this scope.`\n : 'transaction.rollback(db): no transaction is open on that database handle in this scope.'\n );\n }\n return state;\n}\n\n/**\n * Mark the innermost @transaction scope for rollback. Synchronous and\n * non-throwing for the method: SQL after it still runs inside the open\n * transaction; at scope exit the scope rolls back instead of committing and\n * the method's return value still reaches the caller. With a target (a\n * registered database name or a Database handle), only that database's open\n * transaction is marked.\n */\nfunction markRollback(target?: string | object): void {\n const scope = requireScope('rollback');\n if (typeof target === 'undefined') {\n scope.markAll = true;\n return;\n }\n scope.marked.add(matchOpenTransaction(scope, target));\n}\n\n/**\n * Roll back everything the innermost scope has done so far, now. The root\n * scope rolls back and releases its transactions (the next query opens fresh\n * ones); a nested scope rolls back to its savepoints. Marks and the scope's\n * pending afterCommit hooks are cleared; afterSettled hooks stay.\n */\nasync function restartScope(): Promise<void> {\n const scope = requireScope('restart');\n const store = getStore()!;\n if (scope.parent) {\n for (const { state, name } of scope.savepoints) {\n if (state.completed) continue;\n await state.query(`ROLLBACK TO SAVEPOINT ${name}`, []);\n }\n } else {\n const result = await rollbackOwned(scope, store);\n if (result.failed) throw result.error;\n }\n scope.markAll = false;\n scope.marked.clear();\n scope.afterCommit = [];\n}\n\nfunction registerAfterCommit(fn: TransactionHook): void {\n if (typeof fn !== 'function') throw new SqlStackError('transaction.afterCommit(fn) requires a function.');\n requireScope('afterCommit').afterCommit.push(fn);\n}\n\nfunction registerAfterSettled(fn: TransactionHook): void {\n if (typeof fn !== 'function') throw new SqlStackError('transaction.afterSettled(fn) requires a function.');\n requireScope('afterSettled').afterSettled.push(fn);\n}\n\nexport type TransactionDecorator = {\n (target: any, prop: string | symbol, desc: PropertyDescriptor): void;\n (options?: TransactionOptions): (target: any, prop: string | symbol, desc: PropertyDescriptor) => void;\n /**\n * Mark the innermost scope (or, with a database name or handle, only that\n * database's open transaction) for rollback at scope exit. Never throws\n * inside a scope for a valid target; throws SqlStackError outside any\n * scope or when no open transaction matches the target.\n */\n rollback(target?: string | object): void;\n /** Roll back the scope's work now; the next query opens fresh transactions. */\n restart(): Promise<void>;\n /** Run fn after the root scope commits (dropped on rollback). */\n afterCommit(fn: TransactionHook): void;\n /** Run fn after the root scope finishes, committed or not. */\n afterSettled(fn: TransactionHook): void;\n};\n\nconst transactionDecorator = function (...args: any[]) {\n // @transaction\n if (args.length === 3 && typeof args[2]?.value === 'function') {\n const [target, prop, desc] = args as [any, string | symbol, PropertyDescriptor];\n wrapMethod(target, prop, desc, undefined);\n return;\n }\n // @transaction() or @transaction({ ... })\n const options: TransactionOptions | undefined = args.length > 0 ? args[0] : undefined;\n return function (target: any, prop: string | symbol, desc: PropertyDescriptor) {\n wrapMethod(target, prop, desc, options);\n };\n};\n\nexport const transaction: TransactionDecorator = Object.assign(transactionDecorator, {\n rollback: markRollback,\n restart: restartScope,\n afterCommit: registerAfterCommit,\n afterSettled: registerAfterSettled,\n}) as any;\n\n/**\n * A name (`{ db }`) or an eager open (`lazy: false`) keeps the name-based\n * behaviour of withTransaction. Everything else is a scope: no entry is\n * resolved; queries open transactions on first touch.\n */\nfunction isNameBased(options: TransactionOptions | undefined): boolean {\n return typeof options?.db !== 'undefined' || options?.lazy === false;\n}\n\nfunction wrapMethod(_target: any, _prop: string | symbol, desc: PropertyDescriptor, options?: TransactionOptions) {\n const original = desc.value;\n if (isNameBased(options)) {\n desc.value = async function (...callArgs: any[]) {\n return await withTransaction(() => original.apply(this, callArgs), options);\n };\n return;\n }\n desc.value = async function (...callArgs: any[]) {\n return await runInScope(() => original.apply(this, callArgs));\n };\n}\n\nexport type ActiveTransaction = {\n query(sql: string, params: unknown[]): Promise<QueryResult>;\n};\n\nexport function getActiveTransaction(entry: DatabaseEntry): ActiveTransaction | undefined {\n const store = getStore();\n return store?.txByDb.get(entry);\n}\n\n/**\n * Active transaction whose registered database is exactly `db` (object\n * identity), if any. `run(db, ...)` uses this so a handle passed at call time\n * joins a transaction opened on the same database (by `@transaction` or\n * `withTransaction`) instead of bypassing it. A handle that was never\n * registered with a SqlStack (or the legacy registry) never matches.\n */\nexport function getActiveTransactionForDatabase(db: object): ActiveTransaction | undefined {\n const store = getStore();\n if (!store) return undefined;\n for (const state of store.txByDb.values()) {\n if (state.db === db) return state;\n }\n return undefined;\n}\n"]}
1
+ {"version":3,"file":"transactions.js","sourceRoot":"","sources":["../../src/transactions.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAuTA,gDAOC;AAOD,sDAEC;AAGD,sDAKC;AAED,0CAkBC;AAmID,gDAKC;AAmOD,oDAyBC;AA6CD,sEA2BC;AAiUD,oDAGC;AASD,0E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S,CAAC;AACnB,CAAC","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Database, QueryResult } from './registry';\nimport { createPgDb, createMysqlDb } from './adapters';\nimport { RollbackTransactionError, SqlStackError } from './core/errors';\nimport type { DatabaseEntry } from './stack';\nimport { resolveExecution, legacyEntry } from './runtime';\n\nexport type TransactionOptions = {\n db?: string;\n lazy?: boolean;\n nested?: 'join';\n};\n\n/** Work registered with transaction.afterCommit / transaction.afterSettled. */\nexport type TransactionHook = () => unknown;\n\n/** Observable transaction events (see onTransactionEvent). */\nexport type TransactionEvent = {\n readonly type: 'sqlstack.transaction.multi_database';\n /** Names of the databases the scope has opened, in open order. */\n readonly databases: readonly string[];\n};\n\nexport type TransactionEventListener = (event: TransactionEvent) => void;\n\n// Keyed by concrete DatabaseEntry identity (owning stack + registration), so\n// two roots transacting on the same name (\"primary\") can never collide\n// (spec 16 §20, spec 17 §14). `scope` is the innermost @transaction scope of\n// this flow; the map is shared by every scope of one flow.\ntype TxStore = {\n txByDb: Map<DatabaseEntry, TxState>;\n scope?: TxScope;\n};\n\nconst als = new AsyncLocalStorage<TxStore>();\n\nfunction getStore(): TxStore | undefined {\n return als.getStore();\n}\n\nfunction getOrCreateStore(): { store: TxStore; isNew: boolean } {\n const existing = getStore();\n if (existing) return { store: existing, isNew: false };\n return { store: { txByDb: new Map() }, isNew: true };\n}\n\nfunction isRollbackTransactionError(err: unknown): err is RollbackTransactionError {\n return err instanceof RollbackTransactionError;\n}\n\nfunction unwrapRollbackCause(err: RollbackTransactionError): unknown {\n return typeof err.cause === 'undefined' ? err : err.cause;\n}\n\nexport class TransactionHandle {\n readonly entry: DatabaseEntry;\n #state: TxState;\n #owned: boolean;\n #finished = false;\n\n constructor(entry: DatabaseEntry, state: TxState, owned: boolean) {\n this.entry = entry;\n this.#state = state;\n this.#owned = owned;\n }\n\n get dbName(): string {\n return this.entry.name;\n }\n\n async ensureStarted() {\n await this.#state.ensureStarted();\n }\n\n rollbackOnly(errorToThrow?: unknown) {\n this.#state.rollbackOnly = true;\n if (typeof errorToThrow !== 'undefined') {\n this.#state.rollbackError = errorToThrow;\n }\n }\n\n async commit() {\n if (!this.#owned) return;\n await this.#state.commitIfStarted();\n }\n\n async rollback() {\n if (!this.#owned) return;\n await this.#state.rollbackIfStarted();\n }\n\n async release() {\n if (!this.#owned) return;\n await this.#state.release();\n }\n\n async finishOnSuccess() {\n if (!this.#owned || this.#finished) return;\n this.#finished = true;\n await this.#state.finishOnSuccess();\n }\n\n async finishOnError(err: unknown) {\n if (!this.#owned || this.#finished) return;\n this.#finished = true;\n await this.#state.finishOnError(err);\n }\n}\n\nclass TxState {\n readonly entry: DatabaseEntry;\n readonly db: Database;\n readonly options: Required<Pick<TransactionOptions, 'lazy'>> & Pick<TransactionOptions, 'nested'>;\n depth = 1;\n started = false;\n completed = false;\n rollbackOnly = false;\n rollbackError: unknown | undefined;\n /** SQLite opening statement: name-based transactions keep plain BEGIN. */\n sqliteBegin: 'BEGIN' | 'BEGIN IMMEDIATE' = 'BEGIN';\n /** Called once when the transaction releases its connection (SQLite queue turn). */\n onRelease: (() => void) | undefined;\n /** The @transaction root that opened (and will finish) this transaction, if any. */\n ownerRoot: TxScope | undefined;\n\n private txDb: Database | undefined;\n private releaseFn: (() => Promise<void>) | undefined;\n\n constructor(entry: DatabaseEntry, options: TransactionOptions | undefined) {\n this.entry = entry;\n this.db = entry.db;\n this.options = {\n lazy: options?.lazy ?? true,\n nested: options?.nested ?? 'join',\n };\n }\n\n get activeDb(): Database {\n return this.txDb ?? this.db;\n }\n\n async ensureStarted() {\n if (this.started) return;\n\n const dialect = this.db.dialect ?? 'sqlite';\n if (dialect === 'postgres') {\n const pool: any = this.db.conn;\n if (!pool || typeof pool.connect !== 'function') {\n throw new SqlStackError('Postgres transactions require a pg Pool with .connect() as Database.conn');\n }\n const client = await pool.connect();\n this.txDb = createPgDb(client);\n this.releaseFn = async () => {\n if (typeof client.release === 'function') client.release();\n };\n await this.txDb.query('BEGIN', []);\n this.started = true;\n return;\n }\n\n if (dialect === 'mysql') {\n const pool: any = this.db.conn;\n if (!pool || typeof pool.getConnection !== 'function') {\n throw new SqlStackError('MySQL transactions require a mysql2 Pool with .getConnection() as Database.conn');\n }\n const conn = await pool.getConnection();\n this.txDb = createMysqlDb(conn);\n this.releaseFn = async () => {\n if (typeof conn.release === 'function') conn.release();\n };\n await this.txDb.query('START TRANSACTION', []);\n this.started = true;\n return;\n }\n\n // sqlite: existing connection is already bound, unless the adapter hands\n // out a per-transaction handle (e.g. sqlego) to keep other flows out.\n if (typeof this.db.transactionHandle === 'function') {\n this.txDb = this.db.transactionHandle();\n }\n await this.control('begin');\n this.started = true;\n }\n\n /**\n * Send one transaction-control step on the active handle: through its\n * `transactionHooks` when it has them, otherwise as SQL (unchanged path).\n */\n async control(\n op: 'begin' | 'commit' | 'rollback' | 'savepoint' | 'releaseSavepoint' | 'rollbackToSavepoint',\n name?: string\n ): Promise<void> {\n const db = this.activeDb;\n const hooks = db.transactionHooks;\n if (!hooks) {\n const sql =\n op === 'begin' ? this.sqliteBegin\n : op === 'commit' ? 'COMMIT'\n : op === 'rollback' ? 'ROLLBACK'\n : op === 'savepoint' ? `SAVEPOINT ${name}`\n : op === 'releaseSavepoint' ? `RELEASE SAVEPOINT ${name}`\n : `ROLLBACK TO SAVEPOINT ${name}`;\n await db.query(sql, []);\n return;\n }\n if (op === 'begin') return void (await hooks.begin({ immediate: this.sqliteBegin === 'BEGIN IMMEDIATE' }));\n if (op === 'commit') return void (await hooks.commit());\n if (op === 'rollback') return void (await hooks.rollback());\n // Check the whole trio before opening a savepoint: a nested scope must not\n // start if it could not later roll back (or release) its piece.\n const required = op === 'savepoint' ? (['savepoint', 'releaseSavepoint', 'rollbackToSavepoint'] as const) : [op];\n const missing = required.filter((k) => typeof hooks[k] !== 'function');\n if (missing.length > 0) {\n throw new SqlStackError(\n `Nested @transaction scopes need savepoints, but this database's transactionHooks has no ${missing.map((k) => `${k}()`).join(', ')} hook. ` +\n 'Supply savepoint, releaseSavepoint and rollbackToSavepoint, or avoid nesting @transaction methods on this database.'\n );\n }\n const fn = hooks[op]!;\n await fn.call(hooks, name!);\n }\n\n async query(sql: string, params: unknown[]): Promise<QueryResult> {\n await this.ensureStarted();\n return await this.activeDb.query(sql, params);\n }\n\n async commitIfStarted() {\n if (this.completed) return;\n if (!this.started) {\n this.completed = true;\n return;\n }\n await this.control('commit');\n this.completed = true;\n }\n\n async rollbackIfStarted() {\n if (this.completed) return;\n if (!this.started) {\n this.completed = true;\n return;\n }\n await this.control('rollback');\n this.completed = true;\n }\n\n async release() {\n try {\n if (this.releaseFn) await this.releaseFn();\n } finally {\n this.txDb = undefined;\n this.releaseFn = undefined;\n const onRelease = this.onRelease;\n this.onRelease = undefined;\n onRelease?.();\n }\n }\n\n async finishOnSuccess() {\n try {\n if (this.rollbackOnly) {\n await this.rollbackIfStarted();\n if (typeof this.rollbackError !== 'undefined') throw this.rollbackError;\n throw new RollbackTransactionError();\n }\n await this.commitIfStarted();\n } finally {\n await this.release();\n }\n }\n\n async finishOnError(err: unknown) {\n try {\n await this.rollbackIfStarted();\n } finally {\n await this.release();\n }\n if (isRollbackTransactionError(err)) {\n throw unwrapRollbackCause(err);\n }\n throw err;\n }\n}\n\nfunction enterTx(entry: DatabaseEntry, options?: TransactionOptions): { handle: TransactionHandle; store: TxStore; isNewStore: boolean } {\n const { store, isNew } = getOrCreateStore();\n const existing = store.txByDb.get(entry);\n if (existing) {\n existing.depth++;\n return { handle: new TransactionHandle(entry, existing, false), store, isNewStore: isNew };\n }\n const state = new TxState(entry, options);\n store.txByDb.set(entry, state);\n return { handle: new TransactionHandle(entry, state, true), store, isNewStore: isNew };\n}\n\nasync function exitTx(entry: DatabaseEntry, store: TxStore) {\n const state = store.txByDb.get(entry);\n if (!state) return;\n state.depth = Math.max(0, state.depth - 1);\n if (state.depth === 0) {\n store.txByDb.delete(entry);\n }\n}\n\n/**\n * @deprecated Synchronous lookup against the legacy global registry only.\n * Under an active IoC root, use `currentTransactionFor(entry)` with an entry\n * from the root's SqlStack (`stack.getEntry(name)`).\n */\nexport function currentTransaction(db?: string): TransactionHandle | undefined {\n const store = getStore();\n if (!store) return undefined;\n const entry = legacyEntry(db);\n const state = store.txByDb.get(entry);\n if (!state) return undefined;\n return new TransactionHandle(entry, state, false);\n}\n\n/**\n * Whether this async call carries any transaction records. This observation\n * never resolves a database, opens a connection, or consults legacy defaults.\n * It does not choose an owner: use currentTransactionFor(entry) for that.\n */\nexport function hasTransactionContext(): boolean {\n return (getStore()?.txByDb.size ?? 0) > 0;\n}\n\n/** Active transaction handle for a concrete database entry, if any. */\nexport function currentTransactionFor(entry: DatabaseEntry): TransactionHandle | undefined {\n const store = getStore();\n const state = store?.txByDb.get(entry);\n if (!state) return undefined;\n return new TransactionHandle(entry, state, false);\n}\n\nexport async function withTransaction<T>(fn: () => Promise<T>, options?: TransactionOptions): Promise<T> {\n const { entry } = await resolveExecution(options?.db);\n const { handle, store, isNewStore } = enterTx(entry, options);\n\n const run = async () => {\n try {\n const out = await fn();\n await handle.finishOnSuccess();\n return out;\n } catch (err) {\n await handle.finishOnError(err);\n throw err;\n } finally {\n await exitTx(entry, store);\n }\n };\n\n return isNewStore ? await als.run(store, run) : await run();\n}\n\n// ---------------------------------------------------------------------------\n// Scope-based @transaction (docs/transactions.md)\n// ---------------------------------------------------------------------------\n\n/**\n * One @transaction method invocation. The root scope (no parent) owns every\n * transaction opened in the flow and commits/rolls them back at its exit; a\n * nested scope is a piece of its parent, delimited by savepoints.\n */\nclass TxScope {\n readonly parent: TxScope | undefined;\n readonly root: TxScope;\n readonly depth: number;\n closed = false;\n markAll = false;\n readonly marked = new Set<TxState>();\n afterCommit: TransactionHook[] = [];\n afterSettled: TransactionHook[] = [];\n /** Nested scopes: the savepoint this scope holds on each open transaction. */\n readonly savepoints: Array<{ state: TxState; name: string }> = [];\n /**\n * Queries (open + statement) owned by this scope or a descendant that have\n * not settled. Every scope drains its own before it closes: a nested scope\n * before its savepoint cleanup, the root before commit/rollback, so no\n * query publishes or writes after its scope's exit has started.\n */\n readonly inFlight = new Set<Promise<void>>();\n\n // Root-only bookkeeping.\n /** Transactions opened in this flow, in open order (root commits them). */\n readonly opened: TxState[] = [];\n /** Undefined: the root closed while the open was waiting, so it ran nothing. */\n readonly opening = new Map<DatabaseEntry, Promise<TxState | undefined>>();\n /** Databases this root has opened (multi_database event), with their reported names. */\n readonly seen: Array<{ entry: DatabaseEntry; name: string }> = [];\n savepointSeq = 0;\n\n /**\n * Root-only: settles once the root's transactions have been committed or\n * rolled back and released (before its hooks run). A query that arrives\n * after the root closed waits for this instead of joining a transaction\n * that is being torn down.\n */\n readonly tornDown: Promise<void>;\n private resolveTornDown!: () => void;\n\n /** Siblings share one savepoint stack; descendants queue on their own parent. */\n private childTail: Promise<void> = Promise.resolve();\n\n constructor(parent: TxScope | undefined) {\n this.parent = parent;\n this.root = parent ? parent.root : this;\n this.depth = parent ? parent.depth + 1 : 1;\n this.tornDown = new Promise<void>((resolve) => {\n this.resolveTornDown = resolve;\n });\n }\n\n markTornDown(): void {\n this.resolveTornDown();\n }\n\n get hasMarks(): boolean {\n return this.markAll || this.marked.size > 0;\n }\n\n isMarked(state: TxState): boolean {\n return this.markAll || this.marked.has(state);\n }\n\n reserveChild(): { ready: Promise<void>; release: () => void } {\n const ready = this.childTail;\n let release!: () => void;\n this.childTail = new Promise<void>((resolve) => {\n release = resolve;\n });\n return { ready, release };\n }\n\n async waitForChildren(): Promise<void> {\n let observed: Promise<void>;\n do {\n observed = this.childTail;\n await observed;\n } while (observed !== this.childTail);\n }\n}\n\n/**\n * The scope a query issued under `scope` belongs to now: `scope` itself, or\n * its nearest ancestor that has not closed (a query can outlive the nested\n * scope it was issued in). Undefined once the root has closed.\n */\nfunction owningScope(scope: TxScope): TxScope | undefined {\n let s: TxScope | undefined = scope;\n while (s && s.closed) s = s.parent;\n return s;\n}\n\n/**\n * Run one scope query, registered in `inFlight` of `owner` and every ancestor\n * until it settles. Callers pick `owner` with owningScope() and call this with\n * no await in between, so registration and the closed check are one step.\n */\nfunction trackQuery<T>(owner: TxScope, work: () => Promise<T>): Promise<T> {\n const result = work();\n const settled = result.then(\n () => undefined,\n () => undefined\n );\n const scopes: TxScope[] = [];\n for (let s: TxScope | undefined = owner; s; s = s.parent) {\n s.inFlight.add(settled);\n scopes.push(s);\n }\n void settled.then(() => {\n for (const s of scopes) s.inFlight.delete(settled);\n });\n return result;\n}\n\nconst eventListeners = new Set<TransactionEventListener>();\n\n/**\n * Observe transaction trace events. Today the only event is\n * `sqlstack.transaction.multi_database`, emitted once per root scope the\n * moment it opens its second database. Returns an unsubscribe function.\n * Listener errors are ignored so observation never affects a transaction.\n */\nexport function onTransactionEvent(listener: TransactionEventListener): () => void {\n eventListeners.add(listener);\n return () => {\n eventListeners.delete(listener);\n };\n}\n\nfunction emitTransactionEvent(event: TransactionEvent): void {\n for (const listener of [...eventListeners]) {\n try {\n listener(event);\n } catch {\n // observation must never affect the transaction\n }\n }\n}\n\n/** Innermost scope of this flow that has not exited yet. */\nfunction activeScope(store: TxStore | undefined): TxScope | undefined {\n let scope = store?.scope;\n while (scope && scope.closed) scope = scope.parent;\n return scope;\n}\n\nfunction requireScope(api: string): TxScope {\n const scope = activeScope(getStore());\n if (!scope) {\n throw new SqlStackError(`transaction.${api}() called outside a @transaction method.`);\n }\n return scope;\n}\n\n// SQLite serialisation: one connection carries one transaction at a time, so\n// independent flows opening a scope transaction on the same connection wait\n// for the previous holder to release instead of failing with \"cannot start a\n// transaction within a transaction\". Keyed by the Database object (the\n// connection), which is the entry's database.\nconst sqliteTails = new WeakMap<object, Promise<void>>();\n\nasync function acquireSqliteTurn(db: object): Promise<() => void> {\n const previous = sqliteTails.get(db) ?? Promise.resolve();\n let release!: () => void;\n const mine = new Promise<void>((resolve) => {\n release = resolve;\n });\n sqliteTails.set(\n db,\n previous.then(() => mine)\n );\n await previous;\n let released = false;\n return () => {\n if (released) return;\n released = true;\n release();\n };\n}\n\nasync function issueSavepoint(scope: TxScope, state: TxState): Promise<void> {\n const name = `sqlstack_sp_${scope.depth}_${++scope.root.savepointSeq}`;\n await state.ensureStarted();\n await state.control('savepoint', name);\n scope.savepoints.push({ state, name });\n}\n\n// A Database handle given to run(db, ...) that a @transaction scope opens a\n// transaction on gets one synthetic entry per handle object, so the scope's\n// TxState is keyed by the handle itself. Never registered anywhere; the name is\n// a label only (excluded from name matching in transaction.rollback(name)).\nconst HANDLE_LABEL = 'handle';\nconst handleEntries = new WeakMap<object, DatabaseEntry>();\nconst syntheticEntries = new WeakSet<DatabaseEntry>();\n\nfunction handleEntryFor(db: object): DatabaseEntry {\n let entry = handleEntries.get(db);\n if (!entry) {\n entry = { name: HANDLE_LABEL, db: db as Database, owned: false, stack: undefined } as unknown as DatabaseEntry;\n handleEntries.set(db, entry);\n syntheticEntries.add(entry);\n }\n return entry;\n}\n\nfunction isHandleEntry(entry: DatabaseEntry): boolean {\n return syntheticEntries.has(entry);\n}\n\n/**\n * Whether a transaction keyed by `other` is the transaction `entry` must join:\n * the same entry, or — when either side was opened through a handle — the\n * same database object (identity). Two registered entries that merely share\n * a Database are left as they were.\n */\nfunction sameTransactionTarget(entry: DatabaseEntry, other: DatabaseEntry): boolean {\n if (entry === other) return true;\n return (isHandleEntry(entry) || isHandleEntry(other)) && entry.db === other.db;\n}\n\nfunction findOpenTransaction(store: TxStore, entry: DatabaseEntry): TxState | undefined {\n const direct = store.txByDb.get(entry);\n if (direct) return direct;\n for (const [key, state] of store.txByDb) {\n if (!state.completed && sameTransactionTarget(entry, key)) return state;\n }\n return undefined;\n}\n\nfunction findPendingOpen(root: TxScope, entry: DatabaseEntry): Promise<TxState | undefined> | undefined {\n const direct = root.opening.get(entry);\n if (direct) return direct;\n for (const [key, pending] of root.opening) {\n if (sameTransactionTarget(entry, key)) return pending;\n }\n return undefined;\n}\n\n/** Name reported for `entry` in the multi_database event. */\nfunction reportedName(store: TxStore, entry: DatabaseEntry): string {\n if (!isHandleEntry(entry)) return entry.name;\n // A handle that is the database of a registered entry this flow knows uses that name.\n for (const key of store.txByDb.keys()) {\n if (!isHandleEntry(key) && key.db === entry.db) return key.name;\n }\n return HANDLE_LABEL;\n}\n\n/**\n * Undefined when the root closed while this open was waiting: nothing was left\n * open, and the caller runs the statement on the database directly.\n */\nasync function openScopedTransaction(store: TxStore, scope: TxScope, entry: DatabaseEntry): Promise<TxState | undefined> {\n const existing = findOpenTransaction(store, entry);\n if (existing) return existing;\n const root = scope.root;\n const pending = findPendingOpen(root, entry);\n if (pending) return await pending;\n\n const open = (async () => {\n const state = new TxState(entry, undefined);\n state.sqliteBegin = 'BEGIN IMMEDIATE';\n const dialect = entry.db.dialect ?? 'sqlite';\n // A flow that already holds this connection must not wait on itself.\n const holdsConnection = root.opened.some((s) => s.db === entry.db && !s.completed);\n if (dialect === 'sqlite' && !holdsConnection) {\n state.onRelease = await acquireSqliteTurn(entry.db);\n }\n // Backstop: the root drains in-flight queries before closing, so this\n // should not happen; if it does, hand the turn straight back.\n if (root.closed) {\n await state.release();\n return undefined;\n }\n try {\n await state.ensureStarted();\n } catch (err) {\n await state.release();\n throw err;\n }\n\n // First opened inside a nested scope: every enclosing nested scope gets\n // its savepoint right after BEGIN, outermost first. The transaction is\n // published (txByDb / root.opened) only once they all exist: until then a\n // concurrent query finds the pending open in root.opening and awaits it\n // (receiving its rejection), so it can never run in — or after the\n // teardown of — a transaction that lacks its savepoints.\n const chain: TxScope[] = [];\n for (let s: TxScope | undefined = scope; s && s.parent; s = s.parent) chain.unshift(s);\n try {\n for (const s of chain) await issueSavepoint(s, state);\n } catch (err) {\n for (const s of chain) {\n for (let j = s.savepoints.length - 1; j >= 0; j--) if (s.savepoints[j]!.state === state) s.savepoints.splice(j, 1);\n }\n try {\n await state.rollbackIfStarted();\n } catch {\n // the savepoint failure wins\n } finally {\n await state.release();\n }\n throw err;\n }\n\n // Backstop: started, but the root has already committed/rolled back and\n // nobody would ever finish it. Roll it back and release it now. No await\n // between this check and the publish below.\n if (root.closed) {\n for (const s of chain) {\n for (let j = s.savepoints.length - 1; j >= 0; j--) if (s.savepoints[j]!.state === state) s.savepoints.splice(j, 1);\n }\n try {\n await state.rollbackIfStarted();\n } finally {\n await state.release();\n }\n return undefined;\n }\n\n state.ownerRoot = root;\n store.txByDb.set(entry, state);\n root.opened.push(state);\n\n if (!root.seen.some((s) => sameTransactionTarget(entry, s.entry))) {\n root.seen.push({ entry, name: reportedName(store, entry) });\n if (root.seen.length === 2) {\n emitTransactionEvent({\n type: 'sqlstack.transaction.multi_database',\n databases: root.seen.map((s) => s.name),\n });\n }\n }\n return state;\n })();\n\n root.opening.set(entry, open);\n try {\n return await open;\n } finally {\n root.opening.delete(entry);\n }\n}\n\n/**\n * @internal The transaction a query on `entry` runs in: the one already open\n * in this flow (including one a handle of the same database opened), or —\n * while a @transaction scope is active — one opened on that entry by the\n * query itself (on first execution, not on resolution). Undefined means \"run\n * on the database directly\".\n *\n * Inside a scope every query — on a transaction already open or one it opens —\n * is tracked by its owning scope, so the scope's exit waits for it.\n */\nexport function getTransactionTarget(entry: DatabaseEntry): ActiveTransaction | undefined {\n const store = getStore();\n if (!store) return undefined;\n // The flow's innermost scope, closed or not: the wrapper decides at query time.\n const scope = store.scope;\n if (!scope) return findOpenTransaction(store, entry);\n return {\n async query(sql: string, params: unknown[]): Promise<QueryResult> {\n const owner = owningScope(scope);\n if (!owner) {\n return await queryAfterRootClosed(\n () => findOpenTransaction(store, entry),\n async () => await entry.db.query(sql, params),\n sql,\n params\n );\n }\n // Registered in the same synchronous step as the closed check.\n return await trackQuery(owner, async () => {\n const state = await openScopedTransaction(store, owner, entry);\n if (!state) return await entry.db.query(sql, params);\n return await state.query(sql, params);\n });\n },\n };\n}\n\nfunction findStateForDatabase(store: TxStore, db: object): TxState | undefined {\n for (const state of store.txByDb.values()) {\n if (state.db === db) return state;\n }\n return undefined;\n}\n\n/**\n * A query whose scope chain has fully closed. It never joins a transaction a\n * closed root still owns (its COMMIT/ROLLBACK and release may be in flight, and\n * the query is not tracked by anything): it waits for that root's teardown and\n * looks again — by then the transaction is gone from the flow. A transaction\n * that genuinely encloses the query (an outer withTransaction) is joined.\n */\nasync function queryAfterRootClosed(\n find: () => TxState | undefined,\n direct: () => Promise<QueryResult>,\n sql: string,\n params: unknown[]\n): Promise<QueryResult> {\n const waited = new Set<TxScope>();\n for (;;) {\n const open = find();\n const closing = open?.ownerRoot;\n if (closing && closing.closed) {\n // Torn down already and still listed: never join it; run directly.\n if (waited.has(closing)) return await direct();\n waited.add(closing);\n await closing.tornDown;\n continue;\n }\n return open ? await open.query(sql, params) : await direct();\n }\n}\n\n/**\n * @internal The transaction a query on a Database handle (run(db, ...)) runs\n * in. A transaction already open in this flow on that exact object is joined\n * (identity; registered or handle-opened). Inside a @transaction scope with\n * none open, the query opens one on the handle on first execution, exactly as\n * the name-resolved path does. Outside any scope the behaviour is unchanged:\n * join by identity or run directly (undefined).\n */\nexport function getTransactionTargetForHandle(db: { query(sql: string, params: unknown[]): Promise<unknown> }): ActiveTransaction | undefined {\n const store = getStore();\n if (!store) return undefined;\n // The flow's innermost scope, closed or not: the wrapper decides at query time.\n const scope = store.scope;\n if (!scope) return findStateForDatabase(store, db);\n return {\n async query(sql: string, params: unknown[]): Promise<QueryResult> {\n const owner = owningScope(scope);\n if (!owner) {\n return await queryAfterRootClosed(\n () => findStateForDatabase(store, db),\n async () => (await db.query(sql, params)) as QueryResult,\n sql,\n params\n );\n }\n // Registered in the same synchronous step as the closed check. An open\n // transaction on this object (registered or handle-opened) is joined by\n // openScopedTransaction's identity lookup.\n return await trackQuery(owner, async () => {\n const state = await openScopedTransaction(store, owner, handleEntryFor(db));\n if (!state) return (await db.query(sql, params)) as QueryResult;\n return await state.query(sql, params);\n });\n },\n };\n}\n\nfunction dropFromStore(store: TxStore, state: TxState): void {\n if (store.txByDb.get(state.entry) === state) store.txByDb.delete(state.entry);\n}\n\nasync function runHooks(hooks: TransactionHook[]): Promise<{ failed: boolean; error: unknown }> {\n let failed = false;\n let error: unknown;\n for (const hook of hooks) {\n try {\n // Outside every scope: a hook that is itself @transaction opens a fresh one.\n await als.exit(() => hook());\n } catch (err) {\n if (!failed) {\n failed = true;\n error = err;\n }\n }\n }\n return { failed, error };\n}\n\n/** Roll back and release every transaction the root owns. Returns the first failure. */\nasync function rollbackOwned(root: TxScope, store: TxStore): Promise<{ failed: boolean; error: unknown }> {\n let failed = false;\n let error: unknown;\n for (const state of root.opened) {\n try {\n await state.rollbackIfStarted();\n } catch (err) {\n if (!failed) {\n failed = true;\n error = err;\n }\n } finally {\n try {\n await state.release();\n } catch (err) {\n if (!failed) {\n failed = true;\n error = err;\n }\n }\n dropFromStore(store, state);\n }\n }\n root.opened.length = 0;\n return { failed, error };\n}\n\nasync function exitRootOnSuccess(root: TxScope, store: TxStore): Promise<void> {\n // Name-based API compatibility: currentTransaction()?.rollbackOnly(err)\n // rolls everything back and throws, exactly as it does for withTransaction.\n const legacyMarked = root.opened.find((s) => s.rollbackOnly);\n if (legacyMarked) {\n const err = typeof legacyMarked.rollbackError !== 'undefined' ? legacyMarked.rollbackError : new RollbackTransactionError();\n await rollbackOwned(root, store);\n root.markTornDown();\n await runHooks(root.afterSettled);\n throw err;\n }\n\n let failed = false;\n let error: unknown;\n for (const state of root.opened) {\n try {\n if (failed || root.isMarked(state)) await state.rollbackIfStarted();\n else await state.commitIfStarted();\n } catch (err) {\n if (!failed) {\n failed = true;\n error = err;\n }\n } finally {\n try {\n await state.release();\n } catch (err) {\n if (!failed) {\n failed = true;\n error = err;\n }\n }\n dropFromStore(store, state);\n }\n }\n root.opened.length = 0;\n root.markTornDown();\n\n const commitHooks = !failed && !root.hasMarks ? await runHooks(root.afterCommit) : { failed: false, error: undefined };\n const settledHooks = await runHooks(root.afterSettled);\n if (failed) throw error;\n if (commitHooks.failed) throw commitHooks.error;\n if (settledHooks.failed) throw settledHooks.error;\n}\n\nasync function exitRootOnError(root: TxScope, store: TxStore): Promise<void> {\n await rollbackOwned(root, store);\n root.markTornDown();\n await runHooks(root.afterSettled);\n}\n\nasync function exitNestedOnSuccess(scope: TxScope): Promise<void> {\n const parent = scope.parent!;\n try {\n for (const { state, name } of scope.savepoints) {\n if (state.completed) continue;\n if (scope.isMarked(state)) await state.control('rollbackToSavepoint', name);\n await state.control('releaseSavepoint', name);\n }\n if (!scope.hasMarks) parent.afterCommit.push(...scope.afterCommit);\n } finally {\n parent.afterSettled.push(...scope.afterSettled);\n }\n}\n\nasync function exitNestedOnError(scope: TxScope): Promise<void> {\n for (const { state, name } of scope.savepoints) {\n if (state.completed) continue;\n try {\n await state.control('rollbackToSavepoint', name);\n await state.control('releaseSavepoint', name);\n } catch {\n // the original error wins; the root rolls back everything if it propagates\n }\n }\n scope.parent!.afterSettled.push(...scope.afterSettled);\n}\n\n/**\n * Wait for child scopes and for every query this scope (or a descendant) still\n * has in flight (opening or running), then close. The emptiness check and\n * `closed = true` share one synchronous step, so no query can register in\n * between: a nested scope's savepoint cleanup and the root's commit/rollback\n * see every write made under them.\n */\nasync function closeWhenIdle(scope: TxScope): Promise<void> {\n for (;;) {\n await scope.waitForChildren();\n if (scope.inFlight.size === 0) break;\n await Promise.all([...scope.inFlight]);\n }\n scope.closed = true;\n}\n\nasync function runInScope<T>(fn: () => Promise<T>): Promise<T> {\n const outer = getStore();\n const parent = activeScope(outer);\n const scope = new TxScope(parent);\n const store: TxStore = { txByDb: outer?.txByDb ?? new Map(), scope };\n // Reserve synchronously, before yielding: a parent must see even queued children.\n const turn = parent?.reserveChild();\n\n try {\n if (turn) await turn.ready;\n return await als.run(store, async () => {\n let out: T;\n try {\n if (parent) {\n // Siblings enter one at a time, so releasing one cannot erase another's savepoint.\n for (const state of scope.root.opened) {\n if (!state.completed) await issueSavepoint(scope, state);\n }\n }\n out = await fn();\n } catch (err) {\n // Promise.all may reject while another child is still writing. Keep this\n // scope active until those children (and, on a root, queries still\n // opening or running) settle, then roll back their work too.\n await closeWhenIdle(scope);\n if (parent) {\n await exitNestedOnError(scope);\n throw err;\n }\n await exitRootOnError(scope, store);\n throw isRollbackTransactionError(err) ? unwrapRollbackCause(err) : err;\n }\n await closeWhenIdle(scope);\n if (parent) await exitNestedOnSuccess(scope);\n else await exitRootOnSuccess(scope, store);\n return out;\n });\n } finally {\n // Never leave a late query waiting on a root that exited abnormally.\n if (!parent) scope.markTornDown();\n // Release only after savepoint cleanup and descendants, on success or failure.\n turn?.release();\n }\n}\n\nfunction matchOpenTransaction(scope: TxScope, target: string | object): TxState {\n const open = scope.root.opened.filter((s) => !s.completed);\n const state =\n typeof target === 'string'\n ? open.find((s) => !isHandleEntry(s.entry) && s.entry.name === target)\n : open.find((s) => s.db === target);\n if (!state) {\n throw new SqlStackError(\n typeof target === 'string'\n ? `transaction.rollback(\"${target}\"): no transaction is open on a database named \"${target}\" in this scope.`\n : 'transaction.rollback(db): no transaction is open on that database handle in this scope.'\n );\n }\n return state;\n}\n\n/**\n * Mark the innermost @transaction scope for rollback. Synchronous and\n * non-throwing for the method: SQL after it still runs inside the open\n * transaction; at scope exit the scope rolls back instead of committing and\n * the method's return value still reaches the caller. With a target (a\n * registered database name or a Database handle), only that database's open\n * transaction is marked.\n */\nfunction markRollback(target?: string | object): void {\n const scope = requireScope('rollback');\n if (typeof target === 'undefined') {\n scope.markAll = true;\n return;\n }\n scope.marked.add(matchOpenTransaction(scope, target));\n}\n\n/**\n * Roll back everything the innermost scope has done so far, now. The root\n * scope rolls back and releases its transactions (the next query opens fresh\n * ones); a nested scope rolls back to its savepoints. Marks and the scope's\n * pending afterCommit hooks are cleared; afterSettled hooks stay.\n */\nasync function restartScope(): Promise<void> {\n const scope = requireScope('restart');\n const store = getStore()!;\n if (scope.parent) {\n for (const { state, name } of scope.savepoints) {\n if (state.completed) continue;\n await state.control('rollbackToSavepoint', name);\n }\n } else {\n const result = await rollbackOwned(scope, store);\n if (result.failed) throw result.error;\n }\n scope.markAll = false;\n scope.marked.clear();\n scope.afterCommit = [];\n}\n\nfunction registerAfterCommit(fn: TransactionHook): void {\n if (typeof fn !== 'function') throw new SqlStackError('transaction.afterCommit(fn) requires a function.');\n requireScope('afterCommit').afterCommit.push(fn);\n}\n\nfunction registerAfterSettled(fn: TransactionHook): void {\n if (typeof fn !== 'function') throw new SqlStackError('transaction.afterSettled(fn) requires a function.');\n requireScope('afterSettled').afterSettled.push(fn);\n}\n\nexport type TransactionDecorator = {\n (target: any, prop: string | symbol, desc: PropertyDescriptor): void;\n (options?: TransactionOptions): (target: any, prop: string | symbol, desc: PropertyDescriptor) => void;\n /**\n * Mark the innermost scope (or, with a database name or handle, only that\n * database's open transaction) for rollback at scope exit. Never throws\n * inside a scope for a valid target; throws SqlStackError outside any\n * scope or when no open transaction matches the target.\n */\n rollback(target?: string | object): void;\n /** Roll back the scope's work now; the next query opens fresh transactions. */\n restart(): Promise<void>;\n /** Run fn after the root scope commits (dropped on rollback). */\n afterCommit(fn: TransactionHook): void;\n /** Run fn after the root scope finishes, committed or not. */\n afterSettled(fn: TransactionHook): void;\n};\n\nconst transactionDecorator = function (...args: any[]) {\n // @transaction\n if (args.length === 3 && typeof args[2]?.value === 'function') {\n const [target, prop, desc] = args as [any, string | symbol, PropertyDescriptor];\n wrapMethod(target, prop, desc, undefined);\n return;\n }\n // @transaction() or @transaction({ ... })\n const options: TransactionOptions | undefined = args.length > 0 ? args[0] : undefined;\n return function (target: any, prop: string | symbol, desc: PropertyDescriptor) {\n wrapMethod(target, prop, desc, options);\n };\n};\n\nexport const transaction: TransactionDecorator = Object.assign(transactionDecorator, {\n rollback: markRollback,\n restart: restartScope,\n afterCommit: registerAfterCommit,\n afterSettled: registerAfterSettled,\n}) as any;\n\n/**\n * A name (`{ db }`) or an eager open (`lazy: false`) keeps the name-based\n * behaviour of withTransaction. Everything else is a scope: no entry is\n * resolved; queries open transactions on first touch.\n */\nfunction isNameBased(options: TransactionOptions | undefined): boolean {\n return typeof options?.db !== 'undefined' || options?.lazy === false;\n}\n\nfunction wrapMethod(_target: any, _prop: string | symbol, desc: PropertyDescriptor, options?: TransactionOptions) {\n const original = desc.value;\n if (isNameBased(options)) {\n desc.value = async function (...callArgs: any[]) {\n return await withTransaction(() => original.apply(this, callArgs), options);\n };\n return;\n }\n desc.value = async function (...callArgs: any[]) {\n return await runInScope(() => original.apply(this, callArgs));\n };\n}\n\nexport type ActiveTransaction = {\n query(sql: string, params: unknown[]): Promise<QueryResult>;\n};\n\nexport function getActiveTransaction(entry: DatabaseEntry): ActiveTransaction | undefined {\n const store = getStore();\n return store?.txByDb.get(entry);\n}\n\n/**\n * Active transaction whose registered database is exactly `db` (object\n * identity), if any. `run(db, ...)` uses this so a handle passed at call time\n * joins a transaction opened on the same database (by `@transaction` or\n * `withTransaction`) instead of bypassing it. A handle that was never\n * registered with a SqlStack (or the legacy registry) never matches.\n */\nexport function getActiveTransactionForDatabase(db: object): ActiveTransaction | undefined {\n const store = getStore();\n if (!store) return undefined;\n for (const state of store.txByDb.values()) {\n if (state.db === db) return state;\n }\n return undefined;\n}\n"]}
@@ -0,0 +1,33 @@
1
+ import { producesRows } from './sqlite.js';
2
+ /**
3
+ * Wrap an exec-style SQLite handle. Row-producing statements return rows;
4
+ * others return `{ rowsAffected }` from the cursor's `rowsWritten`.
5
+ * Rows vs write is decided from `columnNames` when the cursor exposes it,
6
+ * falling back to the SQL text (leading SELECT/WITH or a RETURNING clause).
7
+ */
8
+ export function createExecSqliteDb(handle, options = {}) {
9
+ if (!handle || typeof handle.exec !== 'function') {
10
+ throw new TypeError('createExecSqliteDb requires a handle with exec(sql, ...params)');
11
+ }
12
+ const db = {
13
+ dialect: 'sqlite',
14
+ async query(sql, params) {
15
+ const cursor = await handle.exec(sql, ...(params ?? []));
16
+ const rows = cursor.toArray();
17
+ const columns = cursor.columnNames;
18
+ const hasResultSet = Array.isArray(columns) ? columns.length > 0 : producesRows(sql);
19
+ if (hasResultSet)
20
+ return rows;
21
+ return { rowsAffected: Number(cursor.rowsWritten ?? 0) };
22
+ },
23
+ conn: handle,
24
+ async close() {
25
+ if (options.close)
26
+ await options.close();
27
+ },
28
+ };
29
+ if (options.transactionHooks)
30
+ db.transactionHooks = options.transactionHooks;
31
+ return db;
32
+ }
33
+ //# sourceMappingURL=execSqlite.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execSqlite.js","sourceRoot":"","sources":["../../../src/adapters/execSqlite.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AA8BxC;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAAC,MAA4B,EAAE,UAA+B,EAAE;IAChG,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;QACjD,MAAM,IAAI,SAAS,CAAC,gEAAgE,CAAC,CAAC;IACxF,CAAC;IACD,MAAM,EAAE,GAAa;QACnB,OAAO,EAAE,QAAQ;QACjB,KAAK,CAAC,KAAK,CAAC,GAAW,EAAE,MAAiB;YACxC,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC;YACzD,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,EAAE,CAAC;YAC9B,MAAM,OAAO,GAAG,MAAM,CAAC,WAAW,CAAC;YACnC,MAAM,YAAY,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC;YACrF,IAAI,YAAY;gBAAE,OAAO,IAAI,CAAC;YAC9B,OAAO,EAAE,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,WAAW,IAAI,CAAC,CAAC,EAAE,CAAC;QAC3D,CAAC;QACD,IAAI,EAAE,MAAM;QACZ,KAAK,CAAC,KAAK;YACT,IAAI,OAAO,CAAC,KAAK;gBAAE,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC;QAC3C,CAAC;KACF,CAAC;IACF,IAAI,OAAO,CAAC,gBAAgB;QAAE,EAAE,CAAC,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAC7E,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["import type { Database, TransactionHooks } from '../registry';\nimport { producesRows } from './sqlite';\n\n/**\n * Cursor returned by an exec-style call. Structural: matches Cloudflare\n * Durable Object `SqlStorageCursor` without depending on its types.\n */\nexport interface ExecSqliteCursorLike {\n /** All result rows as objects (DO cursor: `toArray()`). */\n toArray(): Record<string, unknown>[];\n /** Column names; a non-empty list means the statement produced a result set. */\n readonly columnNames?: readonly string[];\n /** Rows written by the statement (DO cursor: `rowsWritten`). */\n readonly rowsWritten?: number;\n}\n\n/** A handle with one `exec(sql, ...params)` call (DO: `ctx.storage.sql`). */\nexport interface ExecSqliteHandleLike {\n exec(sql: string, ...params: unknown[]): ExecSqliteCursorLike | Promise<ExecSqliteCursorLike>;\n}\n\nexport interface ExecSqliteDbOptions {\n /**\n * Host transaction API. Hosts that reject `BEGIN`/`COMMIT`/`SAVEPOINT`\n * statements (Durable Objects) must supply these; see docs/transactions.md.\n */\n transactionHooks?: TransactionHooks;\n /** Called by `Database.close()`. The handle itself is never closed. */\n close?: () => void | Promise<void>;\n}\n\n/**\n * Wrap an exec-style SQLite handle. Row-producing statements return rows;\n * others return `{ rowsAffected }` from the cursor's `rowsWritten`.\n * Rows vs write is decided from `columnNames` when the cursor exposes it,\n * falling back to the SQL text (leading SELECT/WITH or a RETURNING clause).\n */\nexport function createExecSqliteDb(handle: ExecSqliteHandleLike, options: ExecSqliteDbOptions = {}): Database {\n if (!handle || typeof handle.exec !== 'function') {\n throw new TypeError('createExecSqliteDb requires a handle with exec(sql, ...params)');\n }\n const db: Database = {\n dialect: 'sqlite',\n async query(sql: string, params: unknown[]) {\n const cursor = await handle.exec(sql, ...(params ?? []));\n const rows = cursor.toArray();\n const columns = cursor.columnNames;\n const hasResultSet = Array.isArray(columns) ? columns.length > 0 : producesRows(sql);\n if (hasResultSet) return rows;\n return { rowsAffected: Number(cursor.rowsWritten ?? 0) };\n },\n conn: handle,\n async close() {\n if (options.close) await options.close();\n },\n };\n if (options.transactionHooks) db.transactionHooks = options.transactionHooks;\n return db;\n}\n"]}
@@ -2,4 +2,5 @@ export { createSqliteDb } from './sqlite.js';
2
2
  export { createPgDb } from './pg.js';
3
3
  export { createMysqlDb } from './mysql.js';
4
4
  export { createSqlegoDb } from './sqlego.js';
5
+ export { createExecSqliteDb } from './execSqlite.js';
5
6
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/adapters/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC","sourcesContent":["export { createSqliteDb } from './sqlite';\nexport { createPgDb } from './pg';\nexport { createMysqlDb } from './mysql';\nexport { createSqlegoDb } from './sqlego';\nexport type {\n SqlegoClientLike,\n SqlegoTransactionLike,\n SqlegoTargetLike,\n SqlegoDbOptions,\n SqlegoParams,\n SqlegoValue,\n} from './sqlego';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/adapters/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export { createSqliteDb } from './sqlite';\nexport { createPgDb } from './pg';\nexport { createMysqlDb } from './mysql';\nexport { createSqlegoDb } from './sqlego';\nexport { createExecSqliteDb } from './execSqlite';\nexport type { ExecSqliteHandleLike, ExecSqliteCursorLike, ExecSqliteDbOptions } from './execSqlite';\nexport type {\n SqlegoClientLike,\n SqlegoTransactionLike,\n SqlegoTargetLike,\n SqlegoDbOptions,\n SqlegoParams,\n SqlegoValue,\n} from './sqlego';\n"]}
@@ -88,6 +88,22 @@ export class TransactionBusyError extends SqlStackError {
88
88
  this.name = 'TransactionBusyError';
89
89
  }
90
90
  }
91
+ /**
92
+ * A database family's provider.open() did not settle within the family's
93
+ * `openTimeoutMs`. The attempt was abandoned: waiting acquires are rejected
94
+ * and their leases rolled back, and a handle that arrives later is closed.
95
+ * `code` is `'family-open-timeout'`.
96
+ */
97
+ export class FamilyOpenTimeoutError extends SqlStackError {
98
+ constructor(family, keyId, timeoutMs) {
99
+ super(`Opening "${family}/${keyId}" timed out after ${timeoutMs}ms; the attempt was abandoned.`);
100
+ this.code = 'family-open-timeout';
101
+ this.family = family;
102
+ this.keyId = keyId;
103
+ this.timeoutMs = timeoutMs;
104
+ this.name = 'FamilyOpenTimeoutError';
105
+ }
106
+ }
91
107
  // Signals that the current transaction should be rolled back.
92
108
  // If `cause` is provided, wrappers may rethrow it after rollback.
93
109
  export class RollbackTransactionError extends SqlStackError {
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/core/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAgB;QAC1B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9B,CAAC;CACF;AAED,MAAM,OAAO,kBAAmB,SAAQ,aAAa;IACnD,YAAY,WAAmB;QAC7B,KAAK,CAAC,iCAAiC,WAAW,EAAE,CAAC,CAAC;QACtD,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC,CAAC;CACF;AAED,MAA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ACnB,MAAM,IAAI,GAAI,KAAwC,EAAE,IAAI,CAAC;QAC7D,IAAI,OAAO,IAAI,KAAK,QAAQ;YAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAC/C,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9B,CAAC;CAKF;AAED;;;;;;GAMG;AACH,MAAM,OAAO,uBAAwB,SAAQ,aAAa;IACxD,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QAIR,SAAI,GAAG,YAAY,CAAC;QAH3B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACxC,CAAC;CAGF;AAED;;;;GAIG;AACH,MAAM,OAAO,oBAAqB,SAAQ,aAAa;IACrD,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QAIR,SAAI,GAAG,SAAS,CAAC;QAHxB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;IACrC,CAAC;CAGF;AAED,8DAA8D;AAC9D,kEAAkE;AAClE,MAAM,OAAO,wBAAyB,SAAQ,aAAa;IACzD,YAAY,OAAO,GAAG,yBAAyB,EAAE,KAAe;QAC9D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;IACzC,CAAC;CAEF","sourcesContent":["export class SqlStackError extends Error {\n constructor(message?: string) {\n super(message);\n this.name = 'SqlStackError';\n }\n}\n\nexport class ExactlyOneRowError extends SqlStackError {\n constructor(actualCount: number) {\n super(`Expected exactly one row, got ${actualCount}`);\n this.name = 'ExactlyOneRowError';\n }\n}\n\nexport class NoRowsError extends SqlStackError {\n constructor() {\n super('Expected at least one row, got 0');\n this.name = 'NoRowsError';\n }\n}\n\nexport class RowsExistError extends SqlStackError {\n constructor(actualCount: number) {\n super(`Expected no rows, got ${actualCount}`);\n this.name = 'RowsExistError';\n }\n}\n\n// A result-shape decorator (@Single/@Only/@Exist/@None) was applied to a\n// method whose statement produced no result set (a plain write). Shapes\n// require rows; use `... RETURNING` or drop the decorator.\nexport class ExpectedRowsError extends SqlStackError {\n constructor(method: string, shape: string) {\n const decorator = '@' + shape.charAt(0).toUpperCase() + shape.slice(1);\n super(\n `${decorator} on ${method} requires a result set, but the statement produced a write result ` +\n `({ rowsAffected }). Add a RETURNING clause or remove the shape decorator.`\n );\n this.method = method;\n this.shape = shape;\n this.name = 'ExpectedRowsError';\n }\n method: string;\n shape: string;\n}\n\nexport class ValidationError extends SqlStackError {\n constructor(details: string) {\n super(`Validation failed: ${details}`);\n this.details = details;\n this.name = 'ValidationError';\n }\n details: string;\n}\n\n/**\n * A statement failed: the driver rejected it, or (for the `run(...)` forms\n * that take arguments) the SQL could not be compiled, bound, or routed to a\n * database. The original error is kept in `.cause`; when the cause carries a\n * string driver code (`SQLITE_CONSTRAINT_UNIQUE`, `23505`, `ER_DUP_ENTRY`)\n * it is copied to `.code` so existing `err.code` checks keep working.\n */\nexport class DatabaseError extends SqlStackError {\n constructor(message: string, sql: string, cause?: Error) {\n super(`${message}\\nSQL: ${sql}`);\n this.sql = sql;\n this.cause = cause;\n const code = (cause as { code?: unknown } | undefined)?.code;\n if (typeof code === 'string') this.code = code;\n this.name = 'DatabaseError';\n }\n sql: string;\n cause?: Error;\n /** Driver error code copied from `cause` when it is a string. */\n code?: string;\n}\n\n/**\n * The database ended the transaction on its own and rolled it back: a sqlego\n * lease ran out (no statement within the lease), the transaction hit the\n * server's hard cap on its duration, or the client connection dropped.\n * `code` is `'tx-expired'`. Statements fail with it (wrapped in\n * DatabaseError, which copies the code); COMMIT fails with it directly.\n */\nexport class TransactionExpiredError extends SqlStackError {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.cause = cause;\n this.name = 'TransactionExpiredError';\n }\n readonly code = 'tx-expired';\n cause?: unknown;\n}\n\n/**\n * Another process held the database in a transaction for longer than the\n * server lets a request wait (sqlego's queue timeout). Nothing ran; the\n * statement or BEGIN can be retried. `code` is `'tx-busy'`.\n */\nexport class TransactionBusyError extends SqlStackError {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.cause = cause;\n this.name = 'TransactionBusyError';\n }\n readonly code = 'tx-busy';\n cause?: unknown;\n}\n\n// Signals that the current transaction should be rolled back.\n// If `cause` is provided, wrappers may rethrow it after rollback.\nexport class RollbackTransactionError extends SqlStackError {\n constructor(message = 'Transaction rolled back', cause?: unknown) {\n super(message);\n this.cause = cause;\n this.name = 'RollbackTransactionError';\n }\n cause?: unknown;\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/core/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAgB;QAC1B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9B,CAAC;CACF;AAED,MAAM,OAAO,kBAAmB,SAAQ,aAAa;IACnD,YAAY,WAAmB;QAC7B,KAAK,CAAC,iCAAiC,WAAW,EAAE,CAAC,CAAC;QACtD,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC,CAAC;CACF;AAED,MAAM,OAAO,WAAY,SAAQ,aAAa;IAC5C;QACE,KAAK,CAAC,kCAAkC,CAAC,CAAC;QAC1C,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAC5B,CAAC;CACF;AAED,MAAM,OAAO,cAAe,SAAQ,aAAa;IAC/C,YAAY,WAAmB;QAC7B,KAAK,CAAC,yBAAyB,WAAW,EAAE,CAAC,CAAC;QAC9C,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC/B,CAAC;CACF;AAED,yEAAyE;AACzE,wEAAwE;AACxE,2DAA2D;AAC3D,MAAM,OAAO,iBAAkB,SAAQ,a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AC;QACnB,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACxC,CAAC;CAGF;AAED;;;;GAIG;AACH,MAAM,OAAO,oBAAqB,SAAQ,aAAa;IACrD,YAAY,OAAe,EAAE,KAAe;QAC1C,KAAK,CAAC,OAAO,CAAC,CAAC;QAIR,SAAI,GAAG,SAAS,CAAC;QAHxB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;IACrC,CAAC;CAGF;AAED;;;;;GAKG;AACH,MAAM,OAAO,sBAAuB,SAAQ,aAAa;IACvD,YAAY,MAAc,EAAE,KAAa,EAAE,SAAiB;QAC1D,KAAK,CAAC,YAAY,MAAM,IAAI,KAAK,qBAAqB,SAAS,gCAAgC,CAAC,CAAC;QAM1F,SAAI,GAAG,qBAAqB,CAAC;QALpC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAC;IACvC,CAAC;CAKF;AAED,8DAA8D;AAC9D,kEAAkE;AAClE,MAAM,OAAO,wBAAyB,SAAQ,aAAa;IACzD,YAAY,OAAO,GAAG,yBAAyB,EAAE,KAAe;QAC9D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;IACzC,CAAC;CAEF","sourcesContent":["export class SqlStackError extends Error {\n constructor(message?: string) {\n super(message);\n this.name = 'SqlStackError';\n }\n}\n\nexport class ExactlyOneRowError extends SqlStackError {\n constructor(actualCount: number) {\n super(`Expected exactly one row, got ${actualCount}`);\n this.name = 'ExactlyOneRowError';\n }\n}\n\nexport class NoRowsError extends SqlStackError {\n constructor() {\n super('Expected at least one row, got 0');\n this.name = 'NoRowsError';\n }\n}\n\nexport class RowsExistError extends SqlStackError {\n constructor(actualCount: number) {\n super(`Expected no rows, got ${actualCount}`);\n this.name = 'RowsExistError';\n }\n}\n\n// A result-shape decorator (@Single/@Only/@Exist/@None) was applied to a\n// method whose statement produced no result set (a plain write). Shapes\n// require rows; use `... RETURNING` or drop the decorator.\nexport class ExpectedRowsError extends SqlStackError {\n constructor(method: string, shape: string) {\n const decorator = '@' + shape.charAt(0).toUpperCase() + shape.slice(1);\n super(\n `${decorator} on ${method} requires a result set, but the statement produced a write result ` +\n `({ rowsAffected }). Add a RETURNING clause or remove the shape decorator.`\n );\n this.method = method;\n this.shape = shape;\n this.name = 'ExpectedRowsError';\n }\n method: string;\n shape: string;\n}\n\nexport class ValidationError extends SqlStackError {\n constructor(details: string) {\n super(`Validation failed: ${details}`);\n this.details = details;\n this.name = 'ValidationError';\n }\n details: string;\n}\n\n/**\n * A statement failed: the driver rejected it, or (for the `run(...)` forms\n * that take arguments) the SQL could not be compiled, bound, or routed to a\n * database. The original error is kept in `.cause`; when the cause carries a\n * string driver code (`SQLITE_CONSTRAINT_UNIQUE`, `23505`, `ER_DUP_ENTRY`)\n * it is copied to `.code` so existing `err.code` checks keep working.\n */\nexport class DatabaseError extends SqlStackError {\n constructor(message: string, sql: string, cause?: Error) {\n super(`${message}\\nSQL: ${sql}`);\n this.sql = sql;\n this.cause = cause;\n const code = (cause as { code?: unknown } | undefined)?.code;\n if (typeof code === 'string') this.code = code;\n this.name = 'DatabaseError';\n }\n sql: string;\n cause?: Error;\n /** Driver error code copied from `cause` when it is a string. */\n code?: string;\n}\n\n/**\n * The database ended the transaction on its own and rolled it back: a sqlego\n * lease ran out (no statement within the lease), the transaction hit the\n * server's hard cap on its duration, or the client connection dropped.\n * `code` is `'tx-expired'`. Statements fail with it (wrapped in\n * DatabaseError, which copies the code); COMMIT fails with it directly.\n */\nexport class TransactionExpiredError extends SqlStackError {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.cause = cause;\n this.name = 'TransactionExpiredError';\n }\n readonly code = 'tx-expired';\n cause?: unknown;\n}\n\n/**\n * Another process held the database in a transaction for longer than the\n * server lets a request wait (sqlego's queue timeout). Nothing ran; the\n * statement or BEGIN can be retried. `code` is `'tx-busy'`.\n */\nexport class TransactionBusyError extends SqlStackError {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.cause = cause;\n this.name = 'TransactionBusyError';\n }\n readonly code = 'tx-busy';\n cause?: unknown;\n}\n\n/**\n * A database family's provider.open() did not settle within the family's\n * `openTimeoutMs`. The attempt was abandoned: waiting acquires are rejected\n * and their leases rolled back, and a handle that arrives later is closed.\n * `code` is `'family-open-timeout'`.\n */\nexport class FamilyOpenTimeoutError extends SqlStackError {\n constructor(family: string, keyId: string, timeoutMs: number) {\n super(`Opening \"${family}/${keyId}\" timed out after ${timeoutMs}ms; the attempt was abandoned.`);\n this.family = family;\n this.keyId = keyId;\n this.timeoutMs = timeoutMs;\n this.name = 'FamilyOpenTimeoutError';\n }\n readonly code = 'family-open-timeout';\n family: string;\n keyId: string;\n timeoutMs: number;\n}\n\n// Signals that the current transaction should be rolled back.\n// If `cause` is provided, wrappers may rethrow it after rollback.\nexport class RollbackTransactionError extends SqlStackError {\n constructor(message = 'Transaction rolled back', cause?: unknown) {\n super(message);\n this.cause = cause;\n this.name = 'RollbackTransactionError';\n }\n cause?: unknown;\n}\n"]}