fastify-auto-sqlapi 0.5.0 → 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 +258 -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 +94 -28
  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 -62
  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 +33 -21
  91. package/dist/lib/read-access.d.ts.map +1 -1
  92. package/dist/lib/read-access.js +42 -23
  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
@@ -70,7 +70,7 @@ function detectPrimaryKey(schema) {
70
70
  ? { pk: 'id', autoIncrement: false, source: 'inferred' }
71
71
  : { pk: PK_PLACEHOLDER, autoIncrement: false, source: 'unresolved' };
72
72
  }
73
- // Heuristic fallback for hand-written/legacy schema files without primaryKey.
73
+ // Heuristic fallback for a schema file without primaryKey (written by hand).
74
74
  if (schema.fields.includes('id')) {
75
75
  return {
76
76
  pk: 'id',
@@ -192,13 +192,13 @@ function schemaOverridesLine(schema, pk) {
192
192
  function tenantScopeLine(childRels) {
193
193
  const rel = childRels[0];
194
194
  if (!rel)
195
- return ` // tenantScope: { column: 'tenant_col' },`;
196
- return ` // tenantScope: { column: 'tenant_col', through: { schema: ${rel.parentSchemaName}, localField: '${rel.childField}', foreignField: '${rel.parentField}' } },`;
195
+ return ` // tenantScope: { column: 'organizationId' },`;
196
+ return ` // tenantScope: { column: 'organizationId', through: { schema: ${rel.parentSchemaName}, localField: '${rel.childField}', foreignField: '${rel.parentField}' } },`;
197
197
  }
198
- function allowedReadJoinsLines(parentRels) {
198
+ function readJoinsLines(parentRels) {
199
199
  if (parentRels.length === 0)
200
- return [` // allowedReadJoins: [],`];
201
- const lines = [` // allowedReadJoins: [`];
200
+ return [` // readJoins: [],`];
201
+ const lines = [` // readJoins: [`];
202
202
  for (const rel of parentRels) {
203
203
  lines.push(` // buildRelation(${rel.parentSchemaName}, '${rel.parentField}', ${rel.childSchemaName}, '${rel.childField}'),`);
204
204
  }
@@ -253,8 +253,8 @@ export function generateSingleTableFile(schema, allSchemas) {
253
253
  const relatedSchemas = collectRelatedSchemas(schema.schemaName, parentRels, childRels);
254
254
  const lines = [];
255
255
  // Imports
256
- lines.push(`import {defineTable, exportTableInfo, Type} from 'fastify-auto-sqlapi';`);
257
- lines.push(`import type {ValidationError} from 'fastify-auto-sqlapi';`);
256
+ lines.push(`import {defineTable, Type} from 'fastify-auto-sqlapi';`);
257
+ lines.push(`import type {ValidatorResult} from 'fastify-auto-sqlapi';`);
258
258
  lines.push(`import {${schema.schemaName} as Schema} from '../schemas/${schema.schemaName}.js';`);
259
259
  // Commented imports for related schemas
260
260
  for (const relSchema of relatedSchemas) {
@@ -262,54 +262,48 @@ export function generateSingleTableFile(schema, allSchemas) {
262
262
  }
263
263
  lines.push(``);
264
264
  // Extra filters placeholder
265
- lines.push(`// const extraFiltersValidation = Type.Object({`);
266
- lines.push(`// q: Type.String(),`);
267
- lines.push(`// });`);
268
265
  // Table definition
269
266
  lines.push(``);
270
267
  lines.push(...viewNotice(schema, source));
271
268
  lines.push(`// Fields: ${schema.fields.join(', ')}`);
272
269
  lines.push(`export const ${tableVarName} = defineTable({`);
273
270
  lines.push(` primary: ${formatPrimary(pk)},`);
274
- lines.push(` ...exportTableInfo(Schema),`);
271
+ lines.push(` schema: Schema,`);
275
272
  // Commented example with extraFilters + extendedCondition
276
- lines.push(` // ...exportTableInfo(`);
277
- lines.push(` // Schema,`);
278
- lines.push(` // extraFiltersValidation,`);
279
- lines.push(` // (condition, filters) => {`);
280
- lines.push(` // // Prefix columns with the table name: the query may carry joins, and a`);
281
- lines.push(` // // bare column shared with a joined table would be ambiguous.`);
282
- lines.push(` // if (filters.q) condition.isILike(\`\${Schema.tableName}.\${Schema.col('${schema.fields.includes('name') ? 'name' : schema.fields[0]}')}\`, \`%\${filters.q}%\`);`);
283
- lines.push(` // }`);
284
- lines.push(` // ),`);
273
+ lines.push(` // extraFilters: { q: Type.String() },`);
274
+ lines.push(` // extendedCondition: (condition, filters) => {`);
275
+ lines.push(` // // Prefix columns with the table name: the query may carry joins, and a`);
276
+ lines.push(` // // bare column shared with a joined table would be ambiguous.`);
277
+ lines.push(` // if (filters.q) condition.isILike(\`\${Schema.tableName}.\${Schema.col('${schema.fields.includes('name') ? 'name' : schema.fields[0]}')}\`, \`%\${filters.q}%\`);`);
278
+ lines.push(` // },`);
285
279
  lines.push(` defaultOrder: '${defaultOrderField(schema, pk, source)}',`);
286
280
  lines.push(...viewOperationsLine(schema, source));
287
281
  // A view is never inserted into by the auto routes as generated, so the creation whitelist
288
282
  // would be a line about an operation that is not exposed.
289
283
  if (!schema.isView) {
290
284
  if (autoIncrement) {
291
- lines.push(` excludeFromCreation: ['${pkFirst(pk)}'],`);
285
+ lines.push(` insertExclude: ['${pkFirst(pk)}'],`);
292
286
  }
293
287
  else {
294
- lines.push(` // excludeFromCreation: [],`);
288
+ lines.push(` // insertExclude: [],`);
295
289
  }
296
290
  }
297
291
  // Hide columns from every read (writes still accept them, e.g. a password hash)
298
292
  lines.push(` // readExclude: [],`);
299
293
  lines.push(...writeExcludeLines(schema));
300
- lines.push(...allowedReadJoinsLines(parentRels));
294
+ lines.push(...readJoinsLines(parentRels));
301
295
  const upsertPk = pkFields(pk).map((p) => `'${p}'`).join(', ');
302
- lines.push(` // upsertMap: buildUpsertRules(buildUpsertRule(Schema, [${upsertPk}])),`);
296
+ lines.push(` // upsertKey: [${upsertPk}],`);
303
297
  lines.push(schemaOverridesLine(schema, pk));
304
298
  // validate: use first non-PK field for example
305
299
  const exampleField = schema.fields.find(f => !pkFields(pk).includes(f)) || schema.fields[0];
306
- lines.push(` validate: async (db, req, main, secondaries) => {`);
307
- lines.push(` const errors: ValidationError[] = [];`);
308
- lines.push(` // if (!main.${exampleField}) errors.push(['${exampleField}', 'required']);`);
300
+ lines.push(` validate: async ({ db, req, main, upsert, replace }) => {`);
301
+ lines.push(` const errors: ValidatorResult = [];`);
302
+ lines.push(` // if (!main.${exampleField}) errors.push({ path: 'main.${exampleField}', code: 'required' });`);
309
303
  lines.push(` return errors;`);
310
304
  lines.push(` },`);
311
- lines.push(` // beforeInsert: async (db, req, record) => {},`);
312
- lines.push(` // beforeUpdate: async (db, req, fields) => {},`);
305
+ lines.push(` // beforeInsert: async ({ db, req, record }) => {},`);
306
+ lines.push(` // beforeUpdate: async ({ db, req, record }) => {},`);
313
307
  lines.push(tenantScopeLine(childRels));
314
308
  lines.push(`});`);
315
309
  lines.push(``);
@@ -334,60 +328,3 @@ export function generateDbTablesIndex(schemas) {
334
328
  lines.push(``);
335
329
  return lines.join('\n');
336
330
  }
337
- // ─── Code Generation (legacy) ───────────────────────────────
338
- /** One `defineTable({...})` block for the legacy single-file generator. */
339
- function legacyTableBlock(schema, parentRels, childRels) {
340
- const { pk, autoIncrement, source } = detectPrimaryKey(schema);
341
- const tableVarName = 'Table' + schema.schemaName.replace(/^Schema/, '');
342
- const upsertPk = pkFields(pk).map((p) => `'${p}'`).join(', ');
343
- const exampleField = schema.fields.find((f) => !pkFields(pk).includes(f)) || schema.fields[0];
344
- const lines = [
345
- ``,
346
- `// ─── ${schema.tableName} ──────────────────────────────`,
347
- ...viewNotice(schema, source),
348
- `// Fields: ${schema.fields.join(', ')}`,
349
- `const ${tableVarName} = defineTable({`,
350
- ` primary: ${formatPrimary(pk)},`,
351
- ` ...exportTableInfo(${schema.schemaName}),`,
352
- ` defaultOrder: '${defaultOrderField(schema, pk, source)}',`,
353
- ...viewOperationsLine(schema, source),
354
- ];
355
- if (!schema.isView) {
356
- lines.push(autoIncrement
357
- ? ` excludeFromCreation: ['${pkFirst(pk)}'],`
358
- : ` // excludeFromCreation: [],`);
359
- }
360
- lines.push(...allowedReadJoinsLines(parentRels));
361
- lines.push(` // upsertMap: buildUpsertRules(buildUpsertRule(${schema.schemaName}, [${upsertPk}])),`, ` // schemaOverrides: {},`, ` validate: async (db, req, main, secondaries) => {`, ` const errors: ValidationError[] = [];`, ` // if (!main.${exampleField}) errors.push(['${exampleField}', 'required']);`, ` return errors;`, ` },`, ` // beforeInsert: async (db, req, record) => {},`, ` // beforeUpdate: async (db, req, fields) => {},`, tenantScopeLine(childRels), `});`);
362
- return lines;
363
- }
364
- /** Legacy single-file DbTables generator.
365
- * @testonly Exported only so unit tests can exercise it directly.
366
- */
367
- export function generateTablesFile(schemas) {
368
- const { byParent, byChild } = indexRelations(detectRelations(schemas));
369
- const lines = [];
370
- // Imports
371
- lines.push(`import {defineTable, exportTableInfo, Type} from 'fastify-auto-sqlapi';`);
372
- lines.push(`import type { DbTables, ValidationError } from 'fastify-auto-sqlapi';`);
373
- lines.push(``);
374
- // Schema imports
375
- for (const schema of schemas) {
376
- lines.push(`import {${schema.schemaName}} from './${schema.schemaName}.js';`);
377
- }
378
- // Table definitions
379
- for (const schema of schemas) {
380
- lines.push(...legacyTableBlock(schema, byParent.get(schema.schemaName) ?? [], byChild.get(schema.schemaName) ?? []));
381
- }
382
- // DbTables export
383
- lines.push(``);
384
- lines.push(`// ─── DbTables ──────────────────────────────────────`);
385
- lines.push(`export const dbTables: DbTables = {`);
386
- for (const schema of schemas) {
387
- const tableVarName = 'Table' + schema.schemaName.replace(/^Schema/, '');
388
- lines.push(` ${schema.tableName}: ${tableVarName},`);
389
- }
390
- lines.push(`};`);
391
- lines.push(``);
392
- return lines.join('\n');
393
- }
package/dist/lib/db.d.ts CHANGED
@@ -1,15 +1,22 @@
1
- import { Expression } from 'node-condition-builder';
2
- import type { ConditionBuilder } from 'node-condition-builder';
3
- import type { Queryable, SqlResult, DbRecord, SelectOptions } from '../types.js';
1
+ import { Expression, ConditionBuilder } from 'node-condition-builder';
2
+ import type { ConditionValue } from 'node-condition-builder';
3
+ import type { Queryable, SqlResult, DbRecord, SelectOptions, WrittenRow } from '../types/db.js';
4
4
  import type { SqlDialect } from './dialect.js';
5
- /** @deprecated Use db.qi() instead */
6
- export declare const escapeIdent: (f: string) => string;
5
+ /** The options of {@link QueryClient.bulkUpsert}. */
6
+ export interface BulkUpsertOptions {
7
+ chunkSize?: number;
8
+ immutableCols?: string[];
9
+ }
7
10
  export declare class QueryClient {
8
11
  #private;
9
12
  private client;
10
13
  private dialect;
11
14
  private debug;
12
- constructor(client: Queryable, dialect?: SqlDialect);
15
+ /** True on the client `withTransaction` hands its callback: it wraps the transaction's connection. */
16
+ private readonly inTransaction;
17
+ constructor(client: Queryable, dialect?: SqlDialect, inTransaction?: boolean);
18
+ /** Whether `withTransaction` can run: the Queryable has `connect()`, or this client already is a transaction. */
19
+ get supportsTransactions(): boolean;
13
20
  get qi(): (id: string) => string;
14
21
  get ph(): (i: number) => string;
15
22
  get dialectName(): string;
@@ -25,27 +32,45 @@ export declare class QueryClient {
25
32
  query<T = Record<string, unknown>>(text: string, values?: unknown[]): Promise<SqlResult<T>>;
26
33
  /**
27
34
  * Run `fn` inside a DB transaction on a dedicated connection (BEGIN/COMMIT, with
28
- * ROLLBACK + rethrow on error). Requires the underlying Queryable to expose
29
- * `connect()`; when it does not (legacy custom adapters), `fn` runs directly on
30
- * this client without transactional guarantees.
35
+ * ROLLBACK + rethrow on error). Requires the underlying Queryable to expose `connect()`.
36
+ *
37
+ * Without it the call fails, and nothing runs: a write that asked for atomicity — a main
38
+ * row with its secondaries, deletions and after-hooks — must not be executed as separate
39
+ * autocommitted statements because the adapter cannot do better: a custom adapter without
40
+ * `connect()` would otherwise lose the guarantee in silence (ADR 0023).
31
41
  *
32
- * Nested calls join the outer transaction: the tx QueryClient wraps a dedicated
33
- * connection that has no `connect()`, so an inner `withTransaction` is a no-op
34
- * wrapper around the same connection.
42
+ * Nested calls join the outer transaction: the tx QueryClient wraps the dedicated
43
+ * connection, which has no `connect()` either, so an inner `withTransaction` runs `fn` on
44
+ * the same connection. That is the one case where a missing `connect()` is not an error.
35
45
  */
36
46
  withTransaction<T>(fn: (tx: QueryClient) => Promise<T>): Promise<T>;
37
47
  insert(table: string, record: DbRecord, pkCol: string | string[]): Promise<Record<string, unknown>>;
38
- insertOrUpdate(table: string, record: DbRecord, conflictKeys: string[], pkCol: string | string[]): Promise<Record<string, unknown>>;
48
+ /**
49
+ * Insert `record`, or update the row its `conflictKeys` already name: `{ pk, action }`, the
50
+ * row's primary key and whether it was inserted or updated. The conflict keys are never in
51
+ * the update set. They must be a unique key the database enforces (ADR 0021).
52
+ */
53
+ upsert(table: string, record: DbRecord, conflictKeys: string[], pkCol: string | string[]): Promise<WrittenRow>;
39
54
  bulkInsert(table: string, records: DbRecord[], pkCol: string | string[], chunkSize?: number): Promise<Record<string, unknown>[]>;
40
55
  /**
41
- * `immutableCols` are written when the row is inserted but left untouched when the statement
42
- * lands on an existing row — like the conflict keys, which are never in the update set either.
43
- * Used by tenant isolation to keep an upsert from re-assigning a row's owner.
56
+ * `upsert` for every record, in chunks: `{ pk, action }` per record, in input order. Each
57
+ * record writes only its own fields (ADR 0003).
58
+ *
59
+ * - `chunkSize`: records per statement (default {@link DEFAULT_CHUNK_SIZE}).
60
+ * - `immutableCols`: written when the row is inserted, left untouched when the statement
61
+ * lands on an existing row — like the conflict keys. Tenant isolation uses it to keep an
62
+ * upsert from re-assigning a row's owner.
44
63
  */
45
- bulkInsertOrUpdate(table: string, records: DbRecord[], conflictKeys: string[], pkCol: string | string[], chunkSize?: number, immutableCols?: string[]): Promise<Record<string, unknown>[]>;
64
+ bulkUpsert(table: string, records: DbRecord[], conflictKeys: string[], pkCol: string | string[], options?: BulkUpsertOptions): Promise<WrittenRow[]>;
46
65
  update(table: string, record: DbRecord, where: DbRecord, extraCondition?: ConditionBuilder): Promise<number>;
47
66
  delete(table: string, where: DbRecord, extraCondition?: ConditionBuilder): Promise<number>;
48
67
  select<T = Record<string, unknown>>({ tableName, columns, where, values, limit, orderBy, joins, distinct, }: SelectOptions): Promise<T[]>;
49
68
  }
69
+ /**
70
+ * The predicate matching a set of rows by their keys: `col IN (…)` for a single column, and for
71
+ * several an OR of one {@link buildKeyEquals} group per key, so each key binds all of its columns
72
+ * together — never one column alone, which would reach every row sharing that value.
73
+ */
74
+ export declare function buildKeyMatch(db: QueryClient, cols: string[], keys: ConditionValue[][]): ConditionBuilder;
50
75
  export declare function createQueryClient(pool: Queryable, dialectName?: string): QueryClient;
51
76
  //# sourceMappingURL=db.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"db.d.ts","sourceRoot":"","sources":["../../src/lib/db.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACjF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAgB/C,sCAAsC;AACtC,eAAO,MAAM,WAAW,GAAI,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AC,EAAE,gBAAgB,GAChC,OAAO,CAAC,MAAM,CAAC;IAoBZ,MAAM,CACV,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,QAAQ,EACf,cAAc,CAAC,EAAE,gBAAgB,GAChC,OAAO,CAAC,MAAM,CAAC;IAkBZ,MAAM,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EACxC,SAAS,EACT,OAAa,EACb,KAAK,EACL,MAAM,EACN,KAAY,EACZ,OAAY,EACZ,KAAU,EACV,QAAgB,GACjB,EAAE,aAAa,GAAG,OAAO,CAAC,CAAC,EAAE,CAAC;CAchC;AAYD;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,cAAc,EAAE,EAAE,GAAG,gBAAgB,CAOzG;AAED,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,SAAS,EACf,WAAW,CAAC,EAAE,MAAM,GACnB,WAAW,CAGb"}
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"}