"""Utilidades de E-M7 (dentro del contenedor): base /w/tmp/em7.duckdb, macros del commit 5bdca61, informe Markdown.""" import sys, time import duckdb def abrir(db="/w/tmp/em7.duckdb", macros=True): con = duckdb.connect(db) con.execute("SET memory_limit='6GB'; SET threads=4; SET temp_directory='/w/tmp/duckdb_tmp'; SET preserve_insertion_order=false") if macros: from etl.v2 import borme from etl.v2.identidad import MACROS_IDENTIDAD con.execute(MACROS_IDENTIDAD) con.execute(borme.MACROS_BORME) return con def fmt(v): if v is None: return "∅" if isinstance(v, bool): return str(v) 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): return f"{v:,}".replace(",", ".") s = str(v).replace("|", "¦").replace("\n", " ⏎ ") return s if len(s) <= 160 else s[:157] + "…" class Informe: def __init__(self, con, titulo): self.con = con self.md = [f"# {titulo}\n", f"DuckDB {duckdb.__version__} · {time.strftime('%Y-%m-%d %H:%M:%S')}\n"] self.t0 = time.time() def x(self, sql): t = time.time(); r = self.con.execute(sql) print(f" x {time.time() - t:.1f}s {sql.strip()[:70]!r}", file=sys.stderr, flush=True); return r def q(self, titulo, sql, maxf=400): t = time.time(); rel = self.con.execute(sql); filas = rel.fetchall(); cols = [d[0] for d in rel.description] self.md.append(f"\n## {titulo}\n\n_{len(filas)} filas · {time.time() - t:.1f} s_\n\n| " + " | ".join(cols) + " |\n|" + "|".join("---" for _ in cols) + "|\n") for f in filas[:maxf]: self.md.append("| " + " | ".join(fmt(v) for v in f) + " |\n") if len(filas) > maxf: self.md.append(f"\n… {len(filas) - maxf} filas más\n") print(f"{titulo}: {len(filas)} filas, {time.time() - t:.1f} s", file=sys.stderr, flush=True); return filas def texto(self, s): self.md.append("\n" + s + "\n") def guardar(self, ruta): self.md.append(f"\n_Tiempo total: {time.time() - self.t0:.0f} s_\n"); open(ruta, "w").write("".join(self.md))