Quazim0t0 commited on
Commit
c5cf00a
·
verified ·
1 Parent(s): 207d5a0

Update database.py

Browse files
Files changed (1) hide show
  1. database.py +15 -26
database.py CHANGED
@@ -1,30 +1,19 @@
1
- from sqlalchemy import create_engine, MetaData, inspect
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
- Returns a list of existing tables in the database.
11
 
12
- Returns:
13
- list: List of table names.
14
- """
15
- inspector = inspect(engine)
16
- return inspector.get_table_names()
17
 
18
- # Function to initialize database (without forcing a table)
19
- def initialize_database():
20
- """
21
- Ensures the database starts up without failing if no SQL file is uploaded yet.
22
  """
23
- tables = get_existing_tables()
24
- if not tables:
25
- print("No tables found. Waiting for SQL file upload...")
26
- else:
27
- print(f"Database initialized with tables: {tables}")
28
-
29
- initialize_database()
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)}"