@ultimat3/db 31.6.1 → 31.8.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 +32 -31
- package/README.md +4 -0
- package/package.json +2 -2
- package/src/client.ts +2 -2
- 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 +27 -5
- package/src/errors.ts +2 -0
- package/src/generate-history.ts +8 -2
- 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 +29 -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/rolling.ts +25 -12
- package/src/slow-statement-log.ts +103 -0
- package/src/snapshot-parse.ts +15 -0
- package/src/table-storage.ts +222 -0
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
|
|
|
@@ -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
|
+
}
|