File size: 2,193 Bytes
9d4a3b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { mkdir, readFile, readdir } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { DatabaseSync } from "node:sqlite";

const root = process.cwd();
const configuredPath = process.env.LINKEDIN_SQLITE_PATH?.trim();
if (!configuredPath) {
  throw new Error("LINKEDIN_SQLITE_PATH is required for local SQLite migrations.");
}
const deterministicEpoch = process.env.WEBSITEBENCH_DETERMINISTIC_EPOCH_SECONDS?.trim();
if (deterministicEpoch && !/^\d+$/.test(deterministicEpoch)) {
  throw new Error("WEBSITEBENCH_DETERMINISTIC_EPOCH_SECONDS must be unsigned epoch seconds.");
}
const databaseNow = deterministicEpoch ?? "unixepoch()";

const databasePath = resolve(root, configuredPath);
await mkdir(dirname(databasePath), { recursive: true });
const database = new DatabaseSync(databasePath);
try {
  database.exec(`
    PRAGMA foreign_keys = ON;
    PRAGMA journal_mode = WAL;
    PRAGMA busy_timeout = 5000;
    CREATE TABLE IF NOT EXISTS __drizzle_migrations (
      name TEXT PRIMARY KEY NOT NULL,
      applied_at INTEGER NOT NULL DEFAULT (${databaseNow})
    );
  `);
  const applied = database.prepare("SELECT 1 FROM __drizzle_migrations WHERE name = ?");
  const record = database.prepare("INSERT INTO __drizzle_migrations (name) VALUES (?)");
  const migrations = (await readdir(join(root, "drizzle"))).filter((file) => file.endsWith(".sql")).sort();
  let appliedCount = 0;
  for (const migration of migrations) {
    if (applied.get(migration)) continue;
    const source = await readFile(join(root, "drizzle", migration), "utf8");
    const executableSource = deterministicEpoch
      ? source.replaceAll("unixepoch()", deterministicEpoch)
      : source;
    database.exec("BEGIN IMMEDIATE");
    try {
      for (const statement of executableSource.split("--> statement-breakpoint")) {
        if (statement.trim()) database.exec(statement);
      }
      record.run(migration);
      database.exec("COMMIT");
      appliedCount += 1;
    } catch (error) {
      database.exec("ROLLBACK");
      throw error;
    }
  }
  console.log(`Applied ${appliedCount} of ${migrations.length} LinkedIn SQLite migrations.`);
} finally {
  database.close();
}