Quazim0t0 commited on
Commit
2a06aec
·
verified ·
1 Parent(s): 9002697

Update database.py

Browse files
Files changed (1) hide show
  1. database.py +30 -6
database.py CHANGED
@@ -1,13 +1,13 @@
1
- from sqlalchemy import create_engine, MetaData, inspect
2
 
3
- # Initialize the SQLite database
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 tables currently in the database.
11
 
12
  Returns:
13
  list: List of table names.
@@ -15,15 +15,39 @@ def get_existing_tables():
15
  inspector = inspect(engine)
16
  return inspector.get_table_names()
17
 
18
- # Function to safely start the database
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  def initialize_database():
20
  """
21
- Starts the database without failing if no SQL file is uploaded yet.
22
  """
23
  tables = get_existing_tables()
24
 
25
  if not tables:
26
- print("No tables found. The database is waiting for an SQL file upload.")
 
27
  else:
28
  print(f"Database initialized with tables: {tables}")
29
 
 
1
+ from sqlalchemy import create_engine, MetaData, Table, Column, String, Integer, Float, 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.
 
15
  inspector = inspect(engine)
16
  return inspector.get_table_names()
17
 
18
+ # Create a default table if no SQL file is uploaded
19
+ def create_placeholder_table():
20
+ """
21
+ Creates a default 'users' table with example data if no SQL file has been uploaded.
22
+ """
23
+ if "users" not in get_existing_tables():
24
+ users_table = Table(
25
+ "users", metadata_obj,
26
+ Column("id", Integer, primary_key=True),
27
+ Column("name", String(50)),
28
+ Column("age", Integer),
29
+ Column("balance", Float)
30
+ )
31
+ metadata_obj.create_all(engine)
32
+
33
+ with engine.connect() as con:
34
+ con.execute(users_table.insert(), [
35
+ {"id": 1, "name": "Alice", "age": 30, "balance": 100.50},
36
+ {"id": 2, "name": "Bob", "age": 24, "balance": 250.75},
37
+ {"id": 3, "name": "Charlie", "age": 35, "balance": 80.00}
38
+ ])
39
+ print("✅ Created placeholder 'users' table with sample data.")
40
+
41
+ # Function to initialize database (Prevents crashes)
42
  def initialize_database():
43
  """
44
+ Ensures the database starts up with a placeholder table if no SQL file is uploaded.
45
  """
46
  tables = get_existing_tables()
47
 
48
  if not tables:
49
+ print("No tables found. Creating a placeholder table...")
50
+ create_placeholder_table()
51
  else:
52
  print(f"Database initialized with tables: {tables}")
53