File size: 13,159 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import os
import sqlite3

from pyserini.search.lucene import LuceneSearcher
import json
from func_timeout import func_set_timeout, FunctionTimedOut
import time
import multiprocessing
from multiprocessing.pool import ThreadPool
import requests


# get the database cursor for a sqlite database path
def get_cursor_from_path(sqlite_path):
    try:
        if not os.path.exists(sqlite_path):
            print("Openning a new connection %s" % sqlite_path)
        connection = sqlite3.connect(sqlite_path, check_same_thread = False)
    except Exception as e:
        print(sqlite_path)
        raise e
    connection.text_factory = lambda b: b.decode(errors="ignore")
    cursor = connection.cursor()
    return cursor

# execute predicted sql with a time limitation
@func_set_timeout(30)
def execute_sql(cursor, sql):
    cursor.execute(sql)

    return cursor.fetchall()

# execute predicted sql with a long time limitation (for buiding content index)
@func_set_timeout(2000)
def execute_sql_long_time_limitation(cursor, sql):
    cursor.execute(sql)

    return cursor.fetchall()

def check_sql_executability(generated_sql, db):
    if not os.path.exists(db):
        raise Exception("Database file not found: %s" % db)
        
    connection = sqlite3.connect(db, check_same_thread = False)
    connection.text_factory = lambda b: b.decode(errors="ignore")
    cursor = connection.cursor()

    if generated_sql.strip() == "":
        return "Error: empty string"
    try:
        execute_sql(cursor, "EXPLAIN QUERY PLAN " + generated_sql)
        execution_error = None
    except FunctionTimedOut as fto:
        print("SQL execution time out error: {}.".format(fto))
        execution_error = "SQL execution times out."
    except Exception as e:
        # print("SQL execution runtime error: {}.".format(e))
        execution_error = str(e)

    cursor.close()
    connection.close()
    
    return execution_error

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

def detect_special_char(name):
    for special_char in ['(', '-', ')', ' ', '/']:
        if special_char in name:
            return True

    return False

def add_quotation_mark(s):
    return "`" + s + "`"

def get_column_contents(column_name, table_name, cursor):
    select_column_sql = "SELECT DISTINCT `{}` FROM `{}` WHERE `{}` IS NOT NULL LIMIT 2;".format(column_name, table_name, column_name)
    results = execute_sql_long_time_limitation(cursor, select_column_sql)
    column_contents = [str(result[0]).strip() for result in results]
    # remove empty and extremely-long contents
    column_contents = [content for content in column_contents if len(content) != 0 and len(content) <= 25]

    return column_contents

def get_db_schema_sequence(schema):
    """Build a CHESS-style DDL schema string with inline -- comments.

    Each column line follows the format:
        col_name  TYPE,  -- Example Values: `v1`, `v2` | Column Description: ... | Value Description: ...

    Falls back gracefully when description fields are absent.
    """
    schema_sequence = "database schema:\n"
    for table in schema["schema_items"]:
        table_name_raw = table["table_name"]
        table_name = add_quotation_mark(table_name_raw) if detect_special_char(table_name_raw) else table_name_raw

        column_defs = []
        cols = zip(
            table["column_names"],
            table["column_types"],
            table["column_comments"],
            table["column_contents"],
            table["pk_indicators"],
            table.get("column_descriptions", [""] * len(table["column_names"])),
            table.get("value_descriptions", [""] * len(table["column_names"])),
        )
        for col_name, col_type, col_comment, col_content, pk_indicator, col_desc, val_desc in cols:
            display_name = add_quotation_mark(col_name) if detect_special_char(col_name) else col_name

            type_str = col_type.upper() if col_type else "TEXT"
            suffix = "," if True else ""  # always add comma for DDL style

            comment_parts = []
            if col_content:
                examples = ", ".join(f"`{v}`" for v in col_content[:3])
                comment_parts.append(f"Example Values: {examples}")
            if col_desc:
                comment_parts.append(f"Column Description: {col_desc}")
            elif col_comment:
                comment_parts.append(f"Column Description: {col_comment}")
            if val_desc:
                comment_parts.append(f"Value Description: {val_desc}")
            if pk_indicator != 0:
                comment_parts.append("Primary Key")

            if comment_parts:
                column_defs.append(
                    f"    {display_name} {type_str},  -- {' | '.join(comment_parts)}"
                )
            else:
                column_defs.append(f"    {display_name} {type_str},")

        col_block = "\n".join(column_defs)
        schema_sequence += f"CREATE TABLE {table_name}\n(\n{col_block}\n);\n"

    if len(schema["foreign_keys"]) != 0:
        schema_sequence += "-- Foreign keys:\n"
        for foreign_key in schema["foreign_keys"]:
            fk = [add_quotation_mark(p) if detect_special_char(p) else p for p in foreign_key]
            schema_sequence += f"-- {fk[0]}.{fk[1]} = {fk[2]}.{fk[3]}\n"

    return schema_sequence.strip()

def retrieve_most_similar_column_content(question, db_id, table_name, column_name):
    # requests to retrieval api to get most similar column content
    pass


def get_db_schema_sequence_with_matched_examples(schema, question):
    schema_sequence = "database schema:\n"
    for table in schema["schema_items"]:
        table_name, table_comment = table["table_name"], table["table_comment"]
        if detect_special_char(table_name):
            table_name = add_quotation_mark(table_name)
        
        # if table_comment != "":
        #     table_name += " ( comment : " + table_comment + " )"

        column_info_list = []
        for column_name, column_type, column_comment, pk_indicator in \
            zip(table["column_names"], table["column_types"], table["column_comments"], table["pk_indicators"]):
            if detect_special_char(column_name):
                column_name = add_quotation_mark(column_name)
            additional_column_info = []
            # column type
            
            # pk indicator
            if pk_indicator != 0:
                additional_column_info.append("primary key")

            additional_column_info.append(f"type: {column_type}")
            # column comment
            if column_comment != "":
                additional_column_info.append("meaning: " + column_comment)
            # representive column values
            if len(column_content) != 0:
                additional_column_info.append("values: " + " , ".join(column_content))
            
            column_info_list.append(column_name + " | " + " ; ".join(additional_column_info))
        
        schema_sequence += "table "+ table_name + " , columns = [\n  " + "\n  ".join(column_info_list) + "\n]\n"

    if len(schema["foreign_keys"]) != 0:
        schema_sequence += "foreign keys:\n"
        for foreign_key in schema["foreign_keys"]:
            for i in range(len(foreign_key)):
                if detect_special_char(foreign_key[i]):
                    foreign_key[i] = add_quotation_mark(foreign_key[i])
            schema_sequence += "{}.{} = {}.{}\n".format(foreign_key[0], foreign_key[1], foreign_key[2], foreign_key[3])
    else:
        schema_sequence += "foreign keys: None\n"
    return schema_sequence.strip()

def get_matched_content_sequence(matched_contents):
    content_sequence = ""
    if len(matched_contents) != 0:
        content_sequence += "matched contents:\n"
        for tc_name, contents in matched_contents.items():
            table_name = tc_name.split(".")[0]
            column_name = tc_name.split(".")[1]
            if detect_special_char(table_name):
                table_name = add_quotation_mark(table_name)
            if detect_special_char(column_name):
                column_name = add_quotation_mark(column_name)
            
            content_sequence += table_name + "." + column_name + " ( " + " , ".join(contents) + " )\n"
    else:
        content_sequence = "matched contents: None"
    return content_sequence.strip()

def get_most_similar_column_contents(args):
    base_url, source, question, db_id, table_name, column_name = args
    # base_url = "http://localhost:8005"
    url = f"{base_url}/search_column_content"
    payload = {
        "source": source,
        "db_id": db_id,
        "table": table_name,
        "column": column_name,
        "query": question,
        "k": 2
    }

    response = requests.post(url, json=payload)
    if response.status_code == 200:
        return response.json()["results"]
    else:
        print("No results: ", source, db_id, table_name, column_name)
        return []

def get_db_schema(api_url, source, question, db_path, db_comments, db_id,
                  db_descriptions=None):
    """Build the schema dict for a database.

    Args:
        api_url: URL of the BM25 column-content retrieval service.
        source: Dataset identifier ('bird', 'spider', …).
        question: Natural-language question (used for BM25 retrieval).
        db_path: Path to the SQLite file.
        db_comments: Legacy tables.json comment dict {db_id: {table: …}}.
        db_id: Database identifier string.
        db_descriptions: Optional BIRD CSV descriptions loaded via
            bird_csv_utils.load_db_descriptions().  When provided, each
            schema item gets ``column_descriptions`` and
            ``value_descriptions`` lists for CHESS-style DDL rendering.
    """
    if db_id in db_comments:
        db_comment = db_comments[db_id]
    else:
        db_comment = None

    cursor = get_cursor_from_path(db_path)
    
    results = execute_sql(cursor, "SELECT name FROM sqlite_master WHERE type='table';")
    table_names = [result[0].lower() for result in results]

    schema = dict()
    schema["schema_items"] = []
    foreign_keys = []

    for table_name in table_names:
        if table_name == "sqlite_sequence":
            continue

        results = execute_sql(cursor, "SELECT name, type, pk FROM PRAGMA_TABLE_INFO('{}')".format(table_name))
        column_names_in_one_table = [result[0].lower() for result in results]
        column_types_in_one_table = [result[1].lower() for result in results]
        pk_indicators_in_one_table = [result[2] for result in results]

        with ThreadPool(processes=16) as pool:
            column_contents = pool.map(
                get_most_similar_column_contents,
                [(api_url, source, question, db_id, table_name, col) for col in column_names_in_one_table],
            )

        results = execute_sql(cursor, "SELECT * FROM pragma_foreign_key_list('{}');".format(table_name))
        for result in results:
            if None not in [result[3], result[2], result[4]]:
                foreign_keys.append([table_name.lower(), result[3].lower(), result[2].lower(), result[4].lower()])

        if db_comment is not None:
            if table_name in db_comment:
                table_comment = db_comment[table_name]["table_comment"]
                column_comments = [
                    db_comment[table_name]["column_comments"].get(col, "")
                    for col in column_names_in_one_table
                ]
            else:
                table_comment = ""
                column_comments = ["" for _ in column_names_in_one_table]
        else:
            table_comment = ""
            column_comments = ["" for _ in column_names_in_one_table]

        has_none_indicators = []
        for col in column_names_in_one_table:
            cursor.execute(f"SELECT COUNT(*) FROM `{table_name}` WHERE `{col}` IS NULL")
            count = cursor.fetchone()[0]
            has_none_indicators.append(1 if count > 0 else 0)

        # Enrich with BIRD CSV descriptions when available
        table_csv = {}
        if db_descriptions:
            table_csv = db_descriptions.get(table_name, {})

        column_descriptions = []
        value_descriptions = []
        for col in column_names_in_one_table:
            col_info = table_csv.get(col, {})
            column_descriptions.append(col_info.get("column_description", ""))
            value_descriptions.append(col_info.get("value_description", ""))

        schema["schema_items"].append({
            "table_name": table_name,
            "table_comment": table_comment,
            "column_names": column_names_in_one_table,
            "column_types": column_types_in_one_table,
            "column_comments": column_comments,
            "column_contents": column_contents,
            "pk_indicators": pk_indicators_in_one_table,
            "has_none_indicators": has_none_indicators,
            "column_descriptions": column_descriptions,
            "value_descriptions": value_descriptions,
        })

    schema["foreign_keys"] = foreign_keys
    return schema