fastify-auto-sqlapi 0.5.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/AGENTS.md +5 -5
  2. package/AGENTS_BACKEND.md +166 -130
  3. package/AGENTS_FRONTEND.md +60 -38
  4. package/BREAKING_CHANGES.md +9 -893
  5. package/CHANGELOG.md +246 -15
  6. package/README.md +71 -45
  7. package/dist/bin/generate-schema.js +12 -12
  8. package/dist/bin/generate-tables.js +1 -2
  9. package/dist/bin/utils.d.ts +2 -6
  10. package/dist/bin/utils.d.ts.map +1 -1
  11. package/dist/bin/utils.js +13 -33
  12. package/dist/index.d.ts +13 -33
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +6 -37
  15. package/dist/lib/adapters/mysql-adapter.d.ts +5 -2
  16. package/dist/lib/adapters/mysql-adapter.d.ts.map +1 -1
  17. package/dist/lib/adapters/pg-adapter.d.ts +5 -2
  18. package/dist/lib/adapters/pg-adapter.d.ts.map +1 -1
  19. package/dist/lib/agent/manifest.d.ts +27 -10
  20. package/dist/lib/agent/manifest.d.ts.map +1 -1
  21. package/dist/lib/agent/manifest.js +43 -26
  22. package/dist/lib/agent/tool-schemas.d.ts +5 -4
  23. package/dist/lib/agent/tool-schemas.d.ts.map +1 -1
  24. package/dist/lib/agent/tool-schemas.js +5 -5
  25. package/dist/lib/cli/config.d.ts +37 -2
  26. package/dist/lib/cli/config.d.ts.map +1 -1
  27. package/dist/lib/cli/config.js +106 -16
  28. package/dist/lib/cli/mysql-introspect.d.ts +6 -1
  29. package/dist/lib/cli/mysql-introspect.d.ts.map +1 -1
  30. package/dist/lib/cli/mysql-introspect.js +15 -15
  31. package/dist/lib/cli/pg-introspect.d.ts +0 -1
  32. package/dist/lib/cli/pg-introspect.d.ts.map +1 -1
  33. package/dist/lib/cli/pg-introspect.js +2 -13
  34. package/dist/lib/cli/tables-codegen.d.ts +0 -4
  35. package/dist/lib/cli/tables-codegen.d.ts.map +1 -1
  36. package/dist/lib/cli/tables-codegen.js +24 -87
  37. package/dist/lib/db.d.ts +42 -17
  38. package/dist/lib/db.d.ts.map +1 -1
  39. package/dist/lib/db.js +114 -40
  40. package/dist/lib/dialect.d.ts +5 -0
  41. package/dist/lib/dialect.d.ts.map +1 -1
  42. package/dist/lib/dialect.js +3 -0
  43. package/dist/lib/engine/bulk/bulk-delete.d.ts +5 -0
  44. package/dist/lib/engine/bulk/bulk-delete.d.ts.map +1 -1
  45. package/dist/lib/engine/bulk/bulk-delete.js +66 -30
  46. package/dist/lib/engine/bulk/bulk-upsert.d.ts.map +1 -1
  47. package/dist/lib/engine/bulk/bulk-upsert.js +45 -26
  48. package/dist/lib/engine/read-hooks.d.ts +3 -3
  49. package/dist/lib/engine/read-hooks.d.ts.map +1 -1
  50. package/dist/lib/engine/read-hooks.js +3 -3
  51. package/dist/lib/engine/rest/delete.d.ts.map +1 -1
  52. package/dist/lib/engine/rest/delete.js +12 -18
  53. package/dist/lib/engine/rest/get.js +8 -8
  54. package/dist/lib/engine/rest/insert.d.ts.map +1 -1
  55. package/dist/lib/engine/rest/insert.js +31 -18
  56. package/dist/lib/engine/rest/update.d.ts.map +1 -1
  57. package/dist/lib/engine/rest/update.js +34 -17
  58. package/dist/lib/engine/search/aggregations.d.ts +3 -3
  59. package/dist/lib/engine/search/aggregations.d.ts.map +1 -1
  60. package/dist/lib/engine/search/aggregations.js +20 -16
  61. package/dist/lib/engine/search/conditions.d.ts +9 -5
  62. package/dist/lib/engine/search/conditions.d.ts.map +1 -1
  63. package/dist/lib/engine/search/conditions.js +31 -20
  64. package/dist/lib/engine/search/fields.d.ts +44 -11
  65. package/dist/lib/engine/search/fields.d.ts.map +1 -1
  66. package/dist/lib/engine/search/fields.js +93 -27
  67. package/dist/lib/engine/search/join-families.d.ts +7 -7
  68. package/dist/lib/engine/search/join-families.d.ts.map +1 -1
  69. package/dist/lib/engine/search/join-families.js +84 -75
  70. package/dist/lib/engine/search/joins.d.ts +15 -7
  71. package/dist/lib/engine/search/joins.d.ts.map +1 -1
  72. package/dist/lib/engine/search/joins.js +23 -13
  73. package/dist/lib/engine/search/order-by.d.ts +11 -12
  74. package/dist/lib/engine/search/order-by.d.ts.map +1 -1
  75. package/dist/lib/engine/search/order-by.js +24 -28
  76. package/dist/lib/engine/search/search.d.ts.map +1 -1
  77. package/dist/lib/engine/search/search.js +111 -64
  78. package/dist/lib/engine/validate.d.ts +21 -3
  79. package/dist/lib/engine/validate.d.ts.map +1 -1
  80. package/dist/lib/engine/validate.js +106 -16
  81. package/dist/lib/engine/write-helpers.d.ts +69 -16
  82. package/dist/lib/engine/write-helpers.d.ts.map +1 -1
  83. package/dist/lib/engine/write-helpers.js +257 -105
  84. package/dist/lib/errors.d.ts +42 -10
  85. package/dist/lib/errors.d.ts.map +1 -1
  86. package/dist/lib/errors.js +69 -15
  87. package/dist/lib/nullable.d.ts +3 -2
  88. package/dist/lib/nullable.d.ts.map +1 -1
  89. package/dist/lib/nullable.js +14 -5
  90. package/dist/lib/read-access.d.ts +25 -16
  91. package/dist/lib/read-access.d.ts.map +1 -1
  92. package/dist/lib/read-access.js +33 -17
  93. package/dist/lib/schema/bulk-delete.d.ts +13 -7
  94. package/dist/lib/schema/bulk-delete.d.ts.map +1 -1
  95. package/dist/lib/schema/bulk-delete.js +18 -8
  96. package/dist/lib/schema/bulk-upsert.d.ts +3 -3
  97. package/dist/lib/schema/bulk-upsert.d.ts.map +1 -1
  98. package/dist/lib/schema/bulk-upsert.js +9 -14
  99. package/dist/lib/schema/get.d.ts +1 -1
  100. package/dist/lib/schema/get.d.ts.map +1 -1
  101. package/dist/lib/schema/get.js +2 -2
  102. package/dist/lib/schema/helpers.d.ts +41 -23
  103. package/dist/lib/schema/helpers.d.ts.map +1 -1
  104. package/dist/lib/schema/helpers.js +80 -33
  105. package/dist/lib/schema/insert.d.ts +1 -1
  106. package/dist/lib/schema/insert.d.ts.map +1 -1
  107. package/dist/lib/schema/insert.js +12 -20
  108. package/dist/lib/schema/search.d.ts +2 -13
  109. package/dist/lib/schema/search.d.ts.map +1 -1
  110. package/dist/lib/schema/search.js +64 -61
  111. package/dist/lib/schema/update.d.ts +1 -1
  112. package/dist/lib/schema/update.d.ts.map +1 -1
  113. package/dist/lib/schema/update.js +6 -13
  114. package/dist/lib/sql-api.d.ts +47 -25
  115. package/dist/lib/sql-api.d.ts.map +1 -1
  116. package/dist/lib/sql-api.js +70 -27
  117. package/dist/lib/table-helpers.d.ts +92 -14
  118. package/dist/lib/table-helpers.d.ts.map +1 -1
  119. package/dist/lib/table-helpers.js +367 -128
  120. package/dist/lib/tenant.d.ts +16 -22
  121. package/dist/lib/tenant.d.ts.map +1 -1
  122. package/dist/lib/tenant.js +38 -54
  123. package/dist/lib/write-access.d.ts +15 -9
  124. package/dist/lib/write-access.d.ts.map +1 -1
  125. package/dist/lib/write-access.js +12 -4
  126. package/dist/routes/auto/agent-manifest.routes.d.ts +1 -1
  127. package/dist/routes/auto/agent-manifest.routes.js +2 -2
  128. package/dist/routes/auto/bulk-delete.routes.d.ts +2 -2
  129. package/dist/routes/auto/bulk-delete.routes.d.ts.map +1 -1
  130. package/dist/routes/auto/bulk-delete.routes.js +1 -7
  131. package/dist/routes/auto/bulk-upsert.routes.d.ts +2 -2
  132. package/dist/routes/auto/bulk-upsert.routes.d.ts.map +1 -1
  133. package/dist/routes/auto/bulk-upsert.routes.js +2 -2
  134. package/dist/routes/auto/delete.routes.d.ts +2 -2
  135. package/dist/routes/auto/delete.routes.d.ts.map +1 -1
  136. package/dist/routes/auto/delete.routes.js +8 -10
  137. package/dist/routes/auto/get.routes.d.ts +2 -2
  138. package/dist/routes/auto/get.routes.d.ts.map +1 -1
  139. package/dist/routes/auto/get.routes.js +5 -5
  140. package/dist/routes/auto/insert.routes.d.ts +2 -2
  141. package/dist/routes/auto/insert.routes.d.ts.map +1 -1
  142. package/dist/routes/auto/insert.routes.js +1 -7
  143. package/dist/routes/auto/plugin.d.ts +6 -0
  144. package/dist/routes/auto/plugin.d.ts.map +1 -1
  145. package/dist/routes/auto/plugin.js +60 -36
  146. package/dist/routes/auto/route-helpers.d.ts +26 -12
  147. package/dist/routes/auto/route-helpers.d.ts.map +1 -1
  148. package/dist/routes/auto/route-helpers.js +50 -19
  149. package/dist/routes/auto/search.routes.d.ts +2 -2
  150. package/dist/routes/auto/search.routes.d.ts.map +1 -1
  151. package/dist/routes/auto/search.routes.js +36 -24
  152. package/dist/routes/auto/update.routes.d.ts +2 -2
  153. package/dist/routes/auto/update.routes.d.ts.map +1 -1
  154. package/dist/routes/auto/update.routes.js +1 -8
  155. package/dist/routes/sql-api-decorator.d.ts +30 -12
  156. package/dist/routes/sql-api-decorator.d.ts.map +1 -1
  157. package/dist/routes/sql-api-decorator.js +44 -27
  158. package/dist/types/cli.d.ts +17 -6
  159. package/dist/types/cli.d.ts.map +1 -1
  160. package/dist/types/computed.d.ts +1 -1
  161. package/dist/types/computed.d.ts.map +1 -1
  162. package/dist/types/conditions.d.ts +3 -1
  163. package/dist/types/conditions.d.ts.map +1 -1
  164. package/dist/types/db.d.ts +44 -4
  165. package/dist/types/db.d.ts.map +1 -1
  166. package/dist/types/dml.d.ts +26 -17
  167. package/dist/types/dml.d.ts.map +1 -1
  168. package/dist/types/hooks.d.ts +62 -0
  169. package/dist/types/hooks.d.ts.map +1 -0
  170. package/dist/types/hooks.js +1 -0
  171. package/dist/types/join.d.ts +25 -8
  172. package/dist/types/join.d.ts.map +1 -1
  173. package/dist/types/plugin.d.ts +58 -19
  174. package/dist/types/plugin.d.ts.map +1 -1
  175. package/dist/types/plugin.js +2 -0
  176. package/dist/types/request.d.ts +2 -2
  177. package/dist/types/schema.d.ts +3 -3
  178. package/dist/types/schema.d.ts.map +1 -1
  179. package/dist/types/search.d.ts +28 -13
  180. package/dist/types/search.d.ts.map +1 -1
  181. package/dist/types/search.js +2 -1
  182. package/dist/types/table.d.ts +109 -94
  183. package/dist/types/table.d.ts.map +1 -1
  184. package/dist/types/table.js +7 -2
  185. package/dist/types/tenant.d.ts +28 -2
  186. package/dist/types/tenant.d.ts.map +1 -1
  187. package/dist/types/tenant.js +7 -1
  188. package/dist/types/validation.d.ts +69 -13
  189. package/dist/types/validation.d.ts.map +1 -1
  190. package/dist/types.d.ts +1 -0
  191. package/dist/types.d.ts.map +1 -1
  192. package/dist/types.js +1 -0
  193. package/docs/GLOSSARY.md +11 -5
  194. package/docs/adr/0003-bulk-not-transactional.md +2 -1
  195. package/docs/adr/0006-raw-db-errors.md +2 -1
  196. package/docs/adr/0013-sanitized-db-errors.md +2 -1
  197. package/docs/adr/0014-what-follows-a-write-join.md +1 -1
  198. package/docs/adr/0022-stay-on-0x-while-every-consumer-is-first-party.md +88 -0
  199. package/docs/adr/0023-a-write-runs-in-a-transaction-or-not-at-all.md +60 -0
  200. package/docs/adr/0024-the-consumer-maps-driver-codes-through-dberrors.md +78 -0
  201. package/docs/adr/0025-validatebulk-replaces-validate-in-a-bulk-upsert.md +46 -0
  202. package/docs/adr/0026-update-carries-its-primary-key-in-main.md +43 -0
  203. package/docs/adr/0027-the-1-0-contract.md +74 -0
  204. package/docs/adr/0028-select-star-is-the-default-projection.md +64 -0
  205. package/docs/adr/0029-a-write-names-its-child-rows-by-action.md +96 -0
  206. package/docs/adr/0030-a-child-row-is-validated-by-its-own-table.md +117 -0
  207. package/docs/adr/0031-an-insert-excluded-upsert-key-addresses-an-existing-row.md +58 -0
  208. package/docs/adr/0032-tenant-scope-names-schema-fields.md +56 -0
  209. package/docs/adr/README.md +12 -1
  210. package/docs/upgrading/0.x.md +906 -0
  211. package/docs/upgrading/1.0.md +628 -0
  212. package/package.json +4 -5
@@ -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;AA2P3B,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"}
@@ -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,46 +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: the main table's own columns, qualified ("hour".* or the readable list).
52
- // Never a bare `*`: the statement may carry a LEFT JOIN (filtered/ordered joinLeft) or the
53
- // tenant's INNER JOIN, and a bare `*` would hand the joined table's columns to the row.
54
- const readableColumns = readableSelectColumns(tableConf, tableConf.Schema, db);
55
- // 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
56
60
  // here (would require placeholder-aware composition with WHERE values).
57
- let columns = readableColumns;
58
- if (selectComputed?.length) {
59
- const projections = [readableColumns];
60
- for (const name of selectComputed) {
61
- const fn = ownField(tableConf.computedFields, name);
62
- if (!fn)
63
- err400(`Unknown computed field in selectComputed: '${name}'`);
64
- const out = evaluateComputedField(name, fn, tableConf.Schema, db, undefined, `Computed field '${name}' with bound values cannot be used in selectComputed`);
65
- projections.push(`${out.value} AS ${db.qi(name)}`);
66
- }
67
- 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);
68
70
  }
71
+ const columns = projections.join(', ');
69
72
  const rows = await db.select({
70
73
  tableName,
71
74
  columns,
@@ -76,38 +79,74 @@ async function executeMainQuery(db, tableConf, where, values, orderBy, paginator
76
79
  distinct: tableConf.distinctResults,
77
80
  joins: extraJoins.length > 0 ? extraJoins : undefined,
78
81
  });
79
- 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;
80
115
  }
81
- async function buildPagination(db, tableConf, where, values, paginator, extraJoins = [], computeMin, computeMax, computeSum, computeAvg) {
82
- const tableName = tableConf.Schema.tableName;
116
+ async function buildPagination(db, tableConf, where, values, paginator, extraJoins = []) {
117
+ const tableName = tableConf.schema.tableName;
83
118
  const joinClause = extraJoins.length > 0 ? ' ' + extraJoins.join(' ') : '';
84
119
  const countResult = await db.query(`SELECT COUNT(*) as total FROM ${db.qi(tableName)}${joinClause} WHERE ${where}`, values);
85
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(' ') : '';
86
133
  const computed = {};
87
- const computations = [
88
- { key: 'min', field: computeMin, fn: 'MIN' },
89
- { key: 'max', field: computeMax, fn: 'MAX' },
90
- { key: 'sum', field: computeSum, fn: 'SUM' },
91
- { key: 'avg', field: computeAvg, fn: 'AVG' },
92
- ];
93
- for (const { key, field, fn } of computations) {
94
- if (field) {
95
- 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);
96
138
  // The aggregate sits in the SELECT list, before the WHERE values: a computed that
97
139
  // binds parameters cannot be placed here.
98
140
  if (refValues(ref.expr).length > 0) {
99
- 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}`);
100
142
  }
101
- const result = await db.query(`SELECT ${fn}(${renderRef(ref.expr, 1, db)}) as value FROM ${db.qi(tableName)}${joinClause} WHERE ${where}`, values);
102
- 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;
103
147
  }
104
148
  }
105
- return {
106
- total,
107
- pages: Math.ceil(total / paginator.itemsPerPage),
108
- ...(Object.keys(computed).length > 0 ? { computed } : {}),
109
- paginator,
110
- };
149
+ return Object.keys(computed).length > 0 ? computed : undefined;
111
150
  }
112
151
  // ─── searchEngine entrypoint ────────────────────────────────
113
152
  /**
@@ -122,20 +161,20 @@ function assertJoinRequestsAllowed(dbTables, params) {
122
161
  const { tableConf, joinMustExist, joinMultiple, joinGroup, joinLeft } = params;
123
162
  if (joinMustExist)
124
163
  for (const a of Object.keys(joinMustExist))
125
- requireJoin(tableConf, a, false);
164
+ requireJoin(tableConf, a, false, `joinMustExist.${a}`);
126
165
  if (joinMultiple)
127
166
  for (const a of Object.keys(joinMultiple))
128
- requireJoin(tableConf, a, false);
167
+ requireJoin(tableConf, a, false, `joinMultiple.${a}`);
129
168
  if (joinGroup)
130
169
  for (const a of Object.keys(joinGroup))
131
- requireJoin(tableConf, a, false);
170
+ requireJoin(tableConf, a, false, `joinGroup.${a}`);
132
171
  if (joinLeft)
133
172
  for (const a of Object.keys(joinLeft))
134
- requireJoin(tableConf, a, true);
135
- assertJoinFilterKeys(dbTables, tableConf, joinMustExist, true);
136
- assertJoinFilterKeys(dbTables, tableConf, joinMultiple, true);
137
- assertJoinFilterKeys(dbTables, tableConf, joinGroup, true);
138
- 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');
139
178
  }
140
179
  /**
141
180
  * The main table's WHERE builder, plus any JOIN the tenant scope needs.
@@ -147,20 +186,20 @@ function assertJoinRequestsAllowed(dbTables, params) {
147
186
  function buildMainCondition(params) {
148
187
  const { db, tableConf, filters, conditions, tenant } = params;
149
188
  assertFiltersReadable(filters, tableConf);
150
- assertKnownFilterKeys(filters, tableConf.Schema, tableConf);
151
- const condition = tableConf.filters(filters || {}, db.cbDialect);
189
+ assertKnownFilterKeys(filters, tableConf.schema, tableConf);
190
+ const condition = buildTableFilters(tableConf, filters || {}, db.cbDialect);
152
191
  if (filters && tableConf.computedFields) {
153
192
  applyComputedFilters(condition, filters, tableConf, db);
154
193
  }
155
194
  if (conditions?.length) {
156
- applyConditions(condition, conditions, tableConf.Schema, tableConf, db);
195
+ applyConditions(condition, conditions, tableConf.schema, tableConf, db);
157
196
  }
158
197
  const tenantJoins = [];
159
198
  if (tenant?.scope) {
160
199
  const scope = tenant.scope;
161
- condition.append(buildTenantCondition(db, scope, tenant.ids, tableConf.Schema.tableName));
200
+ condition.append(buildTenantCondition(db, scope, tenant.ids, tableConf.schema.tableName));
162
201
  if ('through' in scope) {
163
- tenantJoins.push(buildTenantJoin(db, scope, tableConf.Schema.tableName));
202
+ tenantJoins.push(buildTenantJoin(db, scope, tableConf.schema.tableName));
164
203
  }
165
204
  }
166
205
  return { condition, tenantJoins };
@@ -202,7 +241,8 @@ async function attachJoinResults(result, dbTables, params, main) {
202
241
  }
203
242
  }
204
243
  export async function searchEngine(dbTables, params) {
205
- 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);
206
246
  assertRequestWithinLimits(params);
207
247
  assertJoinRequestsAllowed(dbTables, params);
208
248
  const { condition, tenantJoins } = buildMainCondition(params);
@@ -244,11 +284,15 @@ export async function searchEngine(dbTables, params) {
244
284
  safeOrderBy = bound.emit((startIndex) => validateOrderBy(orderBy, tableConf, db, dbTables, joinGroup, startIndex, tenant)).sql;
245
285
  }
246
286
  const mainValues = bound.snapshot();
247
- 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);
248
291
  let pagination;
249
292
  if (paginator) {
250
- pagination = await buildPagination(db, tableConf, where, whereAndJoinValues, paginator, extraJoinClauses, computeMin, computeMax, computeSum, computeAvg);
293
+ pagination = await buildPagination(db, tableConf, where, whereAndJoinValues, paginator, extraJoinClauses);
251
294
  }
295
+ const computed = await buildComputed(db, tableConf, where, whereAndJoinValues, extraJoinClauses, params.compute ?? {});
252
296
  const result = { main };
253
297
  await attachJoinResults(result, dbTables, params, main);
254
298
  // After the joins, not before: they correlate to the main rows by the values the DB
@@ -256,6 +300,9 @@ export async function searchEngine(dbTables, params) {
256
300
  // have them look for a value no child row carries. `main` is the same array either way,
257
301
  // so the response still carries the hook's mutations.
258
302
  await runAfterRead(db, params.request, main, tableConf, 'search');
303
+ if (computed) {
304
+ result.computed = computed;
305
+ }
259
306
  if (pagination) {
260
307
  result.pagination = pagination;
261
308
  }