"""Weekly small measurements, 2026-11-25. PostgreSQL 18.6 lab, port 5418."""
import os, sys, subprocess, tempfile
sys.path.insert(0, os.path.expanduser("~/products/c13/minis"))
from lab import *

HERE = os.path.dirname(os.path.abspath(__file__))
setup(os.path.join(HERE, "results.json"))
start()
save_env()
psql("DROP TABLE IF EXISTS t, t2, c, o, tt, tx, toast CASCADE;"
     "CREATE TABLE t (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, a int NOT NULL, b int NOT NULL, email text NOT NULL, amount numeric(12,2) NOT NULL, amount_big bigint NOT NULL, amount_dbl double precision NOT NULL, created_at timestamptz NOT NULL);"
     "INSERT INTO t (a,b,email,amount,amount_big,amount_dbl,created_at) SELECT g%1000, (g::bigint*7919)%1000, 'user'||g||'@example.com', (g%100000)/100.0, g%100000, (g%100000)/100.0, timestamptz '2026-01-01' + g*interval '10 seconds' FROM generate_series(1,2000000) g;"
     "VACUUM ANALYZE t")

# 1. LIKE prefix under default collation vs text_pattern_ops
coll = q1("select datcollate from pg_database where datname='lab'")
psql("CREATE INDEX t_email ON t (email); ANALYZE t")
lk = {"datcollate": coll, "plain_index": runs("SELECT count(*) FROM t WHERE email LIKE 'user12345%'", 3)}
psql("CREATE INDEX t_email_pat ON t (email text_pattern_ops); ANALYZE t")
lk["pattern_ops_index"] = runs("SELECT count(*) FROM t WHERE email LIKE 'user12345%'", 3)
lk["equality_plain"] = runs("SELECT count(*) FROM t WHERE email = 'user12345@example.com'", 3)
psql("DROP INDEX t_email, t_email_pat")
save("like_prefix", lk)

# 2. composite index order (a = const AND b range) vs (b,a)
q = "SELECT count(*) FROM t WHERE a = 42 AND b BETWEEN 100 AND 199"
psql("CREATE INDEX t_ab ON t (a, b); ANALYZE t")
co = {"ab": runs(q)}
psql("DROP INDEX t_ab; CREATE INDEX t_ba ON t (b, a); ANALYZE t")
co["ba"] = runs(q); co["rows"] = int(q1(q))
psql("DROP INDEX t_ba")
save("composite_order", co)

# 3. two single-column indexes (BitmapAnd) vs one composite
psql("CREATE INDEX t_a ON t (a); CREATE INDEX t_b ON t (b); ANALYZE t")
q3 = "SELECT count(*) FROM t WHERE a = 42 AND b = 7"
bm = {"two_single": runs(q3), "plan_two": psql("EXPLAIN (COSTS OFF) " + q3)}
psql("CREATE INDEX t_ab2 ON t (a, b); ANALYZE t")
bm["composite"] = runs(q3); bm["rows"] = int(q1(q3))
psql("DROP INDEX t_a, t_b, t_ab2")
save("bitmap_and", bm)

# 4. numeric vs bigint vs double sum
save("sum_types", {"numeric": runs("SELECT sum(amount) FROM t", 3, "SET max_parallel_workers_per_gather=0;"),
                   "bigint": runs("SELECT sum(amount_big) FROM t", 3, "SET max_parallel_workers_per_gather=0;"),
                   "double": runs("SELECT sum(amount_dbl) FROM t", 3, "SET max_parallel_workers_per_gather=0;")})

# 5. timestamptz vs text dates
psql("DROP TABLE IF EXISTS tx; CREATE TABLE tx AS SELECT id, created_at, to_char(created_at at time zone 'UTC','YYYY-MM-DD HH24:MI:SS') AS created_txt FROM t;"
     "CREATE INDEX tx_ts ON tx (created_at); CREATE INDEX tx_txt ON tx (created_txt); VACUUM ANALYZE tx")
ts = {"index_ts_mb": mb("tx_ts"), "index_txt_mb": mb("tx_txt"),
      "col_ts_bytes": int(q1("select avg(pg_column_size(created_at))::int from tx")), "col_txt_bytes": int(q1("select avg(pg_column_size(created_txt))::int from tx")),
      "range_ts": runs("SELECT count(*) FROM tx WHERE created_at >= '2026-03-01' AND created_at < '2026-03-08'"),
      "range_txt": runs("SELECT count(*) FROM tx WHERE created_txt >= '2026-03-01' AND created_txt < '2026-03-08'")}
psql("DROP TABLE tx")
save("timestamptz_vs_text", ts)

# 6. char(n) vs varchar(n) vs text
def ctab(typ):
    psql(f"DROP TABLE IF EXISTS cv; CREATE TABLE cv (v {typ}); INSERT INTO cv SELECT 'code'||(g%10000) FROM generate_series(1,2000000) g; VACUUM ANALYZE cv")
    return {"table_mb": mb("cv"), "eq": runs("SELECT count(*) FROM cv WHERE v = 'code42'", 3, "SET max_parallel_workers_per_gather=0;")}
save("char_varchar_text", {"char20": ctab("char(20)"), "varchar20": ctab("varchar(20)"), "text": ctab("text")})
psql("DROP TABLE IF EXISTS cv")

# 7. TOAST threshold: 1 kB, 3 kB, 10 kB strings (random so not compressible)
def toastcase(n):
    psql(f"DROP TABLE IF EXISTS toast; CREATE TABLE toast (id int, body text); "
         f"INSERT INTO toast SELECT g, (SELECT string_agg(md5(g::text||i::text), '') FROM generate_series(1,{n//32}) i) FROM generate_series(1,20000) g; VACUUM ANALYZE toast")
    tid = q1("select reltoastrelid::regclass from pg_class where relname='toast'")
    return {"bytes_each": n, "heap_mb": round(int(q1("select pg_relation_size('toast')"))/1e6, 1),
            "toast_mb": round(int(q1(f"select pg_relation_size('{tid}')"))/1e6, 1),
            "select_id_only": runs("SELECT sum(id) FROM toast", 3, "SET max_parallel_workers_per_gather=0;"),
            "select_body_length": runs("SELECT sum(length(body)) FROM toast", 3, "SET max_parallel_workers_per_gather=0;")}
save("toast", {str(n): toastcase(n) for n in (1024, 3072, 10240)} | {"rows": 20000})
psql("DROP TABLE IF EXISTS toast")

# 8. count(*) vs reltuples
rc = {"count": runs("SELECT count(*) FROM t", 3), "reltuples_query": runs("SELECT reltuples::bigint FROM pg_class WHERE relname='t'", 5),
      "reltuples": int(float(q1("select reltuples from pg_class where relname='t'"))), "actual": 2000000}
psql("INSERT INTO t (a,b,email,amount,amount_big,amount_dbl,created_at) SELECT 1,1,'x',0,0,0,now() FROM generate_series(1,200000)")
rc["reltuples_after_insert_200k_no_analyze"] = int(float(q1("select reltuples from pg_class where relname='t'")))
rc["planner_estimate_after_insert"] = q1("EXPLAIN SELECT * FROM t").split("rows=")[1].split()[0]
psql("DELETE FROM t WHERE email = 'x'; VACUUM ANALYZE t")
save("reltuples", rc)

# 9. semi-join: EXISTS vs IN vs JOIN+DISTINCT ; 10. anti-join: LEFT JOIN IS NULL vs NOT EXISTS
psql("DROP TABLE IF EXISTS c, o; CREATE TABLE c (id int PRIMARY KEY, name text); CREATE TABLE o (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, c_id int, amt int);"
     "INSERT INTO c SELECT g, 'c'||g FROM generate_series(1,200000) g; INSERT INTO o (c_id, amt) SELECT 1+(g*7)%150000, g%100 FROM generate_series(1,2000000) g;"
     "CREATE INDEX o_c ON o (c_id); VACUUM ANALYZE c; VACUUM ANALYZE o")
pre = "SET max_parallel_workers_per_gather=0;"
semi = {k: runs(v, 3, pre) for k, v in {
    "exists": "SELECT count(*) FROM c WHERE EXISTS (SELECT 1 FROM o WHERE o.c_id = c.id)",
    "in": "SELECT count(*) FROM c WHERE id IN (SELECT c_id FROM o)",
    "join_distinct": "SELECT count(*) FROM (SELECT DISTINCT c.id FROM c JOIN o ON o.c_id = c.id) s"}.items()}
semi["rows"] = int(q1("SELECT count(*) FROM c WHERE EXISTS (SELECT 1 FROM o WHERE o.c_id = c.id)"))
save("semi_join", semi)
anti = {"not_exists": runs("SELECT count(*) FROM c WHERE NOT EXISTS (SELECT 1 FROM o WHERE o.c_id = c.id)", 3, pre),
        "left_join_null": runs("SELECT count(*) FROM c LEFT JOIN o ON o.c_id = c.id WHERE o.id IS NULL", 3, pre),
        "plan_not_exists": [l.strip() for l in psql(pre + "EXPLAIN (COSTS OFF) SELECT count(*) FROM c WHERE NOT EXISTS (SELECT 1 FROM o WHERE o.c_id = c.id)").splitlines()][:4],
        "plan_left_join": [l.strip() for l in psql(pre + "EXPLAIN (COSTS OFF) SELECT count(*) FROM c LEFT JOIN o ON o.c_id = c.id WHERE o.id IS NULL").splitlines()][:4],
        "rows": int(q1("SELECT count(*) FROM c WHERE NOT EXISTS (SELECT 1 FROM o WHERE o.c_id = c.id)"))}
save("anti_join", anti)
psql("DROP TABLE c, o")

# 11. OR across two columns vs UNION
psql("CREATE INDEX t_a ON t (a); CREATE INDEX t_b ON t (b); ANALYZE t")
orr = {"or": runs("SELECT count(*) FROM t WHERE a = 42 OR b = 7"),
       "union": runs("SELECT count(*) FROM (SELECT id FROM t WHERE a = 42 UNION SELECT id FROM t WHERE b = 7) s"),
       "plan_or": [l.strip() for l in psql("EXPLAIN (COSTS OFF) SELECT count(*) FROM t WHERE a = 42 OR b = 7").splitlines()][:5]}
psql("DROP INDEX t_a, t_b")
save("or_vs_union", orr)

# 12. date(created_at) = ... vs range
psql("CREATE INDEX t_created ON t (created_at); ANALYZE t")
df = {"function": runs("SELECT count(*) FROM t WHERE date(created_at AT TIME ZONE 'UTC') = '2026-03-01'", 3),
      "range": runs("SELECT count(*) FROM t WHERE created_at >= '2026-03-01 00:00+00' AND created_at < '2026-03-02 00:00+00'", 3)}
psql("DROP INDEX t_created")
save("date_function_filter", df)

# 13. implicit cast: bigint id compared with numeric literal
save("implicit_cast", {"bigint_literal": runs("SELECT count(*) FROM t WHERE id = 1234567", 3),
                       "numeric_literal": runs("SELECT count(*) FROM t WHERE id = 1234567.0", 3),
                       "plan_numeric": [l.strip() for l in psql("EXPLAIN (COSTS OFF) SELECT count(*) FROM t WHERE id = 1234567.0").splitlines()][:4]})

# 14. pgbench select-only: simple vs prepared protocol
tmp = tempfile.mkdtemp(); scr = os.path.join(tmp, "s.sql")
open(scr, "w").write("\\set id random(1, 2000000)\nSELECT email FROM t WHERE id = :id;\n")
def pgb(mode):
    out = subprocess.run([f"{PG}/pgbench", "-n", "-c", "1", "-T", "10", "-M", mode, "-f", scr, "-h", HOST, "-p", "5418", "-U", "postgres", "lab"],
                         capture_output=True, text=True, check=True).stdout
    return [l for l in out.splitlines() if l.startswith("tps")][0]
save("pgbench_protocol", {m: [pgb(m) for _ in range(3)] for m in ("simple", "extended", "prepared")})

psql("DROP TABLE IF EXISTS t CASCADE")
stop()
print("done")
