40 lines
1.3 KiB
Python
40 lines
1.3 KiB
Python
import os
|
|
from pathlib import Path
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
from app.core.config import settings
|
|
|
|
# Create database directory if it doesn't exist
|
|
settings.DB_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
# Ensure we have a safe fallback path if the configured path doesn't work
|
|
try:
|
|
db_path = settings.DB_DIR / "db.sqlite"
|
|
SQLALCHEMY_DATABASE_URL = f"sqlite:///{db_path}"
|
|
# Test creating a file in the directory to ensure permissions are correct
|
|
test_file = settings.DB_DIR / "test_access.txt"
|
|
with open(test_file, "w") as f:
|
|
f.write("test")
|
|
os.remove(test_file)
|
|
except (IOError, PermissionError):
|
|
# Fallback to a local path if the configured path doesn't work
|
|
backup_db_dir = Path("./app/storage/db")
|
|
backup_db_dir.mkdir(parents=True, exist_ok=True)
|
|
db_path = backup_db_dir / "db.sqlite"
|
|
SQLALCHEMY_DATABASE_URL = f"sqlite:///{db_path}"
|
|
print(f"WARNING: Using fallback database path: {db_path}")
|
|
|
|
engine = create_engine(
|
|
SQLALCHEMY_DATABASE_URL,
|
|
connect_args={"check_same_thread": False}
|
|
)
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
# Dependency to get DB session
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close() |