@ultimat3/db 31.6.1 → 31.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +32 -31
- package/README.md +4 -0
- package/package.json +2 -2
- package/src/client.ts +2 -2
- package/src/drift-findings.ts +4 -1
- package/src/drift-index-keys.ts +54 -0
- package/src/drift.ts +14 -2
- package/src/entity-shape.ts +27 -5
- package/src/errors.ts +2 -0
- package/src/generate-history.ts +8 -2
- package/src/generate-snapshot.ts +3 -0
- package/src/generate.ts +9 -1
- package/src/index-ddl.ts +17 -6
- package/src/index-extension.ts +34 -0
- package/src/index-key-ddl.ts +159 -0
- package/src/index-plan.ts +38 -6
- package/src/index.ts +29 -0
- package/src/introspect-index.ts +110 -0
- package/src/introspect.ts +11 -52
- package/src/migration-lock-lint.ts +184 -0
- package/src/pin-statement.ts +154 -0
- package/src/pool-gate.ts +68 -13
- package/src/pool-pins.ts +74 -17
- package/src/rolling.ts +25 -12
- package/src/slow-statement-log.ts +103 -0
- package/src/snapshot-parse.ts +15 -0
- package/src/table-storage.ts +222 -0
|
@@ -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 {
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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,
|