"""Create the wiki database + schema, and import the existing work-notes.md. Idempotent: safe to run repeatedly. Connection comes from the WIKI_DB_* env vars (see db.py). Run: python migrate.py """ from __future__ import annotations import re from pathlib import Path import db from wikilib import slugify LEGACY_FILE = Path("work-notes.md") def _statements(sql: str) -> list[str]: # naive splitter: our schema has no semicolons inside statements return [s.strip() for s in sql.split(";") if s.strip()] def main() -> None: name = db.db_name() # 1. create the database (connect without selecting one) root = db.connect(select_db=False) with root.cursor() as cur: cur.execute( f"CREATE DATABASE IF NOT EXISTS `{name}` " "CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" ) root.close() print(f"database `{name}` ready") # 2. apply schema conn = db.connect() schema = Path("schema.sql").read_text() with conn.cursor() as cur: for stmt in _statements(schema): cur.execute(stmt) # additive migration for existing installs (MySQL lacks ADD COLUMN IF NOT EXISTS) try: cur.execute( "ALTER TABLE notes ADD COLUMN archived TINYINT(1) NOT NULL DEFAULT 0" ) print("added notes.archived column") except Exception: pass # column already exists print("schema applied") # 3. import the legacy single-file note, if present and not already imported if LEGACY_FILE.exists(): body = LEGACY_FILE.read_text() slug = "work-notes" # title = first markdown heading, else a sensible default m = re.search(r"^#\s+(.+)$", body, re.MULTILINE) title = m.group(1).strip() if m else "Work Notes" with conn.cursor() as cur: cur.execute("SELECT id FROM notes WHERE slug=%s", (slug,)) if cur.fetchone(): print(f"note '{slug}' already exists, skipping import") else: cur.execute( "INSERT INTO notes (slug, title, body_md) VALUES (%s,%s,%s)", (slug, title, body), ) print(f"imported {LEGACY_FILE} as note '{slug}' (title: {title!r})") else: print(f"{LEGACY_FILE} not found, nothing to import") conn.close() print("done") if __name__ == "__main__": main()