File size: 8,645 Bytes
778d47d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
"""Build CANONICAL planner dev prompts.

After empirical comparison (BM25 hurt by ~2pp), the canonical format is:
  - Static representative values (first 1-2 DISTINCT non-NULL DB values per column)
  - meaning (column_description from BIRD CSV) when available
  - value description (value_description from BIRD CSV) when available
  - has None (when column has NULL values)
  - primary key, type
  - PRUNED schema (only tables/columns selected by the schema-classifier filter)

This produces the prompt format that gave the highest greedy EX (52.80%
on Qwen-Coder-3B combined-3ep, +0.65pp over paper's checkpoint at 52.15%).
"""
import json, os, re, sqlite3, argparse, sys

sys.path.insert(0, '/home/datht/mats-sql-tist')
from utils.bird_csv_utils import load_all_db_descriptions


def detect_special_char(s): return bool(re.search(r'[^a-zA-Z0-9_]', s))
def add_quotation_mark(s): return f"`{s}`"


def sample_static_values(cur, table, col, n=2):
    """Return up to n DISTINCT non-NULL values from the column (paper-style static)."""
    try:
        qcol = f'`{col}`'
        qtab = f'`{table}`'
        cur.execute(f"SELECT DISTINCT {qcol} FROM {qtab} WHERE {qcol} IS NOT NULL LIMIT {n}")
        vals = [str(r[0]).strip() for r in cur.fetchall()]
        return [v for v in vals if v and len(v) <= 50][:n]
    except Exception:
        return []


def build_schema_seq(db_path, db_id, db_descriptions, table_filter=None, col_filter_per_table=None):
    """Build schema sequence with static values + meaning + VD + has None.

    Args:
        table_filter: set of table names to keep (case-insensitive). None = keep all.
        col_filter_per_table: dict {tname_lower: set(col_names_lower)} — keep only these cols.
    """
    conn = sqlite3.connect(db_path)
    conn.text_factory = lambda b: b.decode(errors='ignore')
    cur = conn.cursor()
    cur.execute("SELECT name FROM sqlite_master WHERE type='table';")
    table_names = [r[0] for r in cur.fetchall() if r[0].lower() != 'sqlite_sequence']
    descs = db_descriptions.get(db_id, {}) if db_descriptions else {}

    schema_seq = "database schema:\n"
    foreign_keys = []
    kept_tables = set()
    for tn in table_names:
        if table_filter is not None and tn.lower() not in table_filter:
            continue
        cur.execute(f"SELECT name, type, pk FROM PRAGMA_TABLE_INFO('{tn}')")
        rows = cur.fetchall()
        cn_list = [r[0] for r in rows]
        ct_list = [r[1].lower() for r in rows]
        pk_list = [r[2] for r in rows]
        # apply col filter
        if col_filter_per_table is not None:
            keep_cols_lc = col_filter_per_table.get(tn.lower(), set())
            keep_idx = [i for i, c in enumerate(cn_list) if c.lower() in keep_cols_lc]
            if not keep_idx:
                continue
            cn_list = [cn_list[i] for i in keep_idx]
            ct_list = [ct_list[i] for i in keep_idx]
            pk_list = [pk_list[i] for i in keep_idx]
        kept_tables.add(tn.lower())
        # FKs
        cur.execute(f"SELECT * FROM pragma_foreign_key_list('{tn}')")
        for r in cur.fetchall():
            if None not in [r[3], r[2], r[4]]:
                foreign_keys.append([tn.lower(), r[3].lower(), r[2].lower(), r[4].lower()])
        # find table description
        tdesc = None
        for k, v in descs.items():
            if k.lower() == tn.lower():
                tdesc = v
                break
        col_lines = []
        qtab = add_quotation_mark(tn) if detect_special_char(tn) else tn
        for cn, ct, pk in zip(cn_list, ct_list, pk_list):
            qcn = add_quotation_mark(cn) if detect_special_char(cn) else cn
            try:
                cur.execute(f"SELECT COUNT(*) FROM `{tn}` WHERE `{cn}` IS NULL")
                has_none = cur.fetchone()[0] > 0
            except Exception:
                has_none = False
            meaning = ""
            vd = ""
            if tdesc:
                for col_key, col_info in tdesc.items():
                    if col_key.lower() == cn.lower():
                        meaning = (col_info.get('column_description') or "").strip()
                        vd = (col_info.get('value_description') or "").strip()
                        break
            vals = sample_static_values(cur, tn, cn, n=2)
            parts = []
            if pk: parts.append("primary key")
            parts.append(f"type: {ct}")
            if meaning:
                parts.append("meaning: " + " ".join(meaning.split()))
            if vd:
                parts.append("value description: " + " ".join(vd.split()))
            if has_none: parts.append("has None")
            if vals:
                parts.append("values: " + " , ".join(str(v) for v in vals if v))
            col_lines.append(f"  {qtab}.{qcn} | " + " ; ".join(parts))
        schema_seq += "table " + qtab + " , columns = [\n" + "\n".join(col_lines) + "\n]\n"
    if foreign_keys:
        # Filter FKs to only kept tables
        filt_fks = [fk for fk in foreign_keys if fk[0] in kept_tables and fk[2] in kept_tables]
        if filt_fks:
            schema_seq += "foreign keys:\n"
            for fk in filt_fks:
                for i in range(len(fk)):
                    if detect_special_char(fk[i]): fk[i] = add_quotation_mark(fk[i])
                schema_seq += f"{fk[0]}.{fk[1]} = {fk[2]}.{fk[3]}\n"
        else:
            schema_seq += "foreign keys: None\n"
    else:
        schema_seq += "foreign keys: None\n"
    conn.close()
    return schema_seq.strip()


def main():
    p = argparse.ArgumentParser()
    p.add_argument('--data', required=True)
    p.add_argument('--bird_dir', required=True)
    p.add_argument('--out', required=True)
    p.add_argument('--pruned_sel', default=None,
                   help='optional: bird_dev_pruned_table_cols.json — schema-classifier pruning')
    args = p.parse_args()

    data = json.load(open(args.data))
    print(f"Loaded {len(data)} samples")
    db_descriptions = load_all_db_descriptions(args.bird_dir)
    print(f"Loaded descriptions for {len(db_descriptions)} DBs")

    bird_dev_path = '/home/datht/mats-sql-tist/data/bird/dev/dev.json'
    bird_dev = json.load(open(bird_dev_path)) if os.path.exists(bird_dev_path) else []
    diff_map = {(s['db_id'], s['question']): s.get('difficulty', 'unknown') for s in bird_dev}

    # Optional pruning selections — keyed by (db_id, question)
    pruned_map = {}
    if args.pruned_sel and os.path.exists(args.pruned_sel):
        psel = json.load(open(args.pruned_sel))
        for p_item in psel:
            tables = {tn.lower(): set(c.lower() for c in cols) for tn, cols in p_item['tables'].items()}
            table_set = set(tables.keys())
            pruned_map[(p_item['db_id'], p_item['question'])] = (table_set, tables)
        print(f"Loaded pruning selections for {len(pruned_map)} (db,question) pairs")

    out = []
    from tqdm import tqdm
    for i, s in enumerate(tqdm(data)):
        q = s.get('question', s.get('text', ''))
        db_id = s['db_id']
        db_path = '/home/datht/mats-sql-tist/' + s['db_path'].lstrip('./') if not s['db_path'].startswith('/') else s['db_path']
        # Apply pruning if available
        table_filter = None
        col_filter = None
        sel = pruned_map.get((db_id, q))
        if sel:
            table_filter, col_filter = sel
        schema_seq = build_schema_seq(db_path, db_id, db_descriptions,
                                       table_filter=table_filter,
                                       col_filter_per_table=col_filter)
        prompt = f"{schema_seq}\n\nQuestion: {q}\nExternal knowledge: {s.get('evidence','')}"
        out.append({
            'idx': i, 'db_id': db_id, 'db_path': db_path,
            'question': q, 'evidence': s.get('evidence',''),
            'gold_sql': s['sql'],
            'difficulty': diff_map.get((db_id, q), 'unknown'),
            'prompt_text': prompt,
        })
        if i > 0 and i % 200 == 0:
            json.dump(out, open(args.out, 'w'))

    json.dump(out, open(args.out, 'w'))
    import statistics
    lens = [len(p['prompt_text']) for p in out]
    print(f"\nWrote {len(out)}{args.out}")
    print(f"median len: {int(statistics.median(lens))}")
    n_meaning = sum(1 for p in out if 'meaning:' in p['prompt_text'])
    n_vd = sum(1 for p in out if 'value description:' in p['prompt_text'])
    n_vals = sum(1 for p in out if 'values:' in p['prompt_text'])
    print(f"with meaning: {n_meaning}/{len(out)}")
    print(f"with value description: {n_vd}/{len(out)}")
    print(f"with values: {n_vals}/{len(out)}")


if __name__ == '__main__':
    main()