"""SoftwareRadar's SQLite foreign-key experiment.

Run with: python3 sqlite-foreign-keys-demo.py
Only Python's standard library is required. All databases are in memory.
No data files are created, existing application databases opened or network calls made.
The explicit OFF/ON settings make the examples independent of a build's default.
"""

from contextlib import closing
import json
import platform
import sqlite3


def fresh():
    connection = sqlite3.connect(":memory:", isolation_level=None)
    connection.executescript("""
        CREATE TABLE projects (id INTEGER PRIMARY KEY);
        CREATE TABLE tasks (
            id INTEGER PRIMARY KEY,
            project_id INTEGER NOT NULL REFERENCES projects(id)
        );
        INSERT INTO projects VALUES (1);
    """)
    return connection


def flag(connection):
    row = connection.execute("PRAGMA foreign_keys").fetchone()
    if row is None:
        raise RuntimeError("This SQLite build does not expose foreign-key support.")
    return row[0]


def task_count(connection):
    return connection.execute("SELECT COUNT(*) FROM tasks").fetchone()[0]


def run():
    results = {"python_version": platform.python_version(), "sqlite_version": sqlite3.sqlite_version, "storage": ":memory:"}
    with closing(fresh()) as connection:
        results["initial_connection_foreign_keys"] = flag(connection)
        connection.execute("PRAGMA foreign_keys = OFF")
        assert flag(connection) == 0
        connection.execute("INSERT INTO tasks VALUES (102, 999)")
        before = task_count(connection)
        connection.execute("PRAGMA foreign_keys = ON")
        assert flag(connection) == 1
        after = task_count(connection)
        violations = connection.execute("PRAGMA foreign_key_check").fetchall()
        assert before == after == 1
        assert violations == [("tasks", 102, "projects", 0)]
        results["already_committed_orphan"] = {
            "insert_with_enforcement_off": "accepted",
            "rows_before_enabling": before,
            "rows_after_enabling": after,
            "foreign_key_check": violations,
        }

    with closing(fresh()) as connection:
        connection.execute("PRAGMA foreign_keys = OFF")
        connection.execute("BEGIN")
        connection.execute("PRAGMA foreign_keys = ON")
        inside_flag = flag(connection)
        connection.execute("INSERT INTO tasks VALUES (102, 999)")
        accepted = task_count(connection)
        connection.execute("ROLLBACK")
        remaining = task_count(connection)
        assert inside_flag == 0 and accepted == 1 and remaining == 0
        results["enable_inside_transaction"] = {
            "foreign_keys_after_attempt": inside_flag,
            "invalid_insert": "accepted",
            "pending_rows": accepted,
            "rows_after_explicit_rollback": remaining,
        }

    with closing(fresh()) as connection:
        connection.execute("PRAGMA foreign_keys = ON")
        assert flag(connection) == 1
        connection.execute("BEGIN")
        connection.execute("INSERT INTO tasks VALUES (101, 1)")
        try:
            connection.execute("INSERT INTO tasks VALUES (102, 999)")
        except sqlite3.IntegrityError as error:
            failure = {"type": type(error).__name__, "message": str(error)}
        else:
            raise AssertionError("An invalid immediate foreign key was accepted.")
        pending = task_count(connection)
        transaction_still_open = connection.in_transaction
        connection.execute("ROLLBACK")
        remaining = task_count(connection)
        assert pending == 1 and transaction_still_open and remaining == 0
        connection.execute("BEGIN")
        connection.execute("INSERT INTO tasks VALUES (201, 1)")
        connection.execute("INSERT INTO tasks VALUES (202, 1)")
        connection.execute("COMMIT")
        committed = task_count(connection)
        violations = connection.execute("PRAGMA foreign_key_check").fetchall()
        assert committed == 2 and violations == []
        results["enable_before_transaction"] = {
            "foreign_keys": 1,
            "invalid_insert_error": failure,
            "earlier_valid_rows_still_pending": pending,
            "transaction_still_open": transaction_still_open,
            "rows_after_explicit_rollback": remaining,
            "valid_rows_after_new_commit": committed,
            "final_foreign_key_check": violations,
        }
    return results


if __name__ == "__main__":
    print(json.dumps(run(), indent=2))
