Spaces:
Build error
Build error
File size: 1,831 Bytes
2a06aec d4bd626 2a06aec d4bd626 add59ac d4bd626 2a06aec 037ba4c c5cf00a d4bd626 add59ac d4bd626 2a06aec d4bd626 2a06aec d4bd626 a400f6e d4bd626 2a06aec d4bd626 a400f6e |
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
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()
|