"""Owned temporary DBs only. Never accepts source DB paths or touches application data."""
from pathlib import Path
import sqlite3,platform,json,time,uuid,contextlib
@contextlib.contextmanager
def owned_directory(base):
 root=base/('authored-wal-'+uuid.uuid4().hex)
 root.mkdir(mode=0o777)
 yield root
 # Preserve only this tiny generated fixture; never recursively remove a caller path.
def demo():
 base=Path(__file__).resolve().parent/'scope33-owned-fixtures';base.mkdir(exist_ok=True)
 with owned_directory(base)as name:
  root=Path(name).resolve();assert root.parent==base.resolve()
  db=root/'source.db';rawcopy=root/'raw-main-copy.db';backup=root/'api-backup.db'
  connections=[]
  def open_db(p):
   assert p.parent==root and p in [db,rawcopy,backup]
   c=sqlite3.connect(p,isolation_level=None,timeout=0.2);connections.append(c);return c
  try:
   writer=open_db(db);assert writer.execute('PRAGMA journal_mode=WAL').fetchone()[0]=='wal'
   writer.execute('PRAGMA wal_autocheckpoint=0');assert writer.execute('PRAGMA wal_autocheckpoint').fetchone()[0]==0
   writer.execute('CREATE TABLE item(id INTEGER PRIMARY KEY,value TEXT NOT NULL)')
   writer.execute("INSERT INTO item VALUES(1,'baseline')")
   cp=writer.execute('PRAGMA wal_checkpoint(TRUNCATE)').fetchone();assert cp==(0,0,0)
   writer.execute('BEGIN');writer.execute("INSERT INTO item VALUES(2,'committed-wal')");writer.execute('COMMIT')
   assert Path(str(db)+'-wal').stat().st_size>0
   writer.execute('BEGIN');writer.execute("INSERT INTO item VALUES(3,'not-committed')")
   reader=open_db(db)
   query='SELECT id,value FROM item ORDER BY id'
   wr=writer.execute(query).fetchall();rr=reader.execute(query).fetchall()
   assert wr==[(1,'baseline'),(2,'committed-wal'),(3,'not-committed')]
   assert rr==[(1,'baseline'),(2,'committed-wal')]
   rawcopy.write_bytes(db.read_bytes());raw=open_db(rawcopy);rawrows=raw.execute(query).fetchall();assert rawrows==[(1,'baseline')]
   dest=open_db(backup);progress=[];started=time.monotonic()
   def check(status,remaining,total):
    progress.append([status,remaining,total])
    if len(progress)>100 or time.monotonic()-started>3:raise TimeoutError('bounded fixture backup')
   reader.backup(dest,pages=1,progress=check,sleep=0.001);dest.close();connections.remove(dest)
   restored=open_db(backup);rows=restored.execute(query).fetchall();integrity=restored.execute('PRAGMA integrity_check').fetchall()
   assert rows==[(1,'baseline'),(2,'committed-wal')]and integrity==[('ok',)]
   schema=restored.execute("SELECT sql FROM sqlite_master WHERE type='table' AND name='item'").fetchone()[0]
   assert schema=='CREATE TABLE item(id INTEGER PRIMARY KEY,value TEXT NOT NULL)'
   writer.execute('ROLLBACK');assert reader.execute(query).fetchall()==rows
   return {'python':platform.python_version(),'sqlite':sqlite3.sqlite_version,'journal_mode':'wal','wal_autocheckpoint':0,'baseline_checkpoint':list(cp),'writer_visible_before_rollback':wr,'independent_reader_visible':rr,'raw_main_only_copy_rows':rawrows,'fresh_connection_restored_rows':rows,'integrity_check':integrity,'restored_schema':schema,'backup_progress':progress,'source_existing_app_data_opened':False,'source_wal_manually_deleted_or_moved':False,'power_loss_or_production_concurrency_test':False,'all_assertions_passed':True}
  finally:
   for c in reversed(connections):c.close()
if __name__=='__main__':print(json.dumps(demo(),indent=2))
