@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 +33 -32
- package/README.md +23 -0
- package/package.json +2 -2
- package/src/array-parameter.ts +4 -2
- package/src/client.ts +34 -6
- package/src/copy-in.ts +219 -0
- package/src/drift-findings.ts +4 -1
- package/src/drift-index-keys.ts +54 -0
- package/src/drift.ts +14 -2
- package/src/entity-shape.ts +22 -5
- package/src/errors.ts +2 -0
- package/src/generate-snapshot.ts +3 -0
- package/src/generate.ts +9 -1
- package/src/index-ddl.ts +17 -6
- package/src/index-extension.ts +34 -0
- package/src/index-key-ddl.ts +159 -0
- package/src/index-plan.ts +38 -6
- package/src/index.ts +31 -0
- package/src/introspect-index.ts +110 -0
- package/src/introspect.ts +11 -52
- package/src/migration-lock-lint.ts +184 -0
- package/src/pin-statement.ts +154 -0
- package/src/pool-gate.ts +68 -13
- package/src/pool-pins.ts +74 -17
- package/src/replica-client.ts +15 -0
- package/src/rolling.ts +25 -12
- package/src/slow-statement-log.ts +103 -0
- package/src/snapshot-parse.ts +15 -0
- package/src/statement-excerpt.ts +50 -5
- package/src/table-storage.ts +222 -0
- package/src/transaction-settings.ts +9 -0
- package/src/transaction.ts +11 -1
package/src/pool-pins.ts
CHANGED
|
@@ -1,19 +1,31 @@
|
|
|
1
|
-
// Single responsibility: the unanswered-statement bound of ONE pinned connection
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
1
|
+
// Single responsibility: the unanswered-statement bound of ONE pinned connection — the
|
|
2
|
+
// `statement_timeout` in force on it, which its statements are swept against like any other's. A
|
|
3
|
+
// miss leaves the pin dead, never reused.
|
|
4
|
+
//
|
|
5
|
+
// The bound is the role's until a `set_config('statement_timeout', …)` or `SET [LOCAL]
|
|
6
|
+
// statement_timeout` it answered moves it; back to the role's at the transaction's end or a RESET,
|
|
7
|
+
// and back to what a SAVEPOINT saw on a ROLLBACK TO it.
|
|
5
8
|
|
|
9
|
+
import { pinStatement } from './pin-statement';
|
|
6
10
|
import type { SqlFragment } from './sql';
|
|
7
11
|
|
|
12
|
+
/** An open savepoint and the bound in force when it was taken: a ROLLBACK TO it restores that. */
|
|
13
|
+
interface Savepoint {
|
|
14
|
+
readonly name: string;
|
|
15
|
+
readonly boundMs: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
8
18
|
/** What one pin is bound by now. `boundMs` 0 is no bound, as the server reads it. */
|
|
9
19
|
export interface PinBound {
|
|
10
20
|
boundMs: number;
|
|
11
21
|
/** A statement on it went unanswered: nothing more is sent on this connection. */
|
|
12
22
|
dead: boolean;
|
|
23
|
+
/** Open savepoints, oldest first — the server's stack, as this pin answered it. */
|
|
24
|
+
readonly savepoints: Savepoint[];
|
|
13
25
|
}
|
|
14
26
|
|
|
15
27
|
export function pinBound(roleBoundMs: number): PinBound {
|
|
16
|
-
return { boundMs: roleBoundMs, dead: false };
|
|
28
|
+
return { boundMs: roleBoundMs, dead: false, savepoints: [] };
|
|
17
29
|
}
|
|
18
30
|
|
|
19
31
|
/** The sweep's deadline for the next statement on `pin`; `0` is none to judge. */
|
|
@@ -23,10 +35,8 @@ export function pinDeadlineMs(pin: PinBound, extraMs: number): number {
|
|
|
23
35
|
|
|
24
36
|
/** `setLocal`'s text (`local-settings.ts`), the framework's one writer, held by `pool-pins.test.ts`. */
|
|
25
37
|
const SET_CONFIG = 'select set_config($1, $2, true)';
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
/^\s*select\s+set_config\s*\(\s*'statement_timeout'\s*,\s*'([^']*)'\s*,\s*(?:true|false)\s*\)\s*;?\s*$/i;
|
|
29
|
-
const ENDS_TRANSACTION = /^\s*(?:commit|rollback|end|abort)(?:\s+(?:work|transaction))?\s*;?\s*$/i;
|
|
38
|
+
/** Longer than any `statement_timeout` value; a bind value is library input too. */
|
|
39
|
+
const TIMEOUT_VALUE_CHARS_MAX = 64;
|
|
30
40
|
const UNITS: ReadonlyMap<string, number> = new Map([
|
|
31
41
|
['us', 0.001],
|
|
32
42
|
['ms', 1],
|
|
@@ -39,7 +49,13 @@ const UNITS: ReadonlyMap<string, number> = new Map([
|
|
|
39
49
|
/** A `statement_timeout` value in Postgres' own grammar, as ms: a bare number is ms. */
|
|
40
50
|
export function timeoutValueMs(value: unknown): number | undefined {
|
|
41
51
|
if (typeof value !== 'string' && typeof value !== 'number') return undefined;
|
|
42
|
-
|
|
52
|
+
if (String(value).length > TIMEOUT_VALUE_CHARS_MAX) return undefined;
|
|
53
|
+
// Quotes and padding come off by hand, so the one pattern left has no two adjacent quantifiers
|
|
54
|
+
// that can both take a space.
|
|
55
|
+
let text = String(value).trim();
|
|
56
|
+
if (text.startsWith("'")) text = text.slice(1);
|
|
57
|
+
if (text.endsWith("'")) text = text.slice(0, -1);
|
|
58
|
+
const match = /^(\d+(?:\.\d+)?)\s*([a-z]*)$/i.exec(text.trim());
|
|
43
59
|
if (match === null) return undefined;
|
|
44
60
|
const scale = UNITS.get((match[2] ?? '').toLowerCase() || 'ms');
|
|
45
61
|
if (scale === undefined) return undefined;
|
|
@@ -53,16 +69,57 @@ export function boundSetBy(fragment: SqlFragment): number | undefined {
|
|
|
53
69
|
? timeoutValueMs(fragment.values[1])
|
|
54
70
|
: undefined;
|
|
55
71
|
}
|
|
56
|
-
const
|
|
57
|
-
return
|
|
72
|
+
const statement = pinStatement(fragment.text);
|
|
73
|
+
return statement?.kind === 'set' ? timeoutValueMs(statement.value) : undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The newest open savepoint called `name`, or -1: names may repeat, the newest one is meant. */
|
|
77
|
+
function savepointIndex(pin: PinBound, name: string): number {
|
|
78
|
+
return pin.savepoints.findLastIndex((savepoint) => savepoint.name === name);
|
|
58
79
|
}
|
|
59
80
|
|
|
60
|
-
/**
|
|
81
|
+
/**
|
|
82
|
+
* After `fragment` ANSWERED on `pin`: a refused statement moved nothing. ROLLBACK TO keeps its
|
|
83
|
+
* savepoint and drops every newer one; RELEASE drops it and every newer one, keeping what was set
|
|
84
|
+
* inside it. The statement is read once, by `pinStatement`.
|
|
85
|
+
*/
|
|
61
86
|
export function noteAnswered(pin: PinBound, fragment: SqlFragment, roleBoundMs: number): void {
|
|
62
|
-
if (
|
|
63
|
-
|
|
87
|
+
if (fragment.text === SET_CONFIG) {
|
|
88
|
+
const set = boundSetBy(fragment);
|
|
89
|
+
if (set !== undefined) pin.boundMs = set;
|
|
64
90
|
return;
|
|
65
91
|
}
|
|
66
|
-
const
|
|
67
|
-
|
|
92
|
+
const statement = pinStatement(fragment.text);
|
|
93
|
+
switch (statement?.kind) {
|
|
94
|
+
case 'end':
|
|
95
|
+
pin.boundMs = roleBoundMs;
|
|
96
|
+
pin.savepoints.length = 0;
|
|
97
|
+
return;
|
|
98
|
+
case 'role-bound':
|
|
99
|
+
pin.boundMs = roleBoundMs;
|
|
100
|
+
return;
|
|
101
|
+
case 'set': {
|
|
102
|
+
const set = timeoutValueMs(statement.value);
|
|
103
|
+
if (set !== undefined) pin.boundMs = set;
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
case 'savepoint':
|
|
107
|
+
pin.savepoints.push({ name: statement.name, boundMs: pin.boundMs });
|
|
108
|
+
return;
|
|
109
|
+
case 'rollback-to': {
|
|
110
|
+
const at = savepointIndex(pin, statement.name);
|
|
111
|
+
const savepoint = pin.savepoints[at];
|
|
112
|
+
if (savepoint === undefined) return;
|
|
113
|
+
pin.boundMs = savepoint.boundMs;
|
|
114
|
+
pin.savepoints.length = at + 1;
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
case 'release': {
|
|
118
|
+
const at = savepointIndex(pin, statement.name);
|
|
119
|
+
if (at !== -1) pin.savepoints.length = at;
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
default:
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
68
125
|
}
|
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/rolling.ts
CHANGED
|
@@ -75,9 +75,10 @@ export interface RollingUnsafeStatement {
|
|
|
75
75
|
/**
|
|
76
76
|
* Words, quoted identifiers and punctuation, with comments, literals and dollar bodies gone. Why
|
|
77
77
|
* not `stripSqlNoise`, which `destructive.ts` reads: it blanks a quoted identifier too, and this
|
|
78
|
-
* rail has to say WHICH column.
|
|
78
|
+
* rail has to say WHICH column. Exported with the readers below for `migration-lock-lint.ts`: two
|
|
79
|
+
* lexical rails over one token stream, never two tokenizers.
|
|
79
80
|
*/
|
|
80
|
-
function tokensOf(statement: string): readonly string[] {
|
|
81
|
+
export function tokensOf(statement: string): readonly string[] {
|
|
81
82
|
let text = '';
|
|
82
83
|
let index = 0;
|
|
83
84
|
while (index < statement.length) {
|
|
@@ -94,30 +95,42 @@ function tokensOf(statement: string): readonly string[] {
|
|
|
94
95
|
return text.match(/"(?:[^"]|"")*"|[A-Za-z_][\w$]*|\S/g) ?? [];
|
|
95
96
|
}
|
|
96
97
|
|
|
97
|
-
const isWord = (lexeme: string | undefined, word: string): boolean =>
|
|
98
|
+
export const isWord = (lexeme: string | undefined, word: string): boolean =>
|
|
98
99
|
lexeme !== undefined && !lexeme.startsWith('"') && lexeme.toLowerCase() === word;
|
|
99
100
|
|
|
100
101
|
/** What Postgres folds a token to: a quoted one keeps its case, a bare one lowers. */
|
|
101
|
-
const nameOf = (token: string): string =>
|
|
102
|
+
export const nameOf = (token: string): string =>
|
|
102
103
|
token.startsWith('"') ? token.slice(1, -1).replaceAll('""', '"') : token.toLowerCase();
|
|
103
104
|
|
|
104
|
-
/** `
|
|
105
|
-
function
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
105
|
+
/** `[schema.]name` from `at`, as the last part folded and where the tokens after it start. */
|
|
106
|
+
export function qualifiedNameAt(
|
|
107
|
+
tokens: readonly string[],
|
|
108
|
+
start: number,
|
|
109
|
+
): { name: string; next: number } | undefined {
|
|
110
|
+
let at = start;
|
|
110
111
|
let name = tokens[at];
|
|
111
112
|
at += 1;
|
|
112
113
|
while (tokens[at] === '.') {
|
|
113
114
|
name = tokens[at + 1];
|
|
114
115
|
at += 2;
|
|
115
116
|
}
|
|
116
|
-
return name === undefined ? undefined : {
|
|
117
|
+
return name === undefined ? undefined : { name: nameOf(name), next: at };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** `alter table [if exists] [only] [schema.]t`, as the table and where its subcommands start. */
|
|
121
|
+
export function alteredTable(
|
|
122
|
+
tokens: readonly string[],
|
|
123
|
+
): { table: string; next: number } | undefined {
|
|
124
|
+
if (!isWord(tokens[0], 'alter') || !isWord(tokens[1], 'table')) return undefined;
|
|
125
|
+
let at = 2;
|
|
126
|
+
if (isWord(tokens[at], 'if') && isWord(tokens[at + 1], 'exists')) at += 2;
|
|
127
|
+
if (isWord(tokens[at], 'only')) at += 1;
|
|
128
|
+
const named = qualifiedNameAt(tokens, at);
|
|
129
|
+
return named === undefined ? undefined : { table: named.name, next: named.next };
|
|
117
130
|
}
|
|
118
131
|
|
|
119
132
|
/** Top-level commas only: `add constraint … (a, b)` is one subcommand. */
|
|
120
|
-
function subcommands(tokens: readonly string[]): readonly (readonly string[])[] {
|
|
133
|
+
export function subcommands(tokens: readonly string[]): readonly (readonly string[])[] {
|
|
121
134
|
const parts: string[][] = [[]];
|
|
122
135
|
let depth = 0;
|
|
123
136
|
for (const token of tokens) {
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// Single responsibility: one grep-able `warn` line per slow statement, from the `db.statement` bus
|
|
2
|
+
// event — the normalised shape (never a bound value), duration, rows and, through the logger's
|
|
3
|
+
// context fields, the request/job ids. Sampled to one line per shape per window, memo bounded.
|
|
4
|
+
// The runtime decides whether it runs (500 ms in production, off in tests); this is the mechanism.
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
type DbStatementEvent,
|
|
8
|
+
finiteOption,
|
|
9
|
+
isUltimateError,
|
|
10
|
+
logger,
|
|
11
|
+
SEMCONV,
|
|
12
|
+
SEMCONV_VALUES,
|
|
13
|
+
subscribe,
|
|
14
|
+
} from '@ultimat3/core';
|
|
15
|
+
import { statementVerb } from './statement-shape';
|
|
16
|
+
|
|
17
|
+
/** The production default the runtime passes as `thresholdMs`. */
|
|
18
|
+
export const SLOW_STATEMENT_THRESHOLD_MS = 500;
|
|
19
|
+
/** One line per shape per this long; the rest are counted onto the next line as `suppressed`. */
|
|
20
|
+
export const SLOW_STATEMENT_WINDOW_MS = 10_000;
|
|
21
|
+
/** Shapes remembered at once. A process with more distinct slow shapes forgets the oldest first. */
|
|
22
|
+
export const SLOW_STATEMENT_SHAPES_MAX = 512;
|
|
23
|
+
/** A bulk insert's text can run to megabytes; a log line carries its head. */
|
|
24
|
+
const SHAPE_CHARS_MAX = 2_000;
|
|
25
|
+
const WHITESPACE = /\s+/g;
|
|
26
|
+
|
|
27
|
+
export interface SlowStatementLogOptions {
|
|
28
|
+
/** Statements at or over this many ms log. `0` (or less) is off: nothing subscribes. */
|
|
29
|
+
readonly thresholdMs: number;
|
|
30
|
+
readonly windowMs?: number | undefined;
|
|
31
|
+
/** Monotonic ms, for the sampling window only. Defaults to `performance.now`. */
|
|
32
|
+
readonly now?: (() => number) | undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface Seen {
|
|
36
|
+
readonly at: number;
|
|
37
|
+
suppressed: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The text with whitespace collapsed, capped: already `$n`-parameterised by `sql()`. */
|
|
41
|
+
function shapeOf(text: string): string {
|
|
42
|
+
const shape = text.replace(WHITESPACE, ' ').trim();
|
|
43
|
+
return shape.length > SHAPE_CHARS_MAX ? `${shape.slice(0, SHAPE_CHARS_MAX - 3)}...` : shape;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function lineOf(
|
|
47
|
+
event: DbStatementEvent,
|
|
48
|
+
shape: string,
|
|
49
|
+
suppressed: number,
|
|
50
|
+
): Record<string, unknown> {
|
|
51
|
+
const verb = statementVerb(event.text);
|
|
52
|
+
const attribution = event.attribution;
|
|
53
|
+
return {
|
|
54
|
+
[SEMCONV.dbSystemName]: SEMCONV_VALUES.dbSystemPostgres,
|
|
55
|
+
[SEMCONV.dbQueryText]: shape,
|
|
56
|
+
...(verb === '' ? {} : { [SEMCONV.dbOperationName]: verb.toUpperCase() }),
|
|
57
|
+
[SEMCONV.dbResponseReturnedRows]: event.rows,
|
|
58
|
+
durationMs: Math.round(event.durationMs),
|
|
59
|
+
...(attribution === undefined
|
|
60
|
+
? {}
|
|
61
|
+
: { attribution: `${attribution.entity}.${attribution.op}` }),
|
|
62
|
+
...(event.error === undefined
|
|
63
|
+
? {}
|
|
64
|
+
: { [SEMCONV.errorType]: isUltimateError(event.error) ? event.error.code : '_OTHER' }),
|
|
65
|
+
...(suppressed === 0 ? {} : { suppressed }),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Subscribe the slow-statement line. Returns the unsubscribe — wire it into the drain. Bound values
|
|
71
|
+
* never reach the line: the event's `values` is not read at all.
|
|
72
|
+
*/
|
|
73
|
+
export function slowStatementLog(options: SlowStatementLogOptions): () => void {
|
|
74
|
+
const { thresholdMs } = options;
|
|
75
|
+
if (!(thresholdMs > 0)) return () => undefined;
|
|
76
|
+
const windowMs = finiteOption(
|
|
77
|
+
'slowStatementLog',
|
|
78
|
+
'windowMs',
|
|
79
|
+
options.windowMs ?? SLOW_STATEMENT_WINDOW_MS,
|
|
80
|
+
);
|
|
81
|
+
const now = options.now ?? (() => performance.now());
|
|
82
|
+
// Insertion order is last-logged order: a re-log deletes and re-inserts, so the first key is
|
|
83
|
+
// always the shape that logged longest ago — the one eviction drops.
|
|
84
|
+
const seen = new Map<string, Seen>();
|
|
85
|
+
|
|
86
|
+
return subscribe('db.statement', ({ payload }) => {
|
|
87
|
+
if (payload.durationMs < thresholdMs) return;
|
|
88
|
+
const shape = shapeOf(payload.text);
|
|
89
|
+
const at = now();
|
|
90
|
+
const last = seen.get(shape);
|
|
91
|
+
if (last !== undefined && at - last.at < windowMs) {
|
|
92
|
+
last.suppressed += 1;
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
seen.delete(shape);
|
|
96
|
+
if (seen.size >= SLOW_STATEMENT_SHAPES_MAX) {
|
|
97
|
+
const oldest = seen.keys().next();
|
|
98
|
+
if (oldest.done !== true) seen.delete(oldest.value);
|
|
99
|
+
}
|
|
100
|
+
seen.set(shape, { at, suppressed: 0 });
|
|
101
|
+
logger.warn('db.statement.slow', lineOf(payload, shape, last?.suppressed ?? 0));
|
|
102
|
+
});
|
|
103
|
+
}
|
package/src/snapshot-parse.ts
CHANGED
|
@@ -33,6 +33,10 @@ const interval = (value: unknown): value is PartitionInterval => INTERVALS.inclu
|
|
|
33
33
|
const order = (value: unknown): value is 'asc' | 'desc' | null =>
|
|
34
34
|
value === null || value === 'asc' || value === 'desc';
|
|
35
35
|
|
|
36
|
+
/** One direction per key, each of the closed set. */
|
|
37
|
+
const directions = (value: unknown): value is readonly ('asc' | 'desc' | null)[] =>
|
|
38
|
+
Array.isArray(value) && value.every(order);
|
|
39
|
+
|
|
36
40
|
function column(value: unknown): ColumnDescription | undefined {
|
|
37
41
|
if (!isRow(value)) return undefined;
|
|
38
42
|
const { name, dataType, nullable, default: fallback, position, generated, retired } = value;
|
|
@@ -68,6 +72,7 @@ function check(value: unknown): CheckDescription | undefined {
|
|
|
68
72
|
function index(value: unknown): IndexDescription | undefined {
|
|
69
73
|
if (!isRow(value)) return undefined;
|
|
70
74
|
const { name, columns, unique, primary, where, order: direction, using } = value;
|
|
75
|
+
const { expression, orders, include, operatorClass } = value;
|
|
71
76
|
if (!str(name) || !strings(columns) || !bool(unique) || !bool(primary)) return undefined;
|
|
72
77
|
// Written by 1.2.0 onwards. A sidecar from before it carries neither, and the total, ascending
|
|
73
78
|
// reading is what that generation actually emitted — so an older file stays readable rather
|
|
@@ -80,6 +85,12 @@ function index(value: unknown): IndexDescription | undefined {
|
|
|
80
85
|
// method and the fix, not here, where it would discard the whole snapshot without saying which
|
|
81
86
|
// field was wrong. Absent stays absent: `indexMethodOf` reads it as the btree it always was.
|
|
82
87
|
if (!(using === undefined || str(using))) return undefined;
|
|
88
|
+
// The four key parts: each absent or well-formed, never dropped. Dropped here, `indexShape` read
|
|
89
|
+
// the recorded index as the plain one and every `x db gen` rebuilt it — `generated`'s old hole.
|
|
90
|
+
if (!(expression === undefined || str(expression))) return undefined;
|
|
91
|
+
if (!(orders === undefined || directions(orders))) return undefined;
|
|
92
|
+
if (!(include === undefined || strings(include))) return undefined;
|
|
93
|
+
if (!(operatorClass === undefined || str(operatorClass))) return undefined;
|
|
83
94
|
return {
|
|
84
95
|
name,
|
|
85
96
|
columns,
|
|
@@ -88,6 +99,10 @@ function index(value: unknown): IndexDescription | undefined {
|
|
|
88
99
|
where: where === undefined ? null : where,
|
|
89
100
|
order: direction === undefined ? null : direction,
|
|
90
101
|
...(using === undefined ? {} : { using }),
|
|
102
|
+
...(expression === undefined ? {} : { expression }),
|
|
103
|
+
...(orders === undefined ? {} : { orders }),
|
|
104
|
+
...(include === undefined ? {} : { include }),
|
|
105
|
+
...(operatorClass === undefined ? {} : { operatorClass }),
|
|
91
106
|
};
|
|
92
107
|
}
|
|
93
108
|
|
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
|
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
// Single responsibility: a framework-owned table's storage parameters (`fillfactor`, `unlogged`) as
|
|
2
|
+
// ONE declared value — rendered into its `create table`, re-applied to an existing table by
|
|
3
|
+
// idempotent `alter`s at framework-schema apply, and compared against `pg_class` by drift. Before
|
|
4
|
+
// it, framework DDL was fixed strings and nothing could state either parameter.
|
|
5
|
+
//
|
|
6
|
+
// The API, as a framework package uses it (`@ultimat3/http`'s `x_rate_limit`, `@ultimat3/jobs`):
|
|
7
|
+
//
|
|
8
|
+
// import { tableDdl, tableStorage } from '@ultimat3/db';
|
|
9
|
+
// const RATE_LIMIT_STORAGE = tableStorage('x_rate_limit', { fillfactor: 70, unlogged: true });
|
|
10
|
+
// export const SQL_RATE_LIMIT_TABLE = `
|
|
11
|
+
// ${tableDdl(RATE_LIMIT_STORAGE, `
|
|
12
|
+
// key text primary key,
|
|
13
|
+
// tokens double precision not null`)}
|
|
14
|
+
// drop index if exists x_rate_limit_updated_at_idx;
|
|
15
|
+
// `;
|
|
16
|
+
//
|
|
17
|
+
// tableStorageDrift(storage, catalogTable) — pure: declared vs one `CatalogTable`
|
|
18
|
+
// readTableStorageDrift(client, [storage, …]) — one `pg_class` read, every difference
|
|
19
|
+
|
|
20
|
+
import type { DbClient } from './client';
|
|
21
|
+
import { psqlCommand } from './dependent-view';
|
|
22
|
+
import { DbError } from './errors';
|
|
23
|
+
import { sql } from './sql';
|
|
24
|
+
|
|
25
|
+
export interface TableStorageOptions {
|
|
26
|
+
/** 10–100, Postgres' own range. Left out: the table's fillfactor is not this declaration's. */
|
|
27
|
+
readonly fillfactor?: number;
|
|
28
|
+
/** `true` unlogged, `false` logged (stated, e.g. a table that must survive a crash). Left out: neither. */
|
|
29
|
+
readonly unlogged?: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface TableStorage {
|
|
33
|
+
readonly table: string;
|
|
34
|
+
readonly fillfactor: number | undefined;
|
|
35
|
+
readonly unlogged: boolean | undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Bare lower-case names only: every framework table is spelled that way, the DDL constants splice
|
|
40
|
+
* the name unquoted, and `framework-schema.test.ts` reads the created names back with that pattern.
|
|
41
|
+
*/
|
|
42
|
+
const FRAMEWORK_NAME = /^[a-z_][a-z0-9_]{0,62}$/;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* `X_SQL_UNSAFE`, the precedent `indexMethodInvalid` set: both values are SPLICED into DDL text —
|
|
46
|
+
* `with (fillfactor = …)` takes no parameter — so an operand TypeScript never saw is an injection.
|
|
47
|
+
*/
|
|
48
|
+
const storageInvalid = (table: string, what: string): DbError =>
|
|
49
|
+
new DbError({
|
|
50
|
+
code: 'X_SQL_UNSAFE',
|
|
51
|
+
cause: `tableStorage(${JSON.stringify(table)}): ${what}`,
|
|
52
|
+
fix: "tableStorage('x_rate_limit', { fillfactor: 70, unlogged: true }) # a bare lower-case name, an integer fillfactor 10-100",
|
|
53
|
+
meta: { table },
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
/** The declaration, validated once where it is made — a module constant, so a bad one fails at import. */
|
|
57
|
+
export function tableStorage(table: string, options: TableStorageOptions): TableStorage {
|
|
58
|
+
if (!FRAMEWORK_NAME.test(table)) {
|
|
59
|
+
throw storageInvalid(table, 'the table name is not a bare lower-case identifier');
|
|
60
|
+
}
|
|
61
|
+
const { fillfactor } = options;
|
|
62
|
+
if (
|
|
63
|
+
fillfactor !== undefined &&
|
|
64
|
+
!(Number.isInteger(fillfactor) && fillfactor >= 10 && fillfactor <= 100)
|
|
65
|
+
) {
|
|
66
|
+
throw storageInvalid(
|
|
67
|
+
table,
|
|
68
|
+
`fillfactor ${String(fillfactor)} is not an integer from 10 to 100`,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
return Object.freeze({ table, fillfactor, unlogged: options.unlogged });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The statements that bring an EXISTING table to the declaration — what `create … if not exists`
|
|
76
|
+
* cannot, since it does nothing to a table that is there. Each is idempotent: `set (fillfactor)`
|
|
77
|
+
* rewrites one `pg_class` row under `SHARE UPDATE EXCLUSIVE`, and `set unlogged` on a table that
|
|
78
|
+
* already is one returns without a rewrite. That last one still takes `ACCESS EXCLUSIVE`, held to
|
|
79
|
+
* the end of the apply transaction; the migrate role's `lock_timeout` bounds the wait.
|
|
80
|
+
*/
|
|
81
|
+
export function storageAlters(storage: TableStorage): readonly string[] {
|
|
82
|
+
const alters: string[] = [];
|
|
83
|
+
if (storage.fillfactor !== undefined) {
|
|
84
|
+
alters.push(`alter table ${storage.table} set (fillfactor = ${String(storage.fillfactor)})`);
|
|
85
|
+
}
|
|
86
|
+
if (storage.unlogged !== undefined) {
|
|
87
|
+
alters.push(`alter table ${storage.table} set ${storage.unlogged ? 'unlogged' : 'logged'}`);
|
|
88
|
+
}
|
|
89
|
+
return alters;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Leading newlines and trailing whitespace off, in one linear pass each: `trimEnd()` and an index
|
|
94
|
+
* walk, never `/\s+$/g`, which retries at every space of an inner run (js/polynomial-redos).
|
|
95
|
+
*/
|
|
96
|
+
function columnBody(columns: string): string {
|
|
97
|
+
let start = 0;
|
|
98
|
+
while (columns.charCodeAt(start) === 10) start += 1;
|
|
99
|
+
return columns.slice(start).trimEnd();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* `create [unlogged] table if not exists <name> (<columns>) [with (fillfactor = n)];` then the
|
|
104
|
+
* alters, each `;`-terminated so the boot's split on `;` sees one statement apiece. `columns` is the
|
|
105
|
+
* body between the parentheses, a fixed constant with no `;` in it, as every framework DDL is.
|
|
106
|
+
*/
|
|
107
|
+
export function tableDdl(storage: TableStorage, columns: string): string {
|
|
108
|
+
const head = storage.unlogged === true ? 'create unlogged table' : 'create table';
|
|
109
|
+
const options =
|
|
110
|
+
storage.fillfactor === undefined ? '' : ` with (fillfactor = ${String(storage.fillfactor)})`;
|
|
111
|
+
const create = `${head} if not exists ${storage.table} (\n${columnBody(columns)}\n)${options};`;
|
|
112
|
+
return [create, ...storageAlters(storage).map((alter) => `${alter};`)].join('\n');
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** What the catalog holds for one table — `CatalogTable` satisfies it. `options` is `reloptions` joined. */
|
|
116
|
+
export interface LiveTableStorage {
|
|
117
|
+
readonly unlogged: boolean;
|
|
118
|
+
readonly options: string | null;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export interface TableStorageDifference {
|
|
122
|
+
readonly table: string;
|
|
123
|
+
readonly parameter: 'table' | 'persistence' | 'fillfactor';
|
|
124
|
+
readonly declared: string;
|
|
125
|
+
readonly live: string;
|
|
126
|
+
/** The statement that converges it, as SQL — `null` for a missing table, which `x db migrate` creates. */
|
|
127
|
+
readonly statement: string | null;
|
|
128
|
+
/** A command that runs as written: `psql … -c '<statement>'`, or `x db migrate`. */
|
|
129
|
+
readonly fix: string;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** `fillfactor=70, autovacuum_enabled=false` → `70`; absent → `null` (the server default, 100). */
|
|
133
|
+
const liveFillfactor = (options: string | null): string | null => {
|
|
134
|
+
for (const option of (options ?? '').split(',')) {
|
|
135
|
+
const [key, value] = option.trim().split('=');
|
|
136
|
+
if (key === 'fillfactor' && value !== undefined) return value;
|
|
137
|
+
}
|
|
138
|
+
return null;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The statement and the line that runs it. `psqlCommand` quotes it as one shell word, and the name
|
|
143
|
+
* inside is the bare lower-case identifier `tableStorage` admitted, so nothing in it is shell-active.
|
|
144
|
+
*/
|
|
145
|
+
const converge = (alter: string | undefined): { statement: string; fix: string } => {
|
|
146
|
+
const statement = `${alter ?? ''};`;
|
|
147
|
+
return { statement, fix: `${psqlCommand(statement)} # then x db migrate, which re-checks` };
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
/** Only what the declaration states is compared: a parameter left out is not this value's to judge. */
|
|
151
|
+
export function tableStorageDrift(
|
|
152
|
+
storage: TableStorage,
|
|
153
|
+
live: LiveTableStorage | undefined,
|
|
154
|
+
): readonly TableStorageDifference[] {
|
|
155
|
+
const { table } = storage;
|
|
156
|
+
if (live === undefined) {
|
|
157
|
+
return [
|
|
158
|
+
{
|
|
159
|
+
table,
|
|
160
|
+
parameter: 'table',
|
|
161
|
+
declared: 'present',
|
|
162
|
+
live: 'absent',
|
|
163
|
+
statement: null,
|
|
164
|
+
fix: 'x db migrate',
|
|
165
|
+
},
|
|
166
|
+
];
|
|
167
|
+
}
|
|
168
|
+
const alters = storageAlters(storage);
|
|
169
|
+
const differences: TableStorageDifference[] = [];
|
|
170
|
+
if (storage.unlogged !== undefined && storage.unlogged !== live.unlogged) {
|
|
171
|
+
const persistence = (unlogged: boolean): string => (unlogged ? 'unlogged' : 'logged');
|
|
172
|
+
differences.push({
|
|
173
|
+
table,
|
|
174
|
+
parameter: 'persistence',
|
|
175
|
+
declared: persistence(storage.unlogged),
|
|
176
|
+
live: persistence(live.unlogged),
|
|
177
|
+
...converge(alters.find((alter) => /set (un)?logged$/.test(alter))),
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
const fillfactor = liveFillfactor(live.options);
|
|
181
|
+
if (storage.fillfactor !== undefined && String(storage.fillfactor) !== fillfactor) {
|
|
182
|
+
differences.push({
|
|
183
|
+
table,
|
|
184
|
+
parameter: 'fillfactor',
|
|
185
|
+
declared: String(storage.fillfactor),
|
|
186
|
+
live: fillfactor ?? 'default (100)',
|
|
187
|
+
...converge(alters.find((alter) => alter.includes('fillfactor'))),
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
return differences;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
interface StorageRow {
|
|
194
|
+
readonly name: string;
|
|
195
|
+
readonly persistence: string;
|
|
196
|
+
readonly options: string | null;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Every declaration against the catalog, in ONE read — the reading `catalog-relations.ts` does
|
|
201
|
+
* (`relpersistence`, `reloptions` joined by `, `), narrowed to the named tables of `current_schema()`.
|
|
202
|
+
*/
|
|
203
|
+
export async function readTableStorageDrift(
|
|
204
|
+
client: DbClient,
|
|
205
|
+
storages: readonly TableStorage[],
|
|
206
|
+
): Promise<readonly TableStorageDifference[]> {
|
|
207
|
+
if (storages.length === 0) return [];
|
|
208
|
+
const rows = await client.query<StorageRow>(sql`
|
|
209
|
+
select c.relname as name, c.relpersistence as persistence,
|
|
210
|
+
array_to_string(c.reloptions, ', ') as options
|
|
211
|
+
from pg_class c join pg_namespace n on n.oid = c.relnamespace
|
|
212
|
+
where n.nspname = current_schema() and c.relkind in ('r', 'p')
|
|
213
|
+
and c.relname = any(${storages.map((storage) => storage.table)}::text[])`);
|
|
214
|
+
const live = new Map(rows.map((row) => [row.name, row]));
|
|
215
|
+
return storages.flatMap((storage) => {
|
|
216
|
+
const row = live.get(storage.table);
|
|
217
|
+
return tableStorageDrift(
|
|
218
|
+
storage,
|
|
219
|
+
row === undefined ? undefined : { unlogged: row.persistence === 'u', options: row.options },
|
|
220
|
+
);
|
|
221
|
+
});
|
|
222
|
+
}
|