@ultimat3/db 31.24.0 → 31.25.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 +2 -2
- package/README.md +1 -1
- package/package.json +2 -2
- package/src/index.ts +5 -13
- package/src/table-autovacuum.ts +71 -0
- package/src/table-storage-drift.ts +124 -0
- package/src/table-storage.ts +32 -120
package/CLAUDE.md
CHANGED
|
@@ -196,8 +196,8 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
|
|
|
196
196
|
`missing-check`'s are one `psql -c` too — `repair()`, schema-scoped off `public`).
|
|
197
197
|
- `introspectSchema()` reads index keys in `indkey` order and a key's two column lists together
|
|
198
198
|
(`unnest(a, b) with ordinality`); `introspect-embedded.test.ts`.
|
|
199
|
-
- **`table-storage.ts`**: a framework table's `fillfactor`/`unlogged
|
|
200
|
-
|
|
199
|
+
- **`table-storage.ts`**: a framework table's `fillfactor`/`unlogged`/`autovacuum`
|
|
200
|
+
(`table-autovacuum.ts`), one value; `tableDdl`: create + alters; `table-storage-drift.ts`: `pg_class`.
|
|
201
201
|
- **`appTables()`** excludes all of `x_` for drift; `introspectSchema()` only `x_migrations`.
|
|
202
202
|
`nonAppRelations` (`app-relation.ts`): extension-owned, views, matviews, foreign tables,
|
|
203
203
|
partitions — always excluded.
|
package/README.md
CHANGED
|
@@ -46,7 +46,7 @@ await withTransaction(async (tx) => {
|
|
|
46
46
|
| `replicatedClient()` / `ReplicaStats` / `REPLICA_URL_ENV` | `As of 2026-08-24`: one `DbClient` over a primary and a standby. `baseClient()` builds one when `DATABASE_REPLICA_URL` is set and the single-pool client when it is not |
|
|
47
47
|
| `INDEX_METHODS` / `IndexMethod` / `indexMethodOf()` / `indexMethodSql()` / `declaredMethod()` | `As of 2026-08-24`: an index's access method — `btree` or `gin`, closed. Absent is `btree`, the live side is read open (whatever `pg_am` said), and the DDL literal is re-derived from the set rather than spliced from the input |
|
|
48
48
|
| `IndexDescriptionLike.expression` / `.orders` / `.include` / `.operatorClass` · `INDEX_OPERATOR_CLASSES` / `requiredExtension()` | `As of 2026-11-12`: the index parts past a plain column list — one expression key (`unique (lower(email))`), a direction per key, INCLUDE payload columns (btree), `gin_trgm_ops` (gin; `requiredExtension()` answers `pg_trgm`). Each optional, absent hashes and renders as before; drift compares each, an expression by presence only |
|
|
49
|
-
| `tableStorage(table, { fillfactor?, unlogged? })` / `tableDdl()` / `storageAlters()` / `tableStorageDrift()` / `readTableStorageDrift()` | `As of 2026-11-
|
|
49
|
+
| `tableStorage(table, { fillfactor?, unlogged?, autovacuum? })` / `tableDdl()` / `storageAlters()` / `tableStorageDrift()` / `readTableStorageDrift()` | `As of 2026-11-14`: a **framework-owned** table's storage parameters as one value; `autovacuum` (`TableAutovacuum`: `vacuumThreshold`, `vacuumScaleFactor`, `analyzeThreshold`, `analyzeScaleFactor`) states when autovacuum visits it. `tableDdl(storage, columns)` renders `create [unlogged] table if not exists … with (fillfactor = n, autovacuum_… = v)` plus the idempotent `alter`s that bring an existing table to it at framework-schema apply; drift reads `relpersistence`/`reloptions`, each difference with its `alter` as `fix`. A bad name, fillfactor or autovacuum value is `X_SQL_UNSAFE` at import |
|
|
50
50
|
| `slowStatementLog({ thresholdMs })` | one `warn` `db.statement.slow` line per slow statement shape per 10 s, with request/trace ids and no bind values; returns the unsubscribe |
|
|
51
51
|
| `lockHeavyStatements()` / `migrationLockHeavy()` / `LOCK_HEAVY_MARKER` / `LOCK_HEAVY_SINCE` | `X_MIGRATION_LOCK_HEAVY`: `set not null` with no prior validate, non-concurrent `create index` on an existing table; `-- lock-heavy: true` to admit; judges ids > `LOCK_HEAVY_SINCE` |
|
|
52
52
|
| `isPlainRead()` | `As of 2026-08-24`: whether a statement may leave the primary. An allow-list — everything it cannot vouch for is the primary's |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/db",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.25.0",
|
|
4
4
|
"description": "Postgres access, transactions, migrations and drift detection",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"test": "bun test"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@ultimat3/core": "31.
|
|
48
|
+
"@ultimat3/core": "31.25.0"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
51
51
|
"@electric-sql/pglite": ">=0.5.0"
|
package/src/index.ts
CHANGED
|
@@ -281,19 +281,11 @@ export type { StatementBoundOptions } from './statement-bound';
|
|
|
281
281
|
export { withStatementTimeout } from './statement-bound';
|
|
282
282
|
export { statementFingerprint, statementKind, statementVerb } from './statement-shape';
|
|
283
283
|
export { statementsOf } from './statement-split';
|
|
284
|
-
export type {
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
} from './table-storage';
|
|
290
|
-
export {
|
|
291
|
-
readTableStorageDrift,
|
|
292
|
-
storageAlters,
|
|
293
|
-
tableDdl,
|
|
294
|
-
tableStorage,
|
|
295
|
-
tableStorageDrift,
|
|
296
|
-
} from './table-storage';
|
|
284
|
+
export type { AutovacuumParameter, TableAutovacuum } from './table-autovacuum';
|
|
285
|
+
export type { TableStorage, TableStorageOptions } from './table-storage';
|
|
286
|
+
export { storageAlters, tableDdl, tableStorage } from './table-storage';
|
|
287
|
+
export type { LiveTableStorage, TableStorageDifference } from './table-storage-drift';
|
|
288
|
+
export { readTableStorageDrift, tableStorageDrift } from './table-storage-drift';
|
|
297
289
|
export {
|
|
298
290
|
completeTransaction,
|
|
299
291
|
currentTx,
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Single responsibility: the autovacuum half of a `tableStorage()` declaration — the four trigger
|
|
2
|
+
// parameters a small, hot framework table states instead of Postgres' defaults (50 rows plus 20% of
|
|
3
|
+
// the table, more dead rows than such a table holds live ones), validated, rendered and read back.
|
|
4
|
+
|
|
5
|
+
/** When autovacuum visits a table, in Postgres' own terms. Each left out is not this value's. */
|
|
6
|
+
export interface TableAutovacuum {
|
|
7
|
+
/** `autovacuum_vacuum_threshold`: dead rows before a vacuum, before the scale factor. */
|
|
8
|
+
readonly vacuumThreshold?: number;
|
|
9
|
+
/** `autovacuum_vacuum_scale_factor`: the fraction of the table added to the threshold. */
|
|
10
|
+
readonly vacuumScaleFactor?: number;
|
|
11
|
+
/** `autovacuum_analyze_threshold`. */
|
|
12
|
+
readonly analyzeThreshold?: number;
|
|
13
|
+
/** `autovacuum_analyze_scale_factor`. */
|
|
14
|
+
readonly analyzeScaleFactor?: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Declaration key → storage parameter, in the order every rendering uses. */
|
|
18
|
+
const PARAMETERS = {
|
|
19
|
+
vacuumThreshold: 'autovacuum_vacuum_threshold',
|
|
20
|
+
vacuumScaleFactor: 'autovacuum_vacuum_scale_factor',
|
|
21
|
+
analyzeThreshold: 'autovacuum_analyze_threshold',
|
|
22
|
+
analyzeScaleFactor: 'autovacuum_analyze_scale_factor',
|
|
23
|
+
} as const;
|
|
24
|
+
|
|
25
|
+
export type AutovacuumParameter = (typeof PARAMETERS)[keyof typeof PARAMETERS];
|
|
26
|
+
|
|
27
|
+
const INT4_MAX = 2 ** 31 - 1;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Why a declaration may not be spliced into DDL, or `undefined`. Postgres' own ranges: a threshold
|
|
31
|
+
* is an integer from 0 to `INT_MAX`, a scale factor a finite number from 0 to 100.
|
|
32
|
+
*/
|
|
33
|
+
export function autovacuumProblem(autovacuum: TableAutovacuum): string | undefined {
|
|
34
|
+
for (const [key, value] of Object.entries(autovacuum)) {
|
|
35
|
+
if (!Object.hasOwn(PARAMETERS, key))
|
|
36
|
+
return `autovacuum.${key} is not a parameter this declaration knows`;
|
|
37
|
+
if (typeof value !== 'number') return `autovacuum.${key} is not a number`;
|
|
38
|
+
const threshold = key.endsWith('Threshold');
|
|
39
|
+
const fits = threshold
|
|
40
|
+
? Number.isInteger(value) && value >= 0 && value <= INT4_MAX
|
|
41
|
+
: Number.isFinite(value) && value >= 0 && value <= 100;
|
|
42
|
+
if (!fits) {
|
|
43
|
+
return `autovacuum.${key} ${String(value)} is not ${threshold ? 'an integer from 0 to 2147483647' : 'a number from 0 to 100'}`;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The declared parameters as `[name, value]`, in rendering order. */
|
|
50
|
+
export function autovacuumEntries(
|
|
51
|
+
autovacuum: TableAutovacuum | undefined,
|
|
52
|
+
): readonly (readonly [AutovacuumParameter, number])[] {
|
|
53
|
+
if (autovacuum === undefined) return [];
|
|
54
|
+
return Object.entries(PARAMETERS).flatMap(([key, name]) => {
|
|
55
|
+
const value = autovacuum[key as keyof TableAutovacuum];
|
|
56
|
+
return value === undefined ? [] : [[name, value] as const];
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** `name = value` for a `with (...)` or `set (...)` list. */
|
|
61
|
+
export const autovacuumSettings = (autovacuum: TableAutovacuum | undefined): readonly string[] =>
|
|
62
|
+
autovacuumEntries(autovacuum).map(([name, value]) => `${name} = ${String(value)}`);
|
|
63
|
+
|
|
64
|
+
/** One option off `reloptions` joined by `, ` (`fillfactor=70, autovacuum_enabled=false`), or `null`. */
|
|
65
|
+
export function reloption(options: string | null, key: string): string | null {
|
|
66
|
+
for (const option of (options ?? '').split(',')) {
|
|
67
|
+
const [name, value] = option.trim().split('=');
|
|
68
|
+
if (name === key && value !== undefined) return value;
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// Single responsibility: a `tableStorage()` declaration against the catalog — what `pg_class` holds
|
|
2
|
+
// for each declared parameter, every difference with the statement that converges it. Split from
|
|
3
|
+
// `table-storage.ts`, which declares and renders.
|
|
4
|
+
|
|
5
|
+
import type { DbClient } from './client';
|
|
6
|
+
import { psqlCommand } from './dependent-view';
|
|
7
|
+
import { sql } from './sql';
|
|
8
|
+
import type { AutovacuumParameter } from './table-autovacuum';
|
|
9
|
+
import { autovacuumEntries, reloption } from './table-autovacuum';
|
|
10
|
+
import type { TableStorage } from './table-storage';
|
|
11
|
+
import { storageAlters } from './table-storage';
|
|
12
|
+
|
|
13
|
+
/** What the catalog holds for one table — `CatalogTable` satisfies it. `options` is `reloptions` joined. */
|
|
14
|
+
export interface LiveTableStorage {
|
|
15
|
+
readonly unlogged: boolean;
|
|
16
|
+
readonly options: string | null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface TableStorageDifference {
|
|
20
|
+
readonly table: string;
|
|
21
|
+
readonly parameter: 'table' | 'persistence' | 'fillfactor' | AutovacuumParameter;
|
|
22
|
+
readonly declared: string;
|
|
23
|
+
readonly live: string;
|
|
24
|
+
/** The statement that converges it, as SQL — `null` for a missing table, which `x db migrate` creates. */
|
|
25
|
+
readonly statement: string | null;
|
|
26
|
+
/** A command that runs as written: `psql … -c '<statement>'`, or `x db migrate`. */
|
|
27
|
+
readonly fix: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The statement and the line that runs it. `psqlCommand` quotes it as one shell word, and the name
|
|
32
|
+
* inside is the bare lower-case identifier `tableStorage` admitted, so nothing in it is shell-active.
|
|
33
|
+
*/
|
|
34
|
+
const converge = (alter: string | undefined): { statement: string; fix: string } => {
|
|
35
|
+
const statement = `${alter ?? ''};`;
|
|
36
|
+
return { statement, fix: `${psqlCommand(statement)} # then x db migrate, which re-checks` };
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** Only what the declaration states is compared: a parameter left out is not this value's to judge. */
|
|
40
|
+
export function tableStorageDrift(
|
|
41
|
+
storage: TableStorage,
|
|
42
|
+
live: LiveTableStorage | undefined,
|
|
43
|
+
): readonly TableStorageDifference[] {
|
|
44
|
+
const { table } = storage;
|
|
45
|
+
if (live === undefined) {
|
|
46
|
+
return [
|
|
47
|
+
{
|
|
48
|
+
table,
|
|
49
|
+
parameter: 'table',
|
|
50
|
+
declared: 'present',
|
|
51
|
+
live: 'absent',
|
|
52
|
+
statement: null,
|
|
53
|
+
fix: 'x db migrate',
|
|
54
|
+
},
|
|
55
|
+
];
|
|
56
|
+
}
|
|
57
|
+
const alters = storageAlters(storage);
|
|
58
|
+
const differences: TableStorageDifference[] = [];
|
|
59
|
+
if (storage.unlogged !== undefined && storage.unlogged !== live.unlogged) {
|
|
60
|
+
const persistence = (unlogged: boolean): string => (unlogged ? 'unlogged' : 'logged');
|
|
61
|
+
differences.push({
|
|
62
|
+
table,
|
|
63
|
+
parameter: 'persistence',
|
|
64
|
+
declared: persistence(storage.unlogged),
|
|
65
|
+
live: persistence(live.unlogged),
|
|
66
|
+
...converge(alters.find((alter) => /set (un)?logged$/.test(alter))),
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
const fillfactor = reloption(live.options, 'fillfactor');
|
|
70
|
+
// A number, as below: a hand-written `fillfactor = 080` is held as that text.
|
|
71
|
+
if (storage.fillfactor !== undefined && Number(fillfactor ?? Number.NaN) !== storage.fillfactor) {
|
|
72
|
+
differences.push({
|
|
73
|
+
table,
|
|
74
|
+
parameter: 'fillfactor',
|
|
75
|
+
declared: String(storage.fillfactor),
|
|
76
|
+
live: fillfactor ?? 'default (100)',
|
|
77
|
+
...converge(alters.find((alter) => alter.includes('fillfactor'))),
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
// Compared as numbers: the catalog keeps the text the alter was written with.
|
|
81
|
+
for (const [parameter, value] of autovacuumEntries(storage.autovacuum)) {
|
|
82
|
+
const held = reloption(live.options, parameter);
|
|
83
|
+
if (held !== null && Number(held) === value) continue;
|
|
84
|
+
differences.push({
|
|
85
|
+
table,
|
|
86
|
+
parameter,
|
|
87
|
+
declared: String(value),
|
|
88
|
+
live: held ?? 'default',
|
|
89
|
+
...converge(alters.find((alter) => alter.includes('autovacuum_'))),
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
return differences;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
interface StorageRow {
|
|
96
|
+
readonly name: string;
|
|
97
|
+
readonly persistence: string;
|
|
98
|
+
readonly options: string | null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Every declaration against the catalog, in ONE read — the reading `catalog-relations.ts` does
|
|
103
|
+
* (`relpersistence`, `reloptions` joined by `, `), narrowed to the named tables of `current_schema()`.
|
|
104
|
+
*/
|
|
105
|
+
export async function readTableStorageDrift(
|
|
106
|
+
client: DbClient,
|
|
107
|
+
storages: readonly TableStorage[],
|
|
108
|
+
): Promise<readonly TableStorageDifference[]> {
|
|
109
|
+
if (storages.length === 0) return [];
|
|
110
|
+
const rows = await client.query<StorageRow>(sql`
|
|
111
|
+
select c.relname as name, c.relpersistence as persistence,
|
|
112
|
+
array_to_string(c.reloptions, ', ') as options
|
|
113
|
+
from pg_class c join pg_namespace n on n.oid = c.relnamespace
|
|
114
|
+
where n.nspname = current_schema() and c.relkind in ('r', 'p')
|
|
115
|
+
and c.relname = any(${storages.map((storage) => storage.table)}::text[])`);
|
|
116
|
+
const live = new Map(rows.map((row) => [row.name, row]));
|
|
117
|
+
return storages.flatMap((storage) => {
|
|
118
|
+
const row = live.get(storage.table);
|
|
119
|
+
return tableStorageDrift(
|
|
120
|
+
storage,
|
|
121
|
+
row === undefined ? undefined : { unlogged: row.persistence === 'u', options: row.options },
|
|
122
|
+
);
|
|
123
|
+
});
|
|
124
|
+
}
|
package/src/table-storage.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
// Single responsibility: a framework-owned table's storage parameters (`fillfactor`, `unlogged
|
|
2
|
-
// ONE declared value — rendered into its `create table`,
|
|
3
|
-
// idempotent `alter`s at framework-schema apply,
|
|
4
|
-
//
|
|
1
|
+
// Single responsibility: a framework-owned table's storage parameters (`fillfactor`, `unlogged`,
|
|
2
|
+
// `table-autovacuum.ts`' triggers) as ONE declared value — rendered into its `create table`,
|
|
3
|
+
// re-applied by idempotent `alter`s at framework-schema apply, compared against `pg_class` by drift.
|
|
4
|
+
//
|
|
5
|
+
// Before it, framework DDL was fixed strings and nothing could state either parameter.
|
|
5
6
|
//
|
|
6
7
|
// The API, as a framework package uses it (`@ultimat3/http`'s `x_rate_limit`, `@ultimat3/jobs`):
|
|
7
8
|
//
|
|
@@ -16,23 +17,28 @@
|
|
|
16
17
|
//
|
|
17
18
|
// tableStorageDrift(storage, catalogTable) — pure: declared vs one `CatalogTable`
|
|
18
19
|
// readTableStorageDrift(client, [storage, …]) — one `pg_class` read, every difference
|
|
20
|
+
//
|
|
21
|
+
// Both drift readers live in `table-storage-drift.ts`.
|
|
19
22
|
|
|
20
|
-
import type { DbClient } from './client';
|
|
21
|
-
import { psqlCommand } from './dependent-view';
|
|
22
23
|
import { DbError } from './errors';
|
|
23
|
-
import {
|
|
24
|
+
import type { TableAutovacuum } from './table-autovacuum';
|
|
25
|
+
import { autovacuumProblem, autovacuumSettings } from './table-autovacuum';
|
|
24
26
|
|
|
25
27
|
export interface TableStorageOptions {
|
|
26
28
|
/** 10–100, Postgres' own range. Left out: the table's fillfactor is not this declaration's. */
|
|
27
29
|
readonly fillfactor?: number;
|
|
28
30
|
/** `true` unlogged, `false` logged (stated, e.g. a table that must survive a crash). Left out: neither. */
|
|
29
31
|
readonly unlogged?: boolean;
|
|
32
|
+
/** When autovacuum visits the table. Left out: Postgres' defaults, never judged. */
|
|
33
|
+
readonly autovacuum?: TableAutovacuum;
|
|
30
34
|
}
|
|
31
35
|
|
|
32
36
|
export interface TableStorage {
|
|
33
37
|
readonly table: string;
|
|
34
38
|
readonly fillfactor: number | undefined;
|
|
35
39
|
readonly unlogged: boolean | undefined;
|
|
40
|
+
/** Optional, so a `TableStorage` written before 31.25 still compiles. */
|
|
41
|
+
readonly autovacuum?: TableAutovacuum | undefined;
|
|
36
42
|
}
|
|
37
43
|
|
|
38
44
|
/**
|
|
@@ -49,7 +55,7 @@ const storageInvalid = (table: string, what: string): DbError =>
|
|
|
49
55
|
new DbError({
|
|
50
56
|
code: 'X_SQL_UNSAFE',
|
|
51
57
|
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",
|
|
58
|
+
fix: "tableStorage('x_rate_limit', { fillfactor: 70, unlogged: true }) # a bare lower-case name, an integer fillfactor 10-100, autovacuum thresholds integers 0-2147483647 and scale factors 0-100",
|
|
53
59
|
meta: { table },
|
|
54
60
|
});
|
|
55
61
|
|
|
@@ -68,7 +74,15 @@ export function tableStorage(table: string, options: TableStorageOptions): Table
|
|
|
68
74
|
`fillfactor ${String(fillfactor)} is not an integer from 10 to 100`,
|
|
69
75
|
);
|
|
70
76
|
}
|
|
71
|
-
|
|
77
|
+
const autovacuum = options.autovacuum;
|
|
78
|
+
const problem = autovacuum === undefined ? undefined : autovacuumProblem(autovacuum);
|
|
79
|
+
if (problem !== undefined) throw storageInvalid(table, problem);
|
|
80
|
+
return Object.freeze({
|
|
81
|
+
table,
|
|
82
|
+
fillfactor,
|
|
83
|
+
unlogged: options.unlogged,
|
|
84
|
+
autovacuum: autovacuum === undefined ? undefined : Object.freeze({ ...autovacuum }),
|
|
85
|
+
});
|
|
72
86
|
}
|
|
73
87
|
|
|
74
88
|
/**
|
|
@@ -86,6 +100,10 @@ export function storageAlters(storage: TableStorage): readonly string[] {
|
|
|
86
100
|
if (storage.unlogged !== undefined) {
|
|
87
101
|
alters.push(`alter table ${storage.table} set ${storage.unlogged ? 'unlogged' : 'logged'}`);
|
|
88
102
|
}
|
|
103
|
+
const autovacuum = autovacuumSettings(storage.autovacuum);
|
|
104
|
+
if (autovacuum.length > 0) {
|
|
105
|
+
alters.push(`alter table ${storage.table} set (${autovacuum.join(', ')})`);
|
|
106
|
+
}
|
|
89
107
|
return alters;
|
|
90
108
|
}
|
|
91
109
|
|
|
@@ -106,117 +124,11 @@ function columnBody(columns: string): string {
|
|
|
106
124
|
*/
|
|
107
125
|
export function tableDdl(storage: TableStorage, columns: string): string {
|
|
108
126
|
const head = storage.unlogged === true ? 'create unlogged table' : 'create table';
|
|
109
|
-
const
|
|
110
|
-
storage.fillfactor === undefined ?
|
|
127
|
+
const settings = [
|
|
128
|
+
...(storage.fillfactor === undefined ? [] : [`fillfactor = ${String(storage.fillfactor)}`]),
|
|
129
|
+
...autovacuumSettings(storage.autovacuum),
|
|
130
|
+
];
|
|
131
|
+
const options = settings.length === 0 ? '' : ` with (${settings.join(', ')})`;
|
|
111
132
|
const create = `${head} if not exists ${storage.table} (\n${columnBody(columns)}\n)${options};`;
|
|
112
133
|
return [create, ...storageAlters(storage).map((alter) => `${alter};`)].join('\n');
|
|
113
134
|
}
|
|
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
|
-
}
|