first upload
This commit is contained in:
30
backend/app/database.py
Normal file
30
backend/app/database.py
Normal file
@@ -0,0 +1,30 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||
import os
|
||||
|
||||
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./drugs.db")
|
||||
|
||||
# For SQLite, ensure the directory exists
|
||||
if "sqlite" in DATABASE_URL:
|
||||
# Extract path from sqlite:/// URL
|
||||
db_path = DATABASE_URL.replace("sqlite:///", "")
|
||||
os.makedirs(os.path.dirname(db_path) or ".", exist_ok=True)
|
||||
|
||||
engine = create_engine(
|
||||
DATABASE_URL,
|
||||
connect_args={"check_same_thread": False} if "sqlite" in DATABASE_URL else {}
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
Base = declarative_base()
|
||||
|
||||
# Drop and recreate all tables (for development only)
|
||||
Base.metadata.drop_all(bind=engine)
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
Reference in New Issue
Block a user