migrator.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import { readMigrationFiles } from "../migrator.js";
  2. import { sql } from "../sql/sql.js";
  3. async function migrate(db, config) {
  4. const migrations = readMigrationFiles(config);
  5. const migrationsTable = config.migrationsTable ?? "__drizzle_migrations";
  6. const migrationTableCreate = sql`
  7. CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
  8. id SERIAL PRIMARY KEY,
  9. hash text NOT NULL,
  10. created_at numeric
  11. )
  12. `;
  13. await db.session.run(migrationTableCreate);
  14. const dbMigrations = await db.values(
  15. sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`
  16. );
  17. const lastDbMigration = dbMigrations[0] ?? void 0;
  18. const statementToBatch = [];
  19. for (const migration of migrations) {
  20. if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
  21. for (const stmt of migration.sql) {
  22. statementToBatch.push(db.run(sql.raw(stmt)));
  23. }
  24. statementToBatch.push(
  25. db.run(
  26. sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`
  27. )
  28. );
  29. }
  30. }
  31. await db.session.migrate(statementToBatch);
  32. }
  33. export {
  34. migrate
  35. };
  36. //# sourceMappingURL=migrator.js.map