sqlstack 3.7.1-dev.0 → 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.
- package/dist/cjs/core/errors.d.ts +13 -0
- package/dist/cjs/core/errors.d.ts.map +1 -1
- package/dist/cjs/core/errors.js +18 -1
- package/dist/cjs/core/errors.js.map +1 -1
- package/dist/cjs/family.d.ts +6 -0
- package/dist/cjs/family.d.ts.map +1 -1
- package/dist/cjs/family.js +126 -33
- package/dist/cjs/family.js.map +1 -1
- package/dist/cjs/familyBinding.d.ts +4 -0
- package/dist/cjs/familyBinding.d.ts.map +1 -1
- package/dist/cjs/familyBinding.js.map +1 -1
- package/dist/cjs/stack.d.ts.map +1 -1
- package/dist/cjs/stack.js +29 -4
- package/dist/cjs/stack.js.map +1 -1
- package/dist/cjs/transactions.d.ts +61 -0
- package/dist/cjs/transactions.d.ts.map +1 -1
- package/dist/cjs/transactions.js +163 -24
- package/dist/cjs/transactions.js.map +1 -1
- package/dist/esm/core/errors.js +16 -0
- package/dist/esm/core/errors.js.map +1 -1
- package/dist/esm/family.js +127 -34
- package/dist/esm/family.js.map +1 -1
- package/dist/esm/familyBinding.js.map +1 -1
- package/dist/esm/stack.js +29 -4
- package/dist/esm/stack.js.map +1 -1
- package/dist/esm/transactions.js +163 -24
- package/dist/esm/transactions.js.map +1 -1
- package/package.json +1 -1
package/dist/cjs/stack.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stack.js","sourceRoot":"","sources":["../../src/stack.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,8CAMyB;AACzB,0CAA8C;AAC9C,gDAAiF;AACjF,qCAAyC;AAEzC,mDAA+E;AAqC/E;;;;;;GAMG;AACH,MAAa,QAAQ;IACnB;;;;;OAKG;IACH,MAAM,CAAC,WAAW,CAAC,QAAqB;QACtC,IAAA,4BAAiB,E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yBAAS,CAAC;IACvB,CAAC;IAED,0EAA0E;IAC1E,OAAO,KAAoB,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;CAelD;AA5RD,4BA4RC;;IAZG,IAAI,uBAAA,IAAI,wBAAQ,EAAE,CAAC;QACjB,MAAM,IAAI,sBAAa,CAAC,yDAAyD,CAAC,CAAC;IACrF,CAAC;AACH,CAAC;IAGC,MAAM,KAAK,GAAG;QACZ,GAAG,CAAC,GAAG,uBAAA,IAAI,yBAAS,CAAC,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC;QACjD,GAAG,CAAC,GAAG,uBAAA,IAAI,0BAAU,CAAC,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,YAAY,CAAC;KAC5D,CAAC;IACF,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;AACpD,CAAC","sourcesContent":["import type { Database } from './registry';\nimport type { SqlResolver } from './core/resolver';\nimport {\n setGlobalResolver,\n clearGlobalResolver,\n ManifestResolver,\n assertManifestCoverage,\n assertManifestCoversClasses,\n} from './core/resolver';\nimport { SqlStackError } from './core/errors';\nimport { setResources, getResources, type SqlResources } from './core/resources';\nimport { FamilyRuntime } from './family';\nimport type { FamilyConfig, FamilyMemberEntry, DatabaseLease } from './family';\nimport { currentBinding, runWithBinding, BindingFrame } from './familyBinding';\n\n/**\n * Concrete database identity inside one SqlStack instance.\n *\n * The entry OBJECT is the identity: two roots that both register a database\n * under the name \"primary\" produce two distinct DatabaseEntry instances, so\n * transaction lookup, caches, and diagnostics keyed by entry can never collide\n * across roots merely because the registration text matches.\n *\n * Dynamic database families (spec 17) extend this identity with a normalized\n * key; a static database is the no-key case.\n */\nexport interface DatabaseEntry {\n readonly name: string;\n readonly db: Database;\n /** Close() closes owned databases; externally supplied ones are left open. */\n readonly owned: boolean;\n /** The stack this entry belongs to, for diagnostics and mismatch checks. */\n readonly stack: SqlStack;\n}\n\nexport type DatabaseRegistration =\n | Database\n | {\n db: Database | (() => Database);\n /** Default false for direct Database values, true for factories. */\n owned?: boolean;\n };\n\nexport interface SqlStackConfig {\n databases?: Record<string, DatabaseRegistration>;\n /** Name of the default database. Required when more than one is registered. */\n default?: string;\n resolver?: SqlResolver;\n}\n\n/**\n * Environment-owned SQLStack runtime (spec 16 §12-13, repo spec 19 §3-5).\n *\n * One instance per owning IoC root; child scopes resolve the root's Singleton.\n * Native @Query/transaction/resolver execution goes through an instance —\n * never through the process-global SqlStackDB registry.\n */\nexport class SqlStack {\n /**\n * @deprecated Legacy v2 process-global resolver registration\n * (`SqlStack.useResolver(...)`). Forwards to the deprecated global state,\n * which is only consulted when no IoC environment is active. Use the\n * per-instance `useResolver` / SqlStackConfig.resolver instead.\n */\n static useResolver(resolver: SqlResolver): void {\n setGlobalResolver(resolver);\n }\n\n /** @deprecated See static useResolver. */\n static clearResolver(): void {\n clearGlobalResolver();\n }\n\n /**\n * Install the packaged SQL resources for this process: a path-keyed map\n * `{ 'server/.../<method>.sql': '<sql>' }` (an `import.meta.glob` raw\n * import, or a build-generated module). Bare `@Query()` methods resolve\n * their guessed module directory + `<method>.sql` against it by path\n * suffix, so the map works unchanged across an asar, a Worker module tree\n * and a plain checkout. Replaces any previously installed map.\n */\n static useResources(resources: SqlResources): void {\n setResources(resources);\n }\n\n /** Remove the packaged SQL resources (tests). */\n static clearResources(): void {\n setResources(undefined);\n }\n\n /** The installed packaged SQL resources, if any. */\n static resources(): SqlResources | undefined {\n return getResources();\n }\n\n #entries = new Map<string, DatabaseEntry>();\n #families = new Map<string, FamilyRuntime<any>>();\n #defaultName: string | undefined;\n #resolver: SqlResolver | undefined;\n #closed = false;\n #closing: Promise<void> | undefined;\n\n constructor(config?: SqlStackConfig) {\n if (config?.databases) {\n for (const [name, reg] of Object.entries(config.databases)) {\n if (typeof reg === 'object' && reg !== null && 'db' in reg) {\n const db = typeof reg.db === 'function' ? reg.db() : reg.db;\n this.register(name, db, { owned: reg.owned ?? typeof reg.db === 'function' });\n } else {\n this.register(name, reg as Database);\n }\n }\n }\n if (config?.default) this.setDefault(config.default);\n if (config?.resolver) this.useResolver(config.resolver);\n }\n\n register(name: string, db: Database, options?: { owned?: boolean; default?: boolean }): this {\n this.#assertOpen();\n const entry: DatabaseEntry = { name, db, owned: options?.owned ?? false, stack: this };\n this.#entries.set(name, entry);\n if (options?.default || this.#entries.size === 1) {\n this.#defaultName ??= name;\n if (options?.default) this.#defaultName = name;\n }\n return this;\n }\n\n setDefault(name: string): this {\n this.#assertOpen();\n if (!this.#entries.has(name)) {\n throw new SqlStackError(\n `SqlStack has no database registered under \"${name}\". Registered: ${this.#registeredNames()}`\n );\n }\n this.#defaultName = name;\n return this;\n }\n\n getEntry(name?: string): DatabaseEntry {\n this.#assertOpen();\n const key = name ?? this.#defaultName;\n if (!key) {\n throw new SqlStackError(\n 'SqlStack has no default database. Register one with { default: true } or call setDefault(name).'\n );\n }\n const entry = this.#entries.get(key);\n if (!entry) {\n throw new SqlStackError(\n `SqlStack has no database registered under \"${key}\". Registered: ${this.#registeredNames()}`\n );\n }\n return entry;\n }\n\n database(name?: string): Database {\n return this.getEntry(name).db;\n }\n\n has(name: string): boolean {\n return this.#entries.has(name) || this.#families.has(name);\n }\n\n /**\n * Register a dynamic database family (spec 17): one registration whose\n * concrete member is selected per execution flow via withDatabase(...).\n */\n registerFamily<K = string>(name: string, config: FamilyConfig<K>): this {\n this.#assertOpen();\n if (this.#entries.has(name)) {\n throw new SqlStackError(`\"${name}\" is already registered as a static database.`);\n }\n this.#families.set(name, new FamilyRuntime(this, name, config));\n return this;\n }\n\n family<K = string>(name: string): FamilyRuntime<K> {\n const fam = this.#families.get(name);\n if (!fam) {\n throw new SqlStackError(\n `SqlStack has no database family registered under \"${name}\". Families: ${\n [...this.#families.keys()].map((n) => `\"${n}\"`).join(', ') || '(none)'\n }`\n );\n }\n return fam;\n }\n\n /**\n * Bind a family registration to a concrete member for the duration of fn\n * (spec 17 §10). The binding is flow-local to this SqlStack; the member's\n * connection is leased lazily on first database resolution and released\n * when fn settles. Rebinding a family to a different key while it has an\n * active transaction fails deterministically (spec 17 §29).\n */\n async withDatabase<T>(family: string, key: unknown, fn: () => Promise<T>): Promise<T> {\n this.#assertOpen();\n const fam = this.family(family);\n const { keyId } = fam.normalize(key);\n\n const outer = currentBinding(this, family);\n if (outer && outer.keyId !== keyId && outer.lease) {\n const { getActiveTransaction } = await import('./transactions');\n if (getActiveTransaction(outer.lease.entry)) {\n throw new SqlStackError(\n `Cannot rebind database family \"${family}\" from \"${outer.keyId}\" to \"${keyId}\": ` +\n 'a transaction is active for the current member. Finish the transaction first.'\n );\n }\n }\n\n const frame: BindingFrame = { stack: this, family, keyInput: key, keyId };\n try {\n return await runWithBinding(frame, fn);\n } finally {\n await frame.lease?.release();\n }\n }\n\n /**\n * Async database resolution for query/transaction execution. Static\n * registrations resolve directly; family registrations resolve through the\n * active flow-local binding, opening/leasing the member on first use.\n */\n async resolveEntry(name?: string): Promise<DatabaseEntry> {\n this.#assertOpen();\n const key =\n name ??\n this.#defaultName ??\n // A stack whose only registration is one family treats it as default.\n (this.#entries.size === 0 && this.#families.size === 1\n ? [...this.#families.keys()][0]\n : undefined);\n if (key !== undefined) {\n const entry = this.#entries.get(key);\n if (entry) return entry;\n const fam = this.#families.get(key);\n if (fam) {\n const frame = currentBinding(this, key);\n if (!frame) {\n throw new SqlStackError(\n `SQLStack database family \"${key}\" requires a concrete database key. ` +\n 'No active binding exists for this execution. Establish the database at the ' +\n `orchestration boundary with sqlStack.withDatabase(\"${key}\", key, ...) ` +\n 'or acquire a member explicitly via sqlStack.family(...).with(...).'\n );\n }\n if (!frame.lease) {\n frame.lease = await fam.acquire(frame.keyInput);\n }\n return frame.lease.entry;\n }\n }\n return this.getEntry(name);\n }\n\n /**\n * Set this stack's SQL resolver. When `options.classes` supplies the\n * repository catalog, manifest coverage is validated from those classes'\n * immutable metadata (environment-local, unpollutable by unrelated\n * imports). Without a catalog, coverage falls back to the deprecated\n * process-global decorated list.\n */\n useResolver(\n resolver: SqlResolver,\n options?: { classes?: ReadonlyArray<abstract new (...args: any[]) => any> }\n ): this {\n this.#assertOpen();\n if (resolver instanceof ManifestResolver && resolver.options.assert !== false) {\n if (options?.classes) {\n assertManifestCoversClasses(resolver, options.classes);\n } else {\n assertManifestCoverage(resolver);\n }\n }\n this.#resolver = resolver;\n return this;\n }\n\n resolver(): SqlResolver | undefined {\n return this.#resolver;\n }\n\n get closed(): boolean {\n return this.#closed;\n }\n\n /**\n * Close owned database adapters exactly once and release runtime resources.\n * Externally supplied databases (owned: false) are not touched. Failures are\n * collected and reported with database identity rather than swallowed.\n */\n close(): Promise<void> {\n if (this.#closing) return this.#closing;\n this.#closed = true;\n this.#closing = Promise.resolve().then(async () => {\n const failures: string[] = [];\n const errors: unknown[] = [];\n const closed = new Set<Database>();\n for (const entry of this.#entries.values()) {\n if (!entry.owned || closed.has(entry.db)) continue;\n closed.add(entry.db);\n try { await entry.db.close(); }\n catch (error: any) {\n errors.push(error);\n failures.push(`\"${entry.name}\": ${error?.message ?? String(error)}`);\n }\n }\n for (const fam of this.#families.values()) {\n try { await fam.closeAll(); }\n catch (error: any) { errors.push(error); failures.push(error?.message ?? String(error)); }\n }\n this.#entries.clear();\n this.#families.clear();\n this.#resolver = undefined;\n if (failures.length) {\n throw Object.assign(new SqlStackError(`SqlStack close failed for ${failures.join(', ')}`), {\n errors: Object.freeze(errors), cause: errors[0],\n });\n }\n });\n return this.#closing;\n }\n\n /** Native IoC resource hook; manually calling close remains supported. */\n dispose(): Promise<void> { return this.close(); }\n\n #assertOpen(): void {\n if (this.#closed) {\n throw new SqlStackError('SqlStack has been closed; its owning root was disposed.');\n }\n }\n\n #registeredNames(): string {\n const names = [\n ...[...this.#entries.keys()].map((n) => `\"${n}\"`),\n ...[...this.#families.keys()].map((n) => `\"${n}\" (family)`),\n ];\n return names.length ? names.join(', ') : '(none)';\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"stack.js","sourceRoot":"","sources":["../../src/stack.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,8CAMyB;AACzB,0CAA8C;AAC9C,gDAAiF;AACjF,qCAAyC;AAEzC,mDAA+E;AAE/E,SAAS,YAAY,CAAC,MAAc,EAAE,KAAa;IACjD,OAAO,IAAI,sBAAa,CACtB,6BAA6B,MAAM,kBAAkB,KAAK,eAAe;QACvE,yEAAyE;QACzE,qCAAqC,CACxC,CAAC;AACJ,CAAC;AAqCD;;;;;;GAMG;AACH,MAAa,QAAQ;IACnB;;;;;OAKG;IACH,MAAM,CAAC,WAAW,CAAC,QAAqB;QACtC,IAAA,4BAAiB,EAAC,QAAQ,CAAC,CAAC;IAC9B,CAAC;IAED,0CAA0C;IAC1C,MAAM,CAAC,aAAa;QAClB,IAAA,8BAAmB,GAAE,CAAC;IACxB,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,YAAY,CAAC,SAAuB;QACzC,IAAA,wBAAY,EAAC,SAAS,CAAC,CAAC;IAC1B,CAAC;IAED,iDAAiD;IACjD,MAAM,CAAC,cAAc;QACnB,IAAA,wBAAY,EAAC,SAAS,CAAC,CAAC;IAC1B,CAAC;IAED,oDAAoD;IACpD,MAAM,CAAC,SAAS;QACd,OAAO,IAAA,wBAAY,GAAE,CAAC;IACxB,CAAC;IASD,YAAY,MAAuB;;QAPnC,4BAAW,IAAI,GAAG,EAAyB,EAAC;QAC5C,6BAAY,IAAI,GAAG,EAA8B,EAAC;QAClD,wCAAiC;QACjC,qCAAmC;QACnC,2BAAU,KAAK,EAAC;QAChB,oCAAoC;QAGlC,IAAI,MAAM,EAAE,SAAS,EAAE,CAAC;YACtB,KAAK,MAAM,CAAC,IAAI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M,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;iBAChD,CAAC,CAAC;YACL,CAAC;QACH,CAAC,CAAC,MAAA,CAAC;QACH,OAAO,uBAAA,IAAI,yBAAS,CAAC;IACvB,CAAC;IAED,0EAA0E;IAC1E,OAAO,KAAoB,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;CAelD;AA/SD,4BA+SC;;IAZG,IAAI,uBAAA,IAAI,wBAAQ,EAAE,CAAC;QACjB,MAAM,IAAI,sBAAa,CAAC,yDAAyD,CAAC,CAAC;IACrF,CAAC;AACH,CAAC;IAGC,MAAM,KAAK,GAAG;QACZ,GAAG,CAAC,GAAG,uBAAA,IAAI,yBAAS,CAAC,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC;QACjD,GAAG,CAAC,GAAG,uBAAA,IAAI,0BAAU,CAAC,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,YAAY,CAAC;KAC5D,CAAC;IACF,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;AACpD,CAAC","sourcesContent":["import type { Database } from './registry';\nimport type { SqlResolver } from './core/resolver';\nimport {\n setGlobalResolver,\n clearGlobalResolver,\n ManifestResolver,\n assertManifestCoverage,\n assertManifestCoversClasses,\n} from './core/resolver';\nimport { SqlStackError } from './core/errors';\nimport { setResources, getResources, type SqlResources } from './core/resources';\nimport { FamilyRuntime } from './family';\nimport type { FamilyConfig, FamilyMemberEntry, DatabaseLease } from './family';\nimport { currentBinding, runWithBinding, BindingFrame } from './familyBinding';\n\nfunction bindingEnded(family: string, keyId: string): SqlStackError {\n return new SqlStackError(\n `SQLStack database family \"${family}\" binding for \"${keyId}\" has ended: ` +\n 'withDatabase(...) already settled. A query started inside the callback ' +\n 'was not awaited before it returned.'\n );\n}\n\n/**\n * Concrete database identity inside one SqlStack instance.\n *\n * The entry OBJECT is the identity: two roots that both register a database\n * under the name \"primary\" produce two distinct DatabaseEntry instances, so\n * transaction lookup, caches, and diagnostics keyed by entry can never collide\n * across roots merely because the registration text matches.\n *\n * Dynamic database families (spec 17) extend this identity with a normalized\n * key; a static database is the no-key case.\n */\nexport interface DatabaseEntry {\n readonly name: string;\n readonly db: Database;\n /** Close() closes owned databases; externally supplied ones are left open. */\n readonly owned: boolean;\n /** The stack this entry belongs to, for diagnostics and mismatch checks. */\n readonly stack: SqlStack;\n}\n\nexport type DatabaseRegistration =\n | Database\n | {\n db: Database | (() => Database);\n /** Default false for direct Database values, true for factories. */\n owned?: boolean;\n };\n\nexport interface SqlStackConfig {\n databases?: Record<string, DatabaseRegistration>;\n /** Name of the default database. Required when more than one is registered. */\n default?: string;\n resolver?: SqlResolver;\n}\n\n/**\n * Environment-owned SQLStack runtime (spec 16 §12-13, repo spec 19 §3-5).\n *\n * One instance per owning IoC root; child scopes resolve the root's Singleton.\n * Native @Query/transaction/resolver execution goes through an instance —\n * never through the process-global SqlStackDB registry.\n */\nexport class SqlStack {\n /**\n * @deprecated Legacy v2 process-global resolver registration\n * (`SqlStack.useResolver(...)`). Forwards to the deprecated global state,\n * which is only consulted when no IoC environment is active. Use the\n * per-instance `useResolver` / SqlStackConfig.resolver instead.\n */\n static useResolver(resolver: SqlResolver): void {\n setGlobalResolver(resolver);\n }\n\n /** @deprecated See static useResolver. */\n static clearResolver(): void {\n clearGlobalResolver();\n }\n\n /**\n * Install the packaged SQL resources for this process: a path-keyed map\n * `{ 'server/.../<method>.sql': '<sql>' }` (an `import.meta.glob` raw\n * import, or a build-generated module). Bare `@Query()` methods resolve\n * their guessed module directory + `<method>.sql` against it by path\n * suffix, so the map works unchanged across an asar, a Worker module tree\n * and a plain checkout. Replaces any previously installed map.\n */\n static useResources(resources: SqlResources): void {\n setResources(resources);\n }\n\n /** Remove the packaged SQL resources (tests). */\n static clearResources(): void {\n setResources(undefined);\n }\n\n /** The installed packaged SQL resources, if any. */\n static resources(): SqlResources | undefined {\n return getResources();\n }\n\n #entries = new Map<string, DatabaseEntry>();\n #families = new Map<string, FamilyRuntime<any>>();\n #defaultName: string | undefined;\n #resolver: SqlResolver | undefined;\n #closed = false;\n #closing: Promise<void> | undefined;\n\n constructor(config?: SqlStackConfig) {\n if (config?.databases) {\n for (const [name, reg] of Object.entries(config.databases)) {\n if (typeof reg === 'object' && reg !== null && 'db' in reg) {\n const db = typeof reg.db === 'function' ? reg.db() : reg.db;\n this.register(name, db, { owned: reg.owned ?? typeof reg.db === 'function' });\n } else {\n this.register(name, reg as Database);\n }\n }\n }\n if (config?.default) this.setDefault(config.default);\n if (config?.resolver) this.useResolver(config.resolver);\n }\n\n register(name: string, db: Database, options?: { owned?: boolean; default?: boolean }): this {\n this.#assertOpen();\n const entry: DatabaseEntry = { name, db, owned: options?.owned ?? false, stack: this };\n this.#entries.set(name, entry);\n if (options?.default || this.#entries.size === 1) {\n this.#defaultName ??= name;\n if (options?.default) this.#defaultName = name;\n }\n return this;\n }\n\n setDefault(name: string): this {\n this.#assertOpen();\n if (!this.#entries.has(name)) {\n throw new SqlStackError(\n `SqlStack has no database registered under \"${name}\". Registered: ${this.#registeredNames()}`\n );\n }\n this.#defaultName = name;\n return this;\n }\n\n getEntry(name?: string): DatabaseEntry {\n this.#assertOpen();\n const key = name ?? this.#defaultName;\n if (!key) {\n throw new SqlStackError(\n 'SqlStack has no default database. Register one with { default: true } or call setDefault(name).'\n );\n }\n const entry = this.#entries.get(key);\n if (!entry) {\n throw new SqlStackError(\n `SqlStack has no database registered under \"${key}\". Registered: ${this.#registeredNames()}`\n );\n }\n return entry;\n }\n\n database(name?: string): Database {\n return this.getEntry(name).db;\n }\n\n has(name: string): boolean {\n return this.#entries.has(name) || this.#families.has(name);\n }\n\n /**\n * Register a dynamic database family (spec 17): one registration whose\n * concrete member is selected per execution flow via withDatabase(...).\n */\n registerFamily<K = string>(name: string, config: FamilyConfig<K>): this {\n this.#assertOpen();\n if (this.#entries.has(name)) {\n throw new SqlStackError(`\"${name}\" is already registered as a static database.`);\n }\n this.#families.set(name, new FamilyRuntime(this, name, config));\n return this;\n }\n\n family<K = string>(name: string): FamilyRuntime<K> {\n const fam = this.#families.get(name);\n if (!fam) {\n throw new SqlStackError(\n `SqlStack has no database family registered under \"${name}\". Families: ${\n [...this.#families.keys()].map((n) => `\"${n}\"`).join(', ') || '(none)'\n }`\n );\n }\n return fam;\n }\n\n /**\n * Bind a family registration to a concrete member for the duration of fn\n * (spec 17 §10). The binding is flow-local to this SqlStack; the member's\n * connection is leased lazily on first database resolution and released\n * when fn settles. Rebinding a family to a different key while it has an\n * active transaction fails deterministically (spec 17 §29).\n */\n async withDatabase<T>(family: string, key: unknown, fn: () => Promise<T>): Promise<T> {\n this.#assertOpen();\n const fam = this.family(family);\n const { keyId } = fam.normalize(key);\n\n const outer = currentBinding(this, family);\n if (outer && outer.keyId !== keyId && outer.lease) {\n const { getActiveTransaction } = await import('./transactions');\n if (getActiveTransaction(outer.lease.entry)) {\n throw new SqlStackError(\n `Cannot rebind database family \"${family}\" from \"${outer.keyId}\" to \"${keyId}\": ` +\n 'a transaction is active for the current member. Finish the transaction first.'\n );\n }\n }\n\n const frame: BindingFrame = { stack: this, family, keyInput: key, keyId };\n try {\n return await runWithBinding(frame, fn);\n } finally {\n // Close the frame first so no new resolution can lease through it, then\n // drain any acquire still in flight so its lease is released here.\n frame.closed = true;\n const inFlight = frame.leasing;\n if (inFlight) await inFlight.then(() => undefined, () => undefined);\n await frame.lease?.release();\n }\n }\n\n /**\n * Async database resolution for query/transaction execution. Static\n * registrations resolve directly; family registrations resolve through the\n * active flow-local binding, opening/leasing the member on first use.\n */\n async resolveEntry(name?: string): Promise<DatabaseEntry> {\n this.#assertOpen();\n const key =\n name ??\n this.#defaultName ??\n // A stack whose only registration is one family treats it as default.\n (this.#entries.size === 0 && this.#families.size === 1\n ? [...this.#families.keys()][0]\n : undefined);\n if (key !== undefined) {\n const entry = this.#entries.get(key);\n if (entry) return entry;\n const fam = this.#families.get(key);\n if (fam) {\n const frame = currentBinding(this, key);\n if (!frame) {\n throw new SqlStackError(\n `SQLStack database family \"${key}\" requires a concrete database key. ` +\n 'No active binding exists for this execution. Establish the database at the ' +\n `orchestration boundary with sqlStack.withDatabase(\"${key}\", key, ...) ` +\n 'or acquire a member explicitly via sqlStack.family(...).with(...).'\n );\n }\n if (frame.closed) throw bindingEnded(key, frame.keyId);\n if (frame.lease) return frame.lease.entry;\n // Single-flight: concurrent first resolutions in one frame share one\n // acquire, so exactly one lease is taken and released at scope end.\n frame.leasing ??= fam.acquire(frame.keyInput).then(\n (lease) => {\n frame.lease = lease;\n return lease;\n },\n (err) => {\n // A failed acquire leaves nothing to release; allow a retry.\n frame.leasing = undefined;\n throw err;\n }\n );\n const lease = await frame.leasing;\n if (frame.closed) throw bindingEnded(key, frame.keyId);\n return lease.entry;\n }\n }\n return this.getEntry(name);\n }\n\n /**\n * Set this stack's SQL resolver. When `options.classes` supplies the\n * repository catalog, manifest coverage is validated from those classes'\n * immutable metadata (environment-local, unpollutable by unrelated\n * imports). Without a catalog, coverage falls back to the deprecated\n * process-global decorated list.\n */\n useResolver(\n resolver: SqlResolver,\n options?: { classes?: ReadonlyArray<abstract new (...args: any[]) => any> }\n ): this {\n this.#assertOpen();\n if (resolver instanceof ManifestResolver && resolver.options.assert !== false) {\n if (options?.classes) {\n assertManifestCoversClasses(resolver, options.classes);\n } else {\n assertManifestCoverage(resolver);\n }\n }\n this.#resolver = resolver;\n return this;\n }\n\n resolver(): SqlResolver | undefined {\n return this.#resolver;\n }\n\n get closed(): boolean {\n return this.#closed;\n }\n\n /**\n * Close owned database adapters exactly once and release runtime resources.\n * Externally supplied databases (owned: false) are not touched. Failures are\n * collected and reported with database identity rather than swallowed.\n */\n close(): Promise<void> {\n if (this.#closing) return this.#closing;\n this.#closed = true;\n this.#closing = Promise.resolve().then(async () => {\n const failures: string[] = [];\n const errors: unknown[] = [];\n const closed = new Set<Database>();\n for (const entry of this.#entries.values()) {\n if (!entry.owned || closed.has(entry.db)) continue;\n closed.add(entry.db);\n try { await entry.db.close(); }\n catch (error: any) {\n errors.push(error);\n failures.push(`\"${entry.name}\": ${error?.message ?? String(error)}`);\n }\n }\n for (const fam of this.#families.values()) {\n try { await fam.closeAll(); }\n catch (error: any) { errors.push(error); failures.push(error?.message ?? String(error)); }\n }\n this.#entries.clear();\n this.#families.clear();\n this.#resolver = undefined;\n if (failures.length) {\n throw Object.assign(new SqlStackError(`SqlStack close failed for ${failures.join(', ')}`), {\n errors: Object.freeze(errors), cause: errors[0],\n });\n }\n });\n return this.#closing;\n }\n\n /** Native IoC resource hook; manually calling close remains supported. */\n dispose(): Promise<void> { return this.close(); }\n\n #assertOpen(): void {\n if (this.#closed) {\n throw new SqlStackError('SqlStack has been closed; its owning root was disposed.');\n }\n }\n\n #registeredNames(): string {\n const names = [\n ...[...this.#entries.keys()].map((n) => `\"${n}\"`),\n ...[...this.#families.keys()].map((n) => `\"${n}\" (family)`),\n ];\n return names.length ? names.join(', ') : '(none)';\n }\n}\n"]}
|
|
@@ -40,6 +40,8 @@ declare class TxState {
|
|
|
40
40
|
sqliteBegin: 'BEGIN' | 'BEGIN IMMEDIATE';
|
|
41
41
|
/** Called once when the transaction releases its connection (SQLite queue turn). */
|
|
42
42
|
onRelease: (() => void) | undefined;
|
|
43
|
+
/** The @transaction root that opened (and will finish) this transaction, if any. */
|
|
44
|
+
ownerRoot: TxScope | undefined;
|
|
43
45
|
private txDb;
|
|
44
46
|
private releaseFn;
|
|
45
47
|
constructor(entry: DatabaseEntry, options: TransactionOptions | undefined);
|
|
@@ -72,6 +74,62 @@ export declare function hasTransactionContext(): boolean;
|
|
|
72
74
|
/** Active transaction handle for a concrete database entry, if any. */
|
|
73
75
|
export declare function currentTransactionFor(entry: DatabaseEntry): TransactionHandle | undefined;
|
|
74
76
|
export declare function withTransaction<T>(fn: () => Promise<T>, options?: TransactionOptions): Promise<T>;
|
|
77
|
+
/**
|
|
78
|
+
* One @transaction method invocation. The root scope (no parent) owns every
|
|
79
|
+
* transaction opened in the flow and commits/rolls them back at its exit; a
|
|
80
|
+
* nested scope is a piece of its parent, delimited by savepoints.
|
|
81
|
+
*/
|
|
82
|
+
declare class TxScope {
|
|
83
|
+
readonly parent: TxScope | undefined;
|
|
84
|
+
readonly root: TxScope;
|
|
85
|
+
readonly depth: number;
|
|
86
|
+
closed: boolean;
|
|
87
|
+
markAll: boolean;
|
|
88
|
+
readonly marked: Set<TxState>;
|
|
89
|
+
afterCommit: TransactionHook[];
|
|
90
|
+
afterSettled: TransactionHook[];
|
|
91
|
+
/** Nested scopes: the savepoint this scope holds on each open transaction. */
|
|
92
|
+
readonly savepoints: Array<{
|
|
93
|
+
state: TxState;
|
|
94
|
+
name: string;
|
|
95
|
+
}>;
|
|
96
|
+
/**
|
|
97
|
+
* Queries (open + statement) owned by this scope or a descendant that have
|
|
98
|
+
* not settled. Every scope drains its own before it closes: a nested scope
|
|
99
|
+
* before its savepoint cleanup, the root before commit/rollback, so no
|
|
100
|
+
* query publishes or writes after its scope's exit has started.
|
|
101
|
+
*/
|
|
102
|
+
readonly inFlight: Set<Promise<void>>;
|
|
103
|
+
/** Transactions opened in this flow, in open order (root commits them). */
|
|
104
|
+
readonly opened: TxState[];
|
|
105
|
+
/** Undefined: the root closed while the open was waiting, so it ran nothing. */
|
|
106
|
+
readonly opening: Map<DatabaseEntry, Promise<TxState | undefined>>;
|
|
107
|
+
/** Databases this root has opened (multi_database event), with their reported names. */
|
|
108
|
+
readonly seen: Array<{
|
|
109
|
+
entry: DatabaseEntry;
|
|
110
|
+
name: string;
|
|
111
|
+
}>;
|
|
112
|
+
savepointSeq: number;
|
|
113
|
+
/**
|
|
114
|
+
* Root-only: settles once the root's transactions have been committed or
|
|
115
|
+
* rolled back and released (before its hooks run). A query that arrives
|
|
116
|
+
* after the root closed waits for this instead of joining a transaction
|
|
117
|
+
* that is being torn down.
|
|
118
|
+
*/
|
|
119
|
+
readonly tornDown: Promise<void>;
|
|
120
|
+
private resolveTornDown;
|
|
121
|
+
/** Siblings share one savepoint stack; descendants queue on their own parent. */
|
|
122
|
+
private childTail;
|
|
123
|
+
constructor(parent: TxScope | undefined);
|
|
124
|
+
markTornDown(): void;
|
|
125
|
+
get hasMarks(): boolean;
|
|
126
|
+
isMarked(state: TxState): boolean;
|
|
127
|
+
reserveChild(): {
|
|
128
|
+
ready: Promise<void>;
|
|
129
|
+
release: () => void;
|
|
130
|
+
};
|
|
131
|
+
waitForChildren(): Promise<void>;
|
|
132
|
+
}
|
|
75
133
|
/**
|
|
76
134
|
* Observe transaction trace events. Today the only event is
|
|
77
135
|
* `sqlstack.transaction.multi_database`, emitted once per root scope the
|
|
@@ -85,6 +143,9 @@ export declare function onTransactionEvent(listener: TransactionEventListener):
|
|
|
85
143
|
* while a @transaction scope is active — one opened on that entry by the
|
|
86
144
|
* query itself (on first execution, not on resolution). Undefined means "run
|
|
87
145
|
* on the database directly".
|
|
146
|
+
*
|
|
147
|
+
* Inside a scope every query — on a transaction already open or one it opens —
|
|
148
|
+
* is tracked by its owning scope, so the scope's exit waits for it.
|
|
88
149
|
*/
|
|
89
150
|
export declare function getTransactionTarget(entry: DatabaseEntry): ActiveTransaction | undefined;
|
|
90
151
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transactions.d.ts","sourceRoot":"","sources":["../../src/transactions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAGxD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAG7C,MAAM,MAAM,kBAAkB,GAAG;IAC/B,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,IAAI,CAAC,EAAE,OAAO,CAAC;IAC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,aAAa,GAAG,iBAAiB,GAAG,SAAS,CAGxF;AAED;;;;;;GAMG;AACH,wBAAgB,+BAA+B,CAAC,EAAE,EAAE,MAAM,GAAG,iBAAiB,GAAG,SAAS,CAOzF"}
|
package/dist/cjs/transactions.js
CHANGED
|
@@ -338,9 +338,17 @@ class TxScope {
|
|
|
338
338
|
this.afterSettled = [];
|
|
339
339
|
/** Nested scopes: the savepoint this scope holds on each open transaction. */
|
|
340
340
|
this.savepoints = [];
|
|
341
|
+
/**
|
|
342
|
+
* Queries (open + statement) owned by this scope or a descendant that have
|
|
343
|
+
* not settled. Every scope drains its own before it closes: a nested scope
|
|
344
|
+
* before its savepoint cleanup, the root before commit/rollback, so no
|
|
345
|
+
* query publishes or writes after its scope's exit has started.
|
|
346
|
+
*/
|
|
347
|
+
this.inFlight = new Set();
|
|
341
348
|
// Root-only bookkeeping.
|
|
342
349
|
/** Transactions opened in this flow, in open order (root commits them). */
|
|
343
350
|
this.opened = [];
|
|
351
|
+
/** Undefined: the root closed while the open was waiting, so it ran nothing. */
|
|
344
352
|
this.opening = new Map();
|
|
345
353
|
/** Databases this root has opened (multi_database event), with their reported names. */
|
|
346
354
|
this.seen = [];
|
|
@@ -350,6 +358,12 @@ class TxScope {
|
|
|
350
358
|
this.parent = parent;
|
|
351
359
|
this.root = parent ? parent.root : this;
|
|
352
360
|
this.depth = parent ? parent.depth + 1 : 1;
|
|
361
|
+
this.tornDown = new Promise((resolve) => {
|
|
362
|
+
this.resolveTornDown = resolve;
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
markTornDown() {
|
|
366
|
+
this.resolveTornDown();
|
|
353
367
|
}
|
|
354
368
|
get hasMarks() {
|
|
355
369
|
return this.markAll || this.marked.size > 0;
|
|
@@ -373,6 +387,36 @@ class TxScope {
|
|
|
373
387
|
} while (observed !== this.childTail);
|
|
374
388
|
}
|
|
375
389
|
}
|
|
390
|
+
/**
|
|
391
|
+
* The scope a query issued under `scope` belongs to now: `scope` itself, or
|
|
392
|
+
* its nearest ancestor that has not closed (a query can outlive the nested
|
|
393
|
+
* scope it was issued in). Undefined once the root has closed.
|
|
394
|
+
*/
|
|
395
|
+
function owningScope(scope) {
|
|
396
|
+
let s = scope;
|
|
397
|
+
while (s && s.closed)
|
|
398
|
+
s = s.parent;
|
|
399
|
+
return s;
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Run one scope query, registered in `inFlight` of `owner` and every ancestor
|
|
403
|
+
* until it settles. Callers pick `owner` with owningScope() and call this with
|
|
404
|
+
* no await in between, so registration and the closed check are one step.
|
|
405
|
+
*/
|
|
406
|
+
function trackQuery(owner, work) {
|
|
407
|
+
const result = work();
|
|
408
|
+
const settled = result.then(() => undefined, () => undefined);
|
|
409
|
+
const scopes = [];
|
|
410
|
+
for (let s = owner; s; s = s.parent) {
|
|
411
|
+
s.inFlight.add(settled);
|
|
412
|
+
scopes.push(s);
|
|
413
|
+
}
|
|
414
|
+
void settled.then(() => {
|
|
415
|
+
for (const s of scopes)
|
|
416
|
+
s.inFlight.delete(settled);
|
|
417
|
+
});
|
|
418
|
+
return result;
|
|
419
|
+
}
|
|
376
420
|
const eventListeners = new Set();
|
|
377
421
|
/**
|
|
378
422
|
* Observe transaction trace events. Today the only event is
|
|
@@ -499,6 +543,10 @@ function reportedName(store, entry) {
|
|
|
499
543
|
}
|
|
500
544
|
return HANDLE_LABEL;
|
|
501
545
|
}
|
|
546
|
+
/**
|
|
547
|
+
* Undefined when the root closed while this open was waiting: nothing was left
|
|
548
|
+
* open, and the caller runs the statement on the database directly.
|
|
549
|
+
*/
|
|
502
550
|
async function openScopedTransaction(store, scope, entry) {
|
|
503
551
|
const existing = findOpenTransaction(store, entry);
|
|
504
552
|
if (existing)
|
|
@@ -516,6 +564,12 @@ async function openScopedTransaction(store, scope, entry) {
|
|
|
516
564
|
if (dialect === 'sqlite' && !holdsConnection) {
|
|
517
565
|
state.onRelease = await acquireSqliteTurn(entry.db);
|
|
518
566
|
}
|
|
567
|
+
// Backstop: the root drains in-flight queries before closing, so this
|
|
568
|
+
// should not happen; if it does, hand the turn straight back.
|
|
569
|
+
if (root.closed) {
|
|
570
|
+
await state.release();
|
|
571
|
+
return undefined;
|
|
572
|
+
}
|
|
519
573
|
try {
|
|
520
574
|
await state.ensureStarted();
|
|
521
575
|
}
|
|
@@ -553,6 +607,24 @@ async function openScopedTransaction(store, scope, entry) {
|
|
|
553
607
|
}
|
|
554
608
|
throw err;
|
|
555
609
|
}
|
|
610
|
+
// Backstop: started, but the root has already committed/rolled back and
|
|
611
|
+
// nobody would ever finish it. Roll it back and release it now. No await
|
|
612
|
+
// between this check and the publish below.
|
|
613
|
+
if (root.closed) {
|
|
614
|
+
for (const s of chain) {
|
|
615
|
+
for (let j = s.savepoints.length - 1; j >= 0; j--)
|
|
616
|
+
if (s.savepoints[j].state === state)
|
|
617
|
+
s.savepoints.splice(j, 1);
|
|
618
|
+
}
|
|
619
|
+
try {
|
|
620
|
+
await state.rollbackIfStarted();
|
|
621
|
+
}
|
|
622
|
+
finally {
|
|
623
|
+
await state.release();
|
|
624
|
+
}
|
|
625
|
+
return undefined;
|
|
626
|
+
}
|
|
627
|
+
state.ownerRoot = root;
|
|
556
628
|
store.txByDb.set(entry, state);
|
|
557
629
|
root.opened.push(state);
|
|
558
630
|
if (!root.seen.some((s) => sameTransactionTarget(entry, s.entry))) {
|
|
@@ -580,24 +652,64 @@ async function openScopedTransaction(store, scope, entry) {
|
|
|
580
652
|
* while a @transaction scope is active — one opened on that entry by the
|
|
581
653
|
* query itself (on first execution, not on resolution). Undefined means "run
|
|
582
654
|
* on the database directly".
|
|
655
|
+
*
|
|
656
|
+
* Inside a scope every query — on a transaction already open or one it opens —
|
|
657
|
+
* is tracked by its owning scope, so the scope's exit waits for it.
|
|
583
658
|
*/
|
|
584
659
|
function getTransactionTarget(entry) {
|
|
585
660
|
const store = getStore();
|
|
586
|
-
|
|
587
|
-
if (open)
|
|
588
|
-
return open;
|
|
589
|
-
const scope = activeScope(store);
|
|
590
|
-
if (!store || !scope)
|
|
661
|
+
if (!store)
|
|
591
662
|
return undefined;
|
|
663
|
+
// The flow's innermost scope, closed or not: the wrapper decides at query time.
|
|
664
|
+
const scope = store.scope;
|
|
665
|
+
if (!scope)
|
|
666
|
+
return findOpenTransaction(store, entry);
|
|
592
667
|
return {
|
|
593
668
|
async query(sql, params) {
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
669
|
+
const owner = owningScope(scope);
|
|
670
|
+
if (!owner) {
|
|
671
|
+
return await queryAfterRootClosed(() => findOpenTransaction(store, entry), async () => await entry.db.query(sql, params), sql, params);
|
|
672
|
+
}
|
|
673
|
+
// Registered in the same synchronous step as the closed check.
|
|
674
|
+
return await trackQuery(owner, async () => {
|
|
675
|
+
const state = await openScopedTransaction(store, owner, entry);
|
|
676
|
+
if (!state)
|
|
677
|
+
return await entry.db.query(sql, params);
|
|
678
|
+
return await state.query(sql, params);
|
|
679
|
+
});
|
|
598
680
|
},
|
|
599
681
|
};
|
|
600
682
|
}
|
|
683
|
+
function findStateForDatabase(store, db) {
|
|
684
|
+
for (const state of store.txByDb.values()) {
|
|
685
|
+
if (state.db === db)
|
|
686
|
+
return state;
|
|
687
|
+
}
|
|
688
|
+
return undefined;
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* A query whose scope chain has fully closed. It never joins a transaction a
|
|
692
|
+
* closed root still owns (its COMMIT/ROLLBACK and release may be in flight, and
|
|
693
|
+
* the query is not tracked by anything): it waits for that root's teardown and
|
|
694
|
+
* looks again — by then the transaction is gone from the flow. A transaction
|
|
695
|
+
* that genuinely encloses the query (an outer withTransaction) is joined.
|
|
696
|
+
*/
|
|
697
|
+
async function queryAfterRootClosed(find, direct, sql, params) {
|
|
698
|
+
const waited = new Set();
|
|
699
|
+
for (;;) {
|
|
700
|
+
const open = find();
|
|
701
|
+
const closing = open?.ownerRoot;
|
|
702
|
+
if (closing && closing.closed) {
|
|
703
|
+
// Torn down already and still listed: never join it; run directly.
|
|
704
|
+
if (waited.has(closing))
|
|
705
|
+
return await direct();
|
|
706
|
+
waited.add(closing);
|
|
707
|
+
await closing.tornDown;
|
|
708
|
+
continue;
|
|
709
|
+
}
|
|
710
|
+
return open ? await open.query(sql, params) : await direct();
|
|
711
|
+
}
|
|
712
|
+
}
|
|
601
713
|
/**
|
|
602
714
|
* @internal The transaction a query on a Database handle (run(db, ...)) runs
|
|
603
715
|
* in. A transaction already open in this flow on that exact object is joined
|
|
@@ -610,19 +722,25 @@ function getTransactionTargetForHandle(db) {
|
|
|
610
722
|
const store = getStore();
|
|
611
723
|
if (!store)
|
|
612
724
|
return undefined;
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
return state;
|
|
616
|
-
}
|
|
617
|
-
const scope = activeScope(store);
|
|
725
|
+
// The flow's innermost scope, closed or not: the wrapper decides at query time.
|
|
726
|
+
const scope = store.scope;
|
|
618
727
|
if (!scope)
|
|
619
|
-
return
|
|
728
|
+
return findStateForDatabase(store, db);
|
|
620
729
|
return {
|
|
621
730
|
async query(sql, params) {
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
731
|
+
const owner = owningScope(scope);
|
|
732
|
+
if (!owner) {
|
|
733
|
+
return await queryAfterRootClosed(() => findStateForDatabase(store, db), async () => (await db.query(sql, params)), sql, params);
|
|
734
|
+
}
|
|
735
|
+
// Registered in the same synchronous step as the closed check. An open
|
|
736
|
+
// transaction on this object (registered or handle-opened) is joined by
|
|
737
|
+
// openScopedTransaction's identity lookup.
|
|
738
|
+
return await trackQuery(owner, async () => {
|
|
739
|
+
const state = await openScopedTransaction(store, owner, handleEntryFor(db));
|
|
740
|
+
if (!state)
|
|
741
|
+
return (await db.query(sql, params));
|
|
742
|
+
return await state.query(sql, params);
|
|
743
|
+
});
|
|
626
744
|
},
|
|
627
745
|
};
|
|
628
746
|
}
|
|
@@ -684,6 +802,7 @@ async function exitRootOnSuccess(root, store) {
|
|
|
684
802
|
if (legacyMarked) {
|
|
685
803
|
const err = typeof legacyMarked.rollbackError !== 'undefined' ? legacyMarked.rollbackError : new errors_1.RollbackTransactionError();
|
|
686
804
|
await rollbackOwned(root, store);
|
|
805
|
+
root.markTornDown();
|
|
687
806
|
await runHooks(root.afterSettled);
|
|
688
807
|
throw err;
|
|
689
808
|
}
|
|
@@ -716,6 +835,7 @@ async function exitRootOnSuccess(root, store) {
|
|
|
716
835
|
}
|
|
717
836
|
}
|
|
718
837
|
root.opened.length = 0;
|
|
838
|
+
root.markTornDown();
|
|
719
839
|
const commitHooks = !failed && !root.hasMarks ? await runHooks(root.afterCommit) : { failed: false, error: undefined };
|
|
720
840
|
const settledHooks = await runHooks(root.afterSettled);
|
|
721
841
|
if (failed)
|
|
@@ -727,6 +847,7 @@ async function exitRootOnSuccess(root, store) {
|
|
|
727
847
|
}
|
|
728
848
|
async function exitRootOnError(root, store) {
|
|
729
849
|
await rollbackOwned(root, store);
|
|
850
|
+
root.markTornDown();
|
|
730
851
|
await runHooks(root.afterSettled);
|
|
731
852
|
}
|
|
732
853
|
async function exitNestedOnSuccess(scope) {
|
|
@@ -760,6 +881,22 @@ async function exitNestedOnError(scope) {
|
|
|
760
881
|
}
|
|
761
882
|
scope.parent.afterSettled.push(...scope.afterSettled);
|
|
762
883
|
}
|
|
884
|
+
/**
|
|
885
|
+
* Wait for child scopes and for every query this scope (or a descendant) still
|
|
886
|
+
* has in flight (opening or running), then close. The emptiness check and
|
|
887
|
+
* `closed = true` share one synchronous step, so no query can register in
|
|
888
|
+
* between: a nested scope's savepoint cleanup and the root's commit/rollback
|
|
889
|
+
* see every write made under them.
|
|
890
|
+
*/
|
|
891
|
+
async function closeWhenIdle(scope) {
|
|
892
|
+
for (;;) {
|
|
893
|
+
await scope.waitForChildren();
|
|
894
|
+
if (scope.inFlight.size === 0)
|
|
895
|
+
break;
|
|
896
|
+
await Promise.all([...scope.inFlight]);
|
|
897
|
+
}
|
|
898
|
+
scope.closed = true;
|
|
899
|
+
}
|
|
763
900
|
async function runInScope(fn) {
|
|
764
901
|
const outer = getStore();
|
|
765
902
|
const parent = activeScope(outer);
|
|
@@ -784,9 +921,9 @@ async function runInScope(fn) {
|
|
|
784
921
|
}
|
|
785
922
|
catch (err) {
|
|
786
923
|
// Promise.all may reject while another child is still writing. Keep this
|
|
787
|
-
// scope active until those children
|
|
788
|
-
|
|
789
|
-
scope
|
|
924
|
+
// scope active until those children (and, on a root, queries still
|
|
925
|
+
// opening or running) settle, then roll back their work too.
|
|
926
|
+
await closeWhenIdle(scope);
|
|
790
927
|
if (parent) {
|
|
791
928
|
await exitNestedOnError(scope);
|
|
792
929
|
throw err;
|
|
@@ -794,8 +931,7 @@ async function runInScope(fn) {
|
|
|
794
931
|
await exitRootOnError(scope, store);
|
|
795
932
|
throw isRollbackTransactionError(err) ? unwrapRollbackCause(err) : err;
|
|
796
933
|
}
|
|
797
|
-
await scope
|
|
798
|
-
scope.closed = true;
|
|
934
|
+
await closeWhenIdle(scope);
|
|
799
935
|
if (parent)
|
|
800
936
|
await exitNestedOnSuccess(scope);
|
|
801
937
|
else
|
|
@@ -804,6 +940,9 @@ async function runInScope(fn) {
|
|
|
804
940
|
});
|
|
805
941
|
}
|
|
806
942
|
finally {
|
|
943
|
+
// Never leave a late query waiting on a root that exited abnormally.
|
|
944
|
+
if (!parent)
|
|
945
|
+
scope.markTornDown();
|
|
807
946
|
// Release only after savepoint cleanup and descendants, on success or failure.
|
|
808
947
|
turn?.release();
|
|
809
948
|
}
|