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.
Files changed (95) hide show
  1. package/dist/cjs/adapters/sqlite.d.ts.map +1 -1
  2. package/dist/cjs/adapters/sqlite.js +4 -1
  3. package/dist/cjs/adapters/sqlite.js.map +1 -1
  4. package/dist/cjs/core/errors.d.ts +9 -0
  5. package/dist/cjs/core/errors.d.ts.map +1 -1
  6. package/dist/cjs/core/errors.js +10 -0
  7. package/dist/cjs/core/errors.js.map +1 -1
  8. package/dist/cjs/decorators/query.d.ts +14 -0
  9. package/dist/cjs/decorators/query.d.ts.map +1 -1
  10. package/dist/cjs/decorators/query.js +124 -17
  11. package/dist/cjs/decorators/query.js.map +1 -1
  12. package/dist/cjs/index.d.ts +2 -1
  13. package/dist/cjs/index.d.ts.map +1 -1
  14. package/dist/cjs/index.js +4 -2
  15. package/dist/cjs/index.js.map +1 -1
  16. package/dist/cjs/run.d.ts +140 -6
  17. package/dist/cjs/run.d.ts.map +1 -1
  18. package/dist/cjs/run.js +127 -17
  19. package/dist/cjs/run.js.map +1 -1
  20. package/dist/cjs/runtime.d.ts +8 -0
  21. package/dist/cjs/runtime.d.ts.map +1 -1
  22. package/dist/cjs/runtime.js +12 -0
  23. package/dist/cjs/runtime.js.map +1 -1
  24. package/dist/cjs/sql.d.ts +19 -0
  25. package/dist/cjs/sql.d.ts.map +1 -1
  26. package/dist/cjs/sql.js +66 -28
  27. package/dist/cjs/sql.js.map +1 -1
  28. package/dist/cjs/stack.d.ts +2 -0
  29. package/dist/cjs/stack.d.ts.map +1 -1
  30. package/dist/cjs/stack.js +40 -27
  31. package/dist/cjs/stack.js.map +1 -1
  32. package/dist/cjs/testing/builder.d.ts.map +1 -1
  33. package/dist/cjs/testing/builder.js +14 -5
  34. package/dist/cjs/testing/builder.js.map +1 -1
  35. package/dist/cjs/testing/fixture-provenance.d.ts +3 -0
  36. package/dist/cjs/testing/fixture-provenance.d.ts.map +1 -0
  37. package/dist/cjs/testing/fixture-provenance.js +21 -0
  38. package/dist/cjs/testing/fixture-provenance.js.map +1 -0
  39. package/dist/cjs/testing/index.d.ts +2 -0
  40. package/dist/cjs/testing/index.d.ts.map +1 -1
  41. package/dist/cjs/testing/index.js +5 -1
  42. package/dist/cjs/testing/index.js.map +1 -1
  43. package/dist/cjs/testing/postgres/database.d.ts +9 -1
  44. package/dist/cjs/testing/postgres/database.d.ts.map +1 -1
  45. package/dist/cjs/testing/postgres/database.js +17 -13
  46. package/dist/cjs/testing/postgres/database.js.map +1 -1
  47. package/dist/cjs/testing/resource.d.ts +76 -0
  48. package/dist/cjs/testing/resource.d.ts.map +1 -0
  49. package/dist/cjs/testing/resource.js +117 -0
  50. package/dist/cjs/testing/resource.js.map +1 -0
  51. package/dist/cjs/testing/sqlite/builder.d.ts.map +1 -1
  52. package/dist/cjs/testing/sqlite/builder.js +10 -2
  53. package/dist/cjs/testing/sqlite/builder.js.map +1 -1
  54. package/dist/cjs/testing/sqlite/database.d.ts +11 -1
  55. package/dist/cjs/testing/sqlite/database.d.ts.map +1 -1
  56. package/dist/cjs/testing/sqlite/database.js +32 -18
  57. package/dist/cjs/testing/sqlite/database.js.map +1 -1
  58. package/dist/cjs/transactions.d.ts +14 -0
  59. package/dist/cjs/transactions.d.ts.map +1 -1
  60. package/dist/cjs/transactions.js +27 -0
  61. package/dist/cjs/transactions.js.map +1 -1
  62. package/dist/esm/adapters/sqlite.js +4 -1
  63. package/dist/esm/adapters/sqlite.js.map +1 -1
  64. package/dist/esm/core/errors.js +10 -0
  65. package/dist/esm/core/errors.js.map +1 -1
  66. package/dist/esm/decorators/query.js +127 -20
  67. package/dist/esm/decorators/query.js.map +1 -1
  68. package/dist/esm/index.js +3 -2
  69. package/dist/esm/index.js.map +1 -1
  70. package/dist/esm/run.js +123 -18
  71. package/dist/esm/run.js.map +1 -1
  72. package/dist/esm/runtime.js +11 -0
  73. package/dist/esm/runtime.js.map +1 -1
  74. package/dist/esm/sql.js +63 -27
  75. package/dist/esm/sql.js.map +1 -1
  76. package/dist/esm/stack.js +40 -27
  77. package/dist/esm/stack.js.map +1 -1
  78. package/dist/esm/testing/builder.js +14 -5
  79. package/dist/esm/testing/builder.js.map +1 -1
  80. package/dist/esm/testing/fixture-provenance.js +15 -0
  81. package/dist/esm/testing/fixture-provenance.js.map +1 -0
  82. package/dist/esm/testing/index.js +1 -0
  83. package/dist/esm/testing/index.js.map +1 -1
  84. package/dist/esm/testing/postgres/database.js +17 -13
  85. package/dist/esm/testing/postgres/database.js.map +1 -1
  86. package/dist/esm/testing/resource.js +106 -0
  87. package/dist/esm/testing/resource.js.map +1 -0
  88. package/dist/esm/testing/sqlite/builder.js +10 -2
  89. package/dist/esm/testing/sqlite/builder.js.map +1 -1
  90. package/dist/esm/testing/sqlite/database.js +32 -18
  91. package/dist/esm/testing/sqlite/database.js.map +1 -1
  92. package/dist/esm/transactions.js +25 -0
  93. package/dist/esm/transactions.js.map +1 -1
  94. package/package.json +1 -1
  95. package/readme.md +128 -39
package/dist/cjs/index.js CHANGED
@@ -14,12 +14,13 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.SourceScanResolver = exports.MANIFEST_DIALECT_EXT = exports.ManifestResolver = exports.FsResolver = exports.sqliteFamily = exports.FamilyRuntime = exports.resolveExecution = exports.activeSqlStack = exports.SqlStack = exports.SqlStackDB = exports.run = exports.SqlFragment = exports.sql = void 0;
17
+ exports.SourceScanResolver = exports.getActiveResolver = exports.MANIFEST_DIALECT_EXT = exports.ManifestResolver = exports.FsResolver = exports.sqliteFamily = exports.FamilyRuntime = exports.resolveExecution = exports.activeSqlStack = exports.SqlStack = exports.SqlStackDB = exports.run = exports.SqlFragment = exports.sql = void 0;
18
18
  // SQL Template Strings
19
19
  var sql_1 = require("./sql");
20
20
  Object.defineProperty(exports, "sql", { enumerable: true, get: function () { return sql_1.sql; } });
21
21
  Object.defineProperty(exports, "SqlFragment", { enumerable: true, get: function () { return sql_1.SqlFragment; } });
22
- // Query body execution — `return run<T>()` inside a @Query method body
22
+ // Query execution — `return run()` inside a @Query method body, or
23
+ // `run(db, sql`...`)` anywhere with a database chosen at call time
23
24
  var run_1 = require("./run");
24
25
  Object.defineProperty(exports, "run", { enumerable: true, get: function () { return run_1.run; } });
25
26
  // Decorators
@@ -56,6 +57,7 @@ var resolver_1 = require("./core/resolver");
56
57
  Object.defineProperty(exports, "FsResolver", { enumerable: true, get: function () { return resolver_1.FsResolver; } });
57
58
  Object.defineProperty(exports, "ManifestResolver", { enumerable: true, get: function () { return resolver_1.ManifestResolver; } });
58
59
  Object.defineProperty(exports, "MANIFEST_DIALECT_EXT", { enumerable: true, get: function () { return resolver_1.MANIFEST_DIALECT_EXT; } });
60
+ Object.defineProperty(exports, "getActiveResolver", { enumerable: true, get: function () { return resolver_1.getActiveResolver; } });
59
61
  var sourceScanResolver_1 = require("./core/sourceScanResolver");
60
62
  Object.defineProperty(exports, "SourceScanResolver", { enumerable: true, get: function () { return sourceScanResolver_1.SourceScanResolver; } });
61
63
  // Legacy exports (kept for backward compatibility)
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,uBAAuB;AACvB,6BAAyC;AAAhC,0FAAA,GAAG,OAAA;AAAE,kGAAA,WAAW,OAAA;AAEzB,uEAAuE;AACvE,6BAA4B;AAAnB,0FAAA,GAAG,OAAA;AAEZ,aAAa;AACb,2DAAyC;AACzC,qDAAmC;AACnC,wDAAsC;AACtC,2DAAyC;AACzC,8DAA4C;AAC5C,yDAAuC;AACvC,oDAAkC;AAElC,eAAe;AACf,iDAA+B;AAE/B,WAAW;AACX,6CAA2B;AAE3B,wBAAwB;AACxB,gDAA8B;AAC9B,mDAAiC;AAEjC,aAAa;AACb,8CAA4B;AAI5B,uCAAkD;AAAzC,sGAAA,UAAU,OAAA;AAEnB,gFAAgF;AAChF,iCAAmC;AAA1B,iGAAA,QAAQ,OAAA;AAEjB,qCAA6D;AAApD,yGAAA,cAAc,OAAA;AAAE,2GAAA,gBAAgB,OAAA;AAEzC,sCAAsC;AACtC,mCAAyC;AAAhC,uGAAA,aAAa,OAAA;AAQtB,wDAAuD;AAA9C,4GAAA,YAAY,OAAA;AAKrB,4CAAqF;AAA5E,sGAAA,UAAU,OAAA;AAAE,4GAAA,gBAAgB,OAAA;AAAE,gHAAA,oBAAoB,OAAA;AAC3D,gEAA+D;AAAtD,wHAAA,kBAAkB,OAAA;AAE3B,mDAAmD;AACnD,sDAAoC","sourcesContent":["// SQL Template Strings\nexport { sql, SqlFragment } from './sql';\n\n// Query body execution — `return run<T>()` inside a @Query method body\nexport { run } from './run';\n\n// Decorators\nexport * from './decorators/queryBinder';\nexport * from './decorators/query';\nexport * from './decorators/defaults';\nexport * from './decorators/resultShape';\nexport * from './decorators/validateResult';\nexport * from './decorators/transform';\nexport * from './decorators/page';\n\n// Transactions\nexport * from './transactions';\n\n// Adapters\nexport * from './adapters';\n\n// Errors and Validation\nexport * from './core/errors';\nexport * from './core/validator';\n\n// DTO Helper\nexport * from './utils/dto';\n\n// Database Registry and Types\nexport type { Dialect, WriteResult, PostgresWriteResult, QueryResult, Database } from './registry';\nexport { SqlStackDB, IStackDB } from './registry';\n\n// Environment-owned runtime (v3): per-root SqlStack + active-context resolution\nexport { SqlStack } from './stack';\nexport type { DatabaseEntry, DatabaseRegistration, SqlStackConfig } from './stack';\nexport { activeSqlStack, resolveExecution } from './runtime';\n\n// Dynamic database families (spec 17)\nexport { FamilyRuntime } from './family';\nexport type {\n DatabaseFamilyProvider,\n FamilyConfig,\n FamilyMemberEntry,\n DatabaseLease,\n DatabaseInspection,\n} from './family';\nexport { sqliteFamily } from './families/sqliteFamily';\nexport type { SqliteFamilyOptions } from './families/sqliteFamily';\n\n// SQL Resolvers (v2): pluggable SQL source resolution\nexport type { SqlResolver, SqlManifest, SqlResolutionRequest, ManifestResolverOptions } from './core/resolver';\nexport { FsResolver, ManifestResolver, MANIFEST_DIALECT_EXT } from './core/resolver';\nexport { SourceScanResolver } from './core/sourceScanResolver';\n\n// Legacy exports (kept for backward compatibility)\nexport * from './binders/sqlBinder';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,uBAAuB;AACvB,6BAAyC;AAAhC,0FAAA,GAAG,OAAA;AAAE,kGAAA,WAAW,OAAA;AAEzB,mEAAmE;AACnE,mEAAmE;AACnE,6BAA4B;AAAnB,0FAAA,GAAG,OAAA;AAGZ,aAAa;AACb,2DAAyC;AACzC,qDAAmC;AACnC,wDAAsC;AACtC,2DAAyC;AACzC,8DAA4C;AAC5C,yDAAuC;AACvC,oDAAkC;AAElC,eAAe;AACf,iDAA+B;AAE/B,WAAW;AACX,6CAA2B;AAE3B,wBAAwB;AACxB,gDAA8B;AAC9B,mDAAiC;AAEjC,aAAa;AACb,8CAA4B;AAI5B,uCAAkD;AAAzC,sGAAA,UAAU,OAAA;AAEnB,gFAAgF;AAChF,iCAAmC;AAA1B,iGAAA,QAAQ,OAAA;AAEjB,qCAA6D;AAApD,yGAAA,cAAc,OAAA;AAAE,2GAAA,gBAAgB,OAAA;AAEzC,sCAAsC;AACtC,mCAAyC;AAAhC,uGAAA,aAAa,OAAA;AAQtB,wDAAuD;AAA9C,4GAAA,YAAY,OAAA;AAKrB,4CAAwG;AAA/F,sGAAA,UAAU,OAAA;AAAE,4GAAA,gBAAgB,OAAA;AAAE,gHAAA,oBAAoB,OAAA;AAAE,6GAAA,iBAAiB,OAAA;AAC9E,gEAA+D;AAAtD,wHAAA,kBAAkB,OAAA;AAE3B,mDAAmD;AACnD,sDAAoC","sourcesContent":["// SQL Template Strings\nexport { sql, SqlFragment } from './sql';\n\n// Query execution — `return run()` inside a @Query method body, or\n// `run(db, sql`...`)` anywhere with a database chosen at call time\nexport { run } from './run';\nexport type { RunDatabase, RejectCompiledSql } from './run';\n\n// Decorators\nexport * from './decorators/queryBinder';\nexport * from './decorators/query';\nexport * from './decorators/defaults';\nexport * from './decorators/resultShape';\nexport * from './decorators/validateResult';\nexport * from './decorators/transform';\nexport * from './decorators/page';\n\n// Transactions\nexport * from './transactions';\n\n// Adapters\nexport * from './adapters';\n\n// Errors and Validation\nexport * from './core/errors';\nexport * from './core/validator';\n\n// DTO Helper\nexport * from './utils/dto';\n\n// Database Registry and Types\nexport type { Dialect, WriteResult, PostgresWriteResult, QueryResult, Database } from './registry';\nexport { SqlStackDB, IStackDB } from './registry';\n\n// Environment-owned runtime (v3): per-root SqlStack + active-context resolution\nexport { SqlStack } from './stack';\nexport type { DatabaseEntry, DatabaseRegistration, SqlStackConfig } from './stack';\nexport { activeSqlStack, resolveExecution } from './runtime';\n\n// Dynamic database families (spec 17)\nexport { FamilyRuntime } from './family';\nexport type {\n DatabaseFamilyProvider,\n FamilyConfig,\n FamilyMemberEntry,\n DatabaseLease,\n DatabaseInspection,\n} from './family';\nexport { sqliteFamily } from './families/sqliteFamily';\nexport type { SqliteFamilyOptions } from './families/sqliteFamily';\n\n// SQL Resolvers (v2): pluggable SQL source resolution\nexport type { SqlResolver, SqlManifest, SqlResolutionRequest, ManifestResolverOptions } from './core/resolver';\nexport { FsResolver, ManifestResolver, MANIFEST_DIALECT_EXT, getActiveResolver } from './core/resolver';\nexport { SourceScanResolver } from './core/sourceScanResolver';\n\n// Legacy exports (kept for backward compatibility)\nexport * from './binders/sqlBinder';\n"]}
package/dist/cjs/run.d.ts CHANGED
@@ -1,29 +1,163 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { SqlStackError } from './core/errors';
3
+ import type { Dialect } from './registry';
4
+ import { SqlFragment } from './sql';
5
+ import type { SqlResolver } from './core/resolver';
6
+ import type { ActiveTransaction } from './transactions';
7
+ /**
8
+ * Anything run(db, ...) can execute against: sqlstack's own `Database`
9
+ * (from createSqliteDb/createPgDb/createMysqlDb), or any application handle
10
+ * exposing `query(sql, params)`. `dialect` selects placeholder style and
11
+ * defaults to `'sqlite'` when absent. run never opens databases by path.
12
+ */
13
+ export interface RunDatabase {
14
+ readonly dialect?: Dialect;
15
+ query(sql: string, params: unknown[]): Promise<unknown>;
16
+ }
17
+ /**
18
+ * Type-level guard for the params form of run: rejects the
19
+ * `{ sql, params }` object returned by `fragment.toSQL()`. Pass the sql``
20
+ * fragment itself instead, so run owns dialect binding and error handling.
21
+ */
22
+ export type RejectCompiledSql<P> = P extends {
23
+ readonly sql: string;
24
+ readonly params: readonly unknown[];
25
+ } ? never : unknown;
26
+ /**
27
+ * What a run(...) call made inside a @Query body asks of the wrapper's
28
+ * pipeline. `default` is the zero-argument run().
29
+ */
30
+ export type RunInvocation = {
31
+ readonly kind: 'default';
32
+ } | {
33
+ readonly kind: 'fragment';
34
+ readonly db?: RunDatabase | string;
35
+ readonly fragment: SqlFragment;
36
+ } | {
37
+ readonly kind: 'params';
38
+ readonly db: RunDatabase | string;
39
+ readonly params: object;
40
+ };
2
41
  /**
3
42
  * Per-invocation context established by the @Query wrapper before the method
4
43
  * body executes. `execute` performs the full query pipeline (resolve SQL,
5
44
  * bind, execute, shape/transform/validate); `ran` records that the body
6
45
  * invoked run(), so the wrapper returns the body's result verbatim instead
7
- * of falling through to the legacy pipeline.
46
+ * of falling through to the legacy pipeline. `invocations` marks a wrapper
47
+ * that understands the argument-taking run forms (an older duplicated copy
48
+ * of the decorator would silently ignore them).
8
49
  */
9
50
  export type RunContext = {
10
- execute: () => Promise<unknown>;
51
+ execute: (invocation?: RunInvocation) => Promise<unknown>;
11
52
  ran: boolean;
53
+ invocations?: true;
12
54
  };
13
55
  export declare const runStorage: AsyncLocalStorage<RunContext>;
14
56
  /**
15
57
  * Execute the current @Query method's SQL and return the finished result.
16
- * Call it as the body of a @Query-decorated method in place of the legacy
17
- * placeholder throw:
58
+ * Call it as the body of a @Query-decorated method:
18
59
  *
19
60
  * @Query()
20
61
  * async getUsers(active: boolean): Promise<User[]> {
21
- * return run<User[]>();
62
+ * return run();
22
63
  * }
23
64
  *
24
65
  * Takes no arguments — the method's own arguments, database, SQL source,
25
66
  * transaction, shaping, transform, and validation all come from the
26
- * decorator context. The generic is a typing convenience only.
67
+ * decorator context. T is inferred from the method's declared return type.
68
+ *
69
+ * @throws {DatabaseError} When the driver rejects the statement (original
70
+ * error in `.cause`).
71
+ * @throws {SqlStackError} When called outside a @Query method, or for
72
+ * shape/validation failures (ExactlyOneRowError, NoRowsError, ValidationError, ...).
27
73
  */
28
74
  export declare function run<T = any>(): Promise<T>;
75
+ /**
76
+ * Inside a @Query method: execute this inline sql`` fragment instead of the
77
+ * method's SQL file. The database comes from the method/class/registry
78
+ * context (`@Query({ db })`, `@QueryBinder({ db })`, the default), the
79
+ * active transaction on it is joined, and the method's shape/transform/
80
+ * validation decorators apply. The method's arguments are not auto-bound —
81
+ * the fragment's `${}` values are the parameters.
82
+ *
83
+ * @Single @Query()
84
+ * async byEmail(email: string): Promise<User | null> {
85
+ * return run(sql`SELECT * FROM users WHERE email = ${email}`);
86
+ * }
87
+ *
88
+ * @throws {DatabaseError} When the fragment cannot be compiled (macro input
89
+ * errors), the database cannot be resolved, or the driver rejects the
90
+ * statement. The original error is in `.cause`.
91
+ * @throws {SqlStackError} When called outside a @Query method (use
92
+ * `run(db, query)` there), or for shape/validation failures.
93
+ */
94
+ export declare function run<T = unknown>(query: SqlFragment): Promise<T>;
95
+ /**
96
+ * Execute an sql`` fragment against an explicit database: a handle
97
+ * (anything with `query(sql, params)`) or the name of a database registered
98
+ * with the active SqlStack / legacy registry. Usable anywhere.
99
+ *
100
+ * Binds for the database's dialect (`$1..` for Postgres, `?` otherwise;
101
+ * default sqlite). Joins an active transaction opened on the same database
102
+ * (same registered handle, or same name). Outside a @Query method the raw
103
+ * result is returned (rows array, or `{ rowsAffected }` for writes); inside
104
+ * one, the method's shape/transform/validation decorators apply.
105
+ *
106
+ * const rows = await run<Row[]>(accountsDb, sql`SELECT * FROM t WHERE id = ${id}`);
107
+ *
108
+ * @throws {DatabaseError} When the fragment cannot be compiled, a named
109
+ * database cannot be resolved, or the driver rejects the statement. The
110
+ * original error is in `.cause`, and its string `code` is copied to `.code`.
111
+ * @throws {SqlStackError} For invalid arguments, or shape/validation failures.
112
+ */
113
+ export declare function run<T = unknown>(db: RunDatabase | string, query: SqlFragment): Promise<T>;
114
+ /**
115
+ * Inside a @Query method: run the method's own SQL (its .sql file or inline
116
+ * `@Query({ sql })`) against `db`, binding `params` (an object for `:named`
117
+ * placeholders, an array for `:arg1..`). The method's raw arguments are NOT
118
+ * auto-bound in this form — `params` is the whole binding input. @Defaults,
119
+ * @Page, shaping, transform, and validation still apply.
120
+ *
121
+ * @Single @Query()
122
+ * async byEmail(db: Database, p: { email: string }): Promise<User | null> {
123
+ * return run(db, p);
124
+ * }
125
+ *
126
+ * @throws {DatabaseError} When binding fails, a named database cannot be
127
+ * resolved, or the driver rejects the statement. The original error is in
128
+ * `.cause`.
129
+ * @throws {SqlStackError} When called outside a @Query method, when passed
130
+ * `.toSQL()` output, or for shape/validation failures.
131
+ */
132
+ export declare function run<T = unknown, P extends object = object>(db: RunDatabase | string, params: P & RejectCompiledSql<P>): Promise<T>;
133
+ /** @internal A database chosen for one run, plus the transaction it joins. */
134
+ export type RunTarget = {
135
+ readonly db: RunDatabase;
136
+ readonly tx: ActiveTransaction | undefined;
137
+ /** SQL resolver of the environment, when the target was resolved by name. */
138
+ readonly resolver: SqlResolver | undefined;
139
+ readonly byName: boolean;
140
+ };
141
+ /**
142
+ * @internal Resolve run's database argument. A name goes through the active
143
+ * SqlStack (or legacy registry) and joins that entry's transaction. A handle
144
+ * is used as-is — no registry lookup, so it works without any SqlStack — and
145
+ * joins an active transaction only if one is open on that same handle.
146
+ */
147
+ export declare function resolveRunTarget(db: RunDatabase | string): Promise<RunTarget>;
148
+ /** @internal Run one bound statement on the target (inside its transaction, if any). */
149
+ export declare function executeOnTarget(target: RunTarget, boundSql: string, params: unknown[]): Promise<unknown>;
150
+ /**
151
+ * @internal Normalize a failure from run's argument-taking forms: errors that
152
+ * are already SqlStackError (DatabaseError, shape/validation errors) pass
153
+ * through; anything else becomes DatabaseError with the original in `.cause`.
154
+ */
155
+ export declare function toRunError(err: unknown, sqlText: string): SqlStackError;
156
+ /** @internal Raw template text of a fragment, for error messages. */
157
+ export declare function fragmentText(fragment: SqlFragment): string;
158
+ /** @internal Compile a fragment for the dialect, wrapping macro errors. */
159
+ export declare function compileForRun(fragment: SqlFragment, dialect: Dialect): {
160
+ sql: string;
161
+ params: unknown[];
162
+ };
29
163
  //# sourceMappingURL=run.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../src/run.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAGrD;;;;;;GAMG;AACH,MAAM,MAAM,UAAU,GAAG;IACvB,OAAO,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IAChC,GAAG,EAAE,OAAO,CAAC;CACd,CAAC;AAUF,eAAO,MAAM,UAAU,EAA0B,iBAAiB,CAAC,UAAU,CAAC,CAAC;AAE/E;;;;;;;;;;;;;GAaG;AACH,wBAAsB,GAAG,CAAC,CAAC,GAAG,GAAG,KAAK,OAAO,CAAC,CAAC,CAAC,CAS/C"}
1
+ {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../src/run.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAiB,MAAM,eAAe,CAAC;AAC7D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAkC,MAAM,OAAO,CAAC;AAEpE,OA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E,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,aAAa,CAEvE;AAWD,qEAAqE;AACrE,wBAAgB,YAAY,CAAC,QAAQ,EAAE,WAAW,GAAG,MAAM,CAE1D;AAED,2EAA2E;AAC3E,wBAAgB,aAAa,CAAC,QAAQ,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,OAAO,EAAE,CAAA;CAAE,CAMzG"}
package/dist/cjs/run.js CHANGED
@@ -2,8 +2,16 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.runStorage = void 0;
4
4
  exports.run = run;
5
+ exports.resolveRunTarget = resolveRunTarget;
6
+ exports.executeOnTarget = executeOnTarget;
7
+ exports.toRunError = toRunError;
8
+ exports.fragmentText = fragmentText;
9
+ exports.compileForRun = compileForRun;
5
10
  const node_async_hooks_1 = require("node:async_hooks");
6
11
  const errors_1 = require("./core/errors");
12
+ const sql_1 = require("./sql");
13
+ const runtime_1 = require("./runtime");
14
+ const transactions_1 = require("./transactions");
7
15
  // Anchored on globalThis via Symbol.for so duplicated module instances
8
16
  // (npm link, dual ESM/CJS loads) share one channel between the decorator
9
17
  // and the run() the application imports.
@@ -13,26 +21,128 @@ if (!anchor[RUN_CHANNEL]) {
13
21
  anchor[RUN_CHANNEL] = new node_async_hooks_1.AsyncLocalStorage();
14
22
  }
15
23
  exports.runStorage = anchor[RUN_CHANNEL];
16
- /**
17
- * Execute the current @Query method's SQL and return the finished result.
18
- * Call it as the body of a @Query-decorated method in place of the legacy
19
- * placeholder throw:
20
- *
21
- * @Query()
22
- * async getUsers(active: boolean): Promise<User[]> {
23
- * return run<User[]>();
24
- * }
25
- *
26
- * Takes no arguments — the method's own arguments, database, SQL source,
27
- * transaction, shaping, transform, and validation all come from the
28
- * decorator context. The generic is a typing convenience only.
29
- */
30
- async function run() {
24
+ async function run(...args) {
25
+ const invocation = parseRunArgs(args);
31
26
  const ctx = exports.runStorage.getStore();
32
27
  if (!ctx) {
33
- throw new errors_1.SqlStackError('run() called outside a @Query method. It may only be invoked from the body of a @Query-decorated method.');
28
+ if (invocation.kind === 'fragment' && invocation.db !== undefined) {
29
+ return executeFragment(invocation.db, invocation.fragment);
30
+ }
31
+ if (invocation.kind === 'default') {
32
+ throw new errors_1.SqlStackError('run() called outside a @Query method. It may only be invoked from the body of a @Query-decorated method.');
33
+ }
34
+ if (invocation.kind === 'fragment') {
35
+ throw new errors_1.SqlStackError('run(query) called outside a @Query method has no database. Pass one explicitly: run(db, query).');
36
+ }
37
+ throw new errors_1.SqlStackError('run(db, params) called outside a @Query method has no SQL source. ' +
38
+ 'Pass an sql`` fragment instead: run(db, sql`...`).');
39
+ }
40
+ if (invocation.kind !== 'default' && !ctx.invocations) {
41
+ throw new errors_1.SqlStackError('run(...) with arguments reached a @Query wrapper from an older sqlstack copy that cannot honour them. ' +
42
+ 'Make sure a single sqlstack version is installed.');
34
43
  }
35
44
  ctx.ran = true;
36
- return ctx.execute();
45
+ return invocation.kind === 'default' ? ctx.execute() : ctx.execute(invocation);
46
+ }
47
+ function parseRunArgs(args) {
48
+ if (args.length === 0)
49
+ return { kind: 'default' };
50
+ if (args.length === 1) {
51
+ const [query] = args;
52
+ if ((0, sql_1.isSqlFragment)(query))
53
+ return { kind: 'fragment', fragment: query };
54
+ throw new errors_1.SqlStackError(typeof query === 'string'
55
+ ? 'run(query) does not accept SQL strings. Build the statement with the sql`` tag: run(sql`...`).'
56
+ : 'run(query) requires an sql`` fragment.');
57
+ }
58
+ if (args.length === 2) {
59
+ const [db, second] = args;
60
+ assertRunDatabase(db);
61
+ if ((0, sql_1.isSqlFragment)(second))
62
+ return { kind: 'fragment', db, fragment: second };
63
+ if (typeof second === 'string') {
64
+ throw new errors_1.SqlStackError('run(db, query) does not accept SQL strings. Build the statement with the sql`` tag: run(db, sql`...`).');
65
+ }
66
+ if (isCompiledSql(second)) {
67
+ throw new errors_1.SqlStackError('run(db, ...) received the { sql, params } output of .toSQL(). Pass the sql`` fragment itself so run can ' +
68
+ 'bind it for the target dialect: run(db, sql`...`).');
69
+ }
70
+ if (typeof second === 'object' && second !== null)
71
+ return { kind: 'params', db, params: second };
72
+ throw new errors_1.SqlStackError('run(db, x) requires an sql`` fragment or a params object/array as its second argument.');
73
+ }
74
+ throw new errors_1.SqlStackError(`run() accepts at most 2 arguments, got ${args.length}.`);
75
+ }
76
+ function assertRunDatabase(db) {
77
+ if (typeof db === 'string' && db.length > 0)
78
+ return;
79
+ if (typeof db === 'object' && db !== null && typeof db.query === 'function')
80
+ return;
81
+ throw new errors_1.SqlStackError('run(db, ...) requires a database handle with query(sql, params) or a registered database name as its first argument.');
82
+ }
83
+ function isCompiledSql(value) {
84
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
85
+ return false;
86
+ const keys = Object.keys(value);
87
+ const rec = value;
88
+ return keys.length === 2 && typeof rec.sql === 'string' && Array.isArray(rec.params);
89
+ }
90
+ /**
91
+ * @internal Resolve run's database argument. A name goes through the active
92
+ * SqlStack (or legacy registry) and joins that entry's transaction. A handle
93
+ * is used as-is — no registry lookup, so it works without any SqlStack — and
94
+ * joins an active transaction only if one is open on that same handle.
95
+ */
96
+ async function resolveRunTarget(db) {
97
+ if (typeof db === 'string') {
98
+ const { entry, resolver } = await (0, runtime_1.resolveExecution)(db);
99
+ return { db: entry.db, tx: (0, transactions_1.getActiveTransaction)(entry), resolver, byName: true };
100
+ }
101
+ return { db, tx: (0, transactions_1.getActiveTransactionForDatabase)(db), resolver: undefined, byName: false };
102
+ }
103
+ /** @internal Run one bound statement on the target (inside its transaction, if any). */
104
+ async function executeOnTarget(target, boundSql, params) {
105
+ try {
106
+ return target.tx ? await target.tx.query(boundSql, params) : await target.db.query(boundSql, params);
107
+ }
108
+ catch (dbError) {
109
+ throw toDatabaseError(dbError, boundSql);
110
+ }
111
+ }
112
+ /**
113
+ * @internal Normalize a failure from run's argument-taking forms: errors that
114
+ * are already SqlStackError (DatabaseError, shape/validation errors) pass
115
+ * through; anything else becomes DatabaseError with the original in `.cause`.
116
+ */
117
+ function toRunError(err, sqlText) {
118
+ return err instanceof errors_1.SqlStackError ? err : toDatabaseError(err, sqlText);
119
+ }
120
+ function toDatabaseError(err, sqlText) {
121
+ const message = err?.message;
122
+ return new errors_1.DatabaseError(typeof message === 'string' && message ? message : String(err), sqlText, err instanceof Error ? err : undefined);
123
+ }
124
+ /** @internal Raw template text of a fragment, for error messages. */
125
+ function fragmentText(fragment) {
126
+ return fragment.strings.join('?');
127
+ }
128
+ /** @internal Compile a fragment for the dialect, wrapping macro errors. */
129
+ function compileForRun(fragment, dialect) {
130
+ try {
131
+ return (0, sql_1.compileFragment)(fragment, dialect);
132
+ }
133
+ catch (err) {
134
+ throw toRunError(err, fragmentText(fragment));
135
+ }
136
+ }
137
+ async function executeFragment(db, fragment) {
138
+ let target;
139
+ try {
140
+ target = await resolveRunTarget(db);
141
+ }
142
+ catch (err) {
143
+ throw toRunError(err, fragmentText(fragment));
144
+ }
145
+ const { sql: boundSql, params } = compileForRun(fragment, target.db.dialect ?? 'sqlite');
146
+ return executeOnTarget(target, boundSql, params);
37
147
  }
38
148
  //# sourceMappingURL=run.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"run.js","sourceRoot":"","sources":["../../src/run.ts"],"names":[],"mappings":";;;AAuCA,kBASC;AAhDD,uDAAqD;AACrD,0CAA8C;AAc9C,uEAAuE;AACvE,yEAAyE;AACzE,yCAAyC;AACzC,MAAM,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AAC5D,MAAM,MAAM,GAAG,UAA0C,CAAC;AAC1D,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,EAAE,CAAC;IACzB,MAAM,CAAC,WAAW,CAAC,GAAG,IAAI,oCAAiB,EAAc,CAAC;AAC5D,CAAC;AACY,QAAA,UAAU,GAAG,MAAM,CAAC,WAAW,CAAkC,CAAC;AAE/E;;;;;;;;;;;;;GAaG;AACI,KAAK,UAAU,GAAG;IACvB,MAAM,GAAG,GAAG,kBAAU,CAAC,QAAQ,EAAE,CAAC;IAClC,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,MAAM,IAAI,sBAAa,CACrB,0GAA0G,CAC3G,CAAC;IACJ,CAAC;IACD,GAAG,CAAC,GAAG,GAAG,IAAI,CAAC;IACf,OAAO,GAAG,CAAC,OAAO,EAAgB,CAAC;AACrC,CAAC","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { SqlStackError } from './core/errors';\n\n/**\n * Per-invocation context established by the @Query wrapper before the method\n * body executes. `execute` performs the full query pipeline (resolve SQL,\n * bind, execute, shape/transform/validate); `ran` records that the body\n * invoked run(), so the wrapper returns the body's result verbatim instead\n * of falling through to the legacy pipeline.\n */\nexport type RunContext = {\n execute: () => Promise<unknown>;\n ran: boolean;\n};\n\n// Anchored on globalThis via Symbol.for so duplicated module instances\n// (npm link, dual ESM/CJS loads) share one channel between the decorator\n// and the run() the application imports.\nconst RUN_CHANNEL = Symbol.for('noego.sqlstack.runContext');\nconst anchor = globalThis as Record<PropertyKey, unknown>;\nif (!anchor[RUN_CHANNEL]) {\n anchor[RUN_CHANNEL] = new AsyncLocalStorage<RunContext>();\n}\nexport const runStorage = anchor[RUN_CHANNEL] as AsyncLocalStorage<RunContext>;\n\n/**\n * Execute the current @Query method's SQL and return the finished result.\n * Call it as the body of a @Query-decorated method in place of the legacy\n * placeholder throw:\n *\n * @Query()\n * async getUsers(active: boolean): Promise<User[]> {\n * return run<User[]>();\n * }\n *\n * Takes no arguments — the method's own arguments, database, SQL source,\n * transaction, shaping, transform, and validation all come from the\n * decorator context. The generic is a typing convenience only.\n */\nexport async function run<T = any>(): Promise<T> {\n const ctx = runStorage.getStore();\n if (!ctx) {\n throw new SqlStackError(\n 'run() called outside a @Query method. It may only be invoked from the body of a @Query-decorated method.'\n );\n }\n ctx.ran = true;\n return ctx.execute() as Promise<T>;\n}\n"]}
1
+ {"version":3,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AAC,GAAG,CAAC,EAC9D,OAAO,EACP,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CACvC,CAAC;AACJ,CAAC;AAED,qEAAqE;AACrE,SAAgB,YAAY,CAAC,QAAqB;IAChD,OAAO,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACpC,CAAC;AAED,2EAA2E;AAC3E,SAAgB,aAAa,CAAC,QAAqB,EAAE,OAAgB;IACnE,IAAI,CAAC;QACH,OAAO,IAAA,qBAAe,EAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC5C,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,UAAU,CAAC,GAAG,EAAE,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC;IAChD,CAAC;AACH,CAAC;AAED,KAAK,UAAU,eAAe,CAAC,EAAwB,EAAE,QAAqB;IAC5E,IAAI,MAAiB,CAAC;IACtB,IAAI,CAAC;QACH,MAAM,GAAG,MAAM,gBAAgB,CAAC,EAAE,CAAC,CAAC;IACtC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,UAAU,CAAC,GAAG,EAAE,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC;IAChD,CAAC;IACD,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,aAAa,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,CAAC,OAAO,IAAI,QAAQ,CAAC,CAAC;IACzF,OAAO,eAAe,CAAC,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { SqlStackError, DatabaseError } from './core/errors';\nimport type { Dialect } from './registry';\nimport { SqlFragment, isSqlFragment, compileFragment } from './sql';\nimport { resolveExecution } from './runtime';\nimport type { SqlResolver } from './core/resolver';\nimport { getActiveTransaction, getActiveTransactionForDatabase } from './transactions';\nimport type { ActiveTransaction } from './transactions';\n\n/**\n * Anything run(db, ...) can execute against: sqlstack's own `Database`\n * (from createSqliteDb/createPgDb/createMysqlDb), or any application handle\n * exposing `query(sql, params)`. `dialect` selects placeholder style and\n * defaults to `'sqlite'` when absent. run never opens databases by path.\n */\nexport interface RunDatabase {\n readonly dialect?: Dialect;\n query(sql: string, params: unknown[]): Promise<unknown>;\n}\n\n/**\n * Type-level guard for the params form of run: rejects the\n * `{ sql, params }` object returned by `fragment.toSQL()`. Pass the sql``\n * fragment itself instead, so run owns dialect binding and error handling.\n */\nexport type RejectCompiledSql<P> = P extends { readonly sql: string; readonly params: readonly unknown[] }\n ? never\n : unknown;\n\n/**\n * What a run(...) call made inside a @Query body asks of the wrapper's\n * pipeline. `default` is the zero-argument run().\n */\nexport type RunInvocation =\n | { readonly kind: 'default' }\n | { readonly kind: 'fragment'; readonly db?: RunDatabase | string; readonly fragment: SqlFragment }\n | { readonly kind: 'params'; readonly db: RunDatabase | string; readonly params: object };\n\n/**\n * Per-invocation context established by the @Query wrapper before the method\n * body executes. `execute` performs the full query pipeline (resolve SQL,\n * bind, execute, shape/transform/validate); `ran` records that the body\n * invoked run(), so the wrapper returns the body's result verbatim instead\n * of falling through to the legacy pipeline. `invocations` marks a wrapper\n * that understands the argument-taking run forms (an older duplicated copy\n * of the decorator would silently ignore them).\n */\nexport type RunContext = {\n execute: (invocation?: RunInvocation) => Promise<unknown>;\n ran: boolean;\n invocations?: true;\n};\n\n// Anchored on globalThis via Symbol.for so duplicated module instances\n// (npm link, dual ESM/CJS loads) share one channel between the decorator\n// and the run() the application imports.\nconst RUN_CHANNEL = Symbol.for('noego.sqlstack.runContext');\nconst anchor = globalThis as Record<PropertyKey, unknown>;\nif (!anchor[RUN_CHANNEL]) {\n anchor[RUN_CHANNEL] = new AsyncLocalStorage<RunContext>();\n}\nexport const runStorage = anchor[RUN_CHANNEL] as AsyncLocalStorage<RunContext>;\n\n/**\n * Execute the current @Query method's SQL and return the finished result.\n * Call it as the body of a @Query-decorated method:\n *\n * @Query()\n * async getUsers(active: boolean): Promise<User[]> {\n * return run();\n * }\n *\n * Takes no arguments — the method's own arguments, database, SQL source,\n * transaction, shaping, transform, and validation all come from the\n * decorator context. T is inferred from the method's declared return type.\n *\n * @throws {DatabaseError} When the driver rejects the statement (original\n * error in `.cause`).\n * @throws {SqlStackError} When called outside a @Query method, or for\n * shape/validation failures (ExactlyOneRowError, NoRowsError, ValidationError, ...).\n */\nexport function run<T = any>(): Promise<T>;\n/**\n * Inside a @Query method: execute this inline sql`` fragment instead of the\n * method's SQL file. The database comes from the method/class/registry\n * context (`@Query({ db })`, `@QueryBinder({ db })`, the default), the\n * active transaction on it is joined, and the method's shape/transform/\n * validation decorators apply. The method's arguments are not auto-bound —\n * the fragment's `${}` values are the parameters.\n *\n * @Single @Query()\n * async byEmail(email: string): Promise<User | null> {\n * return run(sql`SELECT * FROM users WHERE email = ${email}`);\n * }\n *\n * @throws {DatabaseError} When the fragment cannot be compiled (macro input\n * errors), the database cannot be resolved, or the driver rejects the\n * statement. The original error is in `.cause`.\n * @throws {SqlStackError} When called outside a @Query method (use\n * `run(db, query)` there), or for shape/validation failures.\n */\nexport function run<T = unknown>(query: SqlFragment): Promise<T>;\n/**\n * Execute an sql`` fragment against an explicit database: a handle\n * (anything with `query(sql, params)`) or the name of a database registered\n * with the active SqlStack / legacy registry. Usable anywhere.\n *\n * Binds for the database's dialect (`$1..` for Postgres, `?` otherwise;\n * default sqlite). Joins an active transaction opened on the same database\n * (same registered handle, or same name). Outside a @Query method the raw\n * result is returned (rows array, or `{ rowsAffected }` for writes); inside\n * one, the method's shape/transform/validation decorators apply.\n *\n * const rows = await run<Row[]>(accountsDb, sql`SELECT * FROM t WHERE id = ${id}`);\n *\n * @throws {DatabaseError} When the fragment cannot be compiled, a named\n * database cannot be resolved, or the driver rejects the statement. The\n * original error is in `.cause`, and its string `code` is copied to `.code`.\n * @throws {SqlStackError} For invalid arguments, or shape/validation failures.\n */\nexport function run<T = unknown>(db: RunDatabase | string, query: SqlFragment): Promise<T>;\n/**\n * Inside a @Query method: run the method's own SQL (its .sql file or inline\n * `@Query({ sql })`) against `db`, binding `params` (an object for `:named`\n * placeholders, an array for `:arg1..`). The method's raw arguments are NOT\n * auto-bound in this form — `params` is the whole binding input. @Defaults,\n * @Page, shaping, transform, and validation still apply.\n *\n * @Single @Query()\n * async byEmail(db: Database, p: { email: string }): Promise<User | null> {\n * return run(db, p);\n * }\n *\n * @throws {DatabaseError} When binding fails, a named database cannot be\n * resolved, or the driver rejects the statement. The original error is in\n * `.cause`.\n * @throws {SqlStackError} When called outside a @Query method, when passed\n * `.toSQL()` output, or for shape/validation failures.\n */\nexport function run<T = unknown, P extends object = object>(\n db: RunDatabase | string,\n params: P & RejectCompiledSql<P>\n): Promise<T>;\nexport async function run(...args: unknown[]): Promise<unknown> {\n const invocation = parseRunArgs(args);\n const ctx = runStorage.getStore();\n\n if (!ctx) {\n if (invocation.kind === 'fragment' && invocation.db !== undefined) {\n return executeFragment(invocation.db, invocation.fragment);\n }\n if (invocation.kind === 'default') {\n throw new SqlStackError(\n 'run() called outside a @Query method. It may only be invoked from the body of a @Query-decorated method.'\n );\n }\n if (invocation.kind === 'fragment') {\n throw new SqlStackError(\n 'run(query) called outside a @Query method has no database. Pass one explicitly: run(db, query).'\n );\n }\n throw new SqlStackError(\n 'run(db, params) called outside a @Query method has no SQL source. ' +\n 'Pass an sql`` fragment instead: run(db, sql`...`).'\n );\n }\n\n if (invocation.kind !== 'default' && !ctx.invocations) {\n throw new SqlStackError(\n 'run(...) with arguments reached a @Query wrapper from an older sqlstack copy that cannot honour them. ' +\n 'Make sure a single sqlstack version is installed.'\n );\n }\n\n ctx.ran = true;\n return invocation.kind === 'default' ? ctx.execute() : ctx.execute(invocation);\n}\n\nfunction parseRunArgs(args: unknown[]): RunInvocation {\n if (args.length === 0) return { kind: 'default' };\n\n if (args.length === 1) {\n const [query] = args;\n if (isSqlFragment(query)) return { kind: 'fragment', fragment: query };\n throw new SqlStackError(\n typeof query === 'string'\n ? 'run(query) does not accept SQL strings. Build the statement with the sql`` tag: run(sql`...`).'\n : 'run(query) requires an sql`` fragment.'\n );\n }\n\n if (args.length === 2) {\n const [db, second] = args;\n assertRunDatabase(db);\n if (isSqlFragment(second)) return { kind: 'fragment', db, fragment: second };\n if (typeof second === 'string') {\n throw new SqlStackError(\n 'run(db, query) does not accept SQL strings. Build the statement with the sql`` tag: run(db, sql`...`).'\n );\n }\n if (isCompiledSql(second)) {\n throw new SqlStackError(\n 'run(db, ...) received the { sql, params } output of .toSQL(). Pass the sql`` fragment itself so run can ' +\n 'bind it for the target dialect: run(db, sql`...`).'\n );\n }\n if (typeof second === 'object' && second !== null) return { kind: 'params', db, params: second };\n throw new SqlStackError('run(db, x) requires an sql`` fragment or a params object/array as its second argument.');\n }\n\n throw new SqlStackError(`run() accepts at most 2 arguments, got ${args.length}.`);\n}\n\nfunction assertRunDatabase(db: unknown): asserts db is RunDatabase | string {\n if (typeof db === 'string' && db.length > 0) return;\n if (typeof db === 'object' && db !== null && typeof (db as { query?: unknown }).query === 'function') return;\n throw new SqlStackError(\n 'run(db, ...) requires a database handle with query(sql, params) or a registered database name as its first argument.'\n );\n}\n\nfunction isCompiledSql(value: unknown): boolean {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const keys = Object.keys(value);\n const rec = value as { sql?: unknown; params?: unknown };\n return keys.length === 2 && typeof rec.sql === 'string' && Array.isArray(rec.params);\n}\n\n// ---------------------------------------------------------------------------\n// Shared execution helpers (also used by the @Query wrapper)\n// ---------------------------------------------------------------------------\n\n/** @internal A database chosen for one run, plus the transaction it joins. */\nexport type RunTarget = {\n readonly db: RunDatabase;\n readonly tx: ActiveTransaction | undefined;\n /** SQL resolver of the environment, when the target was resolved by name. */\n readonly resolver: SqlResolver | undefined;\n readonly byName: boolean;\n};\n\n/**\n * @internal Resolve run's database argument. A name goes through the active\n * SqlStack (or legacy registry) and joins that entry's transaction. A handle\n * is used as-is — no registry lookup, so it works without any SqlStack — and\n * joins an active transaction only if one is open on that same handle.\n */\nexport async function resolveRunTarget(db: RunDatabase | string): Promise<RunTarget> {\n if (typeof db === 'string') {\n const { entry, resolver } = await resolveExecution(db);\n return { db: entry.db, tx: getActiveTransaction(entry), resolver, byName: true };\n }\n return { db, tx: getActiveTransactionForDatabase(db), resolver: undefined, byName: false };\n}\n\n/** @internal Run one bound statement on the target (inside its transaction, if any). */\nexport async function executeOnTarget(target: RunTarget, boundSql: string, params: unknown[]): Promise<unknown> {\n try {\n return target.tx ? await target.tx.query(boundSql, params) : await target.db.query(boundSql, params);\n } catch (dbError) {\n throw toDatabaseError(dbError, boundSql);\n }\n}\n\n/**\n * @internal Normalize a failure from run's argument-taking forms: errors that\n * are already SqlStackError (DatabaseError, shape/validation errors) pass\n * through; anything else becomes DatabaseError with the original in `.cause`.\n */\nexport function toRunError(err: unknown, sqlText: string): SqlStackError {\n return err instanceof SqlStackError ? err : toDatabaseError(err, sqlText);\n}\n\nfunction toDatabaseError(err: unknown, sqlText: string): DatabaseError {\n const message = (err as { message?: unknown } | undefined)?.message;\n return new DatabaseError(\n typeof message === 'string' && message ? message : String(err),\n sqlText,\n err instanceof Error ? err : undefined\n );\n}\n\n/** @internal Raw template text of a fragment, for error messages. */\nexport function fragmentText(fragment: SqlFragment): string {\n return fragment.strings.join('?');\n}\n\n/** @internal Compile a fragment for the dialect, wrapping macro errors. */\nexport function compileForRun(fragment: SqlFragment, dialect: Dialect): { sql: string; params: unknown[] } {\n try {\n return compileFragment(fragment, dialect);\n } catch (err) {\n throw toRunError(err, fragmentText(fragment));\n }\n}\n\nasync function executeFragment(db: RunDatabase | string, fragment: SqlFragment): Promise<unknown> {\n let target: RunTarget;\n try {\n target = await resolveRunTarget(db);\n } catch (err) {\n throw toRunError(err, fragmentText(fragment));\n }\n const { sql: boundSql, params } = compileForRun(fragment, target.db.dialect ?? 'sqlite');\n return executeOnTarget(target, boundSql, params);\n}\n"]}
@@ -20,6 +20,14 @@ export type ResolvedExecution = {
20
20
  * Resolve the concrete database entry (and SQL resolver) for one execution.
21
21
  */
22
22
  export declare function resolveExecution(dbName?: string): Promise<ResolvedExecution>;
23
+ /**
24
+ * @internal The SQL source resolver for one execution WITHOUT resolving a
25
+ * database — used when the caller supplied a database handle directly
26
+ * (`run(db, params)`). Same environment rules as resolveExecution: the
27
+ * active root's SqlStack resolver when an IoC environment is active (and an
28
+ * error when that environment has no SqlStack), else the legacy global one.
29
+ */
30
+ export declare function resolveSqlResolver(): Promise<SqlResolver | undefined>;
23
31
  /** @internal Resolve a legacy global-registry database as a DatabaseEntry. */
24
32
  export declare function legacyEntry(dbName?: string): DatabaseEntry;
25
33
  //# sourceMappingURL=runtime.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAGlD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAyCnD,6DAA6D;AAC7D,wBAAgB,mBAAmB,IAAI,IAAI,CAE1C;AAkBD;;;;;;GAMG;AACH,wBAAsB,cAAc,IAAI,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC,CAyBpE;AAED,MAAM,MAAM,iBAAiB,GAAG;IAC9B,KAAK,EAAE,aAAa,CAAC;IACrB,QAAQ,EAAE,WAAW,GAAG,SAAS,CAAC;IAClC,gEAAgE;IAChE,QAAQ,EAAE,OAAO,CAAC;CACnB,CAAC;AAEF;;GAEG;AACH,wBAAsB,gBAAgB,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAUlF;AAgBD,8EAA8E;AAC9E,wBAAgB,WAAW,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,aAAa,CAQ1D"}
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAGlD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAyCnD,6DAA6D;AAC7D,wBAAgB,mBAAmB,IAAI,IAAI,CAE1C;AAkBD;;;;;;GAMG;AACH,wBAAsB,cAAc,IAAI,OAAO,CAAC,QAAQ,GAAG,SAAS,CAAC,CAyBpE;AAED,MAAM,MAAM,iBAAiB,GAAG;IAC9B,KAAK,EAAE,aAAa,CAAC;IACrB,QAAQ,EAAE,WAAW,GAAG,SAAS,CAAC;IAClC,gEAAgE;IAChE,QAAQ,EAAE,OAAO,CAAC;CACnB,CAAC;AAEF;;GAEG;AACH,wBAAsB,gBAAgB,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAUlF;AAED;;;;;;GAMG;AACH,wBAAsB,kBAAkB,IAAI,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC,CAG3E;AAgBD,8EAA8E;AAC9E,wBAAgB,WAAW,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,aAAa,CAQ1D"}
@@ -36,6 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.__resetIocDetection = __resetIocDetection;
37
37
  exports.activeSqlStack = activeSqlStack;
38
38
  exports.resolveExecution = resolveExecution;
39
+ exports.resolveSqlResolver = resolveSqlResolver;
39
40
  exports.legacyEntry = legacyEntry;
40
41
  const stack_1 = require("./stack");
41
42
  const registry_1 = require("./registry");
@@ -111,6 +112,17 @@ async function resolveExecution(dbName) {
111
112
  viaStack: false,
112
113
  };
113
114
  }
115
+ /**
116
+ * @internal The SQL source resolver for one execution WITHOUT resolving a
117
+ * database — used when the caller supplied a database handle directly
118
+ * (`run(db, params)`). Same environment rules as resolveExecution: the
119
+ * active root's SqlStack resolver when an IoC environment is active (and an
120
+ * error when that environment has no SqlStack), else the legacy global one.
121
+ */
122
+ async function resolveSqlResolver() {
123
+ const stack = await activeSqlStack();
124
+ return stack ? stack.resolver() : (0, resolver_1.getActiveResolver)();
125
+ }
114
126
  // ---------------------------------------------------------------------------
115
127
  // Legacy (deprecated) global-registry support
116
128
  // ---------------------------------------------------------------------------
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/runtime.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,kDAEC;AAyBD,wCAyBC;AAYD,4CAUC;AAiBD,kCAQC;AAhJD,mCAAkD;AAClD,yCAAwC;AAGxC,8CAAoD;AACpD,0CAA8C;AA0B9C,0EAA0E;AAC1E,yEAAyE;AACzE,mEAAmE;AACnE,IAAI,gBAA4D,CAAC;AAEjE,SAAS,OAAO;IACd,gBAAgB,KAAhB,gBAAgB,GAAK,kDAAO,YAAY,IAAE,IAAI,CAC5C,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,gBAAgB,CAAC,CAAC,CAAE,CAAe,CAAC,CAAC,CAAC,SAAS,CAAC,EAChE,GAAG,EAAE,CAAC,SAAS,CAChB,EAAC;IACF,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAED,6DAA6D;AAC7D,SAAgB,mBAAmB;IACjC,gBAAgB,GAAG,SAAS,CAAC;AAC/B,CAAC;AAED,SAAS,0BAA0B;IACjC,OAAO,IAAI,sBAAa,CACtB,+EAA+E;QAC7E,mFAAmF,CACtF,CAAC;AACJ,CAAC;AAED,SAAS,4BAA4B,CAAC,GAAc,EAAE,GAAY;IAChE,MAAM,uBAAuB,GAAG,GAAG,CAAC,uBAAuB,CAAC;IAC5D,OAAO,CACL,OAAO,uBAAuB,KAAK,UAAU;QAC7C,GAAG,YAAY,uBAAuB;QACtC,GAAG,CAAC,OAAO,KAAK,gCAAgC,CACjD,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACI,KAAK,UAAU,cAAc;IAClC,MA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AC;AAED,8EAA8E;AAC9E,8CAA8C;AAC9C,8EAA8E;AAE9E,yEAAyE;AACzE,0EAA0E;AAC1E,0EAA0E;AAC1E,uDAAuD;AACvD,MAAM,aAAa,GAAG,IAAI,GAAG,EAAkD,CAAC;AAEhF,8EAA8E;AAC9E,+DAA+D;AAC/D,IAAI,WAAiC,CAAC;AAEtC,8EAA8E;AAC9E,SAAgB,WAAW,CAAC,MAAe;IACzC,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,qBAAU,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACjD,MAAM,MAAM,GAAG,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACvC,IAAI,MAAM,IAAI,MAAM,CAAC,EAAE,KAAK,EAAE;QAAE,OAAO,MAAM,CAAC,KAAK,CAAC;IACpD,WAAW,KAAX,WAAW,GAAK,IAAI,gBAAQ,EAAE,EAAC;IAC/B,MAAM,KAAK,GAAkB,EAAE,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC;IAC5E,aAAa,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;IACvC,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { SqlStack, DatabaseEntry } from './stack';\nimport { SqlStackDB } from './registry';\nimport type { Database } from './registry';\nimport type { SqlResolver } from './core/resolver';\nimport { getActiveResolver } from './core/resolver';\nimport { SqlStackError } from './core/errors';\n\n/**\n * Active-environment resolution for @Query and transactions (spec 16 §17,\n * repo spec 19 §7/§9).\n *\n * Canonical path: the active IoC execution context (owned by @noego/ioc)\n * supplies the current scope; the scope resolves its root's SqlStack\n * Singleton. When an IoC environment is active, the process-global legacy\n * registry is NEVER consulted — legacy state cannot override an active root.\n *\n * Legacy path: with no active IoC environment, execution falls back to the\n * deprecated process-global SqlStackDB registry so existing consumers keep\n * working during migration.\n */\n\ntype IocModule = {\n ExecutionContext: { current(): any };\n DependencyNotFoundError?: new (...args: any[]) => Error;\n};\n\ntype ActiveScope = {\n get(label: any): unknown;\n isRegistered?(label: any): boolean;\n};\n\n// @noego/ioc is an optional peer: sqlstack remains usable standalone. The\n// import is dynamic so the CJS and ESM builds both work and so a missing\n// peer only disables the IoC path instead of breaking module load.\nlet iocModulePromise: Promise<IocModule | undefined> | undefined;\n\nfunction loadIoc(): Promise<IocModule | undefined> {\n iocModulePromise ??= import('@noego/ioc').then(\n (m: any) => (m?.ExecutionContext ? (m as IocModule) : undefined),\n () => undefined\n );\n return iocModulePromise;\n}\n\n/** @internal Test-only: force re-detection of @noego/ioc. */\nexport function __resetIocDetection(): void {\n iocModulePromise = undefined;\n}\n\nfunction missingActiveSqlStackError(): SqlStackError {\n return new SqlStackError(\n 'An IoC execution environment is active, but no SqlStack is registered in it. ' +\n 'Register a SqlStack at root composition (see registerSqlStack in \"sqlstack/ioc\").'\n );\n}\n\nfunction isDirectMissingSqlStackError(ioc: IocModule, err: unknown): boolean {\n const DependencyNotFoundError = ioc.DependencyNotFoundError;\n return (\n typeof DependencyNotFoundError === 'function' &&\n err instanceof DependencyNotFoundError &&\n err.message === 'Dependency not found: SqlStack'\n );\n}\n\n/**\n * The SqlStack for the active IoC execution context, or undefined when no\n * IoC environment is active (or @noego/ioc is not installed).\n *\n * Throws when an environment IS active but has no SqlStack registered —\n * silently falling back to global state under an active root is forbidden.\n */\nexport async function activeSqlStack(): Promise<SqlStack | undefined> {\n const ioc = await loadIoc();\n if (!ioc) return undefined;\n const scope = ioc.ExecutionContext.current() as ActiveScope | undefined;\n if (!scope) return undefined;\n\n // Newer IoC peers expose exact-token registration knowledge. Consulting it\n // before resolution distinguishes an absent SqlStack from errors raised by a\n // registered SqlStack provider (including DependencyNotFoundError).\n const registrationKnown = typeof scope.isRegistered === 'function';\n if (registrationKnown && !scope.isRegistered!(SqlStack)) {\n throw missingActiveSqlStackError();\n }\n\n try {\n return (await scope.get(SqlStack)) as SqlStack;\n } catch (err) {\n // Older optional peers cannot answer isRegistered(). Their direct missing\n // error is recognized by exported error identity plus the exact SqlStack\n // label; nested provider errors retain their original identity.\n if (!registrationKnown && isDirectMissingSqlStackError(ioc, err)) {\n throw missingActiveSqlStackError();\n }\n throw err;\n }\n}\n\nexport type ResolvedExecution = {\n entry: DatabaseEntry;\n resolver: SqlResolver | undefined;\n /** True when resolved through an active IoC root's SqlStack. */\n viaStack: boolean;\n};\n\n/**\n * Resolve the concrete database entry (and SQL resolver) for one execution.\n */\nexport async function resolveExecution(dbName?: string): Promise<ResolvedExecution> {\n const stack = await activeSqlStack();\n if (stack) {\n return { entry: await stack.resolveEntry(dbName), resolver: stack.resolver(), viaStack: true };\n }\n return {\n entry: legacyEntry(dbName),\n resolver: getActiveResolver(),\n viaStack: false,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Legacy (deprecated) global-registry support\n// ---------------------------------------------------------------------------\n\n// Stable DatabaseEntry identities for the legacy global registry, so the\n// entry-keyed transaction store works identically on both paths. Keyed by\n// name AND database object so re-registration under a name yields a fresh\n// identity (matching the fresh underlying connection).\nconst legacyEntries = new Map<string, { db: Database; entry: DatabaseEntry }>();\n\n// One shared legacy pseudo-stack so legacy entries carry a stack identity for\n// diagnostics. It is intentionally NOT usable as a real stack.\nlet legacyStack: SqlStack | undefined;\n\n/** @internal Resolve a legacy global-registry database as a DatabaseEntry. */\nexport function legacyEntry(dbName?: string): DatabaseEntry {\n const { name, db } = SqlStackDB.getEntry(dbName);\n const cached = legacyEntries.get(name);\n if (cached && cached.db === db) return cached.entry;\n legacyStack ??= new SqlStack();\n const entry: DatabaseEntry = { name, db, owned: false, stack: legacyStack };\n legacyEntries.set(name, { db, entry });\n return entry;\n}\n"]}
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/runtime.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,kDAEC;AAyBD,wCAyBC;AAYD,4CAUC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a,GAAG,IAAI,GAAG,EAAkD,CAAC;AAEhF,8EAA8E;AAC9E,+DAA+D;AAC/D,IAAI,WAAiC,CAAC;AAEtC,8EAA8E;AAC9E,SAAgB,WAAW,CAAC,MAAe;IACzC,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,qBAAU,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACjD,MAAM,MAAM,GAAG,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACvC,IAAI,MAAM,IAAI,MAAM,CAAC,EAAE,KAAK,EAAE;QAAE,OAAO,MAAM,CAAC,KAAK,CAAC;IACpD,WAAW,KAAX,WAAW,GAAK,IAAI,gBAAQ,EAAE,EAAC;IAC/B,MAAM,KAAK,GAAkB,EAAE,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC;IAC5E,aAAa,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;IACvC,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { SqlStack, DatabaseEntry } from './stack';\nimport { SqlStackDB } from './registry';\nimport type { Database } from './registry';\nimport type { SqlResolver } from './core/resolver';\nimport { getActiveResolver } from './core/resolver';\nimport { SqlStackError } from './core/errors';\n\n/**\n * Active-environment resolution for @Query and transactions (spec 16 §17,\n * repo spec 19 §7/§9).\n *\n * Canonical path: the active IoC execution context (owned by @noego/ioc)\n * supplies the current scope; the scope resolves its root's SqlStack\n * Singleton. When an IoC environment is active, the process-global legacy\n * registry is NEVER consulted — legacy state cannot override an active root.\n *\n * Legacy path: with no active IoC environment, execution falls back to the\n * deprecated process-global SqlStackDB registry so existing consumers keep\n * working during migration.\n */\n\ntype IocModule = {\n ExecutionContext: { current(): any };\n DependencyNotFoundError?: new (...args: any[]) => Error;\n};\n\ntype ActiveScope = {\n get(label: any): unknown;\n isRegistered?(label: any): boolean;\n};\n\n// @noego/ioc is an optional peer: sqlstack remains usable standalone. The\n// import is dynamic so the CJS and ESM builds both work and so a missing\n// peer only disables the IoC path instead of breaking module load.\nlet iocModulePromise: Promise<IocModule | undefined> | undefined;\n\nfunction loadIoc(): Promise<IocModule | undefined> {\n iocModulePromise ??= import('@noego/ioc').then(\n (m: any) => (m?.ExecutionContext ? (m as IocModule) : undefined),\n () => undefined\n );\n return iocModulePromise;\n}\n\n/** @internal Test-only: force re-detection of @noego/ioc. */\nexport function __resetIocDetection(): void {\n iocModulePromise = undefined;\n}\n\nfunction missingActiveSqlStackError(): SqlStackError {\n return new SqlStackError(\n 'An IoC execution environment is active, but no SqlStack is registered in it. ' +\n 'Register a SqlStack at root composition (see registerSqlStack in \"sqlstack/ioc\").'\n );\n}\n\nfunction isDirectMissingSqlStackError(ioc: IocModule, err: unknown): boolean {\n const DependencyNotFoundError = ioc.DependencyNotFoundError;\n return (\n typeof DependencyNotFoundError === 'function' &&\n err instanceof DependencyNotFoundError &&\n err.message === 'Dependency not found: SqlStack'\n );\n}\n\n/**\n * The SqlStack for the active IoC execution context, or undefined when no\n * IoC environment is active (or @noego/ioc is not installed).\n *\n * Throws when an environment IS active but has no SqlStack registered —\n * silently falling back to global state under an active root is forbidden.\n */\nexport async function activeSqlStack(): Promise<SqlStack | undefined> {\n const ioc = await loadIoc();\n if (!ioc) return undefined;\n const scope = ioc.ExecutionContext.current() as ActiveScope | undefined;\n if (!scope) return undefined;\n\n // Newer IoC peers expose exact-token registration knowledge. Consulting it\n // before resolution distinguishes an absent SqlStack from errors raised by a\n // registered SqlStack provider (including DependencyNotFoundError).\n const registrationKnown = typeof scope.isRegistered === 'function';\n if (registrationKnown && !scope.isRegistered!(SqlStack)) {\n throw missingActiveSqlStackError();\n }\n\n try {\n return (await scope.get(SqlStack)) as SqlStack;\n } catch (err) {\n // Older optional peers cannot answer isRegistered(). Their direct missing\n // error is recognized by exported error identity plus the exact SqlStack\n // label; nested provider errors retain their original identity.\n if (!registrationKnown && isDirectMissingSqlStackError(ioc, err)) {\n throw missingActiveSqlStackError();\n }\n throw err;\n }\n}\n\nexport type ResolvedExecution = {\n entry: DatabaseEntry;\n resolver: SqlResolver | undefined;\n /** True when resolved through an active IoC root's SqlStack. */\n viaStack: boolean;\n};\n\n/**\n * Resolve the concrete database entry (and SQL resolver) for one execution.\n */\nexport async function resolveExecution(dbName?: string): Promise<ResolvedExecution> {\n const stack = await activeSqlStack();\n if (stack) {\n return { entry: await stack.resolveEntry(dbName), resolver: stack.resolver(), viaStack: true };\n }\n return {\n entry: legacyEntry(dbName),\n resolver: getActiveResolver(),\n viaStack: false,\n };\n}\n\n/**\n * @internal The SQL source resolver for one execution WITHOUT resolving a\n * database — used when the caller supplied a database handle directly\n * (`run(db, params)`). Same environment rules as resolveExecution: the\n * active root's SqlStack resolver when an IoC environment is active (and an\n * error when that environment has no SqlStack), else the legacy global one.\n */\nexport async function resolveSqlResolver(): Promise<SqlResolver | undefined> {\n const stack = await activeSqlStack();\n return stack ? stack.resolver() : getActiveResolver();\n}\n\n// ---------------------------------------------------------------------------\n// Legacy (deprecated) global-registry support\n// ---------------------------------------------------------------------------\n\n// Stable DatabaseEntry identities for the legacy global registry, so the\n// entry-keyed transaction store works identically on both paths. Keyed by\n// name AND database object so re-registration under a name yields a fresh\n// identity (matching the fresh underlying connection).\nconst legacyEntries = new Map<string, { db: Database; entry: DatabaseEntry }>();\n\n// One shared legacy pseudo-stack so legacy entries carry a stack identity for\n// diagnostics. It is intentionally NOT usable as a real stack.\nlet legacyStack: SqlStack | undefined;\n\n/** @internal Resolve a legacy global-registry database as a DatabaseEntry. */\nexport function legacyEntry(dbName?: string): DatabaseEntry {\n const { name, db } = SqlStackDB.getEntry(dbName);\n const cached = legacyEntries.get(name);\n if (cached && cached.db === db) return cached.entry;\n legacyStack ??= new SqlStack();\n const entry: DatabaseEntry = { name, db, owned: false, stack: legacyStack };\n legacyEntries.set(name, { db, entry });\n return entry;\n}\n"]}
package/dist/cjs/sql.d.ts CHANGED
@@ -1,11 +1,30 @@
1
+ import type { Dialect } from './registry';
1
2
  export declare class SqlFragment {
2
3
  readonly strings: readonly string[];
3
4
  readonly values: readonly unknown[];
4
5
  constructor(strings: readonly string[], values: readonly unknown[]);
6
+ /**
7
+ * Compile to SQL with `?` placeholders and the matching parameter list.
8
+ *
9
+ * @throws {Error} When a binder macro (`:insert`, `:update`, `:filter`,
10
+ * `:batch_insert`) receives invalid input. `run(...)` wraps this in
11
+ * DatabaseError with the original error in `.cause`.
12
+ */
5
13
  toSQL(): {
6
14
  sql: string;
7
15
  params: unknown[];
8
16
  };
9
17
  }
18
+ /** @internal True for a SqlFragment from this or any other sqlstack copy. */
19
+ export declare function isSqlFragment(value: unknown): value is SqlFragment;
20
+ /**
21
+ * @internal Compile a fragment for a dialect: `$1, $2, ...` for Postgres,
22
+ * `?` for SQLite and MySQL. Throws plain Error on invalid macro input
23
+ * (callers in run() wrap it).
24
+ */
25
+ export declare function compileFragment(fragment: SqlFragment, dialect: Dialect): {
26
+ sql: string;
27
+ params: unknown[];
28
+ };
10
29
  export declare function sql(strings: TemplateStringsArray, ...values: unknown[]): SqlFragment;
11
30
  //# sourceMappingURL=sql.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sql.d.ts","sourceRoot":"","sources":["../../src/sql.ts"],"names":[],"mappings":"AAaA,qBAAa,WAAW;aAEJ,OAAO,EAAE,SAAS,MAAM,EAAE;aAC1B,MAAM,EAAE,SAAS,OAAO,EAAE;gBAD1B,OAAO,EAAE,SAAS,MAAM,EAAE,EAC1B,MAAM,EAAE,SAAS,OAAO,EAAE;IAG5C,KAAK,IAAI;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,OAAO,EAAE,CAAA;KAAE;CA8B5C;AAwDD,wBAAgB,GAAG,CAAC,OAAO,EAAE,oBAAoB,EAAE,GAAG,MAAM,EAAE,OAAO,EAAE,GAAG,WAAW,CAEpF"}
1
+ {"version":3,"file":"sql.d.ts","sourceRoot":"","s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