| |
| """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) |
| |
| |
| |
| |
| _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')" |
| ) |
| |
| pre = stmt[:wm.start()] |
| pre = _AS_LT_RE.sub(r"\1 TIMESTAMP(3)", pre) |
| |
| stmt = pre + new_with + stmt[wm.end():] |
| elif ctype == "print": |
| found_print = True |
| sink_id = f"sink{print_idx}" |
| print_idx += 1 |
| |
| 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" |
|
|