42 lines
1.1 KiB
Python
42 lines
1.1 KiB
Python
import dotenv
|
|
dotenv.load_dotenv()
|
|
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
import os
|
|
import logging
|
|
from sqlalchemy.exc import SQLAlchemyError
|
|
|
|
|
|
engine = create_engine(
|
|
os.getenv("DB_URL"),
|
|
pool_pre_ping=True,
|
|
echo=True if os.getenv("IS_DEV") == "True" else False, # Disable in production - this uses memory
|
|
connect_args={
|
|
"sslmode": "require" if os.getenv("IS_DEV") == "False" else "disable",
|
|
"connect_timeout": 10, # Connection timeout
|
|
},
|
|
)
|
|
|
|
Base = declarative_base() # Base class for ORM models
|
|
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
db.commit() # Explicit commit
|
|
except SQLAlchemyError as e:
|
|
db.rollback()
|
|
logging.error(f"Database error: {e}")
|
|
raise
|
|
except Exception as e:
|
|
db.rollback()
|
|
logging.error(f"Unexpected error: {e}")
|
|
raise
|
|
finally:
|
|
db.close()
|