@ultimat3/db 31.7.0 → 31.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,7 @@
3
3
  // part of it — a column's `on delete` rule included — crosses the seam by shape or not at all.
4
4
 
5
5
  import type { ColumnDefaultLike } from './column-default';
6
+ import type { IndexOperatorClass } from './index-key-ddl';
6
7
  import type { IndexMethod } from './index-method';
7
8
 
8
9
  /** Structurally assignment-compatible with `@ultimat3/entity`'s `ColumnDescription`. */
@@ -108,13 +109,29 @@ export interface IndexDescriptionLike {
108
109
  */
109
110
  readonly using?: IndexMethod | undefined;
110
111
  /**
111
- * `indexes: [{ on, concurrently: true }]`: build it with `create index concurrently` in a
112
- * migration of its own that runs OUTSIDE a transaction (`concurrent-index.ts`), so a hot table
113
- * keeps taking writes while it builds. HOW the index is built, never WHAT it is — so it is not
114
- * part of the name, not recorded in a snapshot and never a reason to rebuild one. Absent is the
115
- * plain, transactional `create index` every index was before it existed.
112
+ * HOW the index is built, never WHAT it is — not part of the name, not recorded in a snapshot
113
+ * and never a reason to rebuild one. Absent or `true`: on a table that already exists, `create
114
+ * index concurrently` in a migration of its own OUTSIDE a transaction (`concurrent-index.ts`), so
115
+ * a hot table keeps taking writes. `false`: the plain, transactional build, which `index-plan.ts`
116
+ * marks `-- lock-heavy: true` for `X_MIGRATION_LOCK_HEAVY`. A table the same migration creates,
117
+ * and a partitioned parent (`0A000`), are always built plainly.
116
118
  */
117
119
  readonly concurrently?: boolean | undefined;
120
+ /**
121
+ * The four parts past a plain column list (`index-key-ddl.ts` renders them). Each is optional
122
+ * and absent by default, for `using`'s reason: a description written before them emits, records
123
+ * and compares exactly as it did.
124
+ *
125
+ * `expression`: the ONE key is this SQL expression (`lower(email)`, `(payload->>'kind')`), and
126
+ * `columns` names the columns it reads — what a foreign key's covering rule looks at.
127
+ */
128
+ readonly expression?: string | undefined;
129
+ /** A direction per key, in key order; `null` writes none. Replaces `order`, never beside it. */
130
+ readonly orders?: readonly ('asc' | 'desc' | null)[] | undefined;
131
+ /** INCLUDE payload columns — stored in the index, never keyed (btree only). */
132
+ readonly include?: readonly string[] | undefined;
133
+ /** An operator class on every key. One member: `gin_trgm_ops`, which `contains` needs (gin only). */
134
+ readonly operatorClass?: IndexOperatorClass | undefined;
118
135
  }
119
136
 
120
137
  /** Structurally assignment-compatible with `@ultimat3/entity`'s `EntityDescription`. */
package/src/errors.ts CHANGED
@@ -59,6 +59,7 @@ export const DB_OWNED_ERROR_CODES = [
59
59
  'X_ENTITY_RETAIN_INVALID',
60
60
  'X_LIFECYCLE_TRIGGER_MISSING',
61
61
  'X_MIGRATION_PARTITION_CHANGE',
62
+ 'X_MIGRATION_LOCK_HEAVY',
62
63
  ] as const;
63
64
 
64
65
  /**
@@ -133,6 +134,7 @@ export const DB_ERROR_TITLES: Readonly<Record<DbOwnedErrorCode, string>> = {
133
134
  X_LIFECYCLE_TRIGGER_MISSING:
134
135
  'a history or counter trigger the migrations created is missing from the database',
135
136
  X_MIGRATION_PARTITION_CHANGE: 'an existing table gained or lost entity({ partitionBy })',
137
+ X_MIGRATION_LOCK_HEAVY: 'this migration holds a live table still for a full scan',
136
138
  };
137
139
 
138
140
  // Registered unconditionally, in one call, so a second package claiming one of db's codes fails
@@ -7,6 +7,7 @@ import { defaultExpression } from './column-default';
7
7
  import type { EntityDescriptionLike } from './entity-shape';
8
8
  import { foreignKeysOf } from './foreign-key-plan';
9
9
  import { splitViews, viewDescriptionOf } from './generate-view';
10
+ import { declaredKeyParts } from './index-key-ddl';
10
11
  import type { ColumnDescription, SchemaDescription, TableDescription } from './introspect';
11
12
  import { declaredIndexes } from './invariant-ddl';
12
13
  import { withSameTenantIndexes } from './same-tenant';
@@ -65,6 +66,8 @@ export function snapshotOf(
65
66
  // every sidecar in every app on the next `x db gen` — a diff on every file for a fact
66
67
  // that was already true, which `indexMethodOf` reads out of the absence anyway.
67
68
  ...(index.using === undefined ? {} : { using: index.using }),
69
+ // The four key parts, the same rule: each only when declared (`declaredKeyParts`).
70
+ ...declaredKeyParts(index.name, index),
68
71
  })),
69
72
  foreignKeys: foreignKeysOf(entity),
70
73
  // Absent, never `[]`, on a table declaring none: a sidecar that predates this field must
package/src/generate.ts CHANGED
@@ -21,6 +21,7 @@ import { splitViews, viewPlan } from './generate-view';
21
21
  import type { Regeneration } from './generated-column';
22
22
  import { generatedClause, isGenerated, regenerate } from './generated-column';
23
23
  import { createIndex, impliedByColumnClause } from './index-ddl';
24
+ import { extensionStatements } from './index-extension';
24
25
  import { indexPlan } from './index-plan';
25
26
  import {
26
27
  type ColumnDescription,
@@ -446,7 +447,14 @@ export function generateMigration(given: GenerateOptions): GeneratedMigration {
446
447
  return assembleSteps({
447
448
  id,
448
449
  name: options.name,
449
- up: [...viewed.before.up, ...preAlters.up, ...plan.up, ...viewed.after.up],
450
+ // An index's extension first (`index-extension.ts`): `gin_trgm_ops` does not exist before it.
451
+ up: [
452
+ ...extensionStatements(options.entities, current),
453
+ ...viewed.before.up,
454
+ ...preAlters.up,
455
+ ...plan.up,
456
+ ...viewed.after.up,
457
+ ],
450
458
  // Reverse order: the last thing created is the first thing dropped. `preAlters` goes in at the
451
459
  // FRONT here precisely so reversal puts it last — a key is added back only once both of its
452
460
  // ends have been retyped back, which is every other statement in the script.
package/src/index-ddl.ts CHANGED
@@ -8,6 +8,13 @@ import { assert } from '@ultimat3/core';
8
8
  import { indexOrderInvalid, indexPredicateUnsafe } from './ddl-errors';
9
9
  import type { EntityDescriptionLike, IndexDescriptionLike } from './entity-shape';
10
10
  import type { Plan } from './foreign-key-plan';
11
+ import {
12
+ declaredKeyParts,
13
+ hasKeyParts,
14
+ indexIncludeSql,
15
+ indexKeyShape,
16
+ indexKeysSql,
17
+ } from './index-key-ddl';
11
18
  import { declaredMethod, indexMethodOf, indexMethodSql } from './index-method';
12
19
  import type { IndexDescription } from './introspect';
13
20
  import { identifier } from './sql';
@@ -118,17 +125,17 @@ export function createIndex(
118
125
  const kind =
119
126
  (index.unique ? 'create unique index' : 'create index') +
120
127
  (concurrently ? ' concurrently if not exists' : '');
121
- const direction = indexOrderSql(index);
122
- const columns = index.columns
123
- .map((column) => `${identifier(column).text}${direction}`)
124
- .join(', ');
128
+ // Keys, then INCLUDE, then the predicate — Postgres' clause order. Both helpers answer the plain
129
+ // column list and `''` for an index declaring none of the newer parts: the same bytes as before.
130
+ const columns = indexKeysSql(index, indexOrderSql(index));
131
+ const include = indexIncludeSql(index);
125
132
  const predicate = indexPredicateSql(index);
126
133
  // Re-derived from the closed set, never spliced: `indexMethodSql` answers `''` for a btree, so
127
134
  // an index that declared no method emits the statement this generator always emitted, byte for
128
135
  // byte, and one that declared a method Postgres does not have is refused instead of built.
129
136
  return (
130
137
  `${kind} ${identifier(index.name).text} on ${identifier(table).text}` +
131
- `${indexMethodSql(method)} (${columns})${predicate};`
138
+ `${indexMethodSql(method)} (${columns})${include}${predicate};`
132
139
  );
133
140
  }
134
141
 
@@ -159,7 +166,8 @@ export function mayBeConstraintBacked(index: IndexDescription): boolean {
159
166
  !index.primary &&
160
167
  index.where === null &&
161
168
  index.order === null &&
162
- indexMethodOf(index) === 'btree'
169
+ indexMethodOf(index) === 'btree' &&
170
+ !hasKeyParts(index)
163
171
  );
164
172
  }
165
173
 
@@ -177,6 +185,7 @@ export function asDeclared(index: IndexDescription): IndexDescriptionLike {
177
185
  where: index.where,
178
186
  order: index.order,
179
187
  ...(index.using === undefined ? {} : { using: declaredMethod(index.using) }),
188
+ ...declaredKeyParts(index.name, index),
180
189
  };
181
190
  }
182
191
 
@@ -188,6 +197,8 @@ export function indexShape(index: IndexDescriptionLike | IndexDescription): stri
188
197
  index.where,
189
198
  index.order ?? null,
190
199
  indexMethodOf(index),
200
+ // Spread, so an index declaring none of the four parts hashes exactly as it always did.
201
+ ...indexKeyShape(index),
191
202
  ]);
192
203
  }
193
204
 
@@ -0,0 +1,34 @@
1
+ // Single responsibility: the `create extension` an index needs before it can be built — today one,
2
+ // `pg_trgm` for `gin_trgm_ops` — emitted by `x db gen` once, in the migration that first builds
3
+ // such an index. Never dropped in `down`: another index, or the app's own SQL, may use it.
4
+
5
+ import type { EntityDescriptionLike } from './entity-shape';
6
+ import { requiredExtension } from './index-key-ddl';
7
+ import { findTable, type SchemaDescription } from './introspect';
8
+ import { declaredIndexes } from './invariant-ddl';
9
+ import { identifier } from './sql';
10
+
11
+ /**
12
+ * `create extension if not exists …` for each extension a declared index needs whose recorded
13
+ * counterpart did not already need it — so the migration that adds the first trigram index carries
14
+ * it, and the next `x db gen` (the index recorded) carries nothing. Sorted, one per extension.
15
+ */
16
+ export function extensionStatements(
17
+ entities: readonly EntityDescriptionLike[],
18
+ current: SchemaDescription,
19
+ ): readonly string[] {
20
+ const needed = new Set<string>();
21
+ for (const entity of entities) {
22
+ const recorded = findTable(current, entity.table)?.indexes ?? [];
23
+ for (const index of declaredIndexes(entity)) {
24
+ const extension = requiredExtension(index);
25
+ if (extension === null) continue;
26
+ const before = recorded.find((each) => each.name === index.name);
27
+ if (before !== undefined && requiredExtension(before) === extension) continue;
28
+ needed.add(extension);
29
+ }
30
+ }
31
+ return [...needed]
32
+ .sort()
33
+ .map((extension) => `create extension if not exists ${identifier(extension).text};`);
34
+ }
@@ -0,0 +1,159 @@
1
+ // Single responsibility: an index's KEYS past a plain column list — an expression key, a direction
2
+ // per key, INCLUDE payload columns, the trigram operator class — as statement text, plus the shape
3
+ // parts and the extension they add. Split from `index-ddl.ts`, which assembles the statement.
4
+ // Every part is optional, and absent writes and hashes exactly what it did before it existed.
5
+
6
+ import { assert, describeValue } from '@ultimat3/core';
7
+ import type { IndexDescriptionLike } from './entity-shape';
8
+ import { DbError } from './errors';
9
+ import { identifier } from './sql';
10
+ import { statementsOf } from './statement-split';
11
+
12
+ /**
13
+ * One member, deliberately — `index-method.ts`'s rule: `gin_trgm_ops` has a caller (`contains`,
14
+ * `like '%x%'`, which no btree serves) and every other class would be a rule with no test.
15
+ */
16
+ export const INDEX_OPERATOR_CLASSES = ['gin_trgm_ops'] as const;
17
+
18
+ export type IndexOperatorClass = (typeof INDEX_OPERATOR_CLASSES)[number];
19
+
20
+ /** The four parts as one optional bag — what both sides of a comparison and a snapshot carry. */
21
+ export interface IndexKeyParts {
22
+ readonly expression?: string | undefined;
23
+ readonly orders?: readonly ('asc' | 'desc' | null)[] | undefined;
24
+ readonly include?: readonly string[] | undefined;
25
+ readonly operatorClass?: string | undefined;
26
+ }
27
+
28
+ /** `X_SQL_UNSAFE`, `indexOrderInvalid`'s reasoning: each value is SPLICED into the statement. */
29
+ const keyUnsafe = (index: string, what: string, fix: string): DbError =>
30
+ new DbError({ code: 'X_SQL_UNSAFE', cause: `index "${index}": ${what}`, fix, meta: { index } });
31
+
32
+ /** Re-derived from the closed set, never spliced — the input crossed the tier seam untyped. */
33
+ function directionSql(index: string, order: unknown): string {
34
+ if (order === null) return '';
35
+ if (order === 'asc') return ' asc';
36
+ if (order === 'desc') return ' desc';
37
+ throw keyUnsafe(
38
+ index,
39
+ `a key direction must be 'asc', 'desc' or null; got ${describeValue(order)}`,
40
+ `indexes: [{ on: ['a', 'b'], orders: [null, 'desc'] }] # then x db gen`,
41
+ );
42
+ }
43
+
44
+ function operatorClassSql(index: IndexDescriptionLike): string {
45
+ const { operatorClass } = index;
46
+ if (operatorClass === undefined) return '';
47
+ if (operatorClass !== 'gin_trgm_ops') {
48
+ throw keyUnsafe(
49
+ index.name,
50
+ `an operator class must be 'gin_trgm_ops'; got ${describeValue(operatorClass)}`,
51
+ `indexes: [{ on: ['name'], using: 'gin', operatorClass: 'gin_trgm_ops' }] # then x db gen`,
52
+ );
53
+ }
54
+ assert(
55
+ index.using === 'gin',
56
+ `index "${index.name}" declares gin_trgm_ops on a ${index.using ?? 'btree'} index; it is a gin operator class`,
57
+ `indexes: [{ on: ['<column>'], using: 'gin', operatorClass: 'gin_trgm_ops' }]`,
58
+ );
59
+ return ' gin_trgm_ops';
60
+ }
61
+
62
+ /** The key list as SQL, without its parentheses. `fallback` is the single `order` direction. */
63
+ export function indexKeysSql(index: IndexDescriptionLike, fallback: string): string {
64
+ const keys = index.expression === undefined ? [...index.columns] : [index.expression];
65
+ if (index.expression !== undefined) {
66
+ const commands = statementsOf(index.expression).length;
67
+ if (commands > 1) {
68
+ throw keyUnsafe(
69
+ index.name,
70
+ `the expression holds ${String(commands)} commands; an index key is one expression`,
71
+ `indexes: [{ on: ['email'], expression: 'lower(email)' }] # one expression, then x db gen`,
72
+ );
73
+ }
74
+ }
75
+ const { orders } = index;
76
+ if (orders !== undefined) {
77
+ assert(
78
+ index.order === null,
79
+ `index "${index.name}" declares both order and orders; orders states every key's direction`,
80
+ `indexes: [{ on: ['a', 'b'], orders: ['desc', 'desc'] }] # drop order`,
81
+ );
82
+ assert(
83
+ orders.length === keys.length,
84
+ `index "${index.name}" has ${String(keys.length)} keys and ${String(orders.length)} directions`,
85
+ `indexes: [{ on: ['a', 'b'], orders: [null, 'desc'] }] # one direction per key`,
86
+ );
87
+ assert(
88
+ (index.using ?? 'btree') === 'btree',
89
+ `index "${index.name}" is ${String(index.using)} and orders its keys; only a btree orders its keys`,
90
+ `indexes: [{ on: ['<column>'] }] # drop orders, or drop using`,
91
+ );
92
+ }
93
+ const opclass = operatorClassSql(index);
94
+ return keys
95
+ .map((key, position) => {
96
+ const head = index.expression === undefined ? identifier(key).text : `(${key})`;
97
+ const direction =
98
+ orders === undefined ? fallback : directionSql(index.name, orders[position]);
99
+ return `${head}${opclass}${direction}`;
100
+ })
101
+ .join(', ');
102
+ }
103
+
104
+ /** ` include ("a", "b")`, or `''`. Postgres stores it in btree, gist and spgist; this set has btree. */
105
+ export function indexIncludeSql(index: IndexDescriptionLike): string {
106
+ if (index.include === undefined || index.include.length === 0) return '';
107
+ assert(
108
+ (index.using ?? 'btree') === 'btree',
109
+ `index "${index.name}" is ${String(index.using)} and declares include; Postgres has no INCLUDE on it`,
110
+ `indexes: [{ on: ['<column>'], include: ['<column>'] }] # drop using, or drop include`,
111
+ );
112
+ return ` include (${index.include.map((column) => identifier(column).text).join(', ')})`;
113
+ }
114
+
115
+ /** The extension an index needs before it can be built — `null` for every index but a trigram one. */
116
+ export const requiredExtension = (index: IndexKeyParts): string | null =>
117
+ index.operatorClass === 'gin_trgm_ops' ? 'pg_trgm' : null;
118
+
119
+ /** Only the parts present, so an index declaring none hashes exactly as it did before them. */
120
+ export function indexKeyShape(index: IndexKeyParts): readonly unknown[] {
121
+ const parts: unknown[] = [];
122
+ if (index.expression !== undefined) parts.push({ expression: index.expression });
123
+ if (index.orders !== undefined) parts.push({ orders: [...index.orders] });
124
+ if (index.include !== undefined && index.include.length > 0) {
125
+ parts.push({ include: [...index.include] });
126
+ }
127
+ if (index.operatorClass !== undefined) parts.push({ operatorClass: index.operatorClass });
128
+ return parts;
129
+ }
130
+
131
+ /** True when any part is present — none of them can be what a UNIQUE constraint built. */
132
+ export const hasKeyParts = (index: IndexKeyParts): boolean => indexKeyShape(index).length > 0;
133
+
134
+ type DeclaredKeyParts = Pick<
135
+ IndexDescriptionLike,
136
+ 'expression' | 'orders' | 'include' | 'operatorClass'
137
+ >;
138
+
139
+ /**
140
+ * A RECORDED index's parts as a declaration this generator can emit again — `declaredMethod`'s
141
+ * rule: the recorded side is typed open, and a class this generator cannot write is refused rather
142
+ * than rebuilt without it. Each part only when present, so absent stays absent.
143
+ */
144
+ export function declaredKeyParts(name: string, index: IndexKeyParts): DeclaredKeyParts {
145
+ const { operatorClass } = index;
146
+ if (operatorClass !== undefined && operatorClass !== 'gin_trgm_ops') {
147
+ throw keyUnsafe(
148
+ name,
149
+ `an operator class must be 'gin_trgm_ops'; got ${describeValue(operatorClass)}`,
150
+ `indexes: [{ on: ['name'], using: 'gin', operatorClass: 'gin_trgm_ops' }] # then x db gen`,
151
+ );
152
+ }
153
+ return {
154
+ ...(index.expression === undefined ? {} : { expression: index.expression }),
155
+ ...(index.orders === undefined ? {} : { orders: [...index.orders] }),
156
+ ...(index.include === undefined ? {} : { include: [...index.include] }),
157
+ ...(operatorClass === undefined ? {} : { operatorClass }),
158
+ };
159
+ }
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
@@ -40,6 +40,8 @@ export {
40
40
  isPartitionedBuildRefusal,
41
41
  NO_TRANSACTION_MARKER,
42
42
  } from './concurrent-index';
43
+ export type { CopyInClient } from './copy-in';
44
+ export { canCopyIn } from './copy-in';
43
45
  export { dbExecutor } from './db-executor';
44
46
  export type { DbHealthReport } from './db-health';
45
47
  export { checkDb } from './db-health';
@@ -113,6 +115,8 @@ export { partitionMaintenance } from './generate-partition';
113
115
  export type { PartitionRun, PartitionRunOptions } from './generate-partition-run';
114
116
  export { maintainPartitions, PARTITION_LOCK_TIMEOUT_MS } from './generate-partition-run';
115
117
  export type { RowSecurityOption, TenantColumnLike } from './generate-row-security';
118
+ export type { IndexKeyParts, IndexOperatorClass } from './index-key-ddl';
119
+ export { INDEX_OPERATOR_CLASSES, requiredExtension } from './index-key-ddl';
116
120
  export type { IndexMethod } from './index-method';
117
121
  export { declaredMethod, INDEX_METHODS, indexMethodOf, indexMethodSql } from './index-method';
118
122
  export type {
@@ -172,6 +176,14 @@ export {
172
176
  migrationSnapshotMissing,
173
177
  rollbackStepsInvalid,
174
178
  } from './migration-errors';
179
+ export type { LockHeavyKind, LockHeavyStatement } from './migration-lock-lint';
180
+ export {
181
+ LOCK_HEAVY_MARKER,
182
+ LOCK_HEAVY_SINCE,
183
+ lockHeavyJudged,
184
+ lockHeavyStatements,
185
+ migrationLockHeavy,
186
+ } from './migration-lock-lint';
175
187
  export type {
176
188
  PgliteClient,
177
189
  PgliteDriver,
@@ -243,6 +255,12 @@ export { assertRowSecurityBinds } from './row-security-role';
243
255
  export { APP_ROLE, MIGRATOR_ROLE, rowSecurityRolesSql, serveAsAppRole } from './row-security-roles';
244
256
  export { sameTenantKeyName } from './same-tenant';
245
257
  export { SIBLING_SCOPE_WAIT_MS } from './sibling-turn';
258
+ export type { SlowStatementLogOptions } from './slow-statement-log';
259
+ export {
260
+ SLOW_STATEMENT_THRESHOLD_MS,
261
+ SLOW_STATEMENT_WINDOW_MS,
262
+ slowStatementLog,
263
+ } from './slow-statement-log';
246
264
  export { snapshotJson } from './snapshot-json';
247
265
  export { parseSnapshot } from './snapshot-parse';
248
266
  export type { SqlFragment } from './sql';
@@ -255,6 +273,19 @@ export type { StatementBoundOptions } from './statement-bound';
255
273
  export { withStatementTimeout } from './statement-bound';
256
274
  export { statementFingerprint, statementKind, statementVerb } from './statement-shape';
257
275
  export { statementsOf } from './statement-split';
276
+ export type {
277
+ LiveTableStorage,
278
+ TableStorage,
279
+ TableStorageDifference,
280
+ TableStorageOptions,
281
+ } from './table-storage';
282
+ export {
283
+ readTableStorageDrift,
284
+ storageAlters,
285
+ tableDdl,
286
+ tableStorage,
287
+ tableStorageDrift,
288
+ } from './table-storage';
258
289
  export {
259
290
  completeTransaction,
260
291
  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
+ }