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
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, {
|
|
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
|
-
|
|
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
|
|
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
|
-
"
|
|
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
|
-
"
|
|
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 (`
|
|
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
|
|
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
|
-
>
|
|
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 (
|
|
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 ·
|
|
78
|
-
from the
|
|
79
|
-
transactions, so a write and its
|
|
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
|
|
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
|
|
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; `
|
|
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
|
|
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
|
|
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:
|
|
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
|
-
|
|
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, {
|
|
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 (+
|
|
185
|
-
| `PUT` | `/api/rest/customer` | update (+
|
|
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,
|
|
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 `
|
|
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
|
|
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 *
|
|
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. `
|
|
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.** `
|
|
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.
|
|
292
|
-
mapping is product logic
|
|
293
|
-
|
|
294
|
-
|
|
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,
|
|
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
|
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import * as fs from 'node:fs';
|
|
3
3
|
import * as path from 'node:path';
|
|
4
|
-
import { loadConfig } from '../lib/cli/config.js';
|
|
5
|
-
import {
|
|
4
|
+
import { loadConfig, maskPassword, resolveConnection } from '../lib/cli/config.js';
|
|
5
|
+
import { introspectTables } from '../lib/cli/pg-introspect.js';
|
|
6
6
|
import { buildMysqlConnectionConfig, introspectMysqlTables } from '../lib/cli/mysql-introspect.js';
|
|
7
7
|
import { applyExcludeColumns, applyExcludeTables, buildTableMap, generateSchemaFile, } from '../lib/cli/schema-codegen.js';
|
|
8
|
-
import {
|
|
8
|
+
import { CONSOLE_COLORS, display, displayAsTableRow, parseArgs, runCli } from './utils.js';
|
|
9
9
|
const STATUS_COLOR = {
|
|
10
10
|
created: CONSOLE_COLORS.green,
|
|
11
11
|
updated: CONSOLE_COLORS.cyan,
|
|
12
12
|
untouched: CONSOLE_COLORS.gray,
|
|
13
13
|
};
|
|
14
|
-
function introspect(
|
|
15
|
-
if (dialect === 'mysql' || dialect === 'mariadb') {
|
|
16
|
-
const connConfig = buildMysqlConnectionConfig();
|
|
14
|
+
function introspect(connection, schema) {
|
|
15
|
+
if (connection.dialect === 'mysql' || connection.dialect === 'mariadb') {
|
|
16
|
+
const connConfig = buildMysqlConnectionConfig(connection.url);
|
|
17
17
|
return introspectMysqlTables(connConfig, connConfig.database);
|
|
18
18
|
}
|
|
19
|
-
return introspectTables(
|
|
19
|
+
return introspectTables(connection.url, schema);
|
|
20
20
|
}
|
|
21
21
|
/** Narrow the map to the `--tables` selection. Returns false when nothing matched. */
|
|
22
22
|
function keepOnlyRequestedTables(tableMap, tableNames) {
|
|
@@ -132,19 +132,19 @@ await runCli('fastify-auto-sqlapi: generating schemas', async () => {
|
|
|
132
132
|
const cliArgs = parseArgs({
|
|
133
133
|
output: { type: 'value' },
|
|
134
134
|
tables: { type: 'list' },
|
|
135
|
-
|
|
135
|
+
url: { type: 'value' },
|
|
136
136
|
});
|
|
137
137
|
const config = await loadConfig();
|
|
138
|
-
|
|
139
|
-
const
|
|
140
|
-
const schema = config.schema || 'public';
|
|
138
|
+
const connection = resolveConnection({ url: cliArgs.url, config, env: process.env });
|
|
139
|
+
const schema = config.schema;
|
|
141
140
|
const outputDir = path.resolve(process.cwd(), cliArgs.output || config.outputDir);
|
|
142
141
|
const schemasDir = path.join(outputDir, 'schemas');
|
|
143
142
|
if (!fs.existsSync(schemasDir)) {
|
|
144
143
|
fs.mkdirSync(schemasDir, { recursive: true });
|
|
145
144
|
display(`Created directory: ${schemasDir}`, CONSOLE_COLORS.green);
|
|
146
145
|
}
|
|
147
|
-
|
|
146
|
+
display(`Introspecting ${maskPassword(connection.url)}`, CONSOLE_COLORS.gray);
|
|
147
|
+
const rows = await introspect(connection, schema);
|
|
148
148
|
if (rows.length === 0) {
|
|
149
149
|
display(`No tables found in schema "${schema}".`, CONSOLE_COLORS.magenta);
|
|
150
150
|
return;
|
|
@@ -3,7 +3,7 @@ import * as fs from 'node:fs';
|
|
|
3
3
|
import * as path from 'node:path';
|
|
4
4
|
import { loadConfig } from '../lib/cli/config.js';
|
|
5
5
|
import { parseSchemaFile, generateSingleTableFile, generateDbTablesIndex } from '../lib/cli/tables-codegen.js';
|
|
6
|
-
import {
|
|
6
|
+
import { CONSOLE_COLORS, display, displayAsTableRow, error, parseArgs, runCli } from './utils.js';
|
|
7
7
|
function printHelp() {
|
|
8
8
|
console.log('');
|
|
9
9
|
display('Usage:', CONSOLE_COLORS.yellow);
|
|
@@ -101,7 +101,6 @@ await runCli('fastify-auto-sqlapi: generating tables template', async () => {
|
|
|
101
101
|
process.exit(1);
|
|
102
102
|
}
|
|
103
103
|
const config = await loadConfig();
|
|
104
|
-
loadEnvFile(config.envFile);
|
|
105
104
|
const outputDir = path.resolve(process.cwd(), cliArgs.output || config.outputDir);
|
|
106
105
|
const schemasDir = path.join(outputDir, 'schemas');
|
|
107
106
|
const tablesDir = path.join(outputDir, 'tables');
|
package/dist/bin/utils.d.ts
CHANGED
|
@@ -1,8 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Load .env file from cwd if it exists.
|
|
3
|
-
* Does not override already-set environment variables.
|
|
4
|
-
*/
|
|
5
|
-
export declare function loadEnvFile(envFile?: string): void;
|
|
6
1
|
export declare const CONSOLE_COLORS: {
|
|
7
2
|
readonly black: 30;
|
|
8
3
|
readonly gray: 90;
|
|
@@ -24,7 +19,8 @@ type ArgSpec = {
|
|
|
24
19
|
};
|
|
25
20
|
type ArgValue<S extends ArgSpec> = S['type'] extends 'flag' ? boolean : S['type'] extends 'list' ? string[] : string | undefined;
|
|
26
21
|
/**
|
|
27
|
-
* Tiny declarative argv parser for the bundled CLIs.
|
|
22
|
+
* Tiny declarative argv parser for the bundled CLIs. An option not in `spec` is an error: left
|
|
23
|
+
* unread, its value would be taken for a positional table name.
|
|
28
24
|
* - `value` → recognized as `--name X`, last value wins
|
|
29
25
|
* - `flag` → recognized as `--name`, default false
|
|
30
26
|
* - `list` → comma-separated `--name a,b,c`; can also accept positional comma-/space- separated tokens
|
package/dist/bin/utils.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/bin/utils.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/bin/utils.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,cAAc;;;;;;;;CAQjB,CAAC;AAEX,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,EAChB,KAAK,GAAE,MAAU,GAChB,IAAI,CAQN;AAED,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,GAAE,MAAU,GAAG,IAAI,CAE7D;AAED,wBAAgB,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAExC;AAED,KAAK,OAAO,GACR;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,GACjB;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,GAChB;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAErB,KAAK,QAAQ,CAAC,CAAC,SAAS,OAAO,IAC7B,CAAC,CAAC,MAAM,CAAC,SAAS,MAAM,GAAG,OAAO,GAClC,CAAC,CAAC,MAAM,CAAC,SAAS,MAAM,GAAG,MAAM,EAAE,GACnC,MAAM,GAAG,SAAS,CAAC;AAOrB;;;;;;;;;GASG;AACH,wBAAgB,SAAS,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACzD,IAAI,EAAE,CAAC,EACP,IAAI,WAAwB,GAC3B;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAAE,GAAG;IAAE,UAAU,EAAE,MAAM,EAAE,CAAA;CAAE,CAmB/D;AA2DD;;;GAGG;AACH,wBAAsB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAQjF"}
|
package/dist/bin/utils.js
CHANGED
|
@@ -1,33 +1,3 @@
|
|
|
1
|
-
import { readFileSync, existsSync } from 'node:fs';
|
|
2
|
-
import { resolve } from 'node:path';
|
|
3
|
-
/**
|
|
4
|
-
* Load .env file from cwd if it exists.
|
|
5
|
-
* Does not override already-set environment variables.
|
|
6
|
-
*/
|
|
7
|
-
export function loadEnvFile(envFile) {
|
|
8
|
-
const envPath = resolve(process.cwd(), envFile || '.env');
|
|
9
|
-
if (!existsSync(envPath))
|
|
10
|
-
return;
|
|
11
|
-
const content = readFileSync(envPath, 'utf-8');
|
|
12
|
-
for (const line of content.split('\n')) {
|
|
13
|
-
const trimmed = line.trim();
|
|
14
|
-
if (!trimmed || trimmed.startsWith('#'))
|
|
15
|
-
continue;
|
|
16
|
-
const eqIndex = trimmed.indexOf('=');
|
|
17
|
-
if (eqIndex === -1)
|
|
18
|
-
continue;
|
|
19
|
-
const key = trimmed.slice(0, eqIndex).trim();
|
|
20
|
-
let value = trimmed.slice(eqIndex + 1).trim();
|
|
21
|
-
// Strip surrounding quotes
|
|
22
|
-
if ((value.startsWith('"') && value.endsWith('"')) ||
|
|
23
|
-
(value.startsWith("'") && value.endsWith("'"))) {
|
|
24
|
-
value = value.slice(1, -1);
|
|
25
|
-
}
|
|
26
|
-
if (!(key in process.env)) {
|
|
27
|
-
process.env[key] = value;
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
1
|
export const CONSOLE_COLORS = {
|
|
32
2
|
black: 30,
|
|
33
3
|
gray: 90,
|
|
@@ -52,8 +22,13 @@ export function display(text, color = 0) {
|
|
|
52
22
|
export function error(text) {
|
|
53
23
|
display(text, CONSOLE_COLORS.red);
|
|
54
24
|
}
|
|
25
|
+
/** Options retired in 1.0, each with what replaces it. */
|
|
26
|
+
const RETIRED_OPTIONS = {
|
|
27
|
+
dialect: 'the dialect is the scheme of the connection URL (postgres://, mysql://, mariadb://)',
|
|
28
|
+
};
|
|
55
29
|
/**
|
|
56
|
-
* Tiny declarative argv parser for the bundled CLIs.
|
|
30
|
+
* Tiny declarative argv parser for the bundled CLIs. An option not in `spec` is an error: left
|
|
31
|
+
* unread, its value would be taken for a positional table name.
|
|
57
32
|
* - `value` → recognized as `--name X`, last value wins
|
|
58
33
|
* - `flag` → recognized as `--name`, default false
|
|
59
34
|
* - `list` → comma-separated `--name a,b,c`; can also accept positional comma-/space- separated tokens
|
|
@@ -94,9 +69,14 @@ function pushCsv(target, raw) {
|
|
|
94
69
|
*/
|
|
95
70
|
function readOption(out, spec, argv, i) {
|
|
96
71
|
const name = argv[i].slice(2);
|
|
72
|
+
if (!Object.hasOwn(spec, name)) {
|
|
73
|
+
if (Object.hasOwn(RETIRED_OPTIONS, name)) {
|
|
74
|
+
throw new Error(`--${name} was removed in 1.0: ${RETIRED_OPTIONS[name]}`);
|
|
75
|
+
}
|
|
76
|
+
const known = Object.keys(spec).map((n) => '--' + n).join(', ');
|
|
77
|
+
throw new Error(`unknown option --${name}. Known options: ${known}`);
|
|
78
|
+
}
|
|
97
79
|
const def = spec[name];
|
|
98
|
-
if (!def)
|
|
99
|
-
return 0;
|
|
100
80
|
const hasNext = i + 1 < argv.length;
|
|
101
81
|
if (def.type === 'flag') {
|
|
102
82
|
out[name] = true;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,38 +1,18 @@
|
|
|
1
|
-
export {
|
|
2
|
-
export { QueryClient, createQueryClient,
|
|
3
|
-
export
|
|
4
|
-
export { pgQueryable } from './lib/adapters/pg-adapter.js';
|
|
5
|
-
export { mysqlQueryable } from './lib/adapters/mysql-adapter.js';
|
|
6
|
-
export {
|
|
1
|
+
export { httpError, type HttpErrorField } from './lib/errors.js';
|
|
2
|
+
export { QueryClient, createQueryClient, type BulkUpsertOptions } from './lib/db.js';
|
|
3
|
+
export type { DialectName } from './lib/dialect.js';
|
|
4
|
+
export { pgQueryable, type PgQueryable } from './lib/adapters/pg-adapter.js';
|
|
5
|
+
export { mysqlQueryable, type MysqlQueryable } from './lib/adapters/mysql-adapter.js';
|
|
6
|
+
export { defineTable, buildRelation } from './lib/table-helpers.js';
|
|
7
|
+
export type { TableDefinition, BuildRelationOptions } from './lib/table-helpers.js';
|
|
7
8
|
export { Nullable } from './lib/nullable.js';
|
|
8
|
-
export { buildAgentManifest, renderAgentManifestMd, type AgentManifest, type ManifestTable, } from './lib/agent/manifest.js';
|
|
9
|
+
export { buildAgentManifest, renderAgentManifestMd, type AgentManifest, type ManifestTable, type ManifestField, type ManifestJoin, } from './lib/agent/manifest.js';
|
|
9
10
|
export { agentToolSchemas, type AgentToolSchemas } from './lib/agent/tool-schemas.js';
|
|
10
|
-
export {
|
|
11
|
-
export { resolveTenant } from './lib/tenant.js';
|
|
11
|
+
export { TENANT_ADMIN } from './types.js';
|
|
12
12
|
export { SqlApi, createSqlApi } from './lib/sql-api.js';
|
|
13
|
-
export type { SqlApiOptions, SqlApiSearchParams, SqlApiInsertParams, SqlApiUpdateParams } from './lib/sql-api.js';
|
|
13
|
+
export type { SqlApiOptions, SqlApiSearchParams, SqlApiInsertParams, SqlApiUpdateParams, SqlApiBulkDeleteParams } from './lib/sql-api.js';
|
|
14
14
|
export { default as fastifyAutoSqlApi } from './routes/auto/plugin.js';
|
|
15
|
-
export {
|
|
16
|
-
export {
|
|
17
|
-
export {
|
|
18
|
-
export { default as searchRoutes } from './routes/auto/search.routes.js';
|
|
19
|
-
export { insertEngine } from './lib/engine/rest/insert.js';
|
|
20
|
-
export { InsertTableBody, InsertTableResponse } from './lib/schema/insert.js';
|
|
21
|
-
export { default as insertRoutes } from './routes/auto/insert.routes.js';
|
|
22
|
-
export { getEngine } from './lib/engine/rest/get.js';
|
|
23
|
-
export { default as getRoutes } from './routes/auto/get.routes.js';
|
|
24
|
-
export { deleteEngine } from './lib/engine/rest/delete.js';
|
|
25
|
-
export { default as deleteRoutes } from './routes/auto/delete.routes.js';
|
|
26
|
-
export { updateEngine } from './lib/engine/rest/update.js';
|
|
27
|
-
export { UpdateTableBody, UpdateTableResponse } from './lib/schema/update.js';
|
|
28
|
-
export { default as updateRoutes } from './routes/auto/update.routes.js';
|
|
29
|
-
export { bulkUpsertEngine } from './lib/engine/bulk/bulk-upsert.js';
|
|
30
|
-
export { BulkUpsertTableBody, BulkUpsertTableResponse } from './lib/schema/bulk-upsert.js';
|
|
31
|
-
export { default as bulkUpsertRoutes } from './routes/auto/bulk-upsert.routes.js';
|
|
32
|
-
export { bulkDeleteEngine } from './lib/engine/bulk/bulk-delete.js';
|
|
33
|
-
export { BulkDeleteTableBody, BulkDeleteTableResponse } from './lib/schema/bulk-delete.js';
|
|
34
|
-
export { default as bulkDeleteRoutes } from './routes/auto/bulk-delete.routes.js';
|
|
35
|
-
export { Type, type Static } from '@sinclair/typebox';
|
|
36
|
-
export { ConditionBuilder, Expression } from 'node-condition-builder';
|
|
37
|
-
export type { ApiRequest, SqlApiConfig, ColumnInfo, TableMap, Queryable, TransactionQueryable, SqlResult, DbRecord, DbRecordValue, SelectOptions, SchemaDefinition, JoinDefinition, ITable, TableOperation, DbTables, SqlApiPluginOptions, SwaggerOptions, SearchParams, SearchResult, Paginator, PaginationResult, TableFilterFn, ExtendedConditionFn, FilterRecord, AggregationRequest, JoinGroupRequest, ComputedFieldFn, ComputedFieldContext, ComputedFieldExpr, GetParams, GetResult, DeleteParams, DeleteResult, InsertParams, InsertResult, BulkUpsertItem, BulkUpsertParams, BulkUpsertResult, BulkDeleteParams, BulkDeleteResult, ConditionMethod, SearchCondition, UpdateParams, UpdateResult, TenantId, TenantScope, TenantScopeDirect, TenantScopeIndirect, TenantScopeAnyOf, TenantContext, ValidationError, ValidatorFn, BulkValidatorItem, BulkValidatorFn, } from './types.js';
|
|
15
|
+
export { Type, type Static, type TSchema, type TObject, type TUnsafe } from 'typebox';
|
|
16
|
+
export { ConditionBuilder, Expression, type ConditionValueOrUndefined } from 'node-condition-builder';
|
|
17
|
+
export type { ApiRequest, ApiReply, CliConfig, Queryable, TransactionQueryable, SqlResult, DbRecord, DbRecordValue, WriteAction, WrittenRow, PrimaryKeyValue, SelectOptions, SchemaDefinition, JoinDefinition, JoinFetchRequest, JoinRefFilter, RowsByAlias, WriteJoinSections, TableConfig, TableOperation, DbTables, SqlApiPluginOptions, SwaggerOptions, DbErrorMapping, SearchResult, Paginator, ComputeFn, ComputeRequest, ComputedResult, PaginationResult, ExtendedConditionFn, ExtendedConditionContext, FilterRecord, AggregationRequest, JoinGroupRequest, ComputedFieldFn, ComputedFieldContext, ComputedFieldExpr, GetResult, DeleteResult, InsertResult, BulkUpsertItem, BulkUpsertResult, BulkDeleteResult, ConditionMethod, SearchCondition, UpdateResult, TenantId, TenantAdmin, TenantResolution, GetTenantId, TenantScope, TenantScopeDirect, TenantScopeIndirect, TenantScopeAnyOf, ValidationField, ValidateContext, ValidateParent, BulkValidateContext, HookContext, WriteRecord, WriteHookContext, AfterInsertContext, AfterUpdateContext, AfterReadContext, ReadSource, DeleteHookContext, BulkDeleteHookContext, ValidatorFn, ValidatorResult, BulkValidatorItem, BulkValidatorFn, } from './types.js';
|
|
38
18
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAGjE,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,KAAK,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAGrF,YAAY,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAGpD,OAAO,EAAE,WAAW,EAAE,KAAK,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC7E,OAAO,EAAE,cAAc,EAAE,KAAK,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAGtF,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACpE,YAAY,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AACpF,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAG7C,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,YAAY,GAClB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,gBAAgB,EAAE,KAAK,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAGtF,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAG1C,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACxD,YAAY,EAAE,aAAa,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAI1I,OAAO,EAAE,OAAO,IAAI,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAGvE,OAAO,EAAE,IAAI,EAAE,KAAK,MAAM,EAAE,KAAK,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,SAAS,CAAC;AACtF,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,KAAK,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AAGtG,YAAY,EACV,UAAU,EACV,QAAQ,EACR,SAAS,EACT,SAAS,EACT,oBAAoB,EACpB,SAAS,EACT,QAAQ,EACR,aAAa,EACb,WAAW,EACX,UAAU,EACV,eAAe,EACf,aAAa,EACb,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,aAAa,EACb,WAAW,EACX,iBAAiB,EACjB,WAAW,EACX,cAAc,EACd,QAAQ,EACR,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,YAAY,EACZ,SAAS,EACT,SAAS,EACT,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,mBAAmB,EACnB,wBAAwB,EACxB,YAAY,EACZ,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,EACf,oBAAoB,EACpB,iBAAiB,EACjB,SAAS,EACT,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,YAAY,EACZ,QAAQ,EACR,WAAW,EACX,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,iBAAiB,EACjB,mBAAmB,EACnB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,cAAc,EACd,mBAAmB,EACnB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,kBAAkB,EAClB,kBAAkB,EAClB,gBAAgB,EAChB,UAAU,EACV,iBAAiB,EACjB,qBAAqB,EACrB,WAAW,EACX,eAAe,EACf,iBAAiB,EACjB,eAAe,GAChB,MAAM,YAAY,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,53 +1,22 @@
|
|
|
1
|
-
//
|
|
2
|
-
export {
|
|
1
|
+
// Errors: throw from a hook to answer in the plugin's envelope (a 400 with `fields`)
|
|
2
|
+
export { httpError } from './lib/errors.js';
|
|
3
3
|
// DB
|
|
4
|
-
export { QueryClient, createQueryClient
|
|
5
|
-
// Dialect
|
|
6
|
-
export { getDialect } from './lib/dialect.js';
|
|
4
|
+
export { QueryClient, createQueryClient } from './lib/db.js';
|
|
7
5
|
// Adapters
|
|
8
6
|
export { pgQueryable } from './lib/adapters/pg-adapter.js';
|
|
9
7
|
export { mysqlQueryable } from './lib/adapters/mysql-adapter.js';
|
|
10
8
|
// Table helpers
|
|
11
|
-
export {
|
|
9
|
+
export { defineTable, buildRelation } from './lib/table-helpers.js';
|
|
12
10
|
export { Nullable } from './lib/nullable.js';
|
|
13
11
|
// Agent / LLM client helpers
|
|
14
12
|
export { buildAgentManifest, renderAgentManifestMd, } from './lib/agent/manifest.js';
|
|
15
13
|
export { agentToolSchemas } from './lib/agent/tool-schemas.js';
|
|
16
|
-
export { default as agentManifestRoutes } from './routes/auto/agent-manifest.routes.js';
|
|
17
14
|
// Tenant
|
|
18
|
-
export {
|
|
15
|
+
export { TENANT_ADMIN } from './types.js';
|
|
19
16
|
// SqlApi — programmatic high-level API
|
|
20
17
|
export { SqlApi, createSqlApi } from './lib/sql-api.js';
|
|
21
18
|
// Plugin
|
|
22
19
|
export { default as fastifyAutoSqlApi } from './routes/auto/plugin.js';
|
|
23
|
-
// Swagger
|
|
24
|
-
export { setupSwagger } from './routes/setup-swagger.js';
|
|
25
|
-
// Search
|
|
26
|
-
export { searchEngine } from './lib/engine/search/search.js';
|
|
27
|
-
export { SearchTableBodyPost, SearchTableQuery, SearchTableQueryString, SearchTableResponse } from './lib/schema/search.js';
|
|
28
|
-
export { default as searchRoutes } from './routes/auto/search.routes.js';
|
|
29
|
-
// Insert
|
|
30
|
-
export { insertEngine } from './lib/engine/rest/insert.js';
|
|
31
|
-
export { InsertTableBody, InsertTableResponse } from './lib/schema/insert.js';
|
|
32
|
-
export { default as insertRoutes } from './routes/auto/insert.routes.js';
|
|
33
|
-
// Get
|
|
34
|
-
export { getEngine } from './lib/engine/rest/get.js';
|
|
35
|
-
export { default as getRoutes } from './routes/auto/get.routes.js';
|
|
36
|
-
// Delete
|
|
37
|
-
export { deleteEngine } from './lib/engine/rest/delete.js';
|
|
38
|
-
export { default as deleteRoutes } from './routes/auto/delete.routes.js';
|
|
39
|
-
// Update
|
|
40
|
-
export { updateEngine } from './lib/engine/rest/update.js';
|
|
41
|
-
export { UpdateTableBody, UpdateTableResponse } from './lib/schema/update.js';
|
|
42
|
-
export { default as updateRoutes } from './routes/auto/update.routes.js';
|
|
43
|
-
// Bulk Upsert
|
|
44
|
-
export { bulkUpsertEngine } from './lib/engine/bulk/bulk-upsert.js';
|
|
45
|
-
export { BulkUpsertTableBody, BulkUpsertTableResponse } from './lib/schema/bulk-upsert.js';
|
|
46
|
-
export { default as bulkUpsertRoutes } from './routes/auto/bulk-upsert.routes.js';
|
|
47
|
-
// Bulk Delete
|
|
48
|
-
export { bulkDeleteEngine } from './lib/engine/bulk/bulk-delete.js';
|
|
49
|
-
export { BulkDeleteTableBody, BulkDeleteTableResponse } from './lib/schema/bulk-delete.js';
|
|
50
|
-
export { default as bulkDeleteRoutes } from './routes/auto/bulk-delete.routes.js';
|
|
51
20
|
// Re-export deps
|
|
52
|
-
export { Type } from '
|
|
21
|
+
export { Type } from 'typebox';
|
|
53
22
|
export { ConditionBuilder, Expression } from 'node-condition-builder';
|
|
@@ -4,8 +4,11 @@ export interface MysqlQueryable {
|
|
|
4
4
|
affectedRows?: number;
|
|
5
5
|
insertId?: number;
|
|
6
6
|
}, unknown]>;
|
|
7
|
-
/**
|
|
8
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Present on mysql2 promise pools (and @fastify/mysql): checks out a dedicated connection. Only
|
|
9
|
+
* its `query` and `release` are used.
|
|
10
|
+
*/
|
|
11
|
+
getConnection?(): Promise<Pick<MysqlQueryable, 'query'> & {
|
|
9
12
|
release(): void;
|
|
10
13
|
}>;
|
|
11
14
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mysql-adapter.d.ts","sourceRoot":"","sources":["../../../src/lib/adapters/mysql-adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAmC,MAAM,gBAAgB,CAAC;AAEjF,MAAM,WAAW,cAAc;IAC7B,KAAK,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,GAAG,EAAE,MAAM,EACX,MAAM,CAAC,EAAE,OAAO,EAAE,GACjB,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG;QAAE,YAAY,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,OAAO,CAAC,CAAC,CAAC;IAC1E
|
|
1
|
+
{"version":3,"file":"mysql-adapter.d.ts","sourceRoot":"","sources":["../../../src/lib/adapters/mysql-adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAmC,MAAM,gBAAgB,CAAC;AAEjF,MAAM,WAAW,cAAc;IAC7B,KAAK,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,GAAG,EAAE,MAAM,EACX,MAAM,CAAC,EAAE,OAAO,EAAE,GACjB,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG;QAAE,YAAY,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,OAAO,CAAC,CAAC,CAAC;IAC1E;;;OAGG;IACH,aAAa,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,cAAc,EAAE,OAAO,CAAC,GAAG;QAAE,OAAO,IAAI,IAAI,CAAA;KAAE,CAAC,CAAC;CAChF;AA2BD,wBAAgB,cAAc,CAAC,IAAI,EAAE,cAAc,GAAG,SAAS,CAc9D"}
|
|
@@ -4,8 +4,11 @@ export interface PgQueryable {
|
|
|
4
4
|
rows: T[];
|
|
5
5
|
rowCount: number | null;
|
|
6
6
|
}>;
|
|
7
|
-
/**
|
|
8
|
-
|
|
7
|
+
/**
|
|
8
|
+
* Present on pg.Pool (and @fastify/postgres): checks out a dedicated client. Only its `query`
|
|
9
|
+
* and `release` are used — a PoolClient's own `connect()` is not a checkout.
|
|
10
|
+
*/
|
|
11
|
+
connect?(): Promise<Pick<PgQueryable, 'query'> & {
|
|
9
12
|
release(): void;
|
|
10
13
|
}>;
|
|
11
14
|
}
|