@ultimat3/db 31.7.0 → 31.9.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/CLAUDE.md CHANGED
@@ -58,7 +58,7 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
58
58
  is the one counter. Full rule: `docs/history/db.md`.
59
59
  - **`client.ts` connects, holds the client and the ambient `db()`**, and opens no socket at import;
60
60
  `pool-profile.ts`, `connection-url.ts`, `bun-sql.ts`, `pool-reserve.ts`, `db-health.ts` (`checkDb`),
61
- `statement-funnel.ts` (`sendOn`/`runOn`), `pool-gate.ts`, `pool-sweep.ts`, `pool-retire.ts`,
61
+ `statement-funnel.ts` (`sendOn`/`runOn`), `copy-in.ts`, `pool-gate.ts`, `pool-sweep.ts`, `pool-retire.ts`,
62
62
  `pool-listeners.ts` and `pool-timer.ts` hold the rest.
63
63
  - **`statement-cancel.ts` cancels a POOLED `select` in flight when the ambient `ctx.signal` aborts** (`57014` on the server; `X_ABORTED`, or the coded reason itself). Never a write, never a pin, never a statement sent after the abort. README.
64
64
  - **`pool-gate.ts` is the one count of `max`** (`takeSlot`/`freeSlot`), per pool; a wait past `acquireTimeoutMs` is `X_DB_POOL_EXHAUSTED`. Full rule: `docs/history/db.md`.
@@ -77,25 +77,21 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
77
77
 
78
78
  ## Observation
79
79
 
80
- - **No observer slot** (v31): every statement is a `db.statement` event on core's bus
81
- (`instrument()`), emitted by `traceStatement` (`statement-span.ts`) — the ONE shell both funnels,
82
- `runOn` (`statement-funnel.ts`) and `statement()` (`pglite.ts`), call. Guarded by
83
- `subscribed('db.statement')`; emitted on success and failure, outside the statement's own `try`;
84
- a subscriber's throw is contained by the bus, never the caller's. A subscriber must not issue SQL.
85
- `bun run scripts/instrument-slots.ts` (`X_INSTRUMENT_SLOT_FORBIDDEN`) refuses a `set*Observer`.
86
- Each funnel reads core's `callerStack()` at its ENTRY (before the pool/turn-queue `await`) and
87
- hands it to `traceStatement` as `DbStatementEvent.callerStack` — `undefined`, nothing built,
88
- unless `captureStatementStacks()` is held (the `statements` fixture; never production).
80
+ - **No observer slot** (v31): every statement is a `db.statement` event on core's bus, emitted by
81
+ `traceStatement` (`statement-span.ts`), the ONE shell both funnels (`statement-funnel.ts`,
82
+ `pglite.ts`) call; guarded by `subscribed('db.statement')`, on success and failure, a
83
+ subscriber's throw contained by the bus. A subscriber issues no SQL. A `set*Observer` is
84
+ `X_INSTRUMENT_SLOT_FORBIDDEN`. `callerStack` is read at funnel ENTRY, built only under
85
+ `captureStatementStacks()` (the `statements` fixture).
89
86
  - **`attribution.ts`**: `withStatementAttribution(entity, op, fn)` — guard first (two strings, no
90
87
  allocation; the guard is `subscribed('db.statement')`), a scope not a parameter, innermost pair wins; the funnels stamp it on both settle paths.
91
88
  `@ultimat3/entity`'s `postgresRepo` is the one producer.
92
89
  - **`statement-shape.ts`**: `statementFingerprint(event)` (`entity.op` when attributed, else collapsed
93
90
  text) and `statementKind(text)` off `statementVerb(text)`. Read by `x dev`'s ledger and
94
91
  `@ultimat3/testing`'s `statements` fixture. It counts nothing.
95
- - **`statement-span.ts`**: `withStatementSpan` wraps the send alone — `db.<verb>`, OTel kind
96
- `client`, attributes from core's `SEMCONV` only (`db.system.name`, `db.query.text`,
97
- `db.operation.name`; never the old `db.statement`). **Opened for every statement**, production
98
- included, subscriber or not.
92
+ - **`statement-span.ts`**: `withStatementSpan` wraps the send alone — `db.<verb>`, kind `client`,
93
+ core's `SEMCONV` attributes only. **Opened for every statement**, subscriber or not.
94
+ - **`slow-statement-log.ts`** — `db.statement` subscriber; the runtime installs it.
99
95
  - **`expected-loop.ts` is the ONLY suppression**: `expectedQueryLoop(reason, fn)`, innermost reason,
100
96
  blank is `X_INVARIANT`; the funnel stamps `expected`; it suppresses a verdict, never a statement.
101
97
  The framework's own loops declare themselves (`migrate()`, `rollback()`, admin's `search.ts`).
@@ -103,8 +99,8 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
103
99
  - **`failure-store-pg.ts` writes `x_failures` through `outsideTransaction`** — the 5xx rolled the
104
100
  request's transaction back. Table applied by the boot (`FRAMEWORK_SCHEMA`) whether capture is on
105
101
  or not; bundles only (counts are `x_error_groups`'). `failurePurgeTarget` has no default window.
106
- - `@ultimat3/jobs` never imports this package; its statements reach the bus through
107
- `dbExecutor` (`db-executor.ts`, the ONE `PgExecutor` builder; the CLI binds it), unattributed.
102
+ - `@ultimat3/jobs` never imports this package; its statements reach the bus via `dbExecutor`
103
+ (`db-executor.ts`, the ONE `PgExecutor` builder), unattributed.
108
104
 
109
105
  ## Migrations
110
106
 
@@ -121,18 +117,19 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
121
117
  on it.** `lock: false` reserves nothing and takes no lock; no shipped path passes it
122
118
  (`migrate-pin.test.ts`). `migrate.live.test.ts` pins concurrent and failed-midway runs.
123
119
  - **One send is one statement**: `applyScript` sends `statementsOf(script)` one at a time. Full rule: `docs/history/db.md`.
124
- - **`destructive.ts` decides WHAT is destructive**: only `up`, a closed list of four (`drop table`,
125
- `drop column`, `truncate`, `alter column … type`), decided on blanked text and reported on the
126
- original; a marker is a top-level line comment (`marker-line.ts`). `X_MIGRATION_DESTRUCTIVE` (ship) and `X_MIGRATION_IRREVERSIBLE` (generate) are
127
- two questions.
128
- - **The ledger audit asks one question** — `auditLedger`'s `foreign` filter is `!known.has(row.id)`;
129
- the app version lives in the cause.
120
+ - **`destructive.ts` decides WHAT is destructive**: `up` only, four forms (`drop table`, `drop
121
+ column`, `truncate`, `alter column … type`) on blanked text; a marker is a top-level line comment
122
+ (`marker-line.ts`). `X_MIGRATION_DESTRUCTIVE` (ship) ≠ `X_MIGRATION_IRREVERSIBLE` (generate).
123
+ - **`migration-lock-lint.ts`** — `X_MIGRATION_LOCK_HEAVY`: `set not null` with no prior validate,
124
+ non-concurrent `create index` on an existing table; `-- lock-heavy: true` admits; ids > `LOCK_HEAVY_SINCE`.
125
+ - **The ledger audit asks one question**: `auditLedger`'s `foreign` is `!known.has(row.id)`.
130
126
  - **`refuseDependentViews(tx, script)`** (`dependent-view.ts`) runs before each migration's first statement. Full rule: `docs/history/db.md`.
131
127
 
132
128
  ## Generation (`x db gen`)
133
129
 
134
130
  - **`generate.ts` reads an index, never re-derives one** — `IndexDescriptionLike` carries columns,
135
- unique, `where`, `order`, `using`; an index naming no column is `X_INVARIANT`.
131
+ unique, `where`, `order`, `using`, and (`index-key-ddl.ts`) `expression`, `orders`, `include`,
132
+ `operatorClass`; each absent hashes as before. No column is `X_INVARIANT`.
136
133
  - **An index's ACCESS METHOD is carried end to end**. Full rule: `docs/history/db.md`.
137
134
  - **`index-plan.ts` walks both directions**; a removal and a `concurrently: true` build on a live table go to the non-transactional step (`concurrent-plan.ts`). Full rule: `docs/history/db.md`.
138
135
  - **An entity's INVARIANTS reach the DDL** (`invariant-ddl.ts`): `check` a named constraint, `unique` a unique index, `assert` nothing. Full rule: `docs/history/db.md`.
@@ -189,22 +186,26 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
189
186
  expression) vs `TableDescription.checkNames` (catalog: `conname` for `contype = 'c'`, always written
190
187
  by `introspectSchema()`, `[]` included). Only the declared side is judged; never a `changed-check`.
191
188
  `drift-check.live.test.ts`.
192
- - `compareTable` judges declared indexes (`missing-index`, `changed-index` over method, column list,
193
- uniqueness, predicate presence and direction; `asc` normalises to `null`); never the predicate text.
189
+ - `compareTable` judges declared indexes (`missing-index`, `changed-index` over method, key parts
190
+ — `drift-index-keys.ts`: expression presence, per-key directions, INCLUDE, operator class —
191
+ column list, uniqueness, predicate presence, direction; `asc` is `null`); never expression or
192
+ predicate text. `introspect-index.ts` reads them, each part only when present.
194
193
  - `compareForeignKeys` matches on where a key points (`foreignKeyTarget`, the one copy) and compares
195
194
  `onDelete` through `onDeleteRule` (`changed-foreign-key`; its fix, `changed-column`'s and
196
195
  `missing-check`'s are one `psql -c` too — `repair()`, schema-scoped off `public`).
197
- - `introspectSchema()` reads index columns in key order (`indkey`) and a foreign key's two column lists
198
- together (`unnest(a, b) with ordinality`), pinned by `introspect-embedded.test.ts`.
199
- - **`appTables()`** excludes all of `x_` for drift; `introspectSchema()` alone excludes
200
- `x_migrations` by default. **`app-relation.ts`**: `nonAppRelations(client, schema)` — extension
201
- ownership (`pg_depend`, `deptype = 'e'`), views, materialised views, foreign tables, partitions —
202
- merged into `excluded` unconditionally.
196
+ - `introspectSchema()` reads index keys in `indkey` order and a key's two column lists together
197
+ (`unnest(a, b) with ordinality`); `introspect-embedded.test.ts`.
198
+ - **`table-storage.ts`**: a framework table's `fillfactor`/`unlogged`, one value — `tableDdl`
199
+ renders the create plus idempotent alters (re-applied every framework apply), drift reads `pg_class`.
200
+ - **`appTables()`** excludes all of `x_` for drift; `introspectSchema()` only `x_migrations`.
201
+ `nonAppRelations` (`app-relation.ts`): extension-owned, views, matviews, foreign tables,
202
+ partitions — always excluded.
203
203
  - **A partitioned parent is a table, a partition is not**; a concurrent build on one is
204
204
  `X_MIGRATION_CONCURRENT_PARTITIONED`. `docs/history/db.md` (2026-11-06).
205
205
  - **`dbDrift()` lives in `drift-errors.ts`** (it needs `shellInertIdentifier`), the only one.
206
206
  `errors.ts` registers `DB_ERROR_TITLES` unconditionally.
207
- - **`not-valid-constraint`** (`compareValidated`): `notValidNames` is catalog-only (`convalidated`, absent when none), judged on the declared side, foreign keys by where they point; the fix is the validate statement (`repair`).
207
+ - **`not-valid-constraint`** (`compareValidated`): `notValidNames` is catalog-only (`convalidated`),
208
+ declared side judged, keys by target; fix = the validate statement.
208
209
  - `drift-findings.ts` holds the `DriftDifference` constructors and `DriftKind`; `drift-missing.ts` the
209
210
  missing/rebuilt ones (table, column, index, foreign key); `drift.ts` keeps the comparisons. **No
210
211
  drift fix is `x db migrate`**: the ledger holds the migration, so it applies nothing — every fix is a
package/README.md CHANGED
@@ -30,6 +30,7 @@ await withTransaction(async (tx) => {
30
30
  | `sql` / `raw` / `identifier` / `literal` / `join` | fragment builders |
31
31
  | `keyset({ scope, keys, after, limit })` | keyset paging for a raw join: `{ select, where, orderBy, limit, page(rows) }`, [below](#paging-a-raw-join-keyset) |
32
32
  | `shellInertIdentifier()` | `As of 2026-08-26`: a quoted identifier that is also inert wherever a human PASTES it — or `null`. The one screen a catalog name goes through before it reaches a `fix:`. `identifier()` answers about SQL and **accepts** a backtick and a `$`, which are exactly what a shell substitutes inside double quotes, so a column called `$(id)` inside `x db gen "add $(id)"` runs `id` on paste |
33
+ | `client.copyIn(target, rows)` / `canCopyIn(client)` | `As of 2026-11-11`: `COPY … FROM STDIN` on `postgresClient()`, its pins, a `DbTx` on one and the replica router (to the primary) → [Bulk load: `copyIn`](#bulk-load-copyin) |
33
34
  | `db()` / `baseClient()` / `setDbClient()` | the ambient client; `db()` returns the open tx if any |
34
35
  | `dbClientInstalled()` | `As of 30.0`: whether `setDbClient` installed a client that is still in place. Never builds the lazy default. `@ultimat3/entity`'s `testDriver()` asks it on every repository call |
35
36
  | `dbExecutor(client = db)` | the client as `@ultimat3/core`'s `PgExecutor` (`query(text, values)`) — what a jobs, idempotency, notify or MCP confirmation store takes. The client is resolved per statement: the default reaches the boot's client even when declared at module scope, and joins an open `withTransaction`; `() => pool` pins one pool whatever transaction is open |
@@ -44,6 +45,10 @@ await withTransaction(async (tx) => {
44
45
  | `poolerFromEnv()` / `POOLER_ENV` / `PoolerMode` / `POOLER_WAIT_MS` / `statementBound()` / `lostStatementBound()` / `StatementBound` / `poolerSessionRequired()` | `As of 2026-11-03`: a connection pooler in the path (`pooler.ts`), and the two bounds as the session reads them. [Pool sizing by role](#pool-sizing-by-role) |
45
46
  | `replicatedClient()` / `ReplicaStats` / `REPLICA_URL_ENV` | `As of 2026-08-24`: one `DbClient` over a primary and a standby. `baseClient()` builds one when `DATABASE_REPLICA_URL` is set and the single-pool client when it is not |
46
47
  | `INDEX_METHODS` / `IndexMethod` / `indexMethodOf()` / `indexMethodSql()` / `declaredMethod()` | `As of 2026-08-24`: an index's access method — `btree` or `gin`, closed. Absent is `btree`, the live side is read open (whatever `pg_am` said), and the DDL literal is re-derived from the set rather than spliced from the input |
48
+ | `IndexDescriptionLike.expression` / `.orders` / `.include` / `.operatorClass` · `INDEX_OPERATOR_CLASSES` / `requiredExtension()` | `As of 2026-11-12`: the index parts past a plain column list — one expression key (`unique (lower(email))`), a direction per key, INCLUDE payload columns (btree), `gin_trgm_ops` (gin; `requiredExtension()` answers `pg_trgm`). Each optional, absent hashes and renders as before; drift compares each, an expression by presence only |
49
+ | `tableStorage(table, { fillfactor?, unlogged? })` / `tableDdl()` / `storageAlters()` / `tableStorageDrift()` / `readTableStorageDrift()` | `As of 2026-11-12`: a **framework-owned** table's storage parameters as one value. `tableDdl(storage, columns)` renders `create [unlogged] table if not exists … with (fillfactor = n)` plus the idempotent `alter`s that bring an existing table to it at framework-schema apply; drift reads `relpersistence`/`reloptions`, each difference with its `alter` as `fix`. A bad name or fillfactor is `X_SQL_UNSAFE` at import |
50
+ | `slowStatementLog({ thresholdMs })` | one `warn` `db.statement.slow` line per slow statement shape per 10 s, with request/trace ids and no bind values; returns the unsubscribe |
51
+ | `lockHeavyStatements()` / `migrationLockHeavy()` / `LOCK_HEAVY_MARKER` / `LOCK_HEAVY_SINCE` | `X_MIGRATION_LOCK_HEAVY`: `set not null` with no prior validate, non-concurrent `create index` on an existing table; `-- lock-heavy: true` to admit; judges ids > `LOCK_HEAVY_SINCE` |
47
52
  | `isPlainRead()` | `As of 2026-08-24`: whether a statement may leave the primary. An allow-list — everything it cannot vouch for is the primary's |
48
53
  | `checkDrift()` / `diffSchema()` / `assertNoSchemaDrift()` | drift, with a `--json` report. `checkDrift()` is the **post-migrate verification** — the live database against the ledger: columns, declared indexes (access method `As of 2026-08-24`, columns, uniqueness, direction, and whether a predicate is there at all — never its text), declared CHECK constraints by NAME (`missing-check`, `As of 2026-08-25` — never a predicate, which the catalog answers rewritten) and declared foreign keys, matched on where the key points and not on its constraint name, with the `on delete` rule compared through one normalisation `As of 2026-08-19` |
49
54
  | `declaredSchema()` / `expectedSchema()` | `As of 2026-08`: the schema the migrations write down, or `undefined` when the newest one carries no snapshot — never an older snapshot standing in for it |
@@ -535,6 +540,24 @@ The last row is the one divergence a second connection would remove and PGlite c
535
540
  issued *inside* an open transaction's scope runs immediately rather than waiting for a turn that
536
541
  scope is already holding, because waiting would be a deadlock with no error to explain it.
537
542
 
543
+ ## Bulk load: `copyIn`
544
+
545
+ `As of 2026-11-11`. `postgresClient().copyIn(target, rows)`, `target` a parameterless
546
+ `copy <table> (<columns>) from stdin` built with `identifier()`/`join()`, streams `rows` (each the
547
+ column list's values, in order) through `Bun.SQL`'s `writable()` in the text format and resolves with the server's count. One statement: all or nothing. `copy-in.ts`;
548
+ `copy-in.live.test.ts`. 100k rows × 4 columns: ~0.5 s against ~1.9 s for the same rows as
549
+ chunked `insert`s (loopback, Postgres 17, a loaded box).
550
+
551
+ | Case | |
552
+ |---|---|
553
+ | a cell | encoded as the bound parameter would be: `\N` for null, ISO instant for a `Date`, bytea hex, an array literal; a plain object is `X_SQL_UNSAFE` and the stream aborts — nothing stored |
554
+ | the target | exactly `copy <ident>[.<ident>] (<ident>, …) from stdin`, no `;`, no value — anything else (`to program`, a file path, a second statement) is `X_SQL_UNSAFE` before any send |
555
+ | the caller's `rows` iterator throws | `X_INVARIANT` naming the throw; the stream aborts, nothing stored, a pin stays usable (never `X_DB_UNAVAILABLE`) |
556
+ | a server refusal (`23505`, `22P02`, …) | typed by SQLSTATE like any statement; the connection stays usable |
557
+ | a pin (`reserve()`), a `DbTx` | the copy is that transaction's, under the pin's deadline, rolled back with it |
558
+ | the replica router | forwarded to the primary, and the `withReplicaReads` scope is marked written |
559
+ | `canCopyIn(client)` | `false` for PGlite and a fake, and whenever a row-security settings provider is INSTALLED, tenant in scope or not: Postgres refuses `COPY FROM` under RLS (`0A000`). Callers fall back to `insert` |
560
+
538
561
  ## A pooled read stops when its caller does
539
562
 
540
563
  `As of 2026-11-09`. A `select` sent on the pool, in flight when the ambient `ctx.signal` aborts, is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/db",
3
- "version": "31.7.0",
3
+ "version": "31.9.0",
4
4
  "description": "Postgres access, transactions, migrations and drift detection",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -45,7 +45,7 @@
45
45
  "test": "bun test"
46
46
  },
47
47
  "dependencies": {
48
- "@ultimat3/core": "31.7.0"
48
+ "@ultimat3/core": "31.9.0"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "@electric-sql/pglite": ">=0.5.0"
@@ -37,12 +37,14 @@ const hexOf = (bytes: Uint8Array): string =>
37
37
  * "cannot reach the database". `position` names the parameter when the caller knows it.
38
38
  */
39
39
  export function instantText(value: Date, position?: number): string {
40
+ // Inside the `if`, never as `assert`'s condition: the refusal's text is a template, and as an
41
+ // argument it was built for every valid Date too — every bound timestamp of every statement.
42
+ if (!Number.isNaN(value.getTime())) return value.toISOString();
40
43
  assert(
41
- !Number.isNaN(value.getTime()),
44
+ false,
42
45
  `${position === undefined ? 'an array element' : `parameter $${position}`} is an Invalid Date, which names no instant Postgres could store`,
43
46
  'new Date(input) answers Invalid Date for text it cannot parse — parse it with t.date first, or bind null: Number.isNaN(value.getTime()) ? null : value',
44
47
  );
45
- return value.toISOString();
46
48
  }
47
49
 
48
50
  function element(value: unknown): string {
package/src/client.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  releaseReserved,
14
14
  } from './bun-sql';
15
15
  import { connectionUrl } from './connection-url';
16
+ import { type CopyInClient, copyOn } from './copy-in';
16
17
  // Deliberate cycle, the same shape as `client.ts ⇄ transaction.ts`: nothing here is referenced at
17
18
  // module evaluation, and both sides are `function` declarations, so hoisting covers the TDZ.
18
19
  import { defaultClient } from './default-client';
@@ -79,7 +80,9 @@ export interface PostgresClientOptions {
79
80
  readonly schedule?: Scheduler | undefined;
80
81
  }
81
82
 
82
- export interface PostgresClient extends ReservableClient, ListeningClient {
83
+ export interface PostgresClient extends ReservableClient, ListeningClient, CopyInClient {
84
+ /** A pin copies too: a `COPY` inside a transaction is that transaction's (`copy-in.ts`). */
85
+ reserve(): Promise<DbConnection & CopyInClient>;
83
86
  readonly profile: PoolProfile;
84
87
  readonly pooler: PoolerMode | undefined;
85
88
  ping(): Promise<void>;
@@ -153,7 +156,7 @@ export function postgresClient(options: PostgresClientOptions = {}): PostgresCli
153
156
  }
154
157
 
155
158
  async function run(fragment: SqlFragment): Promise<unknown> {
156
- const slot = takeSlot(connect, profile.acquireTimeoutMs);
159
+ const slot = takeSlot(connect, profile.acquireTimeoutMs, fragment.text);
157
160
  const live = slot instanceof Promise ? await slot : slot;
158
161
  // Pooled only: a pin's statement belongs to a transaction, and cancelling it is not ours to do.
159
162
  const watch = watchAbort(fragment.text);
@@ -168,9 +171,26 @@ export function postgresClient(options: PostgresClientOptions = {}): PostgresCli
168
171
  }
169
172
  }
170
173
 
174
+ /** A copy on the pool: one gate slot and the sweep's deadline, as `run` gives a statement. */
175
+ async function copyPooled(
176
+ target: SqlFragment,
177
+ rows: Iterable<readonly unknown[]>,
178
+ ): Promise<number> {
179
+ const slot = takeSlot(connect, profile.acquireTimeoutMs, target.text);
180
+ const live = slot instanceof Promise ? await slot : slot;
181
+ // No `watchAbort`: a copy is a write, and a write is never cancelled by a hang-up.
182
+ try {
183
+ const sending = copyOn(live.pool, target, rows);
184
+ return await (sweep === undefined ? sending : sweep.track(live, target.text, sending));
185
+ } finally {
186
+ freeSlot(live);
187
+ }
188
+ }
189
+
171
190
  const client: PostgresClient = {
172
191
  profile,
173
192
  pooler,
193
+ copyIn: copyPooled,
174
194
  async query<T>(fragment: SqlFragment): Promise<readonly T[]> {
175
195
  return rowsOf<T>(await run(fragment));
176
196
  },
@@ -181,7 +201,7 @@ export function postgresClient(options: PostgresClientOptions = {}): PostgresCli
181
201
  async execute(fragment: SqlFragment): Promise<number> {
182
202
  return affectedBy(await run(fragment));
183
203
  },
184
- async reserve(): Promise<DbConnection> {
204
+ async reserve(): Promise<DbConnection & CopyInClient> {
185
205
  // A real pin, not a seam: `Bun.SQL` refuses a bare BEGIN on a pooled handle
186
206
  // (`ERR_POSTGRES_UNSAFE_TRANSACTION`), and a BEGIN that landed on a different connection
187
207
  // than the statement after it would not be a transaction at all — which is exactly what
@@ -189,7 +209,7 @@ export function postgresClient(options: PostgresClientOptions = {}): PostgresCli
189
209
  // One gate slot for the life of the pin, so one number counts statements and pins alike.
190
210
  const budget = profile.acquireTimeoutMs;
191
211
  const started = performance.now();
192
- const live = await takeSlot(connect, budget);
212
+ const live = await takeSlot(connect, budget, undefined);
193
213
  let reserved: BunSqlReserved;
194
214
  try {
195
215
  // `reserveWithin` keeps its own timer for `Bun.SQL`'s queue, on what the gate left of ONE
@@ -219,9 +239,12 @@ export function postgresClient(options: PostgresClientOptions = {}): PostgresCli
219
239
  held ? onPinned(fragment) : run(fragment);
220
240
  // A miss retired the pool; this connection is never written to again, so the transaction's
221
241
  // ROLLBACK is refused here rather than waiting out a second bound on the same dead path.
222
- const onPinned = async (fragment: SqlFragment): Promise<unknown> => {
242
+ const onPinned = async (
243
+ fragment: SqlFragment,
244
+ send: () => Promise<unknown> = () => runOn(reserved, fragment),
245
+ ): Promise<unknown> => {
223
246
  if (pin.dead) throw dbUnavailable(PIN_RETIRED);
224
- const sending = runOn(reserved, fragment);
247
+ const sending = send();
225
248
  const deadlineMs = pinDeadlineMs(pin, beyondBoundMs);
226
249
  try {
227
250
  const answer = await (sweep === undefined
@@ -248,6 +271,11 @@ export function postgresClient(options: PostgresClientOptions = {}): PostgresCli
248
271
  query: async <T>(fragment: SqlFragment) => rowsOf<T>(await on(fragment)),
249
272
  one: async <T>(fragment: SqlFragment) => rowsOf<T>(await on(fragment))[0] ?? null,
250
273
  execute: async (fragment: SqlFragment) => affectedBy(await on(fragment)),
274
+ // The pin's deadline and dead-pin refusal, as every pinned statement; released, the pool's.
275
+ copyIn: async (target: SqlFragment, rows: Iterable<readonly unknown[]>) =>
276
+ held
277
+ ? ((await onPinned(target, () => copyOn(reserved, target, rows))) as number)
278
+ : copyPooled(target, rows),
251
279
  release,
252
280
  [Symbol.dispose]: release,
253
281
  };
package/src/copy-in.ts ADDED
@@ -0,0 +1,219 @@
1
+ // Single responsibility: `COPY … FROM STDIN` on a `Bun.SQL` handle — the text-format line each row
2
+ // becomes, the stream that carries them, and the one test for whether a client can take a copy.
3
+ //
4
+ // Its own funnel beside `statement-funnel.ts` because a copy cannot go through `unsafe()`: Bun
5
+ // refuses an awaited COPY (`ERR_POSTGRES_COPY_NOT_SUPPORTED`), and `writable()` must be called
6
+ // before anything awaits the query.
7
+
8
+ import {
9
+ assert,
10
+ callerStack,
11
+ describeValue,
12
+ isUltimateError,
13
+ renderThrowable,
14
+ } from '@ultimat3/core';
15
+ import { instantText, pgArrayLiteral } from './array-parameter';
16
+ import type { DbClient } from './client';
17
+ import { DbError, driverError } from './errors';
18
+ import type { SqlFragment } from './sql';
19
+ import { statementExcerpt } from './statement-excerpt';
20
+ import { traceStatement } from './statement-span';
21
+ import { transactionSettingsInstalled } from './transaction-settings';
22
+
23
+ /** A client that loads rows through `COPY … FROM STDIN`: `postgresClient()`, its pins and a `DbTx` on one. */
24
+ export interface CopyInClient {
25
+ /**
26
+ * `target` is `copy <table> (<columns>) from stdin` with nothing bound; each row is that column
27
+ * list's values, in order, as a statement would bind them. One statement, so all or nothing.
28
+ * Resolves with the rows the server stored.
29
+ */
30
+ copyIn(target: SqlFragment, rows: Iterable<readonly unknown[]>): Promise<number>;
31
+ }
32
+
33
+ /**
34
+ * Whether `copyIn` is the right send, not merely present. Present on `postgresClient()`, its pins,
35
+ * a `DbTx` opened on one and the replica router (which sends it to the primary); absent on PGlite
36
+ * and a fake, which fall back to `insert` statements. And false whenever a row-security provider
37
+ * is INSTALLED, whatever it answers now: Postgres refuses `COPY FROM` on a table under row-level
38
+ * security (`0A000 COPY FROM not supported with row-level security`) even with no tenant in scope,
39
+ * where the `insert` the caller falls back to is judged by the policy like any other write.
40
+ */
41
+ export function canCopyIn(client: DbClient): client is DbClient & CopyInClient {
42
+ return (
43
+ typeof (client as Partial<CopyInClient>).copyIn === 'function' &&
44
+ !transactionSettingsInstalled()
45
+ );
46
+ }
47
+
48
+ /**
49
+ * The four characters the text format reads as structure, and how each is spelled inside a cell.
50
+ * Null-prototype: the key is a cell's own character, and no character may answer a prototype member.
51
+ */
52
+ const ESCAPES: Readonly<Record<string, string>> = Object.assign(Object.create(null), {
53
+ '\\': '\\\\',
54
+ '\t': '\\t',
55
+ '\n': '\\n',
56
+ '\r': '\\r',
57
+ });
58
+ // Two regexes, not one: `test()` on a global regex advances `lastIndex`, and the next cell would be
59
+ // scanned from wherever the last one stopped.
60
+ const HAS_STRUCTURAL = /[\\\t\n\r]/;
61
+ const STRUCTURAL = /[\\\t\n\r]/g;
62
+
63
+ const escaped = (text: string): string =>
64
+ HAS_STRUCTURAL.test(text) ? text.replace(STRUCTURAL, (char) => ESCAPES[char] ?? char) : text;
65
+
66
+ const hexOf = (bytes: Uint8Array): string =>
67
+ Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
68
+
69
+ const cellUnsendable = (value: unknown): DbError =>
70
+ new DbError({
71
+ code: 'X_SQL_UNSAFE',
72
+ cause: `a COPY cell is ${describeValue(value)}, which has no text-format spelling`,
73
+ fix: 'JSON.stringify(value) # a jsonb cell, as its text; a scalar, a Date, a Uint8Array or an array binds as itself',
74
+ meta: { received: describeValue(value) },
75
+ });
76
+
77
+ /**
78
+ * One cell as its column's input function reads it — the same value `encodeBoundParameters` would
79
+ * send as a parameter, so a row copied and the row inserted are one row. `\N` is NULL; the word
80
+ * `NULL` is text. Bytes double their backslash, because the text format reads `\x` as an escape.
81
+ */
82
+ const cellText = (value: unknown): string => {
83
+ if (value === null || value === undefined) return '\\N';
84
+ if (typeof value === 'string') return escaped(value);
85
+ if (typeof value === 'number' || typeof value === 'bigint') return String(value);
86
+ if (typeof value === 'boolean') return value ? 't' : 'f';
87
+ if (value instanceof Date) return instantText(value);
88
+ if (value instanceof Uint8Array) return `\\\\x${hexOf(value)}`;
89
+ if (Array.isArray(value)) return escaped(pgArrayLiteral(value));
90
+ throw cellUnsendable(value);
91
+ };
92
+
93
+ /** One row of `COPY … FROM STDIN` in the text format: cells by tab, the row by newline. */
94
+ export function copyLine(cells: readonly unknown[]): string {
95
+ let line = '';
96
+ for (const [index, cell] of cells.entries())
97
+ line += index === 0 ? cellText(cell) : `\t${cellText(cell)}`;
98
+ return `${line}\n`;
99
+ }
100
+
101
+ /** One identifier as `identifier()` writes it — quoted, `""` for a quote — or a bare name. */
102
+ const IDENT = String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)`;
103
+ /**
104
+ * The whole statement, anchored: `copy <ident>[.<ident>] (<ident>, …) from stdin` and nothing
105
+ * else. A loose `from stdin` search passed `copy (select 1) to program 'id' -- from stdin`, and a
106
+ * file path with `from stdin` inside a block comment after it. A `;` is refused anywhere, a quoted
107
+ * name included: no entity's table or column holds one, and a second statement always does.
108
+ */
109
+ const COPY_TARGET = new RegExp(
110
+ String.raw`^copy\s+${IDENT}(?:\.${IDENT})?\s*\(\s*${IDENT}(?:\s*,\s*${IDENT})*\s*\)\s+from\s+stdin$`,
111
+ 'i',
112
+ );
113
+
114
+ const targetRefused = (text: string, why: string): DbError =>
115
+ new DbError({
116
+ code: 'X_SQL_UNSAFE',
117
+ cause: `copyIn() takes a parameterless "copy <table> (<columns>) from stdin" — ${why}: ${statementExcerpt(text)}`,
118
+ fix: 'copyIn(sql`copy <identifier(table)> (<join(columns.map(identifier))>) from stdin`, rows) # values go in rows, never the statement',
119
+ });
120
+
121
+ /** Before any send: a COPY binds nothing, so a value in the fragment could only be spliced. */
122
+ function refuseTarget(target: SqlFragment): void {
123
+ if (target.values.length > 0) throw targetRefused(target.text, 'it binds a value');
124
+ if (target.text.includes(';') || !COPY_TARGET.test(target.text.trim())) {
125
+ throw targetRefused(target.text, 'it is not one COPY <table> (<columns>) FROM STDIN');
126
+ }
127
+ }
128
+
129
+ /**
130
+ * The caller's row source threw. Not the database's failure — `driverError` would call it
131
+ * `X_DB_UNAVAILABLE`, and on a pin that marks the connection dead — so it is coded as the caller's.
132
+ */
133
+ const rowsFailed = (target: SqlFragment, error: unknown): DbError =>
134
+ new DbError({
135
+ code: 'X_INVARIANT',
136
+ cause: `copyIn()'s rows threw before the stream ended, so nothing was stored: ${renderThrowable(error)}`,
137
+ fix: `copyIn(${statementExcerpt(target.text)}, rows) # the row source threw: fix the throw above, which is its own, then call again`,
138
+ sourceError: error,
139
+ });
140
+
141
+ /** The next row, a throw from the caller's iterator coded as theirs. */
142
+ const nextRow = (
143
+ target: SqlFragment,
144
+ rows: Iterator<readonly unknown[]>,
145
+ ): IteratorResult<readonly unknown[]> => {
146
+ try {
147
+ return rows.next();
148
+ } catch (error) {
149
+ throw rowsFailed(target, error);
150
+ }
151
+ };
152
+
153
+ /** Bytes per write: large enough that a 100k-row copy is a few hundred writes, not 100k. */
154
+ const CHUNK_CHARS = 1 << 16;
155
+
156
+ /** `Bun.SQL`'s query as far as a copy reads it. */
157
+ interface CopyQuery extends PromiseLike<unknown> {
158
+ readonly writable?: () => WritableStream<string>;
159
+ }
160
+
161
+ /** What a copy is sent on: the pool or one pinned connection. */
162
+ export interface CopySend {
163
+ unsafe(text: string): unknown;
164
+ }
165
+
166
+ const countOf = (result: unknown): number => {
167
+ const count = (result as { readonly count?: unknown } | null)?.count;
168
+ return typeof count === 'number' ? count : 0;
169
+ };
170
+
171
+ async function stream(driver: CopySend, target: SqlFragment, rows: Iterable<readonly unknown[]>) {
172
+ const query = driver.unsafe(target.text) as CopyQuery;
173
+ assert(
174
+ typeof query.writable === 'function',
175
+ 'this database driver answered a COPY with no writable() stream',
176
+ 'send the rows with insertAll(rows, { returning: false }) — canCopyIn(client) answers false for it',
177
+ );
178
+ // `writable()` FIRST: attaching a handler starts the query, after which Bun refuses the stream.
179
+ const writer = query.writable().getWriter();
180
+ const answered = Promise.resolve(query);
181
+ answered.catch(() => undefined);
182
+ try {
183
+ let chunk = '';
184
+ const source = rows[Symbol.iterator]();
185
+ for (let next = nextRow(target, source); next.done !== true; next = nextRow(target, source)) {
186
+ chunk += copyLine(next.value);
187
+ if (chunk.length < CHUNK_CHARS) continue;
188
+ await writer.write(chunk);
189
+ chunk = '';
190
+ }
191
+ if (chunk.length > 0) await writer.write(chunk);
192
+ await writer.close();
193
+ } catch (error) {
194
+ // Nothing of an aborted copy is stored, and the connection stays usable (Bun 1.4.4).
195
+ await writer.abort(error).catch(() => undefined);
196
+ // Our own refusal is already coded and names the cell; the server's is typed by its SQLSTATE.
197
+ throw isUltimateError(error) ? error : driverError(statementExcerpt(target.text), error);
198
+ }
199
+ try {
200
+ return countOf(await answered);
201
+ } catch (error) {
202
+ throw driverError(statementExcerpt(target.text), error);
203
+ }
204
+ }
205
+
206
+ /** The copy funnel: one span and one `db.statement` event, like every statement the pool sends. */
207
+ export async function copyOn(
208
+ driver: CopySend,
209
+ target: SqlFragment,
210
+ rows: Iterable<readonly unknown[]>,
211
+ ): Promise<number> {
212
+ refuseTarget(target);
213
+ return traceStatement(
214
+ target,
215
+ () => stream(driver, target, rows),
216
+ (count) => count,
217
+ callerStack(),
218
+ );
219
+ }
@@ -37,7 +37,10 @@ export type DriftKind =
37
37
  | 'unexpected-row-security'
38
38
  // Constructed in `object-drift.ts`: a trigger, function, view, type or sequence in the live
39
39
  // database that replaying the migrations does not create.
40
- | 'unexpected-object';
40
+ | 'unexpected-object'
41
+ // Constructed in `@ultimat3/cli`'s `db-object-drift.ts` from `tableStorageDrift`: a framework
42
+ // table whose persistence or fillfactor is not what its `tableStorage()` declares.
43
+ | 'changed-table-storage';
41
44
 
42
45
  export interface DriftDifference {
43
46
  readonly kind: DriftKind;
@@ -0,0 +1,54 @@
1
+ // Single responsibility: drift's reading of an index's key parts past a plain column list — an
2
+ // expression key, per-key directions, INCLUDE, the operator class. Answers what the live index
3
+ // "is" when it differs from the declaration, in `changedIndex`'s words, or `null` when they agree.
4
+ // Split from `drift.ts` (ceiling); `compareIndexes` asks it after the method, before the columns.
5
+
6
+ import type { IndexDescription } from './introspect';
7
+
8
+ type Index = IndexDescription;
9
+
10
+ /**
11
+ * The effective direction of every key, `asc` folded into `null` — `drift.ts`'s normalisation for
12
+ * `order`, because `createIndex` writes `asc` and Postgres stores it as not-descending. `orders`
13
+ * when present, else `order` repeated: a declared `['desc', 'desc']` and a catalog `order: 'desc'`
14
+ * are the same index.
15
+ */
16
+ const directions = (index: Index): readonly ('desc' | null)[] =>
17
+ (index.orders ?? index.columns.map(() => index.order)).map((d) => (d === 'desc' ? 'desc' : null));
18
+
19
+ /** Whether this comparison owns the direction question — the plain `order` check yields to it. */
20
+ export const ownsDirection = (live: Index, expected: Index): boolean =>
21
+ live.orders !== undefined || expected.orders !== undefined;
22
+
23
+ /** Whether this comparison owns the key-list question — an expression's text is the catalog's. */
24
+ export const ownsKeys = (expected: Index): boolean => expected.expression !== undefined;
25
+
26
+ /**
27
+ * An expression key's TEXT is never compared — the catalog answers its rewriting
28
+ * (`lower((email)::text)`), the predicate's reason in `drift.ts`. Its PRESENCE is: one key, marked
29
+ * by the parentheses `introspect-index.ts` puts on every expression key.
30
+ */
31
+ export function keyPartsChange(live: Index, expected: Index): string | null {
32
+ if (ownsKeys(expected)) {
33
+ const [only] = live.columns;
34
+ if (live.columns.length !== 1 || only === undefined || !only.startsWith('(')) {
35
+ return `covers (${live.columns.join(', ')}), not one expression`;
36
+ }
37
+ }
38
+ if (ownsDirection(live, expected)) {
39
+ const have = directions(live);
40
+ if (have.join(',') !== directions(expected).join(',')) {
41
+ return `orders its keys (${have.map((d) => d ?? 'asc').join(', ')})`;
42
+ }
43
+ }
44
+ const include = (index: Index): string => (index.include ?? []).join(', ');
45
+ if (include(live) !== include(expected)) {
46
+ return include(live) === '' ? 'includes no columns' : `includes (${include(live)})`;
47
+ }
48
+ if ((live.operatorClass ?? null) !== (expected.operatorClass ?? null)) {
49
+ return live.operatorClass === undefined
50
+ ? 'uses the default operator class'
51
+ : `uses ${live.operatorClass}`;
52
+ }
53
+ return null;
54
+ }
package/src/drift.ts CHANGED
@@ -16,6 +16,7 @@ import {
16
16
  unexpectedTable,
17
17
  unknownSchema,
18
18
  } from './drift-findings';
19
+ import { keyPartsChange, ownsDirection, ownsKeys } from './drift-index-keys';
19
20
  import {
20
21
  changedIndex,
21
22
  missingColumn,
@@ -101,7 +102,15 @@ function compareIndexes(live: TableDescription, expected: TableDescription): Dri
101
102
  );
102
103
  continue;
103
104
  }
104
- if (counterpart.columns.join(',') !== index.columns.join(',')) {
105
+ // The key parts past a plain column list (`drift-index-keys.ts`): an expression key, per-key
106
+ // directions, INCLUDE, the operator class. Asked before the column list, which an expression
107
+ // key's catalog spelling could never equal.
108
+ const keyChange = keyPartsChange(counterpart, index);
109
+ if (keyChange !== null) {
110
+ differences.push(changedIndex(live.schema, live.name, index, counterpart, keyChange));
111
+ continue;
112
+ }
113
+ if (!ownsKeys(index) && counterpart.columns.join(',') !== index.columns.join(',')) {
105
114
  differences.push(
106
115
  changedIndex(
107
116
  live.schema,
@@ -125,7 +134,10 @@ function compareIndexes(live: TableDescription, expected: TableDescription): Dri
125
134
  );
126
135
  continue;
127
136
  }
128
- if ((counterpart.order ?? 'asc') !== (index.order ?? 'asc')) {
137
+ if (
138
+ !ownsDirection(counterpart, index) &&
139
+ (counterpart.order ?? 'asc') !== (index.order ?? 'asc')
140
+ ) {
129
141
  differences.push(
130
142
  changedIndex(
131
143
  live.schema,