Spaces:
Running
Running
Update database.py
Browse files- database.py +15 -26
database.py
CHANGED
@@ -1,30 +1,19 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
# Initialize database engine (Persistent SQLite)
|
4 |
-
engine = create_engine("sqlite:///database.db")
|
5 |
-
metadata_obj = MetaData()
|
6 |
-
|
7 |
-
# Function to check existing tables
|
8 |
-
def get_existing_tables():
|
9 |
"""
|
10 |
-
|
11 |
|
12 |
-
|
13 |
-
|
14 |
-
"""
|
15 |
-
inspector = inspect(engine)
|
16 |
-
return inspector.get_table_names()
|
17 |
|
18 |
-
|
19 |
-
|
20 |
-
"""
|
21 |
-
Ensures the database starts up without failing if no SQL file is uploaded yet.
|
22 |
"""
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
|
|
1 |
+
@tool
|
2 |
+
def sql_engine(query: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
"""
|
4 |
+
Executes an SQL SELECT query and returns the results.
|
5 |
|
6 |
+
Parameters:
|
7 |
+
query (str): The SQL query string to execute. Only SELECT queries are allowed.
|
|
|
|
|
|
|
8 |
|
9 |
+
Returns:
|
10 |
+
str: A formatted string containing the query results, or an error message if the query fails.
|
|
|
|
|
11 |
"""
|
12 |
+
try:
|
13 |
+
with engine.connect() as con:
|
14 |
+
rows = con.execute(text(query)).fetchall()
|
15 |
+
if not rows:
|
16 |
+
return "No results found."
|
17 |
+
return "\n".join([", ".join(map(str, row)) for row in rows])
|
18 |
+
except Exception as e:
|
19 |
+
return f"Error: {str(e)}"
|