30 lines
976 B
Python
30 lines
976 B
Python
from urllib.parse import quote_plus
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.orm import sessionmaker, declarative_base
|
|
import os
|
|
|
|
# ---- Environment variables (from Coolify or .env) ----
|
|
DB_USER = os.getenv("DB_USER", "postgres")
|
|
DB_PASSWORD = quote_plus(os.getenv("DB_PASSWORD", ""))
|
|
DB_HOST = os.getenv("DB_HOST", "localhost")
|
|
DB_PORT = os.getenv("DB_PORT", "5432")
|
|
DB_NAME = os.getenv("DB_NAME", "postgres")
|
|
|
|
# ---- Database URL ----
|
|
DATABASE_URL = f"postgresql+psycopg2://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
|
|
|
|
# ---- SQLAlchemy setup ----
|
|
engine = create_engine(DATABASE_URL, pool_pre_ping=True)
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
Base = declarative_base()
|
|
|
|
# ---- Dependency helper for FastAPI ----
|
|
def get_db():
|
|
"""
|
|
FastAPI dependency that yields a database session and ensures it's closed after use.
|
|
"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|