"""Keep committed rows in WAL while a separate backup process runs."""
from pathlib import Path
import sqlite3
import subprocess
import sys

folder = Path("sqlite-backup-demo")
folder.mkdir(exist_ok=True)
source = folder / "live.sqlite"
if source.exists():
    raise SystemExit("Use a fresh demo directory")
con = sqlite3.connect(source, isolation_level=None)
try:
    assert con.execute("PRAGMA journal_mode=WAL").fetchone()[0] == "wal"
    con.execute("PRAGMA wal_autocheckpoint=0")
    con.execute("CREATE TABLE jobs (id INTEGER PRIMARY KEY, status TEXT NOT NULL)")
    con.executemany("INSERT INTO jobs VALUES (?, ?)", [(1, "done"), (2, "done")])
    assert Path(str(source) + "-wal").stat().st_size > 0
    print("WAL has committed data", flush=True)
    subprocess.run([sys.executable, "backup_sqlite.py", str(source),
                    str(folder / "snapshot.sqlite")], check=True)
    con.execute("INSERT INTO jobs VALUES (?, ?)", (3, "later"))
    print("LIVE rows=3; snapshot should still have 2", flush=True)
finally:
    con.close()
