migrator.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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(${sql.raw(`'${migration.hash}'`)}, ${sql.raw(`${migration.folderMillis}`)})`
  27. )
  28. );
  29. }
  30. }
  31. if (statementToBatch.length > 0) {
  32. await db.session.batch(statementToBatch);
  33. }
  34. }
  35. export {
  36. migrate
  37. };
  38. //# sourceMappingURL=migrator.js.map