"""Runtime FK enforcement across explicit in-memory SQLite connections."""
import sqlite3,json
def connection(enabled):
    c=sqlite3.connect(':memory:',isolation_level=None);c.execute('PRAGMA foreign_keys='+('ON'if enabled else'OFF'));state=c.execute('PRAGMA foreign_keys').fetchone();assert state is not None and state[0]==int(enabled)
    c.executescript('CREATE TABLE parent(id INTEGER PRIMARY KEY);CREATE TABLE child(id INTEGER PRIMARY KEY,pid INTEGER REFERENCES parent(id) ON DELETE NO ACTION);CREATE TABLE required_child(id INTEGER PRIMARY KEY,pid INTEGER NOT NULL REFERENCES parent(id) ON DELETE NO ACTION);INSERT INTO parent VALUES(1);')
    return c
def attempt(c,sql,params):
    try:c.execute(sql,params)
    except sqlite3.IntegrityError as e:return {'accepted':False,'error':str(e)}
    return {'accepted':True}
def demo():
    off=connection(False);on=connection(True);out={}
    for name,c in [('off',off),('on',on)]:
        orphan=attempt(c,'INSERT INTO child VALUES(?,?)',(10,999));null=attempt(c,'INSERT INTO child VALUES(?,?)',(11,None));valid=attempt(c,'INSERT INTO child VALUES(?,?)',(12,1));delete=attempt(c,'DELETE FROM parent WHERE id=?',(1,));notnull=attempt(c,'INSERT INTO required_child VALUES(?,?)',(1,None))
        out[name]={'pragma':c.execute('PRAGMA foreign_keys').fetchone()[0],'orphan_insert':orphan,'nullable_fk_null':null,'existing_parent_insert':valid,'referenced_parent_delete':delete,'not_null_is_separate':notnull,'final_children':[list(x)for x in c.execute('SELECT * FROM child ORDER BY id')]}
    assert out['off']['orphan_insert']['accepted']and not out['on']['orphan_insert']['accepted']
    assert out['off']['referenced_parent_delete']['accepted']and not out['on']['referenced_parent_delete']['accepted']
    assert all(x['nullable_fk_null']['accepted']and not x['not_null_is_separate']['accepted']for x in out.values())
    on.execute('BEGIN');on.execute('PRAGMA foreign_keys=OFF');inside=on.execute('PRAGMA foreign_keys').fetchone()[0];assert inside==1;on.execute('ROLLBACK');on.execute('PRAGMA foreign_keys=OFF');outside=on.execute('PRAGMA foreign_keys').fetchone()[0];assert outside==0
    off.close();on.close();return {'sqlite_version':sqlite3.sqlite_version,'explicit_connections':out,'pragma_off_attempt_inside_transaction':inside,'pragma_off_after_rollback':outside,'scope':'Immediate default FK, exact integer parent/child keys, no deferred/composite/cascade example. Definition and runtime enforcement are distinct; FK does not prove authorization, current text hash or business correctness. All data authored in independent :memory: DBs, no CRM touched.'}
if __name__=='__main__':print(json.dumps(demo(),indent=2))
