@ultimat3/db 31.48.0 → 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
package/CLAUDE.md
CHANGED
|
@@ -124,6 +124,7 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
|
|
|
124
124
|
- **`migration-lock-lint.ts`** — `X_MIGRATION_LOCK_HEAVY`: `set not null` with no prior validate,
|
|
125
125
|
non-concurrent `create index` on an existing table; `-- lock-heavy: true` admits; ids > `LOCK_HEAVY_SINCE`.
|
|
126
126
|
- **The ledger audit asks one question**: `auditLedger`'s `foreign` is `!known.has(row.id)`.
|
|
127
|
+
- **Embedded dev's fix is `embeddedResetFix()`** at every `X_MIGRATION_CONFLICT` / `_ROLLBACK_DESTRUCTIVE` site when `embeddedDev()`. `rollback({ confirm })`: under the lock, before any `down`. Why: `docs/history/db.md` (2026-11-19).
|
|
127
128
|
- **`refuseDependentViews(tx, script)`** (`dependent-view.ts`) runs before each migration's first statement. Full rule: `docs/history/db.md`.
|
|
128
129
|
|
|
129
130
|
## Generation (`x db gen`)
|
|
@@ -145,17 +146,17 @@ consults `currentTx()`; `withTransaction` uses `baseClient()`, never `db()`. Kee
|
|
|
145
146
|
every migration on disk stays byte-identical (`generate-default.live.test.ts`, `sql.test.ts`).
|
|
146
147
|
`readonly-role.ts` and `branch.ts` are safe only by their ordering after `identifier()`.
|
|
147
148
|
- **A retype spans its default** (`retypeOverDefault`): `42804` otherwise.
|
|
148
|
-
- **A retype moves its dependents aside** (`retype-dependents.ts`, `retype-keys.ts`):
|
|
149
|
-
- **A generated column** (`generated-column.ts`): plain → generated rebuilds (`rebuilt`)
|
|
150
|
-
|
|
149
|
+
- **A retype moves its dependents aside** (`retype-dependents.ts`, `retype-keys.ts`): the ordinary diff puts them back, never twice. Full rule: `docs/history/db.md`.
|
|
150
|
+
- **A generated column** (`generated-column.ts`): plain → generated rebuilds (`rebuilt`), consented
|
|
151
|
+
as a drop (`column-drop.ts`); rest: `docs/history/db.md` (2026-10-31). `generate-generated-{column,rebuild}.live.test.ts`.
|
|
151
152
|
- **`REPLICA IDENTITY FULL` is a PARAMETER** (`GenerateOptions.replicaIdentityFull`, from the CLI's
|
|
152
153
|
`db-generate.ts`; `replica-identity.ts`): recorded `true` or absent, as a union; last in `up`; an
|
|
153
154
|
undeclared name skipped; `down` reverts it unless this migration created the table.
|
|
154
155
|
- **`appendOnly: true` is a trigger** (`generate-append-only.ts`, `ultimate_append_only`); drift is
|
|
155
156
|
`X_APPEND_ONLY_TRIGGER_MISSING` (`drift-append-only.ts`). Full rule: `docs/history/db.md`.
|
|
156
157
|
- **A foreign key is `alter table … add constraint`** after every table statement (`foreign-key-plan.ts`); a table drop's bucket runs first, children-first (`drop-order.ts`). Full rule: `docs/history/db.md`.
|
|
157
|
-
- **`same-tenant.ts`**: `sameTenant` is `foreignKeysOf`'s composite; `withSameTenantIndexes` opens `generateMigration` and `snapshotOf`, idempotent
|
|
158
|
-
- **The deferred step holds keys too** (`concurrent-plan.ts`, phases in `stepStatements
|
|
158
|
+
- **`same-tenant.ts`**: `sameTenant` is `foreignKeysOf`'s composite; `withSameTenantIndexes` opens `generateMigration` and `snapshotOf`, idempotent; `set null (a)` is one spelling. `foreign-key-plan.test.ts`. Why: `docs/history/db.md` (2026-11-02).
|
|
159
|
+
- **The deferred step holds keys too** (`concurrent-plan.ts`, phases in `stepStatements`; `down` reversed). Full rule: `docs/history/db.md`.
|
|
159
160
|
- **Lifecycle triggers are one list per table** (`generate-triggers.ts`: `declaredTriggers`,
|
|
160
161
|
`triggerPlan`, `recordTriggers`): `history` → `ultimate_history` + `ultimate_history_guard`
|
|
161
162
|
(`generate-history.ts`), each `countedIn` → `ultimate_count_<crc32>` on the CHILD
|
package/README.md
CHANGED
|
@@ -46,7 +46,7 @@ await withTransaction(async (tx) => {
|
|
|
46
46
|
| `completeTransaction()` / `refuseAbandoned()` | `As of 2026-11-02`: the mark that takes the open root's statements and COMMIT past an abandoned scope (a keyed action's), and the check for a write that goes through no `DbTx` (`@ultimat3/entity`'s `writing()`, the enqueue facade) → [Transactions that end badly](#transactions-that-end-badly) |
|
|
47
47
|
| `liveTxConnection()` | the connection of the transaction still **open** on this async context, or `undefined`. `currentTx()` keeps answering a finished scope's handle to a promise chain the body forgot to await; this is the one that says whether a statement sent now is really inside a transaction. `@ultimat3/action` reads it before binding an idempotency settlement to a commit |
|
|
48
48
|
| `sqlState()` / `isRetryableState()` / `SQLSTATE` | `As of 2026-08`: the SQLSTATE a driver error carries, and the closed table from it to a code. `Bun.SQL` puts it on `errno`; PGlite puts it on `code`; **one** reader answers for both |
|
|
49
|
-
| `migrate()` / `rollback()` / `readLedger()` | the `x_migrations` ledger |
|
|
49
|
+
| `migrate()` / `rollback()` / `readLedger()` | the `x_migrations` ledger. `rollback({ steps })` reverses the most recently **applied** migrations (`applied_at`, then id, both descending), `As of 2026-11-19` — not the highest ids: a branch merged late applies an older id after a newer one, and is the first undone. `rollback({ confirm })` is called once, under the migrate lock and before the first `down`, with the exact `LedgerRow`s about to be reversed: throw (or return a promise that rejects — it is awaited) to refuse, and nothing is reversed. `x db rollback [--steps n]` is the command over it. On the embedded development database (`development`, no `DATABASE_URL`) `X_MIGRATION_CONFLICT` and `X_MIGRATION_ROLLBACK_DESTRUCTIVE` lead their fix with `x stop --json && x db reset` (rows lost; `x db seed` refills) in place of `psql "$DATABASE_URL"` and `x deploy --image`, which have nothing to dial there; restoring the file (`git status`, `git log` for an edit) stays in the line |
|
|
50
50
|
| `ledgerAheadOfBuild()` / `ROLLBACK_ALLOW_DESTRUCTIVE_ENV` | `As of 31.30`: the ledger split when it is exactly a rollback onto a newer build's schema (every unknown row newer than the newest shipped, nothing pending), else `undefined` and `auditLedger` refuses it; a destructive row ahead throws `X_MIGRATION_ROLLBACK_DESTRUCTIVE` unless named in the variable. `migrate()`'s own first step, exported so `x db status` judges a ledger as `x db migrate` will |
|
|
51
51
|
| `statementsOf()` | `As of 2026-08`: a SQL script → the statements a driver sends one at a time. One send is one statement, so `migrate()` splits with this — a `;` inside a literal, an identifier, a dollar-quoted body or a comment is data |
|
|
52
52
|
| `withReplicaReads()` | `As of 2026-08-24`: the scope inside which a plain read may be served by a replica — until it writes, after which every read in it is the primary's. No scope open, nothing routes |
|
|
@@ -73,6 +73,7 @@ await withTransaction(async (tx) => {
|
|
|
73
73
|
| `isNonTransactional()` / `NO_TRANSACTION_MARKER` / `isConcurrentIndexStatement()` / `concurrentIndexTarget()` | `As of 2026-10-31`: the `-- transaction: false` marker a migration carries to run outside a transaction, and the concurrent index statements that need it → [Indexes built concurrently](#indexes-built-concurrently-and-every-index-drop) |
|
|
74
74
|
| `rollingUnsafeStatements()` / `hasRollingUnsafeMarker()` / `ROLLING_UNSAFE_MARKER` / `retiredColumnsIn()` / `retireAndContractPending()` / `migrationRollingUnsafe()` | `As of 2026-11-02`: the rolling-deploy rail — would the previous release trip over this `up`? A closed list (`drop column` with no earlier `-- retires`, `rename column`, `rename table`), read by the `drift` step past `rollingSince`, and the pair `migrate()` refuses pending together in production |
|
|
75
75
|
| `recordRetired()` | `As of 2026-11-02`: `snapshotOf` one step on, keeping a retired column and what hangs off it on the record. `x db gen` and the `drift` step both read through it, so they cannot disagree about one |
|
|
76
|
+
| a column leaving a table (`column-drop.ts`) | `As of 2026-11-19`: a plain column declared `generated` is `drop column` + `add column`, so it is asked what an ordinary drop is asked — `X_MIGRATION_ROLLING_UNSAFE` unless the column was retired first or `rollingUnsafe` is set, then `X_MIGRATION_IRREVERSIBLE` unless `allowDestructive` — and the result carries `rollingUnsafe: true` for a column never retired. The `down` of any column drop re-creates the indexes and foreign keys the previous snapshot recorded over the column (a key whose target table the same migration drops is a `--` note); the rows are not restored. An index counts as over the column when it depends on it any way Postgres drops it for — a key, an `include` column, a partial predicate or an expression that reads it — so its restore is in the drop's own `down`, never a follow-up step's. A `.snapshot.json` whose `dataType` holds a second statement is not a snapshot (`parseSnapshot` answers `undefined`) |
|
|
76
77
|
| `destructiveStatements()` / `hasDestructiveMarker()` / `isDestructiveMigration()` / `DESTRUCTIVE_MARKER` | `As of 2026-08`: the destructive-SQL rail — does this `up` drop, truncate or retype, and does the file declare it with `-- destructive: true`? One classifier, read by `x db gen` when it writes the marker and by `x verify` when it demands one |
|
|
77
78
|
| `stripSqlNoise()` | comments, literals, dollar-quoted bodies and quoted identifiers blanked **in source order**, so a reader sees the operation and not the prose. Shared by `readOnlyQuery()` and the destructive rail |
|
|
78
79
|
| `introspectSchema()` | live schema → `SchemaDescription`. **App tables only**, `As of 2026-08-24`: a relation an extension owns (`pg_depend`, `deptype = 'e'`) and anything that is not an ordinary or partitioned table are excluded before the fold, and an explicit `exclude` cannot bring them back. **A partition is not app schema either** (`relispartition`, `As of 2026-11-06`): its parent is judged — keys, indexes, checks, triggers — and carries `partitioned: true`; a key Postgres clones per partition (`conparentid <> 0`) is not read |
|
|
@@ -354,7 +355,7 @@ await withReplicaReads(async () => {
|
|
|
354
355
|
| read-your-writes | one write anywhere in the scope, at any depth, across any `await`, and every later read in it is the primary's |
|
|
355
356
|
| a transaction | always the primary — `reserve()` is delegated there, so BEGIN, the body and COMMIT are one connection on one server. A `readOnly: true` transaction leaves the scope clean |
|
|
356
357
|
| eligibility | `select` / `table` / `values` / a read-only `with`, minus locking reads, `select … into` and the functions a standby answers instead of refusing (`pg_advisory_lock`, `set_config`, `nextval`). Everything else is the primary's |
|
|
357
|
-
| across requests (`As of 2026-11`) | `withReplicaReads(fn, { minPosition })`: a read goes to the standby only once its `pg_last_wal_replay_lsn()` has passed `minPosition` — sampled once per `positionCacheMs` (50 ms) per client, checked BEFORE the breaker's `admit()` so a read sent to the primary for being behind never spends the half-open probe. Unknown or `null` is the primary. `parsePosition` / `formatPosition` / `primaryPosition` (`replica-position.ts`); `ReplicatedClient.primaryPosition()` reads the primary's WAL position. The boot carries it as `__Host-x-pos` + `x-ultimate-position` |
|
|
358
|
+
| across requests (`As of 2026-11`) | `withReplicaReads(fn, { minPosition })`: a read goes to the standby only once its `pg_last_wal_replay_lsn()` has passed `minPosition` — sampled once per `positionCacheMs` (50 ms) per client, checked BEFORE the breaker's `admit()` so a read sent to the primary for being behind never spends the half-open probe. Unknown or `null` is the primary. A PARKED replica is not asked at all (`As of 2026-11-19`): the read is the primary's with no statement sent to the standby, so an outage adds no replica timeout to a request that carries a position. `parsePosition` / `formatPosition` / `primaryPosition` (`replica-position.ts`); `ReplicatedClient.primaryPosition()` reads the primary's WAL position. The boot carries it as `__Host-x-pos` + `x-ultimate-position` |
|
|
358
359
|
| a replica that fails | the statement is re-run on the primary — exactly-once, because only plain reads are sent there and a `25006` refusal never executed. Three failures in a row park it for ten seconds |
|
|
359
360
|
| observability | `client.stats` (`replica`, `primary`, `fallbacks`, `parked`), and a `db.replica_fallback` warning per fallback |
|
|
360
361
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/db",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.49.0",
|
|
4
4
|
"description": "Postgres access, transactions, migrations and drift detection",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"test": "bun test"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@ultimat3/core": "31.
|
|
48
|
+
"@ultimat3/core": "31.49.0"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
51
51
|
"@electric-sql/pglite": ">=0.5.0"
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// Single responsibility: a column leaving a table — the two consents its loss is asked for, the
|
|
2
|
+
// `drop column`, and what `down` puts back. Split from `generate.ts` at its size ceiling, and
|
|
3
|
+
// because `regenerate`'s plain -> generated rebuild is the same drop and must meet the same gate.
|
|
4
|
+
|
|
5
|
+
import { renderFixShellArg } from '@ultimat3/core';
|
|
6
|
+
import type { EntityDescriptionLike } from './entity-shape';
|
|
7
|
+
import { addForeignKey, keyId, unrestorableNote } from './foreign-key';
|
|
8
|
+
import type { ConstraintPlans, Plan } from './foreign-key-plan';
|
|
9
|
+
import { becomesGenerated } from './generated-column';
|
|
10
|
+
import { asDeclared, createIndex } from './index-ddl';
|
|
11
|
+
import type { ColumnDescription, TableDescription } from './introspect';
|
|
12
|
+
import { migrationIrreversible } from './migration-errors';
|
|
13
|
+
import { migrationNameArg } from './primary-key';
|
|
14
|
+
import { contractsMarkerFor } from './retired';
|
|
15
|
+
import { indexDependsOn } from './retype-dependents';
|
|
16
|
+
import { columnDropNotRetired, columnRebuildNotRetired } from './rolling-errors';
|
|
17
|
+
import { identifier } from './sql';
|
|
18
|
+
|
|
19
|
+
/** The three `GenerateOptions` fields a drop reads: the migration's name and the two flags. */
|
|
20
|
+
export interface DropConsent {
|
|
21
|
+
readonly name: string;
|
|
22
|
+
readonly allowDestructive?: boolean | undefined;
|
|
23
|
+
readonly rollingUnsafe?: boolean | undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Order matters: the release boundary first, with the flag or without it. Retiring is what earns
|
|
28
|
+
* the next question; it is never consent to losing the rows, so that one still stands. Answers
|
|
29
|
+
* whether the column goes without having been retired, which is what `-- rolling-unsafe: true`
|
|
30
|
+
* records on the file.
|
|
31
|
+
*/
|
|
32
|
+
function admitted(
|
|
33
|
+
entity: EntityDescriptionLike,
|
|
34
|
+
column: ColumnDescription,
|
|
35
|
+
consent: DropConsent,
|
|
36
|
+
rebuilt: boolean,
|
|
37
|
+
): boolean {
|
|
38
|
+
const unretired = column.retired !== true;
|
|
39
|
+
const name = migrationNameArg(consent.name);
|
|
40
|
+
// A column's name is a sidecar's to choose, so it reaches a `fix:` through the shell screen.
|
|
41
|
+
const shown = renderFixShellArg(column.name, '<column>');
|
|
42
|
+
if (unretired && consent.rollingUnsafe !== true) {
|
|
43
|
+
throw rebuilt
|
|
44
|
+
? columnRebuildNotRetired(entity.name, entity.table, column.name, consent.name)
|
|
45
|
+
: columnDropNotRetired(entity.name, entity.table, column.name, name);
|
|
46
|
+
}
|
|
47
|
+
if (consent.allowDestructive !== true) {
|
|
48
|
+
throw rebuilt
|
|
49
|
+
? migrationIrreversible(
|
|
50
|
+
`making "${entity.table}"."${column.name}" a generated column drops it and adds it back computed, which discards every value stored in it and cannot be undone`,
|
|
51
|
+
`x db gen ${name} --allow-destructive # or keep "${shown}" plain and declare the generated column under a new name`,
|
|
52
|
+
)
|
|
53
|
+
: migrationIrreversible(
|
|
54
|
+
`dropping "${entity.table}"."${column.name}" discards its rows and cannot be undone`,
|
|
55
|
+
`x db gen ${name} --allow-destructive # or put "${shown}" back in columns and keep it`,
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
return unretired;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* A plain column the entity now declares generated is `drop column` + `add column`
|
|
63
|
+
* (`regenerate`): the stored values are gone and a pod of the previous release still writes the
|
|
64
|
+
* column, which Postgres refuses on a generated one (`428C9`). So it is asked exactly what an
|
|
65
|
+
* ordinary drop is asked, BEFORE the table's diff writes a statement — until 2026-11-19 it was
|
|
66
|
+
* asked nothing, and `x db gen` wrote `-- destructive: true` over a loss nobody had consented to.
|
|
67
|
+
* Answers whether any of them went unretired.
|
|
68
|
+
*/
|
|
69
|
+
export function admitRebuilds(
|
|
70
|
+
entity: EntityDescriptionLike,
|
|
71
|
+
live: TableDescription,
|
|
72
|
+
consent: DropConsent,
|
|
73
|
+
): boolean {
|
|
74
|
+
const recorded = new Map(live.columns.map((column) => [column.name, column]));
|
|
75
|
+
let unretired = false;
|
|
76
|
+
for (const column of entity.columns) {
|
|
77
|
+
const held = recorded.get(column.column);
|
|
78
|
+
if (held === undefined || !becomesGenerated(column, held)) continue;
|
|
79
|
+
if (admitted(entity, held, consent, true)) unretired = true;
|
|
80
|
+
}
|
|
81
|
+
return unretired;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* What hung off the dropped columns, as the previous snapshot recorded it: `drop column` took every
|
|
86
|
+
* foreign key over one and every index that depends on one (`indexDependsOn`: a key, an INCLUDE
|
|
87
|
+
* column, a predicate or an expression that reads it), and `add column` brings none of them back. Without these a
|
|
88
|
+
* rollback left a database its own snapshot called drifted (`missing-index`,
|
|
89
|
+
* `missing-foreign-key`), and the `down` before it dropped a constraint that was not there
|
|
90
|
+
* (`42704`). A CHECK is `checkPlan`'s, already restored.
|
|
91
|
+
*
|
|
92
|
+
* Pushed BEFORE the `add column`s because `down` is reversed at assembly, keys before indexes for
|
|
93
|
+
* the same reason. A statement another arm already pushed is not pushed twice: a retype or a
|
|
94
|
+
* rebuild of a second column of the same index restores it too (`moveDependentsAside`), and a
|
|
95
|
+
* second `create index` under one name is `42P07`.
|
|
96
|
+
*/
|
|
97
|
+
function restoreDependents(
|
|
98
|
+
live: TableDescription,
|
|
99
|
+
dropped: ReadonlySet<string>,
|
|
100
|
+
plan: Plan,
|
|
101
|
+
plans: ConstraintPlans,
|
|
102
|
+
): void {
|
|
103
|
+
const over = (columns: readonly string[]): boolean => columns.some((each) => dropped.has(each));
|
|
104
|
+
const restores: string[] = [];
|
|
105
|
+
for (const key of live.foreignKeys) {
|
|
106
|
+
if (!over(key.columns) || plans.predropped.has(keyId(live.name, key.name))) continue;
|
|
107
|
+
restores.push(
|
|
108
|
+
plans.doomed.has(key.referencedTable)
|
|
109
|
+
? unrestorableNote(live.name, key.name, key.referencedTable)
|
|
110
|
+
: addForeignKey(live.name, key),
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
for (const index of live.indexes) {
|
|
114
|
+
if (index.primary || ![...dropped].some((column) => indexDependsOn(index, column))) continue;
|
|
115
|
+
restores.push(createIndex(live.name, asDeclared(index)));
|
|
116
|
+
}
|
|
117
|
+
plan.down.push(...restores.filter((statement) => !plan.down.includes(statement)));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Every recorded column the entity neither declares nor retires: admitted, dropped, and put back
|
|
122
|
+
* empty by `down`. Answers whether any of them was never retired.
|
|
123
|
+
*/
|
|
124
|
+
export function dropColumns(
|
|
125
|
+
entity: EntityDescriptionLike,
|
|
126
|
+
live: TableDescription,
|
|
127
|
+
plan: Plan,
|
|
128
|
+
plans: ConstraintPlans,
|
|
129
|
+
consent: DropConsent,
|
|
130
|
+
): boolean {
|
|
131
|
+
const kept = new Set([
|
|
132
|
+
...entity.columns.map((column) => column.column),
|
|
133
|
+
...(entity.retired ?? []),
|
|
134
|
+
]);
|
|
135
|
+
const leaving = live.columns.filter((column) => !kept.has(column.name));
|
|
136
|
+
if (leaving.length === 0) return false;
|
|
137
|
+
let unretired = false;
|
|
138
|
+
for (const column of leaving) {
|
|
139
|
+
if (admitted(entity, column, consent, false)) unretired = true;
|
|
140
|
+
}
|
|
141
|
+
restoreDependents(live, new Set(leaving.map((column) => column.name)), plan, plans);
|
|
142
|
+
for (const column of leaving) {
|
|
143
|
+
if (column.retired === true) plan.up.push(contractsMarkerFor(entity.table, column.name));
|
|
144
|
+
plan.up.push(
|
|
145
|
+
`alter table ${identifier(entity.table).text} drop column ${identifier(column.name).text};`,
|
|
146
|
+
);
|
|
147
|
+
plan.down.push(
|
|
148
|
+
`alter table ${identifier(entity.table).text} add column ` +
|
|
149
|
+
`${identifier(column.name).text} ${column.dataType};` +
|
|
150
|
+
' -- data is not restored',
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
return unretired;
|
|
154
|
+
}
|
package/src/errors.ts
CHANGED
|
@@ -60,6 +60,7 @@ export const DB_OWNED_ERROR_CODES = [
|
|
|
60
60
|
'X_LIFECYCLE_TRIGGER_MISSING',
|
|
61
61
|
'X_MIGRATION_PARTITION_CHANGE',
|
|
62
62
|
'X_MIGRATION_LOCK_HEAVY',
|
|
63
|
+
'X_MIGRATION_FORKED',
|
|
63
64
|
] as const;
|
|
64
65
|
|
|
65
66
|
/**
|
|
@@ -135,6 +136,7 @@ export const DB_ERROR_TITLES: Readonly<Record<DbOwnedErrorCode, string>> = {
|
|
|
135
136
|
'a history or counter trigger the migrations created is missing from the database',
|
|
136
137
|
X_MIGRATION_PARTITION_CHANGE: 'an existing table gained or lost entity({ partitionBy })',
|
|
137
138
|
X_MIGRATION_LOCK_HEAVY: 'this migration holds a live table still for a full scan',
|
|
139
|
+
X_MIGRATION_FORKED: 'two branches forked the migration chain',
|
|
138
140
|
};
|
|
139
141
|
|
|
140
142
|
// Registered unconditionally, in one call, so a second package claiming one of db's codes fails
|
package/src/generate.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { systemClock } from '@ultimat3/core';
|
|
|
7
7
|
import { checkClauses, checkPlan } from './check-ddl';
|
|
8
8
|
import { alterColumnInPlace, retypeOverDefault, typeClause, wantedDefault } from './column-alter';
|
|
9
9
|
import { defaultExpression } from './column-default';
|
|
10
|
+
import { admitRebuilds, dropColumns } from './column-drop';
|
|
10
11
|
import { emptyConcurrentPlan } from './concurrent-plan';
|
|
11
12
|
import { dropOrder } from './drop-order';
|
|
12
13
|
import type { ColumnDescriptionLike, EntityDescriptionLike } from './entity-shape';
|
|
@@ -35,11 +36,10 @@ import { beforeContract, contractNotNull, type NotNullContracts } from './not-nu
|
|
|
35
36
|
import { addChangedKey, dropChangedKey, migrationNameArg } from './primary-key';
|
|
36
37
|
import type { ReplicaIdentityInput } from './replica-identity';
|
|
37
38
|
import { replicaIdentityFullAfter, replicaIdentityPlan } from './replica-identity';
|
|
38
|
-
import {
|
|
39
|
+
import { recordRetired, retirePlan } from './retired';
|
|
39
40
|
import type { MovedAside } from './retype-dependents';
|
|
40
41
|
import { moveDependentsAside } from './retype-dependents';
|
|
41
42
|
import { moveKeysAside, retypedColumns, retypedIn } from './retype-keys';
|
|
42
|
-
import { columnDropNotRetired } from './rolling-errors';
|
|
43
43
|
import { rowSecurityAfter, rowSecurityPlan } from './row-security-plan';
|
|
44
44
|
import { withSameTenantIndexes } from './same-tenant';
|
|
45
45
|
import { identifier } from './sql';
|
|
@@ -336,45 +336,12 @@ export function generateMigration(given: GenerateOptions): GeneratedMigration {
|
|
|
336
336
|
}
|
|
337
337
|
// The key first and last, around every column statement of the table (`primary-key.ts`): the
|
|
338
338
|
// snapshot below records `entity.primaryKey`, and until this arm existed nothing produced it.
|
|
339
|
+
// Before any statement: a plain column becoming generated is a drop, and is asked as one.
|
|
340
|
+
if (admitRebuilds(entity, live, options)) droppedUnretired = true;
|
|
339
341
|
retirePlan(entity, live, plan, options.entities);
|
|
340
342
|
dropChangedKey(entity, live, current, plan, options.name);
|
|
341
343
|
diffTable(entity, live, plan, retypedIn(retyped, entity.table), contracts);
|
|
342
|
-
|
|
343
|
-
...entity.columns.map((column) => column.column),
|
|
344
|
-
...(entity.retired ?? []),
|
|
345
|
-
]);
|
|
346
|
-
for (const column of live.columns) {
|
|
347
|
-
if (kept.has(column.name)) continue;
|
|
348
|
-
// Order matters: the release boundary first, with the flag or without it. Retiring is what
|
|
349
|
-
// earns the next question; it is never consent to losing the rows, so that one still stands.
|
|
350
|
-
if (column.retired !== true && options.rollingUnsafe !== true) {
|
|
351
|
-
throw columnDropNotRetired(
|
|
352
|
-
entity.name,
|
|
353
|
-
entity.table,
|
|
354
|
-
column.name,
|
|
355
|
-
migrationNameArg(options.name),
|
|
356
|
-
);
|
|
357
|
-
}
|
|
358
|
-
if (options.allowDestructive !== true) {
|
|
359
|
-
throw migrationIrreversible(
|
|
360
|
-
`dropping "${entity.table}"."${column.name}" discards its rows and cannot be undone`,
|
|
361
|
-
`x db gen ${migrationNameArg(options.name)} --allow-destructive # or put "${column.name}" back in columns and keep it`,
|
|
362
|
-
);
|
|
363
|
-
}
|
|
364
|
-
if (column.retired === true) {
|
|
365
|
-
plan.up.push(contractsMarkerFor(entity.table, column.name));
|
|
366
|
-
} else {
|
|
367
|
-
droppedUnretired = true;
|
|
368
|
-
}
|
|
369
|
-
plan.up.push(
|
|
370
|
-
`alter table ${identifier(entity.table).text} drop column ${identifier(column.name).text};`,
|
|
371
|
-
);
|
|
372
|
-
plan.down.push(
|
|
373
|
-
`alter table ${identifier(entity.table).text} add column ` +
|
|
374
|
-
`${identifier(column.name).text} ${column.dataType};` +
|
|
375
|
-
' -- data is not restored',
|
|
376
|
-
);
|
|
377
|
-
}
|
|
344
|
+
if (dropColumns(entity, live, plan, plans, options)) droppedUnretired = true;
|
|
378
345
|
addChangedKey(entity, live, plan, options.name);
|
|
379
346
|
}
|
|
380
347
|
|
package/src/generated-column.ts
CHANGED
|
@@ -68,6 +68,13 @@ function oneExpression(column: string, expression: string): string {
|
|
|
68
68
|
export const isGenerated = (column: ColumnDescriptionLike): boolean =>
|
|
69
69
|
typeof column.generated === 'string';
|
|
70
70
|
|
|
71
|
+
/** Plain on the record, generated in the declaration: the one move `regenerate` makes by a drop. */
|
|
72
|
+
export const becomesGenerated = (
|
|
73
|
+
column: ColumnDescriptionLike,
|
|
74
|
+
recorded: ColumnDescription,
|
|
75
|
+
): boolean =>
|
|
76
|
+
isGenerated(column) && (recorded.generated === undefined || recorded.generated === null);
|
|
77
|
+
|
|
71
78
|
/**
|
|
72
79
|
* A generated column whose TYPE or whose EXPRESSION moved, brought into line without rebuilding it.
|
|
73
80
|
*
|
|
@@ -82,10 +89,11 @@ export const isGenerated = (column: ColumnDescriptionLike): boolean =>
|
|
|
82
89
|
* a generated column"), which is exactly the statement `retypeColumn` emits for every other column
|
|
83
90
|
* — and there is nothing to convert, because the expression produces the new type itself.
|
|
84
91
|
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
92
|
+
* One transition `set expression` cannot make: plain → generated, since the statement needs a
|
|
93
|
+
* column that already has an expression. That one IS a drop and an add — every stored value is
|
|
94
|
+
* lost — so `admitRebuilds` (`column-drop.ts`) asks it the two consents an ordinary column drop is
|
|
95
|
+
* asked before this function is reached. `drop expression` is the generated → plain direction,
|
|
96
|
+
* which keeps the values it computed.
|
|
89
97
|
*
|
|
90
98
|
* **The rebuild moves the column's dependents aside first, and it is `retype-dependents.ts` that
|
|
91
99
|
* says which — never a second answer written here.** The `rebuilt`
|
package/src/index-plan.ts
CHANGED
|
@@ -36,6 +36,7 @@ import {
|
|
|
36
36
|
import type { TableDescription } from './introspect';
|
|
37
37
|
import { declaredIndexes } from './invariant-ddl';
|
|
38
38
|
import { LOCK_HEAVY_MARKER } from './migration-lock-lint';
|
|
39
|
+
import { indexDependsOn } from './retype-dependents';
|
|
39
40
|
|
|
40
41
|
/**
|
|
41
42
|
* An existing table's index is built `concurrently` unless the entity says `concurrently: false`:
|
|
@@ -153,6 +154,7 @@ export function indexPlan(
|
|
|
153
154
|
* | already in `context.moved` | a retype dropped it ahead of the ALTER — a second drop is 42704 |
|
|
154
155
|
* | over a column in `context.rebuilt` | it went with the `drop column` half of `regenerate` — 42704 |
|
|
155
156
|
* | over a column this migration DROPS | `alter table … drop column` takes it, so a drop beside it says nothing new. The rule `foreignKeyPlan` applies to a constraint on a dropped column |
|
|
157
|
+
* | reads a dropped column (predicate, expression, INCLUDE) | the same drop takes it (`indexDependsOn`); deferred to a follow-up, its `down` rebuilt a predicate over a column not there (42703) |
|
|
156
158
|
*
|
|
157
159
|
* A doomed TABLE needs no arm: `generate.ts` only reaches a diff for a table an entity still
|
|
158
160
|
* declares, so `drop table` and this function never meet.
|
|
@@ -164,11 +166,17 @@ function removeUndeclared(
|
|
|
164
166
|
declared: ReadonlySet<string>,
|
|
165
167
|
): void {
|
|
166
168
|
const columns = new Set(entity.columns.map((column) => column.column));
|
|
169
|
+
// `dropColumns`' own reading of "leaving": recorded, neither declared nor retired.
|
|
170
|
+
const retired = new Set(entity.retired ?? []);
|
|
171
|
+
const leaving = live.columns
|
|
172
|
+
.map((column) => column.name)
|
|
173
|
+
.filter((column) => !columns.has(column) && !retired.has(column));
|
|
167
174
|
for (const recorded of live.indexes) {
|
|
168
175
|
if (recorded.primary || declared.has(recorded.name)) continue;
|
|
169
176
|
if (context.moved.has(recorded.name)) continue;
|
|
170
177
|
if (recorded.columns.some((column) => context.rebuilt.has(column))) continue;
|
|
171
178
|
if (!recorded.columns.every((column) => columns.has(column))) continue;
|
|
179
|
+
if (leaving.some((column) => indexDependsOn(recorded, column))) continue;
|
|
172
180
|
removeConcurrently(live.name, recorded, context.concurrent);
|
|
173
181
|
}
|
|
174
182
|
}
|
package/src/index.ts
CHANGED
|
@@ -183,6 +183,7 @@ export { ledgerAheadOfBuild, ROLLBACK_ALLOW_DESTRUCTIVE_ENV } from './migrate-ro
|
|
|
183
183
|
export {
|
|
184
184
|
migrationConcurrentPartitioned,
|
|
185
185
|
migrationDestructive,
|
|
186
|
+
migrationForked,
|
|
186
187
|
migrationIrreversible,
|
|
187
188
|
migrationSnapshotMissing,
|
|
188
189
|
rollbackStepsInvalid,
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Single responsibility: the `fix:` a migration refusal names on the embedded development database,
|
|
2
|
+
// where a deploy's lines cannot run: no image to roll forward to, no `DATABASE_URL` for psql, no git
|
|
3
|
+
// history for a migration written a minute ago. Its own module — an environment probe is not a
|
|
4
|
+
// refusal — at the cost of one module on `ROLE=migrate`'s pinned graph (`MIGRATE_CEILING`).
|
|
5
|
+
|
|
6
|
+
import { tryResolveEnvironment } from '@ultimat3/core';
|
|
7
|
+
|
|
8
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Development, and no `DATABASE_URL`: the database is PGlite under the checkout's `.x/`, which is
|
|
12
|
+
* what `x db reset` rebuilds. The non-throwing read on purpose — this runs while an error is being
|
|
13
|
+
* built, and a typo in `ULTIMATE_ENV` must not replace that error; it reads as "not development".
|
|
14
|
+
* `test` is not development either: a suite's database is the suite's to rebuild.
|
|
15
|
+
*/
|
|
16
|
+
export function embeddedDev(env: Env = Bun.env): boolean {
|
|
17
|
+
return (
|
|
18
|
+
tryResolveEnvironment({ env }) === 'development' && (env['DATABASE_URL'] ?? '').trim() === ''
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The one command that always ends a ledger this checkout cannot reconcile: rebuild the embedded
|
|
24
|
+
* database from the migrations on disk. `x stop` first because `x db reset` refuses beside a
|
|
25
|
+
* running `x dev` (it holds the data directory), and it exits 0 when none is running — so the line
|
|
26
|
+
* runs as pasted either way. `why` is the caller's: what made the ledger irreconcilable, and what
|
|
27
|
+
* to do instead when the rows matter.
|
|
28
|
+
*/
|
|
29
|
+
export const embeddedResetFix = (why: string): string =>
|
|
30
|
+
`x stop --json && x db reset # development: rebuilds the embedded database from the migrations on disk, and its rows are lost (x db seed refills them) — ${why}; then x dev`;
|
package/src/migrate-rollback.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { renderFixShellArg } from '@ultimat3/core';
|
|
6
6
|
import { isDestructiveMigration } from './destructive';
|
|
7
7
|
import { DbError } from './errors';
|
|
8
|
+
import { embeddedDev, embeddedResetFix } from './migrate-dev-fix';
|
|
8
9
|
import type { LedgerRow, Migration } from './migration-ledger';
|
|
9
10
|
import { pendingMigrations } from './migration-ledger';
|
|
10
11
|
|
|
@@ -77,7 +78,13 @@ function assertRollbackSafe(ahead: readonly LedgerRow[], allow: string | undefin
|
|
|
77
78
|
throw new DbError({
|
|
78
79
|
code: 'X_MIGRATION_ROLLBACK_DESTRUCTIVE',
|
|
79
80
|
cause: `the ledger holds ${ids.length} destructive migration(s) a newer build applied (${ids.join(', ')}) and this build predates them — it may read a column or table that no longer exists`,
|
|
80
|
-
|
|
81
|
+
// On the embedded database there is no newer image: the rows are ahead because this checkout
|
|
82
|
+
// dropped their files, and only a build holding a migration's `down` can reverse it.
|
|
83
|
+
fix: embeddedDev()
|
|
84
|
+
? embeddedResetFix(
|
|
85
|
+
'this checkout no longer holds the migration file(s) the cause names; to keep the rows, restore them (git status --short -- packages/db/migrations) and run x db rollback',
|
|
86
|
+
)
|
|
87
|
+
: `x deploy --image <the newer image> --json # roll forward; or, after checking this build runs on the newer schema: ${ROLLBACK_ALLOW_DESTRUCTIVE_ENV}=${renderFixShellArg(all.join(','), '<migration id>')} on the migrate role`,
|
|
81
88
|
meta: { refused: ids, appVersions: [...new Set(refused.map((row) => row.app_version))] },
|
|
82
89
|
});
|
|
83
90
|
}
|
package/src/migrate.ts
CHANGED
|
@@ -13,10 +13,11 @@ import {
|
|
|
13
13
|
} from '@ultimat3/core';
|
|
14
14
|
import { baseClient, type DbClient, type DbConnection, isReservable } from './client';
|
|
15
15
|
import { expectedQueryLoop } from './expected-loop';
|
|
16
|
+
import { embeddedDev, embeddedResetFix } from './migrate-dev-fix';
|
|
16
17
|
import { MIGRATION_LOCK_RETRIES } from './migrate-lock-retry';
|
|
17
18
|
import { destructiveBit, ledgerAheadOfBuild } from './migrate-rollback';
|
|
18
19
|
import { migrateConcurrent, migrationConflict, rollbackStepsInvalid } from './migration-errors';
|
|
19
|
-
import type { Migration } from './migration-ledger';
|
|
20
|
+
import type { LedgerRow, Migration } from './migration-ledger';
|
|
20
21
|
import {
|
|
21
22
|
auditLedger,
|
|
22
23
|
ensureLedger,
|
|
@@ -24,6 +25,7 @@ import {
|
|
|
24
25
|
migrationChecksum,
|
|
25
26
|
pendingMigrations,
|
|
26
27
|
readLedger,
|
|
28
|
+
rollbackTargets,
|
|
27
29
|
} from './migration-ledger';
|
|
28
30
|
import { applyMigrationStep } from './migration-step';
|
|
29
31
|
import { poolProfileFor } from './pool-profile';
|
|
@@ -310,7 +312,10 @@ export async function migrate(options: MigrateOptions): Promise<MigrationReport>
|
|
|
310
312
|
export interface RollbackOptions {
|
|
311
313
|
readonly migrations: readonly Migration[];
|
|
312
314
|
readonly client?: DbClient | undefined;
|
|
313
|
-
/**
|
|
315
|
+
/**
|
|
316
|
+
* How many applied migrations to reverse, most recently applied first (not highest id). A
|
|
317
|
+
* positive integer; defaults to 1.
|
|
318
|
+
*/
|
|
314
319
|
readonly steps?: number | undefined;
|
|
315
320
|
/**
|
|
316
321
|
* Skip the advisory lock, for a database only this process can reach — a branch, a test. No
|
|
@@ -323,9 +328,20 @@ export interface RollbackOptions {
|
|
|
323
328
|
readonly lockTimeoutMs?: number | undefined;
|
|
324
329
|
/** Attempts past the first when `lock_timeout` fires. Defaults to 5, as `migrate`'s does. */
|
|
325
330
|
readonly lockRetries?: number | undefined;
|
|
331
|
+
/**
|
|
332
|
+
* Asked once, under the lock, with the exact rows about to be reversed and before the first
|
|
333
|
+
* `down`: throw (or reject) to refuse — an `async` callback is assignable here and its promise
|
|
334
|
+
* is AWAITED, so an async consent settles before any SQL runs (the type stays `void`: widening
|
|
335
|
+
* it is a public-API change). The caller's consent rule (`x db rollback` outside development) is
|
|
336
|
+
* judged here because only the lock's own ledger read says which rows those are.
|
|
337
|
+
*/
|
|
338
|
+
readonly confirm?: ((targets: readonly LedgerRow[]) => void) | undefined;
|
|
326
339
|
}
|
|
327
340
|
|
|
328
|
-
/**
|
|
341
|
+
/**
|
|
342
|
+
* Reverse the `steps` most recently APPLIED migrations — by `applied_at`, not by id, so a migration
|
|
343
|
+
* merged late is the first undone (`rollbackTargets`). `x db rollback` is the command over it.
|
|
344
|
+
*/
|
|
329
345
|
export async function rollback(options: RollbackOptions): Promise<readonly string[]> {
|
|
330
346
|
const client = options.client ?? baseClient();
|
|
331
347
|
const steps = options.steps ?? 1;
|
|
@@ -345,10 +361,12 @@ export async function rollback(options: RollbackOptions): Promise<readonly strin
|
|
|
345
361
|
finiteCount('migrate', 'lockWaitMs', options.lockWaitMs ?? MIGRATION_LOCK_WAIT_MS, 0),
|
|
346
362
|
async (session) => {
|
|
347
363
|
const ledger = await readLedger(session);
|
|
348
|
-
const targets =
|
|
364
|
+
const targets = rollbackTargets(ledger, steps);
|
|
365
|
+
await options.confirm?.(targets);
|
|
349
366
|
|
|
350
|
-
// The same deliberate loop as `migrate`, read backwards: one transaction per `down`,
|
|
351
|
-
// first, so a `down` that fails leaves every migration before it
|
|
367
|
+
// The same deliberate loop as `migrate`, read backwards: one transaction per `down`, most
|
|
368
|
+
// recently applied first, so a `down` that fails leaves every migration applied before it
|
|
369
|
+
// still applied and recorded.
|
|
352
370
|
return expectedQueryLoop(
|
|
353
371
|
'each migration reverses in its own transaction, newest first, so a failure stops exactly there',
|
|
354
372
|
async () => {
|
|
@@ -360,10 +378,15 @@ export async function rollback(options: RollbackOptions): Promise<readonly strin
|
|
|
360
378
|
`migration "${row.id}" is in the ledger but not in this build, so its down SQL is unknown`,
|
|
361
379
|
// Same reason as `auditLedger`'s: psql works where the CLI is absent. The `down` SQL
|
|
362
380
|
// only exists in the build that shipped it, so the fix reads which build that was.
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
381
|
+
// On the embedded database no other build exists and psql has no URL to dial.
|
|
382
|
+
embeddedDev()
|
|
383
|
+
? embeddedResetFix(
|
|
384
|
+
'the file holding this migration and its down SQL is gone from the checkout; to keep the rows, restore it (git status --short -- packages/db/migrations) and run x db rollback',
|
|
385
|
+
)
|
|
386
|
+
: `psql "$DATABASE_URL" -c "select id, app_version from ${renderFixShellArg(LEDGER_TABLE, '<ledger table>')} ` +
|
|
387
|
+
`order by applied_at desc, id desc limit 5" # deploy the build that shipped the migration ` +
|
|
388
|
+
`whose id is base64 ${Buffer.from(row.id, 'utf8').toString('base64')}, ` +
|
|
389
|
+
'and roll back there — its down SQL exists nowhere else',
|
|
367
390
|
);
|
|
368
391
|
}
|
|
369
392
|
// The marker on `up` governs `down` too: the reversal of a concurrent build is a
|
package/src/migration-errors.ts
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
import { renderFixShellArg } from '@ultimat3/core';
|
|
10
10
|
import { DESTRUCTIVE_CAUSE, DESTRUCTIVE_MARKER, type DestructiveStatement } from './destructive';
|
|
11
11
|
import { DbError } from './errors';
|
|
12
|
+
import type { MigrationFork } from './migration-fork';
|
|
12
13
|
import { statementExcerpt } from './statement-excerpt';
|
|
13
14
|
|
|
14
15
|
/**
|
|
@@ -134,6 +135,72 @@ export const migrationSnapshotMissing = (id: string, file: string): DbError => {
|
|
|
134
135
|
});
|
|
135
136
|
};
|
|
136
137
|
|
|
138
|
+
/** A refusal stays readable however far the branches diverged; `meta` carries the counts. */
|
|
139
|
+
const FORK_CAUSES_SHOWN = 3;
|
|
140
|
+
|
|
141
|
+
function forkCauses(fork: MigrationFork): readonly string[] {
|
|
142
|
+
const label = (kind: string, table: string, name: string): string =>
|
|
143
|
+
kind === 'table' || kind === 'view' ? `${kind} "${name}"` : `${kind} "${table}"."${name}"`;
|
|
144
|
+
return [
|
|
145
|
+
...fork.collisions.map(
|
|
146
|
+
(entry) =>
|
|
147
|
+
`${entry.again} creates ${label(entry.kind, entry.table, entry.name)} again after ${entry.first}, so the chain cannot replay`,
|
|
148
|
+
),
|
|
149
|
+
...fork.lost.map(
|
|
150
|
+
(entry) =>
|
|
151
|
+
`${fork.newest}.snapshot.json omits ${label(entry.kind, entry.table, entry.name)}, which ${entry.recordedBy} recorded and no migration removes`,
|
|
152
|
+
),
|
|
153
|
+
...fork.stale.map(
|
|
154
|
+
(entry) =>
|
|
155
|
+
`${fork.newest}.snapshot.json still records ${label(entry.kind, entry.table, entry.name)}, which ${entry.droppedBy} removed`,
|
|
156
|
+
),
|
|
157
|
+
];
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* The status check comes first because no file says whether a migration ran, and a migration some
|
|
162
|
+
* database applied must never be deleted. Prose after the command, as `migrationSnapshotMissing`
|
|
163
|
+
* degrades: an id a shell would read stays out of the line entirely.
|
|
164
|
+
*/
|
|
165
|
+
function forkCollisionFix(first: string, again: string): string {
|
|
166
|
+
const named = shellSpellable(first) && shellSpellable(again);
|
|
167
|
+
const later = named ? again : 'the later migration named in this error';
|
|
168
|
+
const earlier = named ? first : 'the earlier one';
|
|
169
|
+
return (
|
|
170
|
+
`x db status --json # on every database this app runs against: ${later} repeats what ${earlier} created. ` +
|
|
171
|
+
`Only if data.pending lists ${later} on all of them was it never applied: remove its .sql, .snapshot.json and .hash from packages/db/migrations, then run x db gen --merge-fork. ` +
|
|
172
|
+
`If any database applied it, keep all three files and make the same check for ${earlier}; if each was applied somewhere, keep both, those databases disagree and need a hand-written reconciliation`
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Two branches generated from one parent and were merged. Merging repairs the sidecar and touches
|
|
178
|
+
* no SQL, so it is the fix whether or not either migration was applied: the checksum covers `up`
|
|
179
|
+
* alone. Only a collision needs a migration gone, and only one no database has applied.
|
|
180
|
+
*/
|
|
181
|
+
export const migrationForked = (fork: MigrationFork): DbError => {
|
|
182
|
+
const causes = forkCauses(fork);
|
|
183
|
+
const hidden = causes.length - FORK_CAUSES_SHOWN;
|
|
184
|
+
const collision = fork.collisions[0];
|
|
185
|
+
return new DbError({
|
|
186
|
+
code: 'X_MIGRATION_FORKED',
|
|
187
|
+
cause:
|
|
188
|
+
'two branches generated migrations from one parent and were merged: ' +
|
|
189
|
+
causes.slice(0, FORK_CAUSES_SHOWN).join('; ') +
|
|
190
|
+
(hidden > 0 ? `; and ${hidden} more` : ''),
|
|
191
|
+
fix:
|
|
192
|
+
collision === undefined
|
|
193
|
+
? 'x db gen --merge-fork # records in the newest .snapshot.json what the merged migrations really build; no SQL changes and no migration is deleted, so it is safe after either was applied'
|
|
194
|
+
: forkCollisionFix(collision.first, collision.again),
|
|
195
|
+
meta: {
|
|
196
|
+
newest: fork.newest,
|
|
197
|
+
lost: fork.lost.length,
|
|
198
|
+
stale: fork.stale.length,
|
|
199
|
+
collisions: fork.collisions.length,
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
};
|
|
203
|
+
|
|
137
204
|
/**
|
|
138
205
|
* One error per file, never one per statement: the marker declares the whole migration, so a
|
|
139
206
|
* second finding would repeat an instruction the first already gave. `file` is app-relative and
|