anygrest 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +451 -2
  3. package/dist/src/app.d.ts +96 -0
  4. package/dist/src/app.js +819 -0
  5. package/dist/src/app.js.map +1 -0
  6. package/dist/src/auth/jwt.d.ts +138 -0
  7. package/dist/src/auth/jwt.js +478 -0
  8. package/dist/src/auth/jwt.js.map +1 -0
  9. package/dist/src/db/introspect/views.d.ts +62 -0
  10. package/dist/src/db/introspect/views.js +257 -0
  11. package/dist/src/db/introspect/views.js.map +1 -0
  12. package/dist/src/db/knex.d.ts +72 -0
  13. package/dist/src/db/knex.js +358 -0
  14. package/dist/src/db/knex.js.map +1 -0
  15. package/dist/src/db/pool-timers.d.ts +18 -0
  16. package/dist/src/db/pool-timers.js +8 -0
  17. package/dist/src/db/pool-timers.js.map +1 -0
  18. package/dist/src/db/schema.d.ts +306 -0
  19. package/dist/src/db/schema.js +1387 -0
  20. package/dist/src/db/schema.js.map +1 -0
  21. package/dist/src/db/session.d.ts +160 -0
  22. package/dist/src/db/session.js +399 -0
  23. package/dist/src/db/session.js.map +1 -0
  24. package/dist/src/db/sqlite.d.ts +7 -0
  25. package/dist/src/db/sqlite.js +16 -0
  26. package/dist/src/db/sqlite.js.map +1 -0
  27. package/dist/src/demo.d.ts +5 -0
  28. package/dist/src/demo.js +49 -0
  29. package/dist/src/demo.js.map +1 -0
  30. package/dist/src/errors/mssql.d.ts +10 -0
  31. package/dist/src/errors/mssql.js +53 -0
  32. package/dist/src/errors/mssql.js.map +1 -0
  33. package/dist/src/errors/oracle.d.ts +17 -0
  34. package/dist/src/errors/oracle.js +59 -0
  35. package/dist/src/errors/oracle.js.map +1 -0
  36. package/dist/src/errors.d.ts +84 -0
  37. package/dist/src/errors.js +444 -0
  38. package/dist/src/errors.js.map +1 -0
  39. package/dist/src/http/response.d.ts +229 -0
  40. package/dist/src/http/response.js +452 -0
  41. package/dist/src/http/response.js.map +1 -0
  42. package/dist/src/index.d.ts +13 -0
  43. package/dist/src/index.js +13 -0
  44. package/dist/src/index.js.map +1 -0
  45. package/dist/src/query/ast.d.ts +247 -0
  46. package/dist/src/query/ast.js +19 -0
  47. package/dist/src/query/ast.js.map +1 -0
  48. package/dist/src/query/parser.d.ts +219 -0
  49. package/dist/src/query/parser.js +2304 -0
  50. package/dist/src/query/parser.js.map +1 -0
  51. package/dist/src/query/request.d.ts +183 -0
  52. package/dist/src/query/request.js +1385 -0
  53. package/dist/src/query/request.js.map +1 -0
  54. package/dist/src/server.d.ts +1 -0
  55. package/dist/src/server.js +43 -0
  56. package/dist/src/server.js.map +1 -0
  57. package/dist/src/sql/filters.d.ts +103 -0
  58. package/dist/src/sql/filters.js +730 -0
  59. package/dist/src/sql/filters.js.map +1 -0
  60. package/dist/src/sql/matcher.d.ts +10 -0
  61. package/dist/src/sql/matcher.js +161 -0
  62. package/dist/src/sql/matcher.js.map +1 -0
  63. package/dist/src/sql/read.d.ts +83 -0
  64. package/dist/src/sql/read.js +1745 -0
  65. package/dist/src/sql/read.js.map +1 -0
  66. package/dist/src/sql/rowselect.d.ts +74 -0
  67. package/dist/src/sql/rowselect.js +120 -0
  68. package/dist/src/sql/rowselect.js.map +1 -0
  69. package/dist/src/sql/rpc-read.d.ts +231 -0
  70. package/dist/src/sql/rpc-read.js +887 -0
  71. package/dist/src/sql/rpc-read.js.map +1 -0
  72. package/dist/src/sql/rpc-types.d.ts +23 -0
  73. package/dist/src/sql/rpc-types.js +84 -0
  74. package/dist/src/sql/rpc-types.js.map +1 -0
  75. package/dist/src/sql/rpc.d.ts +47 -0
  76. package/dist/src/sql/rpc.js +214 -0
  77. package/dist/src/sql/rpc.js.map +1 -0
  78. package/dist/src/sql/select.d.ts +138 -0
  79. package/dist/src/sql/select.js +566 -0
  80. package/dist/src/sql/select.js.map +1 -0
  81. package/dist/src/sql/serialize.d.ts +47 -0
  82. package/dist/src/sql/serialize.js +231 -0
  83. package/dist/src/sql/serialize.js.map +1 -0
  84. package/dist/src/sql/values.d.ts +15 -0
  85. package/dist/src/sql/values.js +24 -0
  86. package/dist/src/sql/values.js.map +1 -0
  87. package/dist/src/sql/write-read.d.ts +83 -0
  88. package/dist/src/sql/write-read.js +202 -0
  89. package/dist/src/sql/write-read.js.map +1 -0
  90. package/dist/src/sql/write.d.ts +53 -0
  91. package/dist/src/sql/write.js +1205 -0
  92. package/dist/src/sql/write.js.map +1 -0
  93. package/package.json +88 -4
  94. package/sql/cockroachdb.sql +52 -0
  95. package/sql/mssql.sql +63 -0
  96. package/sql/mysql.sql +55 -0
  97. package/sql/oracle.sql +76 -0
  98. package/sql/postgres.sql +68 -0
  99. package/sql/redshift.sql +50 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 yuukioosaka
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,452 @@
1
- # Temporary Holding Version
1
+ # anygrest
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/yuukioosaka/anygrest/actions/workflows/ci.yml/badge.svg)](https://github.com/yuukioosaka/anygrest/actions/workflows/ci.yml)
4
+
5
+ **Turn any SQL database into a PostgREST-compatible REST API — no code generation, no schema files.**
6
+
7
+ anygrest introspects a SQLite / MySQL / MariaDB / PostgreSQL / CockroachDB / Redshift / MSSQL / Oracle schema at startup and serves the exact query syntax PostgREST clients expect, so [`@supabase/postgrest-js`](https://github.com/supabase/postgrest-js) and `fetch` calls written for Supabase keep working against your own database.
8
+
9
+ - TypeScript, ESM, strict mode
10
+ - [Hono](https://hono.dev/) internally → the app is a standards-based `fetch` handler, usable from Node, Express, Next.js, Bun, Deno, Workers…
11
+ - [Knex.js](https://knexjs.org/) for SQL generation with per-dialect handling
12
+
13
+ ```bash
14
+ npm install anygrest knex sqlite3 # pick your driver: sqlite3 / pg / mysql2 / mssql / oracledb
15
+ ```
16
+
17
+ ## Quick start
18
+
19
+ ```ts
20
+ import { serve } from '@hono/node-server';
21
+ import { createAnygrest, createSqliteKnex } from 'anygrest';
22
+
23
+ const database = { knex: createSqliteKnex('./app.db'), dialect: 'sqlite' as const };
24
+
25
+ const { app } = await createAnygrest(database, { maxRows: 1000 });
26
+
27
+ serve({ fetch: app.fetch, port: 3000 });
28
+ ```
29
+
30
+ ```bash
31
+ curl "http://localhost:3000/posts?select=id,title,users(name),comments(author_name)&order=id.asc"
32
+ ```
33
+
34
+ ```json
35
+ [
36
+ {
37
+ "id": 1,
38
+ "title": "Intro to PostgREST",
39
+ "users": { "name": "Ada Lovelace" },
40
+ "comments": [{ "author_name": "Alan" }, { "author_name": "Grace" }]
41
+ }
42
+ ]
43
+ ```
44
+
45
+ With a Supabase client — just point it at anygrest:
46
+
47
+ ```ts
48
+ import { createClient } from '@supabase/supabase-js';
49
+
50
+ const supabase = createClient('http://localhost:3000', 'unused-anon-key');
51
+ const { data } = await supabase.from('posts').select('id, title, users(name)').eq('published', true);
52
+ ```
53
+
54
+ ## What you get
55
+
56
+ | | |
57
+ | --- | --- |
58
+ | `GET /:table` | Rows as a JSON array, with `Content-Range` on every response. The total is `*` (unknown) unless the request asks for it with `Prefer: count=exact`. `Range: 0-9` pages like `limit`/`offset`; with a known total, a page shorter than it is `206 Partial Content` and a range past it is `416`. `Accept: application/vnd.pgrst.object+json` returns a single object. |
59
+ | `POST /:table` | Insert one row or an array. Returns `201` + rows with `Prefer: return=representation`, otherwise `204`. |
60
+ | `PATCH /:table?…` | Update rows matching the filters. |
61
+ | `DELETE /:table?…` | Delete rows matching the filters (`return=representation` returns them). |
62
+ | `OPTIONS /:table` | `200` with an `Allow` header (CORS preflights are answered for any path with a `200`, never 401/404). |
63
+ | `GET /` | OpenAPI 3.0 document generated from the schema cache. |
64
+
65
+ ### Query syntax
66
+
67
+ ```
68
+ ?select=id,name,posts(title,comments(*)) # columns, aliases (alias:col), embedded relations
69
+ ?select=*,author:users(name)
70
+ ?select=id,tasks(count) # aggregate count per embed
71
+ ?id=eq.1&name=ilike.*ada* # eq neq gt gte lt lte like ilike in is
72
+ ?id=in.(1,2,3)&name=in.("Ada, Lovelace",Grace) # quoted list values keep commas
73
+ ?id=eq(any).{1,2,3} # (any) / (all) quantifiers
74
+ ?id=in.(1,2,3)&deleted_at=is.null
75
+ ?id=not.eq.1&name=not.ilike.*x* # any operator takes the `not.` prefix
76
+ ?id=isdistinct.1&name=match.^Ada # isdistinct, match / imatch
77
+ ?or=(status.eq.active,views.gt.100)&and=(id.gt.10,id.lt.20)
78
+ ?order=created_at.desc.nullslast,name.asc # asc desc nullsfirst nullslast
79
+ ?order=created_at.desc&limit=10&offset=20
80
+ ?comments.body=ilike.*sql*&comments.order=created_at.asc # filter / order inside an embed
81
+ ?select=id,data->>name&data->>name=eq.x # JSON path (one segment)
82
+ ```
83
+
84
+ Full-text search (`fts`, `plfts`, `phfts`, `wfts`) and type casts (`col::text`) are also
85
+ supported on the engines that can express them; see [Limits and PostgREST
86
+ differences](#limits-and-postgrest-differences) for the per-engine gaps.
87
+
88
+ `Prefer` headers: `return=representation|minimal`, `count=exact` (sets `Content-Range`, works on reads too), and `resolution=merge-duplicates|ignore-duplicates` (upsert, with `?on_conflict=`).
89
+
90
+ Writes with `Prefer: return=representation` honour `?select=` (columns and aliases; a `PATCH` cannot return embedded relations). `Accept-Profile` / `Content-Profile` naming any schema but the one served (`public` unless configured) are rejected with `406 PGRST106`.
91
+
92
+ Stored procedures are served at `GET|POST /rpc/:name`, with `POST` required for a `VOLATILE` function.
93
+
94
+ Errors follow PostgREST: `PGRST101`/`PGRST117` (method not allowed, with `Allow`), `PGRST103` (range/offset out of bounds), `PGRST106`, `PGRST200`/`PGRST201` (embed not found / ambiguous), `PGRST202`/`PGRST203` (RPC not found / overloaded), `PGRST204`, `PGRST205`, `PGRST302` (anonymous access disabled), `PGRST303` (JWT claims), and SQLSTATE codes such as `23505` (unique), `23503` (foreign key), `23502` (not null), `22P02` (invalid input). `details` carries the driver's constraint text.
95
+
96
+ Every response — success, error or 404 — carries `Vary: Accept, Prefer, Range` and, when the request has an `Origin`, the CORS policy.
97
+
98
+ The official Supabase client works through a `/rest/v1` prefix (`test/supabase-js.test.ts` drives it via `mountAt` from `examples/_shared/mount.ts`).
99
+
100
+ ## Options
101
+
102
+ ```ts
103
+ const anygrest = await createAnygrest(database, {
104
+ maxRows: 1000, // hard cap on `limit` (PostgREST db-max-rows)
105
+ tables: ['users', 'posts'], // expose only these (default: all); a `(table) => boolean` also works
106
+ authenticate: (req) => // return false for a 401 PGRST302 (WWW-Authenticate: Bearer)
107
+ req.headers.get('authorization') === `Bearer ${process.env.API_KEY}`,
108
+ openapi: true, // serve OpenAPI at `/`
109
+ debug: true, // log unexpected errors
110
+ preRequest: 'auth.check', // SQL function run before each request (db-pre-request)
111
+ urlUseLegacyTargetNames: true, // allow `tasks.order` on `the_tasks:tasks` (Warning: 299)
112
+ cors: { allowedOrigins: ['https://app.example.com'] }, // default: any origin (`*`)
113
+ jwt: { secret: process.env.JWT_SECRET, anonymousRole: 'anon' }, // see below
114
+ context: { /* per-engine names for the request context */ },
115
+ });
116
+
117
+ anygrest.schema; // introspected tables, columns, keys, relations
118
+ anygrest.schemaName; // the schema this instance serves
119
+ anygrest.openapi; // the OpenAPI document, or null when `openapi: false`
120
+ await anygrest.reload(); // re-introspect after DDL changes
121
+ await anygrest.close(); // destroy the pool
122
+ ```
123
+
124
+ ## Databases
125
+
126
+ Every engine is driven through Knex; pass the driver name from `connectDatabase()` or an existing Knex instance.
127
+
128
+ | Engine | `client` | Driver | Role switch | Claims storage | Notes |
129
+ | --- | --- | --- | --- | --- | --- |
130
+ | PostgreSQL | `postgres` / `postgresql` | `pg` | `SET LOCAL ROLE` | `set_config('request.jwt.claims', …, true)` | full PostgREST behaviour |
131
+ | CockroachDB | `cockroachdb` | `pg` | `SET LOCAL ROLE` | `set_config(…, true)`, `anygrest.*` fallback | [sql/cockroachdb.sql](sql/cockroachdb.sql) |
132
+ | MySQL / MariaDB | `mysql` / `mariadb` | `mysql2` | `SET ROLE` (8.0 / 10.0.5+) | `SET @jwt_claims = ?` | [sql/mysql.sql](sql/mysql.sql) |
133
+ | MSSQL | `mssql` | `tedious` | `EXECUTE AS USER` / `REVERT` | `sp_set_session_context @read_only = 1` | [sql/mssql.sql](sql/mssql.sql) |
134
+ | Oracle | `oracle` | `oracledb` | `SET ROLE` | `DBMS_SESSION.SET_CONTEXT` | [sql/oracle.sql](sql/oracle.sql) (context must be created by a DBA) |
135
+ | Amazon Redshift | `redshift` | `pg` | `SET SESSION AUTHORIZATION` (superuser) | temp table `anygrest_ctx` | [sql/redshift.sql](sql/redshift.sql) |
136
+ | SQLite | `sqlite` | `sqlite3` | — | — | no variables: JWT context is not stored |
137
+
138
+ ```ts
139
+ import { connectDatabase } from 'anygrest';
140
+
141
+ const { knex, dialect } = connectDatabase({
142
+ client: 'mssql',
143
+ connection: { server: 'localhost', database: 'app', user: 'sa', password: '…', options: { trustServerCertificate: true } },
144
+ });
145
+ ```
146
+
147
+ ## JWT claims and request context
148
+
149
+ With `jwt`, anygrest authenticates exactly like PostgREST v14:
150
+
151
+ - **Token verification.** The `Authorization: Bearer` token must be a JWS whose `alg` is in the configured allow-list (`HS256/384/512` with `secret`, `RS*`/`ES*` with `publicKey`; override with `algorithms`). `alg: none` and unsigned tokens are always rejected — the algorithm is never taken from the token header alone. A `jwt` without `secret`, `publicKey` or `verifier` verifies nothing: a request that *sends* a token gets `500 PGRST300 "Server lacks JWT secret"`.
152
+ - **Anonymous access.** A request **without** a token, or with a token that has no `role` claim (`jwt-role-claim-key`, default `$.role`), runs as `anonymousRole` (`db-anon-role`). Without an `anonymousRole` it gets `401 PGRST302 "Anonymous access is disabled"` (`WWW-Authenticate: Bearer`) — it never falls back to the connecting role. `jwt.required: false` is the legacy switch that keeps the connecting role instead.
153
+ - **Claims.** `exp`/`nbf`/`iat` are numbers with PostgREST's 30 s clock skew; `aud` is only enforced when `audience` (`jwt-aud`) is set and accepts a string or an array. Failures are `PGRST303` with PostgREST's messages ("JWT expired", "JWT not yet valid", "JWT issued at future", "JWT not in audience", "The JWT 'exp' claim must be a number", …); token decoding failures (`Empty JWT is sent in Authorization header`, `Expected 3 parts in JWT; got N`, `No suitable key or wrong key type`, `Wrong or unsupported encoding algorithm`) are `PGRST301`. Both carry `WWW-Authenticate: Bearer error="invalid_token", error_description="…"`.
154
+
155
+ The role then becomes the `role` the request runs as, and the PostgREST variables are exposed to the database **inside a transaction**:
156
+
157
+ ```ts
158
+ const anygrest = await createAnygrest(database, {
159
+ jwt: {
160
+ secret: process.env.JWT_SECRET, // or publicKey: '-----BEGIN PUBLIC KEY-----…'
161
+ audience: 'my-api', // optional jwt-aud
162
+ anonymousRole: 'anon', // db-anon-role
163
+ roleClaimKey: '$.role', // jwt-role-claim-key (JSON path: $.a.b, $['x'], $.r[0])
164
+ },
165
+ });
166
+ ```
167
+
168
+ On PostgreSQL this is exactly what PostgREST does, so existing policies work unchanged:
169
+
170
+ ```sql
171
+ -- available for every request, request-local (becomes '' after commit):
172
+ select current_setting('request.jwt.claims', true)::json -> 'email';
173
+ select current_setting('request.method', true);
174
+ select current_setting('request.path', true);
175
+ select current_setting('request.headers', true)::json -> 'user-agent';
176
+ select current_setting('request.cookies', true)::json -> 'sessionId';
177
+ ```
178
+
179
+ Other engines cannot store arbitrary JSON in session variables, so each gets the closest equivalent — same values, same request-transaction, read with the matching helpers (`sql/*.sql`):
180
+
181
+ | Engine | Read the claims |
182
+ | --- | --- |
183
+ | MySQL / MariaDB | `select json_extract(@jwt_claims, '$.sub')` or `anygrest_claim('sub')` |
184
+ | MSSQL | `select json_value(session_context(N'jwt_claims'), '$.sub')` or `dbo.anygrest_claim('sub')` |
185
+ | Oracle | `select json_value(sys_context('anygrest', 'jwt_claims'), '$.sub')` |
186
+ | Redshift | `select anygrest_claim('sub')` (temp table `anygrest_ctx`) |
187
+ | CockroachDB | `select extensions.anygrest_claim('sub')` |
188
+
189
+ Operational notes:
190
+
191
+ - Only PostgreSQL holds the claims transaction-locally (`set_config(…, true)`). MySQL, MSSQL and Oracle keep them on the connection/session, so anygrest clears them before the transaction commits and the connection returns to the pool. Enable roles per connection (`SET ROLE`) rather than per user where possible.
192
+ - MSSQL impersonates with `EXECUTE AS USER`, which requires `IMPERSONATE` on the target user; Oracle `SET ROLE` needs the role granted to the pool user.
193
+ - Redshift `SET SESSION AUTHORIZATION` requires a superuser; for least privilege, grant roles instead.
194
+ - SQLite has no variables, so `jwt` only performs authentication there — nothing is exposed to SQL.
195
+ - Without `jwt` (or with `jwt.required: false` and no token) the requests still run in the context transaction with empty claims, and the `request.method` / `request.path` / headers / cookies variables are always set.
196
+
197
+ ## Using it outside Hono
198
+
199
+ `createAnygrest()` returns a **Hono app**, and any Hono app can be mounted anywhere `(Request) => Response` is accepted. Verified setups:
200
+
201
+ **Next.js (App Router, Node runtime)**
202
+
203
+ ```ts
204
+ // app/api/anygrest/[[...path]]/route.ts
205
+ import { createAnygrest } from 'anygrest';
206
+ import { createSqliteKnex } from 'anygrest';
207
+
208
+ export const dynamic = 'force-dynamic';
209
+
210
+ let appPromise: ReturnType<typeof createAnygrest> | undefined;
211
+ const getApp = () => (appPromise ??= createAnygrest({ knex: createSqliteKnex('./app.db'), dialect: 'sqlite' }));
212
+
213
+ const MOUNT = '/api/anygrest';
214
+
215
+ async function handler(request: Request) {
216
+ const { app } = await getApp();
217
+ const url = new URL(request.url);
218
+ const inner = new URL(url.pathname.slice(MOUNT.length) || '/', url.origin);
219
+ inner.search = url.search;
220
+ return app.fetch(new Request(inner, request));
221
+ }
222
+
223
+ export { handler as GET, handler as POST, handler as PATCH, handler as DELETE, handler as HEAD, handler as OPTIONS };
224
+ ```
225
+
226
+ ```ts
227
+ // next.config.ts — keep the DB drivers out of the bundle
228
+ import type { NextConfig } from 'next';
229
+
230
+ const nextConfig: NextConfig = {
231
+ serverExternalPackages: ['knex', 'sqlite3', 'pg', 'mysql2'],
232
+ };
233
+ export default nextConfig;
234
+ ```
235
+
236
+ **Express (or Fastify, or a bare `node:http` server)**
237
+
238
+ ```ts
239
+ import express from 'express';
240
+ import { getRequestListener } from '@hono/node-server';
241
+ import { createAnygrest, createSqliteKnex } from 'anygrest';
242
+
243
+ const { app } = await createAnygrest({ knex: createSqliteKnex('./app.db'), dialect: 'sqlite' });
244
+
245
+ const server = express();
246
+ server.use('/api', getRequestListener(app.fetch)); // mount under a prefix
247
+ server.listen(3000);
248
+ ```
249
+
250
+ ### Ready-made examples
251
+
252
+ Every folder under [`examples/`](examples) is a runnable setup (dev script, config and all wiring):
253
+
254
+ | Target | Folder | Mount |
255
+ | --- | --- | --- |
256
+ | Hono (Node) | [`examples/hono`](examples/hono) | `app.route('/api', anygrest.app)` |
257
+ | Plain `node:http` | [`examples/node-http`](examples/node-http) | `createServer(getRequestListener(...))` |
258
+ | Express 5 | [`examples/express`](examples/express) | `server.use('/api', getRequestListener(fetch))` |
259
+ | Fastify 5 | [`examples/fastify`](examples/fastify) | catch-all `'/api/*'` route |
260
+ | Next.js (App Router) | [`examples/nextjs`](examples/nextjs) | `app/api/anygrest/[[...path]]/route.ts` |
261
+ | AWS Lambda (API Gateway) | [`examples/aws-lambda`](examples/aws-lambda) | `handle()` from `hono/aws-lambda` + SAM template |
262
+ | Bun | [`examples/bun`](examples/bun) | `Bun.serve({ fetch: app.fetch })` |
263
+ | Deno | [`examples/deno`](examples/deno) | `Deno.serve({ fetch: app.fetch })` |
264
+ | Cloudflare Workers | [`examples/platforms/cloudflare-worker`](examples/platforms/cloudflare-worker) | `export default { fetch }` + `wrangler.toml` |
265
+ | Vercel (Function / Edge) | [`examples/platforms/vercel`](examples/platforms/vercel) | `api/[...path].ts` + `vercel.json` |
266
+ | PostgreSQL + RLS + JWT | [`examples/postgres`](examples/postgres) | `DATABASE_URL=… JWT_SECRET=… npm run dev:postgres` (roles, policies and `request.jwt.claims`) |
267
+ | MySQL / MariaDB + JWT | [`examples/mysql`](examples/mysql) | `DATABASE_URL=… JWT_SECRET=… npm run dev:mysql` (roles, `@jwt_claims` and an ownership view) |
268
+
269
+ Run the end-to-end checks against the HTTP servers:
270
+
271
+ ```bash
272
+ npm run test:examples # starts hono, node-http, express, fastify and next build, then curls each
273
+ ```
274
+
275
+ **Mounting semantics** — the handler always expects the path to start at the API root:
276
+
277
+ ```
278
+ /api/posts?select=id,title → /posts?select=id,title (strip the prefix)
279
+ ```
280
+
281
+ Hono's `.route()` does this for you; for every other framework strip the mount prefix yourself (see `examples/*/server.ts`). Hono also does not map `/api` to the app's `/` route, so serve the OpenAPI document explicitly:
282
+
283
+ ```ts
284
+ app.route('/api', anygrest.app);
285
+ app.get('/api', (c) => c.json(anygrest.openapi));
286
+ ```
287
+
288
+ ### Caveats
289
+
290
+ - The app holds an open DB connection **and** the schema cache in memory, so create it once per process (module-level singleton) — not per request. On serverless, cache it across warm invocations.
291
+ - **Node runtime only** for databases that need sockets or native bindings (`sqlite3`, `pg`, `mysql2`). Edge runtimes only work with a HTTP-based driver (e.g. Neon, PlanetScale, Turso).
292
+ - The example folders resolve the library through `node_modules/anygrest`, which is a junction/symlink to the repository root. Recreate it after cloning if you run the examples or `test/frameworks.test.ts` from source:
293
+ ```powershell
294
+ New-Item -ItemType Junction -Path examples\nextjs\node_modules\anygrest -Target <repo>
295
+ New-Item -ItemType Junction -Path examples\express\node_modules\anygrest -Target <repo>
296
+ ```
297
+ - Bundlers must not try to inline Knex's optional drivers → mark `knex` (+ your driver) as an external/server-external package.
298
+ - The handler expects a `Request` whose URL starts at the root path (`/posts?...`); strip your mount prefix as shown above.
299
+ - **Next.js 16** cannot resolve a symlinked `file:` package under Turbopack. The example therefore builds with webpack (`next build --webpack`) and marks `knex`/drivers as `serverExternalPackages`. Published installs from npm work with either bundler.
300
+ - **Cloudflare Workers** have no TCP/native SQLite — you need an HTTP driver (PlanetScale Serverless, Neon HTTP, Turso) and a Knex-compatible wrapper. The Worker example runs the routing layer with a stub to show the wiring.
301
+
302
+ ### Process lifetime
303
+
304
+ An idle Knex pool would otherwise keep the process alive: tarn starts a reaping `setInterval` that is never unref'd. anygrest unrefs it automatically, so one-off scripts and test suites exit on their own; `await anygrest.close()` still destroys the pool for graceful shutdown.
305
+
306
+ ## How it works
307
+
308
+ - **Schema cache** — tables, columns, primary keys and foreign keys are read once via `PRAGMA`, `information_schema`, `sys.columns` / `all_tab_columns` (MSSQL / Oracle) and cached. Each foreign key produces a forward (many-to-one) and a reverse (one-to-many) relation, so `select=posts(title)` vs `select=users(name)` resolve automatically.
309
+ - **No N+1** — embeds are resolved DataLoader-style: one `WHERE fk IN (…)` query per relation edge per level, then rows are grouped and stitched in memory.
310
+ - **Dialect handling** — `ilike` becomes `ILIKE` on the PostgreSQL family and `LOWER(x) LIKE LOWER(?)` elsewhere; `is.true` becomes `IS TRUE` on PostgreSQL and `= 1` on the other engines; engines without `RETURNING` (MySQL, MSSQL, Oracle) re-select the affected rows by primary key.
311
+ - **Request context** — each request runs in a transaction; the PostgREST variables and the role switch are applied before the handler (see [JWT claims and request context](#jwt-claims-and-request-context)).
312
+
313
+ ## Project layout
314
+
315
+ ```
316
+ examples/ one runnable setup per runtime/framework (see table above)
317
+ sql/ database-side helpers per engine (claims functions, RLS examples)
318
+ ├── postgres.sql extensions.anygrest_claims() / anygrest_claim() / anygrest_role()
319
+ ├── cockroachdb.sql helpers that work with request.* and anygrest.* GUCs
320
+ ├── mysql.sql anygrest_claim() over @jwt_claims (JSON_EXTRACT)
321
+ sql/mssql.sql, sql/oracle.sql, sql/redshift.sql
322
+ src/
323
+ ├── index.ts public exports
324
+ ├── app.ts createAnygrest(): routing, JWT, request context, Prefer handling, OpenAPI
325
+ ├── errors.ts AnygrestError + driver error → PGRST/SQLSTATE translation
326
+ ├── server.ts, demo.ts demo server + seed data
327
+ ├── auth/
328
+ │ └── jwt.ts token verification, claim validation, role JSON paths
329
+ ├── db/
330
+ │ ├── knex.ts connectDatabase(), dialect aliases, families, capabilities
331
+ │ ├── schema.ts introspection (SQLite, Postgres, MySQL, MSSQL, Oracle) + SchemaCache
332
+ │ ├── session.ts per-engine request context (claims, method, path, role switch)
333
+ │ ├── pool-timers.ts unrefs tarn's reaping interval so idle pools don't pin the process
334
+ │ └── sqlite.ts createSqliteKnex()
335
+ ├── query/
336
+ │ ├── ast.ts query AST types (the parser ↔ SQL builder contract)
337
+ │ ├── parser.ts select / filters / logic / order / limit / Prefer
338
+ │ └── request.ts HTTP request → AST
339
+ └── sql/
340
+ ├── filters.ts filter AST → WHERE
341
+ ├── select.ts SELECT list building (auto join keys)
342
+ ├── read.ts GET execution (batched relation loading)
343
+ └── write.ts POST / PATCH / DELETE
344
+ ```
345
+
346
+ ```bash
347
+ npm run dev # demo server on :3000 with an in-memory SQLite seed
348
+ npm test # parser, dialect, JWT, session-context and API integration tests
349
+ npm run typecheck # tsc (strict, unused checks)
350
+ npm run build # emit dist/
351
+ npm run test:examples # end-to-end checks against the example servers
352
+ npm run test:all # both of the above
353
+ npm run test:integration # live databases from test/integration/docker-compose.yml
354
+ ```
355
+
356
+ `npm run dev` also honours `DATABASE_URL` with `sqlite:./file.db`, `postgres://…`, `cockroachdb://…`, `mysql://…` or `mariadb://…`. For MSSQL and Oracle, call `connectDatabase({ client: 'mssql' | 'oracle', connection: {…} })` from your own entry point — their connection objects are richer than a URL.
357
+
358
+ ### Continuous integration
359
+
360
+ `.github/workflows/ci.yml` runs on every push to `main` and every pull request:
361
+
362
+ - **test** — `npm ci`, `npm run build`, `npm run typecheck`, `npm test` on Node 20 and 22.
363
+ - **integration** — brings up all six databases with `docker compose`, seeds them and runs `npm run test:integration`.
364
+
365
+ The build comes before the typecheck because `test/frameworks.test.ts` and the
366
+ Next.js example import the package through `examples/*/node_modules/anygrest`,
367
+ which resolves to `dist/`; the workflow creates those links with `ln -s`.
368
+
369
+ `.github/workflows/release.yml` publishes to npm when a `v*` tag is pushed. It
370
+ checks that the tag matches `package.json`, re-runs build, typecheck and the
371
+ unit tests, then `npm publish --provenance`. Publishing needs an `NPM_TOKEN`
372
+ repository secret.
373
+
374
+ The PostgREST `QuerySpec` suite is deliberately not part of CI: it needs a
375
+ built upstream PostgREST and a database the fixtures are loaded into.
376
+
377
+ ## Limits and PostgREST differences
378
+
379
+ anygrest targets PostgREST's behaviour and is checked against upstream's
380
+ `Feature.Query.QuerySpec` suite. Everything below is a known difference, not an
381
+ intended feature. Engine-specific gaps are marked **ENGINE**: PostgREST itself
382
+ would work there because it only runs on PostgreSQL.
383
+
384
+ ### API surface
385
+
386
+ - **`Accept: application/vnd.pgrst.object+json` on a read rejects anything but
387
+ exactly one row** with `406 PGRST116 "Cannot coerce the result to a single JSON
388
+ object"` and `details: "The result contains N rows"`, matching upstream. A
389
+ `?limit=1` that fetches one row answers `200`.
390
+ - **`OPTIONS` answers from a static allow-list** rather than the per-request
391
+ method set, so a `HEAD`-only table and a writable one look the same.
392
+ - **`db-schemas` (several served schemas) is not replicated.** One schema per
393
+ instance, chosen at construction; `options.tables` filters what is exposed.
394
+
395
+ ### Query language
396
+
397
+ - **`like(anyof)` / `like(allof)` / `ilike(anyof)` / `ilike(allof)` are an
398
+ anygrest extension.** Upstream PostgREST has only the `(any)` / `(all)`
399
+ quantifiers (`last_name=like(any).{O*,P*}`). anygrest accepts both spellings,
400
+ and the dotted `like.anyof.{…}` form as well; `like(any)` and `like(all)` are
401
+ the upstream-compatible ones. A list spelling with no `{…}` / `(…)` operand is
402
+ `400 PGRST100` rather than a silent empty result.
403
+ - **Empty pattern lists follow `ANY`/`ALL` over an empty set**: `like(anyof).{}`
404
+ matches no row and `like(allof).{}` matches every row.
405
+ - **Array and range operators (`cs`, `cd`, `ov`, `sl`, `sr`, `nxr`, `nxl`,
406
+ `adj`) are not implemented.** A list operand such as `tags=cs.{1,2}` reaches
407
+ the driver as separate scalars, which PostgreSQL rejects (`22P02`).
408
+ **ENGINE**: these need PostgreSQL's array/range types, so on MySQL, MSSQL,
409
+ Oracle or SQLite there is no faithful equivalent — the closest is a
410
+ `JSON_CONTAINS`-style check whose semantics differ (ordering, duplicates,
411
+ empty-array handling).
412
+ - **Full-text search (`fts` / `plfts` / `phfts` / `wfts`) is PostgreSQL and
413
+ CockroachDB only.** Other engines answer `400 PGRST100`. **ENGINE**: MySQL's
414
+ `MATCH … AGAINST` and MSSQL's `CONTAINS` use different indexing, tokenisation
415
+ and relevance; a query cannot be translated without changing its results.
416
+ CockroachDB also lacks `phfts` / `wfts` and the `(config)` form.
417
+ - **`match` / `imatch` are PostgreSQL (`~` / `~*`) and MySQL/MariaDB
418
+ (`REGEXP`).** **ENGINE**: SQLite, MSSQL and Oracle have no equivalent operator
419
+ in the spelling PostgREST emits, so they answer `400`.
420
+ - **Text ordering follows the database's collation.** A `text/csv` export therefore
421
+ sorts differently from the spec fixture's `en_US.utf8` on a server configured
422
+ otherwise. This is the database's property, not a translation.
423
+
424
+ ### Schema and metadata
425
+
426
+ - **A view's foreign keys are not inferred.** Relations are read from the
427
+ engine's catalog, so embedding through a view works only where that catalog
428
+ reports the key (PostgreSQL over a single table with matching column names).
429
+ This is the largest remaining `Feature.Query.QuerySpec` cluster — 18 of the
430
+ 54 failures.
431
+ - **OpenAPI lacks column-level detail** — descriptions (column comments),
432
+ `format` and `enum` are not emitted.
433
+ - **RPC metadata is not in OpenAPI.** Functions themselves are served and
434
+ `PGRST202` / `PGRST203` (overload resolution by parameter name) work.
435
+
436
+ ### Authentication
437
+
438
+ - **Only a static `secret` or `publicKey`.** `jwt-secret-is-base64` and JWKS key
439
+ rotation are not implemented, so keys cannot be rotated without a restart.
440
+ - **Only PostgreSQL holds the claims transaction-locally.** MySQL, MSSQL and
441
+ Oracle keep them on the connection/session and anygrest clears them before the
442
+ transaction commits; a `SET`-less driver that leaks a pooled connection would
443
+ leak claims. **ENGINE**: no other engine has PostgreSQL's
444
+ `set_config(…, is_local := true)` equivalent.
445
+ - **SQLite has no session variables**, so `jwt` there authenticates but exposes
446
+ nothing to SQL (**ENGINE**).
447
+ - **Redshift `SET SESSION AUTHORIZATION` needs a superuser**; PostgreSQL's
448
+ transaction-local role switch does not.
449
+
450
+ ## License
451
+
452
+ MIT
@@ -0,0 +1,96 @@
1
+ import { Hono } from 'hono';
2
+ import { type JwtVerifier } from './auth/jwt.js';
3
+ import type { Database as DatabaseClient } from './db/knex.js';
4
+ import { type SchemaCache, type TableMeta } from './db/schema.js';
5
+ import { type ContextOptions } from './db/session.js';
6
+ import { type CorsOptions } from './http/response.js';
7
+ /** JWT authentication settings (the subset of PostgREST's auth options). */
8
+ export interface JwtOptions {
9
+ /** HS* shared secret (`jwt-secret`). */
10
+ secret?: string;
11
+ /** PEM public key for RS-xx / ES-xx tokens. */
12
+ publicKey?: string;
13
+ /** Accepted algorithms. Default: HS256/384/512 (or RS256/384/512 with a public key). */
14
+ algorithms?: Array<'HS256' | 'HS384' | 'HS512' | 'RS256' | 'RS384' | 'RS512' | 'ES256' | 'ES384' | 'ES512'>;
15
+ /** Required `aud` claim (`jwt-aud`). */
16
+ audience?: string | string[];
17
+ /**
18
+ * Role assumed when the request carries no token or the token has no role
19
+ * claim (`db-anon-role`). Without it such requests are rejected with
20
+ * 401 PGRST302 "Anonymous access is disabled" (`Auth/Jwt.hs:119-121`); the
21
+ * connecting role is never used as a fallback.
22
+ */
23
+ anonymousRole?: string;
24
+ /**
25
+ * Roles the token may ask for (`db-pre-request` / role switch). An entry maps
26
+ * the claim value to the database role, e.g. `{ anon: 'c##anon' }` on Oracle,
27
+ * whose common roles must carry the `C##` prefix.
28
+ */
29
+ roles?: Record<string, string>;
30
+ /** JSON path of the role claim (`jwt-role-claim-key`, default `$.role`). */
31
+ roleClaimKey?: string;
32
+ /** `true` (default) keeps PostgREST's rules; `false` lets requests without a usable token run as the connecting role. */
33
+ required?: boolean;
34
+ /** Use a custom verifier instead of `secret` / `publicKey`. */
35
+ verifier?: JwtVerifier;
36
+ }
37
+ export interface AnygrestOptions {
38
+ /** Expose the schema cache over `GET /` as OpenAPI. Default: true. */
39
+ openapi?: boolean;
40
+ /**
41
+ * Tables that may be exposed. Defaults to every table found by
42
+ * introspection. Useful to hide internal tables.
43
+ */
44
+ tables?: string[] | ((table: TableMeta) => boolean);
45
+ /** Upper bound for `limit` (PostgREST `db-max-rows`). */
46
+ maxRows?: number;
47
+ /** Called for every request; return `false` to reject with 401. */
48
+ authenticate?: (request: Request) => boolean | Promise<boolean>;
49
+ /**
50
+ * JWT authentication. Claims are exposed to the database for every request
51
+ * (`request.jwt.claims`, `role`, `request.method`, …) and the request runs as
52
+ * the token's role. Only available on engines with session variables.
53
+ */
54
+ jwt?: JwtOptions;
55
+ /** Database-side names for the request context (Oracle namespace, Redshift table…). */
56
+ context?: ContextOptions;
57
+ /**
58
+ * SQL function run inside every request's transaction before the request
59
+ * itself (PostgREST `db-pre-request`). It sees the request variables
60
+ * (`request.jwt.claims`, …) and may raise an error to reject the request.
61
+ */
62
+ preRequest?: string;
63
+ /** Emit `console.error` for unexpected failures. */
64
+ debug?: boolean;
65
+ /**
66
+ * PostgREST `url-use-legacy-target-names` (default `true`): an embedded
67
+ * resource may be named by its relation name in a control even when the
68
+ * `select` aliased it (`tasks.order` on `the_tasks:tasks`). Allowed, the
69
+ * request answers with `Warning: 299`; disabled, it is `400 PGRST108`
70
+ * (`Plan.hs:1094-1108` `matchTarget` / `findLegacyUsage`).
71
+ */
72
+ urlUseLegacyTargetNames?: boolean;
73
+ /**
74
+ * CORS policy (PostgREST `server-cors-allowed-origins`, `Cors.hs`). Applied
75
+ * to every response that carries an `Origin` request header. The default,
76
+ * `*`, allows any origin.
77
+ */
78
+ cors?: CorsOptions;
79
+ }
80
+ export interface Anygrest {
81
+ app: Hono<any>;
82
+ schema: SchemaCache;
83
+ /** The schema this instance serves (`Accept-Profile` / `Content-Profile`). */
84
+ readonly schemaName: string;
85
+ /** OpenAPI document, or `null` when `options.openapi === false`. */
86
+ openapi: Record<string, unknown> | null;
87
+ /** Re-reads table metadata from the database. */
88
+ reload(): Promise<void>;
89
+ /** Destroys the Knex pool so the process can exit (tests, graceful shutdown). */
90
+ close(): Promise<void>;
91
+ }
92
+ /**
93
+ * Builds a Hono application exposing the PostgREST-compatible REST API for the
94
+ * given database connection.
95
+ */
96
+ export declare function createAnygrest(database: DatabaseClient, options?: AnygrestOptions): Promise<Anygrest>;