#!/usr/bin/env python3 """Generate or check Marmot modules against Albedo's migrated SQLite schema.""" from __future__ import annotations import argparse from collections.abc import Callable, Generator, Iterator from concurrent.futures import ThreadPoolExecutor from contextlib import ExitStack, closing, contextmanager import fcntl from functools import cache, partial import os from pathlib import Path import re import sqlite3 import subprocess import sys import tempfile import tomllib ROOT = Path(__file__).resolve().parents[1] APP = ROOT / "apps/albedo" TOOL = ROOT / "tools/marmot" SqlSources = dict[Path, tuple[Path, str]] SchemaGroups = dict[tuple[Path, Path | None], SqlSources] @contextmanager def bootstrap( home: Path, groups: SchemaGroups ) -> Generator[tuple[Path, Callable[[], None]], None, None]: home.mkdir() with tempfile.TemporaryDirectory(dir=home) as directory: work = Path(directory) paths = [] for files in groups.values(): for relative, (_, content) in files.items(): target = work / relative target.parent.mkdir(parents=True, exist_ok=True) target.write_text(content) paths.append(relative) with (home / "marmot-bootstrap.json").open("wb") as manifest: subprocess.run( [generator(), "bootstrap-manifest", *paths], cwd=work, stdin=subprocess.DEVNULL, stdout=manifest, check=True, ) # Extension startup can refresh the catalogues on an empty home. (home / "extensions.json").write_text( '{"models":{"refreshHours":0},"modelFacts":{"url":null}}\n' ) env = { **os.environ, "ALBEDO_HOME": str(home), "ALBEDO_KERNEL_SPARES": "0", "ALBEDO_STANDBY": "0", "ALBEDO_NO_BROWSER": "1", "ALBEDO_PARENT_PID": str(os.getpid()), "GIT_CEILING_DIRECTORIES": os.pathsep.join( filter( None, [str(APP / "build"), os.environ.get("GIT_CEILING_DIRECTORIES")] ) ), } command = ["gleam", "run", "-m", "albedo/manual/marmot_schema"] with subprocess.Popen( command, cwd=APP, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, ) as process: assert process.stdin is not None and process.stdout is not None input_stream, output_stream = process.stdin, process.stdout def verify() -> None: input_stream.write("\n") input_stream.flush() try: for line in output_stream: if line == "marmot:schema-ready\n": break print(line, end="") else: raise subprocess.CalledProcessError(process.wait() or 1, command) yield home / "albedo.sqlite", verify finally: input_stream.close() for line in output_stream: print(line, end="") if status := process.wait(): raise subprocess.CalledProcessError(status, command) def schema_sql(database: Path) -> str: with closing(sqlite3.connect(database.as_uri() + "?mode=ro", uri=True)) as db: shadows = { name for _, name, kind, *_ in db.execute("PRAGMA main.table_list") if kind == "shadow" } rows = db.execute(""" SELECT name, sql FROM main.sqlite_schema WHERE sql IS NOT NULL AND name NOT GLOB 'sqlite_*' ORDER BY CASE type WHEN 'table' THEN 0 WHEN 'view' THEN 1 WHEN 'index' THEN 2 ELSE 3 END, name """) return "".join(sql + ";\n" for name, sql in rows if name not in shadows) @cache def generator() -> Path: built = subprocess.run( ["nix", "build", "--no-link", "--print-out-paths", ".#albedo-marmot"], cwd=ROOT, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True, check=True, ) return Path(built.stdout.strip()) / "bin/albedo-marmot" def script_statements(script: str) -> Iterator[str]: start = 0 for index, character in enumerate(script): if character == ";" and sqlite3.complete_statement(script[start : index + 1]): yield script[start : index + 1] start = index + 1 yield script[start:] def expand_includes(source: Path) -> str: lines = [] for number, line in enumerate( source.read_bytes().decode().splitlines(keepends=True), 1 ): directive = line.strip() if not directive.startswith("-- albedo: include"): lines.append(line) continue location = f"{source.relative_to(ROOT)}:{number}" match = re.fullmatch( r"-- albedo: include ([a-z][a-z0-9_]*\.sql\.inc)", directive ) if match is None: raise ValueError(f"{location}: expected an owner-local .sql.inc filename") included = source.with_name(match[1]) if ( included.is_symlink() or not included.is_file() or included.resolve().parent != source.parent.absolute() ): raise ValueError(f"{location}: invalid SQL include {match[1]}") fragment = included.read_bytes().decode() if not fragment.strip() or any( item.lstrip().startswith("-- albedo:") for item in fragment.splitlines() ): raise ValueError(f"{location}: use literal SQL in {match[1]}") lines.append(fragment if fragment.endswith("\n") else fragment + "\n") return "".join(lines) def script_body(content: str) -> str | None: text = content.strip().removeprefix("-- albedo: native errors\n") marker, _, body = text.partition("\n") return body if marker == "-- albedo: script" else None def prepare_scripts(database: Path, sources: dict[Path, str]) -> None: scripts = { source: body for source, content in sources.items() if (body := script_body(content)) is not None } if not scripts: return with closing(sqlite3.connect(":memory:")) as layout: layout.executescript(schema_sql(database)) for source, body in scripts.items(): with closing( sqlite3.connect(":memory:", cached_statements=0) ) as validation: layout.backup(validation) for statement in script_statements(body): prepare_statement(validation, statement, source) def prepare_statement(db: sqlite3.Connection, statement: str, source: Path) -> None: dependency = None while True: statement = statement.lstrip() if statement.startswith("--"): comment, _, statement = statement.partition("\n") if comment.startswith("-- albedo: requires table "): table = comment.removeprefix("-- albedo: requires table ") if dependency is not None or not re.fullmatch( r"[a-z_][a-z0-9_]*(?:\.[a-z_][a-z0-9_]*)?", table ): raise ValueError( f"{source.relative_to(ROOT)}: invalid script table dependency" ) dependency = f"no such table: {table}" elif statement.startswith("/*") and "*/" in statement: statement = statement.partition("*/")[2] else: break if statement in ("", ";"): return actions: set[int] = set() def record(action: int, *_: str | None) -> int: actions.add(action) return sqlite3.SQLITE_OK db.set_authorizer(record) try: db.execute("EXPLAIN " + statement).close() except sqlite3.Error as error: message = str(error) if message == dependency or ( message.startswith(("table ", "index ", "trigger ", "view ")) and message.endswith(" already exists") ): return raise ValueError(f"{source.relative_to(ROOT)}: {error}") from error finally: db.set_authorizer(None) # Stage structural changes for later statements in this script. A # CREATE TABLE AS SELECT also has SQLITE_SELECT and needs real data. creates_table = ( sqlite3.SQLITE_CREATE_TABLE in actions or sqlite3.SQLITE_CREATE_TEMP_TABLE in actions ) drops_table = ( sqlite3.SQLITE_DROP_TABLE in actions or sqlite3.SQLITE_DROP_TEMP_TABLE in actions ) alters_table = sqlite3.SQLITE_ALTER_TABLE in actions if ( (creates_table and sqlite3.SQLITE_SELECT not in actions) or drops_table or alters_table ): try: db.execute(statement).close() except sqlite3.Error as error: raise ValueError(f"{source.relative_to(ROOT)}: {error}") from error def sql_sources(selected: list[Path]) -> tuple[dict[str, Path], SchemaGroups]: output_dirs: dict[str, Path] = {} groups: SchemaGroups = {} for project in selected: config = project / "gleam.toml" settings = tomllib.loads(config.read_text()) marmot = settings.get("tools", {}).get("marmot", {}) if isinstance(marmot, dict) and "query_function" in marmot: raise ValueError( f"{config.relative_to(ROOT)}: tools.marmot.query_function is not supported by Albedo generation" ) namespace = settings["name"] if namespace in output_dirs: raise ValueError( f"{config.relative_to(ROOT)}: duplicate namespace {namespace}" ) output_dirs[namespace] = project / "src" / namespace / "generated/sql" for query in sorted(project.glob("src/**/sql/**/*.sql")): relative = query.relative_to(project) if ( relative.parts[1] != namespace or relative.parent.name != "sql" or "sql" in relative.parts[1:-2] ): raise ValueError( f"Unexpected Marmot query path: {query.relative_to(ROOT)}" ) overlay = query.parent.parent / "schema.overlay.sql" group = (project.parent, overlay if overlay.is_file() else None) groups.setdefault(group, {})[relative] = (query, expand_includes(query)) return output_dirs, groups def generate( command: Path, database: Path, output_dirs: dict[str, Path], work: Path, overlay: Path | None, sources: SqlSources, ) -> dict[Path, bytes]: work.mkdir() (work / "gleam.toml").write_text('name = "albedo_marmot_workspace"\n') if overlay is not None: schema = work / "historical.sqlite" with ( closing( sqlite3.connect(database.as_uri() + "?mode=ro", uri=True) ) as current, closing(sqlite3.connect(schema)) as historical, ): current.backup(historical) try: historical.executescript(overlay.read_text()) except sqlite3.Error as error: raise ValueError(f"{overlay.relative_to(ROOT)}: {error}") from error database = schema prepare_scripts(database, dict(sources.values())) for relative, (_, content) in sources.items(): target = work / relative target.parent.mkdir(parents=True, exist_ok=True) target.write_text(content) completed = subprocess.run( [command, "--database", database.as_uri() + "?mode=ro"], cwd=work, stdin=subprocess.DEVNULL, capture_output=True, text=True, check=False, ) if completed.returncode or completed.stderr: detail = completed.stderr.strip() or f"Marmot exited {completed.returncode}" raise ValueError(f"{(overlay or ROOT).relative_to(ROOT)}: {detail}") emitted = work / "src/generated/sql" outputs = {} for file in emitted.rglob("*_sql.gleam"): relative = file.relative_to(emitted) if len(relative.parts) == 1: # SQL at src//sql belongs at the root of that package. namespace = file.stem.removesuffix("_sql") module = Path("sql.gleam") else: namespace, *parts = relative.parts module = Path(*parts) outputs[output_dirs[namespace] / module] = file.read_bytes() return outputs def publish(actual: Path, content: bytes | None) -> None: if content is None: actual.unlink(missing_ok=True) return actual.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile(dir=actual.parent, delete=False) as temporary: path = Path(temporary.name) try: temporary.write(content) temporary.close() path.chmod(0o644) path.replace(actual) finally: path.unlink(missing_ok=True) def workspace_projects() -> list[Path]: return [APP, *sorted(ROOT.glob("packages/*")), *sorted(ROOT.glob("extensions/*"))] def main() -> int: parser = argparse.ArgumentParser(description=__doc__) mode = parser.add_mutually_exclusive_group() mode.add_argument("--check", action="store_true", help="Check for drift") mode.add_argument( "--refresh-schema", action="store_true", help="Refresh the schema snapshot from production migrations", ) mode.add_argument("--schema", type=Path, help="Reuse a migrated SQLite database") parser.add_argument( "projects", nargs="*", help="Workspace paths, such as extensions/mail" ) args = parser.parse_args() if args.refresh_schema and args.projects: parser.error( "--refresh-schema validates the whole workspace and takes no project filter" ) projects = workspace_projects() by_project = { str(project.relative_to(ROOT)): project for project in projects if (project / "gleam.toml").is_file() } unknown = sorted(set(args.projects) - by_project.keys()) if unknown: parser.error(f"Unknown workspace project: {', '.join(unknown)}") selected = [by_project[name] for name in (args.projects or by_project)] # Serialize checkout-local generation and drift checks across processes. lock = os.open(ROOT, os.O_RDONLY) try: fcntl.flock(lock, fcntl.LOCK_EX) return run(selected, selected if args.projects else projects, args) finally: os.close(lock) def run(selected: list[Path], projects: list[Path], args: argparse.Namespace) -> int: with ( tempfile.TemporaryDirectory(prefix="albedo-marmot-") as directory, ExitStack() as bootstrap_process, ): scratch = Path(directory) verify = None snapshot = TOOL / "schema.sql" initial_schema = snapshot.read_bytes() if snapshot.exists() else None refreshed = initial_schema output_dirs, groups = sql_sources(selected) def current_outputs() -> dict[Path, bytes]: return { file: file.read_bytes() for project in projects for file in project.glob("src/*/generated/sql/**/*.gleam") } original = current_outputs() if args.schema: database = args.schema.resolve(strict=True) elif args.check or args.refresh_schema: _, bootstrap_groups = ( sql_sources( [ project for project in workspace_projects() if (project / "gleam.toml").is_file() ] ) if args.projects else (output_dirs, groups) ) database, verify = bootstrap_process.enter_context( bootstrap(scratch / "home", bootstrap_groups) ) refreshed = schema_sql(database).encode() if args.refresh_schema: bootstrap_process.close() if args.check and refreshed != initial_schema: raise ValueError( "Marmot schema drift: run nix develop -c python3 test/marmot.py --refresh-schema" ) else: if initial_schema is None: raise ValueError( "Missing Marmot schema snapshot; run with --refresh-schema or --schema" ) database = scratch / "schema.sqlite" with closing(sqlite3.connect(database)) as db: db.executescript(initial_schema.decode()) expected: dict[Path, bytes] = {} if groups: generate_group = partial(generate, generator(), database, output_dirs) with ThreadPoolExecutor(max_workers=4) as pool: jobs = [ pool.submit(generate_group, scratch / str(index), overlay, sources) for index, ((_, overlay), sources) in enumerate(groups.items()) ] for job in jobs: outputs = job.result() if conflicts := expected.keys() & outputs.keys(): raise ValueError( f"Conflicting Marmot output: {min(conflicts).relative_to(ROOT)}" ) expected.update(outputs) if current_outputs() != original: raise ValueError("Generated files changed during generation; retry") drift = [ path for path in sorted(original.keys() | expected.keys()) if original.get(path) != expected.get(path) ] if args.check and drift: for path in drift: print(f"Marmot drift: {path.relative_to(ROOT)}", file=sys.stderr) print( "Run nix develop -c python3 test/marmot.py to regenerate.", file=sys.stderr, ) return 1 if args.check: assert verify is not None verify() return 0 if refreshed != initial_schema: if initial_schema is not None: original[snapshot] = initial_schema assert refreshed is not None expected[snapshot] = refreshed drift.append(snapshot) published = [] try: for path in drift: current = path.read_bytes() if path.exists() else None if current != original.get(path): raise ValueError(f"Concurrent edit to {path}") published.append(path) publish(path, expected.get(path)) except (OSError, ValueError, KeyboardInterrupt): for path in reversed(published): current = path.read_bytes() if path.exists() else None if current == expected.get(path): publish(path, original.get(path)) raise for path in published: print(f"Updated {path.relative_to(ROOT)}") return 0 if __name__ == "__main__": try: sys.exit(main()) except (OSError, ValueError, subprocess.CalledProcessError) as error: sys.exit(str(error))