|
| 1 | +import logging |
| 2 | +from collections import defaultdict |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +from aiodataloader import DataLoader |
| 6 | +from sqlalchemy import select, tuple_ |
| 7 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 8 | +from sqlalchemy.orm import RelationshipProperty |
| 9 | + |
| 10 | +logger = logging.getLogger(__name__) |
| 11 | + |
| 12 | + |
| 13 | +class SQLAlchemyRelationLoader(DataLoader): |
| 14 | + """ |
| 15 | + DataLoader for SQLAlchemy relationships supporting: |
| 16 | + - Composite Keys |
| 17 | + - Many-to-Many (secondary tables) |
| 18 | + - Result grouping via SQL columns (optimized) |
| 19 | + """ |
| 20 | + |
| 21 | + def __init__( |
| 22 | + self, |
| 23 | + session: AsyncSession, |
| 24 | + relation_prop: RelationshipProperty, |
| 25 | + cache: bool = True, |
| 26 | + ): |
| 27 | + super().__init__(cache=cache) |
| 28 | + self.session = session |
| 29 | + self.relation_prop = relation_prop |
| 30 | + self.target_model = relation_prop.mapper.class_ |
| 31 | + self.is_list = relation_prop.uselist |
| 32 | + |
| 33 | + # Identify local and remote columns (handles composite keys) |
| 34 | + if relation_prop.secondary is not None: |
| 35 | + self.local_cols = [lp.key for lp, rp in relation_prop.synchronize_pairs] |
| 36 | + self.remote_cols = [rp.key for lp, rp in relation_prop.synchronize_pairs] |
| 37 | + else: |
| 38 | + self.local_cols = [c.key for c in relation_prop.local_columns] |
| 39 | + self.remote_cols = [c.key for c in relation_prop.remote_side] |
| 40 | + |
| 41 | + self.secondary = relation_prop.secondary |
| 42 | + |
| 43 | + def get_query(self, keys: list[Any]): |
| 44 | + """Builds query. Handles composite IN clause and M2M joins.""" |
| 45 | + target_model = self.target_model |
| 46 | + stmt = select(target_model) |
| 47 | + |
| 48 | + if self.secondary is not None: |
| 49 | + stmt = stmt.join(self.secondary) |
| 50 | + filter_cols = [self.secondary.c[k] for k in self.remote_cols] # ty: ignore[invalid-argument-type] |
| 51 | + else: |
| 52 | + filter_cols = [getattr(target_model, k) for k in self.remote_cols] # ty: ignore[invalid-argument-type] |
| 53 | + |
| 54 | + # Add the filtering columns to the result to allow grouping |
| 55 | + stmt = stmt.add_columns(*filter_cols) |
| 56 | + |
| 57 | + if len(filter_cols) > 1: |
| 58 | + stmt = stmt.where(tuple_(*filter_cols).in_(keys)) |
| 59 | + else: |
| 60 | + # Flatten keys if they are single-element tuples |
| 61 | + flat_keys = [k[0] if isinstance(k, (list, tuple)) else k for k in keys] |
| 62 | + stmt = stmt.where(filter_cols[0].in_(flat_keys)) |
| 63 | + |
| 64 | + return stmt |
| 65 | + |
| 66 | + async def batch_load_fn(self, keys: list[Any]) -> list[Any]: |
| 67 | + logger.debug( |
| 68 | + "SQLAlchemyRelationLoader: Fetching %s for %d parents", |
| 69 | + self.target_model.__name__, |
| 70 | + len(keys), |
| 71 | + ) |
| 72 | + stmt = self.get_query(keys) |
| 73 | + result = await self.session.execute(stmt) |
| 74 | + rows = result.all() |
| 75 | + |
| 76 | + num_filter_cols = len(self.remote_cols) |
| 77 | + grouped = defaultdict(list) |
| 78 | + |
| 79 | + for row in rows: |
| 80 | + item = row[0] |
| 81 | + # The filter columns are appended after the model instance |
| 82 | + key_parts = row[1 : 1 + num_filter_cols] |
| 83 | + key = tuple(key_parts) if num_filter_cols > 1 else key_parts[0] |
| 84 | + grouped[key].append(item) |
| 85 | + |
| 86 | + return [ |
| 87 | + grouped[k] if self.is_list else (grouped[k][0] if grouped[k] else None) |
| 88 | + for k in keys |
| 89 | + ] |
| 90 | + |
| 91 | + |
| 92 | +class LoaderRegistry: |
| 93 | + """ |
| 94 | + Keeps one DataLoader instance per relationship per request. |
| 95 | + """ |
| 96 | + |
| 97 | + def __init__(self, session: AsyncSession): |
| 98 | + self.session = session |
| 99 | + self._loaders: dict[ |
| 100 | + tuple[RelationshipProperty, type[DataLoader]], DataLoader |
| 101 | + ] = {} |
| 102 | + |
| 103 | + def get_loader( |
| 104 | + self, |
| 105 | + relation_prop: RelationshipProperty, |
| 106 | + loader_class: type[SQLAlchemyRelationLoader] = SQLAlchemyRelationLoader, |
| 107 | + ) -> DataLoader: |
| 108 | + key = (relation_prop, loader_class) |
| 109 | + if key not in self._loaders: |
| 110 | + self._loaders[key] = loader_class(self.session, relation_prop) |
| 111 | + return self._loaders[key] |
0 commit comments