Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

migrate.ts

79 lines2.3 KB

1// import type { MigrationConfig } from "drizzle-orm/migrator";
2import { type DB, db } from ".";
3import migrations from "./migrations.json";
4​
5// export async function migrate() {
6// // dialect and session will appear to not exist...but they do
7// console.log("Running migrations...");
8// await db.dialect.migrate(migrations, db.session, {
9// migrationsTable: "drizzle_migrations",
10// } satisfies Omit<MigrationConfig, "migrationsFolder">);
11// }
12​
13async function ensureMigrationsTable(db: DB) {
14 await db.execute(`
15 CREATE TABLE IF NOT EXISTS drizzle_migrations (
16 hash TEXT PRIMARY KEY,
17 created_at TIMESTAMP NOT NULL DEFAULT NOW()
18 )
19 `);
21​
22async function getMigratedHashes(db: DB): Promise<string[]> {
23 const result = await db.execute(`
24 SELECT hash FROM drizzle_migrations ORDER BY created_at ASC
25 `);
26 return result.rows.map((row) => row.hash as string);
28​
29async function recordMigration(hash: string, db: DB) {
30 await db.execute(
31 `
32 INSERT INTO drizzle_migrations (hash, created_at)
33 VALUES ('${hash}', NOW())
34 ON CONFLICT DO NOTHING
35 `,
36 );
38​
39export async function migrate() {
40 console.log("🚀 Starting pglite migration...");
41​
42 // Ensure migrations table exists
43 await ensureMigrationsTable(db);
44​
45 // Get already executed migrations
46 const executedHashes = await getMigratedHashes(db);
47​
48 // Filter and execute pending migrations
49 const pendingMigrations = migrations.filter(
50 (migration) => !executedHashes.includes(migration.hash),
51 );
52​
53 if (pendingMigrations.length === 0) {
54 console.log("✨ No pending migrations found.");
55 return;
56 }
57​
58 console.log(`📦 Found ${pendingMigrations.length} pending migrations`);
59​
60 // Execute migrations in sequence
61 for (const migration of pendingMigrations) {
62 console.log(`⚡ Executing migration: ${migration.hash}`);
63 try {
64 // Execute each SQL statement in sequence
65 for (const sql of migration.sql) {
66 await db.execute(sql);
67 }
68​
69 // Record successful migration
70 await recordMigration(migration.hash, db);
71 console.log(`✅ Successfully completed migration: ${migration.hash}`);
72 } catch (error) {
73 console.error(`❌ Failed to execute migration ${migration.hash}:`, error);
74 throw error;
75 }
76 }
77​
78 console.log("🎉 All migrations completed successfully");