File size: 5,260 Bytes
d847043
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
"""体检测试集:标准 SQL 能不能跑、结果是不是空的、有没有并列导致的结果不唯一、有没有重复题。

    python scripts/check_testset.py data/test_hard.jsonl

加题之后跑一遍,全部 OK 再用。查的东西:
- 报错:标准 SQL 在现生成的 5 份数据上跑不通
- 空结果:一半以上的数据上结果为空 / 全是 0 或 NULL,这种题分不出对错
- 并列:ORDER BY 碰上并列值时结果不唯一(LIMIT 截到一半、排序比顺序、ROW_NUMBER 取第一),
  写对的 SQL 也可能被判错。查法:给最外层 ORDER BY 和 ROW_NUMBER/NTILE/LAG/LEAD 的 ORDER BY
  末尾加一个 random() 再跑几遍,结果会变就是有并列;另外把扫描顺序反过来(没 ORDER BY 的 LIMIT)。
  题目里要说清楚并列怎么处理
- 重复:问题或 SQL 和别的题一样
"""

import argparse
import json
import re
import sys
from collections import Counter
from pathlib import Path

from eval import load_dbs, ordered_by, rows_of, same_result
from seed_suite import make_suite


def trivial(rows) -> bool:
    return not rows or all(all(v in (None, 0) for v in r) for r in rows)


def depths(sql: str) -> list[int]:
    """每个字符所在的括号深度,字符串字面量里的括号不算。"""
    out, depth, quoted = [], 0, False
    for ch in sql:
        if ch == "'":
            quoted = not quoted
        elif not quoted and ch == "(":
            depth += 1
        elif not quoted and ch == ")":
            depth -= 1
        out.append(depth)
    return out


def random_tiebreak(sql: str) -> str:
    """在会受并列影响的 ORDER BY 末尾加 random()。"""
    # 窗口函数:RANK/DENSE_RANK/SUM OVER 对并列本来就有定义,只动这几个
    for m in reversed(list(re.finditer(r"(?i)\b(row_number|ntile|lag|lead)\s*\([^)]*\)\s*over\s*\(", sql))):
        d = depths(sql)
        start = m.end()  # OVER ( 之后
        end = next(i for i in range(start, len(sql)) if sql[i] == ")" and d[i] == d[start - 1] - 1)
        body = sql[start:end]
        body += ", random()" if re.search(r"(?i)\border\s+by\b", body) else " ORDER BY random()"
        sql = sql[:start] + body + sql[end:]
    d = depths(sql)
    tops = [m for m in re.finditer(r"(?i)\border\s+by\b", sql) if d[m.start()] == 0]
    if tops:
        lim = [m for m in re.finditer(r"(?i)\blimit\b", sql) if d[m.start()] == 0 and m.start() > tops[-1].start()]
        cut = lim[0].start() if lim else len(sql.rstrip().rstrip(";"))
        sql = sql[:cut].rstrip() + ", random() " + sql[cut:]
    return sql


def check(items: list[dict], suite: int = 5) -> tuple[list[str], list[str]]:
    """返回 (问题, 提示)。问题:报错、空结果、并列、重复问题;提示:同一条 SQL 换个问法出现多次。"""
    suites = {db: make_suite(db, [it["sql"] for it in items if it["db"] == db], suite)
              for db in {it["db"] for it in items}}
    problems, notes = [], []
    for n, it in enumerate(items, 1):
        _, conns = load_dbs(it["db"], suites[it["db"]])
        _, flipped = load_dbs(it["db"], suites[it["db"]])
        for c in flipped:
            c.execute("PRAGMA reverse_unordered_selects = ON")
        issues = []
        try:
            res = [rows_of(c, it["sql"]) for c in conns]
            res_flipped = [rows_of(c, it["sql"]) for c in flipped]
            shaken = random_tiebreak(it["sql"])
            res_shaken = [[rows_of(c, shaken) for c in conns] for _ in range(3)]
        except Exception as exc:  # noqa: BLE001
            issues.append(f"报错:{exc}")
        else:
            empty = sum(trivial(r) for r in res)
            if empty * 2 > len(res):
                issues.append(f"空结果:{empty}/{len(res)} 份数据上为空或全 0")
            ordered = ordered_by(it["sql"])
            if not all(same_result(a, b, ordered) for a, b in zip(res, res_flipped)) or not all(
                    same_result(a, b, ordered) for run in res_shaken for a, b in zip(res, run)):
                issues.append("并列:并列值的先后一变结果就变,题目要说清楚并列怎么处理")
        if issues:
            problems.append(f"#{n} {it['question']}\n    " + "\n    ".join(issues))

    norm = Counter(re.sub(r"\s+", " ", it["sql"].strip().lower()) for it in items)
    qs = Counter(it["question"].strip() for it in items)
    # 同一条 SQL 换个问法,算测改写的鲁棒性,只提醒不算问题
    notes += [f"提示:同一条 SQL 出现多次(换了问法):{s[:100]}" for s, v in norm.items() if v > 1]
    problems += [f"重复问题:{q}" for q, v in qs.items() if v > 1]
    return problems, notes


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("data")
    ap.add_argument("--suite", type=int, default=5)
    args = ap.parse_args()

    items = [json.loads(l) for l in Path(args.data).read_text(encoding="utf-8").splitlines() if l.strip()]
    problems, notes = check(items, args.suite)
    for line in problems + notes:
        print(line)
    print(f"\n{len(items)} 题,{len(problems)} 个问题" if problems else f"\n{len(items)} 题,全部 OK")
    sys.exit(1 if problems else 0)


if __name__ == "__main__":
    main()