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
@@ -0,0 +1,906 @@
1
+ # Breaking changes in 0.x (archive)
2
+
3
+ The migration notes of the 0.x releases, from 0.1.3 to 0.5.1, kept as they were written: each
4
+ section shows the API of its own release, and the names it uses may have changed since. To
5
+ upgrade to 1.0, read [1.0.md](./1.0.md), which covers everything
6
+ from 0.5.1 to 1.0.0 in one guide, the never-published 0.6.0 included.
7
+
8
+ ---
9
+
10
+ # Breaking Changes — Join API redesign
11
+
12
+ *Landed in **0.1.3**.*
13
+
14
+ The join API was rewritten to be explicit, alias-based, and to add a real `LEFT JOIN` mode (`joinLeft`) for N:1 relationships. **No backward compatibility** — old names are rejected with 400. Both backend (table configuration) and frontend (request/response shapes) are affected. This document is the single source of truth for migrating either side.
15
+
16
+ ## Why this changed
17
+
18
+ - The old API conflated "filter by child", "fetch children", and "aggregate children" under generic names (`joinFilters`, `joins`, `joinGroups`).
19
+ - There was no way to embed a parent record (N:1) inline in the search results, nor to order/filter the main query by a parent field.
20
+ - The same table could not be joined twice with different semantic roles (e.g. `createdBy` and `updatedBy` both pointing to `user`) because lookup keys collided on `joinSchema.tableName`.
21
+
22
+ The new API addresses all three with a coherent `join*` prefix family and explicit `alias`.
23
+
24
+ ## Naming map
25
+
26
+ | Old (request body) | New (request body) | Direction | Cardinality | What it does |
27
+ |--------------------|--------------------|-----------|-------------|--------------|
28
+ | `joinFilters` | `joinMustExist` | child → main | 1:N | Filters main rows via `EXISTS` subquery |
29
+ | `joins` | `joinMultiple` | child → main | 1:N | Fetches child rows in a side query |
30
+ | `joinGroups` | `joinGroup` | child → main | 1:N | Aggregations on children (SUM/MIN/…) with optional GROUP BY |
31
+ | — | `joinLeft` | parent → main | N:1 | **NEW** real `LEFT JOIN` for embedding the parent |
32
+
33
+ | Old (response) | New (response) |
34
+ |----------------|----------------|
35
+ | `result.joins` | `result.joinMultiple` |
36
+ | `result.joinGroups` | `result.joinGroup` |
37
+ | — | `result.joinLeft` (NEW) |
38
+
39
+ | Old (`buildRelation` last arg) | New (`buildRelation` last arg) |
40
+ |---------------------------------|---------------------------------|
41
+ | `selection?: string` (positional) | `options?: { alias?: string; selection?: string; unique?: boolean }` (all optional; `alias` defaults to `joinSchema.tableName`) |
42
+
43
+ | Old (lookup key inside the body) | New (lookup key inside the body) |
44
+ |-----------------------------------|-----------------------------------|
45
+ | `joinSchema.tableName` | `alias` (declared in `buildRelation`) |
46
+
47
+ The `alias` is also the key used in:
48
+ - Response payloads (`result.joinMultiple.<alias>`, `result.joinLeft.<alias>`, `result.joinGroup.<alias>`)
49
+ - `secondaries` and `deletions` payloads in insert/update/bulk-upsert (`secondaries: { <alias>: [...] }`)
50
+ - Dotted notation in `orderBy` and `conditions`
51
+
52
+ ## buildRelation — new signature
53
+
54
+ ```typescript
55
+ // Options object is optional; every field has a sensible default.
56
+ buildRelation(mainSchema, mainField, joinSchema, joinField);
57
+
58
+ // Or with any subset of options:
59
+ buildRelation(mainSchema, mainField, joinSchema, joinField, {
60
+ alias: 'creator', // optional, default = joinSchema.tableName.
61
+ // Used as the key in request/response/secondaries payloads
62
+ // and in dotted-notation orderBy/conditions.
63
+ selection: '*', // optional, default '*'. Comma-separated list, e.g. 'id,name,email'.
64
+ unique: false, // optional, default false.
65
+ // true → relation is N:1 (each main row has at most one join row).
66
+ // Allowed in joinLeft. Forbidden in joinMultiple/joinMustExist/joinGroup.
67
+ // false → relation is 1:N. Allowed in the other three. Forbidden in joinLeft.
68
+ });
69
+ ```
70
+
71
+ You only need to declare an explicit `alias` when:
72
+ - you join the same table more than once (e.g. `createdBy` and `updatedBy` both pointing to `user`); or
73
+ - you want a name different from the join table's name in the API surface (e.g. `'orders'` instead of `'customer_order'`).
74
+
75
+ If two relations within the same `allowedReadJoins` (or `allowedWriteJoins`) end up resolving to the same alias — explicit or implicit — `defineTable` throws at startup with:
76
+
77
+ ```
78
+ defineTable: duplicate alias '<name>' in allowedReadJoins. When omitted,
79
+ alias defaults to joinSchema.tableName — declare an explicit alias to disambiguate.
80
+ ```
81
+
82
+ If a request hits an alias on the wrong family, the engine returns `400`:
83
+
84
+ ```
85
+ Join alias 'orders' is not declared with unique:true; use joinMultiple/joinMustExist/joinGroup instead
86
+ Join alias 'creator' is declared with unique:true; use joinLeft instead
87
+ Unknown join alias: <name>
88
+ ```
89
+
90
+ ## Request body — by family
91
+
92
+ ### `joinMustExist` (was `joinFilters`)
93
+
94
+ EXISTS-based filter: returns main rows that have at least one matching child.
95
+
96
+ ```json
97
+ {
98
+ "joinMustExist": {
99
+ "orders": {
100
+ "filters": { "status": "completed" },
101
+ "conditions": [{ "field": "total", "method": "isGreater", "params": [50] }]
102
+ }
103
+ }
104
+ }
105
+ ```
106
+
107
+ ### `joinMultiple` (was `joins`)
108
+
109
+ Fetches child rows in a side query; populates `result.joinMultiple.<alias>`.
110
+
111
+ ```json
112
+ {
113
+ "joinMultiple": {
114
+ "orders": {
115
+ "filters": { "status": "completed" },
116
+ "selection": "id,total,status"
117
+ }
118
+ }
119
+ }
120
+ ```
121
+
122
+ `selection` is optional and overrides the default declared in `buildRelation`.
123
+
124
+ ### `joinGroup` (was `joinGroups`)
125
+
126
+ Aggregations on the child table; populates `result.joinGroup.<alias>`.
127
+
128
+ ```json
129
+ {
130
+ "joinGroup": {
131
+ "orders": {
132
+ "aggregations": {
133
+ "by": "status",
134
+ "sum": ["total"],
135
+ "count": ["id"]
136
+ },
137
+ "filters": { "status": "completed" }
138
+ }
139
+ }
140
+ }
141
+ ```
142
+
143
+ ### `joinLeft` (NEW, requires `unique: true`)
144
+
145
+ Real `LEFT JOIN` for N:1 (parent) relationships. The parent rows are returned in `result.joinLeft.<alias>` as a deduplicated array (one entry per distinct parent PK).
146
+
147
+ ```json
148
+ {
149
+ "joinLeft": {
150
+ "creator": {},
151
+ "updater": { "filters": { "active": true }, "selection": "id,name" }
152
+ }
153
+ }
154
+ ```
155
+
156
+ The engine attaches a real `LEFT JOIN <parentTable> AS <alias>` to the main query **only when needed**:
157
+ - when the request includes `filters` or `conditions` on the parent (effectively turns into INNER JOIN behavior on those aliases — main rows whose parent doesn't match are excluded);
158
+ - when `orderBy` uses 2-part dotted notation referring to a parent field (`alias.field`).
159
+
160
+ Otherwise only a side query `WHERE pk IN (distinct fk values)` is issued — no LEFT JOIN, no row duplication. Either way, the response shape is the same.
161
+
162
+ > **Limitation**: `extraFilters` declared via `extendedCondition` on the parent table are **not** applied inside `joinLeft.filters` (only schema fields). The other join families fully support extraFilters.
163
+
164
+ ## orderBy — dotted notations
165
+
166
+ | Form | Allowed alias source | What it does |
167
+ |------|----------------------|--------------|
168
+ | `<field>` | main schema | regular column ordering |
169
+ | `<alias>.<field>` | `joinLeft` (`unique: true` aliases) | orders main query by a parent field via LEFT JOIN |
170
+ | `<alias>.<fn>.<field>` | `joinGroup` (declared in the same body) | orders main query by an aggregation via correlated scalar subquery |
171
+
172
+ Ambiguity: 2-part and 3-part are disambiguated by counting dots. The 2-part is rejected unless the alias is in `joinLeft` allowlist; 3-part is rejected unless the alias is in the request `joinGroup` declaration.
173
+
174
+ ## Response shape
175
+
176
+ ```json
177
+ {
178
+ "table": "session",
179
+ "main": [...],
180
+ "joinLeft": { "creator": [...], "updater": [...] },
181
+ "joinMultiple": { "orders": [...] },
182
+ "joinGroup": { "orders": { "sum": { "total": 300 }, "count": { "id": 2 } } },
183
+ "pagination": { "total": 25, "pages": 3, "paginator": { "page": 1, "itemsPerPage": 20 } }
184
+ }
185
+ ```
186
+
187
+ All four `join*` keys appear only when requested. `pagination` only when `paginator` is provided.
188
+
189
+ Each value in `result.joinLeft.<alias>` is an array of parent rows (one entry per distinct FK in `main`). The client maps a main row to its parent by FK lookup (`main.userId === joinLeft.creator[i].id`).
190
+
191
+ ## Write side — secondaries / deletions
192
+
193
+ `secondaries` and `deletions` payloads in insert/update/bulk-upsert now use the **alias** as key (was `joinSchema.tableName`):
194
+
195
+ ```json
196
+ {
197
+ "main": { "name": "Mario" },
198
+ "secondaries": { "orders": [{ "total": 50 }] },
199
+ "deletions": { "orders": [{ "id": 10 }] }
200
+ }
201
+ ```
202
+
203
+ ## Migration recipes (mechanical)
204
+
205
+ ### 1) Find every `buildRelation` call
206
+
207
+ Old form:
208
+ ```
209
+ buildRelation(M, mF, J, jF)
210
+ buildRelation(M, mF, J, jF, '<sel>') // 5th positional arg = selection
211
+ ```
212
+
213
+ New form (alias is optional, defaults to `J.tableName`):
214
+ ```ts
215
+ // Simplest case — no rewrite needed beyond removing the old positional selection:
216
+ buildRelation(M, mF, J, jF)
217
+
218
+ // Or supply any options you actually need:
219
+ buildRelation(M, mF, J, jF, {
220
+ // alias: 'orders', // omit if joinSchema.tableName is fine as alias
221
+ // selection: 'id, total', // omit for '*'
222
+ // unique: true // ADD if jF is the PK of J (relation is N:1)
223
+ })
224
+ ```
225
+
226
+ **Heuristic for `unique`**: if `joinField` is the PK (or part of the composite PK) of `joinSchema`, the relation is N:1 and you almost certainly want `unique: true` so the alias is usable in `joinLeft`. Mark the call with a `// TODO verify unique:true` and review.
227
+
228
+ **When to add an explicit `alias`**: only if (a) you join the same table multiple times, or (b) you want a friendlier name than the SQL table name (e.g. `orders` vs `customer_order`).
229
+
230
+ ### 2) Rename request keys (regex-replace inside HTTP/JSON bodies and search params)
231
+
232
+ ```
233
+ joinFilters: → joinMustExist:
234
+ joins: → joinMultiple:
235
+ joinGroups: → joinGroup:
236
+ ```
237
+
238
+ ### 3) Rename response accessors
239
+
240
+ ```
241
+ result.joins → result.joinMultiple
242
+ result.joinGroups → result.joinGroup
243
+ body.joins → body.joinMultiple
244
+ body.joinGroups → body.joinGroup
245
+ ```
246
+
247
+ (Plus `result.joinLeft` is now available for the new family.)
248
+
249
+ ### 4) Rename secondaries keys
250
+
251
+ If you used the join table's name as the secondaries key, change it to the new alias:
252
+
253
+ ```diff
254
+ - "secondaries": { "customer_order": [...] }
255
+ + "secondaries": { "orders": [...] }
256
+ ```
257
+
258
+ ### 5) Inspect dotted orderBy/conditions
259
+
260
+ `<table>.<fn>.<field>` still works for joinGroup, but `<table>` must now be the alias declared in `buildRelation`. If the alias differs from the old `tableName`, update the string.
261
+
262
+ If you need to order by a parent field, **add a `joinLeft`-eligible relation** (with `unique: true`) and use 2-part notation `alias.field` (NEW capability — not available before).
263
+
264
+ ## Validation summary (400 responses)
265
+
266
+ The engine rejects, with `statusCode: 400`, any of:
267
+
268
+ - `joinLeft` referencing an alias declared with `unique: false`
269
+ - `joinMultiple`/`joinMustExist`/`joinGroup` referencing an alias declared with `unique: true`
270
+ - request keys referencing an alias not declared in `allowedReadJoins`
271
+ - `orderBy` 2-part `<alias>.<field>` whose alias is not in `joinLeft`-eligible (i.e. `unique:true`) declarations
272
+ - `orderBy` 3-part `<alias>.<fn>.<field>` whose alias or `(fn, field)` pair is not declared in `joinGroup` for the same request
273
+ - `defineTable` with two `allowedReadJoins`/`allowedWriteJoins` entries resolving to the same alias (thrown at startup, not at request time)
274
+
275
+ ---
276
+
277
+ # Breaking Change — computed field placeholders use `?` markers
278
+
279
+ *Landed in **0.1.6**.*
280
+
281
+ `ComputedFieldExpr.expr` must now mark each bound value with `?`. The engine assigns the
282
+ placeholder positions. Writing `$1` (or `db.ph(n)`) inside the expression no longer works and
283
+ is rejected with a descriptive error.
284
+
285
+ ## Why this changed
286
+
287
+ A computed field cannot know its own placeholder offset: the position depends on how many
288
+ values the rest of the query bound before it. The previous contract asked the *consumer* to
289
+ supply "stable indices", which is not knowable — so any computed that declared `values` and
290
+ was used together with another filter produced a query that referenced the wrong parameter:
291
+
292
+ ```
293
+ WHERE ("name" = $1) AND (CASE WHEN "role" = $1 THEN ... END = $3)
294
+ values: ['Mario', 'admin', 500]
295
+ ```
296
+
297
+ `$2` ('admin') was bound but never referenced, while the expression read `$1` ('Mario'). The
298
+ query did not fail — it silently returned the wrong rows.
299
+
300
+ ## Migration
301
+
302
+ ```typescript
303
+ // Before — placeholder guessed by the caller (silently misbound)
304
+ bonus: ({ db, qiCol }) => ({
305
+ expr: `CASE WHEN ${qiCol('role')} = ${db.ph(1)} THEN ${qiCol('salary')} ELSE 0 END`,
306
+ values: ['admin'],
307
+ type: Type.Number(),
308
+ }),
309
+
310
+ // After — `?` marker, position assigned by the engine
311
+ bonus: ({ qiCol }) => ({
312
+ expr: `CASE WHEN ${qiCol('role')} = ? THEN ${qiCol('salary')} ELSE 0 END`,
313
+ values: ['admin'],
314
+ type: Type.Number(),
315
+ }),
316
+ ```
317
+
318
+ Computed fields that declare **no** bound values (the majority: JSON extraction, concat,
319
+ `dateTrunc`, arithmetic) are unaffected and need no change. Their SQL is emitted verbatim, so
320
+ a literal `?` — the PostgreSQL jsonb operator — keeps working. In an expression that *does*
321
+ carry values, escape a literal question mark as `\?`.
322
+
323
+ A mismatch between the number of `?` markers and `values.length` now raises a descriptive
324
+ error instead of producing a wrong query.
325
+
326
+ ## What this unlocks
327
+
328
+ Bound values now work in every position that lands in the `WHERE` clause or in `ORDER BY`,
329
+ including `joinLeft.filters` / `joinLeft.conditions` and `orderBy`, which previously rejected
330
+ them with 400. They remain rejected in `selectComputed`, `computeMin/Max/Sum/Avg`,
331
+ `joinGroup.aggregations.by` and `defaultOrder`, where the expression precedes the `WHERE`
332
+ values in the parameter order.
333
+
334
+ # Breaking Change — by-single-id operations disabled for composite primary keys
335
+
336
+ *Landed in **0.1.11**.*
337
+
338
+ Since **0.1.11**, tables whose `primary` is an array of more than one field no longer expose
339
+ the operations that address a record by a single PK value:
340
+
341
+ - `GET /rest/:table/:id` and `DELETE /rest/:table/:id` are **not registered** (404);
342
+ - `POST /bulk/:table/delete` is **not registered** (404);
343
+ - explicitly listing `get`, `delete` or `bulkDelete` in `ITable.operations` for such a table
344
+ now **throws at startup** with a descriptive error;
345
+ - the programmatic `sqlApi.get/delete/bulkDelete` reject with `400`.
346
+
347
+ Search, insert, update and bulk upsert are unaffected — they already matched every PK column.
348
+
349
+ ## Why this changed
350
+
351
+ These operations matched on the **first** PK column alone. On `primary: ['agentId', 'teamId']`:
352
+
353
+ - `DELETE /rest/t/1` deleted **every** row with `agent_id = 1` — not one record;
354
+ - `GET /rest/t/1` returned an arbitrary row among those sharing `agent_id = 1`;
355
+ - bulk delete removed every row matching each listed first-column value.
356
+
357
+ A single `:id` cannot address a composite key; silently matching a prefix of the key is data
358
+ loss waiting to happen, so the operations are refused loudly instead.
359
+
360
+ ## Who is affected
361
+
362
+ Only consumers with composite-PK tables **and** clients calling get/delete/bulk-delete on
363
+ them. If your composite table's first PK column happens to be unique on its own, these
364
+ endpoints previously behaved correctly for you — they are now gone and you must migrate.
365
+
366
+ ## Migration
367
+
368
+ - **Read one record** → `search` with every PK field in the filters:
369
+
370
+ ```typescript
371
+ await fetch('/auto/search/agent_team', {
372
+ method: 'POST',
373
+ body: JSON.stringify({ filters: { agentId: 1, teamId: 2 } }),
374
+ });
375
+ ```
376
+
377
+ - **Delete one record** → a custom route using the low-level `QueryClient`, matching the
378
+ full key:
379
+
380
+ ```typescript
381
+ import { createQueryClient, pgQueryable } from 'fastify-auto-sqlapi';
382
+
383
+ const db = createQueryClient(pgQueryable(app.pg), 'postgres');
384
+
385
+ app.delete('/agent-team/:agentId/:teamId', async (req) => {
386
+ const { agentId, teamId } = req.params;
387
+ await db.delete('agent_team', { agent_id: agentId, team_id: teamId });
388
+ return { main: { agentId, teamId } };
389
+ });
390
+ ```
391
+
392
+ - **Row removal as part of an edit flow** → `update` on the parent with `deletions` (write
393
+ joins), or bulk upsert — both match every PK column.
394
+
395
+ - **First PK column is truly unique on its own?** Then the composite declaration was
396
+ redundant: declare `primary: 'id'` (single) and keep the second column as a plain field —
397
+ every by-id operation comes back.
398
+
399
+ ---
400
+
401
+ # Breaking Change — unknown filter keys are rejected
402
+
403
+ *Landed in **0.1.14**.*
404
+
405
+ `filters` keys that match nothing are now a `400`, on the main table and on every join family.
406
+ Previously they were dropped without a word.
407
+
408
+ ## Why this changed
409
+
410
+ The engine only ever visited filter keys matching a schema field, an `extraFilters` entry or a
411
+ computed field. Anything else — a typo, a renamed column, a field that exists on the table but
412
+ not on the trimmed Schema a relation was declared with — was never looked at, and the query ran
413
+ as if the filter had not been sent.
414
+
415
+ That fails in the dangerous direction. A rejected filter returns *more* rows than the caller
416
+ asked for, and nothing in the response says so; in an application where filters are also how
417
+ visibility is narrowed, a typo becomes a data exposure. It was also the odd one out: an unknown
418
+ field in `selection`, `conditions`, `orderBy` or a `joinGroup` aggregation has always been
419
+ a 400.
420
+
421
+ ## What changed
422
+
423
+ | Request | Before | After |
424
+ |---|---|---|
425
+ | `filters: { nosuchfield: 'x' }` | `200`, filter ignored | `400 Unknown filter field: nosuchfield` |
426
+ | `joinMultiple.<alias>.filters: { nosuchfield: 1 }` | `200`, filter ignored | `400 Unknown filter field: nosuchfield` |
427
+ | `joinLeft.<alias>.filters: { <extraFilter> }` | `200`, filter ignored | `400 Filter '<key>' is an extraFilter: …` |
428
+ | `filters: { knownField: undefined }` | ignored | ignored (unchanged) |
429
+ | `filters: { knownField: null }` | `IS NULL` | `IS NULL` (unchanged) |
430
+
431
+ Two related fixes ship with it:
432
+
433
+ - The check runs in the engine, not in the route schema, so `sqlApi.search()` behaves the same
434
+ as the HTTP routes. (A closed `additionalProperties: false` schema would not have worked:
435
+ Fastify runs Ajv with `removeAdditional: true`, so it would have *stripped* the key and
436
+ reproduced the same silent behaviour one layer up.)
437
+ - Join filters are validated **before any query runs**. They used to be validated inside the
438
+ side query, which is skipped entirely when the main result set is empty — so the same request
439
+ answered 400 or 200 depending on the data it matched.
440
+
441
+ ## Who is affected
442
+
443
+ Callers that send filter keys the target table does not declare. Over-sending is the common
444
+ case: a frontend that spreads a whole form state into `filters`, or reuses one filter object
445
+ across two tables.
446
+
447
+ ## Migration
448
+
449
+ Send only keys the table declares. `GET /agent/manifest` and the Swagger body schema both list
450
+ them per table (schema fields + `extraFilters` + computed fields).
451
+
452
+ For a form-state object, filter it before sending rather than relying on the server to ignore
453
+ the extras:
454
+
455
+ ```typescript
456
+ const ALLOWED = ['name', 'status', 'createdFrom'] as const;
457
+ const filters = Object.fromEntries(
458
+ Object.entries(formState).filter(([k, v]) => ALLOWED.includes(k) && v !== '')
459
+ );
460
+ ```
461
+
462
+ Passing `undefined` for an absent value is still safe and needs no filtering: only keys with a
463
+ defined value are validated.
464
+
465
+ ## joinLeft and extraFilters
466
+
467
+ `joinLeft.<alias>.filters` used to advertise the parent table's `extraFilters` in Swagger and
468
+ accept them at runtime, applying nothing: `buildLeftJoinClauses` builds its condition inline and
469
+ never runs the target's `extendedCondition`, whose column references cannot be qualified with
470
+ the `LEFT JOIN` alias the parent gets there. They are no longer advertised, and sending one
471
+ returns a `400` naming the reason.
472
+
473
+ Use `joinMustExist` on the same relation when you need an extra filter on the parent — that path
474
+ delegates to the target's own `filters()` and does run `extendedCondition`.
475
+
476
+ ---
477
+
478
+ # Breaking Change — request limits, condition arity and tenant scope inside subqueries
479
+
480
+ *Landed in **0.2.0**.*
481
+
482
+ ## Why this changed
483
+
484
+ Four ways a single search request could do more than the plugin admitted, and one where the
485
+ declared scope was not the enforced one.
486
+
487
+ - `maxItemsPerPage` bounds the **rows a search returns**, not the work done to find them. Every
488
+ dotted `conditions` entry and every 3-part `orderBy` token becomes its own correlated subquery,
489
+ so an uncapped list turned one request into arbitrarily many.
490
+ - `paginator.page` and `paginator.itemsPerPage` are rendered straight into `LIMIT`/`OFFSET`.
491
+ `Paginator` is a compile-time type only, and `sqlApi.search()` is a documented public API a
492
+ consumer may hand an unvalidated querystring — the integer check has to exist at runtime.
493
+ - `key in map` and `map[key]` walk `Object.prototype`, so `constructor`, `toString`, `valueOf`,
494
+ `hasOwnProperty` and `__proto__` satisfied every "is this a known field" check and reached the
495
+ SQL builders, where they rendered as `undefined` or as a column that does not exist.
496
+ - A condition method was dispatched with whatever `params` carried. A missing or wrongly shaped
497
+ one threw a `TypeError` inside the builder, which the error handler can only report as a 500.
498
+ - `tenantScope` was applied to the main query and to the tables a request addressed directly. The
499
+ subqueries and child writes the same request produced carried no scope, so a scoped table was
500
+ still readable and writable through its own relations.
501
+
502
+ ## What changed
503
+
504
+ Every row below answers **400** where it previously did something else.
505
+
506
+ | Input | Rule now | Before |
507
+ |---|---|---|
508
+ | `conditions` | at most **100** entries, per section (top level and each join family) — schema `maxItems` plus an engine backstop | unbounded |
509
+ | `orderBy` | at most **20** comma-separated parts; the request schema also caps the string at **1024** characters | unbounded |
510
+ | `paginator` | `page` and `itemsPerPage` must both be integers `>= 1`, checked before any query runs | any value, rendered into `LIMIT`/`OFFSET` as-is |
511
+ | condition `params` | must be an array; single-value methods need 1 entry, `isBetween`/`isNotBetween` 2, `isIn`/`isNotIn` an array as the first entry | passed to the builder as-is → `TypeError` → 500 |
512
+ | field names | inherited `Object.prototype` keys are not fields, in `filters`, condition fields, `orderBy` and `selectComputed` | resolved as known fields and reached the SQL |
513
+
514
+ The two caps are exported as `MAX_CONDITIONS` and `MAX_ORDER_BY_PARTS`. Both checks live in the
515
+ **engine**, not in the route, which is what covers `sqlApi.search()` — no schema validates a
516
+ programmatic caller. `isNull`/`isNotNull` still take no params, and an explicit `undefined` handed
517
+ to `isIn` remains the documented no-op.
518
+
519
+ And `tenantScope` now follows the request into everything it touches:
520
+
521
+ - **secondaries** — a child row written alongside a main row is scoped and anchored by the child
522
+ table's own `tenantScope`;
523
+ - **`joinLeft`** — the predicate lands in the `ON` clause, so `LEFT` semantics survive;
524
+ - **`joinGroup` aggregation subqueries**, and the 3-part aggregation `orderBy` built on them —
525
+ they counted and summed every tenant's child rows, which disagreed with the scoped
526
+ `result.joinGroup` for the same alias and leaked the existence of the rest.
527
+
528
+ ## Who is affected
529
+
530
+ - **A client that sends more than 100 `conditions` or more than 20 `orderBy` parts.** Generated
531
+ filter UIs are the realistic case: a "select all" that emits one condition per row.
532
+ - **A caller that forwards a raw querystring to `sqlApi.search()`.** `itemsPerPage: '10'` is a
533
+ string and is now a 400: parse the querystring before you forward it.
534
+ - **Conditions assembled programmatically.** One built with a missing `params` used to reach the
535
+ builder; it is now refused up front, with the method named.
536
+ - **Any deployment using `tenantScope` with `secondaries`, `joinLeft` or `joinGroup`.**
537
+ Aggregates that used to count across tenants return smaller numbers, and an ordering built on
538
+ them changes with it. A secondary write that used to land in another tenant's rows is now
539
+ refused. This is the fix, not a regression — but a dashboard whose numbers were computed
540
+ cross-tenant will move.
541
+
542
+ Not affected: requests within the caps, a well-formed integer `paginator`, and any deployment
543
+ without `tenantScope`.
544
+
545
+ ## Migration
546
+
547
+ Split an oversized `conditions` list rather than raising anything — the caps are not configurable:
548
+
549
+ ```typescript
550
+ // Before: one request with 400 conditions
551
+ { conditions: ids.map((id) => ({ field: 'id', method: 'isEqual', params: [id] })) }
552
+
553
+ // After: one condition, one bound array
554
+ { conditions: [{ field: 'id', method: 'isIn', params: [ids] }] }
555
+ ```
556
+
557
+ Parse a querystring before it reaches `sqlApi.search()`:
558
+
559
+ ```typescript
560
+ const paginator = {
561
+ page: Number.parseInt(req.query.page ?? '1', 10),
562
+ itemsPerPage: Number.parseInt(req.query.itemsPerPage ?? '50', 10),
563
+ };
564
+ ```
565
+
566
+ Then re-read any number your product computes from `joinGroup`: if it was collected under a
567
+ tenant scope, it was counting rows that tenant cannot see, and it changes with this release.
568
+
569
+ ---
570
+
571
+ # Breaking Change — the tenant follows the request, not the table it addresses
572
+
573
+ *Landed in **0.2.1**.*
574
+
575
+ `tenantScope` on a table is now enforced even when the request was addressed to a **different**
576
+ table that reaches it through a relation. Previously the tenant was resolved from the addressed
577
+ table alone: if that table declared no `tenantScope`, no predicate was applied anywhere — not to
578
+ it, and not to the scoped tables it joined or wrote into.
579
+
580
+ ## Why this changed
581
+
582
+ A relation in `allowedReadJoins` is a read grant on its target, and one in `allowedWriteJoins` is
583
+ a write grant (see [ADR 0010](../adr/0010-joins-do-not-run-route-guards.md)). `tenantScope`
584
+ was documented as the one request-derived protection that crosses a join — the cap that makes a
585
+ relation safe to declare. It did not cross when the *host* was open:
586
+
587
+ ```typescript
588
+ // shift is public on purpose: everyone may see who works when.
589
+ shift: {
590
+ ...exportTableInfo(SchemaShift),
591
+ allowedReadJoins: [buildRelation(SchemaShift, 'id', SchemaSwapRequest, 'shiftId', { alias: 'swap' })],
592
+ },
593
+ // …but why somebody wants to change the roster is not public.
594
+ shift_swap_request: {
595
+ ...exportTableInfo(SchemaSwapRequest),
596
+ tenantScope: { column: 'agent_id' },
597
+ },
598
+ ```
599
+
600
+ ```sql
601
+ -- POST /search/shift { "joinMultiple": { "swap": {} } } — before
602
+ SELECT … FROM shift_swap_request WHERE (shift_id IN ($1))
603
+ -- after
604
+ SELECT … FROM shift_swap_request WHERE (shift_id IN ($1) AND (agent_id IN ($2)))
605
+ ```
606
+
607
+ Every scoped row of the neighbour was readable through the open host, and writable through it as
608
+ a secondary. The declaration said "scoped"; the deployment was not. Nothing in the response said
609
+ so, which is the dangerous direction — the same reasoning as unknown filter keys above.
610
+
611
+ ## What changed
612
+
613
+ - `TenantContext.scope` is now **optional**. `ids` is request-level and travels with the request;
614
+ `scope` is table-level and absent when the addressed table declares none. Absent `scope` means
615
+ "no filter on *this* table", never "no tenant" — related tables still enforce their own.
616
+ - `getTenantId` is now called for a request addressed to an unscoped table **when one of that
617
+ table's declared relations points at a scoped table**. It is still not called when nothing
618
+ scoped is in reach, so genuinely tenant-free routes are unaffected. Reach is one level: joins
619
+ and secondaries resolve from the addressed table's own relations and never chain further.
620
+
621
+ ## Who is affected
622
+
623
+ - **You declare `tenantScope` on a table that another table joins or writes into, where that
624
+ other table has no scope of its own.** Those requests now return fewer rows and can now answer
625
+ `403`. This is the fix: the rows were never yours to serve. Check any UI that displayed them.
626
+ - **Your `getTenantId` assumes an authenticated request.** It now runs on routes that previously
627
+ skipped it — a public host with a scoped neighbour. A body like
628
+ `(request) => request.user.organizationId` throws there, turning a `200` into a `500`.
629
+ - **You read `tenant.scope` in TypeScript** (custom routes using the exported `TenantContext`).
630
+ Its type is now `TenantScope | undefined`.
631
+
632
+ Not affected: tables with no `tenantScope` anywhere in reach, deployments without `getTenantId`,
633
+ admins (`getTenantId` → `null`), and every table that already declared its own scope — their SQL
634
+ is unchanged.
635
+
636
+ ## Migration
637
+
638
+ Make `getTenantId` total. It already had to return `null` for admins, so the null case exists:
639
+
640
+ ```typescript
641
+ // Before — throws on a route that never had a user
642
+ getTenantId: (request) => request.user.organizationId,
643
+
644
+ // After — an absent user is simply an unscoped caller
645
+ getTenantId: (request) => request.user?.organizationId ?? null,
646
+ ```
647
+
648
+ Then decide, for each open table that relates to a scoped one, whether the relation was meant to
649
+ be a read grant at all. If it was not, remove it from `allowedReadJoins` — a relation is the
650
+ grant, and the scope is only the cap on it.
651
+
652
+ ---
653
+
654
+ # Breaking Change — secondaries run the child table's `beforeInsert`
655
+
656
+ *Landed in **0.2.2**.*
657
+
658
+ ## Why this changed
659
+
660
+ `processSecondaries` consulted the child table's configuration for its `excludeFromCreation` and
661
+ its `tenantScope`, but skipped its `beforeInsert`. A child table whose hook *transformed* a value
662
+ rather than adding one — encrypting a column, normalising a unit — therefore stored the raw
663
+ client value whenever its rows arrived as another table's secondaries, and correctly only through
664
+ its own route. Nothing failed at write time; the row read back as garbage later. See
665
+ [ADR 0014](../adr/0014-what-follows-a-write-join.md).
666
+
667
+ ## What changed
668
+
669
+ - A child table's **`beforeInsert` now runs** for rows written as `secondaries`, after that
670
+ table's `excludeFromCreation` strip and before the engine's FK auto-fill (which stays
671
+ authoritative). The child's `validate` and `afterInsert` still do not run.
672
+ - The **get response schema honours `readExclude`**: it previously advertised fields the engine
673
+ never selects. `schemaOverrides` is unchanged — still write bodies only.
674
+ - The **update body now requires the primary key**. It identifies the row (`PUT /rest/:table`
675
+ carries it in `main`), but the generated PK field is `Optional` and that modifier reached the
676
+ update body unchanged, so a request omitting `main.id` built its `WHERE` on `undefined`
677
+ instead of being rejected with a 400.
678
+
679
+ ## Who is affected
680
+
681
+ - **A table of yours declares `beforeInsert` and is also a write-join target.** The hook now runs
682
+ on that path. If it was written assuming the table's own route — reading `req.params`, counting
683
+ invocations, calling an external service per record — it now runs where it did not before. It
684
+ receives the transaction connection, so what it writes rolls back with the host's write.
685
+ - **You send an update without `main.<pk>`.** It never identified a row — the `WHERE` was built
686
+ on `undefined` — and is now a 400.
687
+ - **A client of yours read a `readExclude`d field out of the get route's Swagger.** It was never
688
+ returned; only the documentation claimed it.
689
+
690
+ Not affected: tables with no `beforeInsert`, or none that are write-join targets. Nothing about
691
+ `schemaOverrides` changes.
692
+
693
+ ## Migration
694
+
695
+ For a `beforeInsert` that must keep running on the table's own route only, guard on the context
696
+ it needs rather than on the path:
697
+
698
+ ```typescript
699
+ beforeInsert: async (db, req, record) => {
700
+ record.slug = slugify(record.name); // shaping: correct on both paths, leave it
701
+ if (req.routeOptions?.url?.startsWith('/rest/')) await notify(record); // side effect: narrow it
702
+ },
703
+ ```
704
+
705
+ ---
706
+
707
+ # Breaking Change — the route URL is the `DbTables` key
708
+
709
+ *Landed in **0.3.0**.*
710
+
711
+ ## Why this changed
712
+
713
+ The documentation always said *"the route URL name is the key you use in the `dbTables`
714
+ record"*, and everything but the URL agreed: the handler, `operations`, `onRequests`, the
715
+ Swagger tags and the agent manifest all resolved the table config by its key. The URL alone was
716
+ built from `Schema.tableName`. Two consequences:
717
+
718
+ - **Several table configs over one physical table could not coexist.** Exposing
719
+ `conversation` once for its owner and once for whoever holds a share link — each key with its
720
+ own `operations`, guards and joins — put both on `/search/conversation`, and Fastify refused
721
+ to start: `Method 'POST' already declared for route '/search/conversation'`.
722
+ - **A renamed key was served under the wrong name.** `{ orders: TableCustomerOrder }` started
723
+ fine, but answered on `/search/customer_order` while the manifest told agent clients to call
724
+ `orders`.
725
+
726
+ ## What changed
727
+
728
+ - Every auto route is named after the key: `/search/<key>`, `/rest/<key>`, `/rest/<key>/:id`,
729
+ `/bulk/<key>`, `/bulk/<key>/delete`.
730
+ - The search response's `table` is the key, so it matches the URL that was called and the
731
+ manifest entry.
732
+ - SQL is unchanged: it still targets `Schema.tableName`.
733
+
734
+ ## Who is affected
735
+
736
+ - **A `DbTables` key of yours differs from its schema's `tableName`.** Its routes move from the
737
+ table name to the key, and `table` in its search responses changes the same way.
738
+
739
+ Not affected: configs generated by `sqlapi-generate-tables`, whose keys are the table names, and
740
+ any hand-written config that kept that convention.
741
+
742
+ ## Migration
743
+
744
+ Either call the new URLs, or rename the key back to the table name to keep the old ones:
745
+
746
+ ```typescript
747
+ // before: routes answered on /search/customer_order
748
+ export const dbTables: DbTables = { orders: TableCustomerOrder };
749
+
750
+ // keep the old URLs
751
+ export const dbTables: DbTables = { customer_order: TableCustomerOrder };
752
+ ```
753
+
754
+ A client that read `table` from a search response to recover the physical table name should
755
+ use the key it called instead — that is now what `table` returns.
756
+
757
+ ---
758
+
759
+ # Breaking Change — an upsert targets a unique key verified at startup
760
+
761
+ *Landed in **0.4.0**.* Decision and rationale: [ADR 0021](../adr/0021-upsert-targets-a-verified-unique-key.md).
762
+
763
+ ## Why this changed
764
+
765
+ `upsertMap` accepted any column list, and the dialects disagreed on what it meant:
766
+
767
+ - **No unique index on the declared columns**: PostgreSQL failed every write; MySQL never
768
+ conflicted and inserted duplicates, silently.
769
+ - **MySQL `ON DUPLICATE KEY UPDATE` fires on any unique index**, not on the declared key: a row
770
+ carrying another row's unique value (an `email`, an `id`) updated *that* row, silently, where
771
+ PostgreSQL refused the write.
772
+ - **A natural-key upsert on MySQL returned wrong PKs** for the rows it updated, and secondaries
773
+ were attached to them.
774
+
775
+ ## What changed
776
+
777
+ - **The generated Schema carries `uniqueKeys`**, the table's unique keys other than the
778
+ primary key — emitted even when empty. Partial, expression and (MySQL) prefix indexes are not
779
+ keys an upsert can target and are left out.
780
+ - **`defineTable` refuses an `upsertMap` rule that is not exactly the Schema's `primaryKey` or
781
+ one of its `uniqueKeys`** (same fields, any order). This includes rules on write-join child
782
+ schemas — the child still needs no `defineTable` of its own. A rule on a view is refused.
783
+ - **Every upserted row must carry its key — `400` otherwise**: a natural key must be present
784
+ and not null; the primary key may be absent altogether (a plain insert with a generated key)
785
+ but not partial or null. Two rows of one request with the same key are a `400` too.
786
+ - **MySQL and MariaDB upsert by key** — probe, insert, update — instead of
787
+ `ON DUPLICATE KEY UPDATE`. A row whose other unique column belongs to another row is now a
788
+ database error (sanitized 500) on every dialect, never a write to that other row.
789
+
790
+ ## Who is affected
791
+
792
+ - **Schemas generated before this release** used with a natural-key rule (`['email']`,
793
+ `['customerId', 'tag']` that is not the PK…): `defineTable` throws until they are
794
+ regenerated. Rules on the primary key keep working — `primaryKey` was already generated.
795
+ - **A rule on columns without a unique index**: it never worked on PostgreSQL, and on MySQL it
796
+ was inserting duplicates. `defineTable` now throws.
797
+ - **Clients sending upsert rows without their key**, or twice the same key in one request:
798
+ `400`.
799
+ - **MySQL/MariaDB**: an upsert costs two to three statements per chunk instead of one.
800
+ - **A driver configured without `CLIENT_FOUND_ROWS`** (MySQL/MariaDB): the upsert checks the
801
+ rows its UPDATE matched, and without that flag the driver reports changed rows instead —
802
+ a row re-sent unchanged would be reported as missing. `mysql2` sets the flag by default.
803
+ - **Code using the exported `SqlDialect` type or `getDialect()` for upserts**: `upsertSql()`
804
+ and `upsertUpdateSet()` are gone. They are replaced by `onConflict?: { sql(), updateSet() }`,
805
+ present on PostgreSQL only — its absence is what tells MySQL/MariaDB to upsert by key.
806
+ A custom `SqlDialect` implementation no longer compiles until it drops the two methods.
807
+
808
+ ## Migration
809
+
810
+ 1. Regenerate the schemas: `npx sqlapi-generate-schema`. Each Schema now ends with
811
+ `uniqueKeys: [...]`.
812
+ 2. Start the application: a rule that is not a unique key fails with a message listing the
813
+ keys the table has, e.g.
814
+ `upsertMap rule on 'customer' (email) is not a unique key of the table. An upsert must target exactly one: (id) primary key (ADR 0021).`
815
+ Either add the unique index the rule assumed, or point the rule at an existing key.
816
+ 3. Make sure every upsert row carries its key. For a write-join child keyed on
817
+ `(parentId, lang)`, the FK is filled from the parent — the client sends `lang`.
818
+ 4. If you use `SqlDialect` directly: build an upsert through `QueryClient.insertOrUpdate` /
819
+ `bulkInsertOrUpdate`, which pick the right strategy per dialect, rather than from the
820
+ dialect's clause. The PostgreSQL clause, if you need it, is now
821
+ `getDialect('postgres').onConflict!.sql(keys, getDialect('postgres').onConflict!.updateSet(fields, keepAsIs))`
822
+ — `updateSet` returns `''` when nothing is left to update, as before. A custom dialect
823
+ implements `onConflict` only when its upsert syntax names its conflict target; otherwise it
824
+ leaves it out and gets the upsert by key.
825
+
826
+ ```typescript
827
+ // before
828
+ const dialect = getDialect('postgres');
829
+ dialect.upsertSql(quotedKeys, dialect.upsertUpdateSet(fields, conflictKeys));
830
+
831
+ // after
832
+ const { onConflict } = getDialect('postgres');
833
+ onConflict!.sql(quotedKeys, onConflict!.updateSet(fields, conflictKeys));
834
+ ```
835
+
836
+ ---
837
+
838
+ # Breaking Change — `min`, `max` and `avg` of a main row without children are NULL
839
+
840
+ *Landed in **0.4.1**.*
841
+
842
+ ## Why this changed
843
+
844
+ `orderBy` and HAVING-style conditions on `<alias>.<fn>.<field>` run a correlated subquery per
845
+ main row, and every aggregate was wrapped in `COALESCE(…, 0)`. Over no child rows, that 0 is
846
+ the right answer for `count`, `distinctCount` and `sum`, but `min`, `max` and `avg` have no
847
+ value at all:
848
+
849
+ - **PostgreSQL**: on a text, char, date or timestamp column the request failed with a 500,
850
+ `COALESCE types … and integer cannot be matched`.
851
+ - **MySQL/MariaDB**: no error, but those mains were compared as `0` — `max(orderDate) <
852
+ '2026-03-01'` matched every main without children.
853
+ - **Both, numeric columns**: a 0 that no child row holds decided the ordering and conditions.
854
+
855
+ ## What changed
856
+
857
+ - `count`, `distinctCount` and `sum` over no rows are still 0.
858
+ - `min`, `max` and `avg` over no rows are NULL. In `orderBy` they sort where the database puts
859
+ NULL (PostgreSQL: last in ASC, first in DESC; MySQL/MariaDB: first in ASC, last in DESC). In
860
+ conditions they fail every comparison; `isNull` / `isNotNull` select them.
861
+ - "Without children" includes children all excluded by the joinGroup's own `filters` /
862
+ `conditions`.
863
+ - `result.joinGroup` is unchanged: it was never coalesced.
864
+
865
+ ## Who is affected
866
+
867
+ Clients that order or filter by `min`, `max` or `avg` of a **numeric** column on tables where
868
+ some main rows have no children:
869
+
870
+ - `orderBy=orders.min.total ASC` on PostgreSQL: those mains move from first to last.
871
+ `… DESC`: from last to first. On MySQL/MariaDB the order is unchanged (NULL sorts as the
872
+ smallest value, where the 0 was for non-negative columns).
873
+ - `conditions: [{ field: 'orders.max.total', method: 'isLess', params: [5] }]`: those mains
874
+ no longer match. `isGreater` with a negative value, `isEqual` with 0 and similar change the
875
+ same way.
876
+
877
+ ## Migration
878
+
879
+ - To drop mains without children from a result, add `{ field: 'orders.count.id', method:
880
+ 'isGreater', params: [0] }` (or `isNotNull` on the aggregate).
881
+ - To list only them, use `isNull` on the aggregate, or `isEqual 0` on `count`.
882
+ - Conditions are ANDed, so "below 5 **or** no children" is no longer one request: run the
883
+ `isNull` search separately, or compare against a `count` instead where that expresses the
884
+ same thing.
885
+
886
+ # Breaking Change — Node.js 22 or newer is required
887
+
888
+ *Landed in **0.5.0**.*
889
+
890
+ ## Why this changed
891
+
892
+ `engines.node` said `>=18`, but no Node version other than 24 was tested, and the promise
893
+ was already wrong: Fastify 5, a required peer dependency, supports Node 20 and later only.
894
+ Node 18 and Node 20 are both end-of-life, so the floor now starts at the oldest maintained
895
+ LTS line, and CI runs the full gate on Node 22, 24 and 26 to keep that promise checked.
896
+
897
+ ## Who is affected
898
+
899
+ Deployments still running Node 18 or 20. Nothing in the API, the request/response shapes
900
+ or the table configuration changes.
901
+
902
+ ## Migration
903
+
904
+ Upgrade the runtime to Node 22 or newer. npm only warns on an `engines` mismatch (it fails
905
+ with `engine-strict=true`), so a deployment on an older Node may keep installing, but it is
906
+ no longer supported or tested.