33 lines
1002 B
Python
33 lines
1002 B
Python
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker, declarative_base
|
|
import os
|
|
|
|
# Get absolute path for the backend directory
|
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
# Use DATA_DIR from environment if running in Docker, otherwise fallback to local 'data' folder
|
|
DATA_DIR = os.environ.get("DATA_DIR", os.path.join(BASE_DIR, "data"))
|
|
|
|
# Create data directory if it doesn't exist
|
|
os.makedirs(DATA_DIR, exist_ok=True)
|
|
|
|
# Handle absolute path for SQLite (needs 4 slashes on Unix)
|
|
db_path = os.path.join(DATA_DIR, "inventory.db")
|
|
SQLALCHEMY_DATABASE_URL = f"sqlite:////{db_path}"
|
|
|
|
# connect_args={"check_same_thread": False} is required for SQLite in FastAPI/Starlette
|
|
engine = create_engine(
|
|
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
|
|
)
|
|
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
Base = declarative_base()
|
|
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|