Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

4.2 KB
Raw Blame
import { splitStatements } from './sql-split';

import fs from 'node:fs';
import path from 'node:path';

/**
 * Where the Postgres baseline lives: `server/assets/postgres/`, which the
 * Docker image copies beside `dist/` (the same place the airports and atlas
 * data are read from), reached the same way from `src/` and from `dist/`.
 */
const BASELINE_DIR = path.join(__dirname, '..', '..', '..', '..', 'assets', 'postgres');
const SQL_FILE = 'baseline.sql';
const MANIFEST_FILE = 'baseline.json';

/** The manifest beside the SQL: the last migration the baseline stands for, and every migration it replaces. */
interface BaselineManifest {
  through: string;
  migrations: string[];
}

/**
 * The schema a fresh Postgres database starts from.
 *
 * The migrations up to `through` are written in SQLite and frozen, so a
 * Postgres database does not replay them: it runs these statements, generated
 * from the entities (`npm run gen:pg-baseline`), and records every migration
 * in `migrations` as executed in the same transaction. Migrations after
 * `through` run on both engines through the migrator.
 */
export interface PostgresBaseline extends BaselineManifest {
  statements: string[];
}

/** The two files a baseline is written as, ready to compare or write. */
export function renderBaseline(baseline: PostgresBaseline): { sql: string; manifest: string } {
  return {
    sql:
      '-- The schema a fresh Postgres database starts from. Generated by `npm run gen:pg-baseline`; do not edit.\n' +
      baseline.statements.map((statement) => `${statement};\n`).join(''),
    manifest: `${JSON.stringify({ through: baseline.through, migrations: baseline.migrations }, null, 2)}\n`,
  };
}

/**
 * Whether `data` is a manifest a baseline can be read from: a `through` naming
 * one of a non-empty list of `migrations`, every entry a string.
 */
function isBaselineManifest(data: unknown): data is BaselineManifest {
  if (typeof data !== 'object' || data === null || !('through' in data) || !('migrations' in data)) return false;
  const { through, migrations } = data;
  return (
    typeof through === 'string' &&
    Array.isArray(migrations) &&
    migrations.length > 0 &&
    migrations.every((name): name is string => typeof name === 'string') &&
    migrations.includes(through)
  );
}

function parseManifest(text: string, file: string): BaselineManifest {
  const data: unknown = JSON.parse(text);
  if (!isBaselineManifest(data)) throw new Error(`${file} must name "through" and list it among "migrations"`);
  return { through: data.through, migrations: data.migrations };
}

/** Reads the committed baseline; a missing or malformed one throws, so a boot cannot start from half a schema. */
export function readPostgresBaseline(dir = BASELINE_DIR): PostgresBaseline {
  const manifestFile = path.join(dir, MANIFEST_FILE);
  const manifest = parseManifest(fs.readFileSync(manifestFile, 'utf8'), manifestFile);
  const statements = splitStatements(fs.readFileSync(path.join(dir, SQL_FILE), 'utf8').replace(/^--[^\n]*\n/gm, ''));
  if (statements.length === 0) throw new Error(`${path.join(dir, SQL_FILE)} holds no statements`);
  // The boot sends the baseline as one statement without parameters, where a `?` would be read as a binding.
  if (statements.some((statement) => statement.includes('?'))) {
    throw new Error(`${path.join(dir, SQL_FILE)} holds a "?", which the boot would read as a parameter`);
  }
  return { ...manifest, statements };
}

/** Writes the two files (the generator's `--write`). */
export function writePostgresBaseline(baseline: PostgresBaseline, dir = BASELINE_DIR): void {
  const { sql, manifest } = renderBaseline(baseline);
  fs.mkdirSync(dir, { recursive: true });
  fs.writeFileSync(path.join(dir, SQL_FILE), sql);
  fs.writeFileSync(path.join(dir, MANIFEST_FILE), manifest);
}

/** Whether the committed files are what `baseline` renders to (the generator's `--check`). */
export function baselineMatches(baseline: PostgresBaseline, dir = BASELINE_DIR): boolean {
  const { sql, manifest } = renderBaseline(baseline);
  const read = (file: string) =>
    fs.existsSync(path.join(dir, file)) ? fs.readFileSync(path.join(dir, file), 'utf8') : null;
  return read(SQL_FILE) === sql && read(MANIFEST_FILE) === manifest;
}