fastify-auto-sqlapi 0.5.1 → 1.0.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 (212) hide show
  1. package/AGENTS.md +5 -5
  2. package/AGENTS_BACKEND.md +166 -130
  3. package/AGENTS_FRONTEND.md +60 -38
  4. package/BREAKING_CHANGES.md +9 -893
  5. package/CHANGELOG.md +246 -15
  6. package/README.md +71 -45
  7. package/dist/bin/generate-schema.js +12 -12
  8. package/dist/bin/generate-tables.js +1 -2
  9. package/dist/bin/utils.d.ts +2 -6
  10. package/dist/bin/utils.d.ts.map +1 -1
  11. package/dist/bin/utils.js +13 -33
  12. package/dist/index.d.ts +13 -33
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +6 -37
  15. package/dist/lib/adapters/mysql-adapter.d.ts +5 -2
  16. package/dist/lib/adapters/mysql-adapter.d.ts.map +1 -1
  17. package/dist/lib/adapters/pg-adapter.d.ts +5 -2
  18. package/dist/lib/adapters/pg-adapter.d.ts.map +1 -1
  19. package/dist/lib/agent/manifest.d.ts +27 -10
  20. package/dist/lib/agent/manifest.d.ts.map +1 -1
  21. package/dist/lib/agent/manifest.js +43 -26
  22. package/dist/lib/agent/tool-schemas.d.ts +5 -4
  23. package/dist/lib/agent/tool-schemas.d.ts.map +1 -1
  24. package/dist/lib/agent/tool-schemas.js +5 -5
  25. package/dist/lib/cli/config.d.ts +37 -2
  26. package/dist/lib/cli/config.d.ts.map +1 -1
  27. package/dist/lib/cli/config.js +106 -16
  28. package/dist/lib/cli/mysql-introspect.d.ts +6 -1
  29. package/dist/lib/cli/mysql-introspect.d.ts.map +1 -1
  30. package/dist/lib/cli/mysql-introspect.js +15 -15
  31. package/dist/lib/cli/pg-introspect.d.ts +0 -1
  32. package/dist/lib/cli/pg-introspect.d.ts.map +1 -1
  33. package/dist/lib/cli/pg-introspect.js +2 -13
  34. package/dist/lib/cli/tables-codegen.d.ts +0 -4
  35. package/dist/lib/cli/tables-codegen.d.ts.map +1 -1
  36. package/dist/lib/cli/tables-codegen.js +24 -87
  37. package/dist/lib/db.d.ts +42 -17
  38. package/dist/lib/db.d.ts.map +1 -1
  39. package/dist/lib/db.js +114 -40
  40. package/dist/lib/dialect.d.ts +5 -0
  41. package/dist/lib/dialect.d.ts.map +1 -1
  42. package/dist/lib/dialect.js +3 -0
  43. package/dist/lib/engine/bulk/bulk-delete.d.ts +5 -0
  44. package/dist/lib/engine/bulk/bulk-delete.d.ts.map +1 -1
  45. package/dist/lib/engine/bulk/bulk-delete.js +66 -30
  46. package/dist/lib/engine/bulk/bulk-upsert.d.ts.map +1 -1
  47. package/dist/lib/engine/bulk/bulk-upsert.js +45 -26
  48. package/dist/lib/engine/read-hooks.d.ts +3 -3
  49. package/dist/lib/engine/read-hooks.d.ts.map +1 -1
  50. package/dist/lib/engine/read-hooks.js +3 -3
  51. package/dist/lib/engine/rest/delete.d.ts.map +1 -1
  52. package/dist/lib/engine/rest/delete.js +12 -18
  53. package/dist/lib/engine/rest/get.js +8 -8
  54. package/dist/lib/engine/rest/insert.d.ts.map +1 -1
  55. package/dist/lib/engine/rest/insert.js +31 -18
  56. package/dist/lib/engine/rest/update.d.ts.map +1 -1
  57. package/dist/lib/engine/rest/update.js +34 -17
  58. package/dist/lib/engine/search/aggregations.d.ts +3 -3
  59. package/dist/lib/engine/search/aggregations.d.ts.map +1 -1
  60. package/dist/lib/engine/search/aggregations.js +20 -16
  61. package/dist/lib/engine/search/conditions.d.ts +9 -5
  62. package/dist/lib/engine/search/conditions.d.ts.map +1 -1
  63. package/dist/lib/engine/search/conditions.js +31 -20
  64. package/dist/lib/engine/search/fields.d.ts +44 -11
  65. package/dist/lib/engine/search/fields.d.ts.map +1 -1
  66. package/dist/lib/engine/search/fields.js +93 -27
  67. package/dist/lib/engine/search/join-families.d.ts +7 -7
  68. package/dist/lib/engine/search/join-families.d.ts.map +1 -1
  69. package/dist/lib/engine/search/join-families.js +84 -75
  70. package/dist/lib/engine/search/joins.d.ts +15 -7
  71. package/dist/lib/engine/search/joins.d.ts.map +1 -1
  72. package/dist/lib/engine/search/joins.js +23 -13
  73. package/dist/lib/engine/search/order-by.d.ts +11 -12
  74. package/dist/lib/engine/search/order-by.d.ts.map +1 -1
  75. package/dist/lib/engine/search/order-by.js +24 -28
  76. package/dist/lib/engine/search/search.d.ts.map +1 -1
  77. package/dist/lib/engine/search/search.js +111 -64
  78. package/dist/lib/engine/validate.d.ts +21 -3
  79. package/dist/lib/engine/validate.d.ts.map +1 -1
  80. package/dist/lib/engine/validate.js +106 -16
  81. package/dist/lib/engine/write-helpers.d.ts +69 -16
  82. package/dist/lib/engine/write-helpers.d.ts.map +1 -1
  83. package/dist/lib/engine/write-helpers.js +257 -105
  84. package/dist/lib/errors.d.ts +42 -10
  85. package/dist/lib/errors.d.ts.map +1 -1
  86. package/dist/lib/errors.js +69 -15
  87. package/dist/lib/nullable.d.ts +3 -2
  88. package/dist/lib/nullable.d.ts.map +1 -1
  89. package/dist/lib/nullable.js +14 -5
  90. package/dist/lib/read-access.d.ts +25 -16
  91. package/dist/lib/read-access.d.ts.map +1 -1
  92. package/dist/lib/read-access.js +33 -17
  93. package/dist/lib/schema/bulk-delete.d.ts +13 -7
  94. package/dist/lib/schema/bulk-delete.d.ts.map +1 -1
  95. package/dist/lib/schema/bulk-delete.js +18 -8
  96. package/dist/lib/schema/bulk-upsert.d.ts +3 -3
  97. package/dist/lib/schema/bulk-upsert.d.ts.map +1 -1
  98. package/dist/lib/schema/bulk-upsert.js +9 -14
  99. package/dist/lib/schema/get.d.ts +1 -1
  100. package/dist/lib/schema/get.d.ts.map +1 -1
  101. package/dist/lib/schema/get.js +2 -2
  102. package/dist/lib/schema/helpers.d.ts +41 -23
  103. package/dist/lib/schema/helpers.d.ts.map +1 -1
  104. package/dist/lib/schema/helpers.js +80 -33
  105. package/dist/lib/schema/insert.d.ts +1 -1
  106. package/dist/lib/schema/insert.d.ts.map +1 -1
  107. package/dist/lib/schema/insert.js +12 -20
  108. package/dist/lib/schema/search.d.ts +2 -13
  109. package/dist/lib/schema/search.d.ts.map +1 -1
  110. package/dist/lib/schema/search.js +64 -61
  111. package/dist/lib/schema/update.d.ts +1 -1
  112. package/dist/lib/schema/update.d.ts.map +1 -1
  113. package/dist/lib/schema/update.js +6 -13
  114. package/dist/lib/sql-api.d.ts +47 -25
  115. package/dist/lib/sql-api.d.ts.map +1 -1
  116. package/dist/lib/sql-api.js +70 -27
  117. package/dist/lib/table-helpers.d.ts +92 -14
  118. package/dist/lib/table-helpers.d.ts.map +1 -1
  119. package/dist/lib/table-helpers.js +367 -128
  120. package/dist/lib/tenant.d.ts +16 -22
  121. package/dist/lib/tenant.d.ts.map +1 -1
  122. package/dist/lib/tenant.js +38 -54
  123. package/dist/lib/write-access.d.ts +15 -9
  124. package/dist/lib/write-access.d.ts.map +1 -1
  125. package/dist/lib/write-access.js +12 -4
  126. package/dist/routes/auto/agent-manifest.routes.d.ts +1 -1
  127. package/dist/routes/auto/agent-manifest.routes.js +2 -2
  128. package/dist/routes/auto/bulk-delete.routes.d.ts +2 -2
  129. package/dist/routes/auto/bulk-delete.routes.d.ts.map +1 -1
  130. package/dist/routes/auto/bulk-delete.routes.js +1 -7
  131. package/dist/routes/auto/bulk-upsert.routes.d.ts +2 -2
  132. package/dist/routes/auto/bulk-upsert.routes.d.ts.map +1 -1
  133. package/dist/routes/auto/bulk-upsert.routes.js +2 -2
  134. package/dist/routes/auto/delete.routes.d.ts +2 -2
  135. package/dist/routes/auto/delete.routes.d.ts.map +1 -1
  136. package/dist/routes/auto/delete.routes.js +8 -10
  137. package/dist/routes/auto/get.routes.d.ts +2 -2
  138. package/dist/routes/auto/get.routes.d.ts.map +1 -1
  139. package/dist/routes/auto/get.routes.js +5 -5
  140. package/dist/routes/auto/insert.routes.d.ts +2 -2
  141. package/dist/routes/auto/insert.routes.d.ts.map +1 -1
  142. package/dist/routes/auto/insert.routes.js +1 -7
  143. package/dist/routes/auto/plugin.d.ts +6 -0
  144. package/dist/routes/auto/plugin.d.ts.map +1 -1
  145. package/dist/routes/auto/plugin.js +60 -36
  146. package/dist/routes/auto/route-helpers.d.ts +26 -12
  147. package/dist/routes/auto/route-helpers.d.ts.map +1 -1
  148. package/dist/routes/auto/route-helpers.js +50 -19
  149. package/dist/routes/auto/search.routes.d.ts +2 -2
  150. package/dist/routes/auto/search.routes.d.ts.map +1 -1
  151. package/dist/routes/auto/search.routes.js +36 -24
  152. package/dist/routes/auto/update.routes.d.ts +2 -2
  153. package/dist/routes/auto/update.routes.d.ts.map +1 -1
  154. package/dist/routes/auto/update.routes.js +1 -8
  155. package/dist/routes/sql-api-decorator.d.ts +30 -12
  156. package/dist/routes/sql-api-decorator.d.ts.map +1 -1
  157. package/dist/routes/sql-api-decorator.js +44 -27
  158. package/dist/types/cli.d.ts +17 -6
  159. package/dist/types/cli.d.ts.map +1 -1
  160. package/dist/types/computed.d.ts +1 -1
  161. package/dist/types/computed.d.ts.map +1 -1
  162. package/dist/types/conditions.d.ts +3 -1
  163. package/dist/types/conditions.d.ts.map +1 -1
  164. package/dist/types/db.d.ts +44 -4
  165. package/dist/types/db.d.ts.map +1 -1
  166. package/dist/types/dml.d.ts +26 -17
  167. package/dist/types/dml.d.ts.map +1 -1
  168. package/dist/types/hooks.d.ts +62 -0
  169. package/dist/types/hooks.d.ts.map +1 -0
  170. package/dist/types/hooks.js +1 -0
  171. package/dist/types/join.d.ts +25 -8
  172. package/dist/types/join.d.ts.map +1 -1
  173. package/dist/types/plugin.d.ts +58 -19
  174. package/dist/types/plugin.d.ts.map +1 -1
  175. package/dist/types/plugin.js +2 -0
  176. package/dist/types/request.d.ts +2 -2
  177. package/dist/types/schema.d.ts +3 -3
  178. package/dist/types/schema.d.ts.map +1 -1
  179. package/dist/types/search.d.ts +28 -13
  180. package/dist/types/search.d.ts.map +1 -1
  181. package/dist/types/search.js +2 -1
  182. package/dist/types/table.d.ts +109 -94
  183. package/dist/types/table.d.ts.map +1 -1
  184. package/dist/types/table.js +7 -2
  185. package/dist/types/tenant.d.ts +28 -2
  186. package/dist/types/tenant.d.ts.map +1 -1
  187. package/dist/types/tenant.js +7 -1
  188. package/dist/types/validation.d.ts +69 -13
  189. package/dist/types/validation.d.ts.map +1 -1
  190. package/dist/types.d.ts +1 -0
  191. package/dist/types.d.ts.map +1 -1
  192. package/dist/types.js +1 -0
  193. package/docs/GLOSSARY.md +11 -5
  194. package/docs/adr/0003-bulk-not-transactional.md +2 -1
  195. package/docs/adr/0006-raw-db-errors.md +2 -1
  196. package/docs/adr/0013-sanitized-db-errors.md +2 -1
  197. package/docs/adr/0014-what-follows-a-write-join.md +1 -1
  198. package/docs/adr/0022-stay-on-0x-while-every-consumer-is-first-party.md +88 -0
  199. package/docs/adr/0023-a-write-runs-in-a-transaction-or-not-at-all.md +60 -0
  200. package/docs/adr/0024-the-consumer-maps-driver-codes-through-dberrors.md +78 -0
  201. package/docs/adr/0025-validatebulk-replaces-validate-in-a-bulk-upsert.md +46 -0
  202. package/docs/adr/0026-update-carries-its-primary-key-in-main.md +43 -0
  203. package/docs/adr/0027-the-1-0-contract.md +74 -0
  204. package/docs/adr/0028-select-star-is-the-default-projection.md +64 -0
  205. package/docs/adr/0029-a-write-names-its-child-rows-by-action.md +96 -0
  206. package/docs/adr/0030-a-child-row-is-validated-by-its-own-table.md +117 -0
  207. package/docs/adr/0031-an-insert-excluded-upsert-key-addresses-an-existing-row.md +58 -0
  208. package/docs/adr/0032-tenant-scope-names-schema-fields.md +56 -0
  209. package/docs/adr/README.md +12 -1
  210. package/docs/upgrading/0.x.md +906 -0
  211. package/docs/upgrading/1.0.md +628 -0
  212. package/package.json +4 -5
package/dist/lib/db.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Expression } from 'node-condition-builder';
1
+ import { Expression, ConditionBuilder } from 'node-condition-builder';
2
2
  import { getDialect } from './dialect.js';
3
3
  // Default chunk size for bulk INSERT/UPSERT. Picked to keep parameter count well under
4
4
  // PostgreSQL's hard limit of 65535 bind parameters per statement (≈ 130 columns × 500 rows).
@@ -6,15 +6,23 @@ import { getDialect } from './dialect.js';
6
6
  const DEFAULT_CHUNK_SIZE = 500;
7
7
  // Column tagging each row of an upsert key lookup with its record's position in the chunk
8
8
  const LOOKUP_POSITION = 'sqlapi_lookup_position';
9
- /** @deprecated Use db.qi() instead */
10
- export const escapeIdent = (f) => f.replace(/"/g, '""');
9
+ // Column carrying the dialect's inserted/updated flag in an upsert's RETURNING list
10
+ const INSERTED_FLAG = '__inserted';
11
+ const asInserted = (pkRows) => pkRows.map((pk) => ({ pk, action: 'inserted' }));
11
12
  export class QueryClient {
12
13
  client;
13
14
  dialect;
14
15
  debug = false;
15
- constructor(client, dialect) {
16
+ /** True on the client `withTransaction` hands its callback: it wraps the transaction's connection. */
17
+ inTransaction;
18
+ constructor(client, dialect, inTransaction = false) {
16
19
  this.client = client;
17
20
  this.dialect = dialect ?? getDialect('postgres');
21
+ this.inTransaction = inTransaction;
22
+ }
23
+ /** Whether `withTransaction` can run: the Queryable has `connect()`, or this client already is a transaction. */
24
+ get supportsTransactions() {
25
+ return this.inTransaction || typeof this.client.connect === 'function';
18
26
  }
19
27
  get qi() {
20
28
  return this.dialect.qi;
@@ -55,19 +63,27 @@ export class QueryClient {
55
63
  }
56
64
  /**
57
65
  * Run `fn` inside a DB transaction on a dedicated connection (BEGIN/COMMIT, with
58
- * ROLLBACK + rethrow on error). Requires the underlying Queryable to expose
59
- * `connect()`; when it does not (legacy custom adapters), `fn` runs directly on
60
- * this client without transactional guarantees.
66
+ * ROLLBACK + rethrow on error). Requires the underlying Queryable to expose `connect()`.
67
+ *
68
+ * Without it the call fails, and nothing runs: a write that asked for atomicity — a main
69
+ * row with its secondaries, deletions and after-hooks — must not be executed as separate
70
+ * autocommitted statements because the adapter cannot do better: a custom adapter without
71
+ * `connect()` would otherwise lose the guarantee in silence (ADR 0023).
61
72
  *
62
- * Nested calls join the outer transaction: the tx QueryClient wraps a dedicated
63
- * connection that has no `connect()`, so an inner `withTransaction` is a no-op
64
- * wrapper around the same connection.
73
+ * Nested calls join the outer transaction: the tx QueryClient wraps the dedicated
74
+ * connection, which has no `connect()` either, so an inner `withTransaction` runs `fn` on
75
+ * the same connection. That is the one case where a missing `connect()` is not an error.
65
76
  */
66
77
  async withTransaction(fn) {
67
- if (!this.client.connect)
78
+ if (this.inTransaction)
68
79
  return fn(this);
80
+ if (!this.client.connect) {
81
+ throw new Error('Transactions are unavailable: the Queryable has no connect(). Pass a pool to pgQueryable()/' +
82
+ 'mysqlQueryable(), or implement connect() on the custom adapter: a write with secondaries, ' +
83
+ 'deletions or after-hooks runs in a transaction or not at all.');
84
+ }
69
85
  const conn = await this.client.connect();
70
- const tx = new QueryClient(conn, this.dialect);
86
+ const tx = new QueryClient(conn, this.dialect, true);
71
87
  tx.setDebug(this.debug);
72
88
  try {
73
89
  await conn.query('BEGIN');
@@ -166,11 +182,16 @@ export class QueryClient {
166
182
  VALUES (${placeholders.join(', ')})${returning}`, values);
167
183
  return this.#extractPkRows(result, pkCol, [record])[0];
168
184
  }
169
- async insertOrUpdate(table, record, conflictKeys, pkCol) {
185
+ /**
186
+ * Insert `record`, or update the row its `conflictKeys` already name: `{ pk, action }`, the
187
+ * row's primary key and whether it was inserted or updated. The conflict keys are never in
188
+ * the update set. They must be a unique key the database enforces (ADR 0021).
189
+ */
190
+ async upsert(table, record, conflictKeys, pkCol) {
170
191
  if (!Object.keys(record).length)
171
192
  throw new Error('Cannot execute empty insert');
172
- const [pkRow] = await this.#bulkWrite(table, [record], pkCol, 1, { conflictKeys, keepAsIs: conflictKeys });
173
- return pkRow;
193
+ const [written] = await this.#bulkWrite(table, [record], pkCol, 1, { conflictKeys, keepAsIs: conflictKeys });
194
+ return written;
174
195
  }
175
196
  /**
176
197
  * Group records by their exact field set, keeping each record's input position. A bulk write
@@ -243,14 +264,17 @@ export class QueryClient {
243
264
  });
244
265
  }
245
266
  /**
246
- * One multi-row INSERT for records sharing `fields`; `tail` is the upsert clause, if any.
247
- * Returns the PK rows in the records' order.
267
+ * One multi-row INSERT for records sharing `fields`; `tail` is the upsert clause, if any, and
268
+ * `extraReturning` an expression added to the RETURNING list where the dialect has one.
269
+ * Returns the PK rows (plus that expression's column) in the records' order.
248
270
  */
249
- async #insertRows(table, fields, records, pkCol, tail = '') {
271
+ async #insertRows(table, fields, records, pkCol, tail = '', extraReturning = '') {
250
272
  const { values, rows } = this.#bulkValues(fields, records);
273
+ const returningPk = this.dialect.returningPk(this.#quotedPkCols(pkCol));
274
+ const returning = returningPk && extraReturning ? `${returningPk}, ${extraReturning}` : returningPk;
251
275
  const result = await this.query(`${this.#insertHead(table, fields)}
252
276
  VALUES ${rows}
253
- ${tail}${this.dialect.returningPk(this.#quotedPkCols(pkCol))}`, values);
277
+ ${tail}${returning}`, values);
254
278
  return this.#extractPkRows(result, pkCol, records);
255
279
  }
256
280
  /**
@@ -283,11 +307,11 @@ export class QueryClient {
283
307
  const found = upsert.conflictKeys.every((k) => fields.includes(k))
284
308
  ? await this.#findByKey(table, records, pkCol, upsert.conflictKeys)
285
309
  : new Map();
286
- const pkRows = new Array(records.length);
310
+ const written = new Array(records.length);
287
311
  const inserts = records.flatMap((_, i) => (found.has(i) ? [] : [i]));
288
312
  if (inserts.length) {
289
- const inserted = await this.#insertRows(table, fields, inserts.map((i) => records[i]), pkCol);
290
- inserts.forEach((i, k) => { pkRows[i] = inserted[k]; });
313
+ const insertedRows = await this.#insertRows(table, fields, inserts.map((i) => records[i]), pkCol);
314
+ inserts.forEach((i, k) => { written[i] = { pk: insertedRows[k], action: 'inserted' }; });
291
315
  }
292
316
  const updates = [...found.keys()];
293
317
  const columns = fields.filter((f) => !upsert.keepAsIs.includes(f));
@@ -295,32 +319,46 @@ export class QueryClient {
295
319
  await this.#updateByKey(table, columns, updates.map((i) => records[i]), upsert.conflictKeys);
296
320
  }
297
321
  for (const i of updates)
298
- pkRows[i] = found.get(i)[0];
299
- return pkRows;
322
+ written[i] = { pk: found.get(i)[0], action: 'updated' };
323
+ return written;
300
324
  }
301
325
  /**
302
326
  * One chunk of records sharing `fields`: a plain insert, or an upsert — `ON CONFLICT (key)`
303
- * where the dialect has it, by key otherwise. PK rows in the records' order.
327
+ * where the dialect has it, by key otherwise. Written rows in the records' order, each with
328
+ * the action the statement took on it.
304
329
  */
305
330
  async #writeChunk(table, fields, records, pkCol, upsert) {
306
331
  if (!upsert)
307
- return this.#insertRows(table, fields, records, pkCol);
332
+ return asInserted(await this.#insertRows(table, fields, records, pkCol));
308
333
  const onConflict = this.dialect.onConflict;
309
334
  if (!onConflict)
310
335
  return this.#upsertByKey(table, fields, records, pkCol, upsert);
311
336
  const updateSet = onConflict.updateSet(fields, upsert.keepAsIs);
312
- const pkRows = await this.#insertRows(table, fields, records, pkCol, onConflict.sql(this.#q(upsert.conflictKeys), updateSet));
313
- // Nothing to update: `DO NOTHING` returns no row for an existing one. A group missing a key
314
- // field can only insert, and RETURNING names every row it inserted.
315
- if (!updateSet && upsert.conflictKeys.every((k) => fields.includes(k))) {
316
- return this.#untouchedPkRows(table, records, pkCol, upsert.conflictKeys);
337
+ const clause = onConflict.sql(this.#q(upsert.conflictKeys), updateSet);
338
+ if (!updateSet) {
339
+ // Nothing to update: `DO NOTHING` returns a row for each one it inserted and none for an
340
+ // existing one. A group missing a key field can only insert, so RETURNING names every row;
341
+ // otherwise every row's PK is looked up, and the ones RETURNING named are the inserted.
342
+ const insertedRows = await this.#insertRows(table, fields, records, pkCol, clause);
343
+ if (!upsert.conflictKeys.every((k) => fields.includes(k)))
344
+ return asInserted(insertedRows);
345
+ const pkCols = Array.isArray(pkCol) ? pkCol : [pkCol];
346
+ const pkKey = (row) => pkCols.map((c) => String(row[c])).join('|');
347
+ const inserted = new Set(insertedRows.map(pkKey));
348
+ const pkRows = await this.#untouchedPkRows(table, records, pkCol, upsert.conflictKeys);
349
+ return pkRows.map((pk) => ({ pk, action: inserted.has(pkKey(pk)) ? 'inserted' : 'updated' }));
317
350
  }
318
- return pkRows;
351
+ // The statement itself says which rows it inserted and which it rewrote.
352
+ const rows = await this.#insertRows(table, fields, records, pkCol, clause, `${onConflict.insertedFlag} AS ${this.dialect.qi(INSERTED_FLAG)}`);
353
+ return rows.map(({ [INSERTED_FLAG]: flag, ...pk }) => ({
354
+ pk,
355
+ action: flag === false ? 'updated' : 'inserted',
356
+ }));
319
357
  }
320
358
  /**
321
359
  * Write `records`, one chunk at a time within each same-fields group (a single chunk when
322
360
  * every record has the same fields). With `upsert`, an existing row gets the record's fields
323
- * except `keepAsIs` — the conflict keys and the columns never overwritten. PK rows are
361
+ * except `keepAsIs` — the conflict keys and the columns never overwritten. Written rows are
324
362
  * returned in input order.
325
363
  */
326
364
  async #bulkWrite(table, records, pkCol, chunkSize, upsert) {
@@ -328,8 +366,8 @@ export class QueryClient {
328
366
  for (const { fields, indexes } of this.#groupByFields(records)) {
329
367
  for (let i = 0; i < indexes.length; i += chunkSize) {
330
368
  const chunkIndexes = indexes.slice(i, i + chunkSize);
331
- const pkRows = await this.#writeChunk(table, fields, chunkIndexes.map((j) => records[j]), pkCol, upsert);
332
- pkRows.forEach((row, k) => {
369
+ const written = await this.#writeChunk(table, fields, chunkIndexes.map((j) => records[j]), pkCol, upsert);
370
+ written.forEach((row, k) => {
333
371
  results[chunkIndexes[k]] = row;
334
372
  });
335
373
  }
@@ -339,14 +377,27 @@ export class QueryClient {
339
377
  async bulkInsert(table, records, pkCol, chunkSize = DEFAULT_CHUNK_SIZE) {
340
378
  if (!records.length)
341
379
  return [];
342
- return this.#bulkWrite(table, records, pkCol, chunkSize);
380
+ return (await this.#bulkWrite(table, records, pkCol, chunkSize)).map((r) => r.pk);
343
381
  }
344
382
  /**
345
- * `immutableCols` are written when the row is inserted but left untouched when the statement
346
- * lands on an existing row — like the conflict keys, which are never in the update set either.
347
- * Used by tenant isolation to keep an upsert from re-assigning a row's owner.
383
+ * `upsert` for every record, in chunks: `{ pk, action }` per record, in input order. Each
384
+ * record writes only its own fields (ADR 0003).
385
+ *
386
+ * - `chunkSize`: records per statement (default {@link DEFAULT_CHUNK_SIZE}).
387
+ * - `immutableCols`: written when the row is inserted, left untouched when the statement
388
+ * lands on an existing row — like the conflict keys. Tenant isolation uses it to keep an
389
+ * upsert from re-assigning a row's owner.
348
390
  */
349
- async bulkInsertOrUpdate(table, records, conflictKeys, pkCol, chunkSize = DEFAULT_CHUNK_SIZE, immutableCols = []) {
391
+ async bulkUpsert(table, records, conflictKeys, pkCol, options = {}) {
392
+ // The pre-1.0 `bulkInsertOrUpdate(…, chunkSize, immutableCols)` passed both positionally:
393
+ // refused, so an immutable column is never dropped in silence and written on update. The
394
+ // signature stays strict for TypeScript; the count is the JS caller's check.
395
+ // eslint-disable-next-line prefer-rest-params
396
+ if (arguments.length > 5 || options === null || typeof options !== 'object') {
397
+ throw new TypeError('bulkUpsert: the 5th argument is an options object, { chunkSize, immutableCols }, ' +
398
+ 'not a positional chunkSize');
399
+ }
400
+ const { chunkSize = DEFAULT_CHUNK_SIZE, immutableCols = [] } = options;
350
401
  if (!records.length)
351
402
  return [];
352
403
  const keepAsIs = immutableCols.length ? [...conflictKeys, ...immutableCols] : conflictKeys;
@@ -394,6 +445,29 @@ export class QueryClient {
394
445
  return result.rows;
395
446
  }
396
447
  }
448
+ /**
449
+ * The predicate matching one row by its key: `col = ?` for every key column. `cols` are quoted
450
+ * (and qualified, when the statement needs it); `key` holds one value per column, in order.
451
+ */
452
+ function buildKeyEquals(db, cols, key) {
453
+ const cb = new ConditionBuilder('AND', db.cbDialect);
454
+ cols.forEach((col, i) => cb.isEqual(col, key[i]));
455
+ return cb;
456
+ }
457
+ /**
458
+ * The predicate matching a set of rows by their keys: `col IN (…)` for a single column, and for
459
+ * several an OR of one {@link buildKeyEquals} group per key, so each key binds all of its columns
460
+ * together — never one column alone, which would reach every row sharing that value.
461
+ */
462
+ export function buildKeyMatch(db, cols, keys) {
463
+ if (cols.length === 1) {
464
+ return new ConditionBuilder('AND', db.cbDialect).isIn(cols[0], keys.map((k) => k[0]));
465
+ }
466
+ const match = new ConditionBuilder('OR', db.cbDialect);
467
+ for (const key of keys)
468
+ match.append(buildKeyEquals(db, cols, key));
469
+ return match;
470
+ }
397
471
  export function createQueryClient(pool, dialectName) {
398
472
  const dialect = getDialect((dialectName || 'postgres'));
399
473
  return new QueryClient(pool, dialect);
@@ -23,6 +23,11 @@ export interface SqlDialect {
23
23
  * for every field not in `keepAsIs`; '' when nothing is left to update.
24
24
  */
25
25
  updateSet(fields: string[], keepAsIs: string[]): string;
26
+ /**
27
+ * A boolean SQL expression for the RETURNING list that is true on a row the statement
28
+ * inserted and false on one it updated, so an upsert can report what it did.
29
+ */
30
+ insertedFlag: string;
26
31
  };
27
32
  /** RETURNING pk_col suffix or empty string */
28
33
  returningPk(quotedPkCol: string): string;
@@ -1 +1 @@
1
- {"version":3,"file":"dialect.d.ts","sourceRoot":"","sources":["../../src/lib/dialect.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,WAAW,GAAG,UAAU,GAAG,OAAO,GAAG,SAAS,CAAC;AAE3D,KAAK,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,OAAO,GAAG,KAAK,GAAG,MAAM,CAAC;AAElE,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,WAAW,CAAC;IAClB,gEAAgE;IAChE,EAAE,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAAC;IACvB,sDAAsD;IACtD,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC;IAC1B,oCAAoC;IACpC,SAAS,EAAE,UAAU,GAAG,OAAO,CAAC;IAChC,iBAAiB,EAAE,OAAO,CAAC;IAC3B;;;;;OAKG;IACH,UAAU,CAAC,EAAE;QACX,0FAA0F;QAC1F,GAAG,CAAC,kBAAkB,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,MAAM,CAAC;QACjE;;;WAGG;QACH,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;KACzD,CAAC;IACF,8CAA8C;IAC9C,WAAW,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAAC;IACzC;;;;;;OAMG;IACH,SAAS,CAAC,IAAI,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,CAAC;CAC7D;AAsED,wBAAgB,UAAU,CAAC,IAAI,EAAE,WAAW,GAAG,UAAU,CAIxD"}
1
+ {"version":3,"file":"dialect.d.ts","sourceRoot":"","sources":["../../src/lib/dialect.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,WAAW,GAAG,UAAU,GAAG,OAAO,GAAG,SAAS,CAAC;AAE3D,KAAK,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,OAAO,GAAG,KAAK,GAAG,MAAM,CAAC;AAElE,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,WAAW,CAAC;IAClB,gEAAgE;IAChE,EAAE,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAAC;IACvB,sDAAsD;IACtD,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC;IAC1B,oCAAoC;IACpC,SAAS,EAAE,UAAU,GAAG,OAAO,CAAC;IAChC,iBAAiB,EAAE,OAAO,CAAC;IAC3B;;;;;OAKG;IACH,UAAU,CAAC,EAAE;QACX,0FAA0F;QAC1F,GAAG,CAAC,kBAAkB,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,MAAM,CAAC;QACjE;;;WAGG;QACH,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;QACxD;;;WAGG;QACH,YAAY,EAAE,MAAM,CAAC;KACtB,CAAC;IACF,8CAA8C;IAC9C,WAAW,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAAC;IACzC;;;;;;OAMG;IACH,SAAS,CAAC,IAAI,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,CAAC;CAC7D;AAyED,wBAAgB,UAAU,CAAC,IAAI,EAAE,WAAW,GAAG,UAAU,CAIxD"}
@@ -15,6 +15,9 @@ const PostgresDialect = {
15
15
  const updateCols = fields.filter((f) => !keepAsIs.includes(f));
16
16
  return updateCols.map((f) => `${pgQi(f)} = EXCLUDED.${pgQi(f)}`).join(', ');
17
17
  },
18
+ // A freshly inserted row has no deleting/updating transaction recorded: xmax is 0. A row
19
+ // `ON CONFLICT DO UPDATE` rewrote carries the current transaction's id there.
20
+ insertedFlag: '(xmax = 0)',
18
21
  },
19
22
  returningPk(quotedPkCol) {
20
23
  return ` RETURNING ${quotedPkCol}`;
@@ -1,3 +1,8 @@
1
1
  import type { BulkDeleteParams, BulkDeleteResult } from '../../../types.js';
2
+ /**
3
+ * Delete rows by primary key. A single-column key takes the values themselves; a composite key
4
+ * takes one object per row naming every key field, and each row is matched on all of its key
5
+ * columns together — never on one column alone, which would reach every row sharing it.
6
+ */
2
7
  export declare function bulkDeleteEngine(params: BulkDeleteParams): Promise<BulkDeleteResult[]>;
3
8
  //# sourceMappingURL=bulk-delete.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bulk-delete.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/bulk/bulk-delete.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAE5E,wBAAsB,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAuE5F"}
1
+ {"version":3,"file":"bulk-delete.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/bulk/bulk-delete.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAmB,MAAM,mBAAmB,CAAC;AAE7F;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAsE5F"}
@@ -1,57 +1,93 @@
1
1
  import { ConditionBuilder } from 'node-condition-builder';
2
- import { buildTenantDeleteWhere, assertTenantOwnsAll } from '../../tenant.js';
3
- import { primaryAsString, isCompositePrimary } from '../../../types.js';
2
+ import { buildTenantRowGuard, assertTenantOwnsAll } from '../../tenant.js';
3
+ import { buildKeyMatch } from '../../db.js';
4
4
  import { httpError } from '../../errors.js';
5
+ /**
6
+ * Delete rows by primary key. A single-column key takes the values themselves; a composite key
7
+ * takes one object per row naming every key field, and each row is matched on all of its key
8
+ * columns together — never on one column alone, which would reach every row sharing it.
9
+ */
5
10
  export async function bulkDeleteEngine(params) {
6
11
  const { db, tableConf, ids, tenant, request } = params;
7
- if (isCompositePrimary(tableConf.primary)) {
8
- throw httpError(400, `Table "${tableConf.Schema.tableName}" has a composite primary key: bulk delete matches on "${primaryAsString(tableConf.primary)}" alone and could remove multiple rows per id. Use a custom query.`);
9
- }
10
- if (!ids.length)
12
+ const pkFields = Array.isArray(tableConf.primary) ? tableConf.primary : [tableConf.primary];
13
+ const keys = keyValues(ids, pkFields);
14
+ if (!keys.length)
11
15
  return [];
12
- const pk = primaryAsString(tableConf.primary);
13
- const pkCol = tableConf.Schema.col(pk);
14
- const tableName = tableConf.Schema.tableName;
16
+ const pkCols = pkFields.map((f) => tableConf.schema.col(f));
17
+ const tableName = tableConf.schema.tableName;
18
+ const single = pkFields.length === 1;
19
+ /** A deleted row's key, as the response and `afterBulkDelete` name it. */
20
+ const keyOf = (values) => Object.fromEntries(pkFields.map((f, i) => [f, values[i]]));
15
21
  if (tableConf.beforeBulkDelete) {
16
22
  // Enforce tenant ownership of every id before the hook (single batched SELECT), so it
17
23
  // never runs for rows the tenant cannot access. Called once with all ids — no loop.
18
- await assertTenantOwnsAll(db, tenant, tableName, pkCol, ids);
19
- await tableConf.beforeBulkDelete(db, request, ids);
20
- }
21
- let where;
22
- let values;
23
- if (tenant) {
24
- ({ where, values } = buildTenantDeleteWhere(db, tableName, pkCol, ids, tenant));
25
- }
26
- else {
27
- const cb = new ConditionBuilder('AND', db.cbDialect);
28
- cb.isIn(db.qi(pkCol), ids);
29
- where = cb.build(1, db.ph);
30
- values = cb.getValues();
24
+ await assertTenantOwnsAll(db, tenant, tableName, pkCols, keys);
25
+ await tableConf.beforeBulkDelete({ db, req: request, ids });
31
26
  }
27
+ // The keys, and the tenant's guard when the table is scoped: a row the caller does not own
28
+ // is not deleted, and is left out of the answer like a missing one.
29
+ const keyMatch = buildKeyMatch(db, pkCols.map((c) => db.qi(c)), keys);
30
+ const guard = buildTenantRowGuard(db, tenant, tableName);
31
+ const condition = guard
32
+ ? new ConditionBuilder('AND', db.cbDialect).append(keyMatch).append(guard)
33
+ : keyMatch;
34
+ const where = condition.build(1, db.ph);
35
+ const values = condition.getValues();
36
+ const quotedPkCols = pkCols.map((c) => db.qi(c)).join(', ');
32
37
  let results;
33
38
  if (db.supportsReturning) {
34
- const result = await db.query(`DELETE FROM ${db.qi(tableName)} WHERE ${where}${db.returningPk(db.qi(pkCol))}`, values);
39
+ const result = await db.query(`DELETE FROM ${db.qi(tableName)} WHERE ${where}${db.returningPk(quotedPkCols)}`, values);
35
40
  // Happy path: everything requested was deleted
36
- if (result.affectedRows === ids.length) {
37
- results = ids.map((id) => ({ main: { [pk]: id } }));
41
+ if (result.affectedRows === keys.length) {
42
+ results = keys.map((k) => ({ main: keyOf(k) }));
38
43
  }
39
44
  else {
40
45
  // Partial delete: RETURNING tells exactly which rows went away
41
- results = result.rows.map((r) => ({ main: { [pk]: r[pkCol] } }));
46
+ results = result.rows.map((r) => ({ main: keyOf(pkCols.map((c) => r[c])) }));
42
47
  }
43
48
  }
44
49
  else {
45
50
  // No RETURNING (mysql): affectedRows alone cannot tell WHICH ids were deleted on a
46
51
  // partial match, so look up the rows visible through the same WHERE before deleting.
47
- const existing = await db.query(`SELECT ${db.qi(pkCol)} AS pk FROM ${db.qi(tableName)} WHERE ${where}`, values);
52
+ const keyList = single ? `${quotedPkCols} AS pk` : quotedPkCols;
53
+ const existing = await db.query(`SELECT ${keyList} FROM ${db.qi(tableName)} WHERE ${where}`, values);
48
54
  await db.query(`DELETE FROM ${db.qi(tableName)} WHERE ${where}`, values);
49
- results = existing.rows.map((r) => ({ main: { [pk]: r.pk } }));
55
+ results = existing.rows.map((r) => ({ main: keyOf(single ? [r.pk] : pkCols.map((c) => r[c])) }));
50
56
  }
51
57
  // Called once with the ACTUALLY deleted ids (possibly a subset of the requested ones)
52
58
  if (tableConf.afterBulkDelete && results.length > 0) {
53
- const deletedIds = results.map((r) => r.main[pk]);
54
- await tableConf.afterBulkDelete(db, request, deletedIds);
59
+ const deletedIds = results.map((r) => (single ? r.main[pkFields[0]] : r.main));
60
+ await tableConf.afterBulkDelete({ db, req: request, ids: deletedIds });
55
61
  }
56
62
  return results;
57
63
  }
64
+ /**
65
+ * One value per key column for each id, in `pkFields` order. The HTTP body schema already
66
+ * enforces this shape; `sqlApi` runs no body schema, so it is checked here too, as a 400 at the
67
+ * same paths: an object for a single-column key, or a composite id that is not an object, is a
68
+ * `type` at `ids.<i>`; a missing key field a `required`, a field outside the key an
69
+ * `additionalProperties` at `ids.<i>.<field>`.
70
+ */
71
+ function keyValues(ids, pkFields) {
72
+ return ids.map((id, i) => {
73
+ const isObject = id !== null && typeof id === 'object' && !Array.isArray(id);
74
+ if (pkFields.length === 1) {
75
+ if (isObject)
76
+ throw httpError(400, `ids.${i}: a single-column key takes its value, not an object`, { code: 'type', path: `ids.${i}` });
77
+ return [id];
78
+ }
79
+ if (!isObject) {
80
+ throw httpError(400, `ids.${i}: a composite key takes an object naming ${pkFields.join(', ')}`, { code: 'type', path: `ids.${i}` });
81
+ }
82
+ const key = id;
83
+ const extra = Object.keys(key).find((f) => !pkFields.includes(f));
84
+ if (extra !== undefined) {
85
+ throw httpError(400, `ids.${i}.${extra} is not a primary key field`, { code: 'additionalProperties', path: `ids.${i}.${extra}` });
86
+ }
87
+ const missing = pkFields.find((f) => key[f] == null);
88
+ if (missing !== undefined) {
89
+ throw httpError(400, `ids.${i}.${missing} is required`, { code: 'required', path: `ids.${i}.${missing}` });
90
+ }
91
+ return pkFields.map((f) => key[f]);
92
+ });
93
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"bulk-upsert.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/bulk/bulk-upsert.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAEV,gBAAgB,EAChB,gBAAgB,EAEjB,MAAM,mBAAmB,CAAC;AAgE3B,wBAAsB,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CA0C5F"}
1
+ {"version":3,"file":"bulk-upsert.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/bulk/bulk-upsert.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAEV,gBAAgB,EAChB,gBAAgB,EAIjB,MAAM,mBAAmB,CAAC;AA6F3B,wBAAsB,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CA4C5F"}
@@ -1,72 +1,91 @@
1
1
  import { camelcaseObject } from '../../naming.js';
2
- import { processSecondaries, processDeletions, prepareInsertRecord, assertUpsertKeys, } from '../write-helpers.js';
2
+ import { processSecondaries, processDeletions, prepareInsertRecord, assertUpsertKeys, assertExcludedKeysExist, insertExcludedKeyFields, assertWriteJoinAliases, hasAliases, } from '../write-helpers.js';
3
3
  import { enforceTenantOnWrites, assertTenantOwnsConflicts, tenantImmutableColumns, } from '../../tenant.js';
4
4
  import { runBulkValidation } from '../validate.js';
5
5
  import { primaryAsCols } from '../../../types.js';
6
- /** One bulk statement for every main row, returning the PKs only. */
7
- function upsertMains(params, preparedMains, pkCol) {
6
+ /** One bulk statement for every main row: its PK and what the statement did to it. */
7
+ async function upsertMains(params, preparedMains, pkCol) {
8
8
  const { db, tableConf, tenant } = params;
9
- const schema = tableConf.Schema;
10
- const upsertKeys = tableConf.upsertMap?.get(schema);
9
+ const schema = tableConf.schema;
10
+ const upsertKeys = tableConf.upsertKey;
11
11
  if (!upsertKeys) {
12
- return db.bulkInsert(schema.tableName, preparedMains, pkCol);
12
+ const pkRows = await db.bulkInsert(schema.tableName, preparedMains, pkCol);
13
+ return pkRows.map((pk) => ({ pk, action: 'inserted' }));
13
14
  }
14
15
  const conflictCols = upsertKeys.map((k) => schema.col(k));
15
16
  assertUpsertKeys(schema, conflictCols, [pkCol].flat(), preparedMains);
17
+ await assertExcludedKeysExist(db, schema, conflictCols, insertExcludedKeyFields(tableConf, upsertKeys), preparedMains, params.items.map((item) => item.main), (i, field) => `${i}.main.${field}`);
16
18
  // Tenant isolation: a conflicting upsert must not overwrite rows owned by another tenant, nor
17
19
  // re-assign the owner of a row it legitimately updates.
18
- return assertTenantOwnsConflicts(db, tenant, schema.tableName, conflictCols, preparedMains)
19
- .then(() => db.bulkInsertOrUpdate(schema.tableName, preparedMains, conflictCols, pkCol, undefined, tenantImmutableColumns(tenant)));
20
+ await assertTenantOwnsConflicts(db, tenant, schema.tableName, conflictCols, preparedMains);
21
+ return db.bulkUpsert(schema.tableName, preparedMains, conflictCols, pkCol, { immutableCols: tenantImmutableColumns(tenant) });
20
22
  }
21
- /** Secondaries, deletions and the afterInsert hook for one upserted item. */
22
- async function finalizeUpsertedItem(params, item, inputMain, pkRow) {
23
+ /**
24
+ * The child rows and the afterInsert hook of one upserted item. The batch runs without a
25
+ * transaction (ADR 0003), but an item with a `replace` runs this in a transaction of its own
26
+ * (ADR 0029): its upsert and the removal of the rows it left out commit together, so the item
27
+ * never ends with half its children replaced.
28
+ */
29
+ function finalizeUpsertedItem(params, at, item, inputMain, written) {
30
+ return hasAliases(item.replace)
31
+ ? params.db.withTransaction((tx) => writeItemChildren({ ...params, db: tx }, at, item, inputMain, written))
32
+ : writeItemChildren(params, at, item, inputMain, written);
33
+ }
34
+ async function writeItemChildren(params, at, item, inputMain, written) {
23
35
  const { db, tableConf, dbTables, request, tenant } = params;
24
- // pkRow comes from SQL RETURNING or mysql insertId synthesis — keys are DB column names;
36
+ // The PK row comes from SQL RETURNING or mysql insertId synthesis — keys are DB column names;
25
37
  // camelcaseObject maps them back to schema fields (full composite PK).
26
- const mainPkCamel = camelcaseObject(pkRow, tableConf.Schema);
27
- const result = { main: mainPkCamel };
38
+ const mainPkCamel = camelcaseObject(written.pk, tableConf.schema);
39
+ const result = { main: mainPkCamel, action: written.action };
28
40
  // FK auto-fill: input camelCase + generated PK
29
41
  const mainForFK = { ...inputMain, ...mainPkCamel };
30
- if (item.secondaries && Object.keys(item.secondaries).length > 0) {
31
- const sec = await processSecondaries({ db, tableConf, dbTables, mainRecord: mainForFK, tenant, request }, item.secondaries);
32
- if (Object.keys(sec).length > 0)
33
- result.secondaries = sec;
42
+ let removed = {};
43
+ if (hasAliases(item.upsert, item.replace)) {
44
+ const outcome = await processSecondaries({ db, tableConf, dbTables, mainRecord: mainForFK, tenant, request, at: String(at) }, { upsert: item.upsert, replace: item.replace });
45
+ if (Object.keys(outcome.written).length > 0)
46
+ result.secondaries = outcome.written;
47
+ removed = outcome.removed;
34
48
  }
35
- if (item.deletions && Object.keys(item.deletions).length > 0) {
36
- const del = await processDeletions({ db, tableConf, dbTables, mainRecord: mainForFK, tenant, request }, item.deletions);
49
+ if (hasAliases(item.delete)) {
50
+ const del = await processDeletions({ db, tableConf, dbTables, mainRecord: mainForFK, tenant, request }, item.delete ?? {});
37
51
  if (Object.keys(del).length > 0)
38
52
  result.deletions = del;
39
53
  }
54
+ if (Object.keys(removed).length > 0)
55
+ result.deletions = { ...result.deletions, ...removed };
40
56
  if (tableConf.afterInsert) {
41
- await tableConf.afterInsert(db, request, mainForFK, result.secondaries);
57
+ await tableConf.afterInsert({
58
+ db, req: request, record: mainForFK, secondaries: result.secondaries, deletions: result.deletions,
59
+ });
42
60
  }
43
61
  return result;
44
62
  }
45
63
  export async function bulkUpsertEngine(params) {
46
- const { db, tableConf, request, items, tenant } = params;
64
+ const { db, tableConf, dbTables, request, items, tenant } = params;
47
65
  if (!items.length)
48
66
  return [];
49
- const schema = tableConf.Schema;
67
+ const schema = tableConf.schema;
50
68
  // Full primary key columns — composite PKs need every column (see insertEngine).
51
69
  const pkCol = primaryAsCols(tableConf.primary, (f) => schema.col(f));
70
+ items.forEach((item, i) => assertWriteJoinAliases(tableConf, item, String(i)));
52
71
  // 1. Bulk validation runs once for all items (skips per-item validate). Otherwise per-item
53
72
  // validation happens inside prepareInsertRecord below.
54
73
  if (tableConf.validateBulk) {
55
74
  await runBulkValidation(db, request, tableConf, items);
56
75
  }
57
76
  // 2. For each item: validate (unless validateBulk ran) → beforeInsert → snake → remove excluded.
58
- const prepared = await Promise.all(items.map((item) => prepareInsertRecord({ db, tableConf, request }, item.main, item.secondaries, { skipValidate: !!tableConf.validateBulk })));
77
+ const prepared = await Promise.all(items.map((item, i) => prepareInsertRecord({ db, tableConf, dbTables, request }, item.main, { upsert: item.upsert, replace: item.replace }, { skipValidate: !!tableConf.validateBulk, at: String(i) })));
59
78
  const inputMains = prepared.map((p) => p.camel);
60
79
  const preparedMains = prepared.map((p) => p.snake);
61
80
  // 3. Tenant: inject (direct) or batch-validate FK (indirect) — enforced after user mutations
62
81
  await enforceTenantOnWrites(db, tenant, preparedMains);
63
- // 4. Bulk upsert all mains in one query → returns PK-only
64
- const pkRows = await upsertMains(params, preparedMains, pkCol);
82
+ // 4. Bulk upsert all mains in one query → PK and action per row
83
+ const written = await upsertMains(params, preparedMains, pkCol);
65
84
  // 5-6. Secondaries, deletions and afterInsert per item — sequential on purpose, so hooks
66
85
  // observe the same order the caller sent, and errors surface on the first bad item.
67
86
  const results = [];
68
87
  for (let i = 0; i < items.length; i++) {
69
- results.push(await finalizeUpsertedItem(params, items[i], inputMains[i], pkRows[i]));
88
+ results.push(await finalizeUpsertedItem(params, i, items[i], inputMains[i], written[i]));
70
89
  }
71
90
  return results;
72
91
  }
@@ -1,6 +1,6 @@
1
1
  import type { ApiRequest } from '../../types/request.js';
2
2
  import type { QueryClient } from '../db.js';
3
- import type { ITable, ReadSource } from '../../types.js';
3
+ import type { TableConfig, ReadSource } from '../../types.js';
4
4
  /**
5
5
  * Run a table's `afterRead` hook over the rows a read produced.
6
6
  *
@@ -10,10 +10,10 @@ import type { ITable, ReadSource } from '../../types.js';
10
10
  * gets one call per result set instead of one per row.
11
11
  *
12
12
  * `tableConf` is resolved by the caller, which on a join is the JOINED table's config
13
- * (`dbTables[joinSchema.tableName]`). That is what makes the hook follow a relation without
13
+ * (`resolveJoinTableConf`). That is what makes the hook follow a relation without
14
14
  * being declared on the host, the way `readExclude` and `tenantScope` do (ADR 0010).
15
15
  *
16
16
  * An empty result set is skipped: there is nothing to transform, and the hook may be costly.
17
17
  */
18
- export declare function runAfterRead(db: QueryClient, request: ApiRequest | undefined, rows: Record<string, unknown>[], tableConf: ITable | undefined, source: ReadSource, alias?: string): Promise<void>;
18
+ export declare function runAfterRead(db: QueryClient, request: ApiRequest | undefined, rows: Record<string, unknown>[], tableConf: TableConfig | undefined, source: ReadSource, alias?: string): Promise<void>;
19
19
  //# sourceMappingURL=read-hooks.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"read-hooks.d.ts","sourceRoot":"","sources":["../../../src/lib/engine/read-hooks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,KAAK,EAAoB,MAAM,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE3E;;;;;;;;;;;;;GAaG;AACH,wBAAsB,YAAY,CAChC,EAAE,EAAE,WAAW,EACf,OAAO,EAAE,UAAU,GAAG,SAAS,EAC/B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EAC/B,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,MAAM,EAAE,UAAU,EAClB,KAAK,CAAC,EAAE,MAAM,GACb,OAAO,CAAC,IAAI,CAAC,CAIf"}
1
+ {"version":3,"file":"read-hooks.d.ts","sourceRoot":"","sources":["../../../src/lib/engine/read-hooks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,KAAK,EAAoB,WAAW,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAGhF;;;;;;;;;;;;;GAaG;AACH,wBAAsB,YAAY,CAChC,EAAE,EAAE,WAAW,EACf,OAAO,EAAE,UAAU,GAAG,SAAS,EAC/B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EAC/B,SAAS,EAAE,WAAW,GAAG,SAAS,EAClC,MAAM,EAAE,UAAU,EAClB,KAAK,CAAC,EAAE,MAAM,GACb,OAAO,CAAC,IAAI,CAAC,CAIf"}
@@ -7,7 +7,7 @@
7
7
  * gets one call per result set instead of one per row.
8
8
  *
9
9
  * `tableConf` is resolved by the caller, which on a join is the JOINED table's config
10
- * (`dbTables[joinSchema.tableName]`). That is what makes the hook follow a relation without
10
+ * (`resolveJoinTableConf`). That is what makes the hook follow a relation without
11
11
  * being declared on the host, the way `readExclude` and `tenantScope` do (ADR 0010).
12
12
  *
13
13
  * An empty result set is skipped: there is nothing to transform, and the hook may be costly.
@@ -15,6 +15,6 @@
15
15
  export async function runAfterRead(db, request, rows, tableConf, source, alias) {
16
16
  if (!tableConf?.afterRead || rows.length === 0)
17
17
  return;
18
- const ctx = alias === undefined ? { source } : { source, alias };
19
- await tableConf.afterRead(db, request, rows, ctx);
18
+ const ctx = { db, req: request, rows, source, ...(alias === undefined ? {} : { alias }) };
19
+ await tableConf.afterRead(ctx);
20
20
  }
@@ -1 +1 @@
1
- {"version":3,"file":"delete.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/rest/delete.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEpE,wBAAsB,YAAY,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC,CAuC9E"}
1
+ {"version":3,"file":"delete.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/rest/delete.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEpE,wBAAsB,YAAY,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC,CA8B9E"}