Datasets:
File size: 3,611 Bytes
e8c001c | 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 | # tasks/online-compute/FlinkSQL/flinksql_007/gt/rewrite_sql.py
"""SQL rewriter for flinksql_007 grading.
Swaps datagen connector -> filesystem (read seed CSV) and print connector -> filesystem
(write output CSV). Preserves computed columns, WATERMARK, SELECT/JOIN/INSERT.
Implementation: targeted regex on WITH(...) blocks.
"""
import re
SEED_TABLE_MAP = {
"user_source": "users.csv",
}
_WITH_RE = re.compile(r"WITH\s*\(([^)]*)\)", re.IGNORECASE | re.DOTALL)
_CREATE_RE = re.compile(r"CREATE\s+TABLE\s+(\w+)", re.IGNORECASE)
_CONN_RE = re.compile(r"'connector'\s*=\s*'(\w+)'", re.IGNORECASE)
# 方案 B:把 datagen 源表的计算列 `X AS LOCALTIMESTAMP` 改写为普通 `X TIMESTAMP(3)`
# 列(读 seed CSV 的时间戳列)。agent 若已用普通 TIMESTAMP(3) 则保持不变。
# 两方向都归一到 TIMESTAMP(3),使 GT 与 agent 的 CSV schema 一致。
# 仅作用于 WITH 块之前的列定义区,不影响 WATERMARK / INSERT / SELECT。
_AS_LT_RE = re.compile(r"(\w+)\s+AS\s+LOCALTIMESTAMP", re.IGNORECASE)
_PLAIN_TS_RE = re.compile(r"(\w+)\s+TIMESTAMP(?:\(\d+\))?", re.IGNORECASE)
def rewrite_sql(sql_text, seed_dir, out_dir, out_prefix):
"""Rewrite SQL: datagen -> filesystem seed, print -> filesystem output.
Args:
sql_text: original SQL string
seed_dir: directory containing seed CSV files
out_dir: directory for output CSV (print sink replacement)
out_prefix: "pred" or "gt" — output goes to {out_dir}/{out_prefix}/
Returns:
(rewritten_sql, ok, diagnostic)
"""
out_path = f"{out_dir}/{out_prefix}"
found_datagen = False
found_print = False
print_idx = 0
rewritten = []
for stmt in sql_text.split(";"):
cm = _CREATE_RE.search(stmt)
wm = _WITH_RE.search(stmt)
if cm and wm:
tname = cm.group(1)
conn_m = _CONN_RE.search(wm.group(1))
if conn_m:
ctype = conn_m.group(1).lower()
if ctype == "datagen":
found_datagen = True
seed_file = SEED_TABLE_MAP.get(tname.lower())
if not seed_file:
return "", False, f"no seed mapping for table '{tname}'"
new_with = (
f"WITH ('connector' = 'filesystem', "
f"'path' = '{seed_dir}/{seed_file}', "
f"'format' = 'csv', "
f"'csv.ignore-parse-errors' = 'true')"
)
# 方案 B:AS LOCALTIMESTAMP -> TIMESTAMP(3);普通 TIMESTAMP(3) 保持
pre = stmt[:wm.start()]
pre = _AS_LT_RE.sub(r"\1 TIMESTAMP(3)", pre)
# 普通 TIMESTAMP(3) 列无需改动(已是目标形态)
stmt = pre + new_with + stmt[wm.end():]
elif ctype == "print":
found_print = True
sink_id = f"sink{print_idx}"
print_idx += 1
# 保留 print connector, 加 print-identifier (changelog 归约用)
existing = wm.group(1).rstrip()
if existing.endswith(','):
existing = existing[:-1]
new_with = f"WITH ({existing}, 'print-identifier' = '{sink_id}')"
stmt = stmt[:wm.start()] + new_with + stmt[wm.end():]
rewritten.append(stmt)
if not found_datagen and not found_print:
return "", False, "no datagen/print connector found"
return ";".join(rewritten), True, "ok"
|