@ultimat3/db 31.7.0 → 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.
@@ -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
+ }