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
@@ -1,14 +1,15 @@
1
+ import { buildTableFilters, PLAIN_ORDER_TERM } from '../../table-helpers.js';
1
2
  import { QueryParams } from '../query-params.js';
2
3
  import { buildTenantCondition, buildTenantJoin } from '../../tenant.js';
3
- import { assertFiltersReadable, assertKnownFilterKeys, readableSelectColumns, ownField, } from '../../read-access.js';
4
+ import { assertFiltersReadable, assertKnownFilterKeys, readableSelectColumns, hasOwnField, ownField, } from '../../read-access.js';
4
5
  import { MAX_CONDITIONS, MAX_ORDER_BY_PARTS } from '../../condition-methods.js';
5
- import { primaryAsString } from '../../../types.js';
6
- import { err400, resolveFieldRef, evaluateComputedField, refValues, renderRef, mapRowsToCamelCase, } from './fields.js';
6
+ import { primaryAsString, COMPUTE_FNS } from '../../../types.js';
7
+ import { err400, resolveFieldRef, evaluateComputedField, refValues, renderRef, mapRowsToCamelCase, buildMainSelectColumns, rejectRetiredSearchKeys, } from './fields.js';
7
8
  import { assertJoinFilterKeys, requireJoin } from './joins.js';
8
9
  import { runAfterRead } from '../read-hooks.js';
9
10
  import { collectOrderByLeftAliases, validateOrderBy, convertConfiguredOrder } from './order-by.js';
10
11
  import { applyConditions, applyComputedFilters } from './conditions.js';
11
- import { appendAggConditions } from './aggregations.js';
12
+ import { appendAggConditions, AGG_FN, aggExpr } from './aggregations.js';
12
13
  import { buildLeftJoinOnClauses, buildLeftJoinFilters, executeJoinMultiple, executeJoinLeft, executeJoinGroup, buildJoinMustExistClauses, } from './join-families.js';
13
14
  /**
14
15
  * Guard the request shapes that reach SQL as text rather than as bound values.
@@ -26,44 +27,48 @@ function assertRequestWithinLimits(params) {
26
27
  for (const key of ['page', 'itemsPerPage']) {
27
28
  const value = paginator[key];
28
29
  if (!Number.isInteger(value) || value < 1) {
29
- err400(`Invalid paginator: '${key}' must be an integer >= 1`);
30
+ err400('invalid_paginator', `paginator.${key}`, `Invalid paginator: '${key}' must be an integer >= 1`);
30
31
  }
31
32
  }
32
33
  }
33
34
  if (conditions && conditions.length > MAX_CONDITIONS) {
34
- err400(`Too many conditions: ${conditions.length} (max ${MAX_CONDITIONS})`);
35
+ err400('limit_exceeded', 'conditions', `Too many conditions: ${conditions.length} (max ${MAX_CONDITIONS})`);
35
36
  }
36
37
  if (orderBy && orderBy.split(',').length > MAX_ORDER_BY_PARTS) {
37
- err400(`Too many orderBy parts: max ${MAX_ORDER_BY_PARTS}`);
38
+ err400('limit_exceeded', 'orderBy', `Too many orderBy parts: max ${MAX_ORDER_BY_PARTS}`);
38
39
  }
39
40
  }
40
41
  // ─── Main query execution ───────────────────────────────────
41
- async function executeMainQuery(db, tableConf, where, values, orderBy, paginator, extraJoins = [], selectComputed, maxRows) {
42
- const tableName = tableConf.Schema.tableName;
43
- // Request orderBy arrives already validated and mapped by validateOrderBy;
44
- // configured fallbacks (defaultOrder / primary key) are converted leniently here.
42
+ async function executeMainQuery(db, tableConf, where, values, orderBy, paginator, extraJoins = [], projection, maxRows) {
43
+ const tableName = tableConf.schema.tableName;
44
+ // Request orderBy arrives already validated and mapped by validateOrderBy; the configured
45
+ // fallbacks (defaultOrder / primary key) are converted here, with the same 1-part grammar.
45
46
  const order = orderBy || convertConfiguredOrder(tableConf.defaultOrder || primaryAsString(tableConf.primary), tableConf, db);
46
47
  // With a paginator, the page size governs the LIMIT. Without one, apply `maxRows` (if set) so an
47
48
  // unbounded search cannot dump the whole table; a plain integer is a safe, non-injectable LIMIT.
48
49
  const limit = paginator
49
50
  ? `${paginator.itemsPerPage} OFFSET ${(paginator.page - 1) * paginator.itemsPerPage}`
50
51
  : (maxRows != null ? String(maxRows) : null);
51
- // Base projection: '*' unless the table hides fields via readExclude.
52
- const readableColumns = readableSelectColumns(tableConf, tableConf.Schema, db);
53
- // Optional computed projections — bound values, if any, are NOT yet supported
52
+ // Base projection: the request's `select` plus what the query needs; otherwise the main
53
+ // table's own columns, qualified ("hour".* or the readable list). Never a bare `*`: the
54
+ // statement may carry a LEFT JOIN (filtered/ordered joinLeft) or the tenant's INNER JOIN,
55
+ // and a bare `*` would hand the joined table's columns to the row.
56
+ const readableColumns = projection
57
+ ? buildMainSelectColumns(projection.select, projection.required, tableConf, db)
58
+ : readableSelectColumns(tableConf, tableConf.schema, db);
59
+ // Computed fields listed in `select` — bound values, if any, are NOT yet supported
54
60
  // here (would require placeholder-aware composition with WHERE values).
55
- let columns = readableColumns;
56
- if (selectComputed?.length) {
57
- const projections = [readableColumns ?? '*'];
58
- for (const name of selectComputed) {
59
- const fn = ownField(tableConf.computedFields, name);
60
- if (!fn)
61
- err400(`Unknown computed field in selectComputed: '${name}'`);
62
- const out = evaluateComputedField(name, fn, tableConf.Schema, db, undefined, `Computed field '${name}' with bound values cannot be used in selectComputed`);
63
- projections.push(`${out.value} AS ${db.qi(name)}`);
64
- }
65
- columns = projections.join(', ');
61
+ const projections = [readableColumns];
62
+ const computedNames = [];
63
+ for (const [i, name] of (projection?.select ?? []).entries()) {
64
+ const fn = ownField(tableConf.computedFields, name);
65
+ if (!fn || computedNames.includes(name))
66
+ continue;
67
+ const out = evaluateComputedField(name, fn, tableConf.schema, db, undefined, `Computed field '${name}' with bound values cannot be used in select`, false, `select.${i}`);
68
+ projections.push(`${out.value} AS ${db.qi(name)}`);
69
+ computedNames.push(name);
66
70
  }
71
+ const columns = projections.join(', ');
67
72
  const rows = await db.select({
68
73
  tableName,
69
74
  columns,
@@ -74,38 +79,74 @@ async function executeMainQuery(db, tableConf, where, values, orderBy, paginator
74
79
  distinct: tableConf.distinctResults,
75
80
  joins: extraJoins.length > 0 ? extraJoins : undefined,
76
81
  });
77
- return mapRowsToCamelCase(rows, tableConf.Schema, selectComputed);
82
+ return mapRowsToCamelCase(rows, tableConf.schema, computedNames);
83
+ }
84
+ /**
85
+ * The fields a `select` must carry even when the request leaves them out:
86
+ * - the primary key, which identifies each row;
87
+ * - the main-side key of every requested join family that runs a side query, which
88
+ * correlates the child or parent rows (`joinMustExist` is an EXISTS: nothing to project);
89
+ * - with `distinctResults`, the plain fields the result is ordered by — the database
90
+ * requires `SELECT DISTINCT` to list its ORDER BY expressions.
91
+ */
92
+ function requiredProjection(params) {
93
+ const { tableConf, joinMultiple, joinLeft, joinGroup, orderBy } = params;
94
+ const required = Array.isArray(tableConf.primary) ? [...tableConf.primary] : [tableConf.primary];
95
+ const families = [
96
+ [joinMultiple, 'joinMultiple', false],
97
+ [joinLeft, 'joinLeft', true],
98
+ [joinGroup, 'joinGroup', false],
99
+ ];
100
+ for (const [requests, family, unique] of families) {
101
+ for (const alias of Object.keys(requests ?? {})) {
102
+ const { mainField } = requireJoin(tableConf, alias, unique, `${family}.${alias}`);
103
+ required.push(...(Array.isArray(mainField) ? mainField : [mainField]));
104
+ }
105
+ }
106
+ if (tableConf.distinctResults) {
107
+ const order = orderBy || tableConf.defaultOrder || primaryAsString(tableConf.primary);
108
+ for (const part of order.split(',')) {
109
+ const plain = PLAIN_ORDER_TERM.exec(part.trim());
110
+ if (plain && hasOwnField(tableConf.schema.fields, plain[1]))
111
+ required.push(plain[1]);
112
+ }
113
+ }
114
+ return required;
78
115
  }
79
- async function buildPagination(db, tableConf, where, values, paginator, extraJoins = [], computeMin, computeMax, computeSum, computeAvg) {
80
- const tableName = tableConf.Schema.tableName;
116
+ async function buildPagination(db, tableConf, where, values, paginator, extraJoins = []) {
117
+ const tableName = tableConf.schema.tableName;
81
118
  const joinClause = extraJoins.length > 0 ? ' ' + extraJoins.join(' ') : '';
82
119
  const countResult = await db.query(`SELECT COUNT(*) as total FROM ${db.qi(tableName)}${joinClause} WHERE ${where}`, values);
83
120
  const total = parseInt(countResult.rows[0].total, 10);
121
+ return { total, pages: Math.ceil(total / paginator.itemsPerPage), paginator };
122
+ }
123
+ /**
124
+ * `result.computed`: the requested aggregates over every row the WHERE matches, with no LIMIT,
125
+ * so the value does not depend on the page — nor on whether the search is paginated at all.
126
+ *
127
+ * One statement per (function, field), in a fixed order; errors are reported at the body path
128
+ * `compute.<fn>.<i>`. The functions are joinGroup's, rendered by the same `aggExpr`.
129
+ */
130
+ async function buildComputed(db, tableConf, where, values, extraJoins, compute) {
131
+ const tableName = tableConf.schema.tableName;
132
+ const joinClause = extraJoins.length > 0 ? ' ' + extraJoins.join(' ') : '';
84
133
  const computed = {};
85
- const computations = [
86
- { key: 'min', field: computeMin, fn: 'MIN' },
87
- { key: 'max', field: computeMax, fn: 'MAX' },
88
- { key: 'sum', field: computeSum, fn: 'SUM' },
89
- { key: 'avg', field: computeAvg, fn: 'AVG' },
90
- ];
91
- for (const { key, field, fn } of computations) {
92
- if (field) {
93
- const ref = resolveFieldRef(field, tableConf.Schema, tableConf, db);
134
+ for (const fn of COMPUTE_FNS) {
135
+ for (const [i, field] of (compute[fn] ?? []).entries()) {
136
+ const at = `compute.${fn}.${i}`;
137
+ const ref = resolveFieldRef(field, tableConf.schema, tableConf, db, undefined, at);
94
138
  // The aggregate sits in the SELECT list, before the WHERE values: a computed that
95
139
  // binds parameters cannot be placed here.
96
140
  if (refValues(ref.expr).length > 0) {
97
- err400(`Computed field '${field}' with bound values cannot be used in compute${key.charAt(0).toUpperCase() + key.slice(1)}`);
141
+ err400('bound_values_not_allowed', at, `Computed field '${field}' with bound values cannot be used in compute.${fn}`);
98
142
  }
99
- const result = await db.query(`SELECT ${fn}(${renderRef(ref.expr, 1, db)}) as value FROM ${db.qi(tableName)}${joinClause} WHERE ${where}`, values);
100
- computed[key] = { [field]: result.rows[0].value };
143
+ const result = await db.query(`SELECT ${aggExpr(AGG_FN[fn], renderRef(ref.expr, 1, db))} as value FROM ${db.qi(tableName)}${joinClause} WHERE ${where}`, values);
144
+ const byField = computed[fn] ?? {};
145
+ byField[field] = result.rows[0].value;
146
+ computed[fn] = byField;
101
147
  }
102
148
  }
103
- return {
104
- total,
105
- pages: Math.ceil(total / paginator.itemsPerPage),
106
- ...(Object.keys(computed).length > 0 ? { computed } : {}),
107
- paginator,
108
- };
149
+ return Object.keys(computed).length > 0 ? computed : undefined;
109
150
  }
110
151
  // ─── searchEngine entrypoint ────────────────────────────────
111
152
  /**
@@ -120,20 +161,20 @@ function assertJoinRequestsAllowed(dbTables, params) {
120
161
  const { tableConf, joinMustExist, joinMultiple, joinGroup, joinLeft } = params;
121
162
  if (joinMustExist)
122
163
  for (const a of Object.keys(joinMustExist))
123
- requireJoin(tableConf, a, false);
164
+ requireJoin(tableConf, a, false, `joinMustExist.${a}`);
124
165
  if (joinMultiple)
125
166
  for (const a of Object.keys(joinMultiple))
126
- requireJoin(tableConf, a, false);
167
+ requireJoin(tableConf, a, false, `joinMultiple.${a}`);
127
168
  if (joinGroup)
128
169
  for (const a of Object.keys(joinGroup))
129
- requireJoin(tableConf, a, false);
170
+ requireJoin(tableConf, a, false, `joinGroup.${a}`);
130
171
  if (joinLeft)
131
172
  for (const a of Object.keys(joinLeft))
132
- requireJoin(tableConf, a, true);
133
- assertJoinFilterKeys(dbTables, tableConf, joinMustExist, true);
134
- assertJoinFilterKeys(dbTables, tableConf, joinMultiple, true);
135
- assertJoinFilterKeys(dbTables, tableConf, joinGroup, true);
136
- assertJoinFilterKeys(dbTables, tableConf, joinLeft, false);
173
+ requireJoin(tableConf, a, true, `joinLeft.${a}`);
174
+ assertJoinFilterKeys(dbTables, tableConf, joinMustExist, true, 'joinMustExist');
175
+ assertJoinFilterKeys(dbTables, tableConf, joinMultiple, true, 'joinMultiple');
176
+ assertJoinFilterKeys(dbTables, tableConf, joinGroup, true, 'joinGroup');
177
+ assertJoinFilterKeys(dbTables, tableConf, joinLeft, false, 'joinLeft');
137
178
  }
138
179
  /**
139
180
  * The main table's WHERE builder, plus any JOIN the tenant scope needs.
@@ -145,20 +186,20 @@ function assertJoinRequestsAllowed(dbTables, params) {
145
186
  function buildMainCondition(params) {
146
187
  const { db, tableConf, filters, conditions, tenant } = params;
147
188
  assertFiltersReadable(filters, tableConf);
148
- assertKnownFilterKeys(filters, tableConf.Schema, tableConf);
149
- const condition = tableConf.filters(filters || {}, db.cbDialect);
189
+ assertKnownFilterKeys(filters, tableConf.schema, tableConf);
190
+ const condition = buildTableFilters(tableConf, filters || {}, db.cbDialect);
150
191
  if (filters && tableConf.computedFields) {
151
192
  applyComputedFilters(condition, filters, tableConf, db);
152
193
  }
153
194
  if (conditions?.length) {
154
- applyConditions(condition, conditions, tableConf.Schema, tableConf, db);
195
+ applyConditions(condition, conditions, tableConf.schema, tableConf, db);
155
196
  }
156
197
  const tenantJoins = [];
157
198
  if (tenant?.scope) {
158
199
  const scope = tenant.scope;
159
- condition.append(buildTenantCondition(db, scope, tenant.ids, tableConf.Schema.tableName));
200
+ condition.append(buildTenantCondition(db, scope, tenant.ids, tableConf.schema.tableName));
160
201
  if ('through' in scope) {
161
- tenantJoins.push(buildTenantJoin(db, scope, tableConf.Schema.tableName));
202
+ tenantJoins.push(buildTenantJoin(db, scope, tableConf.schema.tableName));
162
203
  }
163
204
  }
164
205
  return { condition, tenantJoins };
@@ -200,7 +241,8 @@ async function attachJoinResults(result, dbTables, params, main) {
200
241
  }
201
242
  }
202
243
  export async function searchEngine(dbTables, params) {
203
- const { db, tableConf, conditions, joinMustExist, joinGroup, joinLeft, orderBy, paginator, computeMin, computeMax, computeSum, computeAvg, tenant, } = params;
244
+ const { db, tableConf, conditions, joinMustExist, joinGroup, joinLeft, orderBy, paginator, tenant, } = params;
245
+ rejectRetiredSearchKeys(params);
204
246
  assertRequestWithinLimits(params);
205
247
  assertJoinRequestsAllowed(dbTables, params);
206
248
  const { condition, tenantJoins } = buildMainCondition(params);
@@ -242,11 +284,15 @@ export async function searchEngine(dbTables, params) {
242
284
  safeOrderBy = bound.emit((startIndex) => validateOrderBy(orderBy, tableConf, db, dbTables, joinGroup, startIndex, tenant)).sql;
243
285
  }
244
286
  const mainValues = bound.snapshot();
245
- const main = await executeMainQuery(db, tableConf, where, mainValues, safeOrderBy, paginator, extraJoinClauses, params.selectComputed, params.maxRows);
287
+ const projection = params.select
288
+ ? { select: params.select, required: requiredProjection(params) }
289
+ : undefined;
290
+ const main = await executeMainQuery(db, tableConf, where, mainValues, safeOrderBy, paginator, extraJoinClauses, projection, params.maxRows);
246
291
  let pagination;
247
292
  if (paginator) {
248
- pagination = await buildPagination(db, tableConf, where, whereAndJoinValues, paginator, extraJoinClauses, computeMin, computeMax, computeSum, computeAvg);
293
+ pagination = await buildPagination(db, tableConf, where, whereAndJoinValues, paginator, extraJoinClauses);
249
294
  }
295
+ const computed = await buildComputed(db, tableConf, where, whereAndJoinValues, extraJoinClauses, params.compute ?? {});
250
296
  const result = { main };
251
297
  await attachJoinResults(result, dbTables, params, main);
252
298
  // After the joins, not before: they correlate to the main rows by the values the DB
@@ -254,6 +300,9 @@ export async function searchEngine(dbTables, params) {
254
300
  // have them look for a value no child row carries. `main` is the same array either way,
255
301
  // so the response still carries the hook's mutations.
256
302
  await runAfterRead(db, params.request, main, tableConf, 'search');
303
+ if (computed) {
304
+ result.computed = computed;
305
+ }
257
306
  if (pagination) {
258
307
  result.pagination = pagination;
259
308
  }
@@ -1,6 +1,24 @@
1
1
  import type { ApiRequest } from '../../types/request.js';
2
2
  import type { QueryClient } from '../db.js';
3
- import type { ITable, BulkValidatorItem } from '../../types.js';
4
- export declare function runValidation(db: QueryClient, request: ApiRequest, tableConf: ITable, main: Record<string, unknown>, secondaries?: Record<string, Record<string, unknown>[]>): Promise<void>;
5
- export declare function runBulkValidation(db: QueryClient, request: ApiRequest, tableConf: ITable, items: BulkValidatorItem[]): Promise<void>;
3
+ import type { TableConfig, DbTables, ValidationField, BulkValidatorItem, WriteJoinSections } from '../../types.js';
4
+ export declare function runValidation(db: QueryClient, request: ApiRequest | undefined, tableConf: TableConfig, main: Record<string, unknown>, children?: Pick<WriteJoinSections, 'upsert' | 'replace'>): Promise<void>;
5
+ /** Where a child validation runs: the host table's write, and the bulk item it belongs to. */
6
+ interface ChildValidationCtx {
7
+ db: QueryClient;
8
+ request: ApiRequest | undefined;
9
+ tableConf: TableConfig;
10
+ dbTables: DbTables;
11
+ }
12
+ /**
13
+ * Run each child table's `validate` on the child rows a write sends under `upsert` and
14
+ * `replace` (ADR 0030), after the host's own validation and before any SQL. The child sees its
15
+ * row as `main` — with the FK to the host's main row when `hostMain` carries the key it is read
16
+ * from — and `parent: { alias, main: hostMain }`. A child declaring `validateBulk` gets the rows
17
+ * of one alias at once instead. Every child row is checked, and all their errors answer one
18
+ * 400 at the request's paths: `<at>.<section>.<alias>.<i>.<field>`.
19
+ */
20
+ export declare function runChildValidation(ctx: ChildValidationCtx, hostMain: Record<string, unknown>, sections: Pick<WriteJoinSections, 'upsert' | 'replace'>, at?: string): Promise<void>;
21
+ export declare function runBulkValidation(db: QueryClient, request: ApiRequest | undefined, tableConf: TableConfig, items: BulkValidatorItem[]): Promise<void>;
22
+ export declare function throwValidationError(fields: ValidationField[]): never;
23
+ export {};
6
24
  //# sourceMappingURL=validate.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate.d.ts","sourceRoot":"","sources":["../../../src/lib/engine/validate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,KAAK,EAAE,MAAM,EAAmB,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAgBjF,wBAAsB,aAAa,CACjC,EAAE,EAAE,WAAW,EACf,OAAO,EAAE,UAAU,EACnB,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,GACtD,OAAO,CAAC,IAAI,CAAC,CAOf;AAED,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,WAAW,EACf,OAAO,EAAE,UAAU,EACnB,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,iBAAiB,EAAE,GACzB,OAAO,CAAC,IAAI,CAAC,CAOf"}
1
+ {"version":3,"file":"validate.d.ts","sourceRoot":"","sources":["../../../src/lib/engine/validate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAE5C,OAAO,KAAK,EACV,WAAW,EACX,QAAQ,EAER,eAAe,EAEf,iBAAiB,EACjB,iBAAiB,EAClB,MAAM,gBAAgB,CAAC;AA4BxB,wBAAsB,aAAa,CACjC,EAAE,EAAE,WAAW,EACf,OAAO,EAAE,UAAU,GAAG,SAAS,EAC/B,SAAS,EAAE,WAAW,EACtB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,QAAQ,GAAE,IAAI,CAAC,iBAAiB,EAAE,QAAQ,GAAG,SAAS,CAAM,GAC3D,OAAO,CAAC,IAAI,CAAC,CAMf;AAED,8FAA8F;AAC9F,UAAU,kBAAkB;IAC1B,EAAE,EAAE,WAAW,CAAC;IAChB,OAAO,EAAE,UAAU,GAAG,SAAS,CAAC;IAChC,SAAS,EAAE,WAAW,CAAC;IACvB,QAAQ,EAAE,QAAQ,CAAC;CACpB;AAED;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,kBAAkB,EACvB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACjC,QAAQ,EAAE,IAAI,CAAC,iBAAiB,EAAE,QAAQ,GAAG,SAAS,CAAC,EACvD,EAAE,SAAK,GACN,OAAO,CAAC,IAAI,CAAC,CAef;AAoDD,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,WAAW,EACf,OAAO,EAAE,UAAU,GAAG,SAAS,EAC/B,SAAS,EAAE,WAAW,EACtB,KAAK,EAAE,iBAAiB,EAAE,GACzB,OAAO,CAAC,IAAI,CAAC,CAKf;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,eAAe,EAAE,GAAG,KAAK,CAQrE"}
@@ -1,27 +1,117 @@
1
- function toResponseFields(errors) {
2
- return errors.map(([path, code, message]) => ({
3
- path,
4
- code,
5
- message: message ?? code,
6
- }));
7
- }
8
- export async function runValidation(db, request, tableConf, main, secondaries) {
1
+ import { resolveJoinTableConf } from '../table-helpers.js';
2
+ /**
3
+ * The fields of the 400 for what a `validate`/`validateBulk` hook returned: the `{ path, code }`
4
+ * objects as they are, with no `message` — a hook writes no prose, the client translates the
5
+ * code. Anything else is the hook's bug, not the client's — a plain Error (500), never a 400 —
6
+ * and the pre-1.0 tuples are named, so they are not read positionally into the wrong fields.
7
+ */
8
+ function toResponseFields(hook, errors) {
9
+ if (!Array.isArray(errors)) {
10
+ throw new Error(`${hook} must return an array of { path, code } objects (empty: valid)`);
11
+ }
12
+ return errors.map((entry, i) => {
13
+ const at = `${hook} returned [${i}]`;
14
+ if (Array.isArray(entry)) {
15
+ throw new Error(`${at} as a tuple, the pre-1.0 shape: return { path, code } objects`);
16
+ }
17
+ if (!entry || typeof entry !== 'object')
18
+ throw new Error(`${at}: expected { path, code }`);
19
+ const { path, code } = entry;
20
+ if (Object.hasOwn(entry, 'message')) {
21
+ throw new Error(`${at} with a 'message': return { path, code } only, the client translates the code`);
22
+ }
23
+ if (typeof path !== 'string')
24
+ throw new Error(`${at}: path must be a string ('' when not attributable)`);
25
+ if (typeof code !== 'string' || !code)
26
+ throw new Error(`${at}: code must be a non-empty string`);
27
+ return { path, code };
28
+ });
29
+ }
30
+ export async function runValidation(db, request, tableConf, main, children = {}) {
9
31
  if (!tableConf.validate)
10
32
  return;
11
- const errors = await tableConf.validate(db, request, main, secondaries);
12
- if (errors.length > 0) {
13
- throwValidationError(toResponseFields(errors));
33
+ const ctx = { db, req: request, main, upsert: children.upsert, replace: children.replace };
34
+ const fields = toResponseFields('validate', await tableConf.validate(ctx));
35
+ if (fields.length > 0)
36
+ throwValidationError(fields);
37
+ }
38
+ /**
39
+ * Run each child table's `validate` on the child rows a write sends under `upsert` and
40
+ * `replace` (ADR 0030), after the host's own validation and before any SQL. The child sees its
41
+ * row as `main` — with the FK to the host's main row when `hostMain` carries the key it is read
42
+ * from — and `parent: { alias, main: hostMain }`. A child declaring `validateBulk` gets the rows
43
+ * of one alias at once instead. Every child row is checked, and all their errors answer one
44
+ * 400 at the request's paths: `<at>.<section>.<alias>.<i>.<field>`.
45
+ */
46
+ export async function runChildValidation(ctx, hostMain, sections, at = '') {
47
+ const fields = [];
48
+ for (const section of ['upsert', 'replace']) {
49
+ for (const [alias, rows] of Object.entries(sections[section] ?? {})) {
50
+ const join = ctx.tableConf.writeJoins?.find((j) => j.alias === alias);
51
+ const child = join && resolveJoinTableConf(ctx.dbTables, join);
52
+ if (!join || !child || !rows?.length || (!child.validate && !child.validateBulk))
53
+ continue;
54
+ const prefix = [at, section, alias].filter(Boolean).join('.');
55
+ const parent = { alias, main: hostMain };
56
+ const mains = rows.map((row) => withParentKey(row, join, hostMain));
57
+ fields.push(...await validateChildRows(ctx, child, mains, parent, prefix));
58
+ }
59
+ }
60
+ if (fields.length > 0)
61
+ throwValidationError(fields);
62
+ }
63
+ /** The child row as sent, with the FK to the host's main row when the host's key is known. */
64
+ function withParentKey(row, join, hostMain) {
65
+ const mainField = Array.isArray(join.mainField) ? join.mainField[0] : join.mainField;
66
+ const key = hostMain[mainField];
67
+ return key == null ? { ...row } : { ...row, [join.joinField]: key };
68
+ }
69
+ /** One child table's verdict on the rows of one alias, its paths re-rooted at `prefix`. */
70
+ async function validateChildRows(ctx, child, mains, parent, prefix) {
71
+ const table = child.schema.tableName;
72
+ const { db, request: req } = ctx;
73
+ if (child.validateBulk) {
74
+ const hook = `${table}'s validateBulk`;
75
+ const items = mains.map((main) => ({ main }));
76
+ return toResponseFields(hook, await child.validateBulk({ db, req, items, parent }))
77
+ .map((f) => ({ ...f, path: rerootBulkPath(hook, f.path, prefix) }));
78
+ }
79
+ const fields = [];
80
+ for (const [i, main] of mains.entries()) {
81
+ const hook = `${table}'s validate`;
82
+ fields.push(...toResponseFields(hook, await child.validate({ db, req, main, parent }))
83
+ .map((f) => ({ ...f, path: rerootRowPath(hook, f.path, `${prefix}.${i}`) })));
14
84
  }
85
+ return fields;
86
+ }
87
+ /**
88
+ * A child row's path in its own grammar (`main.<field>`, `main`, `''`) as a path of the
89
+ * request (`<row>.<field>`, `<row>`). Anything else is the hook's bug: a 500 naming it.
90
+ */
91
+ function rerootRowPath(hook, path, row) {
92
+ if (path === '' || path === 'main')
93
+ return row;
94
+ if (path.startsWith('main.'))
95
+ return `${row}${path.slice('main'.length)}`;
96
+ throw new Error(`${hook}, run on a child row, returned path '${path}': expected main.<field> or ''`);
97
+ }
98
+ /** A child `validateBulk` path (`items.<j>.main.<field>`, `items.<j>`, `''`) as a path of the request. */
99
+ function rerootBulkPath(hook, path, alias) {
100
+ if (path === '')
101
+ return alias;
102
+ const m = /^items\.(\d+)(?:\.main(\..+)?)?$/.exec(path);
103
+ if (m)
104
+ return `${alias}.${m[1]}${m[2] ?? ''}`;
105
+ throw new Error(`${hook}, run on child rows, returned path '${path}': expected items.<i>.main.<field>, items.<i> or ''`);
15
106
  }
16
107
  export async function runBulkValidation(db, request, tableConf, items) {
17
108
  if (!tableConf.validateBulk)
18
109
  return;
19
- const errors = await tableConf.validateBulk(db, request, items);
20
- if (errors.length > 0) {
21
- throwValidationError(toResponseFields(errors));
22
- }
110
+ const fields = toResponseFields('validateBulk', await tableConf.validateBulk({ db, req: request, items }));
111
+ if (fields.length > 0)
112
+ throwValidationError(fields);
23
113
  }
24
- function throwValidationError(fields) {
114
+ export function throwValidationError(fields) {
25
115
  const error = new Error('Validation failed');
26
116
  error.statusCode = 400;
27
117
  error.validationErrors = fields;
@@ -1,6 +1,6 @@
1
1
  import type { ApiRequest } from '../../types/request.js';
2
- import type { QueryClient } from '../db.js';
3
- import type { ITable, DbTables, TenantContext, SchemaDefinition } from '../../types.js';
2
+ import { type QueryClient } from '../db.js';
3
+ import type { TableConfig, DbTables, TenantContext, SchemaDefinition, RowsByAlias, WriteJoinSections } from '../../types.js';
4
4
  /**
5
5
  * Every upserted record must carry its key (ADR 0021), checked on the record as it reaches the
6
6
  * database — after hooks, tenant injection and the FK auto-fill of secondaries:
@@ -13,32 +13,74 @@ import type { ITable, DbTables, TenantContext, SchemaDefinition } from '../../ty
13
13
  * Throws 400 before any SQL runs. Column names and record keys are DB column names.
14
14
  */
15
15
  export declare function assertUpsertKeys(schema: SchemaDefinition, conflictCols: string[], pkCols: string[], records: Record<string, unknown>[]): void;
16
- export declare function findSecondaryTableConf(dbTables: DbTables, joinTableName: string): ITable | undefined;
16
+ /**
17
+ * The fields of an upsert key the client may not set on insert (`insertExclude`). Such a key
18
+ * is kept on the rows that carry it — it names the row to update — but it may not name a new
19
+ * row: the client never picks a value `insertExclude` reserves to the server.
20
+ */
21
+ export declare function insertExcludedKeyFields(tableConf: TableConfig | undefined, upsertKey: readonly string[]): string[];
22
+ /**
23
+ * Every row carrying an upsert key that `insertExclude` reserves to the server must name an
24
+ * existing row: such a key addresses a row, it cannot create one (see
25
+ * `insertExcludedKeyFields`). One SELECT for the rows whose key the client sent (`sent`, the
26
+ * rows as the request carried them, camelCase); each one no row matches is a 400 `not_found`
27
+ * at `pathOf(i)`, before the upsert runs. Rows without the key are plain inserts and are not
28
+ * probed, nor is a key a `beforeInsert` assigned. `records` and `conflictCols` are DB column
29
+ * names.
30
+ */
31
+ export declare function assertExcludedKeysExist(db: QueryClient, schema: SchemaDefinition, conflictCols: string[], excludedKeyFields: string[], records: Record<string, unknown>[], sent: Record<string, unknown>[], pathOf: (i: number, field: string) => string): Promise<void>;
32
+ /** True when any of `sections` names at least one alias — an empty list included. */
33
+ export declare function hasAliases(...sections: (RowsByAlias | undefined)[]): boolean;
34
+ /**
35
+ * Refuse the pre-1.0 child-row keys of a write request: `secondaries` became `upsert` and
36
+ * `deletions` became `delete` (ADR 0029). A 400 `retired_key` at `<at>.<key>`, never ignored:
37
+ * dropped, the child rows would go unwritten or undeleted with the write answering success.
38
+ * `at` is the bulk item's index, empty for a single write.
39
+ */
40
+ export declare function rejectRetiredWriteKeys(input: object, at?: string): void;
41
+ /**
42
+ * Check the aliases of a write request's `upsert`, `delete` and `replace` sections, before
43
+ * anything is validated or written; a 400 at `<at>.<section>.<alias>`:
44
+ * - `unknown_field` for an alias the table does not declare in `writeJoins`. Dropped in
45
+ * silence, a typo'd alias would answer success with the child rows unwritten, or the rows to
46
+ * delete still there;
47
+ * - `unknown_field` for a `replace` alias whose relation has no `upsertKey`: the key is what
48
+ * tells a child row the request sends from one to delete;
49
+ * - `conflicting_alias` for an alias in `replace` and in `upsert` or `delete` too: the set
50
+ * `replace` names already says what stays and what goes.
51
+ * `at` is the bulk item's index, empty for a single write.
52
+ */
53
+ export declare function assertWriteJoinAliases(tableConf: TableConfig, sections: WriteJoinSections, at?: string): void;
17
54
  /**
18
55
  * The context a per-alias write pass runs in. Shared by `processSecondaries` and
19
56
  * `processDeletions`, which differ only in the payload they are handed.
20
57
  */
21
58
  export interface WriteJoinPass {
22
59
  db: QueryClient;
23
- tableConf: ITable;
60
+ tableConf: TableConfig;
24
61
  dbTables: DbTables;
25
62
  /** Main record (camelCase), the source of the FK auto-filled into every child row. */
26
63
  mainRecord: Record<string, unknown>;
27
64
  tenant?: TenantContext;
28
65
  /** The request that triggered the write, handed to the child table's `beforeInsert`. */
29
- request: ApiRequest;
66
+ request: ApiRequest | undefined;
67
+ /** The bulk item's index, prefixed to the paths of a child row's errors; absent on a single write. */
68
+ at?: string;
30
69
  }
31
70
  interface PrepareCtx {
32
71
  db: QueryClient;
33
- tableConf: ITable;
34
- request: ApiRequest;
72
+ tableConf: TableConfig;
73
+ dbTables: DbTables;
74
+ request: ApiRequest | undefined;
35
75
  }
36
76
  /**
37
77
  * Prepare a single record for INSERT/UPSERT:
38
78
  * 1. shallow camelCase copy of `input`
39
- * 2. runValidation (camelCase — sees the client payload as sent)
40
- * 3. drop excludeFromCreation fields (client-input whitelist; applied BEFORE the
41
- * hook so values it assigns — e.g. a server-generated id — reach the INSERT)
79
+ * 2. runValidation (camelCase — sees the client payload as sent), then the child tables'
80
+ * own `validate` on the child rows (ADR 0030) — both before the hook and any SQL
81
+ * 3. drop insertExclude fields (client-input whitelist; applied BEFORE the
82
+ * hook so values it assigns — e.g. a server-generated id — reach the INSERT), except
83
+ * those of the table's upsertKey, which name the row to update
42
84
  * 4. beforeInsert hook (caller can mutate the camelCase copy)
43
85
  * 5. drop non-writable fields (generated columns, writeExclude) — AFTER the hook, because
44
86
  * the database refuses those values whoever assigned them
@@ -47,24 +89,35 @@ interface PrepareCtx {
47
89
  * Returns both `camel` (input + hook mutations, used for FK auto-fill / afterInsert) and
48
90
  * `snake` (DB-ready record). The original `input` is left intact.
49
91
  *
50
- * Pass `secondaries` so the validate hook receives them; pass undefined to skip
51
- * secondaries-aware validation (e.g. when a bulk-level validator already ran).
92
+ * Pass the request's `upsert`/`replace` sections so the validate hooks receive them; set
93
+ * `skipValidate` when a bulk-level validator already ran for the host (the child tables still
94
+ * validate their rows), and `at` to the bulk item's index for the error paths.
52
95
  */
53
- export declare function prepareInsertRecord(ctx: PrepareCtx, input: Record<string, unknown>, secondaries?: Record<string, Record<string, unknown>[]>, options?: {
96
+ export declare function prepareInsertRecord(ctx: PrepareCtx, input: Record<string, unknown>, children?: Pick<WriteJoinSections, 'upsert' | 'replace'>, options?: {
54
97
  skipValidate?: boolean;
98
+ at?: string;
55
99
  }): Promise<{
56
100
  camel: Record<string, unknown>;
57
101
  snake: Record<string, unknown>;
58
102
  }>;
103
+ /** What `processSecondaries` did: the child rows written, and those a `replace` removed. */
104
+ export interface SecondariesOutcome {
105
+ written: RowsByAlias;
106
+ removed: RowsByAlias;
107
+ }
59
108
  /**
60
- * Write the child rows a request sent alongside the main record, one bulk statement per alias.
109
+ * Write the child rows of a request's `upsert` and `replace` sections, one bulk statement per
110
+ * alias; for a `replace` alias, then delete every other child row of the main row (ADR 0029).
61
111
  *
62
112
  * A secondary is a write like any other: the child table's own `tenantScope` is enforced on it
63
113
  * (`tenantForTable` re-targets the caller's tenant onto that table's scope). Without this the
64
114
  * client picks the child's tenant value, which lets it plant rows inside another tenant — and,
65
115
  * where the child is upserted, hijack one of that tenant's existing rows via the conflict key.
116
+ *
117
+ * An empty list writes nothing; under `replace` it still removes every child row. An alias the
118
+ * table does not declare is skipped: `assertWriteJoinAliases` refuses it first.
66
119
  */
67
- export declare function processSecondaries(pass: WriteJoinPass, secondaries: Record<string, Record<string, unknown>[]>): Promise<Record<string, Record<string, unknown>[]>>;
120
+ export declare function processSecondaries(pass: WriteJoinPass, sections: Pick<WriteJoinSections, 'upsert' | 'replace'>): Promise<SecondariesOutcome>;
68
121
  /**
69
122
  * Process per-alias deletion requests for a write join.
70
123
  *
@@ -78,6 +131,6 @@ export declare function processSecondaries(pass: WriteJoinPass, secondaries: Rec
78
131
  * The FK alone is not isolation: a child row owned by another tenant may still point at a main
79
132
  * row the caller owns, so the child table's own `tenantScope` is added to the DELETE.
80
133
  */
81
- export declare function processDeletions(pass: WriteJoinPass, deletions: Record<string, Record<string, unknown>[]>): Promise<Record<string, Record<string, unknown>[]>>;
134
+ export declare function processDeletions(pass: WriteJoinPass, deletions: RowsByAlias): Promise<RowsByAlias>;
82
135
  export {};
83
136
  //# sourceMappingURL=write-helpers.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"write-helpers.d.ts","sourceRoot":"","sources":["../../../src/lib/engine/write-helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAEzD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAW5C,OAAO,KAAK,EACV,MAAM,EACN,QAAQ,EAGR,aAAa,EACb,gBAAgB,EACjB,MAAM,gBAAgB,CAAC;AAExB;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,gBAAgB,EACxB,YAAY,EAAE,MAAM,EAAE,EACtB,MAAM,EAAE,MAAM,EAAE,EAChB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GACjC,IAAI,CA0BN;AAmCD,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,QAAQ,EAClB,aAAa,EAAE,MAAM,GACpB,MAAM,GAAG,SAAS,CAKpB;AAED;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,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