MCPcopy
hub / github.com/drizzle-team/drizzle-orm / migrate

Function migrate

drizzle-orm/src/d1/migrator.ts:6–49  ·  view source on GitHub ↗
(
	db: DrizzleD1Database<TSchema>,
	config: MigrationConfig,
)

Source from the content-addressed store, hash-verified

4import type { DrizzleD1Database } from './driver.ts';
5
6export 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}

Callers 15

testsFunction · 0.90
neon-http.test.tsFile · 0.90
pglite.test.tsFile · 0.90
vercel-pg.test.tsFile · 0.90
xata-http.test.tsFile · 0.90
pg-proxy.test.tsFile · 0.90
pg-custom.test.tsFile · 0.90

Calls 4

readMigrationFilesFunction · 0.90
sqlFunction · 0.90
runMethod · 0.45
batchMethod · 0.45

Tested by

no test coverage detected