|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from collections.abc import Callable |
| 4 | +from typing import Any, cast |
| 5 | + |
| 6 | +from graphql import GraphQLObjectType, GraphQLSchema |
| 7 | +from sqlalchemy import select |
| 8 | +from sqlalchemy.orm import DeclarativeBase, RelationshipProperty, class_mapper |
| 9 | + |
| 10 | +from ...objects import ObjectType |
| 11 | +from .dataloaders import LoaderRegistry |
| 12 | +from .types import LoadStrategy |
| 13 | + |
| 14 | + |
| 15 | +class SQLAlchemyObjectType(ObjectType): |
| 16 | + """ |
| 17 | + ObjectType specialized for SQLAlchemy models. |
| 18 | + Automatically binds resolvers for relationships using DataLoaders. |
| 19 | + """ |
| 20 | + |
| 21 | + model: type[DeclarativeBase] |
| 22 | + aliases: dict[str, str] |
| 23 | + strategies: dict[str, LoadStrategy] |
| 24 | + max_depth: int |
| 25 | + _registry_key: str |
| 26 | + |
| 27 | + def __init__( |
| 28 | + self, |
| 29 | + name: str, |
| 30 | + model: type[DeclarativeBase], |
| 31 | + *, |
| 32 | + aliases: dict[str, str] | Callable[[], dict[str, str]] | None = None, |
| 33 | + strategies: dict[str, LoadStrategy] | None = None, |
| 34 | + max_depth: int = 3, |
| 35 | + ): |
| 36 | + super().__init__(name) |
| 37 | + self.model = model |
| 38 | + self.aliases = aliases() if callable(aliases) else (aliases or {}) # ty: ignore[call-top-callable] |
| 39 | + self.strategies = strategies or {} |
| 40 | + self.max_depth = max_depth |
| 41 | + |
| 42 | + def bind_to_schema(self, schema: GraphQLSchema) -> None: |
| 43 | + """Binds this `SQLAlchemyObjectType` to the GraphQL schema. |
| 44 | +
|
| 45 | + Auto-generates resolvers for the model's relationships and aliased |
| 46 | + columns, then delegates to `ObjectType.bind_to_schema` to wire them |
| 47 | + (along with any explicitly-set resolvers) onto the schema's fields. |
| 48 | +
|
| 49 | + The auto-resolvers must be registered before calling `super()` so |
| 50 | + they are included when the parent iterates `self._resolvers` to |
| 51 | + populate the GraphQL type's field `resolve` attributes. |
| 52 | + """ |
| 53 | + graphql_type = schema.type_map.get(self.name) |
| 54 | + self.validate_graphql_type(graphql_type) |
| 55 | + self._bind_auto_resolvers(cast(GraphQLObjectType, graphql_type)) |
| 56 | + super().bind_to_schema(schema) |
| 57 | + |
| 58 | + def get_base_query(self, info: Any, **kwargs: Any): |
| 59 | + """ |
| 60 | + Returns the base SQLAlchemy select statement for root queries. |
| 61 | + Can be overridden to apply default filters. |
| 62 | + """ |
| 63 | + return select(self.model) |
| 64 | + |
| 65 | + def _bind_auto_resolvers(self, graphql_type: GraphQLObjectType) -> None: |
| 66 | + schema_fields = graphql_type.fields |
| 67 | + mapper = class_mapper(self.model) |
| 68 | + |
| 69 | + for gql_field, db_attr in self.aliases.items(): |
| 70 | + if gql_field not in schema_fields: |
| 71 | + continue |
| 72 | + if callable(db_attr): |
| 73 | + self.set_field(gql_field, db_attr) |
| 74 | + else: |
| 75 | + self.set_field( |
| 76 | + gql_field, lambda obj, *_, _attr=db_attr: getattr(obj, _attr) |
| 77 | + ) |
| 78 | + |
| 79 | + for relation in mapper.relationships: |
| 80 | + if relation.key not in schema_fields: |
| 81 | + continue |
| 82 | + if relation.key in self._resolvers: |
| 83 | + continue |
| 84 | + self.set_field(relation.key, self._create_relation_resolver(relation)) |
| 85 | + |
| 86 | + @staticmethod |
| 87 | + def get_loader_registry_from_context(context: Any) -> LoaderRegistry: |
| 88 | + """Get the `LoaderRegistry` from the GraphQL context. |
| 89 | +
|
| 90 | + Override this method to customize how the registry is retrieved. |
| 91 | + """ |
| 92 | + try: |
| 93 | + return context["loader_registry"] |
| 94 | + except KeyError: |
| 95 | + raise RuntimeError( |
| 96 | + "LoaderRegistry not found in context under key 'loader_registry'" |
| 97 | + ) |
| 98 | + |
| 99 | + def _create_relation_resolver(self, relation: RelationshipProperty): |
| 100 | + async def resolve(obj: Any, info: Any, **kwargs: Any): |
| 101 | + # If the attribute is already loaded (e.g. via joinedload/selectinload), |
| 102 | + # return it |
| 103 | + if relation.key in obj.__dict__: |
| 104 | + return getattr(obj, relation.key) |
| 105 | + |
| 106 | + loader_registry = self.get_loader_registry_from_context(info.context) |
| 107 | + |
| 108 | + # Identify which column(s) on the current object connect it to the |
| 109 | + # target table. For a One-to-Many, this is usually a Foreign Key. |
| 110 | + local_relation_columns = [ |
| 111 | + c.key for c in relation.local_columns if c.key is not None |
| 112 | + ] |
| 113 | + |
| 114 | + # Extract the actual database values from this specific object instance. |
| 115 | + join_values = tuple(getattr(obj, col) for col in local_relation_columns) |
| 116 | + |
| 117 | + # If it's a standard single-column relationship, unwrap the tuple to just |
| 118 | + # the ID. If it's a composite key, keep the tuple. |
| 119 | + lookup_key = join_values[0] if len(join_values) == 1 else join_values |
| 120 | + |
| 121 | + loader = loader_registry.get_loader(relation) |
| 122 | + return await loader.load(lookup_key) |
| 123 | + |
| 124 | + return resolve |
0 commit comments