cn-sqlite-sft / scripts /seed_suite.py
YukiKaze1337's picture
Squash history
d847043
Raw History Blame Contribute Delete
16.5 kB
"""给测试库现生成几份像样的假数据。评测时标准 SQL 和模型 SQL 要在每一份上结果都一样才算对。
python scripts/seed_suite.py --data data/test_gym.jsonl --k 5 # 写到 seeds/suite/ 看看长什么样
eval.py 直接 import make_suite,每次评测现生成:日期是相对今天铺的,文件放久了「最近 30 天」就不准了。
seed.py 是按列名猜的,publish_year 里塞的是「季度13」这种字符串,很多 WHERE 对所有行都成立,
漏写条件的 SQL 也能「答对」。这里改成:
- 按声明类型出值,INTEGER 就是整数,年份就是年份
- 把标准 SQL 里的字面量('金卡'、'已完成'、price > 100 的 100)抠出来,让条件有的行成立、有的不成立
- 外键取真实 id,而且偏斜分布,「最多的前几个」才排得出名次
- 名字、手机号这类列不重复,按 id 分组和按名字分组结果一致
- 只有标准 SQL 里用 IS NULL 判断过的列才放 NULL
- 日期铺在近几年,三成落在最近两个月,date('now', ...) 才有意义
- 生成 k 份,每份行数、取值都不同,碰巧在一份上对上的错 SQL 很难 k 份都对上
- 建表语句里注释写了取值的(status TEXT -- 待缴/已缴/逾期),就只用这几个值;
SQL 里写了注释之外的值('approved' 写成 '已批准'),条件永远不成立,一查就是空的
- 声明成 DATE / DATETIME 的列按日期出,列名不带 date 也一样(reg_dt、crt_dt);
parent_xxx_id、manager_employee_id 这种指向自己表的列当自引用
"""
import argparse
import datetime as dt
import json
import random
import re
import sqlite3
from collections import defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parent
if not (ROOT / "schemas").is_dir():
ROOT = ROOT.parent
SURNAMES = "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜"
GIVEN = "伟芳娜秀英敏静丽强磊洋艳勇军杰娟涛明超霞平刚桂"
WORDS = ["星光", "远航", "青禾", "云杉", "锦程", "明川", "北辰", "南风", "晨曦", "松涛"]
# (列名里出现的词, 候选值);标准 SQL 里抠出来的字面量会再混进去
POOLS = [
(("status", "state"), ["已完成", "已取消", "进行中", "待支付", "已发货", "已退款"]),
(("gender", "sex"), ["男", "女"]),
(("level", "tier", "grade"), ["普通", "银卡", "金卡", "钻石"]),
(("city", "address", "region"), ["北京", "上海", "广州", "深圳", "杭州", "成都", "武汉", "南京"]),
(("country", "nationality"), ["中国", "美国", "日本", "德国", "法国", "韩国"]),
(("channel",), ["线上", "门店", "小程序", "APP"]),
(("device",), ["闸机1", "闸机2", "前台", "APP"]),
(("reason",), ["质量问题", "尺码不合适", "不喜欢", "发错货"]),
]
# 8 个,比「前五」多:候选值太少的话 LIMIT 5 和 LIMIT 6 结果一样,写错 LIMIT 也查不出来
GENERIC = ["甲类", "乙类", "丙类", "丁类", "戊类", "己类", "庚类", "辛类"]
PERSON = ("name", "author", "contact", "customer_name", "full_name", "reader_name", "member_name")
NOT_ALIAS = {"on", "where", "join", "left", "right", "inner", "outer", "full", "cross", "natural",
"group", "order", "limit", "having", "union", "using", "as"}
OPS = r"(?:=|!=|<>|>=|<=|>|<)"
def harvest(sqls: list[str], tables: set[str]):
"""从标准 SQL 里抠:每列的文本/数字字面量、LIKE 片段、IS NULL 的列、表之间的连接条件、
date('now', '-30 days') 这种相对日期的偏移量。"""
text, nums, likes = defaultdict(set), defaultdict(set), defaultdict(set)
nulls, joins, offsets = set(), set(), set()
for s in sqls:
offsets.update(m.lower() for m in re.findall(r"(?i)'([+-]\d+\s+(?:days?|months?|years?))'", s))
for col, lit in re.findall(rf"(\w+)\s*{OPS}\s*'([^']*)'", s):
text[col.lower()].add(lit)
for col, body in re.findall(r"(?i)(\w+)\s+(?:not\s+)?in\s*\(([^()]*)\)", s):
text[col.lower()].update(re.findall(r"'([^']*)'", body))
for col, lit in re.findall(r"(?i)(\w+)\s+(?:not\s+)?like\s+'([^']*)'", s):
likes[col.lower()].add(lit.strip("%"))
for col, lit in re.findall(rf"(\w+)\s*{OPS}\s*(-?\d+(?:\.\d+)?)\b", s):
nums[col.lower()].add(float(lit))
nulls.update(c.lower() for c in re.findall(r"(?i)(\w+)\s+is\s+null", s))
alias = {}
for t, a in re.findall(r"(?i)\b(?:from|join)\s+(\w+)(?:\s+(?:as\s+)?(\w+))?", s):
if t.lower() in tables:
alias[t.lower()] = t.lower()
if a and a.lower() not in NOT_ALIAS:
alias[a.lower()] = t.lower()
for a1, c1, a2, c2 in re.findall(r"(\w+)\.(\w+)\s*=\s*(\w+)\.(\w+)", s):
t1, t2 = alias.get(a1.lower()), alias.get(a2.lower())
if t1 and t2 and t1 != t2:
joins.add((t1, c1.lower(), t2, c2.lower()))
joins.add((t2, c2.lower(), t1, c1.lower()))
return text, nums, likes, nulls, joins, offsets
def comment_enums(ddl: str) -> dict[str, dict[str, list[str]]]:
"""建表语句注释里写的取值:`status TEXT, -- 状态:正常/停用/注销` → {"users": {"status": ["正常", "停用", "注销"]}}"""
out, table = defaultdict(dict), None
for line in ddl.splitlines():
m = re.match(r'(?i)\s*create\s+table\s+(?:if\s+not\s+exists\s+)?"?(\w+)"?', line)
if m:
table = m.group(1).lower()
continue
m = re.match(r'\s*"?(\w+)"?\s+\w[^-]*--\s*(.+?)\s*$', line)
if not (m and table):
continue
body = re.split(r"[::]", m.group(2), maxsplit=1)[-1]
vals = [v.strip() for v in body.split("/")]
if len(vals) >= 2 and all(0 < len(v) <= 10 and not re.search(r"[\s,,。()()]", v) for v in vals):
out[table][m.group(1).lower()] = vals
return out
def read_schema(ddl: str):
conn = sqlite3.connect(":memory:")
conn.executescript(ddl)
enums = comment_enums(ddl)
tables = {}
for (t,) in conn.execute("select name from sqlite_master where type='table' and name not like 'sqlite_%'"):
cols = [(c[1], (c[2] or "").upper(), bool(c[3]), bool(c[5]))
for c in conn.execute(f'pragma table_info("{t}")')]
unique = set()
for idx in conn.execute(f'pragma index_list("{t}")').fetchall():
if idx[2]: # unique
unique.update(r[2] for r in conn.execute(f'pragma index_info("{idx[1]}")'))
tables[t.lower()] = {"name": t, "cols": cols, "unique": unique, "enums": enums.get(t.lower(), {}),
"pk": next((c[0] for c in cols if c[3]), None)}
return tables
def fk_targets(tables, joins) -> dict[tuple[str, str], str]:
"""(表, 列) -> 被引用的表。先按「列名就是别的表的主键」认,重名的用标准 SQL 里的 JOIN 消歧。"""
by_pk = defaultdict(list)
for t, info in tables.items():
if info["pk"]:
by_pk[info["pk"].lower()].append(t)
out = {}
for t, info in tables.items():
for name, *_ , is_pk in info["cols"]:
c = name.lower()
if is_pk:
continue
joined = [tb for (ta, ca, tb, cb) in joins
if ta == t and ca == c and tables[tb]["pk"] and tables[tb]["pk"].lower() == cb]
cands = [x for x in by_pk.get(c, []) if x != t]
if not cands: # origin_airport_id 这种:后缀是别的表的主键;manager_employee_id 后缀是自己的主键,就是自引用
cands = [x for pk, ts in by_pk.items() if c.endswith("_" + pk) for x in ts]
pick = [x for x in cands if x in joined] or (cands if len(cands) == 1 else []) or joined
if pick:
out[(t, c)] = pick[0]
elif c == "parent_id" or re.fullmatch(r"parent_\w+_id", c): # parent_dept_id:缩写了,对不上主键名
out[(t, c)] = t
return out
def rand_date(c: str, rng: random.Random, today: dt.date, avoid: set[dt.date] = frozenset(),
with_time: bool = False) -> str:
if "birth" in c:
start, end = dt.date(1960, 1, 1), dt.date(2006, 12, 31)
elif any(k in c for k in ("expire", "due", "expected", "end")):
start, end = today - dt.timedelta(days=365), today + dt.timedelta(days=365)
elif rng.random() < 0.3:
start, end = today - dt.timedelta(days=60), today
else:
start, end = today - dt.timedelta(days=5 * 365), today
for _ in range(20): # 边界那几天不放数据,见 make_suite
d = start + dt.timedelta(days=rng.randint(0, (end - start).days))
if d not in avoid:
break
if with_time or "time" in c or c.endswith("_at"):
return f"{d} {rng.randint(0, 23):02d}:{rng.randint(0, 59):02d}:{rng.randint(0, 59):02d}"
return str(d)
def rand_num(c: str, is_int: bool, lits: set[float], rng: random.Random, today: dt.date):
if c.startswith(("is_", "has_")) or c in ("refunded", "deleted", "enabled", "active"):
return int(rng.random() < 0.5)
if "year" in c:
lo = int(min(lits)) - 10 if lits else 1950
return rng.randint(lo, today.year)
if lits and max(lits) > 0:
lo, hi = min(lits) * 0.3, max(lits) * 2.5
elif c == "age" or c.endswith("_age"):
lo, hi = 18, 70
else:
# 顺序有讲究:duration 里含 ratio,discount 里含 count,先匹配的赢
lo, hi = next((r for keys, r in (
(("month_no",), (1, 12)),
(("rating",), (1, 5)), (("gpa",), (1, 4)), (("score",), (0, 100)), (("duration", "minutes"), (30, 120)),
(("discount", "ratio", "rate"), (0, 0.3)), (("level",), (1, 3)), (("capacity",), (3, 12)),
(("safety",), (10, 80)), (("quantity", "qty", "stock", "count", "copies", "num"), (1, 150)),
(("salary",), (3000, 30000)),
(("price", "amount", "amt", "fee", "cost", "total", "balance", "budget", "revenue"), (10, 3000)),
) if any(k in c for k in keys)), (1, 100))
v = rng.uniform(lo, hi)
return int(round(v)) if is_int else round(v, 2)
def make_one(tables, fks, h, rng: random.Random, today: dt.date, avoid: set[dt.date]) -> str:
text, nums, likes, nulls, _, _ = h
has_fk = {t for (t, _c) in fks}
nrows = {t: rng.randint(30, 80) if t in has_fk else rng.randint(12, 30) for t in tables}
# 外键偏斜:每张被引用的表随机排个「热门度」,热门的 id 被引用得多
hot = {}
for t, n in nrows.items():
ids = list(range(1, n + 1))
rng.shuffle(ids)
hot[t] = (ids, [1 / (r + 1) ** 0.9 for r in range(n)])
# 作者、联系人这种会重复出现(一个作者写好几本书),DISTINCT 才有东西可去
shared = [rng.choice(SURNAMES) + rng.choice(GIVEN) + rng.choice(GIVEN) for _ in range(8)]
lines = []
for t, info in tables.items():
used = defaultdict(set)
for i in range(1, nrows[t] + 1):
vals = []
for name, decl, notnull, is_pk in info["cols"]:
c = name.lower()
if is_pk and "INT" in decl:
v = i
elif c in nulls and not notnull and rng.random() < 0.3:
v = None
elif (t, c) in fks:
ref = fks[(t, c)]
if ref == t: # 自引用(parent_id):前几行当根
v = None if i <= 3 and not notnull else rng.randint(1, max(1, i - 1))
else:
v = rng.choices(*hot[ref])[0]
elif "DATE" in decl or "TIME" in decl:
v = rand_date(c, rng, today, avoid, with_time="TIME" in decl)
elif any(k in decl for k in ("INT", "REAL", "FLOA", "DOUB", "NUM", "DEC")):
v = rand_num(c, "INT" in decl, nums.get(c, set()), rng, today)
elif any(k in c for k in ("date", "time", "birth", "since")) or c.endswith("_at"):
v = rand_date(c, rng, today, avoid)
elif c in info["enums"]:
v = rng.choice(info["enums"][c])
elif "month" in c or "period" in c: # bill_month、bill_period 存的是 '2025-03'
v = rand_date(c, rng, today, avoid)[:7]
elif "phone" in c or "mobile" in c:
v = "1" + "".join(rng.choice("0123456789") for _ in range(10))
elif "email" in c:
v = f"user{i}_{rng.randint(100, 999)}@example.com"
elif c in PERSON or c.endswith(PERSON[3:]) or c == "title" or c.endswith(("name", "sku", "code", "_no")):
# 名字类:基本不重复;标准 SQL 里 = '某某' 的原样放几行,LIKE '%瑜伽%' 的嵌进名字里
exact = sorted(text.get(c, set()) - used[c])
like = sorted(likes.get(c, set()))
if exact and rng.random() < 0.3:
v = rng.choice(exact)
elif c in ("author", "contact"):
v = rng.choice(shared)
elif c in PERSON or c.endswith(PERSON[3:]):
v = rng.choice(SURNAMES) + "".join(rng.choice(GIVEN) for _ in range(rng.randint(1, 2)))
if v in used[c]:
v += str(i)
else:
v = f"{rng.choice(WORDS)}{rng.choice(like) if like and rng.random() < 0.4 else ''}{i}"
else:
pool = next((p for keys, p in POOLS if any(k in c for k in keys)), GENERIC)
lits = sorted(text.get(c, set()))
v = rng.choice(lits) if lits and rng.random() < 0.5 else rng.choice(pool)
if name in info["unique"] and v is not None:
while v in used[c]:
v = f"{v}_{rng.randint(0, 9)}"
used[c].add(v)
vals.append(v)
cols_sql = ", ".join(f'"{c[0]}"' for c in info["cols"])
lit = ", ".join("NULL" if v is None else "'" + v.replace("'", "''") + "'" if isinstance(v, str)
else str(v) for v in vals)
lines.append(f'INSERT INTO "{info["name"]}" ({cols_sql}) VALUES ({lit});')
return "\n".join(lines) + "\n"
def make_suite(db: str, gold_sqls: list[str], k: int = 5, seed: int = 0) -> list[str]:
"""返回 k 份 INSERT 脚本。同样的库、标准 SQL、seed 和日期,生成的东西一样。"""
ddl = next((ROOT / "schemas").rglob(f"{db}.sql")).read_text(encoding="utf-8")
tables = read_schema(ddl)
h = harvest(gold_sqls, set(tables))
fks = fk_targets(tables, h[4])
# 日期按 SQLite 的 'now'(UTC)算,和标准 SQL 里的 date('now') 对齐;用电脑本地日期会差出一天
clock = sqlite3.connect(":memory:")
today = dt.date.fromisoformat(clock.execute("select date('now')").fetchone()[0])
# 「今天」和「今天往前 30 天」这种边界当天不放数据:按日期比(date(x) >= date('now','-30 days'))
# 和按时间点比(x >= datetime('now','-30 days'))只在这一天上有分歧,两种写法都说得通,不该靠运气判对错
avoid = {today} | {dt.date.fromisoformat(clock.execute("select date('now', ?)", (o,)).fetchone()[0])
for o in h[5]}
return [make_one(tables, fks, h, random.Random(f"{db}-{seed}-{i}"), today, avoid) for i in range(k)]
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--data", required=True, help="测试集 jsonl,从里面的标准 SQL 抠字面量")
ap.add_argument("--k", type=int, default=5)
ap.add_argument("--seed", type=int, default=0)
args = ap.parse_args()
items = [json.loads(l) for l in Path(args.data).read_text(encoding="utf-8").splitlines() if l.strip()]
by_db = defaultdict(list)
for it in items:
by_db[it["db"]].append(it["sql"])
for db, sqls in by_db.items():
out = ROOT / "seeds" / "suite" / db
out.mkdir(parents=True, exist_ok=True)
for i, script in enumerate(make_suite(db, sqls, args.k, args.seed)):
(out / f"{i}.sql").write_text(script, encoding="utf-8")
print(f"{db}: {args.k} 份写到 {out}")
if __name__ == "__main__":
main()