sqlstack 3.4.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 (44) hide show
  1. package/dist/cjs/core/errors.d.ts +9 -0
  2. package/dist/cjs/core/errors.d.ts.map +1 -1
  3. package/dist/cjs/core/errors.js +10 -0
  4. package/dist/cjs/core/errors.js.map +1 -1
  5. package/dist/cjs/decorators/query.d.ts +14 -0
  6. package/dist/cjs/decorators/query.d.ts.map +1 -1
  7. package/dist/cjs/decorators/query.js +124 -17
  8. package/dist/cjs/decorators/query.js.map +1 -1
  9. package/dist/cjs/index.d.ts +1 -0
  10. package/dist/cjs/index.d.ts.map +1 -1
  11. package/dist/cjs/index.js +2 -1
  12. package/dist/cjs/index.js.map +1 -1
  13. package/dist/cjs/run.d.ts +140 -6
  14. package/dist/cjs/run.d.ts.map +1 -1
  15. package/dist/cjs/run.js +127 -17
  16. package/dist/cjs/run.js.map +1 -1
  17. package/dist/cjs/runtime.d.ts +8 -0
  18. package/dist/cjs/runtime.d.ts.map +1 -1
  19. package/dist/cjs/runtime.js +12 -0
  20. package/dist/cjs/runtime.js.map +1 -1
  21. package/dist/cjs/sql.d.ts +19 -0
  22. package/dist/cjs/sql.d.ts.map +1 -1
  23. package/dist/cjs/sql.js +66 -28
  24. package/dist/cjs/sql.js.map +1 -1
  25. package/dist/cjs/transactions.d.ts +8 -0
  26. package/dist/cjs/transactions.d.ts.map +1 -1
  27. package/dist/cjs/transactions.js +18 -0
  28. package/dist/cjs/transactions.js.map +1 -1
  29. package/dist/esm/core/errors.js +10 -0
  30. package/dist/esm/core/errors.js.map +1 -1
  31. package/dist/esm/decorators/query.js +127 -20
  32. package/dist/esm/decorators/query.js.map +1 -1
  33. package/dist/esm/index.js +2 -1
  34. package/dist/esm/index.js.map +1 -1
  35. package/dist/esm/run.js +123 -18
  36. package/dist/esm/run.js.map +1 -1
  37. package/dist/esm/runtime.js +11 -0
  38. package/dist/esm/runtime.js.map +1 -1
  39. package/dist/esm/sql.js +63 -27
  40. package/dist/esm/sql.js.map +1 -1
  41. package/dist/esm/transactions.js +17 -0
  42. package/dist/esm/transactions.js.map +1 -1
  43. package/package.json +1 -1
  44. package/readme.md +128 -39
package/dist/cjs/sql.js CHANGED
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SqlFragment = void 0;
4
+ exports.isSqlFragment = isSqlFragment;
5
+ exports.compileFragment = compileFragment;
4
6
  exports.sql = sql;
5
7
  /**
6
8
  * Tagged template literal for SQL queries with `?` placeholders.
@@ -11,45 +13,82 @@ exports.sql = sql;
11
13
  * sql`UPDATE users SET :update(${data}) WHERE id = ${id}`
12
14
  * sql`SELECT * FROM users WHERE :filter(${criteria})`
13
15
  * sql`INSERT INTO users :batch_insert(${rows})`
16
+ *
17
+ * Execute a fragment with `run(db, fragment)` (or `run(fragment)` inside a
18
+ * @Query method): run binds it for the target dialect (`?` for SQLite/MySQL,
19
+ * `$1..` for Postgres) and wraps failures in DatabaseError.
14
20
  */
15
21
  const MACRO_OPEN = /:(insert|update|filter|batch_insert)\s*\(\s*$/i;
16
22
  const MACRO_CLOSE = /^\s*\)/;
23
+ // Cross-copy identity for fragments: duplicated module instances (npm link,
24
+ // dual ESM/CJS loads) each define their own SqlFragment class, so `instanceof`
25
+ // alone would misclassify a fragment built by another copy.
26
+ const FRAGMENT_BRAND = Symbol.for('noego.sqlstack.SqlFragment');
17
27
  class SqlFragment {
18
28
  constructor(strings, values) {
19
29
  this.strings = strings;
20
30
  this.values = values;
21
31
  }
32
+ /**
33
+ * Compile to SQL with `?` placeholders and the matching parameter list.
34
+ *
35
+ * @throws {Error} When a binder macro (`:insert`, `:update`, `:filter`,
36
+ * `:batch_insert`) receives invalid input. `run(...)` wraps this in
37
+ * DatabaseError with the original error in `.cause`.
38
+ */
22
39
  toSQL() {
23
- const segments = [...this.strings];
24
- const sqlParts = [];
25
- const params = [];
26
- for (let i = 0; i < segments.length; i++) {
27
- if (i < this.values.length) {
28
- const openMatch = segments[i].match(MACRO_OPEN);
29
- const closeMatch = segments[i + 1]?.match(MACRO_CLOSE);
30
- if (openMatch && closeMatch) {
31
- // Binder macro: trim the macro syntax and expand
32
- sqlParts.push(segments[i].slice(0, -openMatch[0].length));
33
- segments[i + 1] = segments[i + 1].slice(closeMatch[0].length);
34
- const { text, params: expanded } = expandMacro(openMatch[1].toLowerCase(), this.values[i]);
35
- sqlParts.push(text);
36
- params.push(...expanded);
37
- }
38
- else {
39
- sqlParts.push(segments[i]);
40
- sqlParts.push('?');
41
- params.push(this.values[i]);
42
- }
40
+ return compileParts(this.strings, this.values, () => '?');
41
+ }
42
+ }
43
+ exports.SqlFragment = SqlFragment;
44
+ Object.defineProperty(SqlFragment.prototype, FRAGMENT_BRAND, { value: true });
45
+ /** @internal True for a SqlFragment from this or any other sqlstack copy. */
46
+ function isSqlFragment(value) {
47
+ if (value instanceof SqlFragment)
48
+ return true;
49
+ return (typeof value === 'object' &&
50
+ value !== null &&
51
+ value[FRAGMENT_BRAND] === true);
52
+ }
53
+ /**
54
+ * @internal Compile a fragment for a dialect: `$1, $2, ...` for Postgres,
55
+ * `?` for SQLite and MySQL. Throws plain Error on invalid macro input
56
+ * (callers in run() wrap it).
57
+ */
58
+ function compileFragment(fragment, dialect) {
59
+ let next = 0;
60
+ const placeholder = dialect === 'postgres' ? () => `$${++next}` : () => '?';
61
+ return compileParts(fragment.strings, fragment.values, placeholder);
62
+ }
63
+ function compileParts(strings, values, placeholder) {
64
+ const segments = [...strings];
65
+ const sqlParts = [];
66
+ const params = [];
67
+ for (let i = 0; i < segments.length; i++) {
68
+ if (i < values.length) {
69
+ const openMatch = segments[i].match(MACRO_OPEN);
70
+ const closeMatch = segments[i + 1]?.match(MACRO_CLOSE);
71
+ if (openMatch && closeMatch) {
72
+ // Binder macro: trim the macro syntax and expand
73
+ sqlParts.push(segments[i].slice(0, -openMatch[0].length));
74
+ segments[i + 1] = segments[i + 1].slice(closeMatch[0].length);
75
+ const { text, params: expanded } = expandMacro(openMatch[1].toLowerCase(), values[i], placeholder);
76
+ sqlParts.push(text);
77
+ params.push(...expanded);
43
78
  }
44
79
  else {
45
80
  sqlParts.push(segments[i]);
81
+ sqlParts.push(placeholder());
82
+ params.push(values[i]);
46
83
  }
47
84
  }
48
- return { sql: sqlParts.join(''), params };
85
+ else {
86
+ sqlParts.push(segments[i]);
87
+ }
49
88
  }
89
+ return { sql: sqlParts.join(''), params };
50
90
  }
51
- exports.SqlFragment = SqlFragment;
52
- function expandMacro(type, value) {
91
+ function expandMacro(type, value, placeholder) {
53
92
  switch (type) {
54
93
  case 'insert': {
55
94
  assertPlainObject(value, ':insert()');
@@ -58,7 +97,7 @@ function expandMacro(type, value) {
58
97
  if (keys.length === 0)
59
98
  throw new Error(':insert() requires at least one column');
60
99
  const cols = keys.join(', ');
61
- const placeholders = keys.map(() => '?').join(', ');
100
+ const placeholders = keys.map(() => placeholder()).join(', ');
62
101
  return { text: `(${cols}) VALUES (${placeholders})`, params: keys.map(k => obj[k]) };
63
102
  }
64
103
  case 'update': {
@@ -67,7 +106,7 @@ function expandMacro(type, value) {
67
106
  if (entries.length === 0)
68
107
  throw new Error(':update() requires at least one defined column');
69
108
  return {
70
- text: entries.map(([k]) => `${k} = ?`).join(', '),
109
+ text: entries.map(([k]) => `${k} = ${placeholder()}`).join(', '),
71
110
  params: entries.map(([, v]) => v),
72
111
  };
73
112
  }
@@ -77,7 +116,7 @@ function expandMacro(type, value) {
77
116
  if (entries.length === 0)
78
117
  throw new Error(':filter() requires at least one defined condition');
79
118
  return {
80
- text: entries.map(([k]) => `${k} = ?`).join(' AND '),
119
+ text: entries.map(([k]) => `${k} = ${placeholder()}`).join(' AND '),
81
120
  params: entries.map(([, v]) => v),
82
121
  };
83
122
  }
@@ -89,8 +128,7 @@ function expandMacro(type, value) {
89
128
  if (keys.length === 0)
90
129
  throw new Error(':batch_insert() requires at least one column');
91
130
  const cols = keys.join(', ');
92
- const rowPlaceholder = `(${keys.map(() => '?').join(', ')})`;
93
- const allPlaceholders = value.map(() => rowPlaceholder).join(', ');
131
+ const allPlaceholders = value.map(() => `(${keys.map(() => placeholder()).join(', ')})`).join(', ');
94
132
  return {
95
133
  text: `(${cols}) VALUES ${allPlaceholders}`,
96
134
  params: value.flatMap(row => keys.map(k => row[k])),
@@ -1 +1 @@
1
- {"version":3,"file":"sql.js","sourceRoot":"","sources":["../../src/sql.ts"],"names":[],"mappings":";;;AAyGA,kBAEC;AA3GD;;;;;;;;;GASG;AACH,MAAM,UAAU,GAAG,gDAAgD,CAAC;AACpE,MAAM,WAAW,GAAG,QAAQ,CAAC;AAE7B,MAAa,WAAW;IACtB,YACkB,OAA0B,EAC1B,MAA0B;QAD1B,YAAO,GAAP,OAAO,CAAmB;QAC1B,WAAM,GAAN,MAAM,CAAoB;IACzC,CAAC;IAEJ,KAAK;QACH,MAAM,QAAQ,GAAG,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC;QACnC,MAAM,QAAQ,GAAa,EAAE,CAAC;QAC9B,MAAM,MAAM,GAAc,EAAE,CAAC;QAE7B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACzC,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;gBAC3B,MAAM,SAAS,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;gBAChD,MAAM,UAAU,GAAG,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,WAAW,CAAC,CAAC;gBAEvD,IAAI,SAAS,IAAI,UAAU,EAAE,CAAC;oBAC5B,iDAAiD;oBACjD,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,SAAS,C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,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAE,GAA+B,CAAC,CAAC,CAAC,CAAC,CAAC;aACjF,CAAC;QACJ,CAAC;QACD;YACE,MAAM,IAAI,KAAK,CAAC,yBAAyB,IAAI,IAAI,CAAC,CAAC;IACvD,CAAC;AACH,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAc,EAAE,KAAa;IACtD,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAChE,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,8CAA8C,CAAC,CAAC;IAC1E,CAAC;AACH,CAAC;AAED,SAAgB,GAAG,CAAC,OAA6B,EAAE,GAAG,MAAiB;IACrE,OAAO,IAAI,WAAW,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["/**\n * Tagged template literal for SQL queries with `?` placeholders.\n *\n * Usage:\n * sql`SELECT * FROM users WHERE id = ${userId} AND status = ${status}`\n * sql`INSERT INTO users :insert(${data})`\n * sql`UPDATE users SET :update(${data}) WHERE id = ${id}`\n * sql`SELECT * FROM users WHERE :filter(${criteria})`\n * sql`INSERT INTO users :batch_insert(${rows})`\n */\nconst MACRO_OPEN = /:(insert|update|filter|batch_insert)\\s*\\(\\s*$/i;\nconst MACRO_CLOSE = /^\\s*\\)/;\n\nexport class SqlFragment {\n constructor(\n public readonly strings: readonly string[],\n public readonly values: readonly unknown[],\n ) {}\n\n toSQL(): { sql: string; params: unknown[] } {\n const segments = [...this.strings];\n const sqlParts: string[] = [];\n const params: unknown[] = [];\n\n for (let i = 0; i < segments.length; i++) {\n if (i < this.values.length) {\n const openMatch = segments[i].match(MACRO_OPEN);\n const closeMatch = segments[i + 1]?.match(MACRO_CLOSE);\n\n if (openMatch && closeMatch) {\n // Binder macro: trim the macro syntax and expand\n sqlParts.push(segments[i].slice(0, -openMatch[0].length));\n segments[i + 1] = segments[i + 1].slice(closeMatch[0].length);\n\n const { text, params: expanded } = expandMacro(openMatch[1].toLowerCase(), this.values[i]);\n sqlParts.push(text);\n params.push(...expanded);\n } else {\n sqlParts.push(segments[i]);\n sqlParts.push('?');\n params.push(this.values[i]);\n }\n } else {\n sqlParts.push(segments[i]);\n }\n }\n\n return { sql: sqlParts.join(''), params };\n }\n}\n\nfunction expandMacro(type: string, value: unknown): { text: string; params: unknown[] } {\n switch (type) {\n case 'insert': {\n assertPlainObject(value, ':insert()');\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj);\n if (keys.length === 0) throw new Error(':insert() requires at least one column');\n const cols = keys.join(', ');\n const placeholders = keys.map(() => '?').join(', ');\n return { text: `(${cols}) VALUES (${placeholders})`, params: keys.map(k => obj[k]) };\n }\n case 'update': {\n assertPlainObject(value, ':update()');\n const entries = Object.entries(value as Record<string, unknown>).filter(([, v]) => v !== undefined);\n if (entries.length === 0) throw new Error(':update() requires at least one defined column');\n return {\n text: entries.map(([k]) => `${k} = ?`).join(', '),\n params: entries.map(([, v]) => v),\n };\n }\n case 'filter': {\n assertPlainObject(value, ':filter()');\n const entries = Object.entries(value as Record<string, unknown>).filter(([, v]) => v !== undefined);\n if (entries.length === 0) throw new Error(':filter() requires at least one defined condition');\n return {\n text: entries.map(([k]) => `${k} = ?`).join(' AND '),\n params: entries.map(([, v]) => v),\n };\n }\n case 'batch_insert': {\n if (!Array.isArray(value) || value.length === 0) {\n throw new Error(':batch_insert() requires a non-empty array of objects');\n }\n const keys = Object.keys(value[0]);\n if (keys.length === 0) throw new Error(':batch_insert() requires at least one column');\n const cols = keys.join(', ');\n const rowPlaceholder = `(${keys.map(() => '?').join(', ')})`;\n const allPlaceholders = value.map(() => rowPlaceholder).join(', ');\n return {\n text: `(${cols}) VALUES ${allPlaceholders}`,\n params: value.flatMap(row => keys.map(k => (row as Record<string, unknown>)[k])),\n };\n }\n default:\n throw new Error(`Unknown binder macro :${type}()`);\n }\n}\n\nfunction assertPlainObject(value: unknown, label: string): asserts value is Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} in sql\\`\\` template requires a plain object`);\n }\n}\n\nexport function sql(strings: TemplateStringsArray, ...values: unknown[]): SqlFragment {\n return new SqlFragment(strings, values);\n}\n"]}
1
+ {"version":3,"file":"sql.js","sourceRoot":"","sources":["../../src/sql.ts"],"names":[],"mappings":";;;AA6CA,sCAOC;AAOD,0CAIC;AA0FD,kBAEC;AAzJD;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,GAAG,gDAAgD,CAAC;AACpE,MAAM,WAAW,GAAG,QAAQ,CAAC;AAE7B,4EAA4E;AAC5E,+EAA+E;AAC/E,4DAA4D;AAC5D,MAAM,cAAc,GAAG,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;AAEhE,MAAa,WAAW;IACtB,YACkB,OAA0B,EAC1B,MAA0B;QAD1B,YAAO,GAAP,OAAO,CAAmB;QAC1B,WAAM,GAAN,MAAM,CAAoB;IACzC,CAAC;IAEJ;;;;;;OAMG;IACH,KAAK;QACH,OAAO,YAAY,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC;IAC5D,CAAC;CACF;AAhBD,kCAgBC;AAED,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,SAAS,EAAE,cAAc,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AAE9E,6EAA6E;AAC7E,SAAgB,aAAa,CAAC,KAAc;IAC1C,IAAI,KAAK,YAAY,WAAW;QAAE,OAAO,IAAI,CAAC;IAC9C,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACb,KAAwC,CAAC,cAAc,CAAC,KAAK,IAAI,CACnE,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAgB,eA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C;AACH,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAc,EAAE,KAAa;IACtD,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAChE,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,8CAA8C,CAAC,CAAC;IAC1E,CAAC;AACH,CAAC;AAED,SAAgB,GAAG,CAAC,OAA6B,EAAE,GAAG,MAAiB;IACrE,OAAO,IAAI,WAAW,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["import type { Dialect } from './registry';\n\n/**\n * Tagged template literal for SQL queries with `?` placeholders.\n *\n * Usage:\n * sql`SELECT * FROM users WHERE id = ${userId} AND status = ${status}`\n * sql`INSERT INTO users :insert(${data})`\n * sql`UPDATE users SET :update(${data}) WHERE id = ${id}`\n * sql`SELECT * FROM users WHERE :filter(${criteria})`\n * sql`INSERT INTO users :batch_insert(${rows})`\n *\n * Execute a fragment with `run(db, fragment)` (or `run(fragment)` inside a\n * @Query method): run binds it for the target dialect (`?` for SQLite/MySQL,\n * `$1..` for Postgres) and wraps failures in DatabaseError.\n */\nconst MACRO_OPEN = /:(insert|update|filter|batch_insert)\\s*\\(\\s*$/i;\nconst MACRO_CLOSE = /^\\s*\\)/;\n\n// Cross-copy identity for fragments: duplicated module instances (npm link,\n// dual ESM/CJS loads) each define their own SqlFragment class, so `instanceof`\n// alone would misclassify a fragment built by another copy.\nconst FRAGMENT_BRAND = Symbol.for('noego.sqlstack.SqlFragment');\n\nexport class SqlFragment {\n constructor(\n public readonly strings: readonly string[],\n public readonly values: readonly unknown[],\n ) {}\n\n /**\n * Compile to SQL with `?` placeholders and the matching parameter list.\n *\n * @throws {Error} When a binder macro (`:insert`, `:update`, `:filter`,\n * `:batch_insert`) receives invalid input. `run(...)` wraps this in\n * DatabaseError with the original error in `.cause`.\n */\n toSQL(): { sql: string; params: unknown[] } {\n return compileParts(this.strings, this.values, () => '?');\n }\n}\n\nObject.defineProperty(SqlFragment.prototype, FRAGMENT_BRAND, { value: true });\n\n/** @internal True for a SqlFragment from this or any other sqlstack copy. */\nexport function isSqlFragment(value: unknown): value is SqlFragment {\n if (value instanceof SqlFragment) return true;\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { [FRAGMENT_BRAND]?: unknown })[FRAGMENT_BRAND] === true\n );\n}\n\n/**\n * @internal Compile a fragment for a dialect: `$1, $2, ...` for Postgres,\n * `?` for SQLite and MySQL. Throws plain Error on invalid macro input\n * (callers in run() wrap it).\n */\nexport function compileFragment(fragment: SqlFragment, dialect: Dialect): { sql: string; params: unknown[] } {\n let next = 0;\n const placeholder = dialect === 'postgres' ? () => `$${++next}` : () => '?';\n return compileParts(fragment.strings, fragment.values, placeholder);\n}\n\nfunction compileParts(\n strings: readonly string[],\n values: readonly unknown[],\n placeholder: () => string,\n): { sql: string; params: unknown[] } {\n const segments = [...strings];\n const sqlParts: string[] = [];\n const params: unknown[] = [];\n\n for (let i = 0; i < segments.length; i++) {\n if (i < values.length) {\n const openMatch = segments[i].match(MACRO_OPEN);\n const closeMatch = segments[i + 1]?.match(MACRO_CLOSE);\n\n if (openMatch && closeMatch) {\n // Binder macro: trim the macro syntax and expand\n sqlParts.push(segments[i].slice(0, -openMatch[0].length));\n segments[i + 1] = segments[i + 1].slice(closeMatch[0].length);\n\n const { text, params: expanded } = expandMacro(openMatch[1].toLowerCase(), values[i], placeholder);\n sqlParts.push(text);\n params.push(...expanded);\n } else {\n sqlParts.push(segments[i]);\n sqlParts.push(placeholder());\n params.push(values[i]);\n }\n } else {\n sqlParts.push(segments[i]);\n }\n }\n\n return { sql: sqlParts.join(''), params };\n}\n\nfunction expandMacro(type: string, value: unknown, placeholder: () => string): { text: string; params: unknown[] } {\n switch (type) {\n case 'insert': {\n assertPlainObject(value, ':insert()');\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj);\n if (keys.length === 0) throw new Error(':insert() requires at least one column');\n const cols = keys.join(', ');\n const placeholders = keys.map(() => placeholder()).join(', ');\n return { text: `(${cols}) VALUES (${placeholders})`, params: keys.map(k => obj[k]) };\n }\n case 'update': {\n assertPlainObject(value, ':update()');\n const entries = Object.entries(value as Record<string, unknown>).filter(([, v]) => v !== undefined);\n if (entries.length === 0) throw new Error(':update() requires at least one defined column');\n return {\n text: entries.map(([k]) => `${k} = ${placeholder()}`).join(', '),\n params: entries.map(([, v]) => v),\n };\n }\n case 'filter': {\n assertPlainObject(value, ':filter()');\n const entries = Object.entries(value as Record<string, unknown>).filter(([, v]) => v !== undefined);\n if (entries.length === 0) throw new Error(':filter() requires at least one defined condition');\n return {\n text: entries.map(([k]) => `${k} = ${placeholder()}`).join(' AND '),\n params: entries.map(([, v]) => v),\n };\n }\n case 'batch_insert': {\n if (!Array.isArray(value) || value.length === 0) {\n throw new Error(':batch_insert() requires a non-empty array of objects');\n }\n const keys = Object.keys(value[0]);\n if (keys.length === 0) throw new Error(':batch_insert() requires at least one column');\n const cols = keys.join(', ');\n const allPlaceholders = value.map(() => `(${keys.map(() => placeholder()).join(', ')})`).join(', ');\n return {\n text: `(${cols}) VALUES ${allPlaceholders}`,\n params: value.flatMap(row => keys.map(k => (row as Record<string, unknown>)[k])),\n };\n }\n default:\n throw new Error(`Unknown binder macro :${type}()`);\n }\n}\n\nfunction assertPlainObject(value: unknown, label: string): asserts value is Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} in sql\\`\\` template requires a plain object`);\n }\n}\n\nexport function sql(strings: TemplateStringsArray, ...values: unknown[]): SqlFragment {\n return new SqlFragment(strings, values);\n}\n"]}
@@ -63,5 +63,13 @@ export type ActiveTransaction = {
63
63
  query(sql: string, params: unknown[]): Promise<QueryResult>;
64
64
  };
65
65
  export declare function getActiveTransaction(entry: DatabaseEntry): ActiveTransaction | undefined;
66
+ /**
67
+ * Active transaction whose registered database is exactly `db` (object
68
+ * identity), if any. `run(db, ...)` uses this so a handle passed at call time
69
+ * joins a transaction opened on the same database (by `@transaction` or
70
+ * `withTransaction`) instead of bypassing it. A handle that was never
71
+ * registered with a SqlStack (or the legacy registry) never matches.
72
+ */
73
+ export declare function getActiveTransactionForDatabase(db: object): ActiveTransaction | undefined;
66
74
  export {};
67
75
  //# sourceMappingURL=transactions.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"transactions.d.ts","sourceRoot":"","sources":["../../src/transactions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAGxD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAG7C,MAAM,MAAM,kBAAkB,GAAG;IAC/B,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AA6BF,qBAAa,iBAAiB;;IAC5B,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC;gBAKlB,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO;IAMhE,IAAI,MAAM,IAAI,MAAM,CAEnB;IAEK,aAAa;IAInB,YAAY,CAAC,YAAY,CAAC,EAAE,OAAO;IAO7B,MAAM;IAKN,QAAQ;IAKR,OAAO;IAKP,eAAe;IAMf,aAAa,CAAC,GAAG,EAAE,OAAO;CAKjC;AAED,cAAM,OAAO;IACX,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC;IAC9B,QAAQ,CAAC,EAAE,EAAE,QAAQ,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,IAAI,CAAC,kBAAkB,EAAE,MAAM,CAAC,CAAC,GAAG,IAAI,CAAC,kBAAkB,EAAE,QAAQ,CAAC,CAAC;IAClG,KAAK,SAAK;IACV,OAAO,UAAS;IAChB,SAAS,UAAS;IAClB,YAAY,UAAS;IACrB,aAA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,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,aAAa,GAAG,iBAAiB,GAAG,SAAS,CAGxF;AAED;;;;;;GAMG;AACH,wBAAgB,+BAA+B,CAAC,EAAE,EAAE,MAAM,GAAG,iBAAiB,GAAG,SAAS,CAOzF"}
@@ -18,6 +18,7 @@ exports.hasTransactionContext = hasTransactionContext;
18
18
  exports.currentTransactionFor = currentTransactionFor;
19
19
  exports.withTransaction = withTransaction;
20
20
  exports.getActiveTransaction = getActiveTransaction;
21
+ exports.getActiveTransactionForDatabase = getActiveTransactionForDatabase;
21
22
  const node_async_hooks_1 = require("node:async_hooks");
22
23
  const adapters_1 = require("./adapters");
23
24
  const errors_1 = require("./core/errors");
@@ -297,4 +298,21 @@ function getActiveTransaction(entry) {
297
298
  const store = getStore();
298
299
  return store?.txByDb.get(entry);
299
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
+ }
300
318
  //# sourceMappingURL=transactions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"transactions.js","sourceRoot":"","sources":["../../src/transactions.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAsPA,gDAOC;AAOD,sDAEC;AAGD,sDAKC;AAED,0CAkBC;AAgCD,oDAGC;AArUD,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;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AAK,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/**\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"]}
1
+ {"version":3,"file":"trans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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;AAED;;;;;;GAMG;AACH,SAAgB,+BAA+B,CAAC,EAAU;IACxD,MAAM,KAAK,GAAG,QAAQ,EAAE,CAAC;IACzB,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC;QAC1C,IAAI,KAAK,CAAC,EAAE,KAAK,EAAE;YAAE,OAAO,KAAK,CAAC;IACpC,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Database, QueryResult } from './registry';\nimport { createPgDb, createMysqlDb } from './adapters';\nimport { RollbackTransactionError, SqlStackError } from './core/errors';\nimport type { DatabaseEntry } from './stack';\nimport { resolveExecution, legacyEntry } from './runtime';\n\nexport type TransactionOptions = {\n db?: string;\n lazy?: boolean;\n nested?: 'join';\n};\n\n// 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"]}
@@ -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,cAAe,SAAQ,aAAa;IAC/C,YAAY,WAAmB;QAC7B,KAAK,CAAC,yBAAyB,WAAW,EAAE,CAAC,CAAC;QAC9C,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC/B,CAAC;CACF;AAED,yEAAyE;AACzE,wEAAwE;AACxE,2DAA2D;AAC3D,MAAM,OAAO,iBAAkB,SAAQ,aAAa;IAClD,YAAY,MAAc,EAAE,KAAa;QACvC,MAAM,SAAS,GAAG,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACvE,KAAK,CACH,GAAG,SAAS,OAAO,MAAM,oEAAoE;YAC3F,2EAA2E,CAC9E,CAAC;QACF,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;IAClC,CAAC;CAGF;AAED,MAAM,OAAO,eAAgB,SAAQ,aAAa;IAChD,YAAY,OAAe;QACzB,KAAK,CAAC,sBAAsB,OAAO,EAAE,CAAC,CAAC;QACvC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;IAChC,CAAC;CAEF;AAED,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,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9B,CAAC;CAGF;AAED,8DAA8D;AAC9D,kEAAkE;AAClE,MAAM,OAAO,wBAAyB,SAAQ,aAAa;IACzD,YAAY,OAAO,GAAG,yBAAyB,EAAE,KAAe;QAC9D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;IACzC,CAAC;CAEF","sourcesContent":["export class SqlStackError extends Error {\n constructor(message?: string) {\n super(message);\n this.name = 'SqlStackError';\n }\n}\n\nexport class ExactlyOneRowError extends SqlStackError {\n constructor(actualCount: number) {\n super(`Expected exactly one row, got ${actualCount}`);\n this.name = 'ExactlyOneRowError';\n }\n}\n\nexport class NoRowsError extends SqlStackError {\n constructor() {\n super('Expected at least one row, got 0');\n this.name = 'NoRowsError';\n }\n}\n\nexport class RowsExistError extends SqlStackError {\n constructor(actualCount: number) {\n super(`Expected no rows, got ${actualCount}`);\n this.name = 'RowsExistError';\n }\n}\n\n// A result-shape decorator (@Single/@Only/@Exist/@None) was applied to a\n// method whose statement produced no result set (a plain write). Shapes\n// require rows; use `... RETURNING` or drop the decorator.\nexport class ExpectedRowsError extends SqlStackError {\n constructor(method: string, shape: string) {\n const decorator = '@' + shape.charAt(0).toUpperCase() + shape.slice(1);\n super(\n `${decorator} on ${method} requires a result set, but the statement produced a write result ` +\n `({ rowsAffected }). Add a RETURNING clause or remove the shape decorator.`\n );\n this.method = method;\n this.shape = shape;\n this.name = 'ExpectedRowsError';\n }\n method: string;\n shape: string;\n}\n\nexport class ValidationError extends SqlStackError {\n constructor(details: string) {\n super(`Validation failed: ${details}`);\n this.details = details;\n this.name = 'ValidationError';\n }\n details: string;\n}\n\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 this.name = 'DatabaseError';\n }\n sql: string;\n cause?: Error;\n}\n\n// Signals that the current transaction should be rolled back.\n// If `cause` is provided, wrappers may rethrow it after rollback.\nexport class RollbackTransactionError extends SqlStackError {\n constructor(message = 'Transaction rolled back', cause?: unknown) {\n super(message);\n this.cause = cause;\n this.name = 'RollbackTransactionError';\n }\n cause?: unknown;\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/core/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAgB;QAC1B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9B,CAAC;CACF;AAED,MAAM,OAAO,kBAAmB,SAAQ,aAAa;IACnD,YAAY,WAAmB;QAC7B,KAAK,CAAC,iCAAiC,WAAW,EAAE,CAAC,CAAC;QACtD,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC,CAAC;CACF;AAED,MAAM,OAAO,WAAY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AI,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
- // The full file/inline pipeline (resolve source, bind, execute,
49
- // shape/transform/validate). Invoked either by run() from inside the
50
- // method body, or directly as the legacy fallback when the body throws.
51
- const pipeline = async () => {
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
- const dbName = labels.db ?? options?.db ?? classLabels?.db;
56
- const { entry, resolver: activeResolver } = await resolveExecution(dbName);
57
- const db = entry.db;
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
- const { sql: boundSql, params } = binder.bind(workingSql, args);
261
- // 5) execute query via registry DB
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
- const tx = getActiveTransaction(entry);
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
- // 6) If rows were returned (SELECT/CTE/RETURNING), shape + transform + validate;
272
- // otherwise return the write result as-is (or fail if a shape was requested)
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): execute it.
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;