Spaces:
Build error
Build error
| from sqlalchemy import create_engine | |
| from sqlalchemy.ext.declarative import declarative_base | |
| from sqlalchemy.orm import sessionmaker | |
| from sqlalchemy.exc import OperationalError | |
| import os | |
| # Read database URL from environment or fallback to docker-compose default | |
| SQLALCHEMY_DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://admin:adminpassword@localhost:5432/bankbot") | |
| USE_SQLITE = os.getenv("USE_SQLITE", "false").lower() in ("true", "1", "yes") | |
| BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| sqlite_db_path = os.path.join(BASE_DIR, "bankbot.db") | |
| if USE_SQLITE: | |
| SQLALCHEMY_DATABASE_URL = f"sqlite:///{sqlite_db_path}" | |
| connect_args = {} | |
| if "sqlite" in SQLALCHEMY_DATABASE_URL: | |
| connect_args = {"check_same_thread": False} | |
| try: | |
| engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args=connect_args) | |
| # Test connection | |
| with engine.connect() as conn: | |
| pass | |
| except (OperationalError, Exception) as e: | |
| print(f"Database connection to {SQLALCHEMY_DATABASE_URL} failed: {e}") | |
| print(f"Falling back to SQLite database at sqlite:///{sqlite_db_path}...") | |
| SQLALCHEMY_DATABASE_URL = f"sqlite:///{sqlite_db_path}" | |
| connect_args = {"check_same_thread": False} | |
| engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args=connect_args) | |
| SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) | |
| Base = declarative_base() | |
| def get_db(): | |
| db = SessionLocal() | |
| try: | |
| yield db | |
| finally: | |
| db.close() | |