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,10 +1,11 @@
1
1
  import { ConditionBuilder, Expression } from 'node-condition-builder';
2
2
  import { assertReadable, assertFiltersReadable, hasOwnField, ownField } from '../../read-access.js';
3
3
  import { ALLOWED_SET } from '../../condition-methods.js';
4
- import { err400, validateSchemaField, evaluateComputedField, mapRowsToCamelCase, buildSelectionColumns, } from './fields.js';
4
+ import { err400, validateSchemaField, evaluateComputedField, mapRowsToCamelCase, buildJoinSelectColumns, rejectRetiredKey, } from './fields.js';
5
5
  import { runAfterRead } from '../read-hooks.js';
6
6
  import { appendJoinTenantScope, subqueryAlias, requireJoin, extractJoinRefs, } from './joins.js';
7
7
  import { tenantForTable, buildTenantRowGuard } from '../../tenant.js';
8
+ import { resolveJoinTableConf } from '../../table-helpers.js';
8
9
  import { dispatchConditionMethod, buildJoinRefCondition } from './conditions.js';
9
10
  import { AGG_FN, aggExpr } from './aggregations.js';
10
11
  /**
@@ -39,20 +40,21 @@ function applyJoinLeftFilters(cb, filters, scope) {
39
40
  }
40
41
  }
41
42
  /** `joinLeft.conditions` — operator methods. An unknown field is a 400, not a no-op. */
42
- function applyJoinLeftConditions(cb, conditions, scope, dbTables) {
43
- for (const c of conditions) {
43
+ function applyJoinLeftConditions(cb, conditions, scope) {
44
+ for (const [i, c] of conditions.entries()) {
45
+ const here = `joinLeft.${scope.alias}.conditions.${i}`;
44
46
  if (!ALLOWED_SET.has(c.method)) {
45
- err400(`Invalid condition method: ${c.method}`);
47
+ err400('invalid_method', `${here}.method`, `Invalid condition method: ${c.method}`);
46
48
  }
47
49
  if (hasOwnField(scope.joinSchema.fields, c.field)) {
48
- assertReadable(dbTables[scope.joinSchema.tableName], c.field);
50
+ assertReadable(scope.joinTableConf, c.field, `${here}.field`);
49
51
  }
50
52
  else if (!ownField(scope.computed, c.field)) {
51
- err400(`Unknown field: ${c.field}`);
53
+ err400('unknown_field', `${here}.field`, `Unknown field: ${c.field}`);
52
54
  }
53
55
  const ref = resolveJoinLeftField(c.field, scope);
54
56
  if (ref !== null)
55
- dispatchConditionMethod(cb, c.method, ref, c.params ?? []);
57
+ dispatchConditionMethod(cb, c.method, ref, c.params ?? [], here);
56
58
  }
57
59
  }
58
60
  /**
@@ -73,12 +75,12 @@ export function buildLeftJoinOnClauses(db, dbTables, tableConf, aliasesNeedingJo
73
75
  const values = [];
74
76
  let currentIdx = startIdx;
75
77
  for (const alias of aliasesNeedingJoin) {
76
- const joinDef = requireJoin(tableConf, alias, true);
78
+ const joinDef = requireJoin(tableConf, alias, true, `joinLeft.${alias}`);
77
79
  const refs = extractJoinRefs(db, tableConf, joinDef);
78
80
  const aliasIdent = db.qi(alias);
79
81
  // The guard references the join through its ALIAS: one table may be joined under several
80
82
  // aliases, and each predicate must bind to the row this clause produced.
81
- const guard = buildTenantRowGuard(db, tenantForTable(tenant, dbTables[joinDef.joinSchema.tableName]), alias);
83
+ const guard = buildTenantRowGuard(db, tenantForTable(tenant, resolveJoinTableConf(dbTables, joinDef)), alias);
82
84
  let scoped = '';
83
85
  if (guard) {
84
86
  scoped = ` AND ${guard.build(currentIdx, db.ph)}`;
@@ -96,7 +98,7 @@ export function buildLeftJoinFilters(db, dbTables, tableConf, aliasesNeedingJoin
96
98
  const values = [];
97
99
  let currentIdx = startIdx;
98
100
  for (const alias of aliasesNeedingJoin) {
99
- const joinDef = requireJoin(tableConf, alias, true);
101
+ const joinDef = requireJoin(tableConf, alias, true, `joinLeft.${alias}`);
100
102
  const { joinSchema } = joinDef;
101
103
  const aliasIdent = db.qi(alias);
102
104
  const ref = joinLeft?.[alias];
@@ -107,20 +109,21 @@ export function buildLeftJoinFilters(db, dbTables, tableConf, aliasesNeedingJoin
107
109
  // `assertJoinFilterKeys` rejects them up front rather than letting them through as a
108
110
  // silent no-op, and the generated body schema does not advertise them for unique:true
109
111
  // relations.
110
- const joinTableConf = dbTables[joinSchema.tableName];
112
+ const joinTableConf = resolveJoinTableConf(dbTables, joinDef);
111
113
  const scope = {
112
114
  db,
113
115
  alias,
114
116
  aliasIdent,
115
117
  joinSchema,
118
+ joinTableConf,
116
119
  computed: joinTableConf?.computedFields,
117
120
  };
118
121
  const cb = new ConditionBuilder('AND', db.cbDialect);
119
- assertFiltersReadable(ref.filters, joinTableConf);
122
+ assertFiltersReadable(ref.filters, joinTableConf, `joinLeft.${alias}.filters`);
120
123
  if (ref.filters)
121
124
  applyJoinLeftFilters(cb, ref.filters, scope);
122
125
  if (ref.conditions?.length)
123
- applyJoinLeftConditions(cb, ref.conditions, scope, dbTables);
126
+ applyJoinLeftConditions(cb, ref.conditions, scope);
124
127
  const sql = cb.build(currentIdx, db.ph);
125
128
  const vals = cb.getValues();
126
129
  if (sql) {
@@ -148,14 +151,15 @@ function scopeJoinSideQuery(cb, db, joinSchema, joinField, ids, joinTableConf, t
148
151
  async function fetchJoinRows(db, dbTables, tableConf, mainResults, requests, mode, tenant, request) {
149
152
  const result = {};
150
153
  for (const [alias, ref] of Object.entries(requests)) {
151
- const joinDef = requireJoin(tableConf, alias, mode.requireUnique);
152
- const { joinSchema, joinField, mainField, selection: defaultSelection } = joinDef;
153
- const joinTableConf = dbTables[joinSchema.tableName];
154
- // The selection is resolved before the empty-result bail-out: it is validated against
154
+ const at = `${mode.source}.${alias}`;
155
+ const joinDef = requireJoin(tableConf, alias, mode.requireUnique, at);
156
+ const { joinSchema, joinField, mainField } = joinDef;
157
+ const joinTableConf = resolveJoinTableConf(dbTables, joinDef);
158
+ // The projection is resolved before the empty-result bail-out: it is validated against
155
159
  // the join schema, and that rejection must not depend on whether the main query
156
160
  // matched rows.
157
- const selection = ref?.selection ?? defaultSelection;
158
- const columns = buildSelectionColumns(selection, joinSchema, db, joinTableConf, joinDef.fields !== undefined);
161
+ rejectRetiredKey(ref, 'selection', `${at}.selection`, `use 'select', an array of field names`);
162
+ const columns = buildJoinSelectColumns(ref?.select ?? joinDef.select, joinSchema, db, joinTableConf, joinDef.fields !== undefined, `${at}.select`);
159
163
  // For joinLeft, mainField on the main table is the FK pointing at joinField (the
160
164
  // parent's PK), so the same collect-then-look-up works for both directions.
161
165
  const ids = collectIds(mainResults, mainField);
@@ -164,7 +168,7 @@ async function fetchJoinRows(db, dbTables, tableConf, mainResults, requests, mod
164
168
  continue;
165
169
  }
166
170
  const cb = mode.applyRefCondition
167
- ? buildJoinRefCondition(joinTableConf, joinSchema, ref || {}, db)
171
+ ? buildJoinRefCondition(joinTableConf, joinSchema, ref || {}, db, undefined, at)
168
172
  : new ConditionBuilder('AND', db.cbDialect);
169
173
  const { where, values, tenantJoins } = scopeJoinSideQuery(cb, db, joinSchema, joinField, ids, joinTableConf, tenant);
170
174
  const rows = await db.select({
@@ -204,21 +208,21 @@ export function executeJoinLeft(db, dbTables, tableConf, mainResults, joinLeft,
204
208
  * values supported in this position; reject with 400 if the computed
205
209
  * returns values)
206
210
  */
207
- function buildByExpression(by, joinSchema, joinTableConf, db) {
211
+ function buildByExpression(by, joinSchema, joinTableConf, db, at) {
208
212
  if (typeof by !== 'string') {
209
- err400(`Invalid 'by' specification: expected a field or computed name`);
213
+ err400('invalid_aggregation', at, `Invalid 'by' specification: expected a field or computed name`);
210
214
  }
211
215
  if (hasOwnField(joinSchema.fields, by)) {
212
216
  // validateSchemaField also enforces readExclude: GROUP BY on a hidden field
213
217
  // would return its distinct values verbatim in `rows[].by`.
214
- const col = validateSchemaField(by, joinSchema, joinTableConf);
218
+ const col = validateSchemaField(by, joinSchema, joinTableConf, at);
215
219
  return `${db.qi(joinSchema.tableName)}.${db.qi(col)}`;
216
220
  }
217
221
  const fn = ownField(joinTableConf?.computedFields, by);
218
222
  if (fn) {
219
- return evaluateComputedField(by, fn, joinSchema, db, undefined, `Computed field '${by}' with bound values cannot be used in aggregations.by`).value;
223
+ return evaluateComputedField(by, fn, joinSchema, db, undefined, `Computed field '${by}' with bound values cannot be used in joinGroup by`, false, at).value;
220
224
  }
221
- err400(`Unknown field: ${by}`);
225
+ err400('unknown_field', at, `Unknown field: ${by}`);
222
226
  }
223
227
  // ─── joinGroup (aggregations) ───────────────────────────────
224
228
  /**
@@ -227,77 +231,81 @@ function buildByExpression(by, joinSchema, joinTableConf, db) {
227
231
  * Every field is validated against the join schema here, so an unknown or unreachable one
228
232
  * is a 400 regardless of what the data happens to contain.
229
233
  */
230
- function buildJoinGroupSelect(aggregations, joinSchema, joinTableConf, db) {
234
+ const AGG_KINDS = ['distinctCount', 'min', 'max', 'sum', 'avg', 'count'];
235
+ /**
236
+ * SELECT and GROUP BY fragments for one joinGroup alias, plus the column alias → response
237
+ * position map the rows are shaped with.
238
+ *
239
+ * Refuses a request with no aggregate function (a GROUP BY alone computes nothing), and the
240
+ * pre-1.0 `aggregations` wrapper, which a JavaScript caller can still send: ignoring it would
241
+ * answer an empty result instead of saying why.
242
+ */
243
+ function buildJoinGroupSelect(groupReq, joinSchema, joinTableConf, db, at) {
244
+ if ('aggregations' in groupReq) {
245
+ err400('invalid_aggregation', `${at}.aggregations`, `joinGroup '${at}': 'by' and the aggregate functions go directly in the joinGroup entry, not under 'aggregations'`);
246
+ }
247
+ if (!AGG_KINDS.some((kind) => (groupReq[kind]?.length ?? 0) > 0)) {
248
+ err400('invalid_aggregation', at, `joinGroup '${at}' computes nothing: name at least one of ${AGG_KINDS.join(', ')}`);
249
+ }
231
250
  const selectParts = [];
232
251
  const groupByParts = [];
233
- if (aggregations.by) {
234
- const byExpr = buildByExpression(aggregations.by, joinSchema, joinTableConf, db);
252
+ // Column alias → [function, field]: the response is shaped from this map, never by
253
+ // splitting the alias, so a field name holding `_` survives the round trip.
254
+ const columns = new Map();
255
+ if (groupReq.by) {
256
+ const byExpr = buildByExpression(groupReq.by, joinSchema, joinTableConf, db, `${at}.by`);
235
257
  selectParts.push(`${byExpr} as "by"`);
236
258
  groupByParts.push(byExpr);
237
259
  }
238
- const addAgg = (kind, fields) => {
239
- if (!fields)
240
- return;
260
+ for (const kind of AGG_KINDS) {
241
261
  const fn = AGG_FN[kind];
242
- for (const f of fields) {
243
- const col = validateSchemaField(f, joinSchema, joinTableConf);
262
+ for (const [i, f] of (groupReq[kind] ?? []).entries()) {
263
+ const col = validateSchemaField(f, joinSchema, joinTableConf, `${at}.${kind}.${i}`);
244
264
  const colRef = `${db.qi(joinSchema.tableName)}.${db.qi(col)}`;
245
- selectParts.push(`${aggExpr(fn, colRef)} as "${kind}_${f}"`);
265
+ const colAlias = `${kind}_${f}`;
266
+ columns.set(colAlias, [kind, f]);
267
+ selectParts.push(`${aggExpr(fn, colRef)} as "${colAlias}"`);
246
268
  }
247
- };
248
- addAgg('distinctCount', aggregations.distinctCount);
249
- addAgg('min', aggregations.min);
250
- addAgg('max', aggregations.max);
251
- addAgg('sum', aggregations.sum);
252
- addAgg('avg', aggregations.avg);
253
- addAgg('count', aggregations.count);
254
- return { selectParts, groupByParts };
255
- }
256
- /**
257
- * Shape aggregation rows into the response: a single row without `by` collapses to
258
- * `{ fn: { field: value } }`; anything else stays a list under `rows`.
259
- */
260
- function formatJoinGroupRows(rows, hasBy) {
261
- const formatted = {};
262
- if (rows.length === 0)
263
- return formatted;
264
- const row = rows.length === 1 && !hasBy ? rows[0] : rows;
265
- if (Array.isArray(row)) {
266
- formatted.rows = row;
267
- return formatted;
268
- }
269
- for (const [key, value] of Object.entries(row)) {
270
- if (key === 'by')
271
- continue;
272
- const [fn, field] = key.split('_');
273
- if (!formatted[fn])
274
- formatted[fn] = {};
275
- formatted[fn][field] = value;
276
269
  }
277
- return formatted;
270
+ return { selectParts, groupByParts, columns };
271
+ }
272
+ /** Shape aggregation rows into the response: `{ by?, <fn>: { <field>: value } }` per row. */
273
+ function formatJoinGroupRows(rows, columns) {
274
+ return rows.map((row) => {
275
+ const out = {};
276
+ if ('by' in row)
277
+ out.by = row.by;
278
+ for (const [colAlias, [kind, field]] of columns) {
279
+ if (!out[kind])
280
+ out[kind] = {};
281
+ out[kind][field] = row[colAlias];
282
+ }
283
+ return out;
284
+ });
278
285
  }
279
286
  export async function executeJoinGroup(db, dbTables, tableConf, mainResults, joinGroup, tenant) {
280
287
  const result = {};
281
288
  for (const [alias, groupReq] of Object.entries(joinGroup)) {
282
- const joinDef = requireJoin(tableConf, alias, false);
289
+ const at = `joinGroup.${alias}`;
290
+ const joinDef = requireJoin(tableConf, alias, false, at);
283
291
  const { joinSchema, joinField, mainField } = joinDef;
284
- const joinTableConf = dbTables[joinSchema.tableName];
292
+ const joinTableConf = resolveJoinTableConf(dbTables, joinDef);
285
293
  const ids = collectIds(mainResults, mainField);
286
- const { aggregations, filters: groupFilters, conditions: groupConditions } = groupReq;
287
- const { selectParts, groupByParts } = buildJoinGroupSelect(aggregations, joinSchema, joinTableConf, db);
294
+ const { filters: groupFilters, conditions: groupConditions } = groupReq;
295
+ const { selectParts, groupByParts, columns } = buildJoinGroupSelect(groupReq, joinSchema, joinTableConf, db, at);
288
296
  // Bail out only here: `by` and every aggregation field have now been validated.
289
- if (selectParts.length === 0 || ids.length === 0) {
290
- result[alias] = {};
297
+ if (ids.length === 0) {
298
+ result[alias] = { rows: [] };
291
299
  continue;
292
300
  }
293
301
  const groupRef = { filters: groupFilters, conditions: groupConditions };
294
- const cb = buildJoinRefCondition(joinTableConf, joinSchema, groupRef, db);
302
+ const cb = buildJoinRefCondition(joinTableConf, joinSchema, groupRef, db, undefined, at);
295
303
  const { where, values, tenantJoins } = scopeJoinSideQuery(cb, db, joinSchema, joinField, ids, joinTableConf, tenant);
296
304
  const groupBy = groupByParts.length > 0 ? `GROUP BY ${groupByParts.join(', ')}` : '';
297
305
  const fromJoins = tenantJoins.length > 0 ? ` ${tenantJoins.join(' ')}` : '';
298
306
  const sql = `SELECT ${selectParts.join(', ')} FROM ${db.qi(joinSchema.tableName)}${fromJoins} WHERE ${where} ${groupBy}`;
299
307
  const queryResult = await db.query(sql, values);
300
- result[alias] = formatJoinGroupRows(queryResult.rows, Boolean(aggregations.by));
308
+ result[alias] = { rows: formatJoinGroupRows(queryResult.rows, columns) };
301
309
  }
302
310
  return result;
303
311
  }
@@ -321,15 +329,16 @@ function collectIds(mainResults, mainField) {
321
329
  export function buildJoinMustExistClauses(params, db, dbTables, tableConf, joinMustExist, tenant) {
322
330
  let where = '';
323
331
  for (const [alias, ref] of Object.entries(joinMustExist)) {
324
- const joinDef = requireJoin(tableConf, alias, false);
332
+ const at = `joinMustExist.${alias}`;
333
+ const joinDef = requireJoin(tableConf, alias, false, at);
325
334
  const { joinSchema } = joinDef;
326
- const joinTableConf = dbTables[joinSchema.tableName];
335
+ const joinTableConf = resolveJoinTableConf(dbTables, joinDef);
327
336
  const refs = extractJoinRefs(db, tableConf, joinDef);
328
337
  // The EXISTS FROM is aliased so the correlation to the outer table survives a
329
338
  // self-referencing relation; everything inside references the alias.
330
339
  const subAlias = subqueryAlias(alias, tableConf);
331
340
  const subRef = db.qi(subAlias);
332
- const filterCondition = buildJoinRefCondition(joinTableConf, joinSchema, ref, db, subAlias);
341
+ const filterCondition = buildJoinRefCondition(joinTableConf, joinSchema, ref, db, subAlias, at);
333
342
  const tenantJoins = [];
334
343
  appendJoinTenantScope(db, joinTableConf, tenant, subAlias, filterCondition, tenantJoins);
335
344
  const filterWhere = params.emitCondition(filterCondition, db);
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import { ConditionBuilder } from 'node-condition-builder';
9
9
  import type { QueryClient } from '../../db.js';
10
- import type { DbTables, FilterRecord, ITable, JoinDefinition, TenantContext } from '../../../types.js';
10
+ import type { DbTables, FilterRecord, TableConfig, JoinDefinition, TenantContext } from '../../../types.js';
11
11
  /**
12
12
  * Tenant-scope a join side-query. When the joined table declares its own `tenantScope`,
13
13
  * appends the tenant condition to `cb` (direct: `col IN ids`; indirect: condition on the
@@ -17,14 +17,14 @@ import type { DbTables, FilterRecord, ITable, JoinDefinition, TenantContext } fr
17
17
  * `joinTableRef` is the raw name the join table goes by in the statement: its table name
18
18
  * in plain side-queries, or the subquery alias inside an aliased, correlated EXISTS.
19
19
  */
20
- export declare function appendJoinTenantScope(db: QueryClient, joinTableConf: ITable | undefined, tenant: TenantContext | undefined, joinTableRef: string, cb: ConditionBuilder, joins?: string[]): void;
20
+ export declare function appendJoinTenantScope(db: QueryClient, joinTableConf: TableConfig | undefined, tenant: TenantContext | undefined, joinTableRef: string, cb: ConditionBuilder, joins?: string[]): void;
21
21
  /**
22
22
  * Alias for the FROM of a correlated subquery (EXISTS, aggregate). The subquery must not
23
23
  * say `FROM <table>` bare: on a self-referencing relation the inner table would shadow the
24
24
  * outer one and the correlation would silently compare each row with itself. The request
25
25
  * alias is used, suffixed when it would itself collide with the outer table's name.
26
26
  */
27
- export declare function subqueryAlias(alias: string, tableConf: ITable): string;
27
+ export declare function subqueryAlias(alias: string, tableConf: TableConfig): string;
28
28
  /**
29
29
  * Validate the filter keys of every join reference in a request map.
30
30
  *
@@ -33,11 +33,19 @@ export declare function subqueryAlias(alias: string, tableConf: ITable): string;
33
33
  * same request answer 400 or 200 depending on the data it happens to match.
34
34
  *
35
35
  * Unknown aliases are left to `requireJoin`, which reports them with its own message.
36
+ *
37
+ * `family` is the request key the map came from (`joinMultiple`, …): a rejected filter is
38
+ * reported at `<family>.<alias>.filters.<key>`.
36
39
  */
37
- export declare function assertJoinFilterKeys(dbTables: DbTables, tableConf: ITable, refs: Record<string, {
40
+ export declare function assertJoinFilterKeys(dbTables: DbTables, tableConf: TableConfig, refs: Record<string, {
38
41
  filters?: FilterRecord;
39
- }> | undefined, allowExtraFilters: boolean): void;
40
- export declare function requireJoin(tableConf: ITable, alias: string, requireUnique: boolean): JoinDefinition;
42
+ }> | undefined, allowExtraFilters: boolean, family: string): void;
43
+ /**
44
+ * The relation a request names by alias, or a 400 when the host declares no such alias or
45
+ * declares it for the other join direction. `at` is the request path naming the alias
46
+ * (`joinLeft.<alias>`, `orderBy`), '' when unknown.
47
+ */
48
+ export declare function requireJoin(tableConf: TableConfig, alias: string, requireUnique: boolean, at?: string): JoinDefinition;
41
49
  export interface JoinRefs {
42
50
  mainColName: string;
43
51
  /** db.qi'd column reference on main side (FK or PK) */
@@ -51,5 +59,5 @@ export interface JoinRefs {
51
59
  }
52
60
  /** Extract quoted identifiers for a join reference. Used by joinMustExist, joinLeft and joinGroup
53
61
  * SQL builders to avoid the 4-line FK/PK destructuring boilerplate at every call site. */
54
- export declare function extractJoinRefs(db: QueryClient, tableConf: ITable, joinDef: JoinDefinition): JoinRefs;
62
+ export declare function extractJoinRefs(db: QueryClient, tableConf: TableConfig, joinDef: JoinDefinition): JoinRefs;
55
63
  //# sourceMappingURL=joins.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"joins.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/joins.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAI/C,OAAO,KAAK,EACV,QAAQ,EACR,YAAY,EACZ,MAAM,EACN,cAAc,EACd,aAAa,EACd,MAAM,mBAAmB,CAAC;AAE3B;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,CACnC,EAAE,EAAE,WAAW,EACf,aAAa,EAAE,MAAM,GAAG,SAAS,EACjC,MAAM,EAAE,aAAa,GAAG,SAAS,EACjC,YAAY,EAAE,MAAM,EACpB,EAAE,EAAE,gBAAgB,EACpB,KAAK,CAAC,EAAE,MAAM,EAAE,GACf,IAAI,CAON;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAEtE;AAMD;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE;IAAE,OAAO,CAAC,EAAE,YAAY,CAAA;CAAE,CAAC,GAAG,SAAS,EAC5D,iBAAiB,EAAE,OAAO,GACzB,IAAI,CAUN;AAED,wBAAgB,WAAW,CACzB,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,MAAM,EACb,aAAa,EAAE,OAAO,GACrB,cAAc,CAYhB;AAED,MAAM,WAAW,QAAQ;IACvB,WAAW,EAAE,MAAM,CAAC;IACpB,uDAAuD;IACvD,OAAO,EAAE,MAAM,CAAC;IAChB,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,uDAAuD;IACvD,KAAK,EAAE,MAAM,CAAC;CACf;AAED;0FAC0F;AAC1F,wBAAgB,eAAe,CAC7B,EAAE,EAAE,WAAW,EACf,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,cAAc,GACtB,QAAQ,CAUV"}
1
+ {"version":3,"file":"joins.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/joins.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAK/C,OAAO,KAAK,EACV,QAAQ,EACR,YAAY,EACZ,WAAW,EACX,cAAc,EACd,aAAa,EACd,MAAM,mBAAmB,CAAC;AAE3B;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,CACnC,EAAE,EAAE,WAAW,EACf,aAAa,EAAE,WAAW,GAAG,SAAS,EACtC,MAAM,EAAE,aAAa,GAAG,SAAS,EACjC,YAAY,EAAE,MAAM,EACpB,EAAE,EAAE,gBAAgB,EACpB,KAAK,CAAC,EAAE,MAAM,EAAE,GACf,IAAI,CAON;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,GAAG,MAAM,CAE3E;AAMD;;;;;;;;;;;GAWG;AACH,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,WAAW,EACtB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE;IAAE,OAAO,CAAC,EAAE,YAAY,CAAA;CAAE,CAAC,GAAG,SAAS,EAC5D,iBAAiB,EAAE,OAAO,EAC1B,MAAM,EAAE,MAAM,GACb,IAAI,CAWN;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CACzB,SAAS,EAAE,WAAW,EACtB,KAAK,EAAE,MAAM,EACb,aAAa,EAAE,OAAO,EACtB,EAAE,SAAK,GACN,cAAc,CAYhB;AAED,MAAM,WAAW,QAAQ;IACvB,WAAW,EAAE,MAAM,CAAC;IACpB,uDAAuD;IACvD,OAAO,EAAE,MAAM,CAAC;IAChB,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,uDAAuD;IACvD,KAAK,EAAE,MAAM,CAAC;CACf;AAED;0FAC0F;AAC1F,wBAAgB,eAAe,CAC7B,EAAE,EAAE,WAAW,EACf,SAAS,EAAE,WAAW,EACtB,OAAO,EAAE,cAAc,GACtB,QAAQ,CAUV"}
@@ -1,5 +1,6 @@
1
1
  import { buildTenantCondition, buildTenantJoin } from '../../tenant.js';
2
2
  import { assertFiltersReadable, assertKnownFilterKeys } from '../../read-access.js';
3
+ import { resolveJoinTableConf, resolvedTenantScope } from '../../table-helpers.js';
3
4
  import { err400 } from './fields.js';
4
5
  /**
5
6
  * Tenant-scope a join side-query. When the joined table declares its own `tenantScope`,
@@ -11,7 +12,7 @@ import { err400 } from './fields.js';
11
12
  * in plain side-queries, or the subquery alias inside an aliased, correlated EXISTS.
12
13
  */
13
14
  export function appendJoinTenantScope(db, joinTableConf, tenant, joinTableRef, cb, joins) {
14
- const scope = joinTableConf?.tenantScope;
15
+ const scope = resolvedTenantScope(joinTableConf);
15
16
  if (!tenant || !scope)
16
17
  return;
17
18
  cb.append(buildTenantCondition(db, scope, tenant.ids, joinTableRef));
@@ -26,10 +27,10 @@ export function appendJoinTenantScope(db, joinTableConf, tenant, joinTableRef, c
26
27
  * alias is used, suffixed when it would itself collide with the outer table's name.
27
28
  */
28
29
  export function subqueryAlias(alias, tableConf) {
29
- return alias === tableConf.Schema.tableName ? `${alias}_sub` : alias;
30
+ return alias === tableConf.schema.tableName ? `${alias}_sub` : alias;
30
31
  }
31
32
  function findJoinByAlias(tableConf, alias) {
32
- return tableConf.allowedReadJoins?.find((j) => j.alias === alias);
33
+ return tableConf.readJoins?.find((j) => j.alias === alias);
33
34
  }
34
35
  /**
35
36
  * Validate the filter keys of every join reference in a request map.
@@ -39,30 +40,39 @@ function findJoinByAlias(tableConf, alias) {
39
40
  * same request answer 400 or 200 depending on the data it happens to match.
40
41
  *
41
42
  * Unknown aliases are left to `requireJoin`, which reports them with its own message.
43
+ *
44
+ * `family` is the request key the map came from (`joinMultiple`, …): a rejected filter is
45
+ * reported at `<family>.<alias>.filters.<key>`.
42
46
  */
43
- export function assertJoinFilterKeys(dbTables, tableConf, refs, allowExtraFilters) {
47
+ export function assertJoinFilterKeys(dbTables, tableConf, refs, allowExtraFilters, family) {
44
48
  if (!refs)
45
49
  return;
46
50
  for (const [alias, ref] of Object.entries(refs)) {
47
51
  const joinDef = findJoinByAlias(tableConf, alias);
48
52
  if (!joinDef)
49
53
  continue;
50
- const joinTableConf = dbTables[joinDef.joinSchema.tableName];
54
+ const joinTableConf = resolveJoinTableConf(dbTables, joinDef);
51
55
  const filters = ref?.filters;
52
- assertFiltersReadable(filters, joinTableConf);
53
- assertKnownFilterKeys(filters, joinDef.joinSchema, joinTableConf, allowExtraFilters);
56
+ const at = `${family}.${alias}.filters`;
57
+ assertFiltersReadable(filters, joinTableConf, at);
58
+ assertKnownFilterKeys(filters, joinDef.joinSchema, joinTableConf, allowExtraFilters, at);
54
59
  }
55
60
  }
56
- export function requireJoin(tableConf, alias, requireUnique) {
61
+ /**
62
+ * The relation a request names by alias, or a 400 when the host declares no such alias or
63
+ * declares it for the other join direction. `at` is the request path naming the alias
64
+ * (`joinLeft.<alias>`, `orderBy`), '' when unknown.
65
+ */
66
+ export function requireJoin(tableConf, alias, requireUnique, at = '') {
57
67
  const joinDef = findJoinByAlias(tableConf, alias);
58
68
  if (!joinDef) {
59
- err400(`Unknown join alias: ${alias}`);
69
+ err400('unknown_alias', at, `Unknown join alias: ${alias}`);
60
70
  }
61
71
  if (requireUnique && !joinDef.unique) {
62
- err400(`Join alias '${alias}' is not declared with unique:true; use joinMultiple/joinMustExist/joinGroup instead`);
72
+ err400('wrong_join_family', at, `Join alias '${alias}' is not declared with unique:true; use joinMultiple/joinMustExist/joinGroup instead`);
63
73
  }
64
74
  if (!requireUnique && joinDef.unique) {
65
- err400(`Join alias '${alias}' is declared with unique:true; use joinLeft instead`);
75
+ err400('wrong_join_family', at, `Join alias '${alias}' is declared with unique:true; use joinLeft instead`);
66
76
  }
67
77
  return joinDef;
68
78
  }
@@ -73,8 +83,8 @@ export function extractJoinRefs(db, tableConf, joinDef) {
73
83
  const mainColName = Array.isArray(mainField) ? mainField[0] : mainField;
74
84
  return {
75
85
  mainColName,
76
- mainCol: db.qi(tableConf.Schema.col(mainColName)),
77
- mainTable: db.qi(tableConf.Schema.tableName),
86
+ mainCol: db.qi(tableConf.schema.col(mainColName)),
87
+ mainTable: db.qi(tableConf.schema.tableName),
78
88
  joinTable: db.qi(joinSchema.tableName),
79
89
  fkCol: db.qi(joinSchema.col(joinField)),
80
90
  };
@@ -4,11 +4,11 @@
4
4
  * 2-part `alias.field` a joinLeft parent field, via a real LEFT JOIN
5
5
  * 3-part `alias.fn.field` a joinGroup aggregation, via a correlated subquery
6
6
  *
7
- * The request `orderBy` is validated strictly; `defaultOrder` from the table config is
8
- * deliberately lenient — see `convertConfiguredOrder`.
7
+ * The request `orderBy` is validated here per request; `defaultOrder` from the table config has
8
+ * the 1-part grammar only, checked by `defineTable` — see `convertConfiguredOrder`.
9
9
  */
10
10
  import type { QueryClient } from '../../db.js';
11
- import type { DbTables, ITable, JoinGroupRequest, TenantContext } from '../../../types.js';
11
+ import type { DbTables, TableConfig, JoinGroupRequest, TenantContext } from '../../../types.js';
12
12
  export interface OrderByResult {
13
13
  sql: string;
14
14
  values: unknown[];
@@ -19,17 +19,16 @@ export interface OrderByResult {
19
19
  * Pre-scan `orderBy` for the joinLeft aliases referenced in 2-part notation (`<alias>.<field>`).
20
20
  * Needed BEFORE building the LEFT JOIN clauses (which must know their aliases) while the actual
21
21
  * orderBy SQL — with its parameter placeholders — is only baked later, once the LEFT JOIN value
22
- * count is known. Validates each alias against `allowedReadJoins` (throws 400), mirroring
22
+ * count is known. Validates each alias against `readJoins` (throws 400), mirroring
23
23
  * `validateOrderBy`; 3-part aggregation entries are ignored (they use joinGroup, not a LEFT JOIN).
24
24
  */
25
- export declare function collectOrderByLeftAliases(orderBy: string, tableConf: ITable): Set<string>;
26
- export declare function validateOrderBy(orderBy: string, tableConf: ITable, db: QueryClient, dbTables: DbTables, joinGroup: Record<string, JoinGroupRequest> | undefined, startIdx: number, tenant?: TenantContext): OrderByResult;
25
+ export declare function collectOrderByLeftAliases(orderBy: string, tableConf: TableConfig): Set<string>;
26
+ export declare function validateOrderBy(orderBy: string, tableConf: TableConfig, db: QueryClient, dbTables: DbTables, joinGroup: Record<string, JoinGroupRequest> | undefined, startIdx: number, tenant?: TenantContext): OrderByResult;
27
27
  /**
28
- * Converts a configured order (`defaultOrder` or the primary-key fallback) to SQL.
29
- * Unlike the request `orderBy` (strictly validated by `validateOrderBy`), this is
30
- * lenient for backward compatibility: tokens matching a camelCase schema field are
31
- * mapped to their quoted DB column, computed fields (without bound values) expand
32
- * to their expression, and anything else passes through unchanged as raw SQL.
28
+ * Converts a configured order (`defaultOrder` or the primary-key fallback) to SQL: each
29
+ * `field [ASC|DESC]` term becomes the table-qualified column, or the expression of a computed
30
+ * field (without bound values). `defineTable` has already refused anything else; a config
31
+ * written by hand past it fails here, as a programming error, rather than reaching the SQL.
33
32
  */
34
- export declare function convertConfiguredOrder(order: string, tableConf: ITable, db: QueryClient): string;
33
+ export declare function convertConfiguredOrder(order: string, tableConf: TableConfig, db: QueryClient): string;
35
34
  //# sourceMappingURL=order-by.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"order-by.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/order-by.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAY/C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAE3F,MAAM,WAAW,aAAa;IAC5B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,OAAO,EAAE,CAAC;IAClB,2EAA2E;IAC3E,eAAe,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CAC9B;AAED;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAazF;AAED,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,EAAE,EAAE,WAAW,EACf,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,GAAG,SAAS,EACvD,QAAQ,EAAE,MAAM,EAChB,MAAM,CAAC,EAAE,aAAa,GACrB,aAAa,CAuDf;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,EACjB,EAAE,EAAE,WAAW,GACd,MAAM,CAwBR"}
1
+ {"version":3,"file":"order-by.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/order-by.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAa/C,OAAO,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAEhG,MAAM,WAAW,aAAa;IAC5B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,OAAO,EAAE,CAAC;IAClB,2EAA2E;IAC3E,eAAe,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CAC9B;AAED;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,GAAG,GAAG,CAAC,MAAM,CAAC,CAa9F;AAED,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,WAAW,EACtB,EAAE,EAAE,WAAW,EACf,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,GAAG,SAAS,EACvD,QAAQ,EAAE,MAAM,EAChB,MAAM,CAAC,EAAE,aAAa,GACrB,aAAa,CAuDf;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,WAAW,EACtB,EAAE,EAAE,WAAW,GACd,MAAM,CAmBR"}
@@ -1,12 +1,13 @@
1
1
  import { err400, validateSchemaField, resolveFieldRef, refValues, renderRef, evaluateComputedField, } from './fields.js';
2
2
  import { requireJoin } from './joins.js';
3
+ import { resolveJoinTableConf, PLAIN_ORDER_TERM, defaultOrderTermProblem, defaultOrderError } from '../../table-helpers.js';
3
4
  import { hasOwnField, ownField } from '../../read-access.js';
4
5
  import { buildAggOrderExpr } from './aggregations.js';
5
6
  /**
6
7
  * Pre-scan `orderBy` for the joinLeft aliases referenced in 2-part notation (`<alias>.<field>`).
7
8
  * Needed BEFORE building the LEFT JOIN clauses (which must know their aliases) while the actual
8
9
  * orderBy SQL — with its parameter placeholders — is only baked later, once the LEFT JOIN value
9
- * count is known. Validates each alias against `allowedReadJoins` (throws 400), mirroring
10
+ * count is known. Validates each alias against `readJoins` (throws 400), mirroring
10
11
  * `validateOrderBy`; 3-part aggregation entries are ignored (they use joinGroup, not a LEFT JOIN).
11
12
  */
12
13
  export function collectOrderByLeftAliases(orderBy, tableConf) {
@@ -18,7 +19,7 @@ export function collectOrderByLeftAliases(orderBy, tableConf) {
18
19
  const m = /^(\w+)\.(\w+)(?:\s+(ASC|DESC))?$/i.exec(trimmed);
19
20
  if (m) {
20
21
  const alias = m[1];
21
- requireJoin(tableConf, alias, true);
22
+ requireJoin(tableConf, alias, true, 'orderBy');
22
23
  aliases.add(alias);
23
24
  }
24
25
  }
@@ -36,10 +37,10 @@ export function validateOrderBy(orderBy, tableConf, db, dbTables, joinGroup, sta
36
37
  const dotted3 = /^(\w+)\.(\w+)\.(\w+)(?:\s+(ASC|DESC))?$/i.exec(trimmed);
37
38
  if (dotted3) {
38
39
  if (tableConf.distinctResults) {
39
- err400('Cannot combine distinctResults with aggregation orderBy');
40
+ err400('invalid_order_by', 'orderBy', 'Cannot combine distinctResults with aggregation orderBy');
40
41
  }
41
42
  const [, alias, fn, field, dir] = dotted3;
42
- const expr = buildAggOrderExpr(db, dbTables, tableConf, alias, fn, field, joinGroup, tenant);
43
+ const expr = buildAggOrderExpr(db, dbTables, tableConf, alias, fn, field, joinGroup, tenant, 'orderBy');
43
44
  const aggVals = [...expr.values];
44
45
  outParts.push(`${renderRef(expr, currentIdx, db)} ${(dir || 'ASC').toUpperCase()}`);
45
46
  outValues.push(...aggVals);
@@ -50,20 +51,20 @@ export function validateOrderBy(orderBy, tableConf, db, dbTables, joinGroup, sta
50
51
  const dotted2 = /^(\w+)\.(\w+)(?:\s+(ASC|DESC))?$/i.exec(trimmed);
51
52
  if (dotted2) {
52
53
  const [, alias, field, dir] = dotted2;
53
- const joinDef = requireJoin(tableConf, alias, true);
54
- const col = validateSchemaField(field, joinDef.joinSchema, dbTables[joinDef.joinSchema.tableName]);
54
+ const joinDef = requireJoin(tableConf, alias, true, 'orderBy');
55
+ const col = validateSchemaField(field, joinDef.joinSchema, resolveJoinTableConf(dbTables, joinDef), 'orderBy');
55
56
  // Reference the LEFT JOIN'd table via its alias (SQL identifier).
56
57
  outParts.push(`${db.qi(alias)}.${db.qi(col)} ${(dir || 'ASC').toUpperCase()}`);
57
58
  leftJoinAliases.add(alias);
58
59
  continue;
59
60
  }
60
61
  // 1-part: <field> [ASC|DESC] — schema field or computed
61
- const plain = /^(\w+)(?:\s+(ASC|DESC))?$/i.exec(trimmed);
62
+ const plain = PLAIN_ORDER_TERM.exec(trimmed);
62
63
  if (!plain) {
63
- err400(`Invalid orderBy: ${trimmed}`);
64
+ err400('invalid_order_by', 'orderBy', `Invalid orderBy: ${trimmed}`);
64
65
  }
65
66
  const [, field, dir] = plain;
66
- const ref = resolveFieldRef(field, tableConf.Schema, tableConf, db);
67
+ const ref = resolveFieldRef(field, tableConf.schema, tableConf, db, undefined, 'orderBy');
67
68
  // A computed field binds its own values here: ORDER BY is emitted after the WHERE, so
68
69
  // its placeholders continue from `currentIdx`.
69
70
  const refVals = refValues(ref.expr);
@@ -74,31 +75,26 @@ export function validateOrderBy(orderBy, tableConf, db, dbTables, joinGroup, sta
74
75
  return { sql: outParts.join(', '), values: outValues, leftJoinAliases };
75
76
  }
76
77
  /**
77
- * Converts a configured order (`defaultOrder` or the primary-key fallback) to SQL.
78
- * Unlike the request `orderBy` (strictly validated by `validateOrderBy`), this is
79
- * lenient for backward compatibility: tokens matching a camelCase schema field are
80
- * mapped to their quoted DB column, computed fields (without bound values) expand
81
- * to their expression, and anything else passes through unchanged as raw SQL.
78
+ * Converts a configured order (`defaultOrder` or the primary-key fallback) to SQL: each
79
+ * `field [ASC|DESC]` term becomes the table-qualified column, or the expression of a computed
80
+ * field (without bound values). `defineTable` has already refused anything else; a config
81
+ * written by hand past it fails here, as a programming error, rather than reaching the SQL.
82
82
  */
83
83
  export function convertConfiguredOrder(order, tableConf, db) {
84
84
  return order
85
85
  .split(',')
86
86
  .map((part) => {
87
- const trimmed = part.trim();
88
- const match = /^(\w+)(?:\s+(ASC|DESC))?$/i.exec(trimmed);
89
- if (match) {
90
- const [, field, dir] = match;
91
- const suffix = dir ? ` ${dir.toUpperCase()}` : '';
92
- if (hasOwnField(tableConf.Schema.fields, field)) {
93
- return `${db.qi(tableConf.Schema.tableName)}.${db.qi(tableConf.Schema.col(field))}${suffix}`;
94
- }
95
- const computed = ownField(tableConf.computedFields, field);
96
- if (computed) {
97
- const ev = evaluateComputedField(field, computed, tableConf.Schema, db, undefined, `Computed field '${field}' with bound values cannot be used in defaultOrder`);
98
- return `${ev.value}${suffix}`;
99
- }
87
+ const term = part.trim();
88
+ const problem = defaultOrderTermProblem(term, tableConf);
89
+ if (problem)
90
+ throw defaultOrderError('search', term, tableConf, problem);
91
+ const [, field, dir] = PLAIN_ORDER_TERM.exec(term);
92
+ const suffix = dir ? ` ${dir.toUpperCase()}` : '';
93
+ if (hasOwnField(tableConf.schema.fields, field)) {
94
+ return `${db.qi(tableConf.schema.tableName)}.${db.qi(tableConf.schema.col(field))}${suffix}`;
100
95
  }
101
- return trimmed;
96
+ const ev = evaluateComputedField(field, ownField(tableConf.computedFields, field), tableConf.schema, db, undefined, `Computed field '${field}' with bound values cannot be used in defaultOrder`);
97
+ return `${ev.value}${suffix}`;
102
98
  })
103
99
  .join(', ');
104
100
  }
@@ -1 +1 @@
1
- {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/search.ts"],"names":[],"mappings":"AAiCA,OAAO,KAAK,EACV,QAAQ,EACR,YAAY,EACZ,YAAY,EAGb,MAAM,mBAAmB,CAAC;AAyP3B,wBAAsB,YAAY,CAChC,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,YAAY,GACnB,OAAO,CAAC,YAAY,CAAC,CA4FvB"}
1
+ {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/search.ts"],"names":[],"mappings":"AAqCA,OAAO,KAAK,EACV,QAAQ,EACR,YAAY,EACZ,YAAY,EAGb,MAAM,mBAAmB,CAAC;AA+S3B,wBAAsB,YAAY,CAChC,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,YAAY,GACnB,OAAO,CAAC,YAAY,CAAC,CAmGvB"}