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
package/CHANGELOG.md CHANGED
@@ -2,12 +2,241 @@
2
2
 
3
3
  All notable changes to this project are documented here. This project follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and adheres to
5
- [Semantic Versioning](https://semver.org/) — with the caveat that while the version is
6
- `0.x`, breaking changes may land in a minor release.
5
+ [Semantic Versioning](https://semver.org/): from 1.0, a breaking change bumps the major
6
+ ([ADR 0027](./docs/adr/0027-the-1-0-contract.md)). Through 0.x, a breaking change bumped the
7
+ minor and never the patch ([ADR 0022](./docs/adr/0022-stay-on-0x-while-every-consumer-is-first-party.md)).
7
8
 
8
- Migration instructions for breaking changes live in **[BREAKING_CHANGES.md](./BREAKING_CHANGES.md)**.
9
+ Migration instructions, one guide per release line, indexed in
10
+ [BREAKING_CHANGES.md](./BREAKING_CHANGES.md): **[docs/upgrading/1.0.md](./docs/upgrading/1.0.md)**
11
+ from 0.5 to 1.0, [docs/upgrading/0.x.md](./docs/upgrading/0.x.md) for the 0.x releases.
9
12
 
10
- ## [Unreleased]
13
+ ## [1.0.0] - 2026-11-18
14
+
15
+ The API made coherent in one breaking release: one name and one place for each concept, one
16
+ shape for each result, every retired key refused rather than ignored. **Upgrading from 0.5:
17
+ [docs/upgrading/1.0.md](./docs/upgrading/1.0.md)**, one guide for the whole release. The contract
18
+ of 1.0 — what is public, how it changes — is [ADR 0027](./docs/adr/0027-the-1-0-contract.md),
19
+ which supersedes ADR 0022.
20
+
21
+ 1.0.0 follows 0.5.1. The 0.6.0 prepared after it, TypeBox 1.x and a first cleanup of the public
22
+ names, was never published: its changes are listed here and covered by the same guide.
23
+
24
+ ### Added
25
+
26
+ - **`extendedCondition` receives `{ col }`**, its third argument: `col(field)` is the column
27
+ quoted for the dialect and qualified for the statement the condition lands in — the table in
28
+ the main search and in a side query, the alias inside a join's correlated subquery. A bare
29
+ `Schema.col()` was unquoted (a camelCase column failed on PostgreSQL) and a table-name prefix
30
+ bound to the outer row inside a self-relation's subquery. Typed by the schema's fields; a
31
+ name that is not one throws. Type `ExtendedConditionContext`.
32
+ - **`replace` in a write request** ([ADR 0029](./docs/adr/0029-a-write-names-its-child-rows-by-action.md)):
33
+ the complete set of child rows of an alias — the rows sent are upserted, every other child
34
+ row of the main row is deleted and reported under `deletions`, in the response and to
35
+ `afterInsert`/`afterUpdate`. `[]` removes them all. Needs the relation's `upsertKey`, which
36
+ the manifest now reports on each write join. In a bulk upsert, an item with a `replace` runs
37
+ its child rows in a transaction of its own.
38
+ - **The agent manifest reports a table's own `upsertKey`** (JSON and markdown, with its rule in
39
+ the legend): what every row of an insert or bulk upsert must carry, and that a
40
+ `serverGenerated` key only names an existing row. It already reported a write join's.
41
+ - **Every type a public signature names is exported**: `ApiReply`, `BuildRelationOptions`,
42
+ `JoinFetchRequest`, `JoinRefFilter`, `BulkUpsertOptions`, `ManifestField`, `ManifestJoin`,
43
+ `ValidatorResult` (what `validate` returns), `PrimaryKeyValue`, `WriteJoinSections`, and the
44
+ adapters' parameter types `PgQueryable` and `MysqlQueryable`, which a consumer could only
45
+ reach through another type before. The dependency types the public signatures name are
46
+ re-exported too, so a consumer needs no direct dependency on them: `TSchema`, `TObject`,
47
+ `TUnsafe` (TypeBox) and `ConditionValueOrUndefined` (node-condition-builder).
48
+ - **A secondary's `beforeInsert` sees the FK to the main row** already filled in, over the
49
+ client's value; the engine still fills it again after the hook, which cannot move it.
50
+ - **Bulk delete on a composite primary key.** `POST /bulk/:table/delete` and
51
+ `sqlApi.bulkDelete()` take one object per key, `{ ids: [{ postId: 1, tagId: 2 }] }`, matched
52
+ on every key column; the hooks receive the same objects, typed `PrimaryKeyValue`. A link
53
+ table (M:N) no longer needs a custom route. `get` and `delete` by `:id` stay unavailable on
54
+ such a table.
55
+ - **`dbErrors`**: driver error codes the consumer answers with an HTTP status and a code of
56
+ its own instead of the sanitized 500, keyed by `err.code` as the driver raises it:
57
+ `dbErrors: { '23505': { status: 409, code: 'duplicate' } }` (`'ER_DUP_ENTRY'` on
58
+ MySQL/MariaDB). The answer keeps the error envelope with `fields: [{ path: '', code }]`, and
59
+ no driver detail. The plugin ships no mapping (ADR 0024). An invalid entry fails
60
+ registration. Exported type `DbErrorMapping`.
61
+ - **One error envelope**, `{ statusCode, error, message, requestId, fields? }`, for every error
62
+ the routes return. `error` is the reason phrase, `requestId` the log's `reqId`, and every 400
63
+ carries `fields: [{ path, code, message }]` — the engine's rejections included, with a stable
64
+ code and the request path of the offending value. Codes and the path grammar are listed in
65
+ AGENTS_FRONTEND.md. `httpError(400, msg, { code, path })` is exported, for hooks.
66
+ - **Plugin option `operations`**: the operations a registration exposes, intersected with each
67
+ table's own. The agent manifest of the registration and `agentToolSchemas(…, { operations })`
68
+ follow it.
69
+ - **Plugin option `decorate`** (default `true`): `false` for every registration but the one
70
+ owning `app.sqlApi`.
71
+ - **`select` in search**: the fields to project, schema and computed alike, over HTTP and in
72
+ `sqlApi.search()`. The primary key, the keys the requested joins correlate on and, with
73
+ `distinctResults`, the ORDER BY fields are always projected. `'*'` stands for every readable
74
+ field: `['*', 'fullName']` adds a computed field without listing the others.
75
+ - **`compute` in search**: `{ min, max, sum, avg, count, distinctCount }`, several fields per
76
+ function, answered in a top-level `computed` over every matching row, with or without a
77
+ paginator.
78
+ - **`action: 'inserted' | 'updated'`** on the single insert response and on every item of the
79
+ bulk upsert response. Exported types `WriteAction`, `WrittenRow`.
80
+ - **`upsertKey`** on the table (main rows) and on `buildRelation` (the secondaries of a write
81
+ join), verified at startup (ADR 0021).
82
+ - **`target` on `buildRelation`**: the `dbTables` key whose config governs the joined table,
83
+ required when that table sits under several keys.
84
+ - **`TENANT_ADMIN`**: what `getTenantId` returns for unrestricted access. Exported types
85
+ `TenantAdmin`, `TenantResolution`, `GetTenantId`.
86
+ - **Hook context types**: `HookContext`, `WriteRecord`, `WriteHookContext`,
87
+ `AfterInsertContext`, `AfterUpdateContext`, `AfterReadContext`, `ReadSource`,
88
+ `DeleteHookContext`, `BulkDeleteHookContext`, `ValidateContext`, `BulkValidateContext`.
89
+ - **`QueryClient.supportsTransactions`**, and `Date` as a QueryClient value.
90
+ - **`createSqlApi` infers the table names** of the `dbTables` it is given: a misspelled one
91
+ fails at compile time.
92
+ - **Types** `TableDefinition` (what `defineTable` takes), `ValidationField`, `ComputeFn`,
93
+ `ComputeRequest`, `ComputedResult`, `RowsByAlias`, `SqlApiBulkDeleteParams`, `CliConfig`.
94
+ - **ADRs 0023–0032**: a write runs in a transaction or not at all; `dbErrors`; `validateBulk`
95
+ replaces `validate` in a bulk upsert; an update carries its primary key in `main`; the 1.0
96
+ contract; `*` is the default projection
97
+ ([0028](./docs/adr/0028-select-star-is-the-default-projection.md)); a write names its child
98
+ rows by action; a child row is validated by its own table; an insert-excluded upsert key
99
+ addresses an existing row; tenant scope names schema fields.
100
+ - **`tenantScope` names schema fields**, like every other key of a table config
101
+ ([ADR 0032](./docs/adr/0032-tenant-scope-names-schema-fields.md)): `column`, `anyOf` and
102
+ `through.localField` resolve through the table's schema, the indirect `column` and
103
+ `through.foreignField` through `through.schema`. The column of a field is accepted as written,
104
+ so a scope naming columns keeps working; any other name fails `defineTable` at startup, where a
105
+ misspelling used to fail as a 500 on the first query. The startup error for a field name is gone,
106
+ and the CLI `tables` template, which already wrote `localField` as a field, is now correct.
107
+
108
+ ### Changed
109
+
110
+ Every entry below is breaking; [docs/upgrading/1.0.md](./docs/upgrading/1.0.md) has the migration for each.
111
+
112
+ - **TypeBox 1.x** ([`typebox`](https://www.npmjs.com/package/typebox)) replaces
113
+ `@sinclair/typebox` 0.34. `Type` and `Static` re-exported by this package now come from it.
114
+ Code that imports `Type` from `fastify-auto-sqlapi`, as the generated schema files do, needs
115
+ no change. Schemas built with `@sinclair/typebox` directly must move to `typebox` 1.x, or
116
+ their `Type.Optional` fields silently become required. Schemas from any `typebox` 1.x copy,
117
+ such as the one `@fastify/type-provider-typebox` 6 brings in, now mix freely with this
118
+ package's.
119
+ - **Plugin and `createSqlApi`**
120
+ - The plugin option `DbTables` is `dbTables`.
121
+ - `getTenantId` returning `null`/`undefined` is a 401 on every table with a tenant scope in
122
+ reach; unrestricted access is `TENANT_ADMIN`.
123
+ - A second registration in the same scope, or one over an application `sqlApi`, fails
124
+ unless it passes `decorate: false`.
125
+ - The plugin is the one way to mount the routes: the route plugins and `setupSwagger` are no
126
+ longer exported.
127
+ - `createSqlApi` takes the dialect from a QueryClient; a `dialect` option beside one throws.
128
+ - A write needs a `Queryable` with `connect()`: without it, inserts and updates throw instead
129
+ of running unprotected (ADR 0023).
130
+ - **Table configuration**
131
+ - `defineTable({ primary, schema, extraFilters, extendedCondition, … })` replaces the spread
132
+ of `exportTableInfo()`; the config carries `schema`, not `Schema`.
133
+ - `allowedReadJoins` / `allowedWriteJoins` are `readJoins` / `writeJoins`.
134
+ - `excludeFromCreation` is `insertExclude`, aligned with `readExclude` / `writeExclude`. Same
135
+ behaviour; the table generator writes the new name.
136
+ - The type `ITable` is `TableConfig`, as the glossary calls the concept.
137
+ - `upsertMap` and `buildUpsertRule(s)` are replaced by `upsertKey`.
138
+ - `defaultOrder` has the 1-part `orderBy` grammar, checked at startup; no raw SQL.
139
+ - `buildRelation({ selection })` is `{ select: [...] }`, checked against the joined schema.
140
+ - A relation over a table exposed under several keys must name its `target`.
141
+ - A `tenantScope` name that is neither a field of its schema nor the column of one fails at
142
+ startup; it was taken as a column (ADR 0032).
143
+ - Every pre-1.0 key throws at startup, naming its replacement.
144
+ - **Hooks**
145
+ - Every hook and validator receives one context object, `{ db, req, …data }`; `req` may be
146
+ `undefined`.
147
+ - `validate` and `validateBulk` return `{ path, code }` objects; tuples, a `message`, or a
148
+ result that is not an array are a programming error. `ValidationError` is gone.
149
+ - `ValidationField.message` is optional: absent on the fields a validator returned and on a
150
+ `dbErrors` answer, where it only repeated the code or the reason phrase.
151
+ - `beforeInsert` and `afterInsert` may return `void`, like every other hook; the secondaries
152
+ and deletions given to `afterInsert` and `afterUpdate` are typed `RowsByAlias`, not
153
+ `unknown`. Type-level only.
154
+ - **`sqlApi` and the QueryClient**
155
+ - `sqlApi.insert` / `update` take `{ main, … }`, the HTTP body; `record` throws.
156
+ - `sqlApi.bulkDelete` takes `{ ids }`.
157
+ - An unknown table in `sqlApi` throws an `Error`; it was a 400 `unknown_table`.
158
+ - The QueryClient upserts with `upsert` and `bulkUpsert`, both answering `{ pk, action }`;
159
+ `bulkUpsert` takes `{ chunkSize, immutableCols }`. `insertOrUpdate`,
160
+ `bulkInsertOrUpdate` and their `*WithAction` versions are gone.
161
+ - **Exports**: the package entry exports the public API only. Gone: the engines, the schema
162
+ builders, `SearchTableQuery` and `SearchTableQueryString`, the naming helpers,
163
+ `getDialect`/`SqlDialect`, `resolveTenant`/`TenantContext`, the engine parameter types,
164
+ `ColumnInfo`, `TableMap`, and `escapeIdent`, which escaped PostgreSQL identifiers only and was
165
+ wrong on MySQL (`db.qi()` replaces it). `SqlApiConfig` is `CliConfig`.
166
+ - **CLI**
167
+ - `sqlapi-generate-schema` connects through one URL whose scheme names the dialect, from
168
+ `--url`, `connection` in `sqlapi.config`, or `DATABASE_URL`, in this order; the `.env` of
169
+ the current directory is loaded before the config. `POSTGRES_*` / `MYSQL_*` are no longer
170
+ read, and with no URL the run fails: it used to fall back to the library's test database.
171
+ - `dialect` and `envFile` in the config and `--dialect` are refused, as is any unknown key or
172
+ option; a config that fails to load fails the run instead of falling back to the defaults.
173
+ - The schema CLI prints the database it introspects, password masked; MySQL credentials in
174
+ the URL are percent-decoded.
175
+ - **HTTP**
176
+ - The search request travels in the body only: `orderBy`, `page`, `itemsPerPage` and
177
+ `computeMin|Max|Sum|Avg` in the querystring are a 400 `retired_key`.
178
+ - `select` replaces `selectComputed` and a join's `selection`, both a 400 `retired_key`.
179
+ - `compute` answers in a top-level `computed`, not `pagination.computed`.
180
+ - `joinGroup` takes `by` and the functions directly, and always answers `{ rows: [...] }`
181
+ with `{ by, sum: { total } }` rows.
182
+ - `POST /bulk/:table/delete` takes `{ ids: [...] }`.
183
+ - A write names its child rows by action: `secondaries` is `upsert`, `deletions` is `delete`,
184
+ and the old keys are a 400 `retired_key`; the response keeps `secondaries` and `deletions`
185
+ for what was written and removed. `validate` receives `{ main, upsert, replace }` (ADR 0029).
186
+ - A child row written through a write join is validated by its own table: the child's
187
+ `validate` (or `validateBulk`, once per alias) runs before any SQL, with
188
+ `parent: { alias, main }`, and its errors answer at `upsert.<alias>.<i>.<field>`. A
189
+ required-FK rule guards on `!parent`: the FK is known only when the request names the
190
+ parent's key (ADR 0030).
191
+ - An alias under `upsert`, `delete` or `replace` not declared in `writeJoins` is a 400
192
+ `unknown_field`, and nothing is written: it was dropped in silence.
193
+ - `error` in an error response is the HTTP reason phrase for every status.
194
+
195
+ ### Fixed
196
+
197
+ - **A response the Schema could not serialize leaked the stored value**: a column changed in the
198
+ database after its Schema was generated made the serializer refuse a row, and its message —
199
+ quoting the value — reached the client as the 500's `message`, unlogged. The error is raised
200
+ after the route handler, outside its sanitization; it is now the fixed 500 like any other
201
+ (ADR 0013), with the original in the log under the request's id and, under
202
+ `exposeDebugInfo`, in `debugInfo`.
203
+ - **An upsert by a key under `insertExclude` duplicated the rows it meant to update**
204
+ ([ADR 0031](./docs/adr/0031-an-insert-excluded-upsert-key-addresses-an-existing-row.md)):
205
+ `upsertKey: ['id']` with the `insertExclude: ['id']` the CLI generates stripped the key, so
206
+ every row sent with an id was inserted again under a new one — main rows and the child rows
207
+ of a write join alike. The key now updates the row it names; a key naming no row is a 400
208
+ `not_found` at its path, and a row without the key is inserted as before.
209
+ - **`pgQueryable(new pg.Pool())` and `pgQueryable(fastify.pg)` did not compile** (TS2345): the
210
+ type of `connect()` required the checked-out client to have a `connect()` of the same type,
211
+ which pg's `PoolClient` does not. The checked-out client now needs only `query` and
212
+ `release`; `mysqlQueryable` is aligned. A `pg.Client` stays refused: its `connect()` opens
213
+ the connection, it does not check one out.
214
+ - **`app.sqlApi` was untyped for a consumer** (TS2339): the `FastifyInstance` augmentation sat
215
+ in a module the package's declarations reached only through a type-only import, which the
216
+ emitted `.d.ts` drops. It is now declared in the plugin module itself.
217
+ - **The 400 for an aggregation grouped by a non-FK column said "Cannot order by" in a condition
218
+ too**: its message now names the clause it was found in (path and code were already right).
219
+ - **A delete under an indirect tenant scope failed on MySQL and MariaDB** (error 1093): the
220
+ DELETE named its rows through a subquery reading the same table. It now tests the parent
221
+ with a correlated `EXISTS`, as the deletions of a write join already did;
222
+ `DELETE /rest/:table/:id` and bulk delete both work.
223
+ - **A search without a paginator was paginated.** The querystring schema declared a default
224
+ `itemsPerPage`, which Ajv injected before the handler: every search ran a `COUNT(*)` and
225
+ answered page 1 of 500 rows. It now returns up to `maxItemsPerPage` rows, without
226
+ `pagination`.
227
+ - **A second registration of the plugin ran its routes with the first one's configuration**:
228
+ its `dbTables`, `getTenantId` and table rules — a tenant scope declared only on the second
229
+ surface was not applied. Each registration's routes run through its own SqlApi.
230
+ - **A join target's config applied only when its `dbTables` key was the table name.**
231
+ Otherwise its `readExclude` fields were returned through `joinMultiple` and `joinLeft`.
232
+ - **An update on a table whose tenant column is camelCase failed with a 500** on PostgreSQL:
233
+ the tenant predicate named the column unquoted.
234
+ - **A search with computed fields and a JOIN on the main query returned the joined table's
235
+ columns in the main rows** (also fixed in 0.5.1).
236
+ - **`GET|DELETE /rest/:table/:id` validate `:id` against the primary key's type**: a 400 on
237
+ `id` instead of a 500, and the value reaches SQL with the key's type.
238
+
239
+ ## [0.5.1]
11
240
 
12
241
  ### Fixed
13
242
 
@@ -28,7 +257,7 @@ Migration instructions for breaking changes live in **[BREAKING_CHANGES.md](./BR
28
257
  - **BREAKING: Node.js 22 or newer is required** (`engines.node` is now `>=22`, was `>=18`).
29
258
  Node 18 and 20 are end-of-life, and Fastify 5 never supported Node 18. CI now runs the
30
259
  full gate on Node 22, 24 and 26. See
31
- [BREAKING_CHANGES.md](./BREAKING_CHANGES.md#breaking-change--nodejs-22-or-newer-is-required).
260
+ [docs/upgrading/0.x.md](./docs/upgrading/0.x.md#breaking-change--nodejs-22-or-newer-is-required).
32
261
 
33
262
  ### Security
34
263
 
@@ -48,7 +277,7 @@ Migration instructions for breaking changes live in **[BREAKING_CHANGES.md](./BR
48
277
  numeric columns, such mains now sort where the database puts NULL (PostgreSQL: last in ASC,
49
278
  first in DESC; MySQL/MariaDB: first in ASC, last in DESC) instead of as 0, and a condition
50
279
  like `max < 5` no longer matches them (`isNull` does). See
51
- [BREAKING_CHANGES.md](./BREAKING_CHANGES.md#breaking-change--min-max-and-avg-of-a-main-row-without-children-are-null).
280
+ [docs/upgrading/0.x.md](./docs/upgrading/0.x.md#breaking-change--min-max-and-avg-of-a-main-row-without-children-are-null).
52
281
 
53
282
  ### Fixed
54
283
 
@@ -78,7 +307,7 @@ Migration instructions for breaking changes live in **[BREAKING_CHANGES.md](./BR
78
307
  - the exported `SqlDialect` type loses `upsertSql()` and `upsertUpdateSet()`, replaced by
79
308
  `onConflict?: { sql(), updateSet() }`, present on PostgreSQL only.
80
309
  Regenerate the schemas; see
81
- [BREAKING_CHANGES.md](./BREAKING_CHANGES.md#breaking-change--an-upsert-targets-a-unique-key-verified-at-startup).
310
+ [docs/upgrading/0.x.md](./docs/upgrading/0.x.md#breaking-change--an-upsert-targets-a-unique-key-verified-at-startup).
82
311
 
83
312
  ### Fixed
84
313
 
@@ -132,7 +361,7 @@ Migration instructions for breaking changes live in **[BREAKING_CHANGES.md](./BR
132
361
  manifest advertised a URL that did not exist. Routes are now `/search/<key>`,
133
362
  `/rest/<key>`, `/bulk/<key>`, and the search response's `table` names the key too. Configs
134
363
  generated by `sqlapi-generate-tables` use the table name as key and are unaffected. See
135
- [BREAKING_CHANGES.md](./BREAKING_CHANGES.md#breaking-change--the-route-url-is-the-dbtables-key).
364
+ [docs/upgrading/0.x.md](./docs/upgrading/0.x.md#breaking-change--the-route-url-is-the-dbtables-key).
136
365
  - **`fastify-plugin` 5 → 6.** The only runtime dependency bump: v6 renames its entry files and
137
366
  drops the long-deprecated `PluginOptions` type (now `PluginMetadata`), neither of which this
138
367
  library uses. No change for consumers; still Fastify 5.
@@ -421,7 +650,7 @@ Migration instructions for breaking changes live in **[BREAKING_CHANGES.md](./BR
421
650
  one; it is still never called when nothing scoped is in reach. Tables that already declared
422
651
  their own scope emit unchanged SQL. Migration — including the `getTenantId` body that now needs
423
652
  to tolerate an unauthenticated request — in
424
- [BREAKING_CHANGES.md](./BREAKING_CHANGES.md#breaking-change--the-tenant-follows-the-request-not-the-table-it-addresses).
653
+ [docs/upgrading/0.x.md](./docs/upgrading/0.x.md#breaking-change--the-tenant-follows-the-request-not-the-table-it-addresses).
425
654
 
426
655
  - **Database errors no longer reach clients verbatim.** Any error escaping an auto-generated
427
656
  route that the plugin did not raise itself now answers `{"statusCode":500,"error":"Internal
@@ -462,7 +691,7 @@ Migration instructions for breaking changes live in **[BREAKING_CHANGES.md](./BR
462
691
  1024-character cap on the `orderBy` string), so Swagger advertises exactly what the engine
463
692
  enforces. Both are exported as `MAX_CONDITIONS` and `MAX_ORDER_BY_PARTS`, and both are checked
464
693
  **in the engine**, which is what covers `sqlApi.search()` — no schema validates a programmatic
465
- caller. See [BREAKING_CHANGES.md](./BREAKING_CHANGES.md#breaking-change--request-limits-condition-arity-and-tenant-scope-inside-subqueries).
694
+ caller. See [docs/upgrading/0.x.md](./docs/upgrading/0.x.md#breaking-change--request-limits-condition-arity-and-tenant-scope-inside-subqueries).
466
695
 
467
696
  - **BREAKING: `paginator` is validated at runtime.** `page` and `itemsPerPage` are rendered
468
697
  straight into `LIMIT`/`OFFSET`, and `Paginator` is a compile-time type only: nothing stopped a
@@ -538,7 +767,7 @@ Migration instructions for breaking changes live in **[BREAKING_CHANGES.md](./BR
538
767
  and aggregations, which have always answered 400. The check lives in the engine, so it
539
768
  covers `sqlApi.search()` as well as the HTTP routes. `undefined` values still mean "filter
540
769
  not supplied" and are ignored; an explicit `null` still filters by `IS NULL`. See
541
- [BREAKING_CHANGES.md](./BREAKING_CHANGES.md#breaking-change--unknown-filter-keys-are-rejected).
770
+ [docs/upgrading/0.x.md](./docs/upgrading/0.x.md#breaking-change--unknown-filter-keys-are-rejected).
542
771
 
543
772
  - **`joinLeft.<alias>.filters` no longer advertises the parent's `extraFilters`.** They were
544
773
  present in the generated body schema and in Swagger, but `buildLeftJoinClauses` never runs
@@ -606,7 +835,7 @@ Migration instructions for breaking changes live in **[BREAKING_CHANGES.md](./BR
606
835
  bulk upsert are unaffected — they already handled every PK column. If your composite table's
607
836
  first PK column happens to be unique, these endpoints previously worked for you and are now
608
837
  gone — see
609
- [BREAKING_CHANGES.md](./BREAKING_CHANGES.md#breaking-change--by-single-id-operations-disabled-for-composite-primary-keys)
838
+ [docs/upgrading/0.x.md](./docs/upgrading/0.x.md#breaking-change--by-single-id-operations-disabled-for-composite-primary-keys)
610
839
  for the migration paths.
611
840
 
612
841
  ### Fixed
@@ -741,7 +970,7 @@ Migration instructions for breaking changes live in **[BREAKING_CHANGES.md](./BR
741
970
  error. Computed fields that declare **no** bound values are unaffected — the majority case
742
971
  (JSON extraction, `CONCAT`, `dateTrunc`, arithmetic) needs no change, and a literal `?` such
743
972
  as the PostgreSQL jsonb operator keeps working.
744
- See [BREAKING_CHANGES.md](./BREAKING_CHANGES.md#breaking-change--computed-field-placeholders-use--markers).
973
+ See [docs/upgrading/0.x.md](./docs/upgrading/0.x.md#breaking-change--computed-field-placeholders-use--markers).
745
974
 
746
975
  ### Added
747
976
 
@@ -792,11 +1021,13 @@ Migration instructions for breaking changes live in **[BREAKING_CHANGES.md](./BR
792
1021
  ## [0.1.3] and earlier
793
1022
 
794
1023
  Released before this changelog was kept. See the git history for details: notable entries are
795
- the join API redesign (documented in [BREAKING_CHANGES.md](./BREAKING_CHANGES.md)), composite
1024
+ the join API redesign (documented in [docs/upgrading/0.x.md](./docs/upgrading/0.x.md)), composite
796
1025
  primary key support in updates, transactional insert/update with secondaries, the hook matrix,
797
1026
  and bulk operations.
798
1027
 
799
- [Unreleased]: https://github.com/LucaRainone/fastify-auto-sqlapi/compare/v0.5.0...HEAD
1028
+ [Unreleased]: https://github.com/LucaRainone/fastify-auto-sqlapi/compare/v1.0.0...HEAD
1029
+ [1.0.0]: https://github.com/LucaRainone/fastify-auto-sqlapi/compare/v0.5.1...v1.0.0
1030
+ [0.5.1]: https://github.com/LucaRainone/fastify-auto-sqlapi/releases/tag/v0.5.1
800
1031
  [0.5.0]: https://github.com/LucaRainone/fastify-auto-sqlapi/releases/tag/v0.5.0
801
1032
  [0.4.1]: https://github.com/LucaRainone/fastify-auto-sqlapi/releases/tag/v0.4.1
802
1033
  [0.4.0]: https://github.com/LucaRainone/fastify-auto-sqlapi/releases/tag/v0.4.0
package/README.md CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  **Your database already knows its tables, columns and relations. This plugin turns that knowledge into a typed, validated REST API inside your [Fastify](https://fastify.dev/) app.**
4
4
 
5
- ```typescript
6
- await app.register(fastifyAutoSqlApi, { DbTables: dbTables, swagger: true, prefix: '/api' });
5
+ ```typescript in=app
6
+ await app.register(fastifyAutoSqlApi, { dbTables, swagger: true, prefix: '/api' });
7
7
  ```
8
8
 
9
9
  ### One `register()` call. Seven endpoints for every table you choose to expose.
@@ -18,7 +18,7 @@ has to own your database, no migrations, no repository layout to adopt. **One ta
18
18
  installation.**
19
19
 
20
20
  Related tables need no endpoints of their own: reads reach them through joins, writes through
21
- nested children, so a whole subgraph can live behind a single exposed table.
21
+ child rows sent with the main row, so a whole subgraph can live behind a single exposed table.
22
22
 
23
23
  ## See what that buys you
24
24
 
@@ -26,16 +26,19 @@ nested children, so a whole subgraph can live behind a single exposed table.
26
26
  spenders first."* No resolver, no query builder, no one-off endpoint:
27
27
 
28
28
  ```jsonc
29
- // POST /api/search/customer?orderBy=orders.sum.total DESC&page=1&itemsPerPage=20
29
+ // POST /api/search/customer
30
30
  {
31
31
  "filters": { "status": "active" },
32
32
  "joinGroup": {
33
33
  "orders": {
34
+ "by": "customerId",
34
35
  "filters": { "status": "completed" },
35
- "aggregations": { "sum": ["total"], "count": ["id"] }
36
+ "sum": ["total"], "count": ["id"]
36
37
  }
37
38
  },
38
- "conditions": [{ "field": "orders.sum.total", "method": "isGreater", "params": [500] }]
39
+ "conditions": [{ "field": "orders.sum.total", "method": "isGreater", "params": [500] }],
40
+ "orderBy": "orders.sum.total DESC",
41
+ "paginator": { "page": 1, "itemsPerPage": 20 }
39
42
  }
40
43
  ```
41
44
 
@@ -45,16 +48,17 @@ Writes read the same way — *"sync these clients and their tags: update the one
45
48
  // PUT /api/bulk/customer — all mains in one SQL; child FKs auto-filled from each parent
46
49
  [
47
50
  { "main": { "email": "mario@acme.it", "name": "Mario" },
48
- "secondaries": { "tags": [{ "tag": "vip" }, { "tag": "newsletter" }] } },
51
+ "upsert": { "tags": [{ "tag": "vip" }, { "tag": "newsletter" }] } },
49
52
  { "main": { "email": "luigi@acme.it", "name": "Luigi" } }
50
53
  ]
51
- // → 200 [{ "main": { "id": 1 }, "secondaries": { "tags": [{ "id": 10 }, { "id": 11 }] } },
52
- // { "main": { "id": 2 } }]
54
+ // → 200 [{ "main": { "id": 1 }, "action": "inserted", "secondaries": { "tags": [{ "id": 10 }, { "id": 11 }] } },
55
+ // { "main": { "id": 2 }, "action": "inserted" }]
56
+ // sent again → the same ids, each with "action": "updated"
53
57
  ```
54
58
 
55
- Conflict keys are declared server-side (`upsertMap`: here customer on `email`, tag on `(customerId, tag)`) and checked at startup against the unique keys the database enforces, so re-sending the same payload updates rows instead of duplicating them and never touches a row through any other key — client-side sync without hand-written diffing.
59
+ Conflict keys are declared server-side (`upsertKey` on the table for the main rows, here customer on `email`, and on the write relation for its child rows, here tags on `(customerId, tag)`) and checked at startup against the unique keys the database enforces, so re-sending the same payload updates rows instead of duplicating them and never touches a row through any other key — client-side sync without hand-written diffing. Send `replace` instead of `upsert` and the tags become exactly these: the ones left out are deleted, in the same transaction.
56
60
 
57
- And multi-tenancy is one plugin option (`getTenantId: (req) => req.user?.organizationId ?? null`), enforced on reads *and* writes with zero code in handlers. Rows of other tenants are simply invisible (`404`); here a caller in org B tries to re-point one of their own orders to a customer belonging to org A:
61
+ And multi-tenancy is one plugin option (`getTenantId: (req) => req.user?.organizationId`), enforced on reads *and* writes with zero code in handlers. Rows of other tenants are simply invisible (`404`); here a caller in org B tries to re-point one of their own orders to a customer belonging to org A:
58
62
 
59
63
  ```jsonc
60
64
  // PUT /api/rest/order — order 7 is mine, customer 41 belongs to another tenant
@@ -62,24 +66,24 @@ And multi-tenancy is one plugin option (`getTenantId: (req) => req.user?.organiz
62
66
  // → 403 Forbidden — cross-tenant references are rejected server-side
63
67
  ```
64
68
 
65
- > ⚠️ **`getTenantId` returning `null`/`undefined` means _admin_ — no filtering, full cross-tenant access.** So "unauthenticated" and "admin" collapse to the same value: if your auth hook is missing or fails, `req.user` is `undefined` and the `?? null` above serves the request as admin. Nothing fails closed. In production, make `getTenantId` (or the auth hook) **reject when there is no authenticated principal**, and reserve `null` for a real superadmin — see the `getTenantId` option docs.
69
+ > Admin is declared, never inferred: `getTenantId` returns the exported `TENANT_ADMIN` for unrestricted, cross-tenant access. Returning `null`/`undefined` — an auth hook that is missing or failed, `req.user` undefined — is a 401 on every scoped table, before any SQL runs. Tables without a tenant scope never ask.
66
70
 
67
71
  No endpoint written by hand, no resolvers, no query language on the server — and these requests are schema-validated, Swagger-documented, size-capped and tenant-isolated like every other one.
68
72
 
69
73
  ## What you get
70
74
 
71
- **Reads** — filters and equality shortcuts · advanced conditions (18 operators) · pagination
75
+ **Reads** — filters and equality shortcuts · advanced conditions (20 operators) · pagination
72
76
  with caps · four explicit relation families (`joinMustExist` for EXISTS filtering,
73
77
  `joinMultiple` for child rows, `joinGroup` for aggregations, `joinLeft` for N:1 parents) ·
74
78
  aggregations with HAVING-style conditions · ordering by related and computed values · computed
75
79
  fields declared as SQL expressions (JSON extraction, derived strings, date bucketing)
76
80
 
77
- **Writes** — validated inserts and updates · nested child records with foreign keys filled in
78
- from the parent · child deletions in the same request · bulk upsert and bulk delete ·
79
- transactions, so a write and its children commit or roll back together
81
+ **Writes** — validated inserts and updates · child rows with foreign keys filled in
82
+ from the main row · child deletions, or the full set replaced, in the same request · bulk upsert and bulk delete ·
83
+ transactions, so a write and its child rows commit or roll back together
80
84
 
81
85
  **Production** — multi-tenant row isolation from one `getTenantId`, enforced on reads *and*
82
- writes · hooks before and after every operation, plus `afterRead` · field-level and
86
+ writes · hooks before and after every write, plus `afterRead` on reads · field-level and
83
87
  cross-entity validation returning structured `400`s · per-table route whitelists · read and
84
88
  write column visibility · Swagger from the same schemas · request-size and pagination caps ·
85
89
  plain parameterized SQL you can print with `debug: true`
@@ -91,7 +95,8 @@ endpoint looks like a table.
91
95
 
92
96
  ### N+1 is structurally absent
93
97
 
94
- A request runs the main select plus one query per requested join alias — a number fixed by the
98
+ A request runs the main select plus at most one query per requested join alias (`joinLeft` and
99
+ `joinMustExist` live inside the main select; `joinMultiple` and `joinGroup` add one each) — a number fixed by the
95
100
  request, **never by the number of rows returned**. There are no lazy relations to accidentally
96
101
  loop over, so N+1 is not something you have to remember to avoid.
97
102
 
@@ -126,7 +131,7 @@ whole database first, no migration tool to take over, no repository layout to co
126
131
  which is what makes this different from adding an ORM to a project that already runs.
127
132
 
128
133
  - **One table is a valid installation.** `sqlapi-generate-schema --tables invoice` and
129
- `sqlapi-generate-tables invoice` generate for that table alone; `DbTables` contains only what
134
+ `sqlapi-generate-tables invoice` generate for that table alone; `dbTables` contains only what
130
135
  you put in it, and the rest of your database stays invisible to the plugin.
131
136
  - **It never writes to your database.** Not a row, not a column: generation is `SELECT`s
132
137
  against `information_schema`, and at runtime the plugin issues no DDL and runs no migrations.
@@ -135,33 +140,49 @@ which is what makes this different from adding an ORM to a project that already
135
140
  `fastify.mysql` off the instance — if your app already registers `@fastify/postgres`, there is
136
141
  nothing to wire.
137
142
  - **It stays inside its prefix.** `prefix: '/api/auto'` and your existing routes never meet it.
138
- You can also register only the route plugins you want (`searchRoutes`, `getRoutes`, …), or
139
- mount the same tables twice under different prefixes with different auth.
143
+ You can narrow a registration to some operations (`operations: ['search', 'get']`), or
144
+ mount the same tables twice under different prefixes with different auth (the second
145
+ registration passes `decorate: false`: one owns `app.sqlApi`).
140
146
  - **Generated files go where you say** (`outputDir`), and the `Table*.ts` files are yours: the
141
- generator never overwrites one that exists, so re-running it only adds files for new tables.
147
+ generator never overwrites one that exists, so re-running it only adds files for new tables
148
+ (`dbTables.ts` is written once: add a new table to it yourself, the generator says so).
142
149
 
143
150
  So a realistic first step on an existing back-office is: generate two tables, register the
144
151
  plugin under a new prefix behind your existing auth hook, move one list screen onto it, and
145
152
  leave everything else exactly where it is. `operations` keeps any table off the auto routes, and
146
- a table with no routes at all can still be reached through a join or written as a nested child.
153
+ a table with no routes at all can still be reached through a join or written as a child row of another table.
147
154
  Expose the CRUD that is CRUD, hand-write the rest.
148
155
 
149
156
  ## Get a REST API in 60 seconds
150
157
 
151
158
  ```bash
152
- npm install fastify-auto-sqlapi fastify @fastify/postgres
153
- # MySQL / MariaDB: npm install fastify-auto-sqlapi fastify mysql2
159
+ npm install fastify-auto-sqlapi fastify @fastify/postgres pg @fastify/swagger @fastify/swagger-ui
160
+ # MySQL / MariaDB: @fastify/mysql mysql2 instead of @fastify/postgres pg, and `dialect: 'mysql'`
161
+ # (or 'mariadb') on the plugin. The two Swagger packages are only for `swagger: true`.
154
162
  ```
155
163
 
156
- Create `sqlapi.config.ts` in the project root (used by the CLI only, not at runtime), then:
164
+ Point the generator at your database, once: a `DATABASE_URL` in the environment or in the
165
+ `.env` of the project root (the scheme names the dialect: `postgres://`, `mysql://`,
166
+ `mariadb://`). Then, with no arguments:
167
+
168
+ ```bash
169
+ # .env
170
+ DATABASE_URL=postgres://user:pass@localhost:5432/mydb
171
+ ```
157
172
 
158
173
  ```bash
159
174
  npx sqlapi-generate-schema # one TypeBox schema per table → <outputDir>/schemas/
160
175
  npx sqlapi-generate-tables --all # one defineTable() template per table → <outputDir>/tables/
161
176
  ```
162
177
 
178
+ An optional `sqlapi.config.ts` (CLI only, never read at runtime) sets the output directory, the
179
+ tables or columns to leave out, and the connection when your variable has another name:
180
+ `connection: process.env.SHOP_DB_URL`. `--url` runs once against another database. A `.ts`
181
+ config needs Node >= 22.18 (type stripping); `sqlapi.config.mjs` / `.js` work on any version.
182
+
163
183
  Schema files are regenerated on every run and should not be edited. **Table files are yours**:
164
- the generator never overwrites one that exists, so re-running only adds files for new tables.
184
+ the generator never overwrites one that exists, so re-running only adds files for new tables;
185
+ `dbTables.ts` is written once, and a table added later goes into it by hand.
165
186
 
166
187
  ```typescript
167
188
  import Fastify from 'fastify';
@@ -171,7 +192,7 @@ import { dbTables } from './src/db/tables/dbTables.js';
171
192
 
172
193
  const app = Fastify();
173
194
  await app.register(fastifyPostgres, { connectionString: 'postgres://user:pass@localhost:5432/mydb' });
174
- await app.register(fastifyAutoSqlApi, { DbTables: dbTables, swagger: true, prefix: '/api' });
195
+ await app.register(fastifyAutoSqlApi, { dbTables, swagger: true, prefix: '/api' });
175
196
  await app.listen({ port: 3000 });
176
197
  ```
177
198
 
@@ -181,8 +202,8 @@ For a table called `customer` you now have:
181
202
  |--------|-----|---|
182
203
  | `POST` | `/api/search/customer` | search with filters, pagination, joins, aggregations |
183
204
  | `GET` | `/api/rest/customer/:id` | get one by primary key |
184
- | `POST` | `/api/rest/customer` | insert (+ nested children) |
185
- | `PUT` | `/api/rest/customer` | update (+ nested children and deletions) |
205
+ | `POST` | `/api/rest/customer` | insert (+ child rows) |
206
+ | `PUT` | `/api/rest/customer` | update (+ child rows written or deleted) |
186
207
  | `DELETE` | `/api/rest/customer/:id` | delete by primary key |
187
208
  | `PUT` | `/api/bulk/customer` | bulk upsert |
188
209
  | `POST` | `/api/bulk/customer/delete` | bulk delete |
@@ -243,7 +264,7 @@ drop only the assumption that the endpoint looks like a table. Full rationale in
243
264
  requests. This covers what most projects reach for GraphQL for — filter, paginate, join,
244
265
  aggregate in one round trip — with a fixed JSON grammar over plain REST: curl-able,
245
266
  Swagger-documented, bounded by design. The write side is generated too. What you give up:
246
- arbitrarily deep nesting, per-field selection on the main table, subscriptions.
267
+ arbitrarily deep nesting, subscriptions.
247
268
  - **Not a hosted black box.** PostgREST / Hasura / Supabase give you an API as a separate
248
269
  service, configured from outside. This is a plugin inside your own app: hooks, validation and
249
270
  auth are TypeScript functions in your codebase, and you can always drop to `app.sqlApi.*` or
@@ -256,7 +277,7 @@ something you remember to avoid.
256
277
  ## Before you ship
257
278
 
258
279
  > ⚠️ **The plugin is open by default.** Registering it with no further configuration exposes
259
- > **every operation on every table in `DbTables`** — reads *and* writes, bulk delete included —
280
+ > **every operation on every table in `dbTables`** — reads *and* writes, bulk delete included —
260
281
  > to anyone who can reach the server. That is intentional: the plugin provides the tools and
261
282
  > imposes no auth model ([ADR 0002](./docs/adr/0002-open-by-default.md)). Locking it down is
262
283
  > yours to do.
@@ -267,31 +288,36 @@ full in [AGENTS_BACKEND.md](./AGENTS_BACKEND.md).
267
288
  **1. Who may call the routes** — `onRequests` runs before every generated route, globally or per
268
289
  table. It is where `jwtVerify()` and your role checks go.
269
290
 
270
- **2. Which routes exist** — `operations: ['search', 'get']` registers only those; the rest answer
271
- 404. It gates HTTP only: your own code still reaches everything through `app.sqlApi.*`.
291
+ **2. Which routes exist** — `operations: ['search', 'get']` registers only those; the rest
292
+ answer 404. It gates HTTP only: your own code still reaches everything through `app.sqlApi.*`.
272
293
 
273
294
  **3. A declared join is a read grant.** Neither of the two above follows a join: a join is
274
- resolved inside the *host* table's query, so the target's hooks never run and its `operations`
295
+ resolved inside the *main* table's query, so the target's hooks never run and its `operations`
275
296
  whitelist does not apply. A table with `operations: []` is still fully readable through any
276
- relation pointing at it. `allowedReadJoins` is therefore a security decision — and
297
+ relation pointing at it. `readJoins` is therefore a security decision — and
277
298
  `buildRelation(..., { fields: ['id', 'name'] })` narrows what a relation exposes, fail-closed.
278
299
  ([ADR 0010](./docs/adr/0010-joins-do-not-run-route-guards.md),
279
300
  [ADR 0011](./docs/adr/0011-join-fields-allowlist.md))
280
301
 
281
- **4. Every Schema field is updatable by default.** `excludeFromCreation` is an ergonomics tool
302
+ **4. Every Schema field is updatable by default.** `insertExclude` is an ergonomics tool
282
303
  for inserts, not a security mechanism, and it deliberately does not apply to updates. So
283
304
  `isAdmin`, roles, ownership and state columns *will* be accepted by the generated update route
284
305
  if they are in the Schema. Whether a field may change is a product decision the plugin cannot
285
306
  make for you — encode it in `beforeUpdate` (silent strip) or `validate` (loud 400), or keep the
286
- privileged transition off the auto routes entirely.
307
+ privileged transition off the auto routes entirely. A column no request may ever write goes in
308
+ `writeExclude`, which applies to updates too.
287
309
  ([ADR 0004](./docs/adr/0004-updates-always-open.md))
288
310
 
289
311
  **5. What leaves the server.** Any error the plugin did not raise itself becomes a bare `500`
290
312
  carrying a `requestId` — driver messages name your tables, columns and constraints, and they
291
- stay in the log. No status code is remapped (a unique violation is a `500`, not a `409`: that
292
- mapping is product logic, for your `setErrorHandler`). Set `exposeDebugInfo: true` while
293
- developing to get the driver detail on the wire, additively.
294
- ([ADR 0013](./docs/adr/0013-sanitized-db-errors.md))
313
+ stay in the log. The plugin remaps no status on its own (a unique violation is a `500`, not a
314
+ `409`: that mapping is product logic). List the driver codes you want answered otherwise in
315
+ `dbErrors` — `{ '23505': { status: 409, code: 'duplicate' } }` — and they get that status and a
316
+ code the client translates, still without driver detail. Set
317
+ `exposeDebugInfo: true` while developing to get the driver detail on the wire, additively.
318
+ The routes answer through their own error handler, so an application `setErrorHandler` never
319
+ sees their errors; an `onError` hook added before the plugin does, for logging and reporting.
320
+ ([ADR 0013](./docs/adr/0013-sanitized-db-errors.md), [ADR 0024](./docs/adr/0024-the-consumer-maps-driver-codes-through-dberrors.md))
295
321
 
296
322
  Two caps are on by default and configurable: `maxItemsPerPage` (1000) bounds a search — and is
297
323
  applied as the `LIMIT` even with no paginator, so an empty-body search cannot dump a table — and
@@ -308,8 +334,8 @@ default rather than rejecting it.
308
334
  |---|---|
309
335
  | [AGENTS_BACKEND.md](./AGENTS_BACKEND.md) | **The reference.** Setup, plugin options, every `defineTable()` key, joins, computed fields, hooks, validation, multi-tenancy, views, `SqlApi`, `QueryClient`, Swagger, patterns, FAQ. Opens with a section map — jump, don't scan. |
310
336
  | [AGENTS_FRONTEND.md](./AGENTS_FRONTEND.md) | **The client contract.** Every endpoint's request and response shape, the four join families, conditions, ordering, pagination, error shapes. |
311
- | [docs/adr/](./docs/adr/README.md) | **Why it behaves like this.** Open-by-default, non-transactional bulk, always-updatable fields, raw DB errors, the schema-as-contract bet. Read the relevant one before filing an issue that proposes changing one of these. |
312
- | [CHANGELOG.md](./CHANGELOG.md) · [BREAKING_CHANGES.md](./BREAKING_CHANGES.md) | What changed, and how to migrate. |
337
+ | [docs/adr/](./docs/adr/README.md) | **Why it behaves like this.** Open-by-default, non-transactional bulk, always-updatable fields, DB errors as a sanitized 500 unless you map them, the schema-as-contract bet. Read the relevant one before filing an issue that proposes changing one of these. |
338
+ | [CHANGELOG.md](./CHANGELOG.md) · [BREAKING_CHANGES.md](./BREAKING_CHANGES.md) | What changed, and how to migrate: one upgrade guide per release line; from 0.5, [docs/upgrading/1.0.md](./docs/upgrading/1.0.md). |
313
339
 
314
340
  The two `AGENTS_*` files are named for their other audience — they ship inside the npm package
315
341
  so a coding agent finds them after `npm install` — but they are the reference documentation for
@@ -326,7 +352,7 @@ request says exactly what to fix.
326
352
  ## Requirements
327
353
 
328
354
  - Node.js >= 22, Fastify >= 5 (peer dependency)
329
- - **PostgreSQL** + `pg` + `@fastify/postgres`, or **MySQL** / **MariaDB** + `mysql2`
355
+ - **PostgreSQL** + `pg` + `@fastify/postgres`, or **MySQL** / **MariaDB** + `mysql2` + `@fastify/mysql`
330
356
  - Optional: `@fastify/swagger` + `@fastify/swagger-ui` for Swagger UI
331
357
 
332
358
  ## License