"""Prompt schema format (copied from the SQLant repository, scripts/build_eval_set.py).""" import sqlite3 from pathlib import Path N_EXAMPLE_ROWS = 3 MAX_VAL_CHARS = 40 def _fmt(v): s = repr(v) if isinstance(v, str) else str(v) return s if len(s) <= MAX_VAL_CHARS else s[:MAX_VAL_CHARS] + "...'" def schema_text(db_path: Path) -> str: con = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) con.text_factory = lambda b: b.decode(errors="replace") cur = con.cursor() parts = [] tables = cur.execute( "SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'" ).fetchall() for name, ddl in tables: block = ddl.strip() + ";" try: rows = cur.execute(f'SELECT * FROM "{name}" LIMIT {N_EXAMPLE_ROWS}').fetchall() cols = [d[0] for d in cur.description] if rows: lines = [" | ".join(cols)] + [" | ".join(_fmt(v) for v in r) for r in rows] block += f"\n/* {len(rows)} example rows from {name}:\n" + "\n".join(lines) + "\n*/" except sqlite3.Error: pass parts.append(block) con.close() return "\n\n".join(parts) def build_prompt(schema: str, question: str, evidence: str | None) -> str: p = f"Database schema (SQLite):\n{schema}\n\n" if evidence: p += f"External knowledge: {evidence}\n\n" p += ( f"Question: {question}\n\n" "Write one SQLite query that answers the question. " "Return only the SQL inside a ```sql code block, with no explanation." ) return p