migrator.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { sql } from "../sql/index.js";
  2. function readMigrationFiles({ journal, migrations }) {
  3. const migrationQueries = [];
  4. for (const journalEntry of journal.entries) {
  5. const query = migrations[`m${journalEntry.idx.toString().padStart(4, "0")}`];
  6. if (!query) {
  7. throw new Error(`Missing migration: ${journalEntry.tag}`);
  8. }
  9. try {
  10. const result = query.split("--> statement-breakpoint").map((it) => {
  11. return it;
  12. });
  13. migrationQueries.push({
  14. sql: result,
  15. bps: journalEntry.breakpoints,
  16. folderMillis: journalEntry.when,
  17. hash: ""
  18. });
  19. } catch {
  20. throw new Error(`Failed to parse migration: ${journalEntry.tag}`);
  21. }
  22. }
  23. return migrationQueries;
  24. }
  25. async function migrate(db, config) {
  26. const migrations = readMigrationFiles(config);
  27. db.transaction((tx) => {
  28. try {
  29. const migrationsTable = "__drizzle_migrations";
  30. const migrationTableCreate = sql`
  31. CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
  32. id SERIAL PRIMARY KEY,
  33. hash text NOT NULL,
  34. created_at numeric
  35. )
  36. `;
  37. db.run(migrationTableCreate);
  38. const dbMigrations = db.values(
  39. sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`
  40. );
  41. const lastDbMigration = dbMigrations[0] ?? void 0;
  42. for (const migration of migrations) {
  43. if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
  44. for (const stmt of migration.sql) {
  45. db.run(sql.raw(stmt));
  46. }
  47. db.run(
  48. sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`
  49. );
  50. }
  51. }
  52. } catch (error) {
  53. tx.rollback();
  54. throw error;
  55. }
  56. });
  57. }
  58. export {
  59. migrate
  60. };
  61. //# sourceMappingURL=migrator.js.map