CoolFace
Apppublic

AK-21/Graphite-Industrial-Intelligence

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
migrator.js61 linesDownload Raw Back to durable-sqlite
1import { sql } from "../sql/index.js";2function 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}25async 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 numeric35				)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}58export {59  migrate60};61//# sourceMappingURL=migrator.js.map