fastify-auto-sqlapi 0.5.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +5 -5
- package/AGENTS_BACKEND.md +166 -130
- package/AGENTS_FRONTEND.md +60 -38
- package/BREAKING_CHANGES.md +9 -893
- package/CHANGELOG.md +258 -15
- package/README.md +71 -45
- package/dist/bin/generate-schema.js +12 -12
- package/dist/bin/generate-tables.js +1 -2
- package/dist/bin/utils.d.ts +2 -6
- package/dist/bin/utils.d.ts.map +1 -1
- package/dist/bin/utils.js +13 -33
- package/dist/index.d.ts +13 -33
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -37
- package/dist/lib/adapters/mysql-adapter.d.ts +5 -2
- package/dist/lib/adapters/mysql-adapter.d.ts.map +1 -1
- package/dist/lib/adapters/pg-adapter.d.ts +5 -2
- package/dist/lib/adapters/pg-adapter.d.ts.map +1 -1
- package/dist/lib/agent/manifest.d.ts +27 -10
- package/dist/lib/agent/manifest.d.ts.map +1 -1
- package/dist/lib/agent/manifest.js +43 -26
- package/dist/lib/agent/tool-schemas.d.ts +5 -4
- package/dist/lib/agent/tool-schemas.d.ts.map +1 -1
- package/dist/lib/agent/tool-schemas.js +5 -5
- package/dist/lib/cli/config.d.ts +37 -2
- package/dist/lib/cli/config.d.ts.map +1 -1
- package/dist/lib/cli/config.js +106 -16
- package/dist/lib/cli/mysql-introspect.d.ts +6 -1
- package/dist/lib/cli/mysql-introspect.d.ts.map +1 -1
- package/dist/lib/cli/mysql-introspect.js +15 -15
- package/dist/lib/cli/pg-introspect.d.ts +0 -1
- package/dist/lib/cli/pg-introspect.d.ts.map +1 -1
- package/dist/lib/cli/pg-introspect.js +2 -13
- package/dist/lib/cli/tables-codegen.d.ts +0 -4
- package/dist/lib/cli/tables-codegen.d.ts.map +1 -1
- package/dist/lib/cli/tables-codegen.js +24 -87
- package/dist/lib/db.d.ts +42 -17
- package/dist/lib/db.d.ts.map +1 -1
- package/dist/lib/db.js +114 -40
- package/dist/lib/dialect.d.ts +5 -0
- package/dist/lib/dialect.d.ts.map +1 -1
- package/dist/lib/dialect.js +3 -0
- package/dist/lib/engine/bulk/bulk-delete.d.ts +5 -0
- package/dist/lib/engine/bulk/bulk-delete.d.ts.map +1 -1
- package/dist/lib/engine/bulk/bulk-delete.js +66 -30
- package/dist/lib/engine/bulk/bulk-upsert.d.ts.map +1 -1
- package/dist/lib/engine/bulk/bulk-upsert.js +45 -26
- package/dist/lib/engine/read-hooks.d.ts +3 -3
- package/dist/lib/engine/read-hooks.d.ts.map +1 -1
- package/dist/lib/engine/read-hooks.js +3 -3
- package/dist/lib/engine/rest/delete.d.ts.map +1 -1
- package/dist/lib/engine/rest/delete.js +12 -18
- package/dist/lib/engine/rest/get.js +8 -8
- package/dist/lib/engine/rest/insert.d.ts.map +1 -1
- package/dist/lib/engine/rest/insert.js +31 -18
- package/dist/lib/engine/rest/update.d.ts.map +1 -1
- package/dist/lib/engine/rest/update.js +34 -17
- package/dist/lib/engine/search/aggregations.d.ts +3 -3
- package/dist/lib/engine/search/aggregations.d.ts.map +1 -1
- package/dist/lib/engine/search/aggregations.js +20 -16
- package/dist/lib/engine/search/conditions.d.ts +9 -5
- package/dist/lib/engine/search/conditions.d.ts.map +1 -1
- package/dist/lib/engine/search/conditions.js +31 -20
- package/dist/lib/engine/search/fields.d.ts +44 -11
- package/dist/lib/engine/search/fields.d.ts.map +1 -1
- package/dist/lib/engine/search/fields.js +94 -28
- package/dist/lib/engine/search/join-families.d.ts +7 -7
- package/dist/lib/engine/search/join-families.d.ts.map +1 -1
- package/dist/lib/engine/search/join-families.js +84 -75
- package/dist/lib/engine/search/joins.d.ts +15 -7
- package/dist/lib/engine/search/joins.d.ts.map +1 -1
- package/dist/lib/engine/search/joins.js +23 -13
- package/dist/lib/engine/search/order-by.d.ts +11 -12
- package/dist/lib/engine/search/order-by.d.ts.map +1 -1
- package/dist/lib/engine/search/order-by.js +24 -28
- package/dist/lib/engine/search/search.d.ts.map +1 -1
- package/dist/lib/engine/search/search.js +111 -62
- package/dist/lib/engine/validate.d.ts +21 -3
- package/dist/lib/engine/validate.d.ts.map +1 -1
- package/dist/lib/engine/validate.js +106 -16
- package/dist/lib/engine/write-helpers.d.ts +69 -16
- package/dist/lib/engine/write-helpers.d.ts.map +1 -1
- package/dist/lib/engine/write-helpers.js +257 -105
- package/dist/lib/errors.d.ts +42 -10
- package/dist/lib/errors.d.ts.map +1 -1
- package/dist/lib/errors.js +69 -15
- package/dist/lib/nullable.d.ts +3 -2
- package/dist/lib/nullable.d.ts.map +1 -1
- package/dist/lib/nullable.js +14 -5
- package/dist/lib/read-access.d.ts +33 -21
- package/dist/lib/read-access.d.ts.map +1 -1
- package/dist/lib/read-access.js +42 -23
- package/dist/lib/schema/bulk-delete.d.ts +13 -7
- package/dist/lib/schema/bulk-delete.d.ts.map +1 -1
- package/dist/lib/schema/bulk-delete.js +18 -8
- package/dist/lib/schema/bulk-upsert.d.ts +3 -3
- package/dist/lib/schema/bulk-upsert.d.ts.map +1 -1
- package/dist/lib/schema/bulk-upsert.js +9 -14
- package/dist/lib/schema/get.d.ts +1 -1
- package/dist/lib/schema/get.d.ts.map +1 -1
- package/dist/lib/schema/get.js +2 -2
- package/dist/lib/schema/helpers.d.ts +41 -23
- package/dist/lib/schema/helpers.d.ts.map +1 -1
- package/dist/lib/schema/helpers.js +80 -33
- package/dist/lib/schema/insert.d.ts +1 -1
- package/dist/lib/schema/insert.d.ts.map +1 -1
- package/dist/lib/schema/insert.js +12 -20
- package/dist/lib/schema/search.d.ts +2 -13
- package/dist/lib/schema/search.d.ts.map +1 -1
- package/dist/lib/schema/search.js +64 -61
- package/dist/lib/schema/update.d.ts +1 -1
- package/dist/lib/schema/update.d.ts.map +1 -1
- package/dist/lib/schema/update.js +6 -13
- package/dist/lib/sql-api.d.ts +47 -25
- package/dist/lib/sql-api.d.ts.map +1 -1
- package/dist/lib/sql-api.js +70 -27
- package/dist/lib/table-helpers.d.ts +92 -14
- package/dist/lib/table-helpers.d.ts.map +1 -1
- package/dist/lib/table-helpers.js +367 -128
- package/dist/lib/tenant.d.ts +16 -22
- package/dist/lib/tenant.d.ts.map +1 -1
- package/dist/lib/tenant.js +38 -54
- package/dist/lib/write-access.d.ts +15 -9
- package/dist/lib/write-access.d.ts.map +1 -1
- package/dist/lib/write-access.js +12 -4
- package/dist/routes/auto/agent-manifest.routes.d.ts +1 -1
- package/dist/routes/auto/agent-manifest.routes.js +2 -2
- package/dist/routes/auto/bulk-delete.routes.d.ts +2 -2
- package/dist/routes/auto/bulk-delete.routes.d.ts.map +1 -1
- package/dist/routes/auto/bulk-delete.routes.js +1 -7
- package/dist/routes/auto/bulk-upsert.routes.d.ts +2 -2
- package/dist/routes/auto/bulk-upsert.routes.d.ts.map +1 -1
- package/dist/routes/auto/bulk-upsert.routes.js +2 -2
- package/dist/routes/auto/delete.routes.d.ts +2 -2
- package/dist/routes/auto/delete.routes.d.ts.map +1 -1
- package/dist/routes/auto/delete.routes.js +8 -10
- package/dist/routes/auto/get.routes.d.ts +2 -2
- package/dist/routes/auto/get.routes.d.ts.map +1 -1
- package/dist/routes/auto/get.routes.js +5 -5
- package/dist/routes/auto/insert.routes.d.ts +2 -2
- package/dist/routes/auto/insert.routes.d.ts.map +1 -1
- package/dist/routes/auto/insert.routes.js +1 -7
- package/dist/routes/auto/plugin.d.ts +6 -0
- package/dist/routes/auto/plugin.d.ts.map +1 -1
- package/dist/routes/auto/plugin.js +60 -36
- package/dist/routes/auto/route-helpers.d.ts +26 -12
- package/dist/routes/auto/route-helpers.d.ts.map +1 -1
- package/dist/routes/auto/route-helpers.js +50 -19
- package/dist/routes/auto/search.routes.d.ts +2 -2
- package/dist/routes/auto/search.routes.d.ts.map +1 -1
- package/dist/routes/auto/search.routes.js +36 -24
- package/dist/routes/auto/update.routes.d.ts +2 -2
- package/dist/routes/auto/update.routes.d.ts.map +1 -1
- package/dist/routes/auto/update.routes.js +1 -8
- package/dist/routes/sql-api-decorator.d.ts +30 -12
- package/dist/routes/sql-api-decorator.d.ts.map +1 -1
- package/dist/routes/sql-api-decorator.js +44 -27
- package/dist/types/cli.d.ts +17 -6
- package/dist/types/cli.d.ts.map +1 -1
- package/dist/types/computed.d.ts +1 -1
- package/dist/types/computed.d.ts.map +1 -1
- package/dist/types/conditions.d.ts +3 -1
- package/dist/types/conditions.d.ts.map +1 -1
- package/dist/types/db.d.ts +44 -4
- package/dist/types/db.d.ts.map +1 -1
- package/dist/types/dml.d.ts +26 -17
- package/dist/types/dml.d.ts.map +1 -1
- package/dist/types/hooks.d.ts +62 -0
- package/dist/types/hooks.d.ts.map +1 -0
- package/dist/types/hooks.js +1 -0
- package/dist/types/join.d.ts +25 -8
- package/dist/types/join.d.ts.map +1 -1
- package/dist/types/plugin.d.ts +58 -19
- package/dist/types/plugin.d.ts.map +1 -1
- package/dist/types/plugin.js +2 -0
- package/dist/types/request.d.ts +2 -2
- package/dist/types/schema.d.ts +3 -3
- package/dist/types/schema.d.ts.map +1 -1
- package/dist/types/search.d.ts +28 -13
- package/dist/types/search.d.ts.map +1 -1
- package/dist/types/search.js +2 -1
- package/dist/types/table.d.ts +109 -94
- package/dist/types/table.d.ts.map +1 -1
- package/dist/types/table.js +7 -2
- package/dist/types/tenant.d.ts +28 -2
- package/dist/types/tenant.d.ts.map +1 -1
- package/dist/types/tenant.js +7 -1
- package/dist/types/validation.d.ts +69 -13
- package/dist/types/validation.d.ts.map +1 -1
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +1 -0
- package/docs/GLOSSARY.md +11 -5
- package/docs/adr/0003-bulk-not-transactional.md +2 -1
- package/docs/adr/0006-raw-db-errors.md +2 -1
- package/docs/adr/0013-sanitized-db-errors.md +2 -1
- package/docs/adr/0014-what-follows-a-write-join.md +1 -1
- package/docs/adr/0022-stay-on-0x-while-every-consumer-is-first-party.md +88 -0
- package/docs/adr/0023-a-write-runs-in-a-transaction-or-not-at-all.md +60 -0
- package/docs/adr/0024-the-consumer-maps-driver-codes-through-dberrors.md +78 -0
- package/docs/adr/0025-validatebulk-replaces-validate-in-a-bulk-upsert.md +46 -0
- package/docs/adr/0026-update-carries-its-primary-key-in-main.md +43 -0
- package/docs/adr/0027-the-1-0-contract.md +74 -0
- package/docs/adr/0028-select-star-is-the-default-projection.md +64 -0
- package/docs/adr/0029-a-write-names-its-child-rows-by-action.md +96 -0
- package/docs/adr/0030-a-child-row-is-validated-by-its-own-table.md +117 -0
- package/docs/adr/0031-an-insert-excluded-upsert-key-addresses-an-existing-row.md +58 -0
- package/docs/adr/0032-tenant-scope-names-schema-fields.md +56 -0
- package/docs/adr/README.md +12 -1
- package/docs/upgrading/0.x.md +906 -0
- package/docs/upgrading/1.0.md +628 -0
- package/package.json +4 -5
|
@@ -0,0 +1,628 @@
|
|
|
1
|
+
# Upgrading from 0.5 to 1.0
|
|
2
|
+
|
|
3
|
+
1.0 makes the API coherent in one breaking release: one name and one place for each concept,
|
|
4
|
+
one shape for each result, and every key the API no longer reads refused rather than ignored
|
|
5
|
+
([ADR 0027](../adr/0027-the-1-0-contract.md)). This guide covers every breaking change
|
|
6
|
+
from 0.5.1 to 1.0.0, grouped by where you make the edit. It includes those of 0.6.0, which was
|
|
7
|
+
prepared but never published: 1.0.0 is the release that follows 0.5.1. The notes of earlier
|
|
8
|
+
releases are in [0.x.md](./0.x.md).
|
|
9
|
+
|
|
10
|
+
**How to work through it.** The old forms fail loudly, naming their replacement:
|
|
11
|
+
|
|
12
|
+
- a pre-1.0 config key or plugin option throws at startup (`defineTable`, plugin registration,
|
|
13
|
+
`createSqlApi`);
|
|
14
|
+
- a pre-1.0 request key is a 400 with code `retired_key` at that key;
|
|
15
|
+
- a pre-1.0 call shape in `sqlApi` or the QueryClient throws a `TypeError` (`record`, a positional
|
|
16
|
+
chunk size); a retired request key given to `sqlApi` is the same 400 `retired_key` as over HTTP;
|
|
17
|
+
- a pre-1.0 key in `sqlapi.config` or option of the CLI fails the run, naming its replacement.
|
|
18
|
+
|
|
19
|
+
One change does not announce itself: a schema built with `@sinclair/typebox` instead of
|
|
20
|
+
`typebox` 1.x loses its optional fields, which become required. Check the imports first
|
|
21
|
+
([TypeBox 1.x](#typebox-1x-replaces-sinclairtypebox), section 4).
|
|
22
|
+
|
|
23
|
+
So: update the backend (sections 1–4), start the application and fix what it reports, then
|
|
24
|
+
update the clients (section 5). Section 6 lists what changes without any edit on your side,
|
|
25
|
+
section 7 the schema generator.
|
|
26
|
+
|
|
27
|
+
Contents:
|
|
28
|
+
|
|
29
|
+
1. [Plugin registration and `createSqlApi`](#1-plugin-registration-and-createsqlapi)
|
|
30
|
+
2. [Table configuration](#2-table-configuration)
|
|
31
|
+
3. [Hooks and validators](#3-hooks-and-validators)
|
|
32
|
+
4. [`sqlApi`, the QueryClient and the imports](#4-sqlapi-the-queryclient-and-the-imports)
|
|
33
|
+
5. [HTTP clients](#5-http-clients)
|
|
34
|
+
6. [Behavior that changes without an edit](#6-behavior-that-changes-without-an-edit)
|
|
35
|
+
7. [The CLI: one connection URL](#7-the-cli-one-connection-url)
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## 1. Plugin registration and `createSqlApi`
|
|
40
|
+
|
|
41
|
+
### `dbTables`, not `DbTables`
|
|
42
|
+
|
|
43
|
+
The option is camelCase, like every other one. `DbTables` throws at registration.
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
// before
|
|
47
|
+
await app.register(fastifyAutoSqlApi, { DbTables: dbTables, prefix: '/api' });
|
|
48
|
+
// after
|
|
49
|
+
await app.register(fastifyAutoSqlApi, { dbTables, prefix: '/api' });
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The `DbTables` *type* keeps its name.
|
|
53
|
+
|
|
54
|
+
### Admin is declared with `TENANT_ADMIN`; no tenant is a 401
|
|
55
|
+
|
|
56
|
+
`getTenantId` returning `null` or `undefined` meant "no filter": an auth hook that did not run,
|
|
57
|
+
a missing claim or a typo served the request as a superadmin. It is now a 401 on every table
|
|
58
|
+
with a `tenantScope` in reach, before any SQL. Unrestricted access is returned explicitly:
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import { TENANT_ADMIN } from 'fastify-auto-sqlapi';
|
|
62
|
+
|
|
63
|
+
// before
|
|
64
|
+
getTenantId: (req) => (req.user?.isSuperadmin ? null : req.user?.organizationId ?? null),
|
|
65
|
+
// after
|
|
66
|
+
getTenantId: (req) => (req.user?.isSuperadmin ? TENANT_ADMIN : req.user?.organizationId),
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`[]` is still a 403, and a table with no scope in reach never calls `getTenantId`.
|
|
70
|
+
|
|
71
|
+
### One registration owns `app.sqlApi`; a second one passes `decorate: false`
|
|
72
|
+
|
|
73
|
+
A second registration in the same scope (another prefix, another surface), or one over a
|
|
74
|
+
`sqlApi` the application decorated itself, fails at startup.
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
await app.register(fastifyAutoSqlApi, { dbTables, prefix: '/admin' }); // owns app.sqlApi
|
|
78
|
+
await app.register(fastifyAutoSqlApi, { dbTables: publicTables, prefix: '/public', decorate: false });
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### The plugin is the one way to mount the routes; `operations` narrows a registration
|
|
82
|
+
|
|
83
|
+
The route plugins (`searchRoutes`, `getRoutes`, `insertRoutes`, `updateRoutes`, `deleteRoutes`,
|
|
84
|
+
`bulkUpsertRoutes`, `bulkDeleteRoutes`, `agentManifestRoutes`) and `setupSwagger` are no longer
|
|
85
|
+
exported. A narrower surface is a registration of the plugin with `operations`, intersected
|
|
86
|
+
with each table's own:
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
// before
|
|
90
|
+
await app.register(async (instance) => {
|
|
91
|
+
await setupSwagger(instance, { swagger: true });
|
|
92
|
+
const opts = { DbTables: publicTables };
|
|
93
|
+
await instance.register(searchRoutes, opts);
|
|
94
|
+
await instance.register(getRoutes, opts);
|
|
95
|
+
await instance.register(agentManifestRoutes, opts);
|
|
96
|
+
}, { prefix: '/public' });
|
|
97
|
+
|
|
98
|
+
// after
|
|
99
|
+
await app.register(fastifyAutoSqlApi, {
|
|
100
|
+
dbTables: publicTables, prefix: '/public', decorate: false,
|
|
101
|
+
operations: ['search', 'get'],
|
|
102
|
+
swagger: true, agentManifest: true,
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
A composite-PK table is skipped for `get`/`delete` named here, not refused. The
|
|
107
|
+
agent manifest of a registration lists its narrowed operations, and
|
|
108
|
+
`agentToolSchemas(dbTables, table, { operations })` takes the same option.
|
|
109
|
+
|
|
110
|
+
A consumer `setErrorHandler` never receives a route error: the plugin's own handler answers
|
|
111
|
+
first. To answer a driver error with a status, list its code in `dbErrors` (new in 1.0, ADR
|
|
112
|
+
0024): `dbErrors: { '23505': { status: 409, code: 'duplicate' } }`.
|
|
113
|
+
|
|
114
|
+
### `createSqlApi`: the QueryClient carries the dialect
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
createSqlApi(createQueryClient(pool, 'mysql'), dbTables); // the QueryClient's dialect
|
|
118
|
+
createSqlApi(mysqlQueryable(pool), dbTables, { dialect: 'mysql' }); // a raw pool: the option
|
|
119
|
+
createSqlApi(pgPool, dbTables); // a raw pool without it: postgres
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
A `dialect` option next to a QueryClient throws a `TypeError`, even when it agrees: drop it.
|
|
123
|
+
|
|
124
|
+
### A write runs in a transaction or not at all
|
|
125
|
+
|
|
126
|
+
Inserts and updates run in a transaction, and a `Queryable` without `connect()` can no longer
|
|
127
|
+
open one: the write throws before running anything (ADR 0023). The built-in `pgQueryable(pool)`
|
|
128
|
+
and `mysqlQueryable(pool)`, a `fastify.pg` from `@fastify/postgres` and a `mysql2/promise` pool
|
|
129
|
+
all have it. A custom adapter needs a `connect()` returning `{ query, release }`:
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
const queryable: Queryable = {
|
|
133
|
+
query: (sql, values) => pool.query(sql, values).then(toSqlResult),
|
|
134
|
+
connect: async () => {
|
|
135
|
+
const conn = await pool.getConnection();
|
|
136
|
+
return { query: (sql, values) => conn.query(sql, values).then(toSqlResult), release: () => conn.release() };
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Reads never open a transaction; the plugin logs a warning once when its client cannot.
|
|
142
|
+
|
|
143
|
+
---
|
|
144
|
+
|
|
145
|
+
## 2. Table configuration
|
|
146
|
+
|
|
147
|
+
### `defineTable` takes one flat object; `exportTableInfo` is gone
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
// before
|
|
151
|
+
defineTable({
|
|
152
|
+
primary: 'id',
|
|
153
|
+
...exportTableInfo(SchemaCustomer, { q: Type.String() }, (condition, filters) => { /* … */ }),
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
// after
|
|
157
|
+
defineTable({
|
|
158
|
+
primary: 'id',
|
|
159
|
+
schema: SchemaCustomer,
|
|
160
|
+
extraFilters: { q: Type.String() }, // or a Type.Object, as before
|
|
161
|
+
extendedCondition: (condition, filters) => { /* … */ },
|
|
162
|
+
});
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
- `...exportTableInfo(S)` → `schema: S`; `(S, EF)` → `schema: S, extraFilters: EF`;
|
|
166
|
+
`(S, EF, fn)` → `schema: S, extraFilters: EF, extendedCondition: fn`.
|
|
167
|
+
- The table config carries `schema`, not `Schema`, and has no `filters` function:
|
|
168
|
+
`tableConf.Schema` → `tableConf.schema`.
|
|
169
|
+
- Tables generated by `sqlapi-generate-tables` before 1.0 use the spread: edit them as above.
|
|
170
|
+
|
|
171
|
+
### `insertExclude` replaces `excludeFromCreation`
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
// before
|
|
175
|
+
excludeFromCreation: ['id'],
|
|
176
|
+
// after
|
|
177
|
+
insertExclude: ['id'],
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Same behaviour, under the name of `readExclude` / `writeExclude`: client input dropped on
|
|
181
|
+
insert, the field Optional in the insert body, hooks and FK auto-fill may still set it.
|
|
182
|
+
`defineTable` refuses the old key, naming the new one: ignoring it would let clients write the
|
|
183
|
+
fields it protected. Every generated table with an auto-increment primary key has it; the
|
|
184
|
+
table generator writes the new name, but existing files are never overwritten, so rename by hand
|
|
185
|
+
or with `sed -i 's/excludeFromCreation/insertExclude/g'` on the table files. A plain JavaScript
|
|
186
|
+
object that skips `defineTable` would have the key silently ignored: find them all with
|
|
187
|
+
`grep -rn excludeFromCreation src/`.
|
|
188
|
+
|
|
189
|
+
### `readJoins` and `writeJoins`
|
|
190
|
+
|
|
191
|
+
```ts
|
|
192
|
+
// before
|
|
193
|
+
allowedReadJoins: [buildRelation(SchemaCustomer, 'id', SchemaOrder, 'customerId', { alias: 'orders' })],
|
|
194
|
+
allowedWriteJoins: [buildRelation(SchemaCustomer, 'id', SchemaOrder, 'customerId', { alias: 'orders' })],
|
|
195
|
+
// after
|
|
196
|
+
readJoins: [buildRelation(SchemaCustomer, 'id', SchemaOrder, 'customerId', { alias: 'orders' })],
|
|
197
|
+
writeJoins: [buildRelation(SchemaCustomer, 'id', SchemaOrder, 'customerId', { alias: 'orders' })],
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
A plain rename; the semantics do not change.
|
|
201
|
+
|
|
202
|
+
### `upsertKey` replaces `upsertMap`
|
|
203
|
+
|
|
204
|
+
The key of the main rows sits on the table; the key of the child rows on the write relation
|
|
205
|
+
that writes them. `buildUpsertRule` and `buildUpsertRules` are gone.
|
|
206
|
+
|
|
207
|
+
```ts
|
|
208
|
+
// before
|
|
209
|
+
defineTable({
|
|
210
|
+
primary: 'id', ...exportTableInfo(SchemaProduct),
|
|
211
|
+
allowedWriteJoins: [buildRelation(SchemaProduct, 'id', SchemaTranslation, 'productId', { alias: 'translations' })],
|
|
212
|
+
upsertMap: buildUpsertRules(
|
|
213
|
+
buildUpsertRule(SchemaProduct, ['sku']),
|
|
214
|
+
buildUpsertRule(SchemaTranslation, ['productId', 'lang']),
|
|
215
|
+
),
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
// after
|
|
219
|
+
defineTable({
|
|
220
|
+
primary: 'id', schema: SchemaProduct,
|
|
221
|
+
upsertKey: ['sku'],
|
|
222
|
+
writeJoins: [
|
|
223
|
+
buildRelation(SchemaProduct, 'id', SchemaTranslation, 'productId', { alias: 'translations', upsertKey: ['productId', 'lang'] }),
|
|
224
|
+
],
|
|
225
|
+
});
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
The key is still checked at startup against the primary key and `uniqueKeys` of the schema
|
|
229
|
+
(ADR 0021). An `upsertKey` on a relation in `readJoins` throws: build a separate relation for
|
|
230
|
+
the read side when the same one was listed in both.
|
|
231
|
+
|
|
232
|
+
### `defaultOrder` has the grammar of `orderBy`
|
|
233
|
+
|
|
234
|
+
`field [ASC|DESC]`, comma separated, each a schema field or a computed field, checked by
|
|
235
|
+
`defineTable`. Nothing reaches the SQL as written any more.
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
// before: an unknown token reached the SQL as written
|
|
239
|
+
defaultOrder: 'created_at DESC' // a DB column name
|
|
240
|
+
defaultOrder: 'LOWER(name), id' // an SQL expression
|
|
241
|
+
// after
|
|
242
|
+
defaultOrder: 'createdAt DESC'
|
|
243
|
+
defaultOrder: 'nameLower, id' // computedFields: { nameLower: ({ qiCol }) => ({ expr: `LOWER(${qiCol('name')})`, values: [], type: Type.String() }) }
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
A dotted notation (`alias.field`) is refused: the default applies to requests without joins.
|
|
247
|
+
|
|
248
|
+
### `tenantScope` names what its schema knows
|
|
249
|
+
|
|
250
|
+
Each name of a scope is a field of the schema it belongs to, or the column of one: `column`,
|
|
251
|
+
`anyOf` and `through.localField` on this table's schema, the indirect `column` and
|
|
252
|
+
`through.foreignField` on `through.schema`. A scope naming the columns of its fields keeps
|
|
253
|
+
working as is; the field names are the documented form (ADR 0032).
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
// before: a column the schema omits, or a misspelling, passed startup and failed on the first query
|
|
257
|
+
tenantScope: { column: 'org_id' } // the Schema has no orgId field
|
|
258
|
+
// after: defineTable throws, naming the table and its fields. Keep the column in the Schema
|
|
259
|
+
// (regenerate it, drop it from excludeColumns) and hide it with readExclude if needed
|
|
260
|
+
tenantScope: { column: 'orgId' }
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
### `buildRelation`: `select`, and `target` when a table sits under several keys
|
|
264
|
+
|
|
265
|
+
- `selection` is `select`, an array only: `{ selection: 'id, total' }` → `{ select: ['id', 'total'] }`.
|
|
266
|
+
Each name is checked against the joined schema at startup.
|
|
267
|
+
- A relation over a table that `dbTables` exposes under several keys must name the one whose
|
|
268
|
+
rules apply, or startup fails listing the candidates:
|
|
269
|
+
|
|
270
|
+
```ts
|
|
271
|
+
readJoins: [
|
|
272
|
+
buildRelation(SchemaChat, 'id', SchemaMessage, 'conversationId', { alias: 'messages', target: 'msgPublic' }),
|
|
273
|
+
],
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
---
|
|
277
|
+
|
|
278
|
+
## 3. Hooks and validators
|
|
279
|
+
|
|
280
|
+
### One context object
|
|
281
|
+
|
|
282
|
+
Every hook and validator receives `{ db, req, ...data }` instead of positional parameters.
|
|
283
|
+
`req` is `ApiRequest | undefined`: `undefined` when reached through `sqlApi.*` without a request.
|
|
284
|
+
|
|
285
|
+
| Hook | Before | After |
|
|
286
|
+
|---|---|---|
|
|
287
|
+
| `validate` | `(db, req, main, secondaries)` | `({ db, req, main, upsert, replace, parent })` — the request's sections, see section 5; `parent` is set on a child row, see section 6 |
|
|
288
|
+
| `validateBulk` | `(db, req, items)` | `({ db, req, items, parent })` — `parent` as for `validate` |
|
|
289
|
+
| `beforeInsert`, `beforeUpdate` | `(db, req, record)` | `({ db, req, record })` |
|
|
290
|
+
| `afterInsert` | `(db, req, record, secondaryRecords)` | `({ db, req, record, secondaries })` |
|
|
291
|
+
| `afterUpdate` | `(db, req, record, secondaryRecords, deletionRecords)` | `({ db, req, record, secondaries, deletions })` |
|
|
292
|
+
| `afterRead` | `(db, req, rows, { source, alias })` | `({ db, req, rows, source, alias })` |
|
|
293
|
+
| `beforeDelete`, `afterDelete` | `(db, req, id)` | `({ db, req, id })` |
|
|
294
|
+
| `beforeBulkDelete` | `(db, req, ids)` | `({ db, req, ids })` |
|
|
295
|
+
| `afterBulkDelete` | `(db, req, deletedIds)` | `({ db, req, ids })` |
|
|
296
|
+
|
|
297
|
+
```ts
|
|
298
|
+
// before
|
|
299
|
+
beforeInsert: async (db, req, record) => { record.createdBy = req.user.id; },
|
|
300
|
+
// after
|
|
301
|
+
beforeInsert: async ({ req, record }) => { record.createdBy = req?.user.id; },
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
A plain JavaScript hook keeps loading and receives the context as its first parameter, with
|
|
305
|
+
`record`, `main`… undefined: migrate the hooks before upgrading. Find them with
|
|
306
|
+
`grep -rnE "(before|after)(Insert|Update|Read|Delete|BulkDelete)|validate(Bulk)?:" src/`.
|
|
307
|
+
|
|
308
|
+
### `validate` returns `{ path, code }` objects
|
|
309
|
+
|
|
310
|
+
```ts
|
|
311
|
+
// before
|
|
312
|
+
validate: async (db, req, main) => {
|
|
313
|
+
const errors: ValidationError[] = [];
|
|
314
|
+
if (!main.email) errors.push(['main.email', 'required']);
|
|
315
|
+
if (main.age < 18) errors.push(['main.age', 'too_young', 'Must be an adult']);
|
|
316
|
+
return errors;
|
|
317
|
+
}
|
|
318
|
+
// after
|
|
319
|
+
validate: async ({ main }) => {
|
|
320
|
+
const errors: ValidatorResult = [];
|
|
321
|
+
if (!main.email) errors.push({ path: 'main.email', code: 'required' });
|
|
322
|
+
if (main.age < 18) errors.push({ path: 'main.age', code: 'too_young' });
|
|
323
|
+
return errors;
|
|
324
|
+
}
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
- The objects become the `fields` of the 400 as they are, without a `message`. A hook writes
|
|
328
|
+
no user-facing text: move it to the client, keyed by the code.
|
|
329
|
+
- A tuple, an object with a `message`, or a result that is not an array is a programming
|
|
330
|
+
error (a 500 naming the hook and the entry), and nothing is written.
|
|
331
|
+
- `ValidationError` is no longer exported. The same applies to `validateBulk`, whose paths
|
|
332
|
+
start with `items.<i>`; when it is declared, `validate` does not run in a bulk upsert
|
|
333
|
+
(ADR 0025).
|
|
334
|
+
|
|
335
|
+
### `ctx.db`: `upsert` and `bulkUpsert`
|
|
336
|
+
|
|
337
|
+
See [the QueryClient](#the-queryclient-upsert-and-bulkupsert) below: a hook calling
|
|
338
|
+
`insertOrUpdate` or `bulkInsertOrUpdate` on `db` needs the rename.
|
|
339
|
+
|
|
340
|
+
---
|
|
341
|
+
|
|
342
|
+
## 4. `sqlApi`, the QueryClient and the imports
|
|
343
|
+
|
|
344
|
+
### `sqlApi.insert` / `sqlApi.update` take the HTTP body
|
|
345
|
+
|
|
346
|
+
```ts
|
|
347
|
+
// before
|
|
348
|
+
await app.sqlApi.insert('customer', { record: { name: 'Mario' } }, req);
|
|
349
|
+
// after
|
|
350
|
+
await app.sqlApi.insert('customer', { main: { name: 'Mario' } }, req);
|
|
351
|
+
await app.sqlApi.insert('customer', req.body, req); // a body for POST /rest/customer, as is
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
`record` throws a `TypeError` naming `main`. Hooks keep `record`. The child rows go under
|
|
355
|
+
`upsert`, `delete` and `replace`, as in the HTTP body (section 5).
|
|
356
|
+
|
|
357
|
+
### `sqlApi.bulkDelete` takes `{ ids }`
|
|
358
|
+
|
|
359
|
+
```ts
|
|
360
|
+
// before
|
|
361
|
+
await app.sqlApi.bulkDelete('agent', [7, 8], req);
|
|
362
|
+
// after
|
|
363
|
+
await app.sqlApi.bulkDelete('agent', { ids: [7, 8] }, req);
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
### `sqlApi.search` takes the HTTP search body
|
|
367
|
+
|
|
368
|
+
The search changes of [section 5](#5-http-clients) apply to `sqlApi.search` as well: `select`
|
|
369
|
+
instead of `selectComputed`, `compute` instead of `computeMin|Max|Sum|Avg`, the `joinGroup`
|
|
370
|
+
request and result shapes, `result.computed`. The one-field keys throw a 400 `retired_key`:
|
|
371
|
+
|
|
372
|
+
```ts
|
|
373
|
+
// before
|
|
374
|
+
await app.sqlApi.search('order', { computeSum: 'total' });
|
|
375
|
+
// after
|
|
376
|
+
await app.sqlApi.search('order', { compute: { sum: ['total'] } });
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
### A table `sqlApi` does not know is a programming error
|
|
380
|
+
|
|
381
|
+
`sqlApi.search('custmer', …)` throws a plain `Error` naming the known tables; it was a 400
|
|
382
|
+
`unknown_table`. `createSqlApi` infers the table names from `dbTables`, so a misspelled one
|
|
383
|
+
fails at compile time.
|
|
384
|
+
|
|
385
|
+
### The QueryClient: `upsert` and `bulkUpsert`
|
|
386
|
+
|
|
387
|
+
```ts
|
|
388
|
+
// before
|
|
389
|
+
db.insertOrUpdate(table, record, keys, pk) // → pk
|
|
390
|
+
db.insertOrUpdateWithAction(table, record, keys, pk) // → { pk, action }
|
|
391
|
+
db.bulkInsertOrUpdate(table, records, keys, pk, 500, ['org_id']) // → pk[]
|
|
392
|
+
db.bulkInsertOrUpdateWithAction(table, records, keys, pk) // → { pk, action }[]
|
|
393
|
+
// after
|
|
394
|
+
db.upsert(table, record, keys, pk) // → { pk, action }
|
|
395
|
+
db.bulkUpsert(table, records, keys, pk, { chunkSize: 500, immutableCols: ['org_id'] }) // → { pk, action }[]
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
- Where the PK was read: `(await db.upsert(…)).pk`, `(await db.bulkUpsert(…)).map((r) => r.pk)`.
|
|
399
|
+
- A positional chunk size or immutable column list throws a `TypeError`.
|
|
400
|
+
- A `Date` is a value now; a JSON object is not (`JSON.stringify` it: the drivers do not).
|
|
401
|
+
|
|
402
|
+
### TypeBox 1.x replaces `@sinclair/typebox`
|
|
403
|
+
|
|
404
|
+
`Type` and `Static`, re-exported by `fastify-auto-sqlapi`, come from
|
|
405
|
+
[`typebox`](https://www.npmjs.com/package/typebox) 1.x, the package TypeBox 1.0 moved to and that
|
|
406
|
+
`@fastify/type-provider-typebox` 6 requires; `@sinclair/typebox` is no longer a dependency. The
|
|
407
|
+
JSON Schema sent to Fastify, Ajv and Swagger is unchanged.
|
|
408
|
+
|
|
409
|
+
The two versions mark a schema's kind and its `Optional` modifier differently, so a schema from
|
|
410
|
+
one placed inside an object built by the other loses its `Optional`: the field silently becomes
|
|
411
|
+
required, and requests that omit it are a `400 required`.
|
|
412
|
+
|
|
413
|
+
- Code that imports `Type` from `fastify-auto-sqlapi`, as the generated schema files do: nothing
|
|
414
|
+
to do at runtime. TypeScript code naming TypeBox types (`TSchema`, `TObject`, …) imports them
|
|
415
|
+
from `fastify-auto-sqlapi` or from `typebox`.
|
|
416
|
+
- Code that builds schemas with `@sinclair/typebox` and passes them to this package
|
|
417
|
+
(`schemaOverrides`, computed fields, extra filters, hand-written schema files): replace
|
|
418
|
+
`'@sinclair/typebox'` with `'typebox'` (1.x, any copy) or import `Type` from
|
|
419
|
+
`fastify-auto-sqlapi`. Re-running `npx sqlapi-generate-schema` regenerates schema files with the
|
|
420
|
+
right import. Find the leftovers with `grep -rn "@sinclair/typebox" src/`.
|
|
421
|
+
|
|
422
|
+
### Imports
|
|
423
|
+
|
|
424
|
+
Gone from the package entry, with what replaces them:
|
|
425
|
+
|
|
426
|
+
| Removed | Use instead |
|
|
427
|
+
|---|---|
|
|
428
|
+
| `ITable` | `TableConfig`, the same type under the glossary's name |
|
|
429
|
+
| `escapeIdent` | `db.qi(name)` on the QueryClient a hook receives: it quotes for the dialect, where `escapeIdent` doubled `"` only and was wrong on MySQL |
|
|
430
|
+
| `exportTableInfo`, `TableFilterFn` | `defineTable({ schema, extraFilters, extendedCondition })`; type `TableDefinition` |
|
|
431
|
+
| `buildUpsertRule`, `buildUpsertRules` | `upsertKey` on the table and on `buildRelation` |
|
|
432
|
+
| `searchRoutes`, `getRoutes`, `insertRoutes`, `updateRoutes`, `deleteRoutes`, `bulkUpsertRoutes`, `bulkDeleteRoutes`, `agentManifestRoutes`, `setupSwagger` | the plugin, with `operations`, `swagger`, `agentManifest` |
|
|
433
|
+
| `searchEngine`, `getEngine`, `insertEngine`, `updateEngine`, `deleteEngine`, `bulkUpsertEngine`, `bulkDeleteEngine` | `createSqlApi(db, dbTables).<operation>(table, …)` |
|
|
434
|
+
| `SearchTableBodyPost`, `InsertTableBody`, `UpdateTableBody`, `BulkUpsertTableBody`, `BulkDeleteTableBody` and their `*Response` | `agentToolSchemas(dbTables, table)` for the request schemas |
|
|
435
|
+
| `SearchTableQuery`, `SearchTableQueryString` | — the search has no querystring |
|
|
436
|
+
| `ValidationError` | `ValidatorResult`, an array of `{ path, code }` |
|
|
437
|
+
| `toCamelCase`, `toUnderscore`, `toSchemaName`, `camelcaseObject`, `snakecaseRecord` | `Schema.col(field)` for a column name |
|
|
438
|
+
| `getDialect`, `SqlDialect` | the dialect name; `db.dialectName`, `db.cbDialect` |
|
|
439
|
+
| `resolveTenant`, `TenantContext` | `tenantScope` on the table, `getTenantId` on the plugin |
|
|
440
|
+
| `SearchParams`, `GetParams`, `InsertParams`, `UpdateParams`, `DeleteParams`, `BulkUpsertParams`, `BulkDeleteParams` | `SqlApiSearchParams`, `SqlApiInsertParams`, `SqlApiUpdateParams`, `SqlApiBulkDeleteParams` |
|
|
441
|
+
| `ColumnInfo`, `TableMap` | — CLI internals |
|
|
442
|
+
| `SqlApiConfig` | `CliConfig`, every key optional: `export default { … } satisfies CliConfig` |
|
|
443
|
+
|
|
444
|
+
`test/unit/public-exports.test.js` pins the runtime exports of 1.0.
|
|
445
|
+
|
|
446
|
+
---
|
|
447
|
+
|
|
448
|
+
## 5. HTTP clients
|
|
449
|
+
|
|
450
|
+
### The search request travels in the body only
|
|
451
|
+
|
|
452
|
+
```jsonc
|
|
453
|
+
// before
|
|
454
|
+
POST /search/orders?orderBy=total+DESC&page=2&itemsPerPage=20&computeSum=total
|
|
455
|
+
{ "filters": { "status": "paid" } }
|
|
456
|
+
// after
|
|
457
|
+
POST /search/orders
|
|
458
|
+
{
|
|
459
|
+
"filters": { "status": "paid" },
|
|
460
|
+
"orderBy": "total DESC",
|
|
461
|
+
"paginator": { "page": 2, "itemsPerPage": 20 },
|
|
462
|
+
"compute": { "sum": ["total"] }
|
|
463
|
+
}
|
|
464
|
+
```
|
|
465
|
+
|
|
466
|
+
`orderBy`, `page`, `itemsPerPage` and `computeMin|Max|Sum|Avg` in the querystring are a 400
|
|
467
|
+
`retired_key` at that key. `page` alone still defaults `itemsPerPage` to 500 (or
|
|
468
|
+
`maxItemsPerPage` when lower). Any other querystring key is left alone.
|
|
469
|
+
|
|
470
|
+
### `select` is the one projection word
|
|
471
|
+
|
|
472
|
+
```jsonc
|
|
473
|
+
// before
|
|
474
|
+
{ "select": ["id", "name"], "selectComputed": ["displayName"],
|
|
475
|
+
"joinMultiple": { "orders": { "selection": "id,total" } } }
|
|
476
|
+
// after
|
|
477
|
+
{ "select": ["id", "name", "displayName"],
|
|
478
|
+
"joinMultiple": { "orders": { "select": ["id", "total"] } } }
|
|
479
|
+
```
|
|
480
|
+
|
|
481
|
+
`select` takes schema and computed fields alike. `selectComputed` alone used to mean "every
|
|
482
|
+
column plus these": that is now `"select": ["*", "displayName"]`, `*` standing for every
|
|
483
|
+
readable field. `selectComputed` and a join's `selection` are a 400 `retired_key`.
|
|
484
|
+
|
|
485
|
+
### `compute` answers in `computed`, with or without a paginator
|
|
486
|
+
|
|
487
|
+
```jsonc
|
|
488
|
+
// request: no paginator needed; count and distinctCount added
|
|
489
|
+
{ "filters": { "status": "paid" }, "compute": { "sum": ["total"], "count": ["id"] } }
|
|
490
|
+
// response — before
|
|
491
|
+
{ "main": […], "pagination": { "total": 25, "pages": 3, "computed": { "sum": { "total": 999 } }, "paginator": {…} } }
|
|
492
|
+
// response — after
|
|
493
|
+
{ "main": […], "computed": { "sum": { "total": 999 }, "count": { "id": 25 } } }
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
Read `result.computed`. It covers every matching row, never the page; `pagination` keeps
|
|
497
|
+
`total`, `pages` and `paginator` and comes only with a paginator.
|
|
498
|
+
|
|
499
|
+
### `joinGroup` has one request and one response shape
|
|
500
|
+
|
|
501
|
+
```jsonc
|
|
502
|
+
// request — before / after
|
|
503
|
+
"joinGroup": { "orders": { "aggregations": { "by": "status", "sum": ["total"] } } }
|
|
504
|
+
"joinGroup": { "orders": { "by": "status", "sum": ["total"] } }
|
|
505
|
+
|
|
506
|
+
// response without by — before / after
|
|
507
|
+
"joinGroup": { "orders": { "sum": { "total": 150 } } }
|
|
508
|
+
"joinGroup": { "orders": { "rows": [{ "sum": { "total": 150 } }] } }
|
|
509
|
+
|
|
510
|
+
// response with by — before / after
|
|
511
|
+
"joinGroup": { "orders": { "rows": [{ "by": "pending", "sum_total": 100 }] } }
|
|
512
|
+
"joinGroup": { "orders": { "rows": [{ "by": "pending", "sum": { "total": 100 } }] } }
|
|
513
|
+
```
|
|
514
|
+
|
|
515
|
+
Aggregate values are shown as numbers for brevity: they reach the client as the driver returns
|
|
516
|
+
them, strings on `pg` (AGENTS_FRONTEND.md). No main rows gives `rows: []`. The `aggregations` wrapper is a 400, and so is a joinGroup with
|
|
517
|
+
no aggregate function. Error paths drop the `aggregations` segment.
|
|
518
|
+
|
|
519
|
+
### A bulk delete takes `{ ids }`
|
|
520
|
+
|
|
521
|
+
```js
|
|
522
|
+
// before
|
|
523
|
+
fetch('/api/bulk/agent/delete', { method: 'POST', body: JSON.stringify([{ agentId: 7 }, { agentId: 8 }]) });
|
|
524
|
+
// after
|
|
525
|
+
fetch('/api/bulk/agent/delete', { method: 'POST', body: JSON.stringify({ ids: [7, 8] }) });
|
|
526
|
+
```
|
|
527
|
+
|
|
528
|
+
The same body for every table, whatever its primary key is called; the ids are typed as it.
|
|
529
|
+
|
|
530
|
+
### Child rows: `upsert`, `delete`, `replace`
|
|
531
|
+
|
|
532
|
+
```jsonc
|
|
533
|
+
// before
|
|
534
|
+
PUT /rest/post { "main": { "id": 1 }, "secondaries": { "tags": [{ "tagId": 3 }] }, "deletions": { "tags": [{ "tagId": 1 }] } }
|
|
535
|
+
// after
|
|
536
|
+
PUT /rest/post { "main": { "id": 1 }, "upsert": { "tags": [{ "tagId": 3 }] }, "delete": { "tags": [{ "tagId": 1 }] } }
|
|
537
|
+
// new: the complete set, the tags left out are deleted (the alias needs an upsertKey)
|
|
538
|
+
PUT /rest/post { "main": { "id": 1 }, "replace": { "tags": [{ "tagId": 2 }, { "tagId": 3 }] } }
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
The request names an action per section; the response keeps its nouns, `secondaries` for the
|
|
542
|
+
rows written and `deletions` for the rows removed, and so do `afterInsert`/`afterUpdate`.
|
|
543
|
+
`validate` receives `{ main, upsert, replace }`, and its paths start with those names
|
|
544
|
+
(`upsert.tags.0.tagId`). `secondaries` or `deletions` in a request is a 400 `retired_key`.
|
|
545
|
+
The same holds in a bulk upsert item and in `sqlApi.insert`/`update`/`bulkUpsert` (ADR 0029).
|
|
546
|
+
|
|
547
|
+
### An undeclared write alias is a 400
|
|
548
|
+
|
|
549
|
+
```jsonc
|
|
550
|
+
// writeJoins declares "orders"
|
|
551
|
+
POST /rest/customer
|
|
552
|
+
{ "main": { "name": "Mario" }, "upsert": { "order": [{ "total": 100 }] } }
|
|
553
|
+
// before: 201 — the customer is written, the order is not, nothing says so
|
|
554
|
+
// after: 400 { "fields": [ { "path": "upsert.order", "code": "unknown_field" } ] }, nothing written
|
|
555
|
+
```
|
|
556
|
+
|
|
557
|
+
The same for `delete` and `replace`, for an alias the table only reads, and in a bulk upsert
|
|
558
|
+
(`<i>.upsert.<alias>`, no item written).
|
|
559
|
+
|
|
560
|
+
### One error envelope
|
|
561
|
+
|
|
562
|
+
Every error is `{ statusCode, error, message, requestId, fields? }`:
|
|
563
|
+
|
|
564
|
+
- `error` is the HTTP reason phrase (`Bad Request`, `Not Found`) for every status; the
|
|
565
|
+
engine's 4xx used to say `Error`.
|
|
566
|
+
- `requestId` is on every error, and matches the server log's `reqId`.
|
|
567
|
+
- every 400 carries `fields: [{ path, code, message? }]`, the engine's rejections included.
|
|
568
|
+
Map `path` to a form field and translate `code`; `message` is a description for the
|
|
569
|
+
developer, not for the user, and is absent on a backend validation and a `dbErrors` answer,
|
|
570
|
+
where the code says everything.
|
|
571
|
+
|
|
572
|
+
---
|
|
573
|
+
|
|
574
|
+
## 6. Behavior that changes without an edit
|
|
575
|
+
|
|
576
|
+
- **A search without `paginator` is not paginated.** Every search used to become page 1 of
|
|
577
|
+
500 rows, with a `COUNT(*)` and a `pagination` block, because the querystring schema
|
|
578
|
+
injected a default. It now returns up to `maxItemsPerPage` rows, without `pagination`.
|
|
579
|
+
- **A join target's config applies whatever its `dbTables` key is called.** A table exposed
|
|
580
|
+
under a key other than its name ran its joins with no config: its `readExclude` fields were
|
|
581
|
+
returned through `joinMultiple` and `joinLeft`. They are now hidden, as configured.
|
|
582
|
+
- **`:id` is typed as the primary key** on `GET` and `DELETE /rest/:table/:id`: `/rest/item/abc`
|
|
583
|
+
on an integer key is a 400 on `id`, no longer a 500.
|
|
584
|
+
- **Each registration's routes run with its own configuration.** A second registration used
|
|
585
|
+
to serve its routes with the first one's `dbTables`, `getTenantId` and table rules.
|
|
586
|
+
- **A child row is validated by its own table.** Rows sent under `upsert` or `replace` now run
|
|
587
|
+
the child table's `validate` (or `validateBulk`), with `parent: { alias, main }`; they used to
|
|
588
|
+
skip it. A child `validate` that requires the FK to the parent refuses an insert whose parent
|
|
589
|
+
key the database generates: guard it with `if (!parent && !main.<fk>)` (ADR 0030).
|
|
590
|
+
- **An upsert key under `insertExclude` names an existing row.** With `upsertKey: ['id']` and
|
|
591
|
+
`insertExclude: ['id']`, a row sent with an id used to be inserted again under a new id. It
|
|
592
|
+
now updates the row with that id; an id naming no row is a 400 `not_found` (ADR 0031).
|
|
593
|
+
|
|
594
|
+
---
|
|
595
|
+
|
|
596
|
+
## 7. The CLI: one connection URL
|
|
597
|
+
|
|
598
|
+
`sqlapi-generate-schema` connects through one URL, whose scheme names the dialect:
|
|
599
|
+
`postgres://` (or `postgresql://`), `mysql://`, `mariadb://`. It is read from `--url`, then from
|
|
600
|
+
`connection` in `sqlapi.config`, then from `DATABASE_URL`; the `.env` of the current directory is
|
|
601
|
+
loaded before the config.
|
|
602
|
+
|
|
603
|
+
```bash
|
|
604
|
+
# before
|
|
605
|
+
POSTGRES_HOST=db POSTGRES_USER=app POSTGRES_PASSWORD=x POSTGRES_DB=shop npx sqlapi-generate-schema
|
|
606
|
+
MYSQL_HOST=db MYSQL_USER=app MYSQL_PASSWORD=x MYSQL_DB=shop npx sqlapi-generate-schema --dialect mysql
|
|
607
|
+
|
|
608
|
+
# after: DATABASE_URL in .env (or the environment), no argument
|
|
609
|
+
DATABASE_URL=mysql://app:x@db:3306/shop
|
|
610
|
+
npx sqlapi-generate-schema
|
|
611
|
+
```
|
|
612
|
+
|
|
613
|
+
```ts
|
|
614
|
+
// before
|
|
615
|
+
export default { dialect: 'mysql', envFile: '.env.local' } satisfies SqlApiConfig;
|
|
616
|
+
|
|
617
|
+
// after
|
|
618
|
+
process.loadEnvFile('.env.local'); // only for an env file other than .env
|
|
619
|
+
export default { connection: process.env.SHOP_DB_URL } satisfies CliConfig; // or omit it: DATABASE_URL
|
|
620
|
+
```
|
|
621
|
+
|
|
622
|
+
- `POSTGRES_HOST|PORT|USER|PASSWORD|DB` and `MYSQL_HOST|PORT|USER|PASSWORD|DB` are no longer
|
|
623
|
+
read: compose them into the URL, percent-encoding a password that holds `@`, `/` or `:`.
|
|
624
|
+
- With no URL the run fails saying how to give one. It used to fall back to
|
|
625
|
+
`test:test@127.0.0.1:5433/testdb` (`3306` on MySQL): the library's own test database.
|
|
626
|
+
- `dialect` and `envFile` in the config, `--dialect` on the command line, and any key or option
|
|
627
|
+
the CLI does not know fail the run instead of being ignored. A config that fails to load fails
|
|
628
|
+
the run too: it used to fall back to the defaults with a warning.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "fastify-auto-sqlapi",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "Fastify plugin for automatic CRUD API generation from PostgreSQL, MySQL and MariaDB tables",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -40,8 +40,7 @@
|
|
|
40
40
|
"dup:strict": "jscpd src --reporters console",
|
|
41
41
|
"knip": "knip --max-issues 0 --treat-config-hints-as-errors --treat-tag-hints-as-errors",
|
|
42
42
|
"depcruise": "depcruise src --config .dependency-cruiser.mjs --output-type err",
|
|
43
|
-
"
|
|
44
|
-
"debt": "npm run lint:strict; npm run dup:strict; npm run depcruise:strict",
|
|
43
|
+
"debt": "npm run lint:strict; npm run dup:strict",
|
|
45
44
|
"check": "npm run lint && npm run typecheck",
|
|
46
45
|
"verify": "npm run check && npm run build && npm run index:check && npm run dup && npm run depcruise && npm run knip && npm run test:unit",
|
|
47
46
|
"prepublishOnly": "npm run build && npm run test:unit",
|
|
@@ -82,9 +81,9 @@
|
|
|
82
81
|
},
|
|
83
82
|
"homepage": "https://github.com/LucaRainone/fastify-auto-sqlapi#readme",
|
|
84
83
|
"dependencies": {
|
|
85
|
-
"@sinclair/typebox": "^0.34.14",
|
|
86
84
|
"fastify-plugin": "^6.0.0",
|
|
87
|
-
"node-condition-builder": "^1.2.0"
|
|
85
|
+
"node-condition-builder": "^1.2.0",
|
|
86
|
+
"typebox": "^1.4.6"
|
|
88
87
|
},
|
|
89
88
|
"devDependencies": {
|
|
90
89
|
"@eslint/js": "^10.0.1",
|