|
| 1 | +import { readdirSync, readFileSync, writeFileSync } from "node:fs"; |
| 2 | +import { join } from "node:path"; |
| 3 | +import { DatabaseSync } from "node:sqlite"; |
| 4 | +import { fields, pages, text } from "./content.mjs"; |
| 5 | + |
| 6 | +// Let SQLite quote bound values for the migration exactly as it executed them. |
| 7 | +export class Seed { |
| 8 | + #sql = []; |
| 9 | + constructor(db) { |
| 10 | + this.db = db; |
| 11 | + } |
| 12 | + row(sql, ...values) { |
| 13 | + if (values.some((v) => typeof v === "string" && v.includes("\0"))) |
| 14 | + throw new Error("NUL byte in SQL text value"); |
| 15 | + const statement = this.db.prepare(sql); |
| 16 | + statement.run(...values); |
| 17 | + this.#sql.push(`${statement.expandedSQL};\n`); |
| 18 | + } |
| 19 | + toString() { |
| 20 | + return this.#sql.join(""); |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +export function insertPosts(seed, dir) { |
| 25 | + pages(dir, (_, meta, body) => { |
| 26 | + const p = fields(meta, [ |
| 27 | + "title", |
| 28 | + "date", |
| 29 | + "icon", |
| 30 | + "summary", |
| 31 | + "external_url", |
| 32 | + ]); |
| 33 | + const external = p.external_url ?? null; |
| 34 | + if (external !== null) text(external, "external_url"); |
| 35 | + if (Boolean(external) === Boolean(body)) |
| 36 | + throw new Error( |
| 37 | + "A post needs either Markdown content or an external_url", |
| 38 | + ); |
| 39 | + seed.row( |
| 40 | + "INSERT INTO blog_posts (title, created_at, icon, description, external_url, content) VALUES (?, ?, ?, ?, ?, ?)", |
| 41 | + text(p.title, "title"), |
| 42 | + text(p.date, "date"), |
| 43 | + text(p.icon, "icon"), |
| 44 | + text(p.summary, "summary"), |
| 45 | + external, |
| 46 | + body || null, |
| 47 | + ); |
| 48 | + }); |
| 49 | +} |
| 50 | + |
| 51 | +export function writeDocumentation(content, migrations) { |
| 52 | + const db = new DatabaseSync(":memory:"); |
| 53 | + try { |
| 54 | + // The generated rows go after the old content tables and before the search index. |
| 55 | + const version = 100; |
| 56 | + const files = readdirSync(migrations) |
| 57 | + .filter((f) => f.endsWith(".sql") && !f.endsWith(".down.sql")) |
| 58 | + .sort((a, b) => Number.parseInt(a, 10) - Number.parseInt(b, 10)); |
| 59 | + for (const file of files) { |
| 60 | + const n = Number.parseInt(file, 10); |
| 61 | + if (n === version) |
| 62 | + throw new Error(`Migration ${version} is reserved: ${file}`); |
| 63 | + if (n < version) db.exec(readFileSync(join(migrations, file), "utf8")); |
| 64 | + } |
| 65 | + const seed = new Seed(db); |
| 66 | + insertPosts(seed, join(content, "blog")); |
| 67 | + writeFileSync( |
| 68 | + join(migrations, `${version}_documentation_content.sql`), |
| 69 | + seed.toString(), |
| 70 | + { flag: "wx" }, |
| 71 | + ); |
| 72 | + } finally { |
| 73 | + db.close(); |
| 74 | + } |
| 75 | +} |
0 commit comments