Text Generation
PEFT
Safetensors
MLX
English
text-to-sql
sql
sqlite
lora
bird
spider
Eval Results (legacy)
sqlant-1b / code /sqlant /schema_tools.py
Nafize's picture
SQLant-1B: PEFT + MLX adapters (generator, verifier3), pipeline code, model card
d2bec35 verified
Raw History Blame Contribute Delete
20.1 kB
"""Copied unchanged from the SQLant repository (scripts/schema_tools.py) except for paths."""
"""Inference-time helpers for SQLant: schema pruning, value retrieval, alias repair.
- db_meta(db) tables -> columns, foreign keys (cached)
- value_index(db) lowercase text value -> [(table, column, original)] (cached on disk)
- match_values(q, ev, db) database values literally mentioned in the question / evidence
- link_tables(...) tables to keep: lexical match on names + value matches + draft SQL tables
+ FK bridges; falls back to the full schema when unsure
- schema_text_subset(...) same format as build_eval_set.schema_text, restricted to some tables
- values_block(matches) prompt block listing matched values
- alias_repair(sql, db) re-point `T1.col` to the one joined table that actually has `col`
"""
import json
import os
import pickle
import re
import sqlite3
import sys
from functools import lru_cache
from pathlib import Path
import sqlglot
from sqlglot import exp
ROOT = Path.cwd() # database paths may be absolute (ROOT / absolute == absolute) or relative to the working dir
from .schema_format import N_EXAMPLE_ROWS, _fmt # noqa: E402
VALUE_DIR = Path(os.environ.get("SQLANT_CACHE", ".sqlant_cache")) / "value_index"
MAX_VALUE_LEN = 60
MAX_DISTINCT_PER_COL = 20_000
STOP = set("""a an the of in on at to for from by with and or not is are was were be been what which who whom whose
how many much list give show find name names number count all each per than that this these those their there
does do did have has had please average total among between more most less least only any its it as into
""".split())
def _con(db):
con = sqlite3.connect(f"file:{ROOT / db}?mode=ro", uri=True)
con.text_factory = lambda b: b.decode(errors="replace")
return con
@lru_cache(maxsize=256)
def db_meta(db: str) -> dict:
con = _con(db)
tables = {}
fks = []
for (name,) in con.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"):
cols = [(r[1], (r[2] or "").upper()) for r in con.execute(f'PRAGMA table_info("{name}")')]
tables[name] = cols
for r in con.execute(f'PRAGMA foreign_key_list("{name}")'):
fks.append((name, r[2])) # (from_table, to_table)
# FK column pairs (from_table, from_col, to_table, to_col); to_col None -> primary key of to_table
pks = {}
for name in tables:
pk = [r[1] for r in con.execute(f'PRAGMA table_info("{name}")') if r[5]]
pks[name] = pk[0] if len(pk) == 1 else None
lower = {t.lower(): t for t in tables}
fkcols = []
for name in tables:
for r in con.execute(f'PRAGMA foreign_key_list("{name}")'):
to_t = lower.get((r[2] or "").lower())
if to_t:
fkcols.append((name, r[3], to_t, r[4] or pks.get(to_t)))
con.close()
return {"tables": tables, "fks": fks, "fkcols": [f for f in fkcols if f[3]], "pks": pks}
def join_keys(db: str, a: str, b: str):
"""(col_in_a, col_in_b) to join tables a and b: declared FK first, then `<b>_id`-style naming."""
meta = db_meta(db)
for ft, fc, tt, tc in meta["fkcols"]:
if ft.lower() == a.lower() and tt.lower() == b.lower():
return fc, tc
if ft.lower() == b.lower() and tt.lower() == a.lower():
return tc, fc
cols = {t.lower(): {c.lower(): c for c, _ in cs} for t, cs in meta["tables"].items()}
ca, cb = cols.get(a.lower(), {}), cols.get(b.lower(), {})
pkb, pka = meta["pks"].get(b), meta["pks"].get(a)
for name in (f"{b.lower()}_id", f"{b.lower()}id"):
if name in ca and pkb:
return ca[name], pkb
for name in (f"{a.lower()}_id", f"{a.lower()}id"):
if name in cb and pka:
return pka, cb[name]
return None
def _words(s: str) -> list:
return re.findall(r"[a-z0-9]+", (s or "").lower())
def _name_tokens(name: str) -> set:
s = re.sub(r"([a-z])([A-Z])", r"\1 \2", name)
return {w for w in _words(s) if w not in STOP and len(w) > 1}
def _stem(w):
for suf in ("ies", "es", "s"):
if w.endswith(suf) and len(w) - len(suf) >= 3:
return w[: -len(suf)] + ("y" if suf == "ies" else "")
return w
# ------------------------------------------------------------------ values
def value_index(db: str) -> dict:
VALUE_DIR.mkdir(parents=True, exist_ok=True)
f = VALUE_DIR / (re.sub(r"[^A-Za-z0-9_]+", "_", db) + ".pkl")
if f.exists():
return pickle.loads(f.read_bytes())
idx: dict = {}
con = _con(db)
for t, cols in db_meta(db)["tables"].items():
for c, typ in cols:
if typ and not any(k in typ for k in ("CHAR", "TEXT", "CLOB", "VARCHAR")) and typ != "":
continue
try:
rows = con.execute(
f'SELECT DISTINCT "{c}" FROM "{t}" WHERE typeof("{c}")=\'text\' '
f'AND length("{c}") BETWEEN 2 AND {MAX_VALUE_LEN} LIMIT {MAX_DISTINCT_PER_COL}').fetchall()
except sqlite3.Error:
continue
for (v,) in rows:
k = v.strip().lower()
if k and not k.isdigit():
idx.setdefault(k, []).append((t, c, v))
con.close()
tmp = f.with_suffix(f".{os.getpid()}.tmp") # atomic: parallel workers may build the same DB
tmp.write_bytes(pickle.dumps(idx))
os.replace(tmp, f)
return idx
def match_values(question: str, evidence: str, db: str, max_hits: int = 12) -> list:
"""Values whose full text appears in the question/evidence (n-grams up to 6 words, case-insensitive)."""
idx = value_index(db)
text = f"{question} {evidence or ''}"
cands = {m.strip().lower() for m in re.findall(r"'([^']{2,60})'|\"([^\"]{2,60})\"", text) for m in m if m}
toks = re.findall(r"[A-Za-z0-9][A-Za-z0-9&.'\-]*", text)
for n in range(6, 0, -1):
for i in range(len(toks) - n + 1):
g = " ".join(toks[i:i + n]).strip(".").lower()
if n == 1 and (g in STOP or len(g) < 3 or g.isdigit()):
continue
cands.add(g)
hits, seen = [], set()
for g in sorted(cands, key=len, reverse=True):
for t, c, v in idx.get(g, [])[:4]:
if (t, c, v) not in seen:
seen.add((t, c, v))
hits.append((t, c, v))
# prefer longer (more specific) values; cap
hits.sort(key=lambda h: -len(h[2]))
return hits[:max_hits]
def strict_values(hits: list, question: str, evidence: str, db: str, per_value: int = 2) -> list:
"""Filter match_values hits down to the ones that are likely meant as values (fewer misleading lines).
1. fragments: drop a value that is a word-span inside another matched value ('Sussex' < 'West Sussex')
2. schema words: drop single-word values that are also a table/column name word ('platform' table vs
genre 'Platform') -- in the question the word names the schema element, not a stored value
3. case variants: per column keep one spelling (the one written in the question, else the first)
4. same value in many columns: prefer columns whose table/column words appear in the question; at most
`per_value` columns per value
"""
text = f"{question} {evidence or ''}"
low = {h[2].strip().lower() for h in hits}
meta = db_meta(db)
schema_words = {_stem(w) for t, cols in meta["tables"].items()
for name in [t] + [c for c, _ in cols] for w in _name_tokens(name)}
q_words = {_stem(w) for w in _words(text) if w not in STOP and len(w) > 1}
def fragment(v):
v = v.lower()
return any(v != o and re.search(rf"(^|\W){re.escape(v)}($|\W)", o) for o in low)
kept = [h for h in hits if not fragment(h[2])
and not (len(_words(h[2])) == 1 and _stem(h[2].strip().lower()) in schema_words)]
by_col = {}
for t, c, v in kept: # 3. one spelling per column
k = (t, c, v.lower())
if k not in by_col or (v in text and by_col[k] not in text):
by_col[k] = v
by_val = {}
for (t, c, vl), v in by_col.items():
by_val.setdefault(vl, []).append((t, c, v))
out = []
for vl, cands in by_val.items(): # 4. rank columns by overlap with the question
def rel(h):
return len(q_words & {_stem(w) for w in _name_tokens(h[0]) | _name_tokens(h[1])})
cands.sort(key=rel, reverse=True)
best = rel(cands[0])
out.extend([h for h in cands if rel(h) == best][:per_value] if best else cands[:per_value])
out.sort(key=lambda h: -len(h[2]))
return out
def values_block(hits: list) -> str:
if not hits:
return ""
lines = [f"{t}.{c} = {v!r}" for t, c, v in hits]
return "\n\n/* Values in the database that match words in the question:\n" + "\n".join(lines) + "\n*/"
# ------------------------------------------------------------------ pruning
def sql_tables(sql: str, db: str) -> set:
names = {t.lower(): t for t in db_meta(db)["tables"]}
try:
tree = sqlglot.parse_one(sql, read="sqlite")
return {names[t.name.lower()] for t in tree.find_all(exp.Table) if t.name.lower() in names}
except Exception: # noqa: BLE001
return {names[w] for w in _words(sql) if w in names}
def link_tables(question: str, evidence: str, db: str, value_hits=(), draft_sql: str | None = None,
min_tables_to_prune: int = 5) -> list:
meta = db_meta(db)
tables = list(meta["tables"])
if len(tables) < min_tables_to_prune:
return tables
q = {_stem(w) for w in _words(f"{question} {evidence or ''}") if w not in STOP and len(w) > 1}
keep = set()
for t, cols in meta["tables"].items():
if {_stem(w) for w in _name_tokens(t)} & q:
keep.add(t)
for c, _ in cols:
ct = {_stem(w) for w in _name_tokens(c)}
if ct and (ct <= q or (len(ct) >= 2 and len(ct & q) >= 2)):
keep.add(t)
keep |= {t for t, _, _ in value_hits}
if draft_sql:
keep |= sql_tables(draft_sql, db)
if not keep:
return tables
# FK bridges: add any table that links two kept tables
for a in tables:
if a in keep:
continue
nbrs = {y for x, y in meta["fks"] if x == a} | {x for x, y in meta["fks"] if y == a}
if len(nbrs & keep) >= 2:
keep.add(a)
return [t for t in tables if t in keep]
def schema_text_subset(db: str, keep: list) -> str:
con = _con(db)
parts = []
ddls = dict(con.execute("SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"))
for name in keep:
block = ddls[name].strip() + ";"
try:
cur = con.execute(f'SELECT * FROM "{name}" LIMIT {N_EXAMPLE_ROWS}')
rows = cur.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 relations_block(db: str, keep: list) -> str:
"""Declared foreign keys between the shown tables, one join condition per line (empty if none)."""
meta = db_meta(db)
shown = {t.lower() for t in keep}
lines = []
for ft, fc, tt, tc in meta["fkcols"]:
if ft.lower() in shown and tt.lower() in shown and ft.lower() != tt.lower():
ln = f"{ft}.{fc} = {tt}.{tc}"
if ln not in lines:
lines.append(ln)
return ("\n\nTable relationships (join keys):\n" + "\n".join(lines)) if lines else ""
# ------------------------------------------------------------------ alias repair
def alias_repair(sql: str, db: str) -> str | None:
"""If a qualified column isn't on its table but exists on exactly one other table in the query,
re-qualify it. Returns the repaired SQL, or None if nothing changed / not parseable."""
meta = db_meta(db)
cols_of = {t.lower(): {c.lower() for c, _ in cs} for t, cs in meta["tables"].items()}
try:
tree = sqlglot.parse_one(sql, read="sqlite")
except Exception: # noqa: BLE001
return None
changed = False
for select in tree.find_all(exp.Select):
alias_to_table = {}
for t in select.find_all(exp.Table):
if t.find_ancestor(exp.Select) is not select:
continue
alias_to_table[(t.alias or t.name).lower()] = t.name.lower()
for col in select.find_all(exp.Column):
if col.find_ancestor(exp.Select) is not select or not col.table:
continue
q, name = col.table.lower(), col.name.lower()
t = alias_to_table.get(q)
if t is None or t not in cols_of or name in cols_of[t]:
continue
owners = [a for a, tt in alias_to_table.items() if tt in cols_of and name in cols_of[tt]]
if len(owners) == 1:
col.set("table", exp.to_identifier(owners[0]))
changed = True
continue
if owners:
continue
# join completion: the column lives in a table one FK hop from this alias's table
tables_l = {tt.lower(): tt for tt in meta["tables"]}
cands = []
for other, ocols in cols_of.items():
if name in ocols and other not in alias_to_table.values():
keys = join_keys(db, tables_l[t], tables_l[other])
if keys:
cands.append((other, keys))
if len(cands) != 1:
continue
other, (ka, kb) = cands[0]
new_alias = f"J{len(alias_to_table) + 1}"
on = exp.EQ(this=exp.column(ka, table=col.table), expression=exp.column(kb, table=new_alias))
select.set("joins", (select.args.get("joins") or []) + [exp.Join(
this=exp.Table(this=exp.to_identifier(tables_l[other]), alias=exp.TableAlias(
this=exp.to_identifier(new_alias))), on=on, kind="INNER")])
alias_to_table[new_alias.lower()] = other
col.set("table", exp.to_identifier(new_alias))
changed = True
return tree.sql(dialect="sqlite") if changed else None
def repair_sql(sql: str, db: str, max_rounds: int = 3) -> str | None:
"""Apply alias repair / join completion repeatedly (multi-hop joins). None if nothing changed."""
cur, changed = sql, False
for _ in range(max_rounds):
new = alias_repair(cur, db)
if not new or new == cur:
break
cur, changed = new, True
return cur if changed else None
# ------------------------------------------------------------------ value snapping
def _norm_val(s: str) -> str:
return re.sub(r"\s+", " ", re.sub(r"[^\w\s]", "", s.lower())).strip()
def _most_common(con, q, vals):
"""Unique value, or the most frequent spelling when the candidates differ only in letter case."""
if not vals or len({v.lower() for v in vals}) != 1:
return None
if len(vals) == 1:
return vals[0]
return max(vals, key=lambda v: con.execute(f"SELECT COUNT(*) FROM {q[0]} WHERE {q[1]} = ?", (v,)).fetchone()[0])
def _snap_one(con, t, c, lit, is_str):
"""-> replacement value for `t.c = lit` when lit does not occur in the column, else None (unique match only)."""
q = f'"{t}"', f'"{c}"'
try:
if con.execute(f"SELECT 1 FROM {q[0]} WHERE {q[1]} = ? LIMIT 1", (lit,)).fetchone():
return None
if not is_str: # number literal: a text column like 'YR2002' that ends with it
rows = con.execute(f"SELECT DISTINCT {q[1]} FROM {q[0]} WHERE typeof({q[1]})='text' "
f"AND {q[1]} LIKE ? LIMIT 3", (f"%{lit}",)).fetchall()
vals = [v for (v,) in rows if re.fullmatch(rf"[A-Za-z]{{0,4}}[\s\-_]?{re.escape(str(lit))}", v)]
return _most_common(con, q, vals)
rows = con.execute(f"SELECT DISTINCT {q[1]} FROM {q[0]} WHERE lower({q[1]}) = lower(?) LIMIT 5",
(lit,)).fetchall()
if rows:
return _most_common(con, q, [v for (v,) in rows])
n = _norm_val(lit)
if not n:
return None
rows = con.execute(f"SELECT DISTINCT {q[1]} FROM {q[0]} WHERE typeof({q[1]})='text' "
f"LIMIT {MAX_DISTINCT_PER_COL}").fetchall()
vals = [v for (v,) in rows if _norm_val(v) == n]
return vals[0] if len(vals) == 1 else None
except (sqlite3.Error, OverflowError, ValueError): # e.g. an integer literal too large for SQLite
return None
def snap_values(sql: str, db: str) -> str | None:
"""Replace literals that do not occur in their column with the unique near-identical stored value
(case, punctuation/spacing, 'YR'-style prefixes), and `col IS NULL` with `col = ''` when the column
has no NULLs but has empty strings. Returns the new SQL, or None if nothing changed."""
meta = db_meta(db)
cols_of = {t.lower(): (t, {c.lower(): c for c, _ in cs}) for t, cs in meta["tables"].items()}
try:
tree = sqlglot.parse_one(sql, read="sqlite")
except Exception: # noqa: BLE001
return None
con = _con(db)
changed = False
def owner(col, select):
amap = {}
for t in select.find_all(exp.Table):
if t.find_ancestor(exp.Select) is select and t.name.lower() in cols_of:
amap[(t.alias or t.name).lower()] = t.name.lower()
name = col.name.lower()
if col.table:
t = amap.get(col.table.lower())
return (cols_of[t][0], cols_of[t][1][name]) if t and name in cols_of[t][1] else None
hits = [t for t in set(amap.values()) if name in cols_of[t][1]]
return (cols_of[hits[0]][0], cols_of[hits[0]][1][name]) if len(hits) == 1 else None
try:
for node in list(tree.find_all(exp.EQ, exp.In, exp.Is)):
select = node.find_ancestor(exp.Select)
if select is None:
continue
if isinstance(node, exp.Is):
col = node.this
if not (isinstance(col, exp.Column) and isinstance(node.expression, exp.Null)) \
or isinstance(node.parent, exp.Not):
continue
o = owner(col, select)
if not o:
continue
t, c = o
r = con.execute(f'SELECT SUM("{c}" IS NULL), SUM("{c}" = \'\') FROM "{t}"').fetchone()
if r and not r[0] and r[1]:
node.replace(exp.EQ(this=col.copy(), expression=exp.Literal.string("")))
changed = True
continue
if isinstance(node, exp.EQ):
pairs = [(node.this, node.expression)] if isinstance(node.this, exp.Column) else \
[(node.expression, node.this)] if isinstance(node.expression, exp.Column) else []
lits = [(col, l) for col, l in pairs if isinstance(l, exp.Literal)]
else:
lits = [(node.this, l) for l in node.expressions if isinstance(node.this, exp.Column)
and isinstance(l, exp.Literal)]
for col, lit in lits:
o = owner(col, select)
if not o:
continue
val = lit.this if lit.is_string else (int(lit.this) if lit.this.lstrip("-").isdigit() else None)
if val is None or (lit.is_string and len(val) < 2):
continue
new = _snap_one(con, o[0], o[1], val, lit.is_string)
if new is not None and new != val:
lit.replace(exp.Literal.string(new))
changed = True
finally:
con.close()
return tree.sql(dialect="sqlite") if changed else None