"""Original partial-import/parent rollback fixture, memory SQLite only."""
import sqlite3,json
INPUT=[(1,'A'),(2,'B'),(3,'A'),(4,'D')]
def db():
    c=sqlite3.connect(':memory:',isolation_level=None);c.execute('CREATE TABLE item(id INTEGER PRIMARY KEY, code TEXT NOT NULL UNIQUE)');return c
def ids(c):return [x[0]for x in c.execute('SELECT id FROM item ORDER BY id')]
def demo():
    whole=db();whole.execute('BEGIN');rejected=None
    try:
        for row in INPUT:whole.execute('INSERT INTO item VALUES(?,?)',row)
    except sqlite3.IntegrityError:rejected=row[0];whole.execute('ROLLBACK')
    assert rejected==3 and ids(whole)==[]
    partial=db();partial.execute('BEGIN');ledger=[]
    for row in INPUT:
        partial.execute('SAVEPOINT one_row')
        try:partial.execute('INSERT INTO item VALUES(?,?)',row)
        except sqlite3.IntegrityError:
            partial.execute('ROLLBACK TO one_row');partial.execute('ROLLBACK TO one_row');ledger.append({'id':row[0],'status':'rejected','savepoint_still_exists_after_rollback_to':True})
        else:ledger.append({'id':row[0],'status':'accepted_in_open_parent'})
        partial.execute('RELEASE one_row')
    assert ids(partial)==[1,2,4];partial.execute('COMMIT');final=ids(partial)
    parent=db();parent.execute('BEGIN');parent.execute('SAVEPOINT inner');parent.execute('INSERT INTO item VALUES(?,?)',(9,'Z'));parent.execute('RELEASE inner');before=ids(parent);assert before==[9]and parent.in_transaction
    parent.execute('ROLLBACK');after=ids(parent);assert after==[]
    for c in [whole,partial,parent]:c.close()
    return {'sqlite_version':sqlite3.sqlite_version,'fixed_authored_input':[list(x)for x in INPUT],'all_or_nothing':{'first_bad_id':rejected,'final_ids':[]},'per_row_savepoint':{'ledger':ledger,'final_ids_after_parent_commit':final},'released_inner_then_outer_rollback':{'before_parent_rollback':before,'after_parent_rollback':after},'scope':'All databases :memory:; commit means committed in-memory transaction, not disk durability/crash test. No CRM/importer/foreign key deferral/concurrency or retry idempotency implemented.'}
if __name__=='__main__':print(json.dumps(demo(),indent=2))
