@ultimat3/db 30.8.0 → 31.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +17 -9
- package/README.md +71 -22
- package/package.json +3 -2
- package/src/adapter.ts +9 -0
- package/src/attribution.ts +8 -9
- package/src/branch-errors.ts +24 -0
- package/src/branch.ts +2 -1
- package/src/check-ddl.ts +2 -2
- package/src/client.ts +7 -1
- package/src/db-diagnostics.ts +15 -4
- package/src/entity-shape.ts +20 -0
- package/src/errors.ts +4 -22
- package/src/expected-loop.ts +3 -3
- package/src/generate-partition-run.ts +97 -0
- package/src/generate-partition.ts +190 -0
- package/src/generate-snapshot.ts +9 -0
- package/src/generate.ts +6 -1
- package/src/index.ts +30 -99
- package/src/introspect.ts +23 -16
- package/src/invariant-ddl.ts +11 -10
- package/src/keyset.ts +26 -1
- package/src/pglite-branch.ts +2 -1
- package/src/pglite.ts +22 -55
- package/src/pool-sweep.ts +2 -3
- package/src/primary-key.ts +1 -2
- package/src/readonly-role.ts +41 -1
- package/src/same-tenant.ts +1 -1
- package/src/snapshot-parse.ts +12 -0
- package/src/sql.ts +21 -3
- package/src/statement-cancel.ts +86 -0
- package/src/statement-funnel.ts +8 -53
- package/src/statement-shape.ts +5 -3
- package/src/statement-span.ts +74 -18
- package/src/observe.ts +0 -90
package/src/introspect.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import { nonAppRelations } from './app-relation';
|
|
7
7
|
import { type DbClient, db } from './client';
|
|
8
|
+
import type { PartitionInterval } from './entity-shape';
|
|
8
9
|
import {
|
|
9
10
|
type CheckRow,
|
|
10
11
|
type ColumnRow,
|
|
@@ -168,6 +169,12 @@ export interface TableDescription {
|
|
|
168
169
|
* descriptions are unchanged. Its partitions are Postgres' and appear in no description.
|
|
169
170
|
*/
|
|
170
171
|
readonly partitioned?: true | undefined;
|
|
172
|
+
/**
|
|
173
|
+
* `entity({ partitionBy })`'s interval, as the migration that created the table recorded it. The
|
|
174
|
+
* SNAPSHOT's half only, never the catalog's: `x db gen` refuses a change to it, because partitions
|
|
175
|
+
* of another width would overlap the ones that exist (`generate-partition.ts`).
|
|
176
|
+
*/
|
|
177
|
+
readonly partitionInterval?: PartitionInterval | undefined;
|
|
171
178
|
/**
|
|
172
179
|
* That a migration gave this table the tenant policy, enabled and forced (`row-security-plan.ts`).
|
|
173
180
|
* The SNAPSHOT's half, `true` or absent for `appendOnly`'s reason; the catalog's is `policyNames`.
|
|
@@ -233,19 +240,19 @@ export async function introspectSchema(
|
|
|
233
240
|
): Promise<SchemaDescription> {
|
|
234
241
|
const client = options.client ?? db();
|
|
235
242
|
const schema = options.schema ?? 'public';
|
|
236
|
-
// Asked
|
|
243
|
+
// Asked unconditionally: everything below reads `information_schema`, which admits a
|
|
237
244
|
// view and an extension's own tables alongside the app's. Merged into `excluded` rather than
|
|
238
245
|
// filtered afterwards so one deny list feeds the whole fold.
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
246
|
+
//
|
|
247
|
+
// Every read below is SENT before any is awaited: none depends on another's answer, and eight
|
|
248
|
+
// round trips one after another were what every CLI command and boot drift check paid.
|
|
249
|
+
const nonApp = nonAppRelations(client, schema);
|
|
243
250
|
|
|
244
251
|
// The type is `format_type`, as `catalog-relations.ts` reads it: `information_schema.data_type`
|
|
245
252
|
// answers `numeric` for `numeric(12,2)`, `ARRAY` for `text[]` and `USER-DEFINED` for an enum, and
|
|
246
253
|
// `ColumnDescription.dataType` has always been documented as the first of each pair. Still FROM
|
|
247
254
|
// the view, which decides which columns this role may see.
|
|
248
|
-
const columns =
|
|
255
|
+
const columns = client.query<ColumnRow>(sql`
|
|
249
256
|
select
|
|
250
257
|
c.table_name,
|
|
251
258
|
c.column_name,
|
|
@@ -280,7 +287,7 @@ export async function introspectSchema(
|
|
|
280
287
|
// inner join dropped it and `(id, lower(title))` read back as `(id)` — an index rebuilt by hand
|
|
281
288
|
// with an extra expression key compared equal to the declared one. It is kept in its position
|
|
282
289
|
// and MARKED by its parentheses, which no declared column name carries.
|
|
283
|
-
const indexes =
|
|
290
|
+
const indexes = client.query<IndexRow>(sql`
|
|
284
291
|
select
|
|
285
292
|
t.relname as table_name,
|
|
286
293
|
i.relname as index_name,
|
|
@@ -314,7 +321,7 @@ export async function introspectSchema(
|
|
|
314
321
|
// same reason `indkey` orders the index query: `references t (y, x)` is not `references t (x, y)`.
|
|
315
322
|
// `conparentid = 0`: a key into a partitioned table makes Postgres add one clone per partition
|
|
316
323
|
// (`notes_event_fkey_1`, `_2`, …), each a fact of the partitioning and never of a migration.
|
|
317
|
-
const foreignKeys =
|
|
324
|
+
const foreignKeys = client.query<ForeignKeyRow>(sql`
|
|
318
325
|
select
|
|
319
326
|
src.relname as table_name,
|
|
320
327
|
c.conname as constraint_name,
|
|
@@ -341,7 +348,7 @@ export async function introspectSchema(
|
|
|
341
348
|
// which no generated spelling can ever equal, so reading it would make every drift check report
|
|
342
349
|
// a correct database as wrong. `contype = 'c'` is the CHECK constraints alone — Postgres 17
|
|
343
350
|
// onwards records a NOT NULL as `'n'`, and a domain's as `'c'` on the domain rather than here.
|
|
344
|
-
const checks =
|
|
351
|
+
const checks = client.query<CheckRow>(sql`
|
|
345
352
|
select src.relname as table_name, c.conname as constraint_name, c.convalidated as validated
|
|
346
353
|
from pg_constraint c
|
|
347
354
|
join pg_class src on src.oid = c.conrelid
|
|
@@ -352,7 +359,7 @@ export async function introspectSchema(
|
|
|
352
359
|
|
|
353
360
|
// Names only, as `checks` above: an append-only table is judged by whether its trigger is THERE
|
|
354
361
|
// and firing, never by `pg_get_triggerdef`'s text. `tgisinternal` is a foreign key's own.
|
|
355
|
-
const triggers =
|
|
362
|
+
const triggers = client.query<TriggerNameRow>(sql`
|
|
356
363
|
select src.relname as table_name, t.tgname as trigger_name
|
|
357
364
|
from pg_trigger t
|
|
358
365
|
join pg_class src on src.oid = t.tgrelid
|
|
@@ -362,12 +369,11 @@ export async function introspectSchema(
|
|
|
362
369
|
order by src.relname, t.tgname
|
|
363
370
|
`);
|
|
364
371
|
|
|
365
|
-
const partitioned =
|
|
366
|
-
const policies =
|
|
372
|
+
const partitioned = partitionedTables(client, schema);
|
|
373
|
+
const policies = policyNameRows(client, schema);
|
|
367
374
|
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
excluded,
|
|
375
|
+
const [nonAppNames, ...rows] = await Promise.all([
|
|
376
|
+
nonApp,
|
|
371
377
|
columns,
|
|
372
378
|
indexes,
|
|
373
379
|
foreignKeys,
|
|
@@ -375,7 +381,8 @@ export async function introspectSchema(
|
|
|
375
381
|
triggers,
|
|
376
382
|
partitioned,
|
|
377
383
|
policies,
|
|
378
|
-
);
|
|
384
|
+
]);
|
|
385
|
+
return buildSchema(schema, [...(options.exclude ?? ['x_migrations']), ...nonAppNames], ...rows);
|
|
379
386
|
}
|
|
380
387
|
|
|
381
388
|
/** Pure, so the row -> description mapping is testable without a database. */
|
package/src/invariant-ddl.ts
CHANGED
|
@@ -17,7 +17,7 @@ import type {
|
|
|
17
17
|
import { indexMethodOf } from './index-method';
|
|
18
18
|
import type { CheckDescription } from './introspect';
|
|
19
19
|
import { constraintNameUnsafe } from './invariant-errors';
|
|
20
|
-
import { identifier } from './sql';
|
|
20
|
+
import { identifier, MAX_IDENTIFIER_BYTES } from './sql';
|
|
21
21
|
|
|
22
22
|
/**
|
|
23
23
|
* `NAMEDATALEN - 1`. Postgres truncates a longer identifier and says nothing, so two constraints
|
|
@@ -26,10 +26,8 @@ import { identifier } from './sql';
|
|
|
26
26
|
* the index names it mints for the same reason; this bound is Postgres', not a convention, so
|
|
27
27
|
* stating it on both sides of the tier seam is one fact written twice rather than two rules.
|
|
28
28
|
*
|
|
29
|
-
*
|
|
30
|
-
* of NAMEDATALEN in one package is two rules that can drift, which is the thing it exists against.
|
|
29
|
+
* One copy of NAMEDATALEN in this package, `sql.ts`'s: `identifier()` refuses past it too.
|
|
31
30
|
*/
|
|
32
|
-
export const MAX_IDENTIFIER_BYTES = 63;
|
|
33
31
|
|
|
34
32
|
/**
|
|
35
33
|
* The convention alone, with nothing validated and nothing refused. One copy, so `constraintNameFor`
|
|
@@ -71,19 +69,22 @@ export function namesConstraint(
|
|
|
71
69
|
*/
|
|
72
70
|
export function constraintNameFor(table: string, invariant: InvariantDescriptionLike): string {
|
|
73
71
|
const name = spellConstraintName(table, invariant);
|
|
74
|
-
// Through the package's one identifier rule, never a second regex: an invariant name is
|
|
75
|
-
// validated by nobody at declaration, so this is where a name that closes the quote is stopped.
|
|
76
|
-
if (!isIdentifier(invariant.name) || !isIdentifier(table)) {
|
|
77
|
-
throw constraintNameUnsafe(table, invariant.name);
|
|
78
|
-
}
|
|
79
72
|
// Bytes and not characters: 63 is what the server counts, and `.length` stops seeing the
|
|
80
73
|
// truncation the moment a name is not ASCII.
|
|
81
74
|
const bytes = new TextEncoder().encode(name).length;
|
|
75
|
+
// Asked before the character screen below, so the name reaching this `fix:` is screened here.
|
|
76
|
+
const head = invariant.name.slice(0, 20);
|
|
82
77
|
assert(
|
|
83
78
|
bytes <= MAX_IDENTIFIER_BYTES,
|
|
84
79
|
`constraint name "${name}" is ${bytes} bytes; Postgres truncates at ${MAX_IDENTIFIER_BYTES} and says nothing`,
|
|
85
|
-
`invariant('${
|
|
80
|
+
`invariant('${isIdentifier(head) ? head : '<name>'}…', …) # shorten the invariant name, then x db gen`,
|
|
86
81
|
);
|
|
82
|
+
// Through the package's one identifier rule, never a second regex: an invariant name is
|
|
83
|
+
// validated by nobody at declaration, so this is where a name that closes the quote is stopped.
|
|
84
|
+
// After the length, which `identifier()` also refuses: the byte count is the more exact answer.
|
|
85
|
+
if (!isIdentifier(invariant.name) || !isIdentifier(table)) {
|
|
86
|
+
throw constraintNameUnsafe(table, invariant.name);
|
|
87
|
+
}
|
|
87
88
|
return name;
|
|
88
89
|
}
|
|
89
90
|
|
package/src/keyset.ts
CHANGED
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
encodeCursor,
|
|
11
11
|
finiteCount,
|
|
12
12
|
pageOf,
|
|
13
|
+
renderCauseValue,
|
|
13
14
|
} from '@ultimat3/core';
|
|
14
15
|
import { DbError } from './errors';
|
|
15
16
|
import { join, raw, type SqlFragment, sql } from './sql';
|
|
@@ -59,6 +60,26 @@ const CASTS: ReadonlyMap<KeysetKind, string> = new Map<KeysetKind, string>([
|
|
|
59
60
|
const NULL_KEY_FIX =
|
|
60
61
|
"keyset({ keys: [{ column: sql`coalesce(p.published_at, p.created_at)`, kind: 'timestamptz', direction: 'desc' }, …] }) # or order by a not-null column";
|
|
61
62
|
|
|
63
|
+
const DIRECTIONS: ReadonlySet<string> = new Set(['asc', 'desc']);
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* A direction and a kind are spliced as SQL text, and a sort read off a query string arrives typed
|
|
67
|
+
* as a `string` the moment it is cast: refused here, before a fragment exists. Lower case only —
|
|
68
|
+
* `'DESC'` would order one way while every `=== 'desc'` below seeks the other.
|
|
69
|
+
*/
|
|
70
|
+
const assertKey = (key: KeysetKey, at: number): void => {
|
|
71
|
+
assert(
|
|
72
|
+
DIRECTIONS.has(key.direction),
|
|
73
|
+
`keyset() key ${String(at)} has direction ${renderCauseValue(key.direction)}; only 'asc' and 'desc' are spliced into SQL`,
|
|
74
|
+
"keyset({ keys: [{ column: raw('p.created_at'), kind: 'timestamptz', direction: input.dir === 'asc' ? 'asc' : 'desc' }], … }) # map a request's sort onto the two literals",
|
|
75
|
+
);
|
|
76
|
+
assert(
|
|
77
|
+
CASTS.has(key.kind),
|
|
78
|
+
`keyset() key ${String(at)} has kind ${renderCauseValue(key.kind)}, which has no cast to bind a position back with`,
|
|
79
|
+
"keyset({ keys: [{ column: raw('p.created_at'), kind: 'timestamptz', … }] }) # one of: timestamptz, uuid, text, integer, bigint",
|
|
80
|
+
);
|
|
81
|
+
};
|
|
82
|
+
|
|
62
83
|
const aliasOf = (index: number): string => `_keyset_${String(index)}`;
|
|
63
84
|
|
|
64
85
|
/**
|
|
@@ -80,6 +101,9 @@ const scopeOf = (scope: string, keys: readonly KeysetKey[]): string => {
|
|
|
80
101
|
const bind = (key: KeysetKey, text: string): SqlFragment =>
|
|
81
102
|
sql`${text}::${raw(CASTS.get(key.kind) ?? 'text')}`;
|
|
82
103
|
|
|
104
|
+
/** The splice re-derived from the closed set, as `entity/src/pg-sql.ts` does: never the caller's text. */
|
|
105
|
+
const orderOf = (key: KeysetKey): SqlFragment => raw(key.direction === 'desc' ? 'desc' : 'asc');
|
|
106
|
+
|
|
83
107
|
const past = (key: KeysetKey, value: SqlFragment): SqlFragment =>
|
|
84
108
|
sql`${key.column} ${raw(key.direction === 'desc' ? '<' : '>')} ${value}`;
|
|
85
109
|
|
|
@@ -158,6 +182,7 @@ export function keyset(options: KeysetOptions): Keyset {
|
|
|
158
182
|
'keyset() was given an empty scope, so a cursor from any other raw read would page this one',
|
|
159
183
|
"keyset({ scope: 'posts.feed', … }) # one name per read, plus its filter arguments",
|
|
160
184
|
);
|
|
185
|
+
keys.forEach(assertKey);
|
|
161
186
|
const limit = finiteCount('keyset', 'limit', options.limit, 1);
|
|
162
187
|
const scope = scopeOf(options.scope, keys);
|
|
163
188
|
const where =
|
|
@@ -165,7 +190,7 @@ export function keyset(options: KeysetOptions): Keyset {
|
|
|
165
190
|
return {
|
|
166
191
|
select: join(keys.map((key, at) => sql`${key.column}::text as ${raw(`"${aliasOf(at)}"`)}`)),
|
|
167
192
|
where,
|
|
168
|
-
orderBy: join(keys.map((key) => sql`${key.column} ${
|
|
193
|
+
orderBy: join(keys.map((key) => sql`${key.column} ${orderOf(key)}`)),
|
|
169
194
|
limit: sql`${limit + 1}`,
|
|
170
195
|
page<Row extends object>(rows: readonly Row[]): Page<KeysetRow<Row>> {
|
|
171
196
|
const positions = rows.map((row, index) => keyText(row, keys, index));
|
package/src/pglite-branch.ts
CHANGED
|
@@ -8,7 +8,8 @@ import { basename, dirname, join } from 'node:path';
|
|
|
8
8
|
import { NotImplementedError, systemClock } from '@ultimat3/core';
|
|
9
9
|
import type { BranchInfo } from './branch';
|
|
10
10
|
import { assertBranchName } from './branch';
|
|
11
|
-
import { branchExists
|
|
11
|
+
import { branchExists } from './branch-errors';
|
|
12
|
+
import { dbUnavailable } from './errors';
|
|
12
13
|
import { PGLITE_MEMORY, pgliteDataDir } from './pglite';
|
|
13
14
|
|
|
14
15
|
export interface PgliteBranchOptions {
|
package/src/pglite.ts
CHANGED
|
@@ -3,19 +3,17 @@
|
|
|
3
3
|
// The module is resolved at first query and never at import: it is an OPTIONAL peer, and an image
|
|
4
4
|
// that only ever talks to a managed Postgres must not carry 26 MB of WASM it will never load.
|
|
5
5
|
|
|
6
|
-
import {
|
|
6
|
+
import { callerStack } from '@ultimat3/core';
|
|
7
7
|
import { refuseUnsendable } from './bound-parameters';
|
|
8
8
|
import type { DbClient, DbConnection, ReservableClient } from './client';
|
|
9
9
|
import { refuseRolledBackCommit } from './commit-tag';
|
|
10
10
|
import { DbError, driverError } from './errors';
|
|
11
|
-
import { expectedQueryLoopReason } from './expected-loop';
|
|
12
11
|
import {
|
|
13
12
|
assertListenChannel,
|
|
14
13
|
type DbSubscription,
|
|
15
14
|
type ListeningClient,
|
|
16
15
|
listenUnsupported,
|
|
17
16
|
} from './listen';
|
|
18
|
-
import { statementObserver } from './observe';
|
|
19
17
|
import { PGLITE_INSTANT_PARSERS } from './pg-instant';
|
|
20
18
|
import { linkPgliteExtensions, type PgliteExtensionLoader } from './pglite-extensions';
|
|
21
19
|
import { PGLITE_PACKAGE } from './pglite-package';
|
|
@@ -30,7 +28,7 @@ import {
|
|
|
30
28
|
import { createTurnQueue } from './pglite-turns';
|
|
31
29
|
import type { SqlFragment } from './sql';
|
|
32
30
|
import { statementExcerpt } from './statement-excerpt';
|
|
33
|
-
import {
|
|
31
|
+
import { traceStatement } from './statement-span';
|
|
34
32
|
import { liveTxConnection } from './transaction';
|
|
35
33
|
|
|
36
34
|
/** What PGlite answers with. `rows` is empty for a write, which is why the count is separate. */
|
|
@@ -249,7 +247,7 @@ export interface PgliteClient extends ReservableClient, ListeningClient {
|
|
|
249
247
|
// PGlite counts MODIFIED rows, so a SELECT that returned rows still reports `affectedRows: 0` —
|
|
250
248
|
// `??` would answer 0 for every read and disagree with `PostgresClient.execute`. A write that
|
|
251
249
|
// modified nothing returned no rows either, so falling back to the row count stays 0 there. One
|
|
252
|
-
// definition, shared: `execute()` and the
|
|
250
|
+
// definition, shared: `execute()` and the `db.statement` event must not disagree about how many rows a
|
|
253
251
|
// statement accounted for.
|
|
254
252
|
function rowsOf(result: PgliteResult): number {
|
|
255
253
|
return result.affectedRows !== undefined && result.affectedRows > 0
|
|
@@ -299,56 +297,21 @@ export function pgliteClient(options: PgliteOptions = {}): PgliteClient {
|
|
|
299
297
|
}
|
|
300
298
|
|
|
301
299
|
/**
|
|
302
|
-
* The funnel — queued, in-transaction and pinned statements all arrive here, so the
|
|
303
|
-
*
|
|
304
|
-
* branch: no clock read, no span, no event object, and `send` receives exactly the call
|
|
305
|
-
* `statement` made before the seam existed (axiom 6). Same shape as `runOn` in `client.ts`, one
|
|
306
|
-
* driver up.
|
|
300
|
+
* The funnel — queued, in-transaction and pinned statements all arrive here, so the span and the
|
|
301
|
+
* `db.statement` event hang off this one function (`traceStatement`, shared with `runOn`).
|
|
307
302
|
*/
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
// And the pair `postgresRepo` left above this frame, for the same reason again: it is what
|
|
315
|
-
// reports a repository loop as "50× findById on members" rather than as fifty rows of SQL.
|
|
316
|
-
const attribution = statementAttribution();
|
|
317
|
-
const started = performance.now();
|
|
318
|
-
let result: PgliteResult;
|
|
319
|
-
try {
|
|
320
|
-
// The span wraps the send and nothing else, so its duration is the statement's and the
|
|
321
|
-
// observer's own work is not charged to the database.
|
|
322
|
-
result = await withStatementSpan(fragment.text, () => send(driver, fragment));
|
|
323
|
-
} catch (error) {
|
|
324
|
-
// The failing path is observed too — the error is already `X_DB_UNAVAILABLE`, and a throw
|
|
325
|
-
// from `onStatement` replaces it, which is why `observe.ts` says a reporting-only observer
|
|
326
|
-
// must not throw.
|
|
327
|
-
observer.onStatement({
|
|
328
|
-
text: fragment.text,
|
|
329
|
-
values: fragment.values,
|
|
330
|
-
durationMs: performance.now() - started,
|
|
331
|
-
rows: 0,
|
|
332
|
-
error,
|
|
333
|
-
attribution,
|
|
334
|
-
expected,
|
|
335
|
-
});
|
|
336
|
-
throw error;
|
|
337
|
-
}
|
|
338
|
-
// Outside the `try` deliberately: a throw from `onStatement` is the observer's, not the
|
|
339
|
-
// database's, and catching it above would report a statement that succeeded as failed.
|
|
340
|
-
observer.onStatement({
|
|
341
|
-
text: fragment.text,
|
|
342
|
-
values: fragment.values,
|
|
343
|
-
durationMs: performance.now() - started,
|
|
344
|
-
rows: rowsOf(result),
|
|
345
|
-
attribution,
|
|
346
|
-
expected,
|
|
347
|
-
});
|
|
348
|
-
return result;
|
|
303
|
+
function statement(
|
|
304
|
+
driver: PgliteDriver,
|
|
305
|
+
fragment: SqlFragment,
|
|
306
|
+
sentFrom: string | undefined,
|
|
307
|
+
): Promise<PgliteResult> {
|
|
308
|
+
return traceStatement(fragment, () => send(driver, fragment), rowsOf, sentFrom);
|
|
349
309
|
}
|
|
350
310
|
|
|
351
311
|
async function run(fragment: SqlFragment): Promise<PgliteResult> {
|
|
312
|
+
// Before the boot's and the turn queue's `await`s, which keep no caller frames: the stack a
|
|
313
|
+
// `db.statement` carries while `captureStatementStacks()` is held. Nothing is built otherwise.
|
|
314
|
+
const sentFrom = callerStack();
|
|
352
315
|
const driver = await connect();
|
|
353
316
|
// A statement issued inside an open transaction is already inside it — there is one
|
|
354
317
|
// connection and that transaction is holding the turn, so waiting for a turn we are already
|
|
@@ -366,8 +329,8 @@ export function pgliteClient(options: PgliteOptions = {}): PgliteClient {
|
|
|
366
329
|
// about who holds this queue, and skipping it put the statement inside whatever transaction
|
|
367
330
|
// this session was running — rolled back with it (`pglite-two-clients.test.ts`).
|
|
368
331
|
const live = liveTxConnection();
|
|
369
|
-
if (live !== undefined && issued.has(live)) return statement(driver, fragment);
|
|
370
|
-
return turns.run(() => statement(driver, fragment));
|
|
332
|
+
if (live !== undefined && issued.has(live)) return statement(driver, fragment, sentFrom);
|
|
333
|
+
return turns.run(() => statement(driver, fragment, sentFrom));
|
|
371
334
|
}
|
|
372
335
|
|
|
373
336
|
return {
|
|
@@ -391,8 +354,12 @@ export function pgliteClient(options: PgliteOptions = {}): PgliteClient {
|
|
|
391
354
|
// released the handle has no claim on the connection, and a leaked `tx` writing straight to
|
|
392
355
|
// it would land inside whatever transaction holds it now, with no error to read; so a late
|
|
393
356
|
// statement queues like any other caller and waits for its own turn.
|
|
394
|
-
const on = (fragment: SqlFragment): Promise<PgliteResult> =>
|
|
395
|
-
|
|
357
|
+
const on = (fragment: SqlFragment): Promise<PgliteResult> => {
|
|
358
|
+
const sentFrom = callerStack();
|
|
359
|
+
return held
|
|
360
|
+
? statement(driver, fragment, sentFrom)
|
|
361
|
+
: turns.run(() => statement(driver, fragment, sentFrom));
|
|
362
|
+
};
|
|
396
363
|
// Idempotent for free: `turn.release()` is a settled promise's `resolve`, not a counter, so
|
|
397
364
|
// a second call cannot hand out a second turn (`pglite-turns.ts`). `[Symbol.dispose]` below
|
|
398
365
|
// is that same call.
|
package/src/pool-sweep.ts
CHANGED
|
@@ -37,9 +37,8 @@ interface InFlight<Owner> {
|
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
/**
|
|
40
|
-
* Age is counted in ticks that FIRED, never read from a clock.
|
|
41
|
-
*
|
|
42
|
-
* a frozen process: a long GC or a SIGSTOP costs one tick however long it lasted, so answers sitting
|
|
40
|
+
* Age is counted in ticks that FIRED, never read from a clock. A tick reads no clock at all, and
|
|
41
|
+
* the count is also the right answer to a frozen process: a long GC or a SIGSTOP costs one tick however long it lasted, so answers sitting
|
|
43
42
|
* unread in their sockets are never judged late. A statement began somewhere inside its first tick,
|
|
44
43
|
* hence the extra one: nothing is judged before the deadline, and everything within one interval of it.
|
|
45
44
|
*/
|
package/src/primary-key.ts
CHANGED
|
@@ -9,9 +9,8 @@ import type { EntityDescriptionLike } from './entity-shape';
|
|
|
9
9
|
import type { Plan } from './foreign-key-plan';
|
|
10
10
|
import { isGenerated } from './generated-column';
|
|
11
11
|
import type { SchemaDescription, TableDescription } from './introspect';
|
|
12
|
-
import { MAX_IDENTIFIER_BYTES } from './invariant-ddl';
|
|
13
12
|
import { migrationIrreversible } from './migration-errors';
|
|
14
|
-
import { identifier } from './sql';
|
|
13
|
+
import { identifier, MAX_IDENTIFIER_BYTES } from './sql';
|
|
15
14
|
|
|
16
15
|
/**
|
|
17
16
|
* Inside shell double quotes a `$`, a backtick and a `!` still run; everything else — a quote, a
|
package/src/readonly-role.ts
CHANGED
|
@@ -3,8 +3,10 @@
|
|
|
3
3
|
// Postgres itself refuses the write. `NOLOGIN` means it is reachable only via `SET LOCAL ROLE`
|
|
4
4
|
// inside an already-`READ ONLY` transaction, never by a connection string.
|
|
5
5
|
|
|
6
|
+
import { stringField } from '@ultimat3/core';
|
|
6
7
|
import type { DbClient } from './client';
|
|
7
8
|
import { identifier, literal, raw, type SqlFragment, sql } from './sql';
|
|
9
|
+
import { sqlState } from './sqlstate';
|
|
8
10
|
|
|
9
11
|
/** The role `ensureReadOnlyRole` creates and `readOnlyQuery` assumes by default. */
|
|
10
12
|
export const READONLY_ROLE = 'ultimate_readonly';
|
|
@@ -89,6 +91,41 @@ export function grantReadOnlySql(options?: ReadOnlyRoleOptions): readonly SqlFra
|
|
|
89
91
|
];
|
|
90
92
|
}
|
|
91
93
|
|
|
94
|
+
/**
|
|
95
|
+
* Two sessions running this DDL at once — `x mcp serve` and the `/_x` panel, two replicas — collide
|
|
96
|
+
* in the catalog: the loser's `CREATE ROLE` is `42710 duplicate_object` past the existence check,
|
|
97
|
+
* and a concurrent GRANT is `XX000 tuple concurrently updated`. Either way the other session made
|
|
98
|
+
* the statement true, so the role is there; read as a refusal, it dropped the layer for the
|
|
99
|
+
* session. Any other `XX000` is still a failure.
|
|
100
|
+
*/
|
|
101
|
+
function lostRace(error: unknown): boolean {
|
|
102
|
+
const state = sqlState(error);
|
|
103
|
+
if (state === DUPLICATE_OBJECT) return true;
|
|
104
|
+
return (
|
|
105
|
+
state === INTERNAL_ERROR && /tuple concurrently (updated|deleted)/.test(messageChain(error))
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const DUPLICATE_OBJECT = '42710';
|
|
110
|
+
const INTERNAL_ERROR = 'XX000';
|
|
111
|
+
|
|
112
|
+
/** Every message down the `sourceError` chain a `DbError` wraps its driver error in. */
|
|
113
|
+
function messageChain(error: unknown): string {
|
|
114
|
+
const messages: string[] = [];
|
|
115
|
+
let value = error;
|
|
116
|
+
for (let depth = 0; depth < 4 && value !== null && value !== undefined; depth += 1) {
|
|
117
|
+
const message = stringField(value, 'message');
|
|
118
|
+
if (message !== undefined) messages.push(message);
|
|
119
|
+
// A getter or a Proxy may throw on the read: a chain that fights being walked ends here.
|
|
120
|
+
try {
|
|
121
|
+
value = typeof value === 'object' ? Reflect.get(value, 'sourceError') : undefined;
|
|
122
|
+
} catch {
|
|
123
|
+
value = undefined;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return messages.join('\n');
|
|
127
|
+
}
|
|
128
|
+
|
|
92
129
|
/**
|
|
93
130
|
* Create/refresh the role and make it assumable by the current user.
|
|
94
131
|
*
|
|
@@ -104,7 +141,10 @@ export async function ensureReadOnlyRole(
|
|
|
104
141
|
const role = options?.role ?? READONLY_ROLE;
|
|
105
142
|
try {
|
|
106
143
|
for (const statement of grantReadOnlySql(options)) {
|
|
107
|
-
|
|
144
|
+
// A lost race is not a refusal: skip the statement the other session already made true.
|
|
145
|
+
await client.execute(statement).catch((error: unknown) => {
|
|
146
|
+
if (!lostRace(error)) throw error;
|
|
147
|
+
});
|
|
108
148
|
}
|
|
109
149
|
return role;
|
|
110
150
|
} catch {
|
package/src/same-tenant.ts
CHANGED
|
@@ -9,7 +9,7 @@ import type {
|
|
|
9
9
|
} from './entity-shape';
|
|
10
10
|
import { referenceParts } from './foreign-key';
|
|
11
11
|
import { findTable, type IndexDescription, type SchemaDescription } from './introspect';
|
|
12
|
-
import { MAX_IDENTIFIER_BYTES } from './
|
|
12
|
+
import { MAX_IDENTIFIER_BYTES } from './sql';
|
|
13
13
|
|
|
14
14
|
/** How much of a name survives beside its hash: `_` and eight hex characters. */
|
|
15
15
|
const KEPT_BYTES = MAX_IDENTIFIER_BYTES - 9;
|
package/src/snapshot-parse.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// this package's answer and the reader on disk is `@ultimat3/cli`'s — two owners of that question
|
|
4
4
|
// is a sidecar one of them accepts and the other cannot use.
|
|
5
5
|
|
|
6
|
+
import { PARTITION_INTERVALS, type PartitionInterval } from './entity-shape';
|
|
6
7
|
import type {
|
|
7
8
|
CheckDescription,
|
|
8
9
|
ColumnDescription,
|
|
@@ -25,6 +26,9 @@ const nullableStr = (value: unknown): value is string | null => value === null |
|
|
|
25
26
|
const strings = (value: unknown): value is readonly string[] =>
|
|
26
27
|
Array.isArray(value) && value.every(str);
|
|
27
28
|
|
|
29
|
+
const INTERVALS: readonly unknown[] = PARTITION_INTERVALS;
|
|
30
|
+
const interval = (value: unknown): value is PartitionInterval => INTERVALS.includes(value);
|
|
31
|
+
|
|
28
32
|
/** `null` is Postgres' own default; anything else must be one of the two directions. */
|
|
29
33
|
const order = (value: unknown): value is 'asc' | 'desc' | null =>
|
|
30
34
|
value === null || value === 'asc' || value === 'desc';
|
|
@@ -138,6 +142,12 @@ function tableOf(value: unknown): TableDescription | undefined {
|
|
|
138
142
|
if (!(rowSecurity === undefined || bool(rowSecurity))) return undefined;
|
|
139
143
|
const retain = value['retain'];
|
|
140
144
|
if (!(retain === undefined || bool(retain))) return undefined;
|
|
145
|
+
// `partitioned` by the same rule; its interval absent, or one of the set — the record
|
|
146
|
+
// `partitionPlan` refuses a removal and a change of width against.
|
|
147
|
+
const partitioned = value['partitioned'];
|
|
148
|
+
if (!(partitioned === undefined || bool(partitioned))) return undefined;
|
|
149
|
+
const width = value['partitionInterval'];
|
|
150
|
+
if (!(width === undefined || interval(width))) return undefined;
|
|
141
151
|
// Absent is none recorded; anything present must be a list of `{ name, install }`.
|
|
142
152
|
const rawTriggers = value['triggers'];
|
|
143
153
|
const triggers = rawTriggers === undefined ? undefined : all(rawTriggers, trigger);
|
|
@@ -148,6 +158,8 @@ function tableOf(value: unknown): TableDescription | undefined {
|
|
|
148
158
|
...(identity === true ? { replicaIdentityFull: true as const } : {}),
|
|
149
159
|
...(appendOnly === true ? { appendOnly: true as const } : {}),
|
|
150
160
|
...(rowSecurity === true ? { rowSecurity: true as const } : {}),
|
|
161
|
+
...(partitioned === true ? { partitioned: true as const } : {}),
|
|
162
|
+
...(width === undefined ? {} : { partitionInterval: width }),
|
|
151
163
|
};
|
|
152
164
|
const raw = value['checks'];
|
|
153
165
|
if (raw === undefined) {
|
package/src/sql.ts
CHANGED
|
@@ -121,16 +121,34 @@ export function raw(trusted: string): SqlFragment {
|
|
|
121
121
|
|
|
122
122
|
const SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;
|
|
123
123
|
|
|
124
|
+
/**
|
|
125
|
+
* NAMEDATALEN - 1: past it Postgres TRUNCATES with a NOTICE and nothing else, so two names sharing
|
|
126
|
+
* their first 63 bytes address one object. Bytes, not characters. The package's one copy.
|
|
127
|
+
*/
|
|
128
|
+
export const MAX_IDENTIFIER_BYTES = 63;
|
|
129
|
+
|
|
124
130
|
/**
|
|
125
131
|
* A quoted identifier — the safe answer to the `raw()` temptation. Table and column names
|
|
126
|
-
* cannot be bound as parameters, so they are validated and double-quoted instead.
|
|
132
|
+
* cannot be bound as parameters, so they are validated and double-quoted instead. Refused: empty,
|
|
133
|
+
* whitespace, `"`, `\\`, a NUL (the wire protocol cannot carry one), and over 63 bytes.
|
|
127
134
|
*/
|
|
128
135
|
export function identifier(name: string): SqlFragment {
|
|
129
|
-
if (SAFE_IDENTIFIER.test(name))
|
|
130
|
-
|
|
136
|
+
if (SAFE_IDENTIFIER.test(name)) {
|
|
137
|
+
if (name.length > MAX_IDENTIFIER_BYTES) throw identifierUnsafe(name, tooLong(name));
|
|
138
|
+
return raw(`"${name}"`);
|
|
139
|
+
}
|
|
140
|
+
if (name.length === 0 || /[\s"\\]/.test(name) || name.includes('\u0000')) {
|
|
141
|
+
throw identifierUnsafe(name);
|
|
142
|
+
}
|
|
143
|
+
if (new TextEncoder().encode(name).length > MAX_IDENTIFIER_BYTES) {
|
|
144
|
+
throw identifierUnsafe(name, tooLong(name));
|
|
145
|
+
}
|
|
131
146
|
return raw(`"${name}"`);
|
|
132
147
|
}
|
|
133
148
|
|
|
149
|
+
const tooLong = (name: string): string =>
|
|
150
|
+
`it is ${String(new TextEncoder().encode(name).length)} bytes, and Postgres truncates an identifier at ${String(MAX_IDENTIFIER_BYTES)} without an error`;
|
|
151
|
+
|
|
134
152
|
/**
|
|
135
153
|
* The two characters a shell substitutes INSIDE double quotes. Rejected before `identifier` is
|
|
136
154
|
* consulted at all, because `identifier` accepts both.
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Single responsibility: cancel a POOLED READ on the server when the scope that sent it aborts, so a
|
|
2
|
+
// caller who hung up stops holding a pool connection until `statement_timeout`. The scope's signal
|
|
3
|
+
// is read ambiently (core's context), once per statement, by `client.ts`'s pooled `run`.
|
|
4
|
+
|
|
5
|
+
import { isUltimateError, throwIfAborted, tryUseContext } from '@ultimat3/core';
|
|
6
|
+
import type { BunSqlDriver } from './bun-sql';
|
|
7
|
+
import { statementVerb } from './statement-shape';
|
|
8
|
+
|
|
9
|
+
type Send = Pick<BunSqlDriver, 'unsafe'>;
|
|
10
|
+
|
|
11
|
+
/** `Bun.SQL`'s query: a promise with `cancel()`, which sends the server a CancelRequest (`57014`). */
|
|
12
|
+
type CancellableQuery = Promise<unknown> & { readonly cancel?: unknown };
|
|
13
|
+
|
|
14
|
+
export interface AbortWatch {
|
|
15
|
+
/** `driver`, with each query it sends watched. */
|
|
16
|
+
on(driver: Send): Send;
|
|
17
|
+
/** What the caller is thrown: the abort's own error when this watch cancelled, else `error`. */
|
|
18
|
+
failure(error: unknown): unknown;
|
|
19
|
+
/** Detach from the signal; the statement settled. */
|
|
20
|
+
end(): void;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* A watch for one pooled statement, or `undefined` when there is nothing to cancel — and the rule
|
|
25
|
+
* for which is the whole design:
|
|
26
|
+
*
|
|
27
|
+
* - **A read, by its verb (`select`), never a write.** A hang-up is Bun's uncoded abort, and a
|
|
28
|
+
* click followed by a navigation must keep landing (`abandonment()` in core); a `with` may hide a
|
|
29
|
+
* data-modifying CTE, so it is not a read here.
|
|
30
|
+
* - **Pooled, never pinned.** Cancelling a statement inside a transaction aborts the transaction,
|
|
31
|
+
* which is `transaction-guard.ts`'s decision to make, not a funnel's (`completeTransaction()`).
|
|
32
|
+
* - **In flight when the abort lands, never sent after it.** A job's settle and a fenced write go
|
|
33
|
+
* out past their abort on purpose, so an already-aborted scope sends exactly as before.
|
|
34
|
+
*
|
|
35
|
+
* A driver whose query carries no `cancel()` (a fake) is waited out, as before this existed.
|
|
36
|
+
*/
|
|
37
|
+
export function watchAbort(text: string): AbortWatch | undefined {
|
|
38
|
+
const ctx = tryUseContext();
|
|
39
|
+
if (ctx === undefined || ctx.signal.aborted || statementVerb(text) !== 'select') return undefined;
|
|
40
|
+
const { signal } = ctx;
|
|
41
|
+
let query: CancellableQuery | undefined;
|
|
42
|
+
let settled = false;
|
|
43
|
+
let cancelled = false;
|
|
44
|
+
const cancel = (): void => {
|
|
45
|
+
if (settled || query === undefined || typeof query.cancel !== 'function') return;
|
|
46
|
+
cancelled = true;
|
|
47
|
+
// Synchronous on `Bun.SQL`; a throw here is the driver's and the statement simply runs on.
|
|
48
|
+
try {
|
|
49
|
+
query.cancel();
|
|
50
|
+
} catch {
|
|
51
|
+
cancelled = false;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
signal.addEventListener('abort', cancel, { once: true });
|
|
55
|
+
return {
|
|
56
|
+
on: (driver) => ({
|
|
57
|
+
unsafe(statement, values) {
|
|
58
|
+
const sending = driver.unsafe(statement, values) as CancellableQuery;
|
|
59
|
+
query = sending;
|
|
60
|
+
// Marked on the query's own settle, before the funnel's chain resumes: a cancel sent after
|
|
61
|
+
// the answer would land on whatever this connection runs next.
|
|
62
|
+
const mark = (): void => {
|
|
63
|
+
settled = true;
|
|
64
|
+
};
|
|
65
|
+
sending.then(mark, mark);
|
|
66
|
+
return sending;
|
|
67
|
+
},
|
|
68
|
+
}),
|
|
69
|
+
failure(error) {
|
|
70
|
+
if (!cancelled) return error;
|
|
71
|
+
// A coded reason was somebody answered (`X_TIMEOUT`, a job's `X_ABORTED`): the same object,
|
|
72
|
+
// as `abandonment()` hands it. Uncoded is a hang-up: core's own `X_ABORTED`, by its one maker.
|
|
73
|
+
if (isUltimateError(signal.reason)) return signal.reason;
|
|
74
|
+
try {
|
|
75
|
+
throwIfAborted(ctx);
|
|
76
|
+
} catch (aborted) {
|
|
77
|
+
return aborted;
|
|
78
|
+
}
|
|
79
|
+
return error;
|
|
80
|
+
},
|
|
81
|
+
end: () => {
|
|
82
|
+
settled = true;
|
|
83
|
+
signal.removeEventListener('abort', cancel);
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|