-
-
Notifications
You must be signed in to change notification settings - Fork 664
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1998 from drizzle-team/libsql-batch-migrate
Add libsql always batch for migrations
- Loading branch information
Showing
1 changed file
with
42 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,51 @@ | ||
import type { MigrationConfig } from '~/migrator.ts'; | ||
import { readMigrationFiles } from '~/migrator.ts'; | ||
import { sql } from '~/sql/sql.ts'; | ||
import type { LibSQLDatabase } from './driver.ts'; | ||
|
||
export function migrate<TSchema extends Record<string, unknown>>( | ||
export async function migrate<TSchema extends Record<string, unknown>>( | ||
db: LibSQLDatabase<TSchema>, | ||
config: MigrationConfig, | ||
) { | ||
const migrations = readMigrationFiles(config); | ||
return db.dialect.migrate(migrations, db.session, config); | ||
const migrationsTable = config === undefined | ||
? '__drizzle_migrations' | ||
: typeof config === 'string' | ||
? '__drizzle_migrations' | ||
: config.migrationsTable ?? '__drizzle_migrations'; | ||
|
||
const migrationTableCreate = sql` | ||
CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} ( | ||
id SERIAL PRIMARY KEY, | ||
hash text NOT NULL, | ||
created_at numeric | ||
) | ||
`; | ||
await db.session.run(migrationTableCreate); | ||
|
||
const dbMigrations = await db.values<[number, string, string]>( | ||
sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`, | ||
); | ||
|
||
const lastDbMigration = dbMigrations[0] ?? undefined; | ||
|
||
const statementToBatch = []; | ||
|
||
for (const migration of migrations) { | ||
if (!lastDbMigration || Number(lastDbMigration[2])! < migration.folderMillis) { | ||
for (const stmt of migration.sql) { | ||
statementToBatch.push(db.run(sql.raw(stmt))); | ||
} | ||
|
||
statementToBatch.push( | ||
db.run( | ||
sql`INSERT INTO ${ | ||
sql.identifier(migrationsTable) | ||
} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`, | ||
), | ||
); | ||
} | ||
} | ||
|
||
await db.session.batch(statementToBatch); | ||
} |