| 1 | import { drizzle } from "drizzle-orm/mysql2"; |
| 2 | import { readMigrationFiles } |
| 3 | import { sql } |
| 4 | import path from "path |
| 5 | import { fileURLToPath } |
| 6 | |
| 7 | const DATABASE_URL = process |
| 8 | if (!DATABASE_URL) { |
| 9 | console.error("[migrate] DATABASE_URL is not set |
| 10 | process.exit(1) |
| 11 | } |
| 12 | |
| 13 | const __filename = fileURLToPath |
| 14 | const __dirname = path |
| 15 | |
| 16 | const db = drizzle |
| 17 | |
| 18 | // MySQL DDL auto-commits statement-by-statement (no transactional DDL like |
| 19 | // Postgres), so a migration killed mid-file leaves some of its statements |
| 20 | // already applied. Re-running that file from the top then fails with |
| 21 | // "duplicate column" / "table already exists" errors even though the |
| 22 | // migration never got marked as applied. Treat those specific errors as |
| 23 | // "already applied" and keep going instead of crashing the whole migrate run. |
| 24 | const ALREADY_APPLIED_ERRNOS = new |
| 25 | 1050, // ER_TABLE_EXISTS_ERROR |
| 26 | 1060, // ER_DUP_FIELDNAME |
| 27 | 1061, // ER_DUP_KEYNAME |
| 28 | 1826, // ER_FK_DUP_NAME |
| 29 | ]); |
| 30 | |
| 31 | const MIGRATIONS_TABLE = " |
| 32 | |
| 33 | console.log("[migrate] running migrations..." |
| 34 | |
| 35 | await db.execute( |
| 36 | create table if not exists ${sql.identifier(MIGRATIONS_TABLE |
| 37 | id serial primary key, |
| 38 | hash text not null, |
| 39 | created_at bigint |
| 40 | ) |
| 41 | `); |
| 42 | |
| 43 | const [lastRow] = |
| 44 | sql`select created_at from ${sql. |
| 45 | ); |
| 46 | const lastAppliedAt = Number |
| 47 | |
| 48 | const migrations = readMigrationFiles |
| 49 | |
| 50 | for (const migration |
| 51 | if (migration.folderMillis |
| 52 | |
| 53 | for (const statement |
| 54 | if (!statement.trim |
| 55 | try { |
| 56 | await db.execute |
| 57 | } catch (error) |
| 58 | const errno = |
| 59 | if (errno && |
| 60 | console.warn(`[migrate] skipping already-applied statement (errno |
| 61 | continue; |
| 62 | } |
| 63 | throw error; |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | await db.execute |
| 68 | sql`insert into ${sql. |
| 69 | ); |
| 70 | } |
| 71 | |
| 72 | console.log("[migrate] done" |
| 73 | process.exit(0); |