TXTAgent / database.py
Quazim0t0's picture
Update database.py
2a06aec verified
raw
history blame
1.83 kB
from sqlalchemy import create_engine, MetaData, Table, Column, String, Integer, Float, inspect
# Initialize database engine (Persistent SQLite)
engine = create_engine("sqlite:///database.db")
metadata_obj = MetaData()
# Function to check existing tables
def get_existing_tables():
"""
Returns a list of existing tables in the database.
Returns:
list: List of table names.
"""
inspector = inspect(engine)
return inspector.get_table_names()
# Create a default table if no SQL file is uploaded
def create_placeholder_table():
"""
Creates a default 'users' table with example data if no SQL file has been uploaded.
"""
if "users" not in get_existing_tables():
users_table = Table(
"users", metadata_obj,
Column("id", Integer, primary_key=True),
Column("name", String(50)),
Column("age", Integer),
Column("balance", Float)
)
metadata_obj.create_all(engine)
with engine.connect() as con:
con.execute(users_table.insert(), [
{"id": 1, "name": "Alice", "age": 30, "balance": 100.50},
{"id": 2, "name": "Bob", "age": 24, "balance": 250.75},
{"id": 3, "name": "Charlie", "age": 35, "balance": 80.00}
])
print("βœ… Created placeholder 'users' table with sample data.")
# Function to initialize database (Prevents crashes)
def initialize_database():
"""
Ensures the database starts up with a placeholder table if no SQL file is uploaded.
"""
tables = get_existing_tables()
if not tables:
print("No tables found. Creating a placeholder table...")
create_placeholder_table()
else:
print(f"Database initialized with tables: {tables}")
initialize_database()