( db: DrizzleSqliteDODatabase<TSchema>, config: MigrationConfig, )
| 39 | } |
| 40 | |
| 41 | export async function migrate< |
| 42 | TSchema extends Record<string, unknown>, |
| 43 | >( |
| 44 | db: DrizzleSqliteDODatabase<TSchema>, |
| 45 | config: MigrationConfig, |
| 46 | ): Promise<void> { |
| 47 | const migrations = readMigrationFiles(config); |
| 48 | |
| 49 | db.transaction((tx) => { |
| 50 | try { |
| 51 | const migrationsTable = '__drizzle_migrations'; |
| 52 | |
| 53 | const migrationTableCreate = sql` |
| 54 | CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} ( |
| 55 | id SERIAL PRIMARY KEY, |
| 56 | hash text NOT NULL, |
| 57 | created_at numeric |
| 58 | ) |
| 59 | `; |
| 60 | db.run(migrationTableCreate); |
| 61 | |
| 62 | const dbMigrations = db.values<[number, string, string]>( |
| 63 | sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`, |
| 64 | ); |
| 65 | |
| 66 | const lastDbMigration = dbMigrations[0] ?? undefined; |
| 67 | |
| 68 | for (const migration of migrations) { |
| 69 | if (!lastDbMigration || Number(lastDbMigration[2])! < migration.folderMillis) { |
| 70 | for (const stmt of migration.sql) { |
| 71 | db.run(sql.raw(stmt)); |
| 72 | } |
| 73 | db.run( |
| 74 | sql`INSERT INTO ${ |
| 75 | sql.identifier(migrationsTable) |
| 76 | } ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`, |
| 77 | ); |
| 78 | } |
| 79 | } |
| 80 | } catch (error: any) { |
| 81 | tx.rollback(); |
| 82 | throw error; |
| 83 | } |
| 84 | }); |
| 85 | } |
nothing calls this directly
no test coverage detected