File size: 1,222 Bytes
345a446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from llm import generate_sql
from database import fetch_query, execute_query, get_schema_info, get_db_path
import pandas as pd

ALLOWED = ("SELECT", "INSERT", "UPDATE", "DELETE")


def ask_ai(question: str):
    """
    Takes English question, returns (answer, sql, dataframe_or_none)
    """
    # Build schema from currently active DB
    schema = get_schema_info(get_db_path())
    sql = generate_sql(question, schema_info=schema)

    sql_upper = sql.upper().strip()

    # Block unsafe or invalid queries
    if sql_upper == "INVALID_QUERY":
        return ("❌ This question cannot be answered with the current database.", sql, None)

    if not sql_upper.startswith(ALLOWED):
        return ("❌ Unsafe or unsupported query blocked.", sql, None)

    try:
        if sql_upper.startswith("SELECT"):
            rows = fetch_query(sql)

            if not rows:
                return ("No records found.", sql, pd.DataFrame())

            df = pd.DataFrame(rows)
            return (f"Found {len(df)} record(s).", sql, df)

        else:
            execute_query(sql)
            return ("✅ Database updated successfully!", sql, None)

    except Exception as e:
        return (f"❌ Error: {e}", sql, None)