from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from config.site import SiteConfig

config = SiteConfig()

POSTGRESQL_HOST = config.get_config("POSTGRESQL_HOST")
POSTGRESQL_DATABASE = config.get_config("POSTGRESQL_DATABASE")
POSTGRESQL_USER = config.get_config("POSTGRESQL_USER")
POSTGRESQL_PASSWORD = config.get_config("POSTGRESQL_PASSWORD")

DATABASE_URL = f"postgresql+psycopg2://{POSTGRESQL_USER}:{POSTGRESQL_PASSWORD}@{POSTGRESQL_HOST}/{POSTGRESQL_DATABASE}"

engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()