Spaces:
Paused

yaz / src /shared /optimized_repository.py
anaselamr's picture
fix(collaboration): production-ready collaboration fixes — all 19 engines
0743ddc
Raw History Blame Contribute Delete
9.23 kB
"""
Enhanced base repository with built-in optimization features
Provides caching, performance monitoring, and query optimization
"""
from datetime import timedelta
from typing import Any, Dict, List, Optional, Type, TypeVar
from uuid import UUID
import structlog
from shared.performance import PerformanceMonitor, monitor_performance
from shared.query_cache import QueryCache, cache_query_result
from sqlalchemy import func
from sqlalchemy.orm import Query, Session, joinedload
logger = structlog.get_logger(__name__)
T = TypeVar("T")
class OptimizedRepository:
"""
Base repository class with optimization features built-in
Features:
- Query result caching
- Performance monitoring
- Eager loading helpers
- Pagination utilities
- Common query patterns
"""
def __init__(self, session: Session):
self.session = session
self._cache_enabled = True
self._monitoring_enabled = True
# ==================== QUERY OPTIMIZATION ====================
def _apply_eager_loading(self, query: Query, *relationships) -> Query:
"""Apply eager loading for specified relationships"""
for rel in relationships:
query = query.options(joinedload(rel))
return query
def _paginate(self, query: Query, skip: int = 0, limit: int = 100) -> Query:
"""Apply pagination with bounds checking"""
limit = min(max(1, limit), 1000) # Between 1 and 1000
skip = max(0, skip)
return query.offset(skip).limit(limit)
def _apply_filters(self, query: Query, filters: dict[str, Any]) -> Query:
"""Apply multiple filters to query"""
model = query.column_descriptions[0]["type"]
for key, value in filters.items():
if value is not None and hasattr(model, key):
query = query.filter(getattr(model, key) == value)
return query
# ==================== CACHED QUERIES ====================
@monitor_performance("repository:get_by_id")
def get_by_id(
self,
model: type[T],
record_id: UUID,
cache_ttl: timedelta | None = None,
eager_load: list | None = None,
) -> T | None:
"""
Get record by ID with optional caching and eager loading
Args:
model: SQLAlchemy model class
record_id: Record UUID
cache_ttl: Cache time-to-live (None = no cache)
eager_load: List of relationships to eager load
"""
cache_key = f"{model.__tablename__}:id:{record_id}" # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr]
# Check cache if enabled
if cache_ttl and self._cache_enabled:
cached = QueryCache.get(cache_key, cache_ttl)
if cached:
logger.debug(f"Cache hit: {cache_key}")
return cached
# Build query
query = self.session.query(model).filter(model.id == record_id) # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr]
# Apply eager loading
if eager_load:
query = self._apply_eager_loading(query, *eager_load)
result = query.first()
# Cache result
if result and cache_ttl and self._cache_enabled:
QueryCache.set(cache_key, result)
return result
@monitor_performance("repository:list")
def list_records(
self,
model: type[T],
filters: dict[str, Any] | None = None,
order_by: Any | None = None,
skip: int = 0,
limit: int = 100,
cache_ttl: timedelta | None = None,
) -> list[T]:
"""
List records with filtering, ordering, and pagination
Args:
model: SQLAlchemy model class
filters: Dictionary of field filters
order_by: SQLAlchemy order_by clause
skip: Number of records to skip
limit: Maximum records to return
cache_ttl: Cache time-to-live (None = no cache)
"""
cache_key = f"{model.__tablename__}:list:{filters}:{skip}:{limit}" # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr]
# Check cache
if cache_ttl and self._cache_enabled:
cached = QueryCache.get(cache_key, cache_ttl)
if cached:
logger.debug(f"Cache hit: {cache_key}")
return cached
# Build query
query = self.session.query(model)
# Apply filters
if filters:
query = self._apply_filters(query, filters)
# Apply ordering
if order_by is not None:
query = query.order_by(order_by)
# Apply pagination
query = self._paginate(query, skip, limit)
result = query.all()
# Cache result
if cache_ttl and self._cache_enabled:
QueryCache.set(cache_key, result)
return result
@monitor_performance("repository:count")
def count_records(
self,
model: type[T],
filters: dict[str, Any] | None = None,
cache_ttl: timedelta | None = None,
) -> int:
"""
Count records with optional filtering and caching
"""
cache_key = f"{model.__tablename__}:count:{filters}" # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr]
# Check cache
if cache_ttl and self._cache_enabled:
cached = QueryCache.get(cache_key, cache_ttl)
if cached is not None:
return cached
# Build query
query = self.session.query(func.count(model.id)) # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr]
# Apply filters
if filters:
query = self._apply_filters(query, filters) # type: ignore[arg-type, assignment]
result = query.scalar()
# Cache result
if cache_ttl and self._cache_enabled:
QueryCache.set(cache_key, result)
return result
# ==================== WRITE OPERATIONS ====================
@monitor_performance("repository:create")
def create_record(self, model: type[T], data: dict[str, Any]) -> T:
"""Create new record and invalidate cache"""
record = model(**data)
self.session.add(record)
self.session.flush()
# Invalidate cache for this model
self._invalidate_model_cache(model)
return record
@monitor_performance("repository:update")
def update_record(self, model: type[T], record_id: UUID, updates: dict[str, Any]) -> T | None:
"""Update record and invalidate cache"""
record = self.get_by_id(model, record_id)
if not record:
return None
for key, value in updates.items():
if hasattr(record, key):
setattr(record, key, value)
self.session.flush()
# Invalidate cache
self._invalidate_model_cache(model)
cache_key = f"{model.__tablename__}:id:{record_id}" # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr]
QueryCache.invalidate(cache_key)
return record
@monitor_performance("repository:delete")
def delete_record(self, model: type[T], record_id: UUID) -> bool:
"""Delete record and invalidate cache"""
record = self.get_by_id(model, record_id)
if not record:
return False
self.session.delete(record)
self.session.flush()
# Invalidate cache
self._invalidate_model_cache(model)
cache_key = f"{model.__tablename__}:id:{record_id}" # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr]
QueryCache.invalidate(cache_key)
return True
@monitor_performance("repository:bulk_create")
def bulk_create_records(self, model: type[T], data_list: list[dict[str, Any]]) -> list[T]:
"""Bulk create records efficiently"""
records = [model(**data) for data in data_list]
self.session.bulk_save_objects(records, return_defaults=True)
self.session.flush()
# Invalidate cache
self._invalidate_model_cache(model)
return records
# ==================== CACHE MANAGEMENT ====================
def _invalidate_model_cache(self, model: type[T]):
"""Invalidate all cache entries for a model"""
if self._cache_enabled:
QueryCache.invalidate_pattern(model.__tablename__) # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr]
def disable_cache(self):
"""Temporarily disable caching"""
self._cache_enabled = False
def enable_cache(self):
"""Re-enable caching"""
self._cache_enabled = True
# ==================== PERFORMANCE ====================
def get_performance_stats(self) -> dict:
"""Get performance statistics for this repository"""
return PerformanceMonitor.get_stats()
def get_slow_queries(self) -> list[dict]:
"""Get slow queries from this repository"""
return PerformanceMonitor.get_slow_queries()
# Export
__all__ = ["OptimizedRepository"]