( db: DrizzleD1Database<TSchema>, config: MigrationConfig, )
| 4 | import type { DrizzleD1Database } from './driver.ts'; |
| 5 | |
| 6 | export async function migrate<TSchema extends Record<string, unknown>>( |
| 7 | db: DrizzleD1Database<TSchema>, |
| 8 | config: MigrationConfig, |
| 9 | ) { |
| 10 | const migrations = readMigrationFiles(config); |
| 11 | const migrationsTable = config.migrationsTable ?? '__drizzle_migrations'; |
| 12 | |
| 13 | const migrationTableCreate = sql` |
| 14 | CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} ( |
| 15 | id SERIAL PRIMARY KEY, |
| 16 | hash text NOT NULL, |
| 17 | created_at numeric |
| 18 | ) |
| 19 | `; |
| 20 | await db.session.run(migrationTableCreate); |
| 21 | |
| 22 | const dbMigrations = await db.values<[number, string, string]>( |
| 23 | sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`, |
| 24 | ); |
| 25 | |
| 26 | const lastDbMigration = dbMigrations[0] ?? undefined; |
| 27 | |
| 28 | const statementToBatch = []; |
| 29 | |
| 30 | for (const migration of migrations) { |
| 31 | if (!lastDbMigration || Number(lastDbMigration[2])! < migration.folderMillis) { |
| 32 | for (const stmt of migration.sql) { |
| 33 | statementToBatch.push(db.run(sql.raw(stmt))); |
| 34 | } |
| 35 | |
| 36 | statementToBatch.push( |
| 37 | db.run( |
| 38 | sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${ |
| 39 | sql.raw(`'${migration.hash}'`) |
| 40 | }, ${sql.raw(`${migration.folderMillis}`)})`, |
| 41 | ), |
| 42 | ); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | if (statementToBatch.length > 0) { |
| 47 | await db.session.batch(statementToBatch); |
| 48 | } |
| 49 | } |
no test coverage detected