Automated Action d024248fe9 Fix Supervisor start error in containerized environment
- Enhanced database connection with multiple fallback paths
- Updated configuration to use environment variables
- Fixed Alembic migrations to work with dynamic database path
- Improved robustness of database initialization
- Added Docker deployment instructions to README
- Updated environment variables documentation
2025-06-03 01:29:32 +00:00

54 lines
1.7 KiB
Python

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from pathlib import Path
import os
# Try to get database path from environment variable
DB_PATH = os.environ.get("DATABASE_PATH")
if DB_PATH:
# Use the provided path
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_PATH}"
else:
# Default paths with fallbacks for different environments
possible_paths = [
Path("/app/storage/db/db.sqlite"), # Docker container standard path
Path("/tmp/hrplatform/db/db.sqlite"), # Fallback to tmp directory
Path.cwd() / "db" / "db.sqlite" # Local development in current directory
]
# Find the first parent directory that is writable
for path in possible_paths:
try:
# Ensure directory exists
path.parent.mkdir(parents=True, exist_ok=True)
# Test if we can write to this directory
test_file = path.parent / ".write_test"
test_file.touch()
test_file.unlink()
SQLALCHEMY_DATABASE_URL = f"sqlite:///{path}"
print(f"Using database at: {path}")
break
except (PermissionError, OSError):
continue
else:
# If we get here, none of the paths worked
raise RuntimeError(
"Could not find a writable location for the database. "
"Please set the DATABASE_PATH environment variable."
)
# Create the engine with the configured URL
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()