"""Re-run of two topics from run.py that failed (2026-11-29): trigger body split on ';', and a CHECK that row 1 violated.
Loads run.py's helpers by exec of its function definitions only."""
import os, sys, json
sys.path.insert(0, os.path.expanduser("~/products/c13/minis"))
from lab import *
import lab
HERE = os.path.dirname(os.path.abspath(__file__))
src = open(os.path.join(HERE, "run.py")).read()
helpers = src[src.index("PAR0 ="):src.index("psql(f\"DROP TABLE IF EXISTS {TABLES} CASCADE\")")]
setup(os.path.join(HERE, "results.json"))
lab.R.update(json.load(open(os.path.join(HERE, "results.json"))))
lab.R.pop("trigger_cost_error", None); lab.R.pop("check_constraint_cost_error", None)
exec(helpers)
start()
SRC = "SELECT g, g % 1000, md5(g::text) FROM generate_series(1,1000000) g"
sess(["DROP TABLE IF EXISTS x_t0, x_t1, x_t2, x_c0, x_c1, x_c5",
      "CREATE OR REPLACE FUNCTION x_noop() RETURNS trigger LANGUAGE plpgsql AS $$BEGIN RETURN NEW; END$$",
      "CREATE TABLE x_t0 (a int, b int, s text)", "CREATE TABLE x_t1 (a int, b int, s text)", "CREATE TABLE x_t2 (a int, b int, s text)",
      "CREATE TRIGGER x_t1_before BEFORE INSERT ON x_t1 FOR EACH ROW EXECUTE FUNCTION x_noop()",
      "CREATE TRIGGER x_t2_after AFTER INSERT ON x_t2 FOR EACH ROW EXECUTE FUNCTION x_noop()"])
r = {"rows": 1000000}
for t, label in [("x_t0", "none"), ("x_t1", "before_row_plpgsql"), ("x_t2", "after_row_plpgsql")]:
    r[label] = multi(f"INSERT INTO {t} {SRC}", tx=True)
save("trigger_cost", r)
sess(["DROP TABLE x_t0, x_t1, x_t2", "DROP FUNCTION x_noop()"])
psql("CREATE TABLE x_c0 (a int, b int, s text);"
     "CREATE TABLE x_c1 (a int CHECK (a > 0), b int, s text);"
     "CREATE TABLE x_c5 (a int CHECK (a > 0), b int CHECK (b >= 0), s text CHECK (length(s) = 32), CHECK (a >= b), CHECK (s <> ''))")
r = {"rows": 1000000}
for t, label in [("x_c0", "none"), ("x_c1", "one_check"), ("x_c5", "five_checks")]:
    r[label] = multi(f"INSERT INTO {t} {SRC}", tx=True)
save("check_constraint_cost", r)
psql("DROP TABLE x_c0, x_c1, x_c5")
stop()
print("DONE")
