@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.
package/src/index-plan.ts CHANGED
@@ -22,11 +22,37 @@ import {
22
22
  redefineConcurrently,
23
23
  removeConcurrently,
24
24
  } from './concurrent-plan';
25
- import type { EntityDescriptionLike } from './entity-shape';
25
+ import type { EntityDescriptionLike, IndexDescriptionLike } from './entity-shape';
26
26
  import type { Plan } from './foreign-key-plan';
27
- import { createIndex, dropIndex, impliedByColumnClause, redefineIndex } from './index-ddl';
27
+ import {
28
+ createIndex,
29
+ dropIndex,
30
+ impliedByColumnClause,
31
+ indexShape,
32
+ redefineIndex,
33
+ } from './index-ddl';
28
34
  import type { TableDescription } from './introspect';
29
35
  import { declaredIndexes } from './invariant-ddl';
36
+ import { LOCK_HEAVY_MARKER } from './migration-lock-lint';
37
+
38
+ /**
39
+ * An existing table's index is built `concurrently` unless the entity says `concurrently: false`:
40
+ * a plain build holds SHARE on the table, stopping every write for the length of the scan, and
41
+ * `X_MIGRATION_LOCK_HEAVY` refuses one the generator did not mark. A partitioned parent is the
42
+ * exception Postgres makes (`0A000`, `X_MIGRATION_CONCURRENT_PARTITIONED`): built plainly, marked.
43
+ */
44
+ const buildsConcurrently = (entity: EntityDescriptionLike, index: IndexDescriptionLike): boolean =>
45
+ index.concurrently !== false && entity.partition === undefined;
46
+
47
+ /**
48
+ * A plain build on a table that was already there is a lock the author chose (`concurrently:
49
+ * false`, a partitioned parent, a column rebuilt under ACCESS EXCLUSIVE anyway). The marker goes on
50
+ * the line directly above THAT build, the only statement it admits, so `x db gen` never writes what
51
+ * `x verify` refuses and a hand-added lock beside it is still judged.
52
+ */
53
+ function pushPlainBuild(plan: Plan, build: string): void {
54
+ plan.up.push(LOCK_HEAVY_MARKER, build);
55
+ }
30
56
 
31
57
  /**
32
58
  * What the rest of this migration has already done to the columns underneath the indexes — every
@@ -75,12 +101,18 @@ export function indexPlan(
75
101
  // `concurrently` only where the table is live and the index is the only thing moving: a
76
102
  // rebuilt or retyped column already holds ACCESS EXCLUSIVE inside the transaction, so a
77
103
  // concurrent rebuild after it buys nothing and leaves the table without the index between.
78
- const concurrently = index.concurrently === true && !gone;
104
+ const concurrently = buildsConcurrently(entity, index) && !gone;
79
105
  if (recorded !== undefined && !gone) {
80
106
  if (concurrently) {
81
107
  redefineConcurrently(entity.table, index, recorded, context.concurrent);
82
- } else {
83
- redefineIndex(entity.table, index, recorded, plan);
108
+ } else if (indexShape(index) !== indexShape(recorded)) {
109
+ // `redefineIndex`'s drop + create, with the marker between them: above the create only.
110
+ const moved: Plan = { up: [], down: [] };
111
+ redefineIndex(entity.table, index, recorded, moved);
112
+ const [drop, ...builds] = moved.up;
113
+ if (drop !== undefined) plan.up.push(drop);
114
+ for (const build of builds) pushPlainBuild(plan, build);
115
+ plan.down.push(...moved.down);
84
116
  }
85
117
  continue;
86
118
  }
@@ -91,7 +123,7 @@ export function indexPlan(
91
123
  buildConcurrently(entity.table, index, context.concurrent);
92
124
  continue;
93
125
  }
94
- plan.up.push(createIndex(entity.table, index));
126
+ pushPlainBuild(plan, createIndex(entity.table, index));
95
127
  // The plain drop, always: this migration CREATED it, with `create index`, so it is an index
96
128
  // and never a constraint's — the ambiguity is about the recorded side only.
97
129
  plan.down.push(dropIndex(index.name));
package/src/index.ts CHANGED
@@ -113,6 +113,8 @@ export { partitionMaintenance } from './generate-partition';
113
113
  export type { PartitionRun, PartitionRunOptions } from './generate-partition-run';
114
114
  export { maintainPartitions, PARTITION_LOCK_TIMEOUT_MS } from './generate-partition-run';
115
115
  export type { RowSecurityOption, TenantColumnLike } from './generate-row-security';
116
+ export type { IndexKeyParts, IndexOperatorClass } from './index-key-ddl';
117
+ export { INDEX_OPERATOR_CLASSES, requiredExtension } from './index-key-ddl';
116
118
  export type { IndexMethod } from './index-method';
117
119
  export { declaredMethod, INDEX_METHODS, indexMethodOf, indexMethodSql } from './index-method';
118
120
  export type {
@@ -172,6 +174,14 @@ export {
172
174
  migrationSnapshotMissing,
173
175
  rollbackStepsInvalid,
174
176
  } from './migration-errors';
177
+ export type { LockHeavyKind, LockHeavyStatement } from './migration-lock-lint';
178
+ export {
179
+ LOCK_HEAVY_MARKER,
180
+ LOCK_HEAVY_SINCE,
181
+ lockHeavyJudged,
182
+ lockHeavyStatements,
183
+ migrationLockHeavy,
184
+ } from './migration-lock-lint';
175
185
  export type {
176
186
  PgliteClient,
177
187
  PgliteDriver,
@@ -243,6 +253,12 @@ export { assertRowSecurityBinds } from './row-security-role';
243
253
  export { APP_ROLE, MIGRATOR_ROLE, rowSecurityRolesSql, serveAsAppRole } from './row-security-roles';
244
254
  export { sameTenantKeyName } from './same-tenant';
245
255
  export { SIBLING_SCOPE_WAIT_MS } from './sibling-turn';
256
+ export type { SlowStatementLogOptions } from './slow-statement-log';
257
+ export {
258
+ SLOW_STATEMENT_THRESHOLD_MS,
259
+ SLOW_STATEMENT_WINDOW_MS,
260
+ slowStatementLog,
261
+ } from './slow-statement-log';
246
262
  export { snapshotJson } from './snapshot-json';
247
263
  export { parseSnapshot } from './snapshot-parse';
248
264
  export type { SqlFragment } from './sql';
@@ -255,6 +271,19 @@ export type { StatementBoundOptions } from './statement-bound';
255
271
  export { withStatementTimeout } from './statement-bound';
256
272
  export { statementFingerprint, statementKind, statementVerb } from './statement-shape';
257
273
  export { statementsOf } from './statement-split';
274
+ export type {
275
+ LiveTableStorage,
276
+ TableStorage,
277
+ TableStorageDifference,
278
+ TableStorageOptions,
279
+ } from './table-storage';
280
+ export {
281
+ readTableStorageDrift,
282
+ storageAlters,
283
+ tableDdl,
284
+ tableStorage,
285
+ tableStorageDrift,
286
+ } from './table-storage';
258
287
  export {
259
288
  completeTransaction,
260
289
  currentTx,
@@ -0,0 +1,110 @@
1
+ // Single responsibility: a schema's indexes read out of `pg_index` and folded into
2
+ // `IndexDescription`s — keys in key order, the method, and the key parts past a plain column list
3
+ // (per-key directions, INCLUDE, a non-default operator class). Split from `introspect.ts` at the
4
+ // 500-line ceiling; each newer part is written only when present, so an index without is unchanged.
5
+
6
+ import type { DbClient } from './client';
7
+ import type { IndexDescription } from './introspect';
8
+ import type { IndexRow } from './introspect-rows';
9
+ import { sql } from './sql';
10
+
11
+ /** The row, plus the key-part columns. Optional: a stub's rows predate them and read as "none". */
12
+ export interface IndexKeyRow extends IndexRow {
13
+ /** `true` per key that is descending, in key order. */
14
+ readonly directions?: readonly boolean[] | undefined;
15
+ /** INCLUDE payload columns, in order; `null` when there are none. */
16
+ readonly include?: readonly string[] | null | undefined;
17
+ /** Per key: the operator class when it is NOT the type's default, else `null`. */
18
+ readonly opclasses?: readonly (string | null)[] | undefined;
19
+ }
20
+
21
+ /**
22
+ * Ordered by the index's own key position, never by `attnum`: `indkey` IS the order the planner
23
+ * sorts by. `indnkeyatts` splits keys from INCLUDE payload columns, which are stored, not keyed.
24
+ *
25
+ * A LEFT join on `pg_attribute`: an expression key has `attnum = 0` and no attribute row, so an
26
+ * inner join dropped it and `(id, lower(title))` read back as `(id)`. It is kept in its position
27
+ * and MARKED by its parentheses, which no declared column name carries.
28
+ *
29
+ * `indclass` is the operator class per key; only a non-default one is named (`opcdefault`), so a
30
+ * jsonb GIN's own `jsonb_ops` reads as nothing declared, which is what its declaration says.
31
+ */
32
+ export const indexRows = (client: DbClient, schema: string): Promise<readonly IndexKeyRow[]> =>
33
+ client.query<IndexKeyRow>(sql`
34
+ select
35
+ t.relname as table_name,
36
+ i.relname as index_name,
37
+ ix.indisunique as is_unique,
38
+ ix.indisprimary as is_primary,
39
+ pg_get_expr(ix.indpred, ix.indrelid) as predicate,
40
+ am.amname as method,
41
+ array_agg(
42
+ coalesce(a.attname::text, '(' || pg_get_indexdef(ix.indexrelid, k.ord::int, false) || ')')
43
+ order by k.ord
44
+ ) as columns,
45
+ bool_and((ix.indoption[k.ord - 1] & 1) = 1) as descending,
46
+ array_agg((ix.indoption[k.ord - 1] & 1) = 1 order by k.ord) as directions,
47
+ array_agg(case when opc.opcdefault then null else opc.opcname::text end order by k.ord)
48
+ as opclasses,
49
+ (
50
+ select array_agg(pa.attname::text order by p.ord)
51
+ from unnest(ix.indkey::smallint[]) with ordinality as p(attnum, ord)
52
+ join pg_attribute pa on pa.attrelid = t.oid and pa.attnum = p.attnum
53
+ where p.ord > ix.indnkeyatts
54
+ ) as include
55
+ from pg_class t
56
+ join pg_namespace n on n.oid = t.relnamespace
57
+ join pg_index ix on ix.indrelid = t.oid
58
+ join pg_class i on i.oid = ix.indexrelid
59
+ join pg_am am on am.oid = i.relam
60
+ cross join lateral unnest(ix.indkey::smallint[]) with ordinality as k(attnum, ord)
61
+ left join pg_attribute a on a.attrelid = t.oid and a.attnum = k.attnum and k.attnum > 0
62
+ left join pg_opclass opc on opc.oid = ix.indclass[k.ord - 1]
63
+ where n.nspname = ${schema} and t.relkind in ('r', 'p') and k.ord <= ix.indnkeyatts
64
+ group by
65
+ t.oid, t.relname, i.relname, ix.indisunique, ix.indisprimary, ix.indpred, ix.indrelid,
66
+ ix.indexrelid, ix.indkey, ix.indnkeyatts, am.amname
67
+ order by t.relname, i.relname
68
+ `);
69
+
70
+ const byName = (a: { name: string }, b: { name: string }): number => (a.name < b.name ? -1 : 1);
71
+
72
+ /**
73
+ * The parts past a plain column list, each only when the catalog holds one: `orders` only for MIXED
74
+ * directions (all-descending is `order: 'desc'`, the reading every snapshot already has), INCLUDE
75
+ * only when non-empty, an operator class only when every key carries the same non-default one.
76
+ */
77
+ function keyPartsOf(row: IndexKeyRow): Partial<IndexDescription> {
78
+ const directions = row.directions ?? [];
79
+ const mixed = directions.some((d) => d) && directions.some((d) => !d);
80
+ const classes = new Set(row.opclasses ?? []);
81
+ const [onlyClass] = classes;
82
+ return {
83
+ ...(mixed ? { orders: directions.map((d) => (d ? ('desc' as const) : null)) } : {}),
84
+ ...(row.include === null || row.include === undefined || row.include.length === 0
85
+ ? {}
86
+ : { include: [...row.include] }),
87
+ ...(classes.size === 1 && typeof onlyClass === 'string' ? { operatorClass: onlyClass } : {}),
88
+ };
89
+ }
90
+
91
+ /** One table's indexes, by name. */
92
+ export function indexesOf(rows: readonly IndexKeyRow[], table: string): IndexDescription[] {
93
+ return rows
94
+ .filter((row) => row.table_name === table)
95
+ .map(
96
+ (row): IndexDescription => ({
97
+ name: row.index_name,
98
+ columns: [...row.columns],
99
+ unique: row.is_unique,
100
+ primary: row.is_primary,
101
+ where: row.predicate,
102
+ order: row.descending ? ('desc' as const) : null,
103
+ // `exactOptionalPropertyTypes`: a row with no method is a stub's, and absent must stay
104
+ // absent rather than becoming an explicit `undefined` a strict comparison can see.
105
+ ...(row.method === undefined ? {} : { using: row.method }),
106
+ ...keyPartsOf(row),
107
+ }),
108
+ )
109
+ .sort(byName);
110
+ }
package/src/introspect.ts CHANGED
@@ -6,11 +6,12 @@
6
6
  import { nonAppRelations } from './app-relation';
7
7
  import { type DbClient, db } from './client';
8
8
  import type { PartitionInterval } from './entity-shape';
9
+ import type { IndexKeyParts } from './index-key-ddl';
10
+ import { type IndexKeyRow, indexesOf, indexRows } from './introspect-index';
9
11
  import {
10
12
  type CheckRow,
11
13
  type ColumnRow,
12
14
  type ForeignKeyRow,
13
- type IndexRow,
14
15
  notValidOf,
15
16
  onDeleteOf,
16
17
  type TriggerNameRow,
@@ -43,7 +44,12 @@ export interface ColumnDescription {
43
44
  readonly retired?: true | undefined;
44
45
  }
45
46
 
46
- export interface IndexDescription {
47
+ /**
48
+ * An index, as a snapshot records it and the catalog reads it. The four key parts past a plain
49
+ * column list (`IndexKeyParts`: expression, per-key directions, INCLUDE, operator class) are
50
+ * optional and absent on every index that has none, so no recorded snapshot changes shape.
51
+ */
52
+ export interface IndexDescription extends IndexKeyParts {
47
53
  readonly name: string;
48
54
  /**
49
55
  * Key columns in **index key order** — the order the planner sorts by, never `attnum`. An
@@ -278,41 +284,7 @@ export async function introspectSchema(
278
284
  order by c.table_name, c.ordinal_position
279
285
  `);
280
286
 
281
- // Ordered by the index's own key position, never by `attnum`: `indkey` IS the order the planner
282
- // sorts by, and a composite index on `(created_at, org_id)` whose columns were declared the
283
- // other way round came back reversed — a description that reads correct and compares wrong.
284
- // `indnkeyatts` drops INCLUDE payload columns, which are stored, not keyed.
285
- //
286
- // A LEFT join on `pg_attribute`: an expression key has `attnum = 0` and no attribute row, so an
287
- // inner join dropped it and `(id, lower(title))` read back as `(id)` — an index rebuilt by hand
288
- // with an extra expression key compared equal to the declared one. It is kept in its position
289
- // and MARKED by its parentheses, which no declared column name carries.
290
- const indexes = client.query<IndexRow>(sql`
291
- select
292
- t.relname as table_name,
293
- i.relname as index_name,
294
- ix.indisunique as is_unique,
295
- ix.indisprimary as is_primary,
296
- pg_get_expr(ix.indpred, ix.indrelid) as predicate,
297
- am.amname as method,
298
- array_agg(
299
- coalesce(a.attname::text, '(' || pg_get_indexdef(ix.indexrelid, k.ord::int, false) || ')')
300
- order by k.ord
301
- ) as columns,
302
- bool_and((ix.indoption[k.ord - 1] & 1) = 1) as descending
303
- from pg_class t
304
- join pg_namespace n on n.oid = t.relnamespace
305
- join pg_index ix on ix.indrelid = t.oid
306
- join pg_class i on i.oid = ix.indexrelid
307
- join pg_am am on am.oid = i.relam
308
- cross join lateral unnest(ix.indkey::smallint[]) with ordinality as k(attnum, ord)
309
- left join pg_attribute a on a.attrelid = t.oid and a.attnum = k.attnum and k.attnum > 0
310
- where n.nspname = ${schema} and t.relkind in ('r', 'p') and k.ord <= ix.indnkeyatts
311
- group by
312
- t.relname, i.relname, ix.indisunique, ix.indisprimary, ix.indpred, ix.indrelid,
313
- ix.indexrelid, am.amname
314
- order by t.relname, i.relname
315
- `);
287
+ const indexes = indexRows(client, schema);
316
288
 
317
289
  // `conkey` and `confkey` are unnested TOGETHER, by shared ordinality: they are two halves of one
318
290
  // ordered pairing, and matching each independently with `= any(...)` is a cross product — a
@@ -390,7 +362,7 @@ export function buildSchema(
390
362
  schema: string,
391
363
  excluded: readonly string[],
392
364
  columns: readonly ColumnRow[],
393
- indexes: readonly IndexRow[],
365
+ indexes: readonly IndexKeyRow[],
394
366
  foreignKeys: readonly ForeignKeyRow[],
395
367
  checks: readonly CheckRow[] = [],
396
368
  /** Absent leaves `triggerNames` off every table: nobody asked the catalog. */
@@ -404,20 +376,7 @@ export function buildSchema(
404
376
  .sort();
405
377
 
406
378
  const tables = names.map((name): TableDescription => {
407
- const tableIndexes = indexes
408
- .filter((row) => row.table_name === name)
409
- .map((row) => ({
410
- name: row.index_name,
411
- columns: [...row.columns],
412
- unique: row.is_unique,
413
- primary: row.is_primary,
414
- where: row.predicate,
415
- order: row.descending ? ('desc' as const) : null,
416
- // `exactOptionalPropertyTypes`: a row with no method is a stub's, and absent must stay
417
- // absent rather than becoming an explicit `undefined` a strict comparison can see.
418
- ...(row.method === undefined ? {} : { using: row.method }),
419
- }))
420
- .sort(byName);
379
+ const tableIndexes = indexesOf(indexes, name);
421
380
  return {
422
381
  schema,
423
382
  name,
@@ -0,0 +1,184 @@
1
+ // Single responsibility: decide whether a hand-written migration's `up` holds a live table still for
2
+ // a full scan — `set not null` with no validated check before it, or a non-concurrent index build —
3
+ // and raise `X_MIGRATION_LOCK_HEAVY` for it. `rolling.ts`'s shape and token stream: lexical, `up`
4
+ // only, a closed list, a marker to admit a deliberate one.
5
+
6
+ import { renderFixShellArg } from '@ultimat3/core';
7
+ import { NO_TRANSACTION_MARKER } from './concurrent-index';
8
+ import { DbError } from './errors';
9
+ import { hasMarkerLine } from './marker-line';
10
+ import { alteredTable, isWord, nameOf, qualifiedNameAt, subcommands, tokensOf } from './rolling';
11
+ import { statementExcerpt } from './statement-excerpt';
12
+ import { statementsOf } from './statement-split';
13
+
14
+ /** The line a migration carries when the lock is deliberate: a small table, a maintenance window. */
15
+ export const LOCK_HEAVY_MARKER = '-- lock-heavy: true';
16
+
17
+ const LOCK_HEAVY_COMMENT = /^--[ \t]*lock-heavy:[ \t]*true[ \t]*\r?\n?$/i;
18
+
19
+ /** The comments and blank space `statementsOf` carries in front of a statement's SQL. */
20
+ const LEADING_NOISE = /^(?:\s*(?:--[^\n]*|\/\*[\s\S]*?\*\/)\s*)+/;
21
+
22
+ /** Only spaces and tabs between `at` and the start of its line in `up` (or the file's start). */
23
+ function startsLine(up: string, at: number): boolean {
24
+ for (let index = at - 1; index >= 0; index -= 1) {
25
+ if (up[index] === '\n') return true;
26
+ if (up[index] !== ' ' && up[index] !== '\t') return false;
27
+ }
28
+ return true;
29
+ }
30
+
31
+ /**
32
+ * Whether the line directly above the statement's first SQL line is the marker, as a line of its
33
+ * own (`hasMarkerLine`). `at` is where the trimmed `statement` starts in `up`: a marker that is the
34
+ * statement's first line must start its line there too, or it trails the previous statement.
35
+ */
36
+ function markedAbove(up: string, statement: string, at: number): boolean {
37
+ const lines = (LEADING_NOISE.exec(statement)?.[0] ?? '').split('\n');
38
+ // The SQL must open its own line: `*/ create …` puts the line above inside the comment.
39
+ if (lines.length < 2 || (lines.at(-1) ?? '').trim() !== '') return false;
40
+ const above = lines.length - 2;
41
+ if (above === 0 && !startsLine(up, at)) return false;
42
+ return hasMarkerLine(`${lines[above] ?? ''}\n`, LOCK_HEAVY_COMMENT);
43
+ }
44
+
45
+ /**
46
+ * The migration id the rail judges after, exclusive: the release that shipped it. An applied
47
+ * migration cannot gain a marker (its checksum covers it), so judging history would turn an
48
+ * existing app red with no fix but rewriting it. The comparison `rollingSince` makes, with the
49
+ * bound fixed by the framework rather than opted into, since every app's next file can comply.
50
+ */
51
+ export const LOCK_HEAVY_SINCE = '20261113000000';
52
+
53
+ export const lockHeavyJudged = (id: string): boolean => id > LOCK_HEAVY_SINCE;
54
+
55
+ /** The closed list. Every other lock is either the generator's or too rare to earn a parser. */
56
+ export type LockHeavyKind = 'set-not-null' | 'create-index';
57
+
58
+ export interface LockHeavyStatement {
59
+ readonly kind: LockHeavyKind;
60
+ readonly table: string;
61
+ /** The column `set not null` names; `null` for an index build. */
62
+ readonly column: string | null;
63
+ /** The statement as written, on one line. */
64
+ readonly statement: string;
65
+ }
66
+
67
+ /**
68
+ * `create [temp|temporary|unlogged|materialized] table|view [if not exists] [schema.]t`: the
69
+ * relation no reader has yet, or none. A materialized view is here because `generate-view.ts`
70
+ * rebuilds one by drop + create and indexes it in the same file.
71
+ */
72
+ function createdTable(tokens: readonly string[]): string | undefined {
73
+ if (!isWord(tokens[0], 'create')) return undefined;
74
+ let at = 1;
75
+ if (['temp', 'temporary', 'unlogged'].some((word) => isWord(tokens[at], word))) at += 1;
76
+ if (isWord(tokens[at], 'materialized') && isWord(tokens[at + 1], 'view')) at += 1;
77
+ else if (!isWord(tokens[at], 'table')) return undefined;
78
+ at += 1;
79
+ if (isWord(tokens[at], 'if') && isWord(tokens[at + 1], 'not') && isWord(tokens[at + 2], 'exists'))
80
+ at += 3;
81
+ return qualifiedNameAt(tokens, at)?.name;
82
+ }
83
+
84
+ /**
85
+ * `create [unique] index …` without `concurrently` and not `on only`: the table it locks. `on only`
86
+ * builds an invalid index on a partitioned parent's own (empty) relation, the first of the
87
+ * concurrent partitioned form, so it scans nothing.
88
+ */
89
+ function blockingIndexTable(tokens: readonly string[]): string | undefined {
90
+ if (!isWord(tokens[0], 'create')) return undefined;
91
+ const at = isWord(tokens[1], 'unique') ? 2 : 1;
92
+ if (!isWord(tokens[at], 'index') || isWord(tokens[at + 1], 'concurrently')) return undefined;
93
+ const on = tokens.findIndex((token, index) => index > at && isWord(token, 'on'));
94
+ if (on < 0 || isWord(tokens[on + 1], 'only')) return undefined;
95
+ return qualifiedNameAt(tokens, on + 1)?.name;
96
+ }
97
+
98
+ /** `alter [column] c set not null`: the column, or none. */
99
+ function setNotNullColumn(part: readonly string[]): string | undefined {
100
+ if (!isWord(part[0], 'alter')) return undefined;
101
+ const at = isWord(part[1], 'column') ? 2 : 1;
102
+ const [name, set, not, nul] = part.slice(at, at + 4);
103
+ if (name === undefined || !isWord(set, 'set') || !isWord(not, 'not') || !isWord(nul, 'null'))
104
+ return undefined;
105
+ return nameOf(name);
106
+ }
107
+
108
+ /**
109
+ * Every statement in `up` that scans a table it did not create under a lock that stops writes, in
110
+ * apply order. A table created earlier in the same `up` has no rows yet. A `validate constraint` on
111
+ * the table earlier in the same `up` is the two-step form's second half: Postgres 12+ proves NOT
112
+ * NULL from a validated `check (c is not null)` and skips the scan. A statement with the marker on
113
+ * the line directly above it is admitted — that statement only, never the file.
114
+ */
115
+ export function lockHeavyStatements(up: string): readonly LockHeavyStatement[] {
116
+ const found: LockHeavyStatement[] = [];
117
+ const created = new Set<string>();
118
+ const validated = new Set<string>();
119
+ let cursor = 0;
120
+ for (const statement of statementsOf(up)) {
121
+ const at = up.indexOf(statement, cursor);
122
+ cursor = at < 0 ? cursor : at + statement.length;
123
+ const admitted = at >= 0 && markedAbove(up, statement, at);
124
+ const tokens = tokensOf(statement);
125
+ const table = createdTable(tokens);
126
+ if (table !== undefined) created.add(table);
127
+ const indexed = blockingIndexTable(tokens);
128
+ if (indexed !== undefined && !created.has(indexed) && !admitted) {
129
+ found.push({
130
+ kind: 'create-index',
131
+ table: indexed,
132
+ column: null,
133
+ statement: statementExcerpt(statement),
134
+ });
135
+ }
136
+ const altered = alteredTable(tokens);
137
+ if (altered === undefined) continue;
138
+ for (const part of subcommands(tokens.slice(altered.next))) {
139
+ if (isWord(part[0], 'validate')) validated.add(altered.table);
140
+ const column = setNotNullColumn(part);
141
+ if (
142
+ column === undefined ||
143
+ admitted ||
144
+ created.has(altered.table) ||
145
+ validated.has(altered.table)
146
+ )
147
+ continue;
148
+ found.push({
149
+ kind: 'set-not-null',
150
+ table: altered.table,
151
+ column,
152
+ statement: statementExcerpt(statement),
153
+ });
154
+ }
155
+ }
156
+ return found;
157
+ }
158
+
159
+ const STATED: Readonly<Record<LockHeavyKind, string>> = {
160
+ 'set-not-null': 'sets a column not null with no validated check before it',
161
+ 'create-index': 'builds an index without concurrently',
162
+ };
163
+
164
+ /** The two-step form for the kind, then the marker for a lock that is deliberate. */
165
+ function twoSteps(first: LockHeavyStatement): string {
166
+ const table = renderFixShellArg(first.table, '<table>');
167
+ if (first.kind === 'create-index')
168
+ return `create index concurrently … on "${table}" (…); # in a migration of its own whose first line is "${NO_TRANSACTION_MARKER}" — x db gen writes it so for an index whose entity does not say concurrently: false`;
169
+ const column = renderFixShellArg(first.column ?? '<column>', '<column>');
170
+ const check = `${table}_${column}_not_null`;
171
+ return (
172
+ `alter table "${table}" add constraint "${check}" check ("${column}" is not null) not valid; # ` +
173
+ `deploy, then a new migration: alter table "${table}" validate constraint "${check}"; alter table "${table}" alter column "${column}" set not null; alter table "${table}" drop constraint "${check}";`
174
+ );
175
+ }
176
+
177
+ /** The gate's finding over a committed file. One per migration, as `migrationRollingUnsafe` is. */
178
+ export const migrationLockHeavy = (file: string, first: LockHeavyStatement, more = 0): DbError =>
179
+ new DbError({
180
+ code: 'X_MIGRATION_LOCK_HEAVY',
181
+ cause: `${file} ${STATED[first.kind]}, so "${first.table}" stops taking writes for a full scan${more === 0 ? '' : ` (and ${more} more)`}: ${first.statement}`,
182
+ fix: `${twoSteps(first)} — a deliberate one: add the line "${LOCK_HEAVY_MARKER}" directly above that statement in ${file} before it is applied — it admits that statement only`,
183
+ meta: { file, kind: first.kind, table: first.table, column: first.column },
184
+ });
@@ -0,0 +1,154 @@
1
+ // Single responsibility: which of the few statements that move a pin's `statement_timeout` a text
2
+ // is — a transaction end, a savepoint verb, a RESET, a SET or a `set_config` — read from its
3
+ // leading words in ONE linear pass. Statement text is library input: no backtracking regex reads
4
+ // it, and a long statement stops being read after `PIN_WORDS_MAX` words.
5
+
6
+ /** More words than any statement recognised here has, so a bulk INSERT is dropped after a dozen. */
7
+ export const PIN_WORDS_MAX = 12;
8
+
9
+ export type PinStatement =
10
+ | { readonly kind: 'end' }
11
+ | { readonly kind: 'savepoint' | 'rollback-to' | 'release'; readonly name: string }
12
+ | { readonly kind: 'role-bound' }
13
+ | { readonly kind: 'set'; readonly value: string };
14
+
15
+ const PUNCTUATION = '=(),;';
16
+
17
+ function isSpace(code: number): boolean {
18
+ return code === 32 || (code >= 9 && code <= 13);
19
+ }
20
+
21
+ /** The index just past the quote closing the one at `start` (`''`/`""` escape it), or -1. */
22
+ function quotedEnd(text: string, start: number, quote: string): number {
23
+ let at = start + 1;
24
+ while (at < text.length) {
25
+ if (text[at] !== quote) at += 1;
26
+ else if (text[at + 1] === quote) at += 2;
27
+ else return at + 1;
28
+ }
29
+ return -1;
30
+ }
31
+
32
+ /**
33
+ * The words of `text`: a quoted identifier or literal whole, each of `= ( ) , ;` alone, any other
34
+ * run of non-space characters as one. One trailing `;` dropped. `undefined` past `PIN_WORDS_MAX`
35
+ * words or at an unterminated quote: neither is a statement this file recognises.
36
+ */
37
+ export function pinWords(text: string): readonly string[] | undefined {
38
+ const words: string[] = [];
39
+ let at = 0;
40
+ for (;;) {
41
+ while (at < text.length && isSpace(text.charCodeAt(at))) at += 1;
42
+ if (at >= text.length) break;
43
+ if (words.length === PIN_WORDS_MAX) return undefined;
44
+ const char = text[at] ?? '';
45
+ let end = at + 1;
46
+ if (char === '"' || char === "'") {
47
+ end = quotedEnd(text, at, char);
48
+ if (end === -1) return undefined;
49
+ } else if (!PUNCTUATION.includes(char)) {
50
+ while (end < text.length && !isSpace(text.charCodeAt(end))) {
51
+ const next = text[end] ?? '';
52
+ if (PUNCTUATION.includes(next) || next === '"' || next === "'") break;
53
+ end += 1;
54
+ }
55
+ }
56
+ words.push(text.slice(at, end));
57
+ at = end;
58
+ }
59
+ if (words.at(-1) === ';') words.pop();
60
+ return words;
61
+ }
62
+
63
+ const UNQUOTED_NAME = /^[a-z_][\w$]*$/i;
64
+
65
+ /** A savepoint name as the server compares it: unquoted folds to lower case, quoted is exact. */
66
+ function nameOf(word: string | undefined): string | undefined {
67
+ if (word === undefined) return undefined;
68
+ if (word.startsWith('"'))
69
+ return word.length > 2 ? word.slice(1, -1).replaceAll('""', '"') : undefined;
70
+ return UNQUOTED_NAME.test(word) ? word.toLowerCase() : undefined;
71
+ }
72
+
73
+ /** `[savepoint] name` as the last one or two words from `from`. */
74
+ function savepointAt(
75
+ words: readonly string[],
76
+ from: number,
77
+ optional: boolean,
78
+ ): string | undefined {
79
+ const at = optional && words[from]?.toLowerCase() === 'savepoint' ? from + 1 : from;
80
+ return at === words.length - 1 ? nameOf(words[at]) : undefined;
81
+ }
82
+
83
+ /** `rollback [work|transaction] to [savepoint] name`, or a bare transaction end. */
84
+ function rollbackOf(words: readonly string[]): PinStatement | undefined {
85
+ const at = ['work', 'transaction'].includes(words[1]?.toLowerCase() ?? '') ? 2 : 1;
86
+ if (at === words.length) return { kind: 'end' };
87
+ if (words[at]?.toLowerCase() !== 'to') return undefined;
88
+ const name = savepointAt(words, at + 1, true);
89
+ return name === undefined ? undefined : { kind: 'rollback-to', name };
90
+ }
91
+
92
+ /** `set [local|session] statement_timeout {=|to} value` — `default` is the role's. */
93
+ function setOf(words: readonly string[]): PinStatement | undefined {
94
+ const at = ['local', 'session'].includes(words[1]?.toLowerCase() ?? '') ? 2 : 1;
95
+ if (words[at]?.toLowerCase() !== 'statement_timeout' || words.length !== at + 3) return undefined;
96
+ if (!['=', 'to'].includes(words[at + 1]?.toLowerCase() ?? '')) return undefined;
97
+ const value = words[at + 2] ?? '';
98
+ return value.toLowerCase() === 'default' ? { kind: 'role-bound' } : { kind: 'set', value };
99
+ }
100
+
101
+ /** `select set_config('statement_timeout', 'value', true|false)`. */
102
+ function setConfigOf(words: readonly string[]): PinStatement | undefined {
103
+ const [, fn, open, key, , value, , local, close] = words;
104
+ const shape =
105
+ words.length === 9 &&
106
+ fn?.toLowerCase() === 'set_config' &&
107
+ open === '(' &&
108
+ key?.toLowerCase() === "'statement_timeout'" &&
109
+ words[4] === ',' &&
110
+ words[6] === ',' &&
111
+ ['true', 'false'].includes(local?.toLowerCase() ?? '') &&
112
+ close === ')' &&
113
+ value?.startsWith("'") === true;
114
+ return shape
115
+ ? { kind: 'set', value: (value ?? '').slice(1, -1).replaceAll("''", "'") }
116
+ : undefined;
117
+ }
118
+
119
+ export function pinStatement(text: string): PinStatement | undefined {
120
+ const words = pinWords(text);
121
+ if (words === undefined) return undefined;
122
+ const verb = words[0]?.toLowerCase();
123
+ switch (verb) {
124
+ case 'commit':
125
+ case 'end':
126
+ case 'abort': {
127
+ const tail = words[1]?.toLowerCase();
128
+ const bare =
129
+ words.length === 1 || (words.length === 2 && ['work', 'transaction'].includes(tail ?? ''));
130
+ return bare ? { kind: 'end' } : undefined;
131
+ }
132
+ case 'rollback':
133
+ return rollbackOf(words);
134
+ case 'savepoint': {
135
+ const name = savepointAt(words, 1, false);
136
+ return name === undefined ? undefined : { kind: 'savepoint', name };
137
+ }
138
+ case 'release': {
139
+ const name = savepointAt(words, 1, true);
140
+ return name === undefined ? undefined : { kind: 'release', name };
141
+ }
142
+ case 'reset': {
143
+ const what = words[1]?.toLowerCase();
144
+ const known = words.length === 2 && (what === 'statement_timeout' || what === 'all');
145
+ return known ? { kind: 'role-bound' } : undefined;
146
+ }
147
+ case 'set':
148
+ return setOf(words);
149
+ case 'select':
150
+ return setConfigOf(words);
151
+ default:
152
+ return undefined;
153
+ }
154
+ }