#!/usr/bin/env python3
"""Generate the per-thread SQL streams for the TBR-2088 reproducer."""
import random, sys
OUT = sys.argv[1] if len(sys.argv) > 1 else "."
TABLES = ["t%d" % i for i in range(1, (int(sys.argv[2]) if len(sys.argv) > 2 else 6) + 1)]

def val(r):
    c = r.randint(0, 5)
    return ("1" if c == 0 else str(r.randint(2, 8)) if c == 1 else
            str(r.randint(9, 64)) if c == 2 else str(r.randint(65, 512)) if c == 3 else
            str(r.randint(513, 4096)) if c == 4 else "NULL")

def blob(v):
    return "REPEAT(SUBSTR(CAST( %s AS CHAR),1,1), @fill_amount)" % v

for f in range(1, 9):
    r = random.Random(400 + f)
    out = ["SET AUTOCOMMIT = 0;", "SET @fill_amount = (@@innodb_page_size / 2 ) + 1;"]
    for _ in range(6000):
        t, v, a = r.choice(TABLES), val(r), r.randint(0, 3)
        if a == 0:
            out.append("UPDATE %s SET col_text = %s;" % (t, blob(v)))
        elif a == 1:
            out.append("UPDATE %s SET col2 = %s;" % (t, v))
        elif a == 2:
            out.append("INSERT INTO %s (col1,col2,col_text) VALUES ( %s, %s, %s );" % (t, v, v, blob(v)))
        else:
            out.append("DELETE FROM %s WHERE col2 = %s OR col2 IS NULL;" % (t, v))
        out.append(r.choice(["COMMIT", "COMMIT", "ROLLBACK"]) + ";")
    open("%s/dml_%d.sql" % (OUT, f), "w").write("\n".join(out) + "\n")
