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