Files
tfm_ainventory/backend/database.py

31 lines
899 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__))
DATA_DIR = os.path.join(BASE_DIR, "data")
# Create data directory if it doesn't exist in the backend folder
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()