"""E-M1b · Ejecuta un .sql en DuckDB y escribe los resultados en Markdown (implementación 1). Uso (dentro del contenedor): python3 /w/sql/run.py /w/sql/NN_x.sql /w/salidas/NN_x.md [--db /w/tmp/em1b.duckdb] - Sentencias separadas por una línea que acaba en ';'. - '-- @ título' justo antes de una sentencia le da título y la imprime; sin título no se imprime. - '-- @max N' cambia el nº máximo de filas impresas de la siguiente sentencia (por defecto 500). - Antepone /w/sql/_comun.sql (límites y vistas sobre los datos, en solo lectura). """ import os import re import sys import time import duckdb sql_path, out_path = sys.argv[1], sys.argv[2] db = sys.argv[sys.argv.index("--db") + 1] if "--db" in sys.argv else None con = duckdb.connect(db) if db else duckdb.connect() def fmt(v): if v is None: return "∅" if isinstance(v, float): if v != v: return "NaN" if abs(v) >= 1000: return f"{v:,.1f}".replace(",", "X").replace(".", ",").replace("X", ".") return f"{v:.4g}".replace(".", ",") if isinstance(v, int) and not isinstance(v, bool): return f"{v:,}".replace(",", ".") s = str(v).replace("|", "¦").replace("\n", " ⏎ ") return s if len(s) <= 160 else s[:157] + "…" def bloques(texto): titulo, maxf, buf = None, 500, [] for linea in texto.splitlines(): m = re.match(r"\s*--\s*@max\s+(\d+)", linea) if m and not buf: maxf = int(m.group(1)) continue m = re.match(r"\s*--\s*@\s*(.*)", linea) if m and not buf: titulo = m.group(1).strip() continue if not buf and (not linea.strip() or linea.strip().startswith("--")): continue buf.append(linea) if linea.rstrip().endswith(";"): yield titulo, maxf, "\n".join(buf) titulo, maxf, buf = None, 500, [] if "".join(buf).strip(): yield titulo, maxf, "\n".join(buf) comun = open("/w/sql/_comun.sql").read() texto = comun + "\n" + open(sql_path).read() salida = [f"# Resultado de `{os.path.basename(sql_path)}`\n\n", f"DuckDB {duckdb.__version__} · {time.strftime('%Y-%m-%d %H:%M:%S %Z')}\n"] t_total = time.time() errores = 0 for titulo, maxf, sent in bloques(texto): t0 = time.time() try: rel = con.execute(sent) filas = rel.fetchall() if rel.description else None except Exception as e: # noqa: BLE001 errores += 1 salida.append(f"\n## {titulo or sent[:80]}\n\n**ERROR**: {e}\n") print("ERROR", titulo, e, file=sys.stderr) continue dt = time.time() - t0 if titulo is None or filas is None: print(f"[{dt:.1f} s] {sent[:70]!r}", file=sys.stderr) continue cols = [d[0] for d in rel.description] salida.append(f"\n## {titulo}\n\n_{len(filas)} filas · {dt:.1f} s_\n\n") salida.append("| " + " | ".join(cols) + " |\n") salida.append("|" + "|".join("---" for _ in cols) + "|\n") for f in filas[:maxf]: salida.append("| " + " | ".join(fmt(v) for v in f) + " |\n") if len(filas) > maxf: salida.append(f"\n… {len(filas) - maxf} filas más\n") print(f"{titulo}: {len(filas)} filas, {dt:.1f} s", file=sys.stderr) salida.append(f"\n_Tiempo total: {time.time() - t_total:.0f} s · errores: {errores}_\n") open(out_path, "w").write("".join(salida)) sys.exit(1 if errores else 0)