Skip to content

Commit 95d9c4e

Browse files
committed
fix(core): recover legacy database migration history without a name column
Some existing installs' __drizzle_migrations table predates the "name" column (older Drizzle journal format) and only has created_at timestamps. The old seeding query silently inserted NULL/nothing for those rows, so the new migration runner would think those migrations were never applied and replay already-applied SQL against those databases. Ported from upstream/dev (fix(core): recover legacy database migration history, anomalyco#45061): detect whether the table has a "name" column via pragma_table_info, and when it doesn't, match each row's created_at timestamp to a migration id prefix instead. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_015KrFrdVEmx7apnofWUViJw
1 parent d3c7b53 commit 95d9c4e

1 file changed

Lines changed: 33 additions & 6 deletions

File tree

‎packages/core/src/database/migration.ts‎

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,39 @@ export function applyOnly(db: Database, input: Migration[]) {
5454
if (
5555
yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ${"__drizzle_migrations"}`)
5656
) {
57-
yield* db.run(sql`
58-
INSERT OR IGNORE INTO ${sql.identifier("migration")} (id, time_completed)
59-
SELECT name, ${Date.now()}
60-
FROM ${sql.identifier("__drizzle_migrations")}
61-
WHERE name IS NOT NULL
62-
`)
57+
const named = (yield* db.all<{ name: string }>(
58+
sql`SELECT name FROM pragma_table_info('__drizzle_migrations')`,
59+
)).some((column) => column.name === "name")
60+
61+
if (named) {
62+
yield* db.run(sql`
63+
INSERT OR IGNORE INTO ${sql.identifier("migration")} (id, time_completed)
64+
SELECT name, ${Date.now()}
65+
FROM ${sql.identifier("__drizzle_migrations")}
66+
WHERE name IS NOT NULL
67+
`)
68+
}
69+
70+
if (!named) {
71+
const entries = yield* db.all<{ created_at: number; prefix: string | null }>(sql`
72+
SELECT created_at, strftime('%Y%m%d%H%M%S', created_at / 1000, 'unixepoch') AS prefix
73+
FROM ${sql.identifier("__drizzle_migrations")}
74+
WHERE created_at IS NOT NULL
75+
`)
76+
77+
for (const entry of entries) {
78+
const migration = input.find((item) => item.id.startsWith(`${entry.prefix}_`))
79+
if (!migration) {
80+
return yield* Effect.die(
81+
new Error(`Legacy migration timestamp ${entry.created_at} does not match any known migration`),
82+
)
83+
}
84+
yield* db.run(sql`
85+
INSERT OR IGNORE INTO ${sql.identifier("migration")} (id, time_completed)
86+
VALUES (${migration.id}, ${Date.now()})
87+
`)
88+
}
89+
}
6390
completed = new Set(
6491
(yield* db.all<{ id: string }>(sql`SELECT id FROM ${sql.identifier("migration")}`)).map((row) => row.id),
6592
)

0 commit comments

Comments
 (0)