@onreza/sqlx-js 0.3.0 → 0.5.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/README.md +129 -36
- package/ROADMAP.md +3 -4
- package/dist/bin/sqlx-js.js +137 -26
- package/dist/src/artifacts.d.ts +9 -0
- package/dist/src/artifacts.js +26 -0
- package/dist/src/cache.d.ts +17 -0
- package/dist/src/cache.js +83 -1
- package/dist/src/codegen.d.ts +2 -1
- package/dist/src/codegen.js +34 -5
- package/dist/src/commands/doctor.d.ts +16 -0
- package/dist/src/commands/doctor.js +196 -0
- package/dist/src/commands/init.d.ts +1 -0
- package/dist/src/commands/init.js +36 -9
- package/dist/src/commands/migrate.js +7 -22
- package/dist/src/commands/pgschema.d.ts +31 -0
- package/dist/src/commands/pgschema.js +208 -0
- package/dist/src/commands/prepare.d.ts +40 -5
- package/dist/src/commands/prepare.js +344 -58
- package/dist/src/commands/watch.d.ts +1 -0
- package/dist/src/commands/watch.js +23 -9
- package/dist/src/config.d.ts +27 -0
- package/dist/src/config.js +141 -11
- package/dist/src/function-cache.d.ts +18 -0
- package/dist/src/function-cache.js +38 -0
- package/dist/src/index.d.ts +6 -2
- package/dist/src/index.js +2 -1
- package/dist/src/pg/functions.d.ts +4 -0
- package/dist/src/pg/functions.js +150 -0
- package/dist/src/pg/oids.js +2 -0
- package/dist/src/pg/schema.d.ts +1 -0
- package/dist/src/pg/schema.js +3 -0
- package/dist/src/postgres-runtime.d.ts +3 -0
- package/dist/src/postgres-runtime.js +66 -29
- package/dist/src/runtime.d.ts +36 -3
- package/dist/src/runtime.js +91 -22
- package/dist/src/scan/scanner.d.ts +9 -2
- package/dist/src/scan/scanner.js +79 -28
- package/dist/src/typed.d.ts +10 -0
- package/package.json +6 -5
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ Compile-time-checked raw SQL for TypeScript + PostgreSQL. Inspired by Rust's [sq
|
|
|
4
4
|
|
|
5
5
|
You write plain SQL strings. A `prepare` step validates them against your database via the PostgreSQL wire protocol and generates a TypeScript declaration file. Wrong column names and stale queries fail during `prepare`; mismatched parameter types and row usage become TypeScript errors.
|
|
6
6
|
|
|
7
|
-
The runtime uses [Postgres.js](https://github.com/porsager/postgres) through a single adapter instead of a Bun-specific client. The published CLI
|
|
7
|
+
The runtime uses [Postgres.js](https://github.com/porsager/postgres) through a single adapter instead of a Bun-specific client. The published CLI requires **Node ≥ 24** (`#!/usr/bin/env node`) and can also run through **Bun ≥ 1.3**.
|
|
8
8
|
|
|
9
9
|
```ts
|
|
10
10
|
import { sql } from "@onreza/sqlx-js";
|
|
@@ -30,19 +30,22 @@ const rows = await sql(
|
|
|
30
30
|
- **Wide built-in type coverage**: numeric, text, date/time, UUID, json/jsonb, network (inet/cidr/macaddr/macaddr8), bit strings, ranges/multiranges, geometric, money, tsvector/tsquery, xml — and the matching array variants.
|
|
31
31
|
- **External SQL files** via `sql.file("queries/foo.sql", ...)` — prepared and typed through `KnownFileQueries`. Watch mode re-prepares on `.sql` edits too.
|
|
32
32
|
- **One-row helpers**: `sql.one(...)`, `sql.optional(...)`, `sql.file.one(...)`, `sql.file.optional(...)`, and the same chain on the `tx` callback — friendly with `noUncheckedIndexedAccess: true`. The scanner walks all of them.
|
|
33
|
-
- **
|
|
33
|
+
- **Unambiguous JSON and PostgreSQL array params** through `sql.json(...)` and `sql.array(...)`. Primitive JSON arrays cannot be silently encoded as PostgreSQL array literals.
|
|
34
34
|
- **Typed transactions** via `sql.transaction(async tx => …)` — the `tx` callback parameter is recognized by the scanner, so queries inside the block keep full type checking.
|
|
35
35
|
- **Sourcemap-accurate error reporting**: every prepare failure points to `file:line:column` of the originating `sql(...)` call site, with PG error code, position, and hint.
|
|
36
36
|
- **Linear migrations** with hash tampering detection.
|
|
37
37
|
- **Migration squash baselines** via `migrate squash`: generate a schema-only baseline from a shadow database, then hash-adopt it on already-migrated databases.
|
|
38
38
|
- **Runtime `migrate()`** with PostgreSQL advisory lock, safe for multi-replica startup.
|
|
39
|
-
- **
|
|
39
|
+
- **Optional pgschema workflow** via `init --schema-provider pgschema` and `sqlx-js db install|check|plan|apply` for PostgreSQL schema-as-code projects.
|
|
40
|
+
- **Versioned offline cache** committed to your repo. `prepare --check` validates fingerprints, generator revision, and type-affecting config without a database; `prepare --verify` compares fresh live/shadow artifacts without writing.
|
|
40
41
|
- **Schema snapshot + LLM manifest** via `schema dump` / `schema check`: tables, columns, constraints, indexes, types, and function/procedure metadata are introspected from PostgreSQL.
|
|
42
|
+
- **Generated function catalog** via `KnownFunctions`: `prepare` records user-schema PostgreSQL functions/procedures from `pg_proc` with approximate parameter and return TypeScript types.
|
|
41
43
|
- **Shadow database validation** via `migrate dev` / `migrate verify`: auto-create a disposable shadow DB, apply migrations, validate SQL, and drop it afterwards.
|
|
42
44
|
- **Safe identifier quoting** via `sql.id(...)`, backed by the committed schema snapshot whitelist.
|
|
43
45
|
- **Single runtime adapter**: Postgres.js backs the runtime on Node/Bun-compatible environments — no Bun.SQL-specific adapter to choose.
|
|
44
|
-
- **Watch mode**: debounced re-prepare with a warm `PgClient` + `SchemaCache` on
|
|
46
|
+
- **Watch mode**: debounced re-prepare with a warm `PgClient` + `SchemaCache` on source/SQL changes and scanner/config graph updates.
|
|
45
47
|
- **Cache pruning** removes orphaned entries automatically (toggleable with `--no-prune`).
|
|
48
|
+
- **Environment doctor** checks runtime versions, config loading, `.env`, database connectivity/permissions, cache metadata, tsconfig inclusion, and pgschema availability.
|
|
46
49
|
|
|
47
50
|
## Install
|
|
48
51
|
|
|
@@ -52,6 +55,8 @@ npm install @onreza/sqlx-js
|
|
|
52
55
|
bun add @onreza/sqlx-js
|
|
53
56
|
```
|
|
54
57
|
|
|
58
|
+
Node.js 24 or newer is required. Bun users need Bun 1.3 or newer.
|
|
59
|
+
|
|
55
60
|
The package installs a `sqlx-js` binary. The CLI examples below use `npx @onreza/sqlx-js`; `bunx @onreza/sqlx-js ...` works the same if your project uses Bun.
|
|
56
61
|
|
|
57
62
|
## Setup
|
|
@@ -64,6 +69,16 @@ npx @onreza/sqlx-js init
|
|
|
64
69
|
|
|
65
70
|
Creates `sqlx-js.config.ts`, a `migrations/` directory, and `.env.example` if they don't already exist (it never overwrites existing files), then prints the next steps. Skip it if you prefer to wire things up manually.
|
|
66
71
|
|
|
72
|
+
For declarative PostgreSQL schema management, scaffold the pgschema workflow instead:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
npx @onreza/sqlx-js init --schema-provider pgschema
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
This creates `schema.sql` and configures `schema.provider = "pgschema"` in `sqlx-js.config.ts`. The npm package does not bundle pgschema, but `sqlx-js db install` downloads the pinned pgschema binary into `node_modules/.cache/sqlx-js/pgschema/`; then `sqlx-js db check` verifies it.
|
|
79
|
+
|
|
80
|
+
The managed pgschema workflow supports Linux and macOS. On Windows, run sqlx-js under WSL/Linux/macOS or use the built-in `sqlx-js migrate` workflow.
|
|
81
|
+
|
|
67
82
|
### 1. Configure the database URL
|
|
68
83
|
|
|
69
84
|
```bash
|
|
@@ -75,6 +90,8 @@ DATABASE_URL=postgres://user:password@localhost:5432/your_db
|
|
|
75
90
|
|
|
76
91
|
Supported `sslmode` values: `disable`, `prefer` (default — try TLS, fall back to plaintext), `require` (TLS or fail), `verify-ca`, `verify-full`. For a private/self-signed CA, point `sslrootcert` (and optionally `sslcert` / `sslkey` for client certs) at PEM files: `?sslmode=verify-full&sslrootcert=/etc/ssl/ca.pem`. `application_name`, `connect_timeout` (seconds), and `statement_timeout` (milliseconds) are also honored when provided as URL parameters.
|
|
77
92
|
|
|
93
|
+
CLI commands load `<root>/.env` before reading connection settings. Variables already present in the process environment take precedence. Application runtime configuration remains owned by your application/framework.
|
|
94
|
+
|
|
78
95
|
### 2. Create a migration
|
|
79
96
|
|
|
80
97
|
```bash
|
|
@@ -152,7 +169,7 @@ Unknown queries, wrong parameter types, and dynamic strings are compile errors.
|
|
|
152
169
|
|
|
153
170
|
### `sql.file(path, ...params)`
|
|
154
171
|
|
|
155
|
-
Load SQL from an external file.
|
|
172
|
+
Load SQL from an external file. The path is root-relative everywhere: prepare resolves it against `--root`, codegen keeps the exact string literal as the `KnownFileQueries` key, and runtime resolves it against `fileRoot` (default: `process.cwd()`). Absolute paths and paths escaping the root are rejected.
|
|
156
173
|
|
|
157
174
|
```ts
|
|
158
175
|
// queries/top_admins.sql
|
|
@@ -165,7 +182,7 @@ const admins = await sql.file("queries/top_admins.sql", "admin", 5);
|
|
|
165
182
|
// admins: { id: bigint; name: string }[]
|
|
166
183
|
```
|
|
167
184
|
|
|
168
|
-
File-backed queries are emitted into a separate `KnownFileQueries` interface.
|
|
185
|
+
File-backed queries are emitted into a separate `KnownFileQueries` interface. A call from any nested source directory still uses the same project-root-relative literal.
|
|
169
186
|
|
|
170
187
|
### `sql.one(query, ...params)` and `sql.optional(query, ...params)`
|
|
171
188
|
|
|
@@ -181,18 +198,46 @@ const maybe = await sql.optional(`SELECT id FROM users WHERE email = $1`, "x@y")
|
|
|
181
198
|
|
|
182
199
|
Both forms also exist on `sql.file` (`sql.file.one("queries/by_id.sql", ...)`) and inside transactions (`tx.one(...)`, `tx.optional(...)`, `tx.file.one(...)`, `tx.file.optional(...)`). The scanner recognizes every chain — these call sites are added to `KnownQueries` / `KnownFileQueries` just like a plain `sql(...)`.
|
|
183
200
|
|
|
184
|
-
###
|
|
201
|
+
### `sql.execute(query, ...params)`
|
|
202
|
+
|
|
203
|
+
Execute a typed statement when rows are not the result contract. It preserves parameter checking and returns Postgres command metadata:
|
|
204
|
+
|
|
205
|
+
```ts
|
|
206
|
+
const result = await sql.execute(
|
|
207
|
+
`UPDATE jobs SET claimed_at = now() WHERE id = $1 AND claimed_at IS NULL`,
|
|
208
|
+
jobId,
|
|
209
|
+
);
|
|
210
|
+
|
|
211
|
+
if (result.rowCount !== 1) throw new Error("job was already claimed");
|
|
212
|
+
// result: { rowCount: number; command: string }
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
`sql.file.execute(...)` and `tx.execute(...)` use the same contract. Query hooks receive the affected-row count rather than `0` for DML without `RETURNING`.
|
|
185
216
|
|
|
186
|
-
|
|
217
|
+
### JSON and PostgreSQL array parameters
|
|
218
|
+
|
|
219
|
+
Parameter wrappers make the wire representation explicit. Use `sql.array(...)` for PostgreSQL arrays and `sql.json(...)` for `json`/`jsonb` values:
|
|
187
220
|
|
|
188
221
|
```ts
|
|
189
|
-
await sql(
|
|
190
|
-
|
|
222
|
+
await sql(
|
|
223
|
+
"SELECT $1::text[] AS tags",
|
|
224
|
+
sql.array(["alpha", "beta,gamma", "with \"quote\""]),
|
|
225
|
+
);
|
|
226
|
+
|
|
227
|
+
await sql(
|
|
228
|
+
"INSERT INTO events (payload) VALUES ($1)",
|
|
229
|
+
sql.json([1, 2, 3]),
|
|
230
|
+
);
|
|
231
|
+
|
|
232
|
+
await sql(
|
|
233
|
+
"SELECT $1::jsonb[] AS payloads",
|
|
234
|
+
sql.array([sql.json({ kind: "created" }), sql.json([1, 2, 3]), null]),
|
|
235
|
+
);
|
|
191
236
|
```
|
|
192
237
|
|
|
193
|
-
|
|
238
|
+
Generated parameter types require `PgArrayParameter<T>` or `JsonParameter<T>`, so mixing the two representations is a TypeScript error. A PostgreSQL `json[]` / `jsonb[]` composes both wrappers: the outer `sql.array(...)` selects the PostgreSQL array representation and each non-SQL-NULL element uses `sql.json(...)`. `sql.json(null)` represents JSON `null`; a bare `null` remains SQL `NULL` when the database parameter is nullable.
|
|
194
239
|
|
|
195
|
-
|
|
240
|
+
Both helpers also work with `unsafe(...)`. `encodePgArrayLiteral(arr)` remains exported for code that explicitly needs a PostgreSQL array literal string.
|
|
196
241
|
|
|
197
242
|
### Parameter nullability
|
|
198
243
|
|
|
@@ -277,13 +322,18 @@ import { createClient, setClient } from "@onreza/sqlx-js";
|
|
|
277
322
|
setClient(createClient(process.env.DATABASE_URL));
|
|
278
323
|
```
|
|
279
324
|
|
|
280
|
-
`createClient(url, options)` accepts every Postgres.js option plus
|
|
325
|
+
`createClient(url, options)` accepts every Postgres.js option plus sqlx-js runtime options:
|
|
281
326
|
|
|
282
327
|
```ts
|
|
283
328
|
setClient(createClient(process.env.DATABASE_URL, {
|
|
284
329
|
// Server-side per-connection statement timeout (ms). Also settable via
|
|
285
330
|
// ?statement_timeout=5000 in DATABASE_URL.
|
|
286
331
|
statementTimeoutMs: 5000,
|
|
332
|
+
// Base directory for root-relative sql.file(...) calls.
|
|
333
|
+
fileRoot: import.meta.dirname,
|
|
334
|
+
// Honored for every unsafe call. Set false for PgBouncer transaction mode
|
|
335
|
+
// unless protocol-level prepared statements are configured there.
|
|
336
|
+
prepare: false,
|
|
287
337
|
// Fires after every query/transaction statement, success or failure.
|
|
288
338
|
onQuery: ({ query, params, durationMs, rowCount, error }) => {
|
|
289
339
|
if (error) logger.error({ query, error }); // database errors are PgError
|
|
@@ -334,8 +384,10 @@ In addition to `import { sql } from "@onreza/sqlx-js"`, the scanner recognises `
|
|
|
334
384
|
## CLI
|
|
335
385
|
|
|
336
386
|
```
|
|
337
|
-
sqlx-js init [--root <dir>]
|
|
338
|
-
sqlx-js
|
|
387
|
+
sqlx-js init [--root <dir>] [--schema-provider builtin|pgschema]
|
|
388
|
+
sqlx-js doctor [--root <dir>] [--json]
|
|
389
|
+
sqlx-js db install | check | plan | apply [--root <dir>] [-- <pgschema args>]
|
|
390
|
+
sqlx-js prepare [--check | --verify | --watch] [--json] [--root <dir>] [--dts <path>] [--no-prune] [--shadow-url <url>]
|
|
339
391
|
sqlx-js migrate dev [--shadow-admin-url <url> | --shadow-url <url>] [--lock-timeout <ms>] | verify [--shadow-admin-url <url> | --shadow-url <url>] [--lock-timeout <ms>] | run [--dry-run] [--json] [--lock-timeout <ms>] | info [--json] | check [--json] | revert [--dry-run] [--json] [--shadow-admin-url <url> | --shadow-url <url>] [--lock-timeout <ms>] | add <name> | squash <name> [--shadow-admin-url <url> | --shadow-url <url>] [--replace] [--pg-dump <path>] [--lock-timeout <ms>] | archive list | archive restore <name> [--force]
|
|
340
392
|
sqlx-js schema dump | check [--schema <path>] [--manifest <path>] [--no-manifest] [--shadow-url <url>]
|
|
341
393
|
sqlx-js --version | --help
|
|
@@ -346,13 +398,14 @@ Regular `prepare` describes queries across a small connection pool (default 8, o
|
|
|
346
398
|
| Flag | Meaning |
|
|
347
399
|
|-----------------------|--------------------------------------------------------------------------------------|
|
|
348
400
|
| `--check` | Offline: verify every scanned query is present in cache, no database required. |
|
|
401
|
+
| `--verify` | Prepare against the live/shadow schema and compare generated artifacts without writing. |
|
|
349
402
|
| `--watch` | Persistent connection, re-prepare on file change. |
|
|
350
403
|
| `--root <dir>` | Source/cache/migrations root (default: cwd). |
|
|
351
404
|
| `--dts <path>` | Declarations output (default: `<root>/sqlx-js-env.d.ts`). |
|
|
352
405
|
| `--no-prune` | Keep orphaned cache entries instead of removing them. |
|
|
353
406
|
| `--migrations <dir>` | Migrations directory (default: `<root>/migrations`). |
|
|
354
407
|
| `--dry-run` | For `migrate run` / `migrate revert`: validate without applying to the target DB. |
|
|
355
|
-
| `--json` | Machine-readable output
|
|
408
|
+
| `--json` | Machine-readable prepare diagnostics, doctor output, migration inspection and dry-runs. |
|
|
356
409
|
| `--force` | For `migrate archive restore`: allow overwriting existing migration files. |
|
|
357
410
|
| `--lock-timeout <ms>` | Advisory-lock acquisition timeout for `migrate run` / `revert` / `dev` / `verify` / `squash`. |
|
|
358
411
|
| `--shadow-url <url>` | Use an existing disposable shadow DB instead of auto-creating one. |
|
|
@@ -362,13 +415,30 @@ Regular `prepare` describes queries across a small connection pool (default 8, o
|
|
|
362
415
|
| `--schema <path>` | Schema snapshot path (default: `<root>/.sqlx-js/schema/schema.json`). |
|
|
363
416
|
| `--manifest <path>` | LLM schema manifest path (default: `<root>/.sqlx-js/schema/schema.md`). |
|
|
364
417
|
| `--no-manifest` | Skip writing the LLM schema manifest during `schema dump`. |
|
|
418
|
+
| `--schema-provider <name>` | For `init`: `builtin` (default) or `pgschema`. |
|
|
365
419
|
|
|
366
420
|
Flags that take a value accept both `--flag value` and `--flag=value` forms.
|
|
367
421
|
|
|
422
|
+
Prepare and doctor JSON use `formatVersion: 1`. Prepare diagnostics include a stable phase plus root-relative file, 1-based line/column, PostgreSQL code/position/hint when available, and the query text. This is intended for CI annotations and editor integrations; stdout contains one JSON document and human progress is suppressed.
|
|
423
|
+
|
|
368
424
|
`DATABASE_URL` must be set for any command that touches the application database or auto-creates a shadow database. `SHADOW_ADMIN_DATABASE_URL` can point at a maintenance/admin database when the application user cannot `CREATE DATABASE`; `SHADOW_DATABASE_URL` can point at a pre-created disposable shadow database. The internal wire client understands `sslmode`, `sslrootcert`, `sslcert`, `sslkey`, `application_name`, `connect_timeout` (seconds), and `statement_timeout` (milliseconds).
|
|
369
425
|
|
|
370
426
|
### Development and deployment flows
|
|
371
427
|
|
|
428
|
+
For complex PostgreSQL schemas with functions, triggers, RLS, grants, partitions, and other schema-level objects, prefer pgschema for DDL ownership and use sqlx-js for application-query typing:
|
|
429
|
+
|
|
430
|
+
```bash
|
|
431
|
+
sqlx-js init --schema-provider pgschema
|
|
432
|
+
sqlx-js db install
|
|
433
|
+
sqlx-js db check
|
|
434
|
+
# edit schema.sql
|
|
435
|
+
sqlx-js db plan -- --output-json plan.json
|
|
436
|
+
sqlx-js db apply -- --auto-approve
|
|
437
|
+
sqlx-js prepare
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
`sqlx-js db install` installs the pinned pgschema version used by this sqlx-js release. `sqlx-js db check`, `plan`, and `apply` use `schema.command` when configured; otherwise they prefer the managed binary under `node_modules/.cache/sqlx-js/pgschema/` and fall back to `pgschema` on `PATH`. `plan` and file-backed `apply` translate `DATABASE_URL` into `--host`, `--port`, `--db`, `--user`, `--file`, and `--schema` arguments, pass the password through `PGPASSWORD`, pass TLS settings through `PGSSLMODE` / `PGSSLROOTCERT` / `PGSSLCERT` / `PGSSLKEY`, and forward any arguments after `--` directly to pgschema. `sqlx-js db apply -- --plan plan.json` applies a reviewed pgschema plan without requiring the local `schema.sql` file. The schema provider is configured in `sqlx-js.config.ts`; by default the schema file is `schema.sql` and the schema is `public`. The pinned pgschema 1.12.0 CLI accepts a single `--schema` value, so sqlx-js rejects pgschema configs with more than one schema instead of silently applying only one.
|
|
441
|
+
|
|
372
442
|
Use `migrate dev` while developing migrations and SQL:
|
|
373
443
|
|
|
374
444
|
```bash
|
|
@@ -379,15 +449,18 @@ sqlx-js migrate dev
|
|
|
379
449
|
|
|
380
450
|
`migrate dev` creates a disposable shadow database, applies all migrations from scratch, validates that the latest migration's `.down.sql` restores the previous schema (squash baselines may omit `.down.sql`), prepares project SQL against the shadow schema, writes `.sqlx-js/` plus `sqlx-js-env.d.ts`, and drops the shadow database. This means you can keep editing a local WIP migration before it is merged. You do not need to drop your application database or create a new migration for every local edit.
|
|
381
451
|
|
|
452
|
+
The built-in `migrate` workflow is kept for simple projects and embedded application startup. PostgreSQL-heavy schema lifecycle features belong in pgschema rather than in sqlx-js.
|
|
453
|
+
|
|
382
454
|
Use `migrate verify` in PR/CI before merge:
|
|
383
455
|
|
|
384
456
|
```bash
|
|
385
457
|
sqlx-js migrate verify
|
|
386
458
|
sqlx-js prepare --check
|
|
459
|
+
sqlx-js doctor --json
|
|
387
460
|
tsc --noEmit
|
|
388
461
|
```
|
|
389
462
|
|
|
390
|
-
`migrate verify` runs the same shadow-database migration/down/SQL validation as `migrate dev`,
|
|
463
|
+
`migrate verify` runs the same shadow-database migration/down/SQL validation as `migrate dev`, generates prepare output in a temporary directory, and fails when the committed `.sqlx-js/` or `sqlx-js-env.d.ts` differs. It never modifies those artifacts.
|
|
391
464
|
|
|
392
465
|
Use `migrate run` in production/staging:
|
|
393
466
|
|
|
@@ -445,20 +518,33 @@ Phases reported separately: `describe failed`, `analyze failed`, `paramMap faile
|
|
|
445
518
|
|
|
446
519
|
`sqlx-js.config.ts` at the project root is optional.
|
|
447
520
|
|
|
521
|
+
Under Node.js, TypeScript config is loaded through Node 24's native type stripping, so keep it to erasable TypeScript syntax. The generated `defineConfig(...)` form works on both Node and Bun; use `.mjs` if the config needs runtime constructs that Node cannot strip.
|
|
522
|
+
|
|
448
523
|
```ts
|
|
449
|
-
import
|
|
524
|
+
import { defineConfig } from "@onreza/sqlx-js";
|
|
450
525
|
|
|
451
|
-
|
|
526
|
+
export default defineConfig({
|
|
527
|
+
scan: {
|
|
528
|
+
include: ["apps/*/src/**/*", "packages/*/src/**/*"],
|
|
529
|
+
exclude: ["**/*.generated.ts"],
|
|
530
|
+
},
|
|
531
|
+
schema: {
|
|
532
|
+
provider: "pgschema",
|
|
533
|
+
file: "schema.sql",
|
|
534
|
+
schemas: ["public"],
|
|
535
|
+
},
|
|
452
536
|
jsonbTypes: {
|
|
453
537
|
"users.settings": "SqlxJsJson.UserSettings",
|
|
454
538
|
"posts.meta": "SqlxJsJson.PostMeta",
|
|
455
539
|
"posts.attachments": "SqlxJsJson.Attachment",
|
|
456
540
|
},
|
|
457
|
-
};
|
|
458
|
-
|
|
459
|
-
export default config;
|
|
541
|
+
});
|
|
460
542
|
```
|
|
461
543
|
|
|
544
|
+
By default the scanner uses the root `tsconfig.json` file list and follows TypeScript project references, so a referenced monorepo is scanned without walking unrelated folders. `scan.include` replaces that source-file universe with TypeScript glob patterns; `scan.exclude` is added to the built-in dependency/build exclusions. If there is no root `tsconfig.json`, the fallback is a recursive TypeScript scan.
|
|
545
|
+
|
|
546
|
+
The `schema` block is optional. Use `provider: "pgschema"` when sqlx-js should delegate schema planning/apply commands to pgschema. `command` can override the managed binary lookup and point at another executable. With the pinned pgschema 1.12.0 CLI, `schemas` must contain exactly one schema name.
|
|
547
|
+
|
|
462
548
|
Declare the referenced types anywhere in your project (`.d.ts` file is conventional):
|
|
463
549
|
|
|
464
550
|
```ts
|
|
@@ -477,7 +563,7 @@ declare global {
|
|
|
477
563
|
export {};
|
|
478
564
|
```
|
|
479
565
|
|
|
480
|
-
After re-running `prepare`, every `jsonb` column or parameter declared in `jsonbTypes` is checked against the corresponding TypeScript type. Columns without a custom mapping use `JsonValue` for result rows and `JsonInput` for parameters, both exported by `@onreza/sqlx-js
|
|
566
|
+
After re-running `prepare`, every `jsonb` column or parameter declared in `jsonbTypes` is checked against the corresponding TypeScript type. Columns without a custom mapping use `JsonValue` for result rows and `JsonInput` inside `JsonParameter` for parameters, both exported by `@onreza/sqlx-js`. Pass JSON parameters through `sql.json(value)`: non-JSON inputs such as `Date`, functions, and `bigint` are rejected by TypeScript while plain JSON objects, arrays, strings, numbers, booleans, and nested JSON `null` values are accepted. A bare top-level `null` remains SQL `NULL` and is allowed only when the mapped database parameter is nullable; use `sql.json(null)` for JSON `null`.
|
|
481
567
|
|
|
482
568
|
### Extension types and `customTypes`
|
|
483
569
|
|
|
@@ -497,16 +583,15 @@ sqlx-js ships with a built-in registry that resolves popular PostgreSQL extensio
|
|
|
497
583
|
Add or override mappings via `customTypes` in `sqlx-js.config.ts`. Keys are `pg_type.typname` values (the bare type name). The registry is global by type name, so two schemas with the same `typname` cannot be mapped differently:
|
|
498
584
|
|
|
499
585
|
```ts
|
|
500
|
-
import
|
|
586
|
+
import { defineConfig } from "@onreza/sqlx-js";
|
|
501
587
|
|
|
502
|
-
|
|
588
|
+
export default defineConfig({
|
|
503
589
|
customTypes: {
|
|
504
590
|
vector: "Float32Array", // override pgvector default
|
|
505
591
|
geometry: "GeoJSON.Geometry", // postgis (not built-in by design)
|
|
506
592
|
myapp_color: "`#${string}`", // your own CREATE TYPE base/domain
|
|
507
593
|
},
|
|
508
|
-
};
|
|
509
|
-
export default config;
|
|
594
|
+
});
|
|
510
595
|
```
|
|
511
596
|
|
|
512
597
|
Domains resolve to their base type through `pg_type.typbasetype`. `CREATE DOMAIN positive_int AS integer CHECK (VALUE > 0)` → `number`, `CREATE DOMAIN tagged AS hstore` → `Record<string, string | null>`. Array variants of any registered scalar are also wired up automatically — `vector[]` → `(number[])[]`.
|
|
@@ -535,15 +620,22 @@ Commit the generated `sqlx-js-env.d.ts` and the `.sqlx-js/` cache directory to y
|
|
|
535
620
|
|
|
536
621
|
```yaml
|
|
537
622
|
- run: bun install
|
|
538
|
-
- run: sqlx-js migrate verify #
|
|
539
|
-
|
|
623
|
+
- run: sqlx-js migrate verify # built-in migration workflow
|
|
624
|
+
# or, when schema.provider is "pgschema":
|
|
625
|
+
- run: sqlx-js db install
|
|
626
|
+
- run: sqlx-js db plan -- --output-json plan.json
|
|
627
|
+
- run: sqlx-js prepare --verify # live/shadow comparison of every generated artifact
|
|
628
|
+
- run: sqlx-js prepare --check # offline cache/version/config consistency
|
|
629
|
+
- run: sqlx-js doctor --json # runtime/config/DB/cache/tsconfig preflight
|
|
540
630
|
- run: sqlx-js schema check # fails if the committed schema snapshot is stale
|
|
541
631
|
- run: tsc --noEmit # fails if types are stale
|
|
542
|
-
- run: bun test
|
|
632
|
+
- run: bun test --timeout 120000
|
|
543
633
|
- run: bun run build # emits publishable JS + declarations under dist/
|
|
544
634
|
```
|
|
545
635
|
|
|
546
|
-
The `migrate verify` step needs `DATABASE_URL` credentials that can either create a temporary database or use `--shadow-admin-url` / `--shadow-url`. It does not write `.sqlx-js/` or `sqlx-js-env.d.ts`. The `prepare --check` step then runs without a database; your committed offline cache is the source of truth. `schema check` intentionally uses a live database because it verifies the committed schema contract against PostgreSQL.
|
|
636
|
+
The `migrate verify` step needs `DATABASE_URL` credentials that can either create a temporary database or use `--shadow-admin-url` / `--shadow-url`. It does not write `.sqlx-js/` or `sqlx-js-env.d.ts`. For pgschema projects, `sqlx-js db plan` checks the desired `schema.sql` against the target database and leaves application query typing to `prepare`. The `prepare --check` step then runs without a database; your committed offline cache is the source of truth. Add `prepare --verify` when CI has a canonical database/shadow schema and must prove byte-for-byte artifact freshness. `schema check` intentionally uses a live database because it verifies the committed schema contract against PostgreSQL.
|
|
637
|
+
|
|
638
|
+
The managed pgschema binary is installed under `node_modules/.cache/sqlx-js/pgschema/`, not `.sqlx-js/`, so it is not part of the committed offline cache.
|
|
547
639
|
|
|
548
640
|
## Contributing
|
|
549
641
|
|
|
@@ -562,23 +654,24 @@ Releases are automated via `release-please`: pushes to `main` accumulate into a
|
|
|
562
654
|
|
|
563
655
|
- PostgreSQL only (no MySQL or SQLite).
|
|
564
656
|
- The scanner only follows direct named imports and namespace imports from `@onreza/sqlx-js`; it does not follow re-exports, dynamic aliases, or tagged-template calls.
|
|
565
|
-
- `INSERT INTO t VALUES (...)` without an explicit column list isn't parameter-mapped.
|
|
566
657
|
- `SELECT *` falls back to conservative nullability.
|
|
567
|
-
-
|
|
658
|
+
- Plain `sql(...)` keeps returning rows, so statements without `RETURNING` produce an empty typed array. Use `sql.execute(...)` when affected-row count and command metadata matter.
|
|
568
659
|
- Nested CTE references (CTE-`b` referencing CTE-`a` in the same `WITH`) and `WITH RECURSIVE` are not analysed transitively — at worst this produces extra `T | null`. Use `AS "id!"` overrides if needed.
|
|
569
660
|
- Column names whose **real** name (not an alias) ends with `!` or `?` are not supported — the runtime strips those suffixes assuming an override. Use `AS "alias"` if you have such a column.
|
|
570
661
|
- Migrations run inside `BEGIN/COMMIT`. DDL that disallows transactions (`CREATE INDEX CONCURRENTLY`, `VACUUM`, `REINDEX CONCURRENTLY`, …) will fail; split such operations into separate migrations executed outside the runner.
|
|
571
662
|
- The **internal** wire client (used by `migrate run`, `prepare`, and the runtime `migrate()` helper) reads `sslmode`, `sslrootcert`/`sslcert`/`sslkey`, `application_name`, `connect_timeout`, and `statement_timeout` from `DATABASE_URL`. The default runtime `sql()` path delegates connection handling to Postgres.js; configure TLS, pooling, and timeouts through the `DATABASE_URL` and `createClient(...)` options it understands (`statementTimeoutMs` is a convenience that maps to a per-connection `statement_timeout`).
|
|
572
663
|
- `connect_timeout` bounds the entire internal-client connect, including the TLS handshake and SCRAM authentication.
|
|
573
|
-
- `sql.file(path)`
|
|
664
|
+
- Runtime `sql.file(path)` resolves against `fileRoot` while prepare resolves against `--root`. They are both root-relative, but applications started outside the project root must set `fileRoot` explicitly.
|
|
574
665
|
|
|
575
666
|
See [ROADMAP.md](./ROADMAP.md) for what's planned.
|
|
576
667
|
|
|
577
668
|
## Upgrading
|
|
578
669
|
|
|
579
|
-
### Cache
|
|
670
|
+
### Cache and parameter contract change (pre-1.0)
|
|
671
|
+
|
|
672
|
+
Generated cache now includes `.sqlx-js/cache-manifest.json` with an explicit cache format, generator revision, and hash of `jsonbTypes` / `customTypes`. Cache without this manifest is rejected. Delete `.sqlx-js/` and re-run `sqlx-js prepare` against your database — there is no data loss because the cache is generated.
|
|
580
673
|
|
|
581
|
-
|
|
674
|
+
Generated JSON and PostgreSQL array parameters now require `sql.json(...)` and `sql.array(...)`. This removes the ambiguous runtime guess where a JavaScript array could mean either a PostgreSQL array or a JSON array. Replace raw array JSON params with `sql.json(value)` and PostgreSQL arrays with `sql.array(value)` before regenerating declarations.
|
|
582
675
|
|
|
583
676
|
CI (`prepare --check`) will also fail loudly until the cache is regenerated; this is intentional so a stale schema can't silently emit incorrect `.d.ts`.
|
|
584
677
|
|
package/ROADMAP.md
CHANGED
|
@@ -6,18 +6,17 @@ Items already shipped live in the [README](./README.md) feature list; this file
|
|
|
6
6
|
|
|
7
7
|
| Feature | ROI | Notes |
|
|
8
8
|
|---------|-----|-------|
|
|
9
|
-
|
|
|
9
|
+
| pgschema integration hardening | 8 | Basic `init --schema-provider pgschema` plus managed `sqlx-js db install/check/plan/apply` exists. Continue with better docs, CI examples, schema snapshot handoff, and migration guidance for projects that outgrow built-in migrations. |
|
|
10
|
+
| Built-in migration lifecycle maintenance | 5 | Keep `migrate run/dev/verify/revert/squash/archive` stable for simple projects and application startup, but avoid expanding it into a full PostgreSQL schema-as-code system. |
|
|
10
11
|
| Prisma migration assistant | 7 | Import Prisma Migrate SQL history and Prisma TypedSQL/raw SQL into `sqlx-js`; classify Prisma Client CRUD/nested-write sites as assisted/manual instead of promising a fully automatic ORM rewrite. |
|
|
11
12
|
| Self-join precision (unqualified ColumnRef) | 4 | `SELECT name FROM users u1 JOIN users u2 ON ...` with unqualified `name` can't be attributed to a specific alias. PG would reject ambiguous unqualified refs anyway, but explicit aliasing currently has no narrowing benefit in self-joins. |
|
|
12
|
-
| `INSERT INTO t VALUES (...)` without column list | 3 | Map params by `pg_attribute attnum` ordering. Rare in practice — most teams use explicit column lists. |
|
|
13
13
|
| Tagged-template literal API (`` sql`SELECT ${x}` ``) | 8 | Restoring sqlx's inline-SQL aesthetic requires either a TS compiler plugin (`ts-patch`) or a Bun preload-time AST rewriter. TS itself hardcodes the first tag argument as `TemplateStringsArray` and refuses to narrow to literal tuples. Significant effort, large UX win. |
|
|
14
|
-
| LSP server | 6 | Realtime diagnostics, hover with column types, autocomplete on schema names.
|
|
14
|
+
| LSP server | 6 | Realtime diagnostics, hover with column types, autocomplete on schema names. Versioned `prepare --json` diagnostics now provide the cheaper CI/editor integration foundation; a full server still needs separate VS Code / Neovim clients. |
|
|
15
15
|
| Schema-aware `jsonb` runtime validation | 5 | Optional opt-in: pass a Zod / Valibot / ArkType schema, validate rows on read. Currently we are compile-time-only by design. |
|
|
16
16
|
| MySQL backend | 5 | Some runtime clients support it, but MySQL has no `Describe Statement` equivalent. Would need a real SQL parser pass + `INFORMATION_SCHEMA` introspection. |
|
|
17
17
|
| SQLite backend | 4 | SQLite's column types are dynamic. Would require running `EXPLAIN` and a heuristic mapper, or schema-driven inference per-statement. |
|
|
18
18
|
| `EXPLAIN`-based performance hints | 6 | `prepare` could optionally run `EXPLAIN` per query and surface seq-scan / missing-index warnings. Independent feature; pairs well with CI. |
|
|
19
19
|
| Multi-statement queries | 2 | One SQL string with multiple statements separated by `;`. PG's `Parse` is single-statement; this would require client-side splitting. |
|
|
20
|
-
| Stored procedure / function typing | 3 | `CALL proc(...)` and `SELECT func(...)` with parameter and return-type binding from `pg_proc`. |
|
|
21
20
|
| Streaming / cursor / COPY typing | 3 | Surface Postgres.js cursor / COPY APIs with proper row types. |
|
|
22
21
|
|
|
23
22
|
## Long-term
|