@ultimat3/db 31.8.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 +1 -1
- package/README.md +19 -0
- package/package.json +2 -2
- package/src/array-parameter.ts +4 -2
- package/src/client.ts +32 -4
- package/src/copy-in.ts +219 -0
- package/src/index.ts +2 -0
- package/src/replica-client.ts +15 -0
- package/src/statement-excerpt.ts +50 -5
- package/src/transaction-settings.ts +9 -0
- package/src/transaction.ts +11 -1
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`.
|
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 |
|
|
@@ -539,6 +540,24 @@ The last row is the one divergence a second connection would remove and PGlite c
|
|
|
539
540
|
issued *inside* an open transaction's scope runs immediately rather than waiting for a turn that
|
|
540
541
|
scope is already holding, because waiting would be a deadlock with no error to explain it.
|
|
541
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
|
+
|
|
542
561
|
## A pooled read stops when its caller does
|
|
543
562
|
|
|
544
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.
|
|
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.
|
|
48
|
+
"@ultimat3/core": "31.9.0"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
51
51
|
"@electric-sql/pglite": ">=0.5.0"
|
package/src/array-parameter.ts
CHANGED
|
@@ -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
|
-
|
|
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>;
|
|
@@ -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
|
|
@@ -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 (
|
|
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 =
|
|
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
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -40,6 +40,8 @@ export {
|
|
|
40
40
|
isPartitionedBuildRefusal,
|
|
41
41
|
NO_TRANSACTION_MARKER,
|
|
42
42
|
} from './concurrent-index';
|
|
43
|
+
export type { CopyInClient } from './copy-in';
|
|
44
|
+
export { canCopyIn } from './copy-in';
|
|
43
45
|
export { dbExecutor } from './db-executor';
|
|
44
46
|
export type { DbHealthReport } from './db-health';
|
|
45
47
|
export { checkDb } from './db-health';
|
package/src/replica-client.ts
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
systemClock,
|
|
14
14
|
} from '@ultimat3/core';
|
|
15
15
|
import { type DbClient, type DbConnection, isReservable, type ReservableClient } from './client';
|
|
16
|
+
import type { CopyInClient } from './copy-in';
|
|
16
17
|
import { POSITION_CACHE_MS, primaryPosition, replayReader } from './replica-position';
|
|
17
18
|
import { isPlainRead } from './replica-route';
|
|
18
19
|
import { markScopeWrote, replicaScope } from './replica-scope';
|
|
@@ -197,6 +198,20 @@ export function replicatedClient(
|
|
|
197
198
|
execute: (fragment: SqlFragment) => send(fragment, (client) => client.execute(fragment)),
|
|
198
199
|
};
|
|
199
200
|
|
|
201
|
+
// A COPY is a write: the primary's, always, and it marks the scope written as any write does so
|
|
202
|
+
// the reads after it are the primary's too. Present only when the primary copies.
|
|
203
|
+
const copying = primary as DbClient & Partial<CopyInClient>;
|
|
204
|
+
if (typeof copying.copyIn === 'function') {
|
|
205
|
+
const copyIn = copying.copyIn.bind(copying);
|
|
206
|
+
Object.assign(base, {
|
|
207
|
+
copyIn: (target: SqlFragment, rows: Iterable<readonly unknown[]>) => {
|
|
208
|
+
markScopeWrote();
|
|
209
|
+
primaryCount += 1;
|
|
210
|
+
return copyIn(target, rows);
|
|
211
|
+
},
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
200
215
|
if (!isReservable(primary)) return base;
|
|
201
216
|
const reservable: ReplicatedClient & ReservableClient = {
|
|
202
217
|
...base,
|
package/src/statement-excerpt.ts
CHANGED
|
@@ -2,17 +2,62 @@
|
|
|
2
2
|
// module because two rails now report statements — `destructive.ts` and `ungeneratable.ts` — and a
|
|
3
3
|
// second copy of "what does a reported statement look like" is two answers to one question.
|
|
4
4
|
|
|
5
|
+
/** The excerpt's ceiling, and where a longer one is cut to make room for `...`. */
|
|
6
|
+
const MAX_CHARS = 120;
|
|
7
|
+
const CUT_AT = 117;
|
|
8
|
+
|
|
9
|
+
/** `\s` as the regex reads it, one UTF-16 unit at a time. Non-global, so it carries no state. */
|
|
10
|
+
const SPACE = /\s/;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Where the statement starts once the comments PRECEDING it are skipped. A scan, not a regex:
|
|
14
|
+
* `^(?:\s*(?:--…|/\*…\*\/)\s*)+` has two adjacent `\s*` across repetitions, which CodeQL flags as
|
|
15
|
+
* polynomial backtracking (js/polynomial-redos). Each step here advances, so it is one pass.
|
|
16
|
+
*/
|
|
17
|
+
const bodyStart = (statement: string): number => {
|
|
18
|
+
let at = 0;
|
|
19
|
+
for (;;) {
|
|
20
|
+
let from = at;
|
|
21
|
+
while (from < statement.length && SPACE.test(statement.charAt(from))) from += 1;
|
|
22
|
+
if (statement.startsWith('--', from)) {
|
|
23
|
+
const end = statement.indexOf('\n', from);
|
|
24
|
+
at = end === -1 ? statement.length : end;
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
if (statement.startsWith('/*', from)) {
|
|
28
|
+
const end = statement.indexOf('*/', from + 2);
|
|
29
|
+
// Unclosed: not a comment, so the statement starts here, as the regex left it.
|
|
30
|
+
if (end === -1) return at;
|
|
31
|
+
at = end + 2;
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
return at;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
5
38
|
/**
|
|
6
39
|
* Only the comments *preceding* the statement come off, the ones `statementsOf` carries in from the
|
|
7
40
|
* file header or from the `-- backfill …` note above it; the SQL itself stays verbatim.
|
|
8
41
|
*
|
|
9
42
|
* Blanking is for **deciding**, never for reporting: `stripSqlNoise` empties quoted identifiers, so
|
|
10
43
|
* a report built from it says `drop table ""`, which names nothing an author can act on.
|
|
44
|
+
*
|
|
45
|
+
* Whitespace runs collapse to one space, leading and trailing ones go, and reading stops at the
|
|
46
|
+
* 121st character kept: past it the answer is already the 117-character cut.
|
|
11
47
|
*/
|
|
12
48
|
export function statementExcerpt(statement: string): string {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
.
|
|
17
|
-
|
|
49
|
+
let line = '';
|
|
50
|
+
let pendingSpace = false;
|
|
51
|
+
for (let at = bodyStart(statement); at < statement.length; at += 1) {
|
|
52
|
+
const char = statement.charAt(at);
|
|
53
|
+
if (SPACE.test(char)) {
|
|
54
|
+
pendingSpace = line.length > 0;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (pendingSpace) line += ' ';
|
|
58
|
+
pendingSpace = false;
|
|
59
|
+
line += char;
|
|
60
|
+
if (line.length > MAX_CHARS) return `${line.slice(0, CUT_AT)}...`;
|
|
61
|
+
}
|
|
62
|
+
return line;
|
|
18
63
|
}
|
|
@@ -22,3 +22,12 @@ export function setTransactionSettings(next: SettingsProvider | undefined): void
|
|
|
22
22
|
export function transactionSettings(): LocalSettings | undefined {
|
|
23
23
|
return provider?.();
|
|
24
24
|
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Whether a provider is installed at all, whatever it answers now. `copy-in.ts` asks: Postgres
|
|
28
|
+
* refuses `COPY FROM` on a table under row-level security (`0A000`) with or without a tenant in
|
|
29
|
+
* scope, so the question is "is row security armed", never "is there a tenant right now".
|
|
30
|
+
*/
|
|
31
|
+
export function transactionSettingsInstalled(): boolean {
|
|
32
|
+
return provider !== undefined;
|
|
33
|
+
}
|
package/src/transaction.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import { assert, finiteCount, nanoid } from '@ultimat3/core';
|
|
7
7
|
import { baseClient, type DbClient, type DbConnection, isReservable } from './client';
|
|
8
|
+
import type { CopyInClient } from './copy-in';
|
|
8
9
|
import { DbError, serializationExhausted } from './errors';
|
|
9
10
|
import { setLocal } from './local-settings';
|
|
10
11
|
import { createTurnQueue, type TurnQueue } from './pglite-turns';
|
|
@@ -145,7 +146,7 @@ function makeTx(
|
|
|
145
146
|
refuseAbandoned(completing);
|
|
146
147
|
return watched(abort, send());
|
|
147
148
|
};
|
|
148
|
-
|
|
149
|
+
const tx: DbTx = {
|
|
149
150
|
id,
|
|
150
151
|
origin,
|
|
151
152
|
query: <T>(fragment: SqlFragment) => guarded(() => connection.query<T>(fragment)),
|
|
@@ -161,6 +162,15 @@ function makeTx(
|
|
|
161
162
|
else if (outcome.value === 'open' || outcome.value === 'ending') commits.push(effect);
|
|
162
163
|
},
|
|
163
164
|
};
|
|
165
|
+
// Only when the connection copies (`postgresClient`'s pin): a COPY on it is this transaction's,
|
|
166
|
+
// guarded like every statement. Absent, `canCopyIn(tx)` answers false and callers insert.
|
|
167
|
+
const pin = connection as DbClient & Partial<CopyInClient>;
|
|
168
|
+
if (typeof pin.copyIn !== 'function') return tx;
|
|
169
|
+
const copyIn = pin.copyIn.bind(pin);
|
|
170
|
+
return Object.assign(tx, {
|
|
171
|
+
copyIn: (target: SqlFragment, rows: Iterable<readonly unknown[]>) =>
|
|
172
|
+
guarded(() => copyIn(target, rows)),
|
|
173
|
+
});
|
|
164
174
|
}
|
|
165
175
|
|
|
166
176
|
const isAborted = (error: unknown): boolean =>
|