Quazim0t0 commited on
Commit
d4bd626
ยท
verified ยท
1 Parent(s): c5cf00a

Update database.py

Browse files
Files changed (1) hide show
  1. database.py +25 -15
database.py CHANGED
@@ -1,19 +1,29 @@
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)}"
 
 
 
 
 
 
 
 
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()