47 lines
1.2 KiB
Python
47 lines
1.2 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,
|
|
pool_size=2, # Reduced from 5
|
|
max_overflow=3, # Reduced from 10
|
|
pool_recycle=1800, # Reduced to 30 minutes
|
|
pool_timeout=30, # Add connection timeout
|
|
echo=False, # Disable in production - this uses memory
|
|
connect_args={
|
|
"sslmode": "require" if os.getenv("IS_DEV") == "False" else "disable",
|
|
"connect_timeout": 10, # Connection timeout
|
|
"command_timeout": 60, # Query 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()
|