| 6 | export type ProxyMigrator = (migrationQueries: string[]) => Promise<void>; |
| 7 | |
| 8 | export async function migrate<TSchema extends Record<string, unknown>>( |
| 9 | db: MySqlRemoteDatabase<TSchema>, |
| 10 | callback: ProxyMigrator, |
| 11 | config: MigrationConfig, |
| 12 | ) { |
| 13 | const migrations = readMigrationFiles(config); |
| 14 | |
| 15 | const migrationsTable = config.migrationsTable ?? '__drizzle_migrations'; |
| 16 | const migrationTableCreate = sql` |
| 17 | create table if not exists ${sql.identifier(migrationsTable)} ( |
| 18 | id serial primary key, |
| 19 | hash text not null, |
| 20 | created_at bigint |
| 21 | ) |
| 22 | `; |
| 23 | await db.execute(migrationTableCreate); |
| 24 | |
| 25 | const dbMigrations = await db.select({ |
| 26 | id: sql.raw('id'), |
| 27 | hash: sql.raw('hash'), |
| 28 | created_at: sql.raw('created_at'), |
| 29 | }).from(sql.identifier(migrationsTable).getSQL()).orderBy( |
| 30 | sql.raw('created_at desc'), |
| 31 | ).limit(1); |
| 32 | |
| 33 | const lastDbMigration = dbMigrations[0]; |
| 34 | |
| 35 | const queriesToRun: string[] = []; |
| 36 | |
| 37 | for (const migration of migrations) { |
| 38 | if ( |
| 39 | !lastDbMigration |
| 40 | || Number(lastDbMigration.created_at) < migration.folderMillis |
| 41 | ) { |
| 42 | queriesToRun.push( |
| 43 | ...migration.sql, |
| 44 | `insert into ${ |
| 45 | sql.identifier(migrationsTable).value |
| 46 | } (\`hash\`, \`created_at\`) values('${migration.hash}', '${migration.folderMillis}')`, |
| 47 | ); |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | await callback(queriesToRun); |
| 52 | } |