"""One stray row in a default partition, and what it does to creating new partitions.

Runs against any PostgreSQL 13+ you point it at:

    docker run --rm -d -p 5432:5432 -e POSTGRES_PASSWORD=pg postgres:18
    pip install "psycopg[binary]"
    DATABASE_URL=postgresql://postgres:pg@localhost:5432/postgres python3 experiment.py

It creates and drops a schema named `partition_lab`, and nothing else.
"""

import os
import statistics
import threading
import time
from datetime import date

import psycopg

URL = os.environ["DATABASE_URL"]
SIZES = (0, 10_000, 100_000, 1_000_000, 2_000_000)
REPEATS = 5

# Fixed dates, so every run prints the same months.
FIRST_MONTH = date(2026, 1, 1)
STRAY_DATE = date(2026, 5, 17)


def month(i: int) -> date:
    """The first day of the month `i` months after FIRST_MONTH."""
    return date(2026 + i // 12, 1 + i % 12, 1)


SCHEMA = """
DROP SCHEMA IF EXISTS partition_lab CASCADE;
CREATE SCHEMA partition_lab;
SET search_path = partition_lab;

CREATE TABLE payments (
    id          bigint GENERATED ALWAYS AS IDENTITY,
    occurred_on date NOT NULL,
    note        text NOT NULL
) PARTITION BY RANGE (occurred_on);
CREATE TABLE payments_default PARTITION OF payments DEFAULT;

CREATE TABLE audit_log (
    id         bigint GENERATED ALWAYS AS IDENTITY,
    written_on date NOT NULL,
    note       text NOT NULL
) PARTITION BY RANGE (written_on);
CREATE TABLE audit_log_default PARTITION OF audit_log DEFAULT;

-- One month of one table.
CREATE FUNCTION create_month(tbl text, month_start date) RETURNS void
LANGUAGE plpgsql AS $$
BEGIN
    EXECUTE format(
        'CREATE TABLE partition_lab.%I PARTITION OF partition_lab.%I FOR VALUES FROM (%L) TO (%L)',
        tbl || '_' || to_char(month_start, 'YYYY_MM'), tbl,
        month_start, (month_start + interval '1 month')::date
    );
END;
$$;

-- The job as it is usually written: every table and month in one go.
CREATE FUNCTION mint_together(first_month date, months int) RETURNS void
LANGUAGE plpgsql AS $$
DECLARE
    tbl text;
BEGIN
    FOREACH tbl IN ARRAY ARRAY['payments', 'audit_log'] LOOP
        FOR i IN 0..months - 1 LOOP
            PERFORM partition_lab.create_month(tbl, (first_month + make_interval(months => i))::date);
        END LOOP;
    END LOOP;
END;
$$;

-- The same job, each month in a subtransaction of its own. Only PostgreSQL's
-- refusal (check_violation) is left behind; anything else still fails the job.
CREATE FUNCTION mint_each(first_month date, months int) RETURNS void
LANGUAGE plpgsql AS $$
DECLARE
    tbl         text;
    month_start date;
BEGIN
    FOREACH tbl IN ARRAY ARRAY['payments', 'audit_log'] LOOP
        FOR i IN 0..months - 1 LOOP
            month_start := (first_month + make_interval(months => i))::date;
            BEGIN
                PERFORM partition_lab.create_month(tbl, month_start);
            EXCEPTION WHEN check_violation THEN
                RAISE WARNING '% % not created: %', tbl, to_char(month_start, 'YYYY-MM'), SQLERRM;
            END;
        END LOOP;
    END LOOP;
END;
$$;
"""

PARTITIONS = """
SELECT c.relname
FROM pg_inherits i
JOIN pg_class c ON c.oid = i.inhrelid
JOIN pg_class p ON p.oid = i.inhparent
WHERE p.relname = %s AND c.relnamespace = 'partition_lab'::regnamespace
ORDER BY c.relname
"""


def connect() -> psycopg.Connection:
    conn = psycopg.connect(URL, autocommit=True)
    conn.execute("SET search_path = partition_lab")
    return conn


def partitions(conn: psycopg.Connection, table: str) -> list[str]:
    return [name.removeprefix(table + "_") for (name,) in conn.execute(PARTITIONS, (table,))]


def reset(conn: psycopg.Connection) -> None:
    conn.execute(SCHEMA)


def heading(text: str) -> None:
    print(f"\n== {text}")


def one_stray_row(conn: psycopg.Connection) -> None:
    heading("1. One row dated in a month that does not exist yet")
    reset(conn)
    conn.execute("INSERT INTO payments (occurred_on, note) VALUES (%s, 'dated ahead')", (STRAY_DATE,))
    holder = conn.execute(
        "SELECT tableoid::regclass::text FROM payments WHERE occurred_on = %s", (STRAY_DATE,)
    ).fetchone()[0]
    print(f"row dated {STRAY_DATE} is stored in: {holder}")

    heading("2. The job that creates every table and month together")
    try:
        conn.execute("SELECT mint_together(%s, 6)", (FIRST_MONTH,))
    except psycopg.errors.CheckViolation as error:
        print(f"SQLSTATE {error.sqlstate}: {error.diag.message_primary}")
    print(f"payments  partitions: {partitions(conn, 'payments')}")
    print(f"audit_log partitions: {partitions(conn, 'audit_log')}")

    heading("3. With no months, every new row goes to the default partitions")
    for i in range(6):
        conn.execute("INSERT INTO payments (occurred_on, note) VALUES (%s, 'ordinary')", (month(i),))
        conn.execute("INSERT INTO audit_log (written_on, note) VALUES (%s, 'ordinary')", (month(i),))
    for table in ("payments", "audit_log"):
        count = conn.execute(f"SELECT count(*) FROM {table}_default").fetchone()[0]  # noqa: S608
        print(f"{table}_default holds {count} rows")

    heading("4. The same job, each month in its own subtransaction")
    reset(conn)
    conn.execute("INSERT INTO payments (occurred_on, note) VALUES (%s, 'dated ahead')", (STRAY_DATE,))
    warnings: list[str] = []
    conn.add_notice_handler(lambda diag: warnings.append(diag.message_primary))
    conn.execute("SELECT mint_each(%s, 6)", (FIRST_MONTH,))
    for warning in warnings:
        print(f"WARNING: {warning}")
    print(f"payments  partitions: {partitions(conn, 'payments')}")
    print(f"audit_log partitions: {partitions(conn, 'audit_log')}")

    heading("5. Repair: move the row and create its month in one transaction")
    with conn.transaction():
        conn.execute("CREATE TEMP TABLE moved ON COMMIT DROP AS SELECT occurred_on, note FROM payments LIMIT 0")
        conn.execute(
            "WITH gone AS (DELETE FROM payments_default WHERE occurred_on >= %s AND occurred_on < %s "
            "RETURNING occurred_on, note) INSERT INTO moved SELECT * FROM gone",
            (month(4), month(5)),
        )
        conn.execute("SELECT create_month('payments', %s)", (month(4),))
        conn.execute("INSERT INTO payments (occurred_on, note) SELECT occurred_on, note FROM moved")
    holder = conn.execute(
        "SELECT tableoid::regclass::text FROM payments WHERE occurred_on = %s", (STRAY_DATE,)
    ).fetchone()[0]
    print(f"row dated {STRAY_DATE} is stored in: {holder}")
    print(f"payments  partitions: {partitions(conn, 'payments')}")


def fill_default(conn: psycopg.Connection, rows: int) -> None:
    """History: rows dated years before the first month, so they belong in no month the job creates."""
    reset(conn)
    conn.execute("SELECT create_month('payments', %s)", (month(0),))
    if rows:
        conn.execute(
            "INSERT INTO payments (occurred_on, note) "
            "SELECT date '2019-01-01' + (n %% 1800), 'history row, about fifty bytes of ordinary text' "
            "FROM generate_series(1, %s) AS n",
            (rows,),
        )
    conn.execute("VACUUM (ANALYZE) payments")
    conn.execute("SELECT count(*) FROM payments_default")  # warm the cache


LOCKS_HELD = """
SELECT c.relname, l.mode
FROM pg_locks l JOIN pg_class c ON c.oid = l.relation
WHERE l.pid = pg_backend_pid() AND l.locktype = 'relation'
  AND c.relname IN ('payments', 'payments_default')
ORDER BY c.relname, l.mode
"""

CREATE_NEXT = "CREATE TABLE payments_2026_02 PARTITION OF payments FOR VALUES FROM ('2026-02-01') TO ('2026-03-01')"
ATTACH_NEXT = (
    "CREATE TABLE payments_2026_02 (LIKE payments);"
    "ALTER TABLE payments ATTACH PARTITION payments_2026_02 FOR VALUES FROM ('2026-02-01') TO ('2026-03-01')"
)


def timed_ms(conn: psycopg.Connection, statement: str) -> float:
    """Run the statement in a transaction, time it, and roll it back."""
    conn.execute("BEGIN")
    started = time.perf_counter()
    conn.execute(statement)
    elapsed = (time.perf_counter() - started) * 1000
    conn.execute("ROLLBACK")
    return elapsed


def the_scan(conn: psycopg.Connection) -> None:
    heading("6. Creating one month, by how many rows the default partition holds")
    print(f"{'rows in default':>16} {'default size':>13} {'create, median ms':>18} {'min':>7} {'max':>7}")
    for rows in SIZES:
        fill_default(conn, rows)
        size = conn.execute("SELECT pg_size_pretty(pg_relation_size('payments_default'))").fetchone()[0]
        runs = [timed_ms(conn, CREATE_NEXT) for _ in range(REPEATS)]
        print(f"{rows:>16,} {size:>13} {statistics.median(runs):>18.1f} {min(runs):>7.1f} {max(runs):>7.1f}")

    heading(f"7. Locks held while creating a month ({SIZES[-1]:,} rows in the default)")
    for label, statement in (("CREATE TABLE ... PARTITION OF", CREATE_NEXT), ("ATTACH PARTITION", ATTACH_NEXT)):
        conn.execute("BEGIN")
        conn.execute(statement)
        held = conn.execute(LOCKS_HELD).fetchall()
        conn.execute("ROLLBACK")
        print(label)
        for relname, mode in held:
            print(f"    {relname:<17} {mode}")

    heading("8. A check constraint on the default partition that excludes the new month")
    conn.execute("ALTER TABLE payments_default ADD CONSTRAINT history_only CHECK (occurred_on < date '2026-01-01')")
    runs = [timed_ms(conn, CREATE_NEXT) for _ in range(REPEATS)]
    print(f"create, median ms: {statistics.median(runs):.1f}  (min {min(runs):.1f}, max {max(runs):.1f})")
    try:
        conn.execute("INSERT INTO payments (occurred_on, note) VALUES (%s, 'dated ahead')", (STRAY_DATE,))
    except psycopg.errors.CheckViolation as error:
        print(f"insert dated {STRAY_DATE}: SQLSTATE {error.sqlstate}: {error.diag.message_primary}")
    conn.execute("ALTER TABLE payments_default DROP CONSTRAINT history_only")


def slowest_ms(statement: str, params: tuple[object, ...], stop: threading.Event, out: list[float]) -> None:
    """Repeat one statement on its own connection until told to stop; record the slowest run."""
    with connect() as conn:
        slowest = 0.0
        while not stop.is_set():
            started = time.perf_counter()
            conn.execute(statement, params).fetchall()
            slowest = max(slowest, (time.perf_counter() - started) * 1000)
            time.sleep(0.002)
        out.append(slowest)


def the_wait(conn: psycopg.Connection) -> None:
    heading(f"9. What other sessions wait for meanwhile ({SIZES[-1]:,} rows in the default)")
    workloads = (
        ("insert into the current month", "INSERT INTO payments (occurred_on, note) VALUES (%s, 'live') RETURNING id"),
        ("read of the current month", "SELECT count(*) FROM payments WHERE occurred_on = %s"),
        ("read across all months", "SELECT count(*) FROM payments WHERE note = %s"),
    )
    params: tuple[tuple[object, ...], ...] = ((date(2026, 1, 15),), (date(2026, 1, 15),), ("live",))
    print(f"{'slowest statement, ms':<32} {'idle':>8} {'PARTITION OF':>13} {'ATTACH':>8}")
    results: dict[str, list[float]] = {name: [] for name, _ in workloads}
    for statement in (None, CREATE_NEXT, ATTACH_NEXT):
        fill_default(conn, SIZES[-1])
        stop = threading.Event()
        outs: list[list[float]] = [[] for _ in workloads]
        threads = [
            threading.Thread(target=slowest_ms, args=(sql, p, stop, out))
            for (_, sql), p, out in zip(workloads, params, outs, strict=True)
        ]
        for thread in threads:
            thread.start()
        time.sleep(0.5)
        if statement:
            for _ in range(REPEATS):
                timed_ms(conn, statement)
                time.sleep(0.1)
        else:
            time.sleep(1.0)
        stop.set()
        for thread in threads:
            thread.join()
        for (name, _), out in zip(workloads, outs, strict=True):
            results[name].append(out[0])
    for name, values in results.items():
        print(f"{name:<32} {values[0]:>8.1f} {values[1]:>13.1f} {values[2]:>8.1f}")


def main() -> None:
    with connect() as conn:
        print(conn.execute("SELECT version()").fetchone()[0])
        one_stray_row(conn)
        the_scan(conn)
        the_wait(conn)
        conn.execute("DROP SCHEMA partition_lab CASCADE")


if __name__ == "__main__":
    main()
