sqlstack 3.3.0 → 3.5.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/adapters/sqlite.d.ts.map +1 -1
- package/dist/cjs/adapters/sqlite.js +4 -1
- package/dist/cjs/adapters/sqlite.js.map +1 -1
- package/dist/cjs/core/errors.d.ts +9 -0
- package/dist/cjs/core/errors.d.ts.map +1 -1
- package/dist/cjs/core/errors.js +10 -0
- package/dist/cjs/core/errors.js.map +1 -1
- package/dist/cjs/decorators/query.d.ts +14 -0
- package/dist/cjs/decorators/query.d.ts.map +1 -1
- package/dist/cjs/decorators/query.js +124 -17
- package/dist/cjs/decorators/query.js.map +1 -1
- package/dist/cjs/index.d.ts +2 -1
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +4 -2
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/run.d.ts +140 -6
- package/dist/cjs/run.d.ts.map +1 -1
- package/dist/cjs/run.js +127 -17
- package/dist/cjs/run.js.map +1 -1
- package/dist/cjs/runtime.d.ts +8 -0
- package/dist/cjs/runtime.d.ts.map +1 -1
- package/dist/cjs/runtime.js +12 -0
- package/dist/cjs/runtime.js.map +1 -1
- package/dist/cjs/sql.d.ts +19 -0
- package/dist/cjs/sql.d.ts.map +1 -1
- package/dist/cjs/sql.js +66 -28
- package/dist/cjs/sql.js.map +1 -1
- package/dist/cjs/stack.d.ts +2 -0
- package/dist/cjs/stack.d.ts.map +1 -1
- package/dist/cjs/stack.js +40 -27
- package/dist/cjs/stack.js.map +1 -1
- package/dist/cjs/testing/builder.d.ts.map +1 -1
- package/dist/cjs/testing/builder.js +14 -5
- package/dist/cjs/testing/builder.js.map +1 -1
- package/dist/cjs/testing/fixture-provenance.d.ts +3 -0
- package/dist/cjs/testing/fixture-provenance.d.ts.map +1 -0
- package/dist/cjs/testing/fixture-provenance.js +21 -0
- package/dist/cjs/testing/fixture-provenance.js.map +1 -0
- package/dist/cjs/testing/index.d.ts +2 -0
- package/dist/cjs/testing/index.d.ts.map +1 -1
- package/dist/cjs/testing/index.js +5 -1
- package/dist/cjs/testing/index.js.map +1 -1
- package/dist/cjs/testing/postgres/database.d.ts +9 -1
- package/dist/cjs/testing/postgres/database.d.ts.map +1 -1
- package/dist/cjs/testing/postgres/database.js +17 -13
- package/dist/cjs/testing/postgres/database.js.map +1 -1
- package/dist/cjs/testing/resource.d.ts +76 -0
- package/dist/cjs/testing/resource.d.ts.map +1 -0
- package/dist/cjs/testing/resource.js +117 -0
- package/dist/cjs/testing/resource.js.map +1 -0
- package/dist/cjs/testing/sqlite/builder.d.ts.map +1 -1
- package/dist/cjs/testing/sqlite/builder.js +10 -2
- package/dist/cjs/testing/sqlite/builder.js.map +1 -1
- package/dist/cjs/testing/sqlite/database.d.ts +11 -1
- package/dist/cjs/testing/sqlite/database.d.ts.map +1 -1
- package/dist/cjs/testing/sqlite/database.js +32 -18
- package/dist/cjs/testing/sqlite/database.js.map +1 -1
- package/dist/cjs/transactions.d.ts +14 -0
- package/dist/cjs/transactions.d.ts.map +1 -1
- package/dist/cjs/transactions.js +27 -0
- package/dist/cjs/transactions.js.map +1 -1
- package/dist/esm/adapters/sqlite.js +4 -1
- package/dist/esm/adapters/sqlite.js.map +1 -1
- package/dist/esm/core/errors.js +10 -0
- package/dist/esm/core/errors.js.map +1 -1
- package/dist/esm/decorators/query.js +127 -20
- package/dist/esm/decorators/query.js.map +1 -1
- package/dist/esm/index.js +3 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/run.js +123 -18
- package/dist/esm/run.js.map +1 -1
- package/dist/esm/runtime.js +11 -0
- package/dist/esm/runtime.js.map +1 -1
- package/dist/esm/sql.js +63 -27
- package/dist/esm/sql.js.map +1 -1
- package/dist/esm/stack.js +40 -27
- package/dist/esm/stack.js.map +1 -1
- package/dist/esm/testing/builder.js +14 -5
- package/dist/esm/testing/builder.js.map +1 -1
- package/dist/esm/testing/fixture-provenance.js +15 -0
- package/dist/esm/testing/fixture-provenance.js.map +1 -0
- package/dist/esm/testing/index.js +1 -0
- package/dist/esm/testing/index.js.map +1 -1
- package/dist/esm/testing/postgres/database.js +17 -13
- package/dist/esm/testing/postgres/database.js.map +1 -1
- package/dist/esm/testing/resource.js +106 -0
- package/dist/esm/testing/resource.js.map +1 -0
- package/dist/esm/testing/sqlite/builder.js +10 -2
- package/dist/esm/testing/sqlite/builder.js.map +1 -1
- package/dist/esm/testing/sqlite/database.js +32 -18
- package/dist/esm/testing/sqlite/database.js.map +1 -1
- package/dist/esm/transactions.js +25 -0
- package/dist/esm/transactions.js.map +1 -1
- package/package.json +1 -1
- package/readme.md +128 -39
package/dist/cjs/transactions.js
CHANGED
|
@@ -14,9 +14,11 @@ var _TransactionHandle_state, _TransactionHandle_owned, _TransactionHandle_finis
|
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
exports.transaction = exports.TransactionHandle = void 0;
|
|
16
16
|
exports.currentTransaction = currentTransaction;
|
|
17
|
+
exports.hasTransactionContext = hasTransactionContext;
|
|
17
18
|
exports.currentTransactionFor = currentTransactionFor;
|
|
18
19
|
exports.withTransaction = withTransaction;
|
|
19
20
|
exports.getActiveTransaction = getActiveTransaction;
|
|
21
|
+
exports.getActiveTransactionForDatabase = getActiveTransactionForDatabase;
|
|
20
22
|
const node_async_hooks_1 = require("node:async_hooks");
|
|
21
23
|
const adapters_1 = require("./adapters");
|
|
22
24
|
const errors_1 = require("./core/errors");
|
|
@@ -238,6 +240,14 @@ function currentTransaction(db) {
|
|
|
238
240
|
return undefined;
|
|
239
241
|
return new TransactionHandle(entry, state, false);
|
|
240
242
|
}
|
|
243
|
+
/**
|
|
244
|
+
* Whether this async call carries any transaction records. This observation
|
|
245
|
+
* never resolves a database, opens a connection, or consults legacy defaults.
|
|
246
|
+
* It does not choose an owner: use currentTransactionFor(entry) for that.
|
|
247
|
+
*/
|
|
248
|
+
function hasTransactionContext() {
|
|
249
|
+
return (getStore()?.txByDb.size ?? 0) > 0;
|
|
250
|
+
}
|
|
241
251
|
/** Active transaction handle for a concrete database entry, if any. */
|
|
242
252
|
function currentTransactionFor(entry) {
|
|
243
253
|
const store = getStore();
|
|
@@ -288,4 +298,21 @@ function getActiveTransaction(entry) {
|
|
|
288
298
|
const store = getStore();
|
|
289
299
|
return store?.txByDb.get(entry);
|
|
290
300
|
}
|
|
301
|
+
/**
|
|
302
|
+
* Active transaction whose registered database is exactly `db` (object
|
|
303
|
+
* identity), if any. `run(db, ...)` uses this so a handle passed at call time
|
|
304
|
+
* joins a transaction opened on the same database (by `@transaction` or
|
|
305
|
+
* `withTransaction`) instead of bypassing it. A handle that was never
|
|
306
|
+
* registered with a SqlStack (or the legacy registry) never matches.
|
|
307
|
+
*/
|
|
308
|
+
function getActiveTransactionForDatabase(db) {
|
|
309
|
+
const store = getStore();
|
|
310
|
+
if (!store)
|
|
311
|
+
return undefined;
|
|
312
|
+
for (const state of store.txByDb.values()) {
|
|
313
|
+
if (state.db === db)
|
|
314
|
+
return state;
|
|
315
|
+
}
|
|
316
|
+
return undefined;
|
|
317
|
+
}
|
|
291
318
|
//# sourceMappingURL=transactions.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transactions.js","sourceRoot":"","sources":["../../src/transactions.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAsPA,gDAOC;AAGD,sDAKC;AAED,0CAkBC;AAgCD,oDAGC;AA5TD,uDAAqD;AAErD,yCAAuD;AACvD,0CAAwE;AAExE,uCAA0D;AAe1D,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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AE,CAAC;QAC9D,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,IAAkD,CAAC;QAChF,UAAU,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;QAC1C,OAAO;IACT,CAAC;IACD,0CAA0C;IAC1C,MAAM,OAAO,GAAmC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACtF,OAAO,UAAU,MAAW,EAAE,IAAqB,EAAE,IAAwB;QAC3E,UAAU,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;IAC1C,CAAC,CAAC;AACJ,CAAQ,CAAC;AAET,SAAS,UAAU,CAAC,OAAY,EAAE,KAAsB,EAAE,IAAwB,EAAE,OAA4B;IAC9G,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC;IAC5B,IAAI,CAAC,KAAK,GAAG,KAAK,WAAW,GAAG,QAAe;QAC7C,OAAO,MAAM,eAAe,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAC;IAC9E,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","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// 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).\ntype TxStore = {\n txByDb: Map<DatabaseEntry, TxState>;\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\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\n await this.db.query('BEGIN', []);\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 }\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/** 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\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\nexport const transaction: 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} as any;\n\nfunction wrapMethod(_target: any, _prop: string | symbol, desc: PropertyDescriptor, options?: TransactionOptions) {\n const original = desc.value;\n desc.value = async function (...callArgs: any[]) {\n return await withTransaction(() => original.apply(this, callArgs), options);\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"]}
|
|
1
|
+
{"version":3,"file":"transactions.js","sourceRoot":"","sources":["../../src/transactions.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAsPA,gDAOC;AAOD,sDAEC;AAGD,sDAKC;AAED,0CAkBC;AAgCD,oDAGC;AASD,0EAOC;AArVD,uDAAqD;AAErD,yCAAuD;AACvD,0CAAwE;AAExE,uCAA0D;AAe1D,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,E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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// 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).\ntype TxStore = {\n txByDb: Map<DatabaseEntry, TxState>;\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\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\n await this.db.query('BEGIN', []);\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 }\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\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\nexport const transaction: 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} as any;\n\nfunction wrapMethod(_target: any, _prop: string | symbol, desc: PropertyDescriptor, options?: TransactionOptions) {\n const original = desc.value;\n desc.value = async function (...callArgs: any[]) {\n return await withTransaction(() => original.apply(this, callArgs), options);\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"]}
|
|
@@ -219,7 +219,10 @@ export async function createSqliteDb(filenameOrDb) {
|
|
|
219
219
|
else {
|
|
220
220
|
try {
|
|
221
221
|
// @ts-ignore optional dependency without types
|
|
222
|
-
|
|
222
|
+
// Optional fallback: defer resolution to runtime rather than making
|
|
223
|
+
// bundlers require sqlite3 when the preferred driver is installed.
|
|
224
|
+
const packageName = 'sqlite3';
|
|
225
|
+
const mod = await import(/* @vite-ignore */ packageName);
|
|
223
226
|
sqlite3 = mod.default ?? mod;
|
|
224
227
|
}
|
|
225
228
|
catch {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sqlite.js","sourceRoot":"","sources":["../../../src/adapters/sqlite.ts"],"names":[],"mappings":"AAEA,SAAS,aAAa,CAAI,KAAc;IACtC,OAAO,CAAC,CAAC,KAAK,IAAI,OAAQ,KAAoB,CAAC,IAAI,KAAK,UAAU,CAAC;AACrE,CAAC;AAED,KAAK,UAAU,gBAAgB,CAAC,EAAO,EAAE,GAAW;IAClD,MAAM,IAAI,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAC7B,OAAO,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MA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AAE,CAAC,CAAC;wBACtB,CAAC,CAAC,CAAC;oBACL,CAAC,CAAC,CAAC;gBACL,CAAC;gBACD,wBAAwB;gBACxB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;oBACrC,EAAE,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,UAAqB,GAAiB;wBACxD,IAAI,GAAG;4BAAE,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;wBAC5B,OAAO,CAAC,EAAE,YAAY,EAAE,MAAM,CAAC,IAAI,EAAE,OAAO,IAAI,CAAC,CAAC,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;oBACpF,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;YACL,CAAC;YACD,IAAI,EAAE,EAAE;YACR,KAAK;gBACH,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;oBAC3C,EAAE,CAAC,KAAK,CAAC,CAAC,GAAiB,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;gBACnE,CAAC,CAAC,CAAC;YACL,CAAC;SACU,CAAC;IAChB,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAC;AAC3F,CAAC","sourcesContent":["import type { Database } from '../registry';\n\nfunction isPromiseLike<T>(value: unknown): value is Promise<T> {\n return !!value && typeof (value as Promise<T>).then === 'function';\n}\n\nasync function prepareStatement(db: any, sql: string) {\n const stmt = db.prepare(sql);\n return isPromiseLike(stmt) ? await stmt : stmt;\n}\n\nasync function finalizeStatement(stmt: any) {\n if (!stmt || typeof stmt.finalize !== 'function') return;\n const result = stmt.finalize();\n if (isPromiseLike(result)) {\n await result;\n }\n}\n\nasync function statementAll(stmt: any, params: unknown[]) {\n if (typeof stmt.all !== 'function') {\n throw new Error('SQLite statement missing all()');\n }\n if (stmt.all.length >= 2) {\n return await new Promise((resolve, reject) => {\n const callback = (err: Error | null, rows: any[]) => {\n if (err) return reject(err);\n resolve(rows || []);\n };\n try {\n if (params.length > 0) {\n stmt.all(params, callback);\n } else {\n stmt.all(callback);\n }\n } catch (error) {\n reject(error);\n }\n });\n }\n const result = stmt.all(...(params as any[]));\n return isPromiseLike(result) ? await result : result;\n}\n\nasync function statementRun(stmt: any, params: unknown[]) {\n if (typeof stmt.run !== 'function') {\n throw new Error('SQLite statement missing run()');\n }\n if (stmt.run.length >= 2) {\n return await new Promise((resolve, reject) => {\n const callback = function (this: any, err: Error | null) {\n if (err) return reject(err);\n resolve({ changes: this?.changes ?? 0, lastInsertId: this?.lastID });\n };\n try {\n if (params.length > 0) {\n stmt.run(params, callback);\n } else {\n stmt.run(callback);\n }\n } catch (error) {\n reject(error);\n }\n });\n }\n const result = stmt.run(...(params as any[]));\n return isPromiseLike(result) ? await result : result;\n}\n\nfunction stripLeadingComments(sql: string): string {\n let i = 0;\n const n = sql.length;\n if (sql.charCodeAt(0) === 0xfeff) i = 1; // BOM\n while (i < n) {\n while (i < n && /\\s/.test(sql[i]!)) i++;\n if (i + 1 < n && sql[i] === '-' && sql[i + 1] === '-') {\n // -- line comment\n i += 2;\n while (i < n && sql[i] !== '\\n') i++;\n continue;\n }\n if (i + 1 < n && sql[i] === '/' && sql[i + 1] === '*') {\n // /* block comment */\n i += 2;\n const end = sql.indexOf('*/', i);\n if (end === -1) return '';\n i = end + 2;\n continue;\n }\n break;\n }\n return sql.slice(i);\n}\n\n// Text-based fallback for drivers that do not expose statement metadata\n// (the sqlite3 callback API). SELECT, CTEs, and `... RETURNING` all produce\n// a result set and must be executed with all(), not run().\nfunction producesRows(sql: string): boolean {\n const text = stripLeadingComments(String(sql)).trimStart().toUpperCase();\n return text.startsWith('SELECT') || text.startsWith('WITH') || /\\bRETURNING\\b/.test(text);\n}\n\n// better-sqlite3 exposes `stmt.reader` (true when the statement returns rows).\nfunction statementReturnsRows(stmt: any, sql: string): boolean {\n return typeof stmt?.reader === 'boolean' ? stmt.reader : producesRows(sql);\n}\n\nexport async function createSqliteDb(filenameOrDb: string | any): Promise<Database> {\n // If a pre-created connection is provided\n if (typeof filenameOrDb !== 'string' && filenameOrDb) {\n const db = filenameOrDb;\n\n // better-sqlite3 shape\n if (typeof db.prepare === 'function') {\n return {\n dialect: 'sqlite',\n async query(sql: string, params: unknown[]) {\n const stmt = await prepareStatement(db, sql);\n try {\n if (statementReturnsRows(stmt, sql)) {\n const rows = await statementAll(stmt, params);\n return rows;\n }\n const info = await statementRun(stmt, params);\n const rowsAffected = Number(info?.changes ?? info?.rowsAffected ?? 0);\n const lastInsertId = info?.lastInsertRowid ?? info?.lastID ?? info?.lastInsertId;\n return { rowsAffected, lastInsertId };\n } finally {\n await finalizeStatement(stmt);\n }\n },\n conn: db,\n // Do not close externally provided connection\n async close() {\n if (typeof db.close === 'function') {\n const res = db.close();\n if (isPromiseLike(res)) {\n await res;\n }\n }\n },\n } as Database;\n }\n\n // sqlite3 shape\n return {\n dialect: 'sqlite',\n async query(sql: string, params: unknown[]) {\n if (producesRows(sql)) {\n return new Promise<any[]>((resolve, reject) => {\n db.all(sql, params, (err: Error | null, rows: any[]) => {\n if (err) return reject(err);\n resolve(rows || []);\n });\n });\n }\n return new Promise((resolve, reject) => {\n // Use function callback to access `this` for metadata\n db.run(sql, params, function (this: any, err: Error | null) {\n if (err) return reject(err);\n resolve({ rowsAffected: Number(this?.changes ?? 0), lastInsertId: this?.lastID });\n });\n });\n },\n conn: db,\n // Do not close externally provided connection\n close() {},\n } as Database;\n }\n\n const filename = filenameOrDb as string;\n\n let BetterSqlite3: any;\n if (typeof require === 'function') {\n try {\n BetterSqlite3 = require('better-sqlite3');\n } catch {\n BetterSqlite3 = null;\n }\n } else {\n try {\n // @ts-ignore optional dependency without types\n const mod = await import('better-sqlite3');\n BetterSqlite3 = (mod as any).default ?? mod;\n } catch {\n BetterSqlite3 = null;\n }\n }\n\n if (BetterSqlite3) {\n const db = new BetterSqlite3(filename);\n return {\n dialect: 'sqlite',\n async query(sql: string, params: unknown[]) {\n const stmt = db.prepare(sql);\n if (statementReturnsRows(stmt, sql)) {\n return stmt.all(...params);\n }\n const info = stmt.run(...params);\n return { rowsAffected: Number(info?.changes ?? 0), lastInsertId: info?.lastInsertRowid };\n },\n conn: db,\n close() {\n db.close();\n },\n } as Database;\n }\n\n let sqlite3: any;\n if (typeof require === 'function') {\n try {\n sqlite3 = require('sqlite3');\n } catch {\n sqlite3 = null;\n }\n } else {\n try {\n // @ts-ignore optional dependency without types\n const mod = await import('sqlite3');\n sqlite3 = (mod as any).default ?? mod;\n } catch {\n sqlite3 = null;\n }\n }\n\n if (sqlite3) {\n const db = new sqlite3.Database(filename);\n return {\n dialect: 'sqlite',\n async query(sql: string, params: unknown[]) {\n if (producesRows(sql)) {\n return new Promise<any[]>((resolve, reject) => {\n db.all(sql, params, (err: Error | null, rows: any[]) => {\n if (err) return reject(err);\n resolve(rows || []);\n });\n });\n }\n // Non-SELECT statements\n return new Promise((resolve, reject) => {\n db.run(sql, params, function (this: any, err: Error | null) {\n if (err) return reject(err);\n resolve({ rowsAffected: Number(this?.changes ?? 0), lastInsertId: this?.lastID });\n });\n });\n },\n conn: db,\n close() {\n return new Promise<void>((resolve, reject) => {\n db.close((err: Error | null) => (err ? reject(err) : resolve()));\n });\n },\n } as Database;\n }\n\n throw new Error('No SQLite driver available. Install either better-sqlite3 or sqlite3.');\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sqlite.js","sourceRoot":"","sources":["../../../src/adapters/sqlite.ts"],"names":[],"mappings":"AAEA,SAAS,aAAa,CAAI,KAAc;IACtC,OAAO,CAAC,CAAC,KAAK,IAAI,OAAQ,KAAoB,CAAC,IAAI,KAAK,UAAU,CAAC;AACrE,CAAC;AAED,KAAK,UAAU,gBAAgB,CAAC,EAAO,EAAE,GAAW;IAClD,MAAM,IAAI,GAAG,EAAE,CAA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,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,CAAC,GAAiB,EAAE,IAAW,EAAE,EAAE;4BACrD,IAAI,GAAG;gCAAE,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;4BAC5B,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC;wBACtB,CAAC,CAAC,CAAC;oBACL,CAAC,CAAC,CAAC;gBACL,CAAC;gBACD,wBAAwB;gBACxB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;oBACrC,EAAE,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,UAAqB,GAAiB;wBACxD,IAAI,GAAG;4BAAE,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;wBAC5B,OAAO,CAAC,EAAE,YAAY,EAAE,MAAM,CAAC,IAAI,EAAE,OAAO,IAAI,CAAC,CAAC,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;oBACpF,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;YACL,CAAC;YACD,IAAI,EAAE,EAAE;YACR,KAAK;gBACH,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;oBAC3C,EAAE,CAAC,KAAK,CAAC,CAAC,GAAiB,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;gBACnE,CAAC,CAAC,CAAC;YACL,CAAC;SACU,CAAC;IAChB,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAC;AAC3F,CAAC","sourcesContent":["import type { Database } from '../registry';\n\nfunction isPromiseLike<T>(value: unknown): value is Promise<T> {\n return !!value && typeof (value as Promise<T>).then === 'function';\n}\n\nasync function prepareStatement(db: any, sql: string) {\n const stmt = db.prepare(sql);\n return isPromiseLike(stmt) ? await stmt : stmt;\n}\n\nasync function finalizeStatement(stmt: any) {\n if (!stmt || typeof stmt.finalize !== 'function') return;\n const result = stmt.finalize();\n if (isPromiseLike(result)) {\n await result;\n }\n}\n\nasync function statementAll(stmt: any, params: unknown[]) {\n if (typeof stmt.all !== 'function') {\n throw new Error('SQLite statement missing all()');\n }\n if (stmt.all.length >= 2) {\n return await new Promise((resolve, reject) => {\n const callback = (err: Error | null, rows: any[]) => {\n if (err) return reject(err);\n resolve(rows || []);\n };\n try {\n if (params.length > 0) {\n stmt.all(params, callback);\n } else {\n stmt.all(callback);\n }\n } catch (error) {\n reject(error);\n }\n });\n }\n const result = stmt.all(...(params as any[]));\n return isPromiseLike(result) ? await result : result;\n}\n\nasync function statementRun(stmt: any, params: unknown[]) {\n if (typeof stmt.run !== 'function') {\n throw new Error('SQLite statement missing run()');\n }\n if (stmt.run.length >= 2) {\n return await new Promise((resolve, reject) => {\n const callback = function (this: any, err: Error | null) {\n if (err) return reject(err);\n resolve({ changes: this?.changes ?? 0, lastInsertId: this?.lastID });\n };\n try {\n if (params.length > 0) {\n stmt.run(params, callback);\n } else {\n stmt.run(callback);\n }\n } catch (error) {\n reject(error);\n }\n });\n }\n const result = stmt.run(...(params as any[]));\n return isPromiseLike(result) ? await result : result;\n}\n\nfunction stripLeadingComments(sql: string): string {\n let i = 0;\n const n = sql.length;\n if (sql.charCodeAt(0) === 0xfeff) i = 1; // BOM\n while (i < n) {\n while (i < n && /\\s/.test(sql[i]!)) i++;\n if (i + 1 < n && sql[i] === '-' && sql[i + 1] === '-') {\n // -- line comment\n i += 2;\n while (i < n && sql[i] !== '\\n') i++;\n continue;\n }\n if (i + 1 < n && sql[i] === '/' && sql[i + 1] === '*') {\n // /* block comment */\n i += 2;\n const end = sql.indexOf('*/', i);\n if (end === -1) return '';\n i = end + 2;\n continue;\n }\n break;\n }\n return sql.slice(i);\n}\n\n// Text-based fallback for drivers that do not expose statement metadata\n// (the sqlite3 callback API). SELECT, CTEs, and `... RETURNING` all produce\n// a result set and must be executed with all(), not run().\nfunction producesRows(sql: string): boolean {\n const text = stripLeadingComments(String(sql)).trimStart().toUpperCase();\n return text.startsWith('SELECT') || text.startsWith('WITH') || /\\bRETURNING\\b/.test(text);\n}\n\n// better-sqlite3 exposes `stmt.reader` (true when the statement returns rows).\nfunction statementReturnsRows(stmt: any, sql: string): boolean {\n return typeof stmt?.reader === 'boolean' ? stmt.reader : producesRows(sql);\n}\n\nexport async function createSqliteDb(filenameOrDb: string | any): Promise<Database> {\n // If a pre-created connection is provided\n if (typeof filenameOrDb !== 'string' && filenameOrDb) {\n const db = filenameOrDb;\n\n // better-sqlite3 shape\n if (typeof db.prepare === 'function') {\n return {\n dialect: 'sqlite',\n async query(sql: string, params: unknown[]) {\n const stmt = await prepareStatement(db, sql);\n try {\n if (statementReturnsRows(stmt, sql)) {\n const rows = await statementAll(stmt, params);\n return rows;\n }\n const info = await statementRun(stmt, params);\n const rowsAffected = Number(info?.changes ?? info?.rowsAffected ?? 0);\n const lastInsertId = info?.lastInsertRowid ?? info?.lastID ?? info?.lastInsertId;\n return { rowsAffected, lastInsertId };\n } finally {\n await finalizeStatement(stmt);\n }\n },\n conn: db,\n // Do not close externally provided connection\n async close() {\n if (typeof db.close === 'function') {\n const res = db.close();\n if (isPromiseLike(res)) {\n await res;\n }\n }\n },\n } as Database;\n }\n\n // sqlite3 shape\n return {\n dialect: 'sqlite',\n async query(sql: string, params: unknown[]) {\n if (producesRows(sql)) {\n return new Promise<any[]>((resolve, reject) => {\n db.all(sql, params, (err: Error | null, rows: any[]) => {\n if (err) return reject(err);\n resolve(rows || []);\n });\n });\n }\n return new Promise((resolve, reject) => {\n // Use function callback to access `this` for metadata\n db.run(sql, params, function (this: any, err: Error | null) {\n if (err) return reject(err);\n resolve({ rowsAffected: Number(this?.changes ?? 0), lastInsertId: this?.lastID });\n });\n });\n },\n conn: db,\n // Do not close externally provided connection\n close() {},\n } as Database;\n }\n\n const filename = filenameOrDb as string;\n\n let BetterSqlite3: any;\n if (typeof require === 'function') {\n try {\n BetterSqlite3 = require('better-sqlite3');\n } catch {\n BetterSqlite3 = null;\n }\n } else {\n try {\n // @ts-ignore optional dependency without types\n const mod = await import('better-sqlite3');\n BetterSqlite3 = (mod as any).default ?? mod;\n } catch {\n BetterSqlite3 = null;\n }\n }\n\n if (BetterSqlite3) {\n const db = new BetterSqlite3(filename);\n return {\n dialect: 'sqlite',\n async query(sql: string, params: unknown[]) {\n const stmt = db.prepare(sql);\n if (statementReturnsRows(stmt, sql)) {\n return stmt.all(...params);\n }\n const info = stmt.run(...params);\n return { rowsAffected: Number(info?.changes ?? 0), lastInsertId: info?.lastInsertRowid };\n },\n conn: db,\n close() {\n db.close();\n },\n } as Database;\n }\n\n let sqlite3: any;\n if (typeof require === 'function') {\n try {\n sqlite3 = require('sqlite3');\n } catch {\n sqlite3 = null;\n }\n } else {\n try {\n // @ts-ignore optional dependency without types\n // Optional fallback: defer resolution to runtime rather than making\n // bundlers require sqlite3 when the preferred driver is installed.\n const packageName = 'sqlite3';\n const mod = await import(/* @vite-ignore */ packageName);\n sqlite3 = (mod as any).default ?? mod;\n } catch {\n sqlite3 = null;\n }\n }\n\n if (sqlite3) {\n const db = new sqlite3.Database(filename);\n return {\n dialect: 'sqlite',\n async query(sql: string, params: unknown[]) {\n if (producesRows(sql)) {\n return new Promise<any[]>((resolve, reject) => {\n db.all(sql, params, (err: Error | null, rows: any[]) => {\n if (err) return reject(err);\n resolve(rows || []);\n });\n });\n }\n // Non-SELECT statements\n return new Promise((resolve, reject) => {\n db.run(sql, params, function (this: any, err: Error | null) {\n if (err) return reject(err);\n resolve({ rowsAffected: Number(this?.changes ?? 0), lastInsertId: this?.lastID });\n });\n });\n },\n conn: db,\n close() {\n return new Promise<void>((resolve, reject) => {\n db.close((err: Error | null) => (err ? reject(err) : resolve()));\n });\n },\n } as Database;\n }\n\n throw new Error('No SQLite driver available. Install either better-sqlite3 or sqlite3.');\n}\n"]}
|
package/dist/esm/core/errors.js
CHANGED
|
@@ -42,11 +42,21 @@ export class ValidationError extends SqlStackError {
|
|
|
42
42
|
this.name = 'ValidationError';
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
|
+
/**
|
|
46
|
+
* A statement failed: the driver rejected it, or (for the `run(...)` forms
|
|
47
|
+
* that take arguments) the SQL could not be compiled, bound, or routed to a
|
|
48
|
+
* database. The original error is kept in `.cause`; when the cause carries a
|
|
49
|
+
* string driver code (`SQLITE_CONSTRAINT_UNIQUE`, `23505`, `ER_DUP_ENTRY`)
|
|
50
|
+
* it is copied to `.code` so existing `err.code` checks keep working.
|
|
51
|
+
*/
|
|
45
52
|
export class DatabaseError extends SqlStackError {
|
|
46
53
|
constructor(message, sql, cause) {
|
|
47
54
|
super(`${message}\nSQL: ${sql}`);
|
|
48
55
|
this.sql = sql;
|
|
49
56
|
this.cause = cause;
|
|
57
|
+
const code = cause?.code;
|
|
58
|
+
if (typeof code === 'string')
|
|
59
|
+
this.code = code;
|
|
50
60
|
this.name = 'DatabaseError';
|
|
51
61
|
}
|
|
52
62
|
}
|
|
@@ -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,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,cAA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,CAAC,IAAI,GAAG,iBAAiB,CAAC;IAChC,CAAC;CAEF;AAED;;;;;;GAMG;AACH,MAAM,OAAO,aAAc,SAAQ,aAAa;IAC9C,YAAY,OAAe,EAAE,GAAW,EAAE,KAAa;QACrD,KAAK,CAAC,GAAG,OAAO,UAAU,GAAG,EAAE,CAAC,CAAC;QACjC,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,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,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// 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,14 +1,28 @@
|
|
|
1
1
|
import { getClassLabels, getMethodLabels, setMethodLabels } from '../core/metadata.js';
|
|
2
2
|
import { SqlStackError, ExactlyOneRowError, NoRowsError, RowsExistError, DatabaseError, ExpectedRowsError } from '../core/errors.js';
|
|
3
3
|
import { isValidationDisabled, validateOutput } from '../core/validator.js';
|
|
4
|
-
import { resolveExecution } from '../runtime.js';
|
|
4
|
+
import { resolveExecution, resolveSqlResolver } from '../runtime.js';
|
|
5
5
|
import { createSqliteBinder, createMysqlBinder, createPostgresBinder } from '../binders/sqlBinder.js';
|
|
6
6
|
import { coerceRootPath, resolveSqlFromFs } from '../core/fileResolution.js';
|
|
7
7
|
import { registerDecoratedMethod, recordQueryMethodOnClass } from '../core/resolver.js';
|
|
8
8
|
import { defaultSourceScanResolver } from '../core/sourceScanResolver.js';
|
|
9
9
|
import { getActiveTransaction } from '../transactions.js';
|
|
10
|
-
import { SqlFragment } from '../sql.js';
|
|
11
|
-
import { runStorage } from '../run.js';
|
|
10
|
+
import { SqlFragment, compileFragment } from '../sql.js';
|
|
11
|
+
import { runStorage, resolveRunTarget, executeOnTarget, toRunError, fragmentText, } from '../run.js';
|
|
12
|
+
/**
|
|
13
|
+
* Turn a method into a database query. The body calls `run(...)` (see `run`
|
|
14
|
+
* for its forms); the wrapper resolves SQL, binds, executes, and applies the
|
|
15
|
+
* shape/transform/validation decorators. A string argument is the root
|
|
16
|
+
* directory holding the method's `.sql` file; `{ sql }` gives inline SQL,
|
|
17
|
+
* `{ db }` pins a registered database, `{ dialect }` overrides binding style.
|
|
18
|
+
*
|
|
19
|
+
* The decorated method's promise rejects with:
|
|
20
|
+
* @throws {DatabaseError} When the driver rejects the statement (original
|
|
21
|
+
* error in `.cause`).
|
|
22
|
+
* @throws {SqlStackError} For missing SQL sources, unresolvable databases,
|
|
23
|
+
* and shape/validation failures (ExpectedRowsError, ExactlyOneRowError,
|
|
24
|
+
* NoRowsError, RowsExistError, ValidationError).
|
|
25
|
+
*/
|
|
12
26
|
export function Query(arg) {
|
|
13
27
|
return function (_target, prop, desc) {
|
|
14
28
|
const options = typeof arg === 'string' ? undefined : arg;
|
|
@@ -45,16 +59,26 @@ export function Query(arg) {
|
|
|
45
59
|
desc.value = async function (...callArgs) {
|
|
46
60
|
const labels = getMethodLabels(this, prop);
|
|
47
61
|
const classLabels = getClassLabels(this);
|
|
48
|
-
//
|
|
49
|
-
//
|
|
50
|
-
//
|
|
51
|
-
|
|
62
|
+
// Resolve, bind, and execute the method's own SQL (inline, resolver,
|
|
63
|
+
// or file) and return the adapter's raw result. `callArgs` is the
|
|
64
|
+
// binding input: the method's own arguments for run() and the legacy
|
|
65
|
+
// fallback, or the params given to run(db, params). `explicit` carries
|
|
66
|
+
// the database chosen by run(db, params).
|
|
67
|
+
const executeMethodSql = async (callArgs, explicit, onSql) => {
|
|
52
68
|
// 1) prepare args with defaults
|
|
53
69
|
const rawInput = callArgs.length === 1 ? callArgs[0] : callArgs; // object or positional array
|
|
54
|
-
// 2) choose database and dialect via the active environment
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
70
|
+
// 2) choose database and dialect via the active environment (or run's explicit database)
|
|
71
|
+
let target;
|
|
72
|
+
let activeResolver;
|
|
73
|
+
if (explicit) {
|
|
74
|
+
target = explicit.target;
|
|
75
|
+
activeResolver = explicit.resolver;
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
target = await contextTarget();
|
|
79
|
+
activeResolver = target.resolver;
|
|
80
|
+
}
|
|
81
|
+
const db = target.db;
|
|
58
82
|
const dialect = options?.dialect ?? db.dialect ?? 'sqlite';
|
|
59
83
|
// 3) load SQL source (inline, environment resolver, v1 fs fallback,
|
|
60
84
|
// or the zero-config source scan — bare @Query() with nothing installed)
|
|
@@ -77,6 +101,7 @@ export function Query(arg) {
|
|
|
77
101
|
if (!sql) {
|
|
78
102
|
throw new SqlStackError(`No SQL source provided for method ${String(prop)}. Use @Query() with a file/folder path or inline sql.`);
|
|
79
103
|
}
|
|
104
|
+
onSql(sql);
|
|
80
105
|
// 4) bind placeholders
|
|
81
106
|
// Decide argument mode: positional if SQL contains :argN
|
|
82
107
|
let workingSql = sql;
|
|
@@ -257,28 +282,96 @@ export function Query(arg) {
|
|
|
257
282
|
}
|
|
258
283
|
}
|
|
259
284
|
const binder = dialect === 'postgres' ? createPostgresBinder() : dialect === 'mysql' ? createMysqlBinder() : createSqliteBinder();
|
|
260
|
-
|
|
261
|
-
//
|
|
285
|
+
// Binding failures (missing :name, bad array value) surface as DatabaseError like every
|
|
286
|
+
// other run() failure; the original error stays in `.cause`.
|
|
287
|
+
let bound;
|
|
288
|
+
try {
|
|
289
|
+
bound = binder.bind(workingSql, args);
|
|
290
|
+
}
|
|
291
|
+
catch (bindError) {
|
|
292
|
+
throw toRunError(bindError, workingSql);
|
|
293
|
+
}
|
|
294
|
+
const { sql: boundSql, params } = bound;
|
|
295
|
+
onSql(boundSql);
|
|
296
|
+
// 5) execute query (inside the active transaction on that database, if any)
|
|
262
297
|
let out;
|
|
263
298
|
try {
|
|
264
|
-
|
|
265
|
-
out = tx ? await tx.query(boundSql, params) : await db.query(boundSql, params);
|
|
299
|
+
out = target.tx ? await target.tx.query(boundSql, params) : await db.query(boundSql, params);
|
|
266
300
|
}
|
|
267
301
|
catch (dbError) {
|
|
268
302
|
// Attach SQL query (with placeholders) to error for debugging
|
|
269
303
|
throw new DatabaseError(dbError?.message || String(dbError), boundSql, dbError instanceof Error ? dbError : undefined);
|
|
270
304
|
}
|
|
271
|
-
|
|
272
|
-
|
|
305
|
+
return out;
|
|
306
|
+
};
|
|
307
|
+
// Database from the decorator context: @Query({ db }), @QueryBinder({ db }),
|
|
308
|
+
// or the environment default.
|
|
309
|
+
const contextTarget = async () => {
|
|
310
|
+
const dbName = labels.db ?? options?.db ?? classLabels?.db;
|
|
311
|
+
const resolved = await resolveExecution(dbName);
|
|
312
|
+
return {
|
|
313
|
+
db: resolved.entry.db,
|
|
314
|
+
tx: getActiveTransaction(resolved.entry),
|
|
315
|
+
resolver: resolved.resolver,
|
|
316
|
+
byName: true,
|
|
317
|
+
};
|
|
318
|
+
};
|
|
319
|
+
// run's argument-taking forms: return the adapter's raw result.
|
|
320
|
+
const executeInvocation = async (invocation, onSql) => {
|
|
321
|
+
if (invocation.kind === 'fragment') {
|
|
322
|
+
// run(query) / run(db, query): the fragment replaces the method's SQL;
|
|
323
|
+
// the method's arguments are not bound.
|
|
324
|
+
const target = invocation.db !== undefined ? await resolveRunTarget(invocation.db) : await contextTarget();
|
|
325
|
+
const dialect = options?.dialect ?? target.db.dialect ?? 'sqlite';
|
|
326
|
+
const { sql: boundSql, params } = compileFragment(invocation.fragment, dialect);
|
|
327
|
+
onSql(boundSql);
|
|
328
|
+
return executeOnTarget(target, boundSql, params);
|
|
329
|
+
}
|
|
330
|
+
// run(db, params): the method's own SQL against db, bound from params
|
|
331
|
+
// only (an object for :named, an array for :argN).
|
|
332
|
+
const target = await resolveRunTarget(invocation.db);
|
|
333
|
+
// Inline SQL needs no resolver; only look one up for file-based SQL.
|
|
334
|
+
const resolver = target.byName
|
|
335
|
+
? target.resolver
|
|
336
|
+
: labels?.source?.kind === 'inline'
|
|
337
|
+
? undefined
|
|
338
|
+
: await resolveSqlResolver();
|
|
339
|
+
const bindArgs = Array.isArray(invocation.params) ? [...invocation.params] : [invocation.params];
|
|
340
|
+
return executeMethodSql(bindArgs, { target, resolver }, onSql);
|
|
341
|
+
};
|
|
342
|
+
// The full pipeline: execute, then — if rows were returned
|
|
343
|
+
// (SELECT/CTE/RETURNING) — shape + transform + validate; a write result
|
|
344
|
+
// is returned as-is (or fails if a shape was requested). Invoked by
|
|
345
|
+
// run() from inside the method body, or directly as the legacy fallback
|
|
346
|
+
// when the body throws. The zero-argument path is unchanged; run's
|
|
347
|
+
// argument-taking forms get the unified error contract: any failure
|
|
348
|
+
// before shaping that is not already a SqlStackError becomes a
|
|
349
|
+
// DatabaseError with the original error in `.cause`.
|
|
350
|
+
const pipeline = async (invocation) => {
|
|
351
|
+
if (invocation === undefined || invocation.kind === 'default') {
|
|
352
|
+
const out = await executeMethodSql(callArgs, undefined, () => { });
|
|
353
|
+
return finishResult(out, labels, this, prop);
|
|
354
|
+
}
|
|
355
|
+
let sqlText = invocation.kind === 'fragment' ? fragmentText(invocation.fragment) : '';
|
|
356
|
+
let out;
|
|
357
|
+
try {
|
|
358
|
+
out = await executeInvocation(invocation, (s) => {
|
|
359
|
+
sqlText = s;
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
catch (err) {
|
|
363
|
+
throw toRunError(err, sqlText);
|
|
364
|
+
}
|
|
273
365
|
return finishResult(out, labels, this, prop);
|
|
274
366
|
};
|
|
275
367
|
// 0) Invoke the method body inside a run() context. Three outcomes:
|
|
276
|
-
// - body calls run(): the pipeline executed inside the body; return
|
|
368
|
+
// - body calls run(...): the pipeline executed inside the body; return
|
|
277
369
|
// the body's result verbatim (it may have caught/transformed it).
|
|
278
|
-
// - body returns a SqlFragment (template literal path):
|
|
370
|
+
// - body returns a SqlFragment (deprecated template literal path):
|
|
371
|
+
// execute it.
|
|
279
372
|
// - body throws without calling run() (legacy placeholder throw):
|
|
280
373
|
// fall through to the pipeline.
|
|
281
|
-
const runCtx = { ran: false, execute: pipeline };
|
|
374
|
+
const runCtx = { ran: false, execute: pipeline, invocations: true };
|
|
282
375
|
let fragmentResult;
|
|
283
376
|
try {
|
|
284
377
|
fragmentResult = await runStorage.run(runCtx, () => original.apply(this, callArgs));
|
|
@@ -293,6 +386,7 @@ export function Query(arg) {
|
|
|
293
386
|
if (runCtx.ran)
|
|
294
387
|
return fragmentResult;
|
|
295
388
|
if (fragmentResult instanceof SqlFragment) {
|
|
389
|
+
warnFragmentBodyDeprecated(this, prop);
|
|
296
390
|
const { sql: boundSql, params } = fragmentResult.toSQL();
|
|
297
391
|
const dbName = labels.db ?? options?.db ?? classLabels?.db;
|
|
298
392
|
const { entry } = await resolveExecution(dbName);
|
|
@@ -312,6 +406,19 @@ export function Query(arg) {
|
|
|
312
406
|
return desc;
|
|
313
407
|
};
|
|
314
408
|
}
|
|
409
|
+
// Deprecated (removal in the next major version): a @Query body that RETURNS
|
|
410
|
+
// an sql`` fragment. It only type-checks when the method's declared return
|
|
411
|
+
// type is bent to admit SqlFragment (an `as any`-style hole). One warning per
|
|
412
|
+
// class.method per process.
|
|
413
|
+
const warnedFragmentBodies = new Set();
|
|
414
|
+
function warnFragmentBodyDeprecated(self, prop) {
|
|
415
|
+
const key = `${self?.constructor?.name ?? '<anonymous>'}.${String(prop)}`;
|
|
416
|
+
if (warnedFragmentBodies.has(key))
|
|
417
|
+
return;
|
|
418
|
+
warnedFragmentBodies.add(key);
|
|
419
|
+
process.emitWarning(`@Query method ${key} returns an sql\`\` fragment from its body. This form is deprecated and will be ` +
|
|
420
|
+
'removed in the next major version. Use `return run(sql`...`)` (or `return run(db, sql`...`)`) instead.', { type: 'DeprecationWarning', code: 'SQLSTACK_FRAGMENT_BODY' });
|
|
421
|
+
}
|
|
315
422
|
function applyDefaults(defaults, input) {
|
|
316
423
|
if (!defaults)
|
|
317
424
|
return input;
|