habit_tracker / src /database /connection.py
GitHub Action Sync
Automated sync from GitHub commit 32442f52cfe2a6bf1450830784883eb41d31da62
4361d77
Raw
History Blame Contribute Delete
829 Bytes
# database/connection.py
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from dotenv import load_dotenv
import os
load_dotenv()
# Grab database URL from environment variables for security
DATABASE_URL = os.getenv("DATABASE_URL")
if not DATABASE_URL:
raise ValueError("DATABASE_URL environment variable is missing!")
# Create the global async engine
engine = create_async_engine(
DATABASE_URL,
echo=True,
connect_args={"ssl": "require"}
)
# Create a session factory
AsyncSessionLocal = sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False
)
# Dependency wrapper (commonly used in FastAPI or async apps)
async def get_session() -> AsyncSession:
async with AsyncSessionLocal() as session:
yield session