@ultimat3/db 31.47.1 → 31.49.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 +6 -5
- package/README.md +3 -2
- package/package.json +2 -2
- package/src/column-drop.ts +154 -0
- package/src/errors.ts +2 -0
- package/src/generate.ts +5 -38
- package/src/generated-column.ts +12 -4
- package/src/index-plan.ts +8 -0
- package/src/index.ts +1 -0
- package/src/migrate-dev-fix.ts +30 -0
- package/src/migrate-rollback.ts +8 -1
- package/src/migrate.ts +33 -10
- package/src/migration-errors.ts +67 -0
- package/src/migration-fork-fold.ts +215 -0
- package/src/migration-fork-sql.ts +133 -0
- package/src/migration-fork.ts +143 -0
- package/src/migration-ledger.ts +37 -1
- package/src/pool-profile.ts +2 -0
- package/src/replica-client.ts +7 -2
- package/src/retype-dependents.ts +17 -0
- package/src/rolling-errors.ts +25 -0
- package/src/schema-dump-entry.ts +10 -2
- package/src/snapshot-parse.ts +5 -0
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
// Single responsibility: the running answer to "what has this chain built so far", one migration at
|
|
2
|
+
// a time: an `up`'s events take objects away, its sidecar adds what it records. `migration-fork.ts`
|
|
3
|
+
// reads the result.
|
|
4
|
+
|
|
5
|
+
import type {
|
|
6
|
+
CheckDescription,
|
|
7
|
+
ColumnDescription,
|
|
8
|
+
ForeignKeyDescription,
|
|
9
|
+
IndexDescription,
|
|
10
|
+
SchemaDescription,
|
|
11
|
+
TableDescription,
|
|
12
|
+
ViewDescription,
|
|
13
|
+
} from './introspect';
|
|
14
|
+
import type { ForkCollision, ForkObjectKind } from './migration-fork';
|
|
15
|
+
import type { ForkEvent } from './migration-fork-sql';
|
|
16
|
+
import { nameOf, tokensOf } from './rolling';
|
|
17
|
+
|
|
18
|
+
export interface Fold {
|
|
19
|
+
readonly tables: Map<string, TableDescription>;
|
|
20
|
+
readonly views: Map<string, ViewDescription>;
|
|
21
|
+
readonly recordedBy: Map<string, string>;
|
|
22
|
+
/** Tables and columns only: an index's `create` may sit in a later concurrent step. */
|
|
23
|
+
readonly gone: Map<string, string>;
|
|
24
|
+
readonly collisions: ForkCollision[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const key = (kind: ForkObjectKind, table: string, name: string): string =>
|
|
28
|
+
`${kind}\0${table}\0${name}`;
|
|
29
|
+
|
|
30
|
+
export const byName = <T extends { readonly name: string }>(a: T, b: T): number =>
|
|
31
|
+
a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
|
|
32
|
+
|
|
33
|
+
const withoutNamed = <T extends { readonly name: string }>(
|
|
34
|
+
items: readonly T[],
|
|
35
|
+
name: string,
|
|
36
|
+
): readonly T[] => items.filter((item) => item.name !== name);
|
|
37
|
+
|
|
38
|
+
function dropConstraint(table: TableDescription, name: string): TableDescription {
|
|
39
|
+
return {
|
|
40
|
+
...table,
|
|
41
|
+
indexes: withoutNamed(table.indexes, name),
|
|
42
|
+
foreignKeys: withoutNamed(table.foreignKeys, name),
|
|
43
|
+
...(table.checks === undefined ? {} : { checks: withoutNamed(table.checks, name) }),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Postgres takes an index, key or check over a dropped column with it, and writes no statement. */
|
|
48
|
+
function dropColumn(table: TableDescription, column: string): TableDescription {
|
|
49
|
+
return {
|
|
50
|
+
...table,
|
|
51
|
+
columns: withoutNamed(table.columns, column),
|
|
52
|
+
indexes: table.indexes.filter((index) => !index.columns.includes(column)),
|
|
53
|
+
foreignKeys: table.foreignKeys.filter((foreign) => !foreign.columns.includes(column)),
|
|
54
|
+
...(table.checks === undefined
|
|
55
|
+
? {}
|
|
56
|
+
: {
|
|
57
|
+
checks: table.checks.filter(
|
|
58
|
+
(check) => !tokensOf(check.expression).map(nameOf).includes(column),
|
|
59
|
+
),
|
|
60
|
+
}),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function dropTable(fold: Fold, table: string, id: string): void {
|
|
65
|
+
fold.tables.delete(table);
|
|
66
|
+
fold.gone.set(key('table', table, table), id);
|
|
67
|
+
for (const [name, other] of fold.tables) {
|
|
68
|
+
fold.tables.set(name, {
|
|
69
|
+
...other,
|
|
70
|
+
foreignKeys: other.foreignKeys.filter((foreign) => foreign.referencedTable !== table),
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function collide(
|
|
76
|
+
fold: Fold,
|
|
77
|
+
kind: 'table' | 'column',
|
|
78
|
+
table: string,
|
|
79
|
+
name: string,
|
|
80
|
+
again: string,
|
|
81
|
+
): void {
|
|
82
|
+
const first = fold.recordedBy.get(key(kind, table, name)) ?? again;
|
|
83
|
+
fold.collisions.push({ kind, table, name, first, again });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function createTable(
|
|
87
|
+
fold: Fold,
|
|
88
|
+
event: Extract<ForkEvent, { op: 'create-table' }>,
|
|
89
|
+
id: string,
|
|
90
|
+
): void {
|
|
91
|
+
if (!event.guarded && fold.tables.has(event.table)) {
|
|
92
|
+
collide(fold, 'table', event.table, event.table, id);
|
|
93
|
+
}
|
|
94
|
+
fold.gone.delete(key('table', event.table, event.table));
|
|
95
|
+
const columnsOf = key('column', event.table, '');
|
|
96
|
+
for (const name of fold.gone.keys()) if (name.startsWith(columnsOf)) fold.gone.delete(name);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function addColumn(fold: Fold, event: Extract<ForkEvent, { op: 'add-column' }>, id: string): void {
|
|
100
|
+
const held = fold.tables.get(event.table)?.columns.some((c) => c.name === event.column) === true;
|
|
101
|
+
if (!event.guarded && held) collide(fold, 'column', event.table, event.column, id);
|
|
102
|
+
fold.gone.delete(key('column', event.table, event.column));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function renameTable(fold: Fold, table: string, to: string, id: string): void {
|
|
106
|
+
const held = fold.tables.get(table);
|
|
107
|
+
dropTable(fold, table, id);
|
|
108
|
+
if (held !== undefined) fold.tables.set(to, { ...held, name: to });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function mapTables(fold: Fold, change: (table: TableDescription) => TableDescription): void {
|
|
112
|
+
for (const [name, table] of fold.tables) fold.tables.set(name, change(table));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function apply(fold: Fold, event: ForkEvent, id: string): void {
|
|
116
|
+
const altered = 'table' in event ? fold.tables.get(event.table) : undefined;
|
|
117
|
+
switch (event.op) {
|
|
118
|
+
case 'create-table':
|
|
119
|
+
createTable(fold, event, id);
|
|
120
|
+
return;
|
|
121
|
+
case 'drop-table':
|
|
122
|
+
dropTable(fold, event.table, id);
|
|
123
|
+
return;
|
|
124
|
+
case 'rename-table':
|
|
125
|
+
renameTable(fold, event.table, event.to, id);
|
|
126
|
+
return;
|
|
127
|
+
case 'add-column':
|
|
128
|
+
addColumn(fold, event, id);
|
|
129
|
+
return;
|
|
130
|
+
case 'drop-column':
|
|
131
|
+
fold.gone.set(key('column', event.table, event.column), id);
|
|
132
|
+
if (altered !== undefined) fold.tables.set(event.table, dropColumn(altered, event.column));
|
|
133
|
+
return;
|
|
134
|
+
case 'drop-constraint':
|
|
135
|
+
if (altered !== undefined) fold.tables.set(event.table, dropConstraint(altered, event.name));
|
|
136
|
+
return;
|
|
137
|
+
case 'drop-index':
|
|
138
|
+
mapTables(fold, (table) => ({
|
|
139
|
+
...table,
|
|
140
|
+
indexes: withoutNamed(table.indexes, event.name),
|
|
141
|
+
}));
|
|
142
|
+
return;
|
|
143
|
+
case 'drop-view':
|
|
144
|
+
fold.views.delete(event.name);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** `next`, plus what only `held` has, in name order; `next` wins on a shared name. */
|
|
149
|
+
function union<T extends { readonly name: string }>(
|
|
150
|
+
held: readonly T[],
|
|
151
|
+
next: readonly T[],
|
|
152
|
+
): readonly T[] {
|
|
153
|
+
const names = new Set(next.map((item) => item.name));
|
|
154
|
+
const extra = held.filter((item) => !names.has(item.name));
|
|
155
|
+
return extra.length === 0 ? next : [...next, ...extra].sort(byName);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Dense and alphabetical, what `snapshotOf` writes, whenever the merge changed the set. */
|
|
159
|
+
function mergedColumns(
|
|
160
|
+
held: readonly ColumnDescription[],
|
|
161
|
+
next: readonly ColumnDescription[],
|
|
162
|
+
): readonly ColumnDescription[] {
|
|
163
|
+
const columns = union(held, next);
|
|
164
|
+
return columns === next
|
|
165
|
+
? next
|
|
166
|
+
: columns.map((column, index) => ({ ...column, position: index + 1 }));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function overlayTable(fold: Fold, next: TableDescription): TableDescription {
|
|
170
|
+
const kept = next.columns.filter(
|
|
171
|
+
(column) => !fold.gone.has(key('column', next.name, column.name)),
|
|
172
|
+
);
|
|
173
|
+
const stated = kept.length === next.columns.length ? next : { ...next, columns: kept };
|
|
174
|
+
const held = fold.tables.get(next.name);
|
|
175
|
+
if (held === undefined) return stated;
|
|
176
|
+
const checks: readonly CheckDescription[] = union(held.checks ?? [], stated.checks ?? []);
|
|
177
|
+
const indexes: readonly IndexDescription[] = union(held.indexes, stated.indexes);
|
|
178
|
+
const foreignKeys: readonly ForeignKeyDescription[] = union(held.foreignKeys, stated.foreignKeys);
|
|
179
|
+
return {
|
|
180
|
+
...stated,
|
|
181
|
+
columns: mergedColumns(held.columns, stated.columns),
|
|
182
|
+
indexes,
|
|
183
|
+
foreignKeys,
|
|
184
|
+
...(checks.length === 0 ? {} : { checks }),
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export const partsOf = (table: TableDescription) =>
|
|
189
|
+
[
|
|
190
|
+
['column', table.columns],
|
|
191
|
+
['index', table.indexes],
|
|
192
|
+
['foreign key', table.foreignKeys],
|
|
193
|
+
['check', table.checks ?? []],
|
|
194
|
+
] as const;
|
|
195
|
+
|
|
196
|
+
export function overlay(fold: Fold, snapshot: SchemaDescription, id: string): void {
|
|
197
|
+
for (const next of snapshot.tables) {
|
|
198
|
+
if (fold.gone.has(key('table', next.name, next.name))) continue;
|
|
199
|
+
const table = overlayTable(fold, next);
|
|
200
|
+
fold.tables.set(next.name, table);
|
|
201
|
+
const tableKey = key('table', next.name, next.name);
|
|
202
|
+
if (!fold.recordedBy.has(tableKey)) fold.recordedBy.set(tableKey, id);
|
|
203
|
+
for (const [kind, items] of partsOf(table)) {
|
|
204
|
+
for (const item of items) {
|
|
205
|
+
const itemKey = key(kind, next.name, item.name);
|
|
206
|
+
if (!fold.recordedBy.has(itemKey)) fold.recordedBy.set(itemKey, id);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
for (const view of snapshot.views ?? []) {
|
|
211
|
+
fold.views.set(view.name, view);
|
|
212
|
+
const viewKey = key('view', view.name, view.name);
|
|
213
|
+
if (!fold.recordedBy.has(viewKey)) fold.recordedBy.set(viewKey, id);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// Single responsibility: what one migration's `up` does to named schema objects, as far as the fork
|
|
2
|
+
// detector has to know. Read off the token stream `rolling.ts` already owns, so comments, literals
|
|
3
|
+
// and dollar bodies never read as DDL and no second tokenizer exists.
|
|
4
|
+
|
|
5
|
+
import { REBUILDABLE_DROP_CLAUSES } from './destructive';
|
|
6
|
+
import { alteredTable, isWord, nameOf, qualifiedNameAt, subcommands, tokensOf } from './rolling';
|
|
7
|
+
import { statementsOf } from './statement-split';
|
|
8
|
+
|
|
9
|
+
export type ForkEvent =
|
|
10
|
+
| { readonly op: 'create-table'; readonly table: string; readonly guarded: boolean }
|
|
11
|
+
| { readonly op: 'drop-table'; readonly table: string }
|
|
12
|
+
| { readonly op: 'rename-table'; readonly table: string; readonly to: string }
|
|
13
|
+
| {
|
|
14
|
+
readonly op: 'add-column';
|
|
15
|
+
readonly table: string;
|
|
16
|
+
readonly column: string;
|
|
17
|
+
readonly guarded: boolean;
|
|
18
|
+
}
|
|
19
|
+
| { readonly op: 'drop-column'; readonly table: string; readonly column: string }
|
|
20
|
+
| { readonly op: 'drop-constraint'; readonly table: string; readonly name: string }
|
|
21
|
+
| { readonly op: 'drop-index'; readonly name: string }
|
|
22
|
+
| { readonly op: 'drop-view'; readonly name: string };
|
|
23
|
+
|
|
24
|
+
/** `add <this>` opens a table constraint, never a column. */
|
|
25
|
+
const ADD_CONSTRAINT_WORDS = ['constraint', 'primary', 'unique', 'foreign', 'check', 'exclude'];
|
|
26
|
+
|
|
27
|
+
/** The position after `if exists` / `if not exists`, and whether one was there. */
|
|
28
|
+
function pastGuard(tokens: readonly string[], at: number): { at: number; guarded: boolean } {
|
|
29
|
+
if (isWord(tokens[at], 'if') && isWord(tokens[at + 1], 'exists')) {
|
|
30
|
+
return { at: at + 2, guarded: true };
|
|
31
|
+
}
|
|
32
|
+
if (
|
|
33
|
+
isWord(tokens[at], 'if') &&
|
|
34
|
+
isWord(tokens[at + 1], 'not') &&
|
|
35
|
+
isWord(tokens[at + 2], 'exists')
|
|
36
|
+
) {
|
|
37
|
+
return { at: at + 3, guarded: true };
|
|
38
|
+
}
|
|
39
|
+
return { at, guarded: false };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** `a, "b", public.c` from `start`: `drop table` and its kin take a list. */
|
|
43
|
+
function namesFrom(tokens: readonly string[], start: number): readonly string[] {
|
|
44
|
+
const names: string[] = [];
|
|
45
|
+
let at = start;
|
|
46
|
+
for (;;) {
|
|
47
|
+
const named = qualifiedNameAt(tokens, at);
|
|
48
|
+
if (named === undefined) return names;
|
|
49
|
+
names.push(named.name);
|
|
50
|
+
if (tokens[named.next] !== ',') return names;
|
|
51
|
+
at = named.next + 1;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function alterEvents(table: string, part: readonly string[]): readonly ForkEvent[] {
|
|
56
|
+
const [verb, second] = part;
|
|
57
|
+
if (second === undefined) return [];
|
|
58
|
+
if (isWord(verb, 'add')) {
|
|
59
|
+
if (ADD_CONSTRAINT_WORDS.includes(second.toLowerCase()) && !second.startsWith('"')) return [];
|
|
60
|
+
const { at, guarded } = pastGuard(part, isWord(second, 'column') ? 2 : 1);
|
|
61
|
+
const column = part[at];
|
|
62
|
+
return column === undefined
|
|
63
|
+
? []
|
|
64
|
+
: [{ op: 'add-column', table, column: nameOf(column), guarded }];
|
|
65
|
+
}
|
|
66
|
+
if (isWord(verb, 'drop')) {
|
|
67
|
+
if (isWord(second, 'constraint')) {
|
|
68
|
+
const name = part[pastGuard(part, 2).at];
|
|
69
|
+
return name === undefined ? [] : [{ op: 'drop-constraint', table, name: nameOf(name) }];
|
|
70
|
+
}
|
|
71
|
+
if (REBUILDABLE_DROP_CLAUSES.includes(second.toLowerCase())) return [];
|
|
72
|
+
const column = part[pastGuard(part, isWord(second, 'column') ? 2 : 1).at];
|
|
73
|
+
return column === undefined ? [] : [{ op: 'drop-column', table, column: nameOf(column) }];
|
|
74
|
+
}
|
|
75
|
+
if (!isWord(verb, 'rename')) return [];
|
|
76
|
+
if (isWord(second, 'to')) {
|
|
77
|
+
const to = part[2];
|
|
78
|
+
return to === undefined ? [] : [{ op: 'rename-table', table, to: nameOf(to) }];
|
|
79
|
+
}
|
|
80
|
+
if (isWord(second, 'constraint')) {
|
|
81
|
+
const name = part[2];
|
|
82
|
+
return name === undefined ? [] : [{ op: 'drop-constraint', table, name: nameOf(name) }];
|
|
83
|
+
}
|
|
84
|
+
// A renamed column leaves its old name behind; the sidecar beside it records the new one.
|
|
85
|
+
const column = isWord(second, 'column') ? part[2] : second;
|
|
86
|
+
return column === undefined ? [] : [{ op: 'drop-column', table, column: nameOf(column) }];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function dropEvents(tokens: readonly string[]): readonly ForkEvent[] {
|
|
90
|
+
if (isWord(tokens[1], 'table')) {
|
|
91
|
+
return namesFrom(tokens, pastGuard(tokens, 2).at).map((table) => ({ op: 'drop-table', table }));
|
|
92
|
+
}
|
|
93
|
+
if (isWord(tokens[1], 'index')) {
|
|
94
|
+
const after = isWord(tokens[2], 'concurrently') ? 3 : 2;
|
|
95
|
+
return namesFrom(tokens, pastGuard(tokens, after).at).map((name) => ({
|
|
96
|
+
op: 'drop-index',
|
|
97
|
+
name,
|
|
98
|
+
}));
|
|
99
|
+
}
|
|
100
|
+
const viewAt = isWord(tokens[1], 'materialized') ? 2 : 1;
|
|
101
|
+
if (!isWord(tokens[viewAt], 'view')) return [];
|
|
102
|
+
return namesFrom(tokens, pastGuard(tokens, viewAt + 1).at).map((name) => ({
|
|
103
|
+
op: 'drop-view',
|
|
104
|
+
name,
|
|
105
|
+
}));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function statementEvents(tokens: readonly string[]): readonly ForkEvent[] {
|
|
109
|
+
if (isWord(tokens[0], 'drop')) return dropEvents(tokens);
|
|
110
|
+
if (isWord(tokens[0], 'create')) {
|
|
111
|
+
const tableAt = isWord(tokens[1], 'unlogged') ? 2 : 1;
|
|
112
|
+
if (!isWord(tokens[tableAt], 'table')) return [];
|
|
113
|
+
const { at, guarded } = pastGuard(tokens, tableAt + 1);
|
|
114
|
+
const named = qualifiedNameAt(tokens, at);
|
|
115
|
+
return named === undefined ? [] : [{ op: 'create-table', table: named.name, guarded }];
|
|
116
|
+
}
|
|
117
|
+
if (isWord(tokens[0], 'alter') && isWord(tokens[1], 'index')) {
|
|
118
|
+
const { at } = pastGuard(tokens, 2);
|
|
119
|
+
const named = qualifiedNameAt(tokens, at);
|
|
120
|
+
return named !== undefined && isWord(tokens[named.next], 'rename')
|
|
121
|
+
? [{ op: 'drop-index', name: named.name }]
|
|
122
|
+
: [];
|
|
123
|
+
}
|
|
124
|
+
const altered = alteredTable(tokens);
|
|
125
|
+
if (altered === undefined) return [];
|
|
126
|
+
return subcommands(tokens.slice(altered.next)).flatMap((part) =>
|
|
127
|
+
alterEvents(altered.table, part),
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Every event of `up`, in apply order: a drop and a re-create in one file cancel by position. */
|
|
132
|
+
export const forkEventsOf = (up: string): readonly ForkEvent[] =>
|
|
133
|
+
statementsOf(up).flatMap((statement) => statementEvents(tokensOf(statement)));
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// Single responsibility: is this migration chain two branches' work merged side by side, and what
|
|
2
|
+
// schema does it really build? No database: the sidecars and the `up` text answer it.
|
|
3
|
+
//
|
|
4
|
+
// `x db gen` diffs against the newest sidecar, so two branches generated from one parent each write
|
|
5
|
+
// a sidecar that has never heard of the other's work. Every `.sql` stays valid; only the newest
|
|
6
|
+
// sidecar is wrong. Taking it at its word made `drift` ask for a second `create table`.
|
|
7
|
+
|
|
8
|
+
import type { SchemaDescription } from './introspect';
|
|
9
|
+
import { apply, byName, type Fold, key, overlay, partsOf } from './migration-fork-fold';
|
|
10
|
+
import { forkEventsOf } from './migration-fork-sql';
|
|
11
|
+
import type { Migration } from './migration-ledger';
|
|
12
|
+
|
|
13
|
+
export type ForkObjectKind = 'table' | 'column' | 'index' | 'foreign key' | 'check' | 'view';
|
|
14
|
+
|
|
15
|
+
/** Built by the chain, missing from the newest sidecar. */
|
|
16
|
+
export interface ForkLoss {
|
|
17
|
+
readonly kind: ForkObjectKind;
|
|
18
|
+
readonly table: string;
|
|
19
|
+
readonly name: string;
|
|
20
|
+
readonly recordedBy: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Dropped by the chain, still in the newest sidecar. */
|
|
24
|
+
export interface ForkStale {
|
|
25
|
+
readonly kind: 'table' | 'column';
|
|
26
|
+
readonly table: string;
|
|
27
|
+
readonly name: string;
|
|
28
|
+
readonly droppedBy: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Created twice with no guard: `again` fails on any database that ran `first`. */
|
|
32
|
+
export interface ForkCollision {
|
|
33
|
+
readonly kind: 'table' | 'column';
|
|
34
|
+
readonly table: string;
|
|
35
|
+
readonly name: string;
|
|
36
|
+
readonly first: string;
|
|
37
|
+
readonly again: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface MigrationFork {
|
|
41
|
+
readonly newest: string;
|
|
42
|
+
/** What the chain builds: the sidecar the newest migration should have written. */
|
|
43
|
+
readonly merged: SchemaDescription;
|
|
44
|
+
readonly lost: readonly ForkLoss[];
|
|
45
|
+
readonly stale: readonly ForkStale[];
|
|
46
|
+
readonly collisions: readonly ForkCollision[];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function lostFrom(fold: Fold, newest: SchemaDescription, newestId: string): readonly ForkLoss[] {
|
|
50
|
+
const recordedBy = (kind: ForkObjectKind, table: string, name: string): string =>
|
|
51
|
+
fold.recordedBy.get(key(kind, table, name)) ?? newestId;
|
|
52
|
+
const recorded = new Map(newest.tables.map((table) => [table.name, table]));
|
|
53
|
+
const lost: ForkLoss[] = [];
|
|
54
|
+
for (const table of [...fold.tables.values()].sort(byName)) {
|
|
55
|
+
const stated = recorded.get(table.name);
|
|
56
|
+
if (stated === undefined) {
|
|
57
|
+
const by = recordedBy('table', table.name, table.name);
|
|
58
|
+
lost.push({ kind: 'table', table: table.name, name: table.name, recordedBy: by });
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const statedParts = partsOf(stated);
|
|
62
|
+
partsOf(table).forEach(([kind, items], index) => {
|
|
63
|
+
const names = new Set((statedParts[index]?.[1] ?? []).map((item) => item.name));
|
|
64
|
+
for (const item of items) {
|
|
65
|
+
if (names.has(item.name)) continue;
|
|
66
|
+
const by = recordedBy(kind, table.name, item.name);
|
|
67
|
+
lost.push({ kind, table: table.name, name: item.name, recordedBy: by });
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
const views = new Set((newest.views ?? []).map((view) => view.name));
|
|
72
|
+
for (const view of [...fold.views.values()].sort(byName)) {
|
|
73
|
+
if (views.has(view.name)) continue;
|
|
74
|
+
const by = recordedBy('view', view.name, view.name);
|
|
75
|
+
lost.push({ kind: 'view', table: view.name, name: view.name, recordedBy: by });
|
|
76
|
+
}
|
|
77
|
+
return lost;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function staleFrom(fold: Fold, newest: SchemaDescription): readonly ForkStale[] {
|
|
81
|
+
const stale: ForkStale[] = [];
|
|
82
|
+
for (const table of newest.tables) {
|
|
83
|
+
const droppedTable = fold.gone.get(key('table', table.name, table.name));
|
|
84
|
+
if (droppedTable !== undefined) {
|
|
85
|
+
const name = table.name;
|
|
86
|
+
stale.push({ kind: 'table', table: name, name, droppedBy: droppedTable });
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
for (const column of table.columns) {
|
|
90
|
+
const droppedBy = fold.gone.get(key('column', table.name, column.name));
|
|
91
|
+
if (droppedBy === undefined) continue;
|
|
92
|
+
stale.push({ kind: 'column', table: table.name, name: column.name, droppedBy });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return stale;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The fork in `migrations`, or `undefined` for a chain that agrees with itself.
|
|
100
|
+
*
|
|
101
|
+
* A fold over the chain: every sidecar adds what it records, every `up` removes what it drops.
|
|
102
|
+
* What survives is what a replay builds, so it needs no record of which branch wrote what, and a
|
|
103
|
+
* loss a later sidecar restored is no loss. A migration with no sidecar was written by hand and may
|
|
104
|
+
* do anything, so what earlier sidecars claim ends there. A newest one with no sidecar is
|
|
105
|
+
* `X_MIGRATION_SNAPSHOT_MISSING`'s, and answers `undefined` here.
|
|
106
|
+
*/
|
|
107
|
+
export function migrationFork(migrations: readonly Migration[]): MigrationFork | undefined {
|
|
108
|
+
const ordered = [...migrations].sort((a, b) => (a.id < b.id ? -1 : 1));
|
|
109
|
+
const newest = ordered.at(-1);
|
|
110
|
+
if (newest?.snapshot === undefined) return undefined;
|
|
111
|
+
const fold: Fold = {
|
|
112
|
+
tables: new Map(),
|
|
113
|
+
views: new Map(),
|
|
114
|
+
recordedBy: new Map(),
|
|
115
|
+
gone: new Map(),
|
|
116
|
+
collisions: [],
|
|
117
|
+
};
|
|
118
|
+
for (const migration of ordered) {
|
|
119
|
+
if (migration.snapshot === undefined) {
|
|
120
|
+
fold.tables.clear();
|
|
121
|
+
fold.views.clear();
|
|
122
|
+
fold.gone.clear();
|
|
123
|
+
fold.recordedBy.clear();
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
for (const event of forkEventsOf(migration.up)) apply(fold, event, migration.id);
|
|
127
|
+
overlay(fold, migration.snapshot, migration.id);
|
|
128
|
+
}
|
|
129
|
+
const lost = lostFrom(fold, newest.snapshot, newest.id);
|
|
130
|
+
const stale = staleFrom(fold, newest.snapshot);
|
|
131
|
+
if (lost.length === 0 && stale.length === 0 && fold.collisions.length === 0) return undefined;
|
|
132
|
+
const views = [...fold.views.values()].sort(byName);
|
|
133
|
+
return {
|
|
134
|
+
newest: newest.id,
|
|
135
|
+
merged: {
|
|
136
|
+
tables: [...fold.tables.values()].sort(byName),
|
|
137
|
+
...(views.length === 0 ? {} : { views }),
|
|
138
|
+
},
|
|
139
|
+
lost,
|
|
140
|
+
stale,
|
|
141
|
+
collisions: fold.collisions,
|
|
142
|
+
};
|
|
143
|
+
}
|
package/src/migration-ledger.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import { isFixShellSafe } from '@ultimat3/core';
|
|
7
7
|
import type { DbClient } from './client';
|
|
8
8
|
import type { SchemaDescription } from './introspect';
|
|
9
|
+
import { embeddedDev, embeddedResetFix } from './migrate-dev-fix';
|
|
9
10
|
import { migrationConflict } from './migration-errors';
|
|
10
11
|
import { raw, sql } from './sql';
|
|
11
12
|
import { SQLSTATE, sqlState } from './sqlstate';
|
|
@@ -157,7 +158,15 @@ export function auditLedger(
|
|
|
157
158
|
const editedMigrationFix = (id: string, checksum: string): string => {
|
|
158
159
|
const path = isFixShellSafe(id) ? `${APP_MIGRATIONS_DIR}/${id}.sql` : APP_MIGRATIONS_DIR;
|
|
159
160
|
const applied = isFixShellSafe(checksum) ? `checksum ${checksum}` : 'the checksum in the cause';
|
|
160
|
-
|
|
161
|
+
const restore = `git log --format='%h %ad %s' --date=short -- ${path} # restore the revision applied with ${applied}: git checkout <rev> -- ${path} and never edit an applied migration; then x db gen "<change>"`;
|
|
162
|
+
// A migration written this session has no revision to list, and the embedded database is the
|
|
163
|
+
// only one that applied it: re-applying the file on disk IS the repair. The restore stays in
|
|
164
|
+
// the line for the migration some other database applied too.
|
|
165
|
+
return embeddedDev()
|
|
166
|
+
? embeddedResetFix(
|
|
167
|
+
`the edited migration is re-applied as it now reads. If it is committed or another database applied it, restore it instead: ${restore.replace(' # ', ' — ')}`,
|
|
168
|
+
)
|
|
169
|
+
: restore;
|
|
161
170
|
};
|
|
162
171
|
|
|
163
172
|
/**
|
|
@@ -181,6 +190,13 @@ const editedMigrationFix = (id: string, checksum: string): string => {
|
|
|
181
190
|
* which migration this is, `fix:` is where they paste. `psql` echoes the row count it deleted.
|
|
182
191
|
*/
|
|
183
192
|
function conflictFix(row: LedgerRow): string {
|
|
193
|
+
// `DATABASE_URL` is empty on the embedded database, so psql has nothing to dial; and the row is
|
|
194
|
+
// there because this checkout dropped the file, not because another build is deployed.
|
|
195
|
+
if (embeddedDev()) {
|
|
196
|
+
return embeddedResetFix(
|
|
197
|
+
'the ledger records a migration whose file this checkout no longer holds; to keep the rows, restore the file (git status --short -- packages/db/migrations)',
|
|
198
|
+
);
|
|
199
|
+
}
|
|
184
200
|
const encodedId = Buffer.from(row.id, 'utf8').toString('base64');
|
|
185
201
|
return (
|
|
186
202
|
'deploy the app version this error names — or, if that build is gone, drop its row: ' +
|
|
@@ -189,6 +205,26 @@ function conflictFix(row: LedgerRow): string {
|
|
|
189
205
|
);
|
|
190
206
|
}
|
|
191
207
|
|
|
208
|
+
/**
|
|
209
|
+
* The `steps` rows a rollback reverses: the most recently APPLIED first, never the highest id. A
|
|
210
|
+
* branch merged late applies an older id after a newer one, and reversing by id then undoes the
|
|
211
|
+
* previous release's migration while the one just shipped stays applied. Rows sharing an
|
|
212
|
+
* `applied_at` (one run on a coarse clock, a restored dump) fall back to id descending, which is
|
|
213
|
+
* one run read backwards: a run applies in id order. Every ledger any release wrote has the column
|
|
214
|
+
* (`not null default now()`); a value no driver could parse ties rather than guessing an order.
|
|
215
|
+
*/
|
|
216
|
+
export function rollbackTargets(ledger: readonly LedgerRow[], steps: number): readonly LedgerRow[] {
|
|
217
|
+
// `applied_at` is typed as text but a driver hands back a `Date`: both construct one.
|
|
218
|
+
const at = (row: LedgerRow): number => new Date(row.applied_at).getTime();
|
|
219
|
+
return [...ledger]
|
|
220
|
+
.sort((a, b) => {
|
|
221
|
+
const later = at(b) - at(a);
|
|
222
|
+
if (later > 0 || later < 0) return later;
|
|
223
|
+
return a.id < b.id ? 1 : a.id > b.id ? -1 : 0;
|
|
224
|
+
})
|
|
225
|
+
.slice(0, steps);
|
|
226
|
+
}
|
|
227
|
+
|
|
192
228
|
export function pendingMigrations(
|
|
193
229
|
ledger: readonly LedgerRow[],
|
|
194
230
|
migrations: readonly Migration[],
|
package/src/pool-profile.ts
CHANGED
|
@@ -131,6 +131,8 @@ export const POOL_MAX_ENV = 'DATABASE_POOL_MAX';
|
|
|
131
131
|
* `max: 20` is 8,000 backends against a `max_connections` of 450. An unparseable value **refuses**
|
|
132
132
|
* rather than falling back: a fleet that ignored the number it was given is the failure the
|
|
133
133
|
* variable exists to prevent, and it would only be found in `pg_stat_activity` at 3am.
|
|
134
|
+
* Per CONTAINER: a supervised container (`ULTIMATE_PROCESSES` > 1) hands each child its
|
|
135
|
+
* `childShare` of it, so the container's connections do not grow with its processes.
|
|
134
136
|
*/
|
|
135
137
|
export function poolMaxFromEnv(
|
|
136
138
|
env: Readonly<Record<string, string | undefined>> = process.env,
|
package/src/replica-client.ts
CHANGED
|
@@ -141,8 +141,13 @@ export function replicatedClient(
|
|
|
141
141
|
// Read-your-writes ACROSS requests: an earlier request's write the replica has not replayed yet.
|
|
142
142
|
// Before `admit()`, never after: `admit()` spends the half-open probe, and a read then sent to
|
|
143
143
|
// the primary for being behind would strand the probe until it lapsed.
|
|
144
|
-
|
|
145
|
-
|
|
144
|
+
//
|
|
145
|
+
// A PARKED replica is not asked at all: the question is a statement on the standby, so every
|
|
146
|
+
// request carrying a position paid the dead replica's whole connect or statement timeout
|
|
147
|
+
// before reaching the primary — the outage the breaker exists to keep off the request path.
|
|
148
|
+
// `state()` only reads, so the half-open probe is still there once the cooldown lapses.
|
|
149
|
+
if (scope.minPosition !== undefined) {
|
|
150
|
+
if (parked() || !(await replay.caughtUp(scope.minPosition))) return undefined;
|
|
146
151
|
}
|
|
147
152
|
// Last, so only a statement about to reach the replica consumes the half-open probe.
|
|
148
153
|
return gate.admit();
|
package/src/retype-dependents.ts
CHANGED
|
@@ -64,6 +64,23 @@ export function referencesColumn(expression: string, column: string): boolean {
|
|
|
64
64
|
return false;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
/**
|
|
68
|
+
* Whether `drop column` takes `index` with it: Postgres drops every index that DEPENDS on the
|
|
69
|
+
* column — keyed by it, carrying it as INCLUDE payload, or reading it in its predicate or its
|
|
70
|
+
* expression key (measured on PGlite: `posts_p on (title) where "legacy" is not null` goes with
|
|
71
|
+
* `legacy`). A catalog-read expression key sits in `columns` in parentheses, so it is read too.
|
|
72
|
+
*/
|
|
73
|
+
export function indexDependsOn(index: IndexDescription, column: string): boolean {
|
|
74
|
+
return (
|
|
75
|
+
index.columns.some((key) =>
|
|
76
|
+
key.startsWith('(') ? referencesColumn(key, column) : key === column,
|
|
77
|
+
) ||
|
|
78
|
+
(index.include ?? []).includes(column) ||
|
|
79
|
+
(index.where !== null && referencesColumn(index.where, column)) ||
|
|
80
|
+
(index.expression !== undefined && referencesColumn(index.expression, column))
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
67
84
|
/** The recorded objects a retype of `column` cannot leave in place. */
|
|
68
85
|
export interface RetypeDependents {
|
|
69
86
|
/**
|
package/src/rolling-errors.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import { renderFixShellArg } from '@ultimat3/core';
|
|
6
6
|
import { DbError } from './errors';
|
|
7
|
+
import { migrationNameArg } from './primary-key';
|
|
7
8
|
import type { RetireAndContract, RollingUnsafeStatement } from './rolling';
|
|
8
9
|
|
|
9
10
|
const CODE = 'X_MIGRATION_ROLLING_UNSAFE';
|
|
@@ -37,6 +38,30 @@ export const columnDropNotRetired = (
|
|
|
37
38
|
meta: { table, column },
|
|
38
39
|
});
|
|
39
40
|
|
|
41
|
+
/**
|
|
42
|
+
* `x db gen`: a plain column declared generated is dropped and added back computed
|
|
43
|
+
* (`regenerate`), with no `retired` in between. The same fact as `columnDropNotRetired` from the
|
|
44
|
+
* other side: the previous release still WRITES it. `migration` is the name as given: this one
|
|
45
|
+
* prints it back as the argument it was (`migrationNameArg`), so the command can be pasted.
|
|
46
|
+
*/
|
|
47
|
+
export const columnRebuildNotRetired = (
|
|
48
|
+
entity: string,
|
|
49
|
+
table: string,
|
|
50
|
+
column: string,
|
|
51
|
+
migration: string,
|
|
52
|
+
): DbError => {
|
|
53
|
+
const c = renderFixShellArg(column, '<column>');
|
|
54
|
+
const gen = `x db gen ${migrationNameArg(migration)} --allow-destructive`;
|
|
55
|
+
return new DbError({
|
|
56
|
+
code: CODE,
|
|
57
|
+
cause:
|
|
58
|
+
`making "${table}"."${column}" a generated column drops it and adds it back computed, and the ` +
|
|
59
|
+
'pods still running the previous release write it: Postgres refuses a value for a generated column (428C9)',
|
|
60
|
+
fix: `entity('${renderFixShellArg(entity, '<entity>')}', { retired: ['${c}'] }) # with ${c} out of columns; then x db gen "retire ${c}", deploy, then declare it generated and ${gen} — one instance that stops before the next starts: ${gen} --rolling-unsafe`,
|
|
61
|
+
meta: { table, column },
|
|
62
|
+
});
|
|
63
|
+
};
|
|
64
|
+
|
|
40
65
|
/** `retired` names what no migration recorded, or a column the entity still declares. */
|
|
41
66
|
export const retiredNameUnknown = (entity: string, table: string, column: string): DbError =>
|
|
42
67
|
new DbError({
|
package/src/schema-dump-entry.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// `@ultimat3/db/schema-dump`: the whole schema as files, and the drift checks over them. Its own
|
|
2
2
|
// entry because only three callers ever run it — `x db gen`, `x db migrate` and the gate's `drift`
|
|
3
|
-
// step — while `@ultimat3/db` is imported by every role of every app: on the barrel these
|
|
4
|
-
//
|
|
3
|
+
// step — while `@ultimat3/db` is imported by every role of every app: on the barrel these modules
|
|
4
|
+
// were evaluated by every web, worker and scheduler pod to serve nothing. The fork check too.
|
|
5
5
|
|
|
6
6
|
export type {
|
|
7
7
|
CatalogColumn,
|
|
@@ -32,6 +32,14 @@ export {
|
|
|
32
32
|
} from './dump-drift';
|
|
33
33
|
export type { IntrospectCatalogOptions } from './introspect-catalog';
|
|
34
34
|
export { introspectCatalog } from './introspect-catalog';
|
|
35
|
+
export type {
|
|
36
|
+
ForkCollision,
|
|
37
|
+
ForkLoss,
|
|
38
|
+
ForkObjectKind,
|
|
39
|
+
ForkStale,
|
|
40
|
+
MigrationFork,
|
|
41
|
+
} from './migration-fork';
|
|
42
|
+
export { migrationFork } from './migration-fork';
|
|
35
43
|
export { unexpectedObjects } from './object-drift';
|
|
36
44
|
export type { SchemaDumpFile } from './schema-dump';
|
|
37
45
|
export { renderSchemaDump } from './schema-dump';
|