-
-
Notifications
You must be signed in to change notification settings - Fork 131
/
Copy pathoptimizer.py
1623 lines (1413 loc) · 53.8 KB
/
optimizer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import contextlib
import contextvars
import copy
import dataclasses
import itertools
from collections import Counter
from collections.abc import Callable
from typing import (
TYPE_CHECKING,
Any,
TypeVar,
cast,
)
from django.db import models
from django.db.models import Prefetch
from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import BaseExpression, Combinable
from django.db.models.fields.reverse_related import (
ManyToManyRel,
ManyToOneRel,
OneToOneRel,
)
from django.db.models.manager import BaseManager
from django.db.models.query import QuerySet
from graphql import (
FieldNode,
GraphQLInterfaceType,
GraphQLObjectType,
GraphQLOutputType,
GraphQLWrappingType,
get_argument_values,
)
from graphql.execution.collect_fields import collect_sub_fields
from graphql.language.ast import OperationType
from graphql.type.definition import GraphQLResolveInfo, get_named_type
from strawberry import relay
from strawberry.extensions import SchemaExtension
from strawberry.relay.utils import SliceMetadata
from strawberry.schema.schema import Schema
from strawberry.schema.schema_converter import get_arguments
from strawberry.types import get_object_definition, has_object_definition
from strawberry.types.base import StrawberryContainer
from strawberry.types.info import Info
from strawberry.types.lazy_type import LazyType
from strawberry.types.object_type import StrawberryObjectDefinition
from typing_extensions import assert_never, assert_type
from strawberry_django.fields.types import resolve_model_field_name
from strawberry_django.pagination import OffsetPaginated, apply_window_pagination
from strawberry_django.queryset import get_queryset_config, run_type_get_queryset
from strawberry_django.relay import ListConnectionWithTotalCount
from strawberry_django.resolvers import django_fetch
from .descriptors import ModelProperty
from .utils.inspect import (
PrefetchInspector,
get_model_field,
get_model_fields,
get_possible_concrete_types,
get_possible_type_definitions,
is_inheritance_manager,
is_inheritance_qs,
is_polymorphic_model,
)
from .utils.typing import (
AnnotateCallable,
AnnotateType,
PrefetchCallable,
PrefetchType,
TypeOrMapping,
TypeOrSequence,
WithStrawberryDjangoObjectDefinition,
get_django_definition,
has_django_definition,
)
if TYPE_CHECKING:
from collections.abc import Generator
from django.contrib.contenttypes.fields import GenericRelation
from strawberry.types.execution import ExecutionContext
from strawberry.types.field import StrawberryField
from strawberry.utils.await_maybe import AwaitableOrValue
__all__ = [
"DjangoOptimizerExtension",
"OptimizerConfig",
"OptimizerStore",
"PrefetchType",
"optimize",
]
_M = TypeVar("_M", bound=models.Model)
_sentinel = object()
_annotate_placeholder = "__annotated_placeholder__"
@dataclasses.dataclass
class OptimizerConfig:
"""Django optimization configuration.
Attributes
----------
enable_only:
Enable `QuerySet.only` optimizations
enable_select_related:
Enable `QuerySet.select_related` optimizations
enable_prefetch_related:
Enable `QuerySet.prefetch_related` optimizations
enable_annotate:
Enable `QuerySet.annotate` optimizations
enable_nested_relations_prefetch:
Enable prefetch of nested relations optimizations.
prefetch_custom_queryset:
Use custom instead of _base_manager for prefetch querysets
"""
enable_only: bool = dataclasses.field(default=True)
enable_select_related: bool = dataclasses.field(default=True)
enable_prefetch_related: bool = dataclasses.field(default=True)
enable_annotate: bool = dataclasses.field(default=True)
enable_nested_relations_prefetch: bool = dataclasses.field(default=True)
prefetch_custom_queryset: bool = dataclasses.field(default=False)
@dataclasses.dataclass
class OptimizerStore:
"""Django optimization store.
Attributes
----------
only:
Set of values to optimize using `QuerySet.only`
selected:
Set of values to optimize using `QuerySet.select_related`
prefetch_related:
Set of values to optimize using `QuerySet.prefetch_related`
annotate:
Dict of values to use in `QuerySet.annotate`
"""
only: list[str] = dataclasses.field(default_factory=list)
select_related: list[str] = dataclasses.field(default_factory=list)
prefetch_related: list[PrefetchType] = dataclasses.field(default_factory=list)
annotate: dict[str, AnnotateType] = dataclasses.field(default_factory=dict)
def __bool__(self):
return any(
[self.only, self.select_related, self.prefetch_related, self.annotate],
)
def __ior__(self, other: OptimizerStore):
self.only.extend(other.only)
self.select_related.extend(other.select_related)
self.prefetch_related.extend(other.prefetch_related)
self.annotate.update(other.annotate)
return self
def __or__(self, other: OptimizerStore):
new = self.copy()
new |= other
return new
def copy(self):
"""Create a shallow copy of the store."""
return self.__class__(
only=self.only[:],
select_related=self.select_related[:],
prefetch_related=self.prefetch_related[:],
annotate=self.annotate.copy(),
)
@classmethod
def with_hints(
cls,
*,
only: TypeOrSequence[str] | None = None,
select_related: TypeOrSequence[str] | None = None,
prefetch_related: TypeOrSequence[PrefetchType] | None = None,
annotate: TypeOrMapping[AnnotateType] | None = None,
):
"""Create a new store with the given hints."""
return cls(
only=[only] if isinstance(only, str) else list(only or []),
select_related=(
[select_related]
if isinstance(select_related, str)
else list(select_related or [])
),
prefetch_related=(
[prefetch_related]
if isinstance(prefetch_related, (str, Prefetch, Callable))
else list(prefetch_related or [])
),
annotate=(
# placeholder here,
# because field name is evaluated later on .annotate call:
{_annotate_placeholder: annotate}
if isinstance(annotate, (BaseExpression, Combinable, Callable))
else dict(annotate or {})
),
)
def with_prefix(self, prefix: str, *, info: GraphQLResolveInfo):
"""Create a copy of this store with the given prefix.
This is useful when we need to apply the same store to a nested field.
`prefix` will be prepended to all fields in the store.
"""
prefetch_related = []
for p in self.prefetch_related:
if isinstance(p, Callable):
assert_type(p, PrefetchCallable)
p = p(info) # noqa: PLW2901
if isinstance(p, str):
prefetch_related.append(f"{prefix}{LOOKUP_SEP}{p}")
elif isinstance(p, Prefetch):
# add_prefix modifies the field's prefetch object, so we copy it before
p_copy = copy.copy(p)
p_copy.add_prefix(prefix)
prefetch_related.append(p_copy)
else: # pragma:nocover
assert_never(p)
annotate = {}
for k, v in self.annotate.items():
if isinstance(v, Callable):
assert_type(v, AnnotateCallable)
v = v(info) # noqa: PLW2901
annotate[f"{prefix}{LOOKUP_SEP}{k}"] = v
return self.__class__(
only=[f"{prefix}{LOOKUP_SEP}{i}" for i in self.only],
select_related=[f"{prefix}{LOOKUP_SEP}{i}" for i in self.select_related],
prefetch_related=prefetch_related,
annotate=annotate,
)
def apply(
self,
qs: QuerySet[_M],
*,
info: GraphQLResolveInfo,
config: OptimizerConfig | None = None,
) -> QuerySet[_M]:
"""Apply this store optimizations to the given queryset."""
config = config or OptimizerConfig()
qs = self._apply_prefetch_related(
qs,
info=info,
config=config,
)
qs, extra_only_set = self._apply_select_related(
qs,
info=info,
config=config,
)
qs = self._apply_only(
qs,
info=info,
config=config,
extra_only_set=extra_only_set,
)
qs = self._apply_annotate(
qs,
info=info,
config=config,
)
return qs # noqa: RET504
def _apply_prefetch_related(
self,
qs: QuerySet[_M],
*,
info: GraphQLResolveInfo,
config: OptimizerConfig,
) -> QuerySet[_M]:
if not config.enable_prefetch_related or not self.prefetch_related:
return qs
abort_only = set()
prefetch_lists = [
qs._prefetch_related_lookups, # type: ignore
self.prefetch_related,
]
# Add all str at the same time to make it easier to handle Prefetch below
to_prefetch: dict[str, str | Prefetch] = {
p: p for p in itertools.chain(*prefetch_lists) if isinstance(p, str)
}
# Merge already existing prefetches together
for p in itertools.chain(*prefetch_lists):
# Already added above
if isinstance(p, str):
continue
if isinstance(p, Callable):
assert_type(p, PrefetchCallable)
p = p(info) # noqa: PLW2901
path = p.prefetch_to
existing = to_prefetch.get(path)
# The simplest case. The prefetch doesn't exist or is a string.
# In this case, just replace it.
if not existing or isinstance(existing, str):
to_prefetch[path] = p
if isinstance(existing, str):
abort_only.add(path)
continue
p1 = PrefetchInspector(existing)
p2 = PrefetchInspector(p)
if getattr(existing, "_optimizer_sentinel", None) is _sentinel:
ret = p1.merge(p2, allow_unsafe_ops=True)
elif getattr(p, "_optimizer_sentinel", None) is _sentinel:
ret = p2.merge(p1, allow_unsafe_ops=True)
else:
# The order here doesn't matter
ret = p1.merge(p2)
to_prefetch[path] = ret.prefetch
# Abort only optimization if one prefetch related was made for everything
for ao in abort_only:
to_prefetch[ao].queryset.query.deferred_loading = ( # type: ignore
[],
True,
)
# First prefetch_related(None) to clear all existing prefetches, and then
# add ours, which also contains them. This is to avoid the
# "lookup was already seen with a different queryset" error
return qs.prefetch_related(None).prefetch_related(*to_prefetch.values())
def _apply_select_related(
self,
qs: QuerySet[_M],
*,
info: GraphQLResolveInfo,
config: OptimizerConfig,
) -> tuple[QuerySet[_M], set[str]]:
only_set = set(self.only)
extra_only_set = set()
select_related_set = set(self.select_related)
# inspect the queryset to find any existing select_related fields
def get_related_fields_with_prefix(
queryset_select_related: dict[str, Any],
prefix: str = "",
):
for parent, nested in queryset_select_related.items():
current_path = f"{prefix}{parent}"
yield current_path
if nested: # If there are nested relations, dive deeper
yield from get_related_fields_with_prefix(
nested,
prefix=f"{current_path}{LOOKUP_SEP}",
)
if isinstance(qs.query.select_related, dict):
select_related_set.update(
get_related_fields_with_prefix(qs.query.select_related)
)
if config.enable_select_related and select_related_set:
qs = qs.select_related(*select_related_set)
# Update our extra_select_related_only_set with the fields that were
# selected by select_related to make sure they actually get selected
for select_related in select_related_set:
if select_related in only_set:
continue
if not any(only.startswith(select_related) for only in only_set):
extra_only_set.add(select_related)
return qs, extra_only_set
def _apply_only(
self,
qs: QuerySet[_M],
*,
info: GraphQLResolveInfo,
config: OptimizerConfig,
extra_only_set: set[str],
) -> QuerySet[_M]:
only_set = set(self.only) | extra_only_set
if config.enable_only and only_set:
qs = qs.only(*only_set)
return qs
def _apply_annotate(
self,
qs: QuerySet[_M],
*,
info: GraphQLResolveInfo,
config: OptimizerConfig,
) -> QuerySet[_M]:
if not config.enable_annotate or not self.annotate:
return qs
to_annotate = {}
for k, v in self.annotate.items():
if isinstance(v, Callable):
assert_type(v, AnnotateCallable)
v = v(info) # noqa: PLW2901
to_annotate[k] = v
return qs.annotate(**to_annotate)
def _get_django_type(
field: StrawberryField,
) -> type[WithStrawberryDjangoObjectDefinition] | None:
f_type = field.type
if isinstance(f_type, LazyType):
f_type = f_type.resolve_type()
if isinstance(f_type, StrawberryContainer):
f_type = f_type.of_type
if isinstance(f_type, LazyType):
f_type = f_type.resolve_type()
return f_type if has_django_definition(f_type) else None
def _get_prefetch_queryset(
remote_model: type[models.Model],
schema: Schema,
field: StrawberryField,
parent_type: GraphQLObjectType | GraphQLInterfaceType,
field_node: FieldNode,
*,
config: OptimizerConfig | None,
info: GraphQLResolveInfo,
related_field_id: str | None = None,
) -> QuerySet:
# We usually want to use the `_base_manager` for prefetching, as it is what django
# itself states we should be using:
# https://docs.djangoproject.com/en/5.0/topics/db/managers/#base-managers
# But in case prefetch_custom_queryset is enabled, we use the custom queryset
# from _default_manager instead.
if config and config.prefetch_custom_queryset:
qs = remote_model._default_manager.all()
else:
qs = remote_model._base_manager.all() # type: ignore
if f_type := _get_django_type(field):
qs = run_type_get_queryset(
qs,
f_type,
info=Info(
_raw_info=info,
_field=field,
),
)
return _optimize_prefetch_queryset(
qs,
schema,
field,
parent_type,
field_node,
config=config,
info=info,
related_field_id=related_field_id,
)
def _optimize_prefetch_queryset(
qs: QuerySet[_M],
schema: Schema,
field: StrawberryField,
parent_type: GraphQLObjectType | GraphQLInterfaceType,
field_node: FieldNode,
*,
config: OptimizerConfig | None,
info: GraphQLResolveInfo,
related_field_id: str | None = None,
) -> QuerySet[_M]:
from strawberry_django.fields.field import (
StrawberryDjangoConnectionExtension,
StrawberryDjangoField,
)
from .relay_cursor import DjangoCursorConnection, apply_cursor_pagination
if (
not config
or not config.enable_nested_relations_prefetch
or related_field_id is None
or not isinstance(field, StrawberryDjangoField)
or is_optimized_by_prefetching(qs)
):
return qs
mark_optimized = True
strawberry_schema = cast("Schema", info.schema._strawberry_schema) # type: ignore
field_name = strawberry_schema.config.name_converter.from_field(field)
field_info = Info(
_raw_info=info,
_field=field,
)
_field_args, field_kwargs = get_arguments(
field=field,
source=None,
info=field_info,
kwargs=get_argument_values(
parent_type.fields[field_name],
field_node,
info.variable_values,
),
config=strawberry_schema.config,
scalar_registry=strawberry_schema.schema_converter.scalar_registry,
)
field_kwargs.pop("info", None)
# Disable the optimizer to avoid doing double optimization while running get_queryset
with DjangoOptimizerExtension.disabled():
qs = field.get_queryset(
qs,
field_info,
_strawberry_related_field_id=related_field_id,
**field_kwargs,
)
connection_extension = next(
(
e
for e in field.extensions
if isinstance(e, StrawberryDjangoConnectionExtension)
),
None,
)
if connection_extension is not None:
connection_type_def = get_object_definition(
connection_extension.connection_type,
strict=True,
)
connection_type = (
connection_type_def.concrete_of
and connection_type_def.concrete_of.origin
)
if (
connection_type is relay.ListConnection
or connection_type is ListConnectionWithTotalCount
):
slice_metadata = SliceMetadata.from_arguments(
Info(_raw_info=info, _field=field),
first=field_kwargs.get("first"),
last=field_kwargs.get("last"),
before=field_kwargs.get("before"),
after=field_kwargs.get("after"),
)
qs = apply_window_pagination(
qs,
related_field_id=related_field_id,
offset=slice_metadata.start,
limit=slice_metadata.end - slice_metadata.start,
max_results=connection_extension.max_results,
)
elif connection_type is DjangoCursorConnection:
qs, _ = apply_cursor_pagination(
qs,
related_field_id=related_field_id,
info=Info(_raw_info=info, _field=field),
first=field_kwargs.get("first"),
last=field_kwargs.get("last"),
before=field_kwargs.get("before"),
after=field_kwargs.get("after"),
max_results=connection_extension.max_results,
)
else:
mark_optimized = False
if isinstance(field.type, type) and issubclass(field.type, OffsetPaginated):
pagination = field_kwargs.get("pagination")
qs = apply_window_pagination(
qs,
related_field_id=related_field_id,
offset=pagination.offset if pagination else 0,
limit=pagination.limit if pagination else -1,
)
if mark_optimized:
qs = mark_optimized_by_prefetching(qs)
return qs
def _get_selections(
info: GraphQLResolveInfo,
parent_type: GraphQLObjectType | GraphQLInterfaceType,
) -> dict[str, list[FieldNode]]:
return collect_sub_fields(
info.schema,
info.fragments,
info.variable_values,
cast("GraphQLObjectType", parent_type),
info.field_nodes,
)
def _generate_selection_resolve_info(
info: GraphQLResolveInfo,
field_nodes: list[FieldNode],
return_type: GraphQLOutputType,
parent_type: GraphQLObjectType | GraphQLInterfaceType,
):
field_node = field_nodes[0]
return GraphQLResolveInfo(
field_name=field_node.name.value,
field_nodes=field_nodes,
return_type=return_type,
parent_type=cast("GraphQLObjectType", parent_type),
path=info.path.add_key(0).add_key(field_node.name.value, parent_type.name),
schema=info.schema,
fragments=info.fragments,
root_value=info.root_value,
operation=info.operation,
variable_values=info.variable_values,
context=info.context,
is_awaitable=info.is_awaitable,
)
def _get_field_data(
selections: list[FieldNode],
object_definition: StrawberryObjectDefinition,
schema: Schema,
*,
parent_type: GraphQLObjectType | GraphQLInterfaceType,
info: GraphQLResolveInfo,
) -> tuple[StrawberryField, GraphQLObjectType, FieldNode, GraphQLResolveInfo] | None:
selection = selections[0]
field_name = selection.name.value
for field in object_definition.fields:
if schema.config.name_converter.get_graphql_name(field) == field_name:
break
else:
return None
# Do not optimize the field if the user asked not to
if getattr(field, "disable_optimization", False):
return None
definition = parent_type.fields[selection.name.value].type
while isinstance(definition, GraphQLWrappingType):
definition = definition.of_type
field_info = _generate_selection_resolve_info(
info,
selections,
definition,
parent_type,
)
return field, definition, selection, field_info
def _get_hints_from_field(
field: StrawberryField,
*,
f_info: GraphQLResolveInfo,
prefix: str = "",
) -> OptimizerStore | None:
if not (field_store := getattr(field, "store", None)):
return None
if len(field_store.annotate) == 1 and _annotate_placeholder in field_store.annotate:
# This is a special case where we need to update the field name,
# because when field_store was created on __init__,
# the field name wasn't available.
# This allows for annotate expressions to be declared as:
# total: int = gql.django.field(annotate=Sum("price")) # noqa: ERA001
# Instead of the more redundant:
# total: int = gql.django.field(annotate={"total": Sum("price")}) # noqa: ERA001
field_store.annotate = {
field.name: field_store.annotate[_annotate_placeholder],
}
return field_store.with_prefix(prefix, info=f_info) if prefix else field_store
def _get_hints_from_model_property(
field: StrawberryField,
model: type[models.Model],
*,
f_info: GraphQLResolveInfo,
prefix: str = "",
) -> OptimizerStore | None:
model_attr = getattr(model, field.python_name, None)
if (
model_attr is not None
and isinstance(model_attr, ModelProperty)
and model_attr.store
):
attr_store = model_attr.store
store = attr_store.with_prefix(prefix, info=f_info) if prefix else attr_store
else:
store = None
return store
def _must_use_prefetch_related(
config: OptimizerConfig,
field: StrawberryField,
model_field: models.ForeignKey | OneToOneRel,
) -> bool:
f_type = _get_django_type(field)
# - If the field has a get_queryset method, use Prefetch so it will be respected
# - If the model is using django-polymorphic,
# use Prefetch so its custom queryset will be used, returning polymorphic models
return (
(f_type and hasattr(f_type, "get_queryset"))
or is_polymorphic_model(model_field.related_model)
or is_inheritance_manager(
model_field.related_model._default_manager
if config.prefetch_custom_queryset
else model_field.related_model._base_manager # type: ignore
)
)
def _get_hints_from_django_foreign_key(
field: StrawberryField,
field_definition: GraphQLObjectType,
field_selection: FieldNode,
model_field: models.ForeignKey | OneToOneRel,
model_fieldname: str,
schema: Schema,
*,
config: OptimizerConfig,
parent_type: GraphQLObjectType | GraphQLInterfaceType,
field_info: GraphQLResolveInfo,
path: str,
cache: dict[type[models.Model], list[tuple[int, OptimizerStore]]],
level: int = 0,
) -> OptimizerStore:
if _must_use_prefetch_related(config, field, model_field):
store = _get_hints_from_django_relation(
field,
field_selection=field_selection,
model_field=model_field,
model_fieldname=model_fieldname,
schema=schema,
config=config,
parent_type=parent_type,
field_info=field_info,
path=path,
cache=cache,
level=level,
)
store.only.append(path)
return store
store = OptimizerStore.with_hints(
only=[path],
select_related=[path],
)
# If adding a reverse relation, make sure to select its pointer to us,
# or else this might causa a refetch from the database
if isinstance(model_field, OneToOneRel):
remote_field = model_field.remote_field
store.only.append(
f"{path}{LOOKUP_SEP}{resolve_model_field_name(remote_field)}",
)
for f_type_def in get_possible_type_definitions(field.type):
f_model = model_field.related_model
f_store = _get_model_hints(
f_model,
schema,
f_type_def,
parent_type=field_definition,
info=field_info,
config=config,
cache=cache,
level=level + 1,
)
if f_store is not None:
cache.setdefault(f_model, []).append((level, f_store))
store |= f_store.with_prefix(path, info=field_info)
return store
def _get_hints_from_django_relation(
field: StrawberryField,
field_selection: FieldNode,
model_field: (
models.ManyToManyField
| ManyToManyRel
| ManyToOneRel
| GenericRelation
| OneToOneRel
| models.ForeignKey
),
model_fieldname: str,
schema: Schema,
*,
config: OptimizerConfig,
parent_type: GraphQLObjectType | GraphQLInterfaceType,
field_info: GraphQLResolveInfo,
path: str,
cache: dict[type[models.Model], list[tuple[int, OptimizerStore]]],
level: int = 0,
) -> OptimizerStore:
try:
from django.contrib.contenttypes.fields import GenericRelation
except (ImportError, RuntimeError): # pragma: no cover
GenericRelation = None # noqa: N806
store = OptimizerStore()
f_types = list(get_possible_type_definitions(field.type))
if len(f_types) > 1:
# This might be a generic foreign key.
# In this case, just prefetch it
store.prefetch_related.append(model_fieldname)
return store
field_store = getattr(field, "store", None)
if field_store and field_store.prefetch_related:
# Skip optimization if 'prefetch_related' is present in the field's store.
# This is necessary because 'prefetch_related' likely modifies the queryset
# with filtering or annotating, making the optimization redundant and
# potentially causing an extra unused query.
return store
remote_field = model_field.remote_field
remote_model = remote_field.model
field_store = None
f_type = f_types[0]
subclasses = []
for concrete_field_type in get_possible_concrete_types(
remote_model, schema, f_type
):
django_definition = get_django_definition(concrete_field_type.origin)
if (
django_definition
and django_definition.model != remote_model
and not django_definition.model._meta.abstract
and issubclass(django_definition.model, remote_model)
):
subclasses.append(django_definition.model)
concrete_store = _get_model_hints(
remote_model,
schema,
concrete_field_type,
parent_type=_get_gql_definition(schema, concrete_field_type),
info=field_info,
config=config,
cache=cache,
level=level + 1,
)
if concrete_store is not None:
field_store = (
concrete_store if field_store is None else field_store | concrete_store
)
if field_store is None:
return store
related_field_id = getattr(remote_field, "attname", None) or getattr(
remote_field, "name", None
)
if (
config.enable_only
and field_store.only
and not isinstance(remote_field, ManyToManyRel)
):
# If adding a reverse relation, make sure to select its
# pointer to us, or else this might causa a refetch from
# the database
if GenericRelation is not None and isinstance(
model_field,
GenericRelation,
):
field_store.only.append(model_field.object_id_field_name)
field_store.only.append(model_field.content_type_field_name)
elif related_field_id is not None:
field_store.only.append(related_field_id)
path_lookup = f"{path}{LOOKUP_SEP}"
if store.only and field_store.only:
extra_only = [o for o in store.only or [] if o.startswith(path_lookup)]
store.only = [o for o in store.only if o not in extra_only]
field_store.only.extend(o[len(path_lookup) :] for o in extra_only)
if store.select_related and field_store.select_related:
extra_sr = [o for o in store.select_related or [] if o.startswith(path_lookup)]
store.select_related = [o for o in store.select_related if o not in extra_sr]
field_store.select_related.extend(o[len(path_lookup) :] for o in extra_sr)
cache.setdefault(remote_model, []).append((level, field_store))
base_qs = _get_prefetch_queryset(
remote_model,
schema,
field,
parent_type,
field_selection,
config=config,
info=field_info,
related_field_id=related_field_id,
)
if is_inheritance_qs(base_qs):
base_qs = base_qs.select_subclasses(*subclasses)
field_qs = field_store.apply(base_qs, info=field_info, config=config)
field_prefetch = Prefetch(path, queryset=field_qs)
field_prefetch._optimizer_sentinel = _sentinel # type: ignore
store.prefetch_related.append(field_prefetch)
return store
def _get_hints_from_django_field(
field: StrawberryField,
field_definition: GraphQLObjectType,
field_selection: FieldNode,
model: type[models.Model],
schema: Schema,
*,
config: OptimizerConfig,
parent_type: GraphQLObjectType | GraphQLInterfaceType,
field_info: GraphQLResolveInfo,
prefix: str = "",
cache: dict[type[models.Model], list[tuple[int, OptimizerStore]]],
level: int = 0,
) -> OptimizerStore | None:
try:
from django.contrib.contenttypes.fields import (
GenericForeignKey,
GenericRelation,
)
except (ImportError, RuntimeError): # pragma: no cover
GenericForeignKey = None # noqa: N806
GenericRelation = None # noqa: N806
relation_fields = (models.ManyToManyField, ManyToManyRel, ManyToOneRel)
else:
relation_fields = (
models.ManyToManyField,
ManyToManyRel,
ManyToOneRel,
GenericRelation,
)
# If the field has a base resolver, don't try to optimize it. The user should
# be defining custom hints in this case, which should already be in the store
# GlobalID and special cases setting `can_optimize` are ok though, as those resolvers
# are auto generated by us
if (
field.base_resolver is not None
and field.type != relay.GlobalID
and not getattr(field.base_resolver.wrapped_func, "can_optimize", False)
):
return None
model_fieldname: str = getattr(field, "django_name", None) or field.python_name
if (model_field := get_model_field(model, model_fieldname)) is None:
return None
path = f"{prefix}{model_fieldname}"
if isinstance(model_field, (models.ForeignKey, OneToOneRel)):
store = _get_hints_from_django_foreign_key(
field,
field_definition=field_definition,
field_selection=field_selection,
model_field=model_field,
model_fieldname=model_fieldname,
schema=schema,
config=config,
parent_type=parent_type,
field_info=field_info,
path=path,
cache=cache,
level=level,
)
elif GenericForeignKey and isinstance(model_field, GenericForeignKey):
# There's not much we can do to optimize generic foreign keys regarding
# only/select_related because they can be anything.
# Just prefetch_related them