chaos: optimizing db perforance
This commit is contained in:
parent
b198b7678e
commit
62b6020897
28
database.py
28
database.py
|
|
@ -5,16 +5,23 @@ from sqlalchemy import create_engine
|
||||||
from sqlalchemy.ext.declarative import declarative_base
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
from sqlalchemy.orm import sessionmaker
|
from sqlalchemy.orm import sessionmaker
|
||||||
import os
|
import os
|
||||||
|
import logging
|
||||||
|
from sqlalchemy.exc import SQLAlchemyError
|
||||||
|
|
||||||
|
|
||||||
engine = create_engine(
|
engine = create_engine(
|
||||||
os.getenv("DB_URL"),
|
os.getenv("DB_URL"),
|
||||||
pool_pre_ping=True, # Check connection before using it
|
pool_pre_ping=True,
|
||||||
pool_size=5, # Connection pool size
|
pool_size=2, # Reduced from 5
|
||||||
max_overflow=10, # Max extra connections when pool is full
|
max_overflow=3, # Reduced from 10
|
||||||
pool_recycle=3600, # Recycle connections after 1 hour
|
pool_recycle=1800, # Reduced to 30 minutes
|
||||||
echo=True, # Log SQL queries
|
pool_timeout=30, # Add connection timeout
|
||||||
connect_args={"sslmode": "require" if os.getenv("IS_DEV") == "False" else "disable"},
|
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
|
Base = declarative_base() # Base class for ORM models
|
||||||
|
|
@ -26,5 +33,14 @@ def get_db():
|
||||||
db = SessionLocal()
|
db = SessionLocal()
|
||||||
try:
|
try:
|
||||||
yield db
|
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:
|
finally:
|
||||||
db.close()
|
db.close()
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue