Shyamnath commited on
Commit
9d5f319
·
1 Parent(s): f0fe332

Improve database initialization with better error handling and startup debugging

Browse files
Files changed (3) hide show
  1. app.py +17 -4
  2. app/database.py +25 -12
  3. app/main.py +8 -2
app.py CHANGED
@@ -20,17 +20,30 @@ def main():
20
  os.makedirs("app/static/images/dishes", exist_ok=True)
21
  os.makedirs("templates", exist_ok=True)
22
 
23
- # Ensure database file is in the correct location for Docker
 
 
 
 
 
 
 
 
 
24
  source_db = "Tabble.db"
25
- target_db = "Tabble.db" # Same location in Docker
26
 
27
  try:
28
  if os.path.exists(source_db):
29
- print(f"✅ Database found at {source_db}")
 
 
 
 
 
30
  else:
31
  print(f"⚠️ Database not found at {source_db}, will create new one")
32
  except Exception as e:
33
- print(f"⚠️ Database setup warning: {e}")
34
 
35
  # Set environment variables for Hugging Face Spaces
36
  os.environ.setdefault("HUGGINGFACE_SPACES", "1")
 
20
  os.makedirs("app/static/images/dishes", exist_ok=True)
21
  os.makedirs("templates", exist_ok=True)
22
 
23
+ # Debug: Check current directory and files
24
+ import os
25
+ print(f"🔍 Current working directory: {os.getcwd()}")
26
+ print(f"🔍 Files in current directory: {os.listdir('.')}")
27
+
28
+ # Check for database file
29
+ db_files = [f for f in os.listdir('.') if f.endswith('.db')]
30
+ print(f"🔍 Database files found: {db_files}")
31
+
32
+ # Ensure database file is accessible
33
  source_db = "Tabble.db"
 
34
 
35
  try:
36
  if os.path.exists(source_db):
37
+ size = os.path.getsize(source_db)
38
+ print(f"✅ Database found: {source_db} ({size} bytes)")
39
+ # Check if file is readable
40
+ with open(source_db, 'rb') as f:
41
+ f.read(16) # Try to read first 16 bytes
42
+ print(f"✅ Database file is readable")
43
  else:
44
  print(f"⚠️ Database not found at {source_db}, will create new one")
45
  except Exception as e:
46
+ print(f"⚠️ Database file check error: {e}")
47
 
48
  # Set environment variables for Hugging Face Spaces
49
  os.environ.setdefault("HUGGINGFACE_SPACES", "1")
app/database.py CHANGED
@@ -409,28 +409,41 @@ def get_current_database():
409
  # Create tables
410
  def create_tables():
411
  try:
412
- # Ensure database directory exists (current working directory)
413
- import os
414
- # We're already in /app in Docker, so just ensure file can be created
415
-
416
  # Create all tables (only creates tables that don't exist)
417
  Base.metadata.create_all(bind=engine)
418
  print("Database tables created/verified successfully")
419
  except Exception as e:
420
  print(f"Error creating database tables: {e}")
421
- # Try to create a new database file if the original doesn't exist
 
422
  try:
423
- print("Attempting to create new database...")
424
  import sqlite3
425
- # Create the database file if it doesn't exist (in current directory)
426
- with sqlite3.connect("Tabble.db") as conn:
427
- conn.execute("SELECT 1")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428
  # Try creating tables again
429
  Base.metadata.create_all(bind=engine)
430
- print("Database created successfully")
 
431
  except Exception as creation_error:
432
- print(f"Failed to create database: {creation_error}")
433
- raise
434
 
435
 
436
  # Get database session (legacy)
 
409
  # Create tables
410
  def create_tables():
411
  try:
 
 
 
 
412
  # Create all tables (only creates tables that don't exist)
413
  Base.metadata.create_all(bind=engine)
414
  print("Database tables created/verified successfully")
415
  except Exception as e:
416
  print(f"Error creating database tables: {e}")
417
+ print("Attempting to create new database with proper initialization...")
418
+
419
  try:
420
+ # Create a new SQLite database file in the current directory
421
  import sqlite3
422
+ import os
423
+
424
+ # Ensure we can write to the current directory
425
+ db_path = "Tabble.db"
426
+
427
+ # Create the database file with basic structure
428
+ conn = sqlite3.connect(db_path)
429
+ conn.execute("PRAGMA journal_mode=WAL;")
430
+ conn.execute("PRAGMA synchronous=NORMAL;")
431
+ conn.close()
432
+
433
+ print(f"Created new database file: {db_path}")
434
+
435
+ # Recreate engine with the new database
436
+ global engine
437
+ engine.dispose()
438
+ engine = create_engine(f"sqlite:///{db_path}", connect_args={"check_same_thread": False})
439
+
440
  # Try creating tables again
441
  Base.metadata.create_all(bind=engine)
442
+ print("Database tables created successfully in new database")
443
+
444
  except Exception as creation_error:
445
+ print(f"Failed to create new database: {creation_error}")
446
+ print("Starting without database - some features may not work")
447
 
448
 
449
  # Get database session (legacy)
app/main.py CHANGED
@@ -43,8 +43,14 @@ app.include_router(table.router)
43
  app.include_router(analytics.router)
44
  app.include_router(settings.router)
45
 
46
- # Create database tables
47
- create_tables()
 
 
 
 
 
 
48
 
49
  # Check if we have the React build folder
50
  react_build_dir = "frontend/build"
 
43
  app.include_router(analytics.router)
44
  app.include_router(settings.router)
45
 
46
+ # Database initialization on startup
47
+ @app.on_event("startup")
48
+ async def startup_event():
49
+ """Initialize database tables on application startup"""
50
+ try:
51
+ create_tables()
52
+ except Exception as e:
53
+ print(f"Warning: Database initialization failed: {e}")
54
 
55
  # Check if we have the React build folder
56
  react_build_dir = "frontend/build"