# 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"