Skip to content

Commit

Permalink
Add libsql always batch for migrations
Browse files Browse the repository at this point in the history
  • Loading branch information
AndriiSherman committed Mar 11, 2024
1 parent d9db4a3 commit e01313e
Showing 1 changed file with 42 additions and 2 deletions.
44 changes: 42 additions & 2 deletions drizzle-orm/src/libsql/migrator.ts
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);
}

1 comment on commit e01313e

@mattfysh
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AndriiSherman this would also be required for the d1 migrator: #1270

Please sign in to comment.