summaryrefslogtreecommitdiff
path: root/venv/lib/python3.11/site-packages/sqlalchemy/orm/interfaces.py
blob: 36336e7a2c2c6fd99c166a4a2305847baa88efcd (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
# orm/interfaces.py
# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php

"""

Contains various base classes used throughout the ORM.

Defines some key base classes prominent within the internals.

This module and the classes within are mostly private, though some attributes
are exposed when inspecting mappings.

"""

from __future__ import annotations

import collections
import dataclasses
import typing
from typing import Any
from typing import Callable
from typing import cast
from typing import ClassVar
from typing import Dict
from typing import Generic
from typing import Iterator
from typing import List
from typing import NamedTuple
from typing import NoReturn
from typing import Optional
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union

from . import exc as orm_exc
from . import path_registry
from .base import _MappedAttribute as _MappedAttribute
from .base import EXT_CONTINUE as EXT_CONTINUE  # noqa: F401
from .base import EXT_SKIP as EXT_SKIP  # noqa: F401
from .base import EXT_STOP as EXT_STOP  # noqa: F401
from .base import InspectionAttr as InspectionAttr  # noqa: F401
from .base import InspectionAttrInfo as InspectionAttrInfo
from .base import MANYTOMANY as MANYTOMANY  # noqa: F401
from .base import MANYTOONE as MANYTOONE  # noqa: F401
from .base import NO_KEY as NO_KEY  # noqa: F401
from .base import NO_VALUE as NO_VALUE  # noqa: F401
from .base import NotExtension as NotExtension  # noqa: F401
from .base import ONETOMANY as ONETOMANY  # noqa: F401
from .base import RelationshipDirection as RelationshipDirection  # noqa: F401
from .base import SQLORMOperations
from .. import ColumnElement
from .. import exc as sa_exc
from .. import inspection
from .. import util
from ..sql import operators
from ..sql import roles
from ..sql import visitors
from ..sql.base import _NoArg
from ..sql.base import ExecutableOption
from ..sql.cache_key import HasCacheKey
from ..sql.operators import ColumnOperators
from ..sql.schema import Column
from ..sql.type_api import TypeEngine
from ..util import warn_deprecated
from ..util.typing import RODescriptorReference
from ..util.typing import TypedDict

if typing.TYPE_CHECKING:
    from ._typing import _EntityType
    from ._typing import _IdentityKeyType
    from ._typing import _InstanceDict
    from ._typing import _InternalEntityType
    from ._typing import _ORMAdapterProto
    from .attributes import InstrumentedAttribute
    from .base import Mapped
    from .context import _MapperEntity
    from .context import ORMCompileState
    from .context import QueryContext
    from .decl_api import RegistryType
    from .decl_base import _ClassScanMapperConfig
    from .loading import _PopulatorDict
    from .mapper import Mapper
    from .path_registry import AbstractEntityRegistry
    from .query import Query
    from .session import Session
    from .state import InstanceState
    from .strategy_options import _LoadElement
    from .util import AliasedInsp
    from .util import ORMAdapter
    from ..engine.result import Result
    from ..sql._typing import _ColumnExpressionArgument
    from ..sql._typing import _ColumnsClauseArgument
    from ..sql._typing import _DMLColumnArgument
    from ..sql._typing import _InfoType
    from ..sql.operators import OperatorType
    from ..sql.visitors import _TraverseInternalsType
    from ..util.typing import _AnnotationScanType

_StrategyKey = Tuple[Any, ...]

_T = TypeVar("_T", bound=Any)
_T_co = TypeVar("_T_co", bound=Any, covariant=True)

_TLS = TypeVar("_TLS", bound="Type[LoaderStrategy]")


class ORMStatementRole(roles.StatementRole):
    __slots__ = ()
    _role_name = (
        "Executable SQL or text() construct, including ORM aware objects"
    )


class ORMColumnsClauseRole(
    roles.ColumnsClauseRole, roles.TypedColumnsClauseRole[_T]
):
    __slots__ = ()
    _role_name = "ORM mapped entity, aliased entity, or Column expression"


class ORMEntityColumnsClauseRole(ORMColumnsClauseRole[_T]):
    __slots__ = ()
    _role_name = "ORM mapped or aliased entity"


class ORMFromClauseRole(roles.StrictFromClauseRole):
    __slots__ = ()
    _role_name = "ORM mapped entity, aliased entity, or FROM expression"


class ORMColumnDescription(TypedDict):
    name: str
    # TODO: add python_type and sql_type here; combining them
    # into "type" is a bad idea
    type: Union[Type[Any], TypeEngine[Any]]
    aliased: bool
    expr: _ColumnsClauseArgument[Any]
    entity: Optional[_ColumnsClauseArgument[Any]]


class _IntrospectsAnnotations:
    __slots__ = ()

    @classmethod
    def _mapper_property_name(cls) -> str:
        return cls.__name__

    def found_in_pep593_annotated(self) -> Any:
        """return a copy of this object to use in declarative when the
        object is found inside of an Annotated object."""

        raise NotImplementedError(
            f"Use of the {self._mapper_property_name()!r} "
            "construct inside of an Annotated object is not yet supported."
        )

    def declarative_scan(
        self,
        decl_scan: _ClassScanMapperConfig,
        registry: RegistryType,
        cls: Type[Any],
        originating_module: Optional[str],
        key: str,
        mapped_container: Optional[Type[Mapped[Any]]],
        annotation: Optional[_AnnotationScanType],
        extracted_mapped_annotation: Optional[_AnnotationScanType],
        is_dataclass_field: bool,
    ) -> None:
        """Perform class-specific initializaton at early declarative scanning
        time.

        .. versionadded:: 2.0

        """

    def _raise_for_required(self, key: str, cls: Type[Any]) -> NoReturn:
        raise sa_exc.ArgumentError(
            f"Python typing annotation is required for attribute "
            f'"{cls.__name__}.{key}" when primary argument(s) for '
            f'"{self._mapper_property_name()}" '
            "construct are None or not present"
        )


class _AttributeOptions(NamedTuple):
    """define Python-local attribute behavior options common to all
    :class:`.MapperProperty` objects.

    Currently this includes dataclass-generation arguments.

    .. versionadded:: 2.0

    """

    dataclasses_init: Union[_NoArg, bool]
    dataclasses_repr: Union[_NoArg, bool]
    dataclasses_default: Union[_NoArg, Any]
    dataclasses_default_factory: Union[_NoArg, Callable[[], Any]]
    dataclasses_compare: Union[_NoArg, bool]
    dataclasses_kw_only: Union[_NoArg, bool]

    def _as_dataclass_field(self, key: str) -> Any:
        """Return a ``dataclasses.Field`` object given these arguments."""

        kw: Dict[str, Any] = {}
        if self.dataclasses_default_factory is not _NoArg.NO_ARG:
            kw["default_factory"] = self.dataclasses_default_factory
        if self.dataclasses_default is not _NoArg.NO_ARG:
            kw["default"] = self.dataclasses_default
        if self.dataclasses_init is not _NoArg.NO_ARG:
            kw["init"] = self.dataclasses_init
        if self.dataclasses_repr is not _NoArg.NO_ARG:
            kw["repr"] = self.dataclasses_repr
        if self.dataclasses_compare is not _NoArg.NO_ARG:
            kw["compare"] = self.dataclasses_compare
        if self.dataclasses_kw_only is not _NoArg.NO_ARG:
            kw["kw_only"] = self.dataclasses_kw_only

        if "default" in kw and callable(kw["default"]):
            # callable defaults are ambiguous. deprecate them in favour of
            # insert_default or default_factory. #9936
            warn_deprecated(
                f"Callable object passed to the ``default`` parameter for "
                f"attribute {key!r} in a ORM-mapped Dataclasses context is "
                "ambiguous, "
                "and this use will raise an error in a future release.  "
                "If this callable is intended to produce Core level INSERT "
                "default values for an underlying ``Column``, use "
                "the ``mapped_column.insert_default`` parameter instead.  "
                "To establish this callable as providing a default value "
                "for instances of the dataclass itself, use the "
                "``default_factory`` dataclasses parameter.",
                "2.0",
            )

        if (
            "init" in kw
            and not kw["init"]
            and "default" in kw
            and not callable(kw["default"])  # ignore callable defaults. #9936
            and "default_factory" not in kw  # illegal but let dc.field raise
        ):
            # fix for #9879
            default = kw.pop("default")
            kw["default_factory"] = lambda: default

        return dataclasses.field(**kw)

    @classmethod
    def _get_arguments_for_make_dataclass(
        cls,
        key: str,
        annotation: _AnnotationScanType,
        mapped_container: Optional[Any],
        elem: _T,
    ) -> Union[
        Tuple[str, _AnnotationScanType],
        Tuple[str, _AnnotationScanType, dataclasses.Field[Any]],
    ]:
        """given attribute key, annotation, and value from a class, return
        the argument tuple we would pass to dataclasses.make_dataclass()
        for this attribute.

        """
        if isinstance(elem, _DCAttributeOptions):
            dc_field = elem._attribute_options._as_dataclass_field(key)

            return (key, annotation, dc_field)
        elif elem is not _NoArg.NO_ARG:
            # why is typing not erroring on this?
            return (key, annotation, elem)
        elif mapped_container is not None:
            # it's Mapped[], but there's no "element", which means declarative
            # did not actually do anything for this field.  this shouldn't
            # happen.
            # previously, this would occur because _scan_attributes would
            # skip a field that's on an already mapped superclass, but it
            # would still include it in the annotations, leading
            # to issue #8718

            assert False, "Mapped[] received without a mapping declaration"

        else:
            # plain dataclass field, not mapped.  Is only possible
            # if __allow_unmapped__ is set up.  I can see this mode causing
            # problems...
            return (key, annotation)


_DEFAULT_ATTRIBUTE_OPTIONS = _AttributeOptions(
    _NoArg.NO_ARG,
    _NoArg.NO_ARG,
    _NoArg.NO_ARG,
    _NoArg.NO_ARG,
    _NoArg.NO_ARG,
    _NoArg.NO_ARG,
)

_DEFAULT_READONLY_ATTRIBUTE_OPTIONS = _AttributeOptions(
    False,
    _NoArg.NO_ARG,
    _NoArg.NO_ARG,
    _NoArg.NO_ARG,
    _NoArg.NO_ARG,
    _NoArg.NO_ARG,
)


class _DCAttributeOptions:
    """mixin for descriptors or configurational objects that include dataclass
    field options.

    This includes :class:`.MapperProperty`, :class:`._MapsColumn` within
    the ORM, but also includes :class:`.AssociationProxy` within ext.
    Can in theory be used for other descriptors that serve a similar role
    as association proxy.   (*maybe* hybrids, not sure yet.)

    """

    __slots__ = ()

    _attribute_options: _AttributeOptions
    """behavioral options for ORM-enabled Python attributes

    .. versionadded:: 2.0

    """

    _has_dataclass_arguments: bool


class _MapsColumns(_DCAttributeOptions, _MappedAttribute[_T]):
    """interface for declarative-capable construct that delivers one or more
    Column objects to the declarative process to be part of a Table.
    """

    __slots__ = ()

    @property
    def mapper_property_to_assign(self) -> Optional[MapperProperty[_T]]:
        """return a MapperProperty to be assigned to the declarative mapping"""
        raise NotImplementedError()

    @property
    def columns_to_assign(self) -> List[Tuple[Column[_T], int]]:
        """A list of Column objects that should be declaratively added to the
        new Table object.

        """
        raise NotImplementedError()


# NOTE: MapperProperty needs to extend _MappedAttribute so that declarative
# typing works, i.e. "Mapped[A] = relationship()".   This introduces an
# inconvenience which is that all the MapperProperty objects are treated
# as descriptors by typing tools, which are misled by this as assignment /
# access to a descriptor attribute wants to move through __get__.
# Therefore, references to MapperProperty as an instance variable, such
# as in PropComparator, may have some special typing workarounds such as the
# use of sqlalchemy.util.typing.DescriptorReference to avoid mis-interpretation
# by typing tools
@inspection._self_inspects
class MapperProperty(
    HasCacheKey,
    _DCAttributeOptions,
    _MappedAttribute[_T],
    InspectionAttrInfo,
    util.MemoizedSlots,
):
    """Represent a particular class attribute mapped by :class:`_orm.Mapper`.

    The most common occurrences of :class:`.MapperProperty` are the
    mapped :class:`_schema.Column`, which is represented in a mapping as
    an instance of :class:`.ColumnProperty`,
    and a reference to another class produced by :func:`_orm.relationship`,
    represented in the mapping as an instance of
    :class:`.Relationship`.

    """

    __slots__ = (
        "_configure_started",
        "_configure_finished",
        "_attribute_options",
        "_has_dataclass_arguments",
        "parent",
        "key",
        "info",
        "doc",
    )

    _cache_key_traversal: _TraverseInternalsType = [
        ("parent", visitors.ExtendedInternalTraversal.dp_has_cache_key),
        ("key", visitors.ExtendedInternalTraversal.dp_string),
    ]

    if not TYPE_CHECKING:
        cascade = None

    is_property = True
    """Part of the InspectionAttr interface; states this object is a
    mapper property.

    """

    comparator: PropComparator[_T]
    """The :class:`_orm.PropComparator` instance that implements SQL
    expression construction on behalf of this mapped attribute."""

    key: str
    """name of class attribute"""

    parent: Mapper[Any]
    """the :class:`.Mapper` managing this property."""

    _is_relationship = False

    _links_to_entity: bool
    """True if this MapperProperty refers to a mapped entity.

    Should only be True for Relationship, False for all others.

    """

    doc: Optional[str]
    """optional documentation string"""

    info: _InfoType
    """Info dictionary associated with the object, allowing user-defined
    data to be associated with this :class:`.InspectionAttr`.

    The dictionary is generated when first accessed.  Alternatively,
    it can be specified as a constructor argument to the
    :func:`.column_property`, :func:`_orm.relationship`, or :func:`.composite`
    functions.

    .. seealso::

        :attr:`.QueryableAttribute.info`

        :attr:`.SchemaItem.info`

    """

    def _memoized_attr_info(self) -> _InfoType:
        """Info dictionary associated with the object, allowing user-defined
        data to be associated with this :class:`.InspectionAttr`.

        The dictionary is generated when first accessed.  Alternatively,
        it can be specified as a constructor argument to the
        :func:`.column_property`, :func:`_orm.relationship`, or
        :func:`.composite`
        functions.

        .. seealso::

            :attr:`.QueryableAttribute.info`

            :attr:`.SchemaItem.info`

        """
        return {}

    def setup(
        self,
        context: ORMCompileState,
        query_entity: _MapperEntity,
        path: AbstractEntityRegistry,
        adapter: Optional[ORMAdapter],
        **kwargs: Any,
    ) -> None:
        """Called by Query for the purposes of constructing a SQL statement.

        Each MapperProperty associated with the target mapper processes the
        statement referenced by the query context, adding columns and/or
        criterion as appropriate.

        """

    def create_row_processor(
        self,
        context: ORMCompileState,
        query_entity: _MapperEntity,
        path: AbstractEntityRegistry,
        mapper: Mapper[Any],
        result: Result[Any],
        adapter: Optional[ORMAdapter],
        populators: _PopulatorDict,
    ) -> None:
        """Produce row processing functions and append to the given
        set of populators lists.

        """

    def cascade_iterator(
        self,
        type_: str,
        state: InstanceState[Any],
        dict_: _InstanceDict,
        visited_states: Set[InstanceState[Any]],
        halt_on: Optional[Callable[[InstanceState[Any]], bool]] = None,
    ) -> Iterator[
        Tuple[object, Mapper[Any], InstanceState[Any], _InstanceDict]
    ]:
        """Iterate through instances related to the given instance for
        a particular 'cascade', starting with this MapperProperty.

        Return an iterator3-tuples (instance, mapper, state).

        Note that the 'cascade' collection on this MapperProperty is
        checked first for the given type before cascade_iterator is called.

        This method typically only applies to Relationship.

        """

        return iter(())

    def set_parent(self, parent: Mapper[Any], init: bool) -> None:
        """Set the parent mapper that references this MapperProperty.

        This method is overridden by some subclasses to perform extra
        setup when the mapper is first known.

        """
        self.parent = parent

    def instrument_class(self, mapper: Mapper[Any]) -> None:
        """Hook called by the Mapper to the property to initiate
        instrumentation of the class attribute managed by this
        MapperProperty.

        The MapperProperty here will typically call out to the
        attributes module to set up an InstrumentedAttribute.

        This step is the first of two steps to set up an InstrumentedAttribute,
        and is called early in the mapper setup process.

        The second step is typically the init_class_attribute step,
        called from StrategizedProperty via the post_instrument_class()
        hook.  This step assigns additional state to the InstrumentedAttribute
        (specifically the "impl") which has been determined after the
        MapperProperty has determined what kind of persistence
        management it needs to do (e.g. scalar, object, collection, etc).

        """

    def __init__(
        self,
        attribute_options: Optional[_AttributeOptions] = None,
        _assume_readonly_dc_attributes: bool = False,
    ) -> None:
        self._configure_started = False
        self._configure_finished = False

        if _assume_readonly_dc_attributes:
            default_attrs = _DEFAULT_READONLY_ATTRIBUTE_OPTIONS
        else:
            default_attrs = _DEFAULT_ATTRIBUTE_OPTIONS

        if attribute_options and attribute_options != default_attrs:
            self._has_dataclass_arguments = True
            self._attribute_options = attribute_options
        else:
            self._has_dataclass_arguments = False
            self._attribute_options = default_attrs

    def init(self) -> None:
        """Called after all mappers are created to assemble
        relationships between mappers and perform other post-mapper-creation
        initialization steps.


        """
        self._configure_started = True
        self.do_init()
        self._configure_finished = True

    @property
    def class_attribute(self) -> InstrumentedAttribute[_T]:
        """Return the class-bound descriptor corresponding to this
        :class:`.MapperProperty`.

        This is basically a ``getattr()`` call::

            return getattr(self.parent.class_, self.key)

        I.e. if this :class:`.MapperProperty` were named ``addresses``,
        and the class to which it is mapped is ``User``, this sequence
        is possible::

            >>> from sqlalchemy import inspect
            >>> mapper = inspect(User)
            >>> addresses_property = mapper.attrs.addresses
            >>> addresses_property.class_attribute is User.addresses
            True
            >>> User.addresses.property is addresses_property
            True


        """

        return getattr(self.parent.class_, self.key)  # type: ignore

    def do_init(self) -> None:
        """Perform subclass-specific initialization post-mapper-creation
        steps.

        This is a template method called by the ``MapperProperty``
        object's init() method.

        """

    def post_instrument_class(self, mapper: Mapper[Any]) -> None:
        """Perform instrumentation adjustments that need to occur
        after init() has completed.

        The given Mapper is the Mapper invoking the operation, which
        may not be the same Mapper as self.parent in an inheritance
        scenario; however, Mapper will always at least be a sub-mapper of
        self.parent.

        This method is typically used by StrategizedProperty, which delegates
        it to LoaderStrategy.init_class_attribute() to perform final setup
        on the class-bound InstrumentedAttribute.

        """

    def merge(
        self,
        session: Session,
        source_state: InstanceState[Any],
        source_dict: _InstanceDict,
        dest_state: InstanceState[Any],
        dest_dict: _InstanceDict,
        load: bool,
        _recursive: Dict[Any, object],
        _resolve_conflict_map: Dict[_IdentityKeyType[Any], object],
    ) -> None:
        """Merge the attribute represented by this ``MapperProperty``
        from source to destination object.

        """

    def __repr__(self) -> str:
        return "<%s at 0x%x; %s>" % (
            self.__class__.__name__,
            id(self),
            getattr(self, "key", "no key"),
        )


@inspection._self_inspects
class PropComparator(SQLORMOperations[_T_co], Generic[_T_co], ColumnOperators):
    r"""Defines SQL operations for ORM mapped attributes.

    SQLAlchemy allows for operators to
    be redefined at both the Core and ORM level.  :class:`.PropComparator`
    is the base class of operator redefinition for ORM-level operations,
    including those of :class:`.ColumnProperty`,
    :class:`.Relationship`, and :class:`.Composite`.

    User-defined subclasses of :class:`.PropComparator` may be created. The
    built-in Python comparison and math operator methods, such as
    :meth:`.operators.ColumnOperators.__eq__`,
    :meth:`.operators.ColumnOperators.__lt__`, and
    :meth:`.operators.ColumnOperators.__add__`, can be overridden to provide
    new operator behavior. The custom :class:`.PropComparator` is passed to
    the :class:`.MapperProperty` instance via the ``comparator_factory``
    argument. In each case,
    the appropriate subclass of :class:`.PropComparator` should be used::

        # definition of custom PropComparator subclasses

        from sqlalchemy.orm.properties import \
                                ColumnProperty,\
                                Composite,\
                                Relationship

        class MyColumnComparator(ColumnProperty.Comparator):
            def __eq__(self, other):
                return self.__clause_element__() == other

        class MyRelationshipComparator(Relationship.Comparator):
            def any(self, expression):
                "define the 'any' operation"
                # ...

        class MyCompositeComparator(Composite.Comparator):
            def __gt__(self, other):
                "redefine the 'greater than' operation"

                return sql.and_(*[a>b for a, b in
                                  zip(self.__clause_element__().clauses,
                                      other.__composite_values__())])


        # application of custom PropComparator subclasses

        from sqlalchemy.orm import column_property, relationship, composite
        from sqlalchemy import Column, String

        class SomeMappedClass(Base):
            some_column = column_property(Column("some_column", String),
                                comparator_factory=MyColumnComparator)

            some_relationship = relationship(SomeOtherClass,
                                comparator_factory=MyRelationshipComparator)

            some_composite = composite(
                    Column("a", String), Column("b", String),
                    comparator_factory=MyCompositeComparator
                )

    Note that for column-level operator redefinition, it's usually
    simpler to define the operators at the Core level, using the
    :attr:`.TypeEngine.comparator_factory` attribute.  See
    :ref:`types_operators` for more detail.

    .. seealso::

        :class:`.ColumnProperty.Comparator`

        :class:`.Relationship.Comparator`

        :class:`.Composite.Comparator`

        :class:`.ColumnOperators`

        :ref:`types_operators`

        :attr:`.TypeEngine.comparator_factory`

    """

    __slots__ = "prop", "_parententity", "_adapt_to_entity"

    __visit_name__ = "orm_prop_comparator"

    _parententity: _InternalEntityType[Any]
    _adapt_to_entity: Optional[AliasedInsp[Any]]
    prop: RODescriptorReference[MapperProperty[_T_co]]

    def __init__(
        self,
        prop: MapperProperty[_T],
        parentmapper: _InternalEntityType[Any],
        adapt_to_entity: Optional[AliasedInsp[Any]] = None,
    ):
        self.prop = prop
        self._parententity = adapt_to_entity or parentmapper
        self._adapt_to_entity = adapt_to_entity

    @util.non_memoized_property
    def property(self) -> MapperProperty[_T_co]:
        """Return the :class:`.MapperProperty` associated with this
        :class:`.PropComparator`.


        Return values here will commonly be instances of
        :class:`.ColumnProperty` or :class:`.Relationship`.


        """
        return self.prop

    def __clause_element__(self) -> roles.ColumnsClauseRole:
        raise NotImplementedError("%r" % self)

    def _bulk_update_tuples(
        self, value: Any
    ) -> Sequence[Tuple[_DMLColumnArgument, Any]]:
        """Receive a SQL expression that represents a value in the SET
        clause of an UPDATE statement.

        Return a tuple that can be passed to a :class:`_expression.Update`
        construct.

        """

        return [(cast("_DMLColumnArgument", self.__clause_element__()), value)]

    def adapt_to_entity(
        self, adapt_to_entity: AliasedInsp[Any]
    ) -> PropComparator[_T_co]:
        """Return a copy of this PropComparator which will use the given
        :class:`.AliasedInsp` to produce corresponding expressions.
        """
        return self.__class__(self.prop, self._parententity, adapt_to_entity)

    @util.ro_non_memoized_property
    def _parentmapper(self) -> Mapper[Any]:
        """legacy; this is renamed to _parententity to be
        compatible with QueryableAttribute."""
        return self._parententity.mapper

    def _criterion_exists(
        self,
        criterion: Optional[_ColumnExpressionArgument[bool]] = None,
        **kwargs: Any,
    ) -> ColumnElement[Any]:
        return self.prop.comparator._criterion_exists(criterion, **kwargs)

    @util.ro_non_memoized_property
    def adapter(self) -> Optional[_ORMAdapterProto]:
        """Produce a callable that adapts column expressions
        to suit an aliased version of this comparator.

        """
        if self._adapt_to_entity is None:
            return None
        else:
            return self._adapt_to_entity._orm_adapt_element

    @util.ro_non_memoized_property
    def info(self) -> _InfoType:
        return self.prop.info

    @staticmethod
    def _any_op(a: Any, b: Any, **kwargs: Any) -> Any:
        return a.any(b, **kwargs)

    @staticmethod
    def _has_op(left: Any, other: Any, **kwargs: Any) -> Any:
        return left.has(other, **kwargs)

    @staticmethod
    def _of_type_op(a: Any, class_: Any) -> Any:
        return a.of_type(class_)

    any_op = cast(operators.OperatorType, _any_op)
    has_op = cast(operators.OperatorType, _has_op)
    of_type_op = cast(operators.OperatorType, _of_type_op)

    if typing.TYPE_CHECKING:

        def operate(
            self, op: OperatorType, *other: Any, **kwargs: Any
        ) -> ColumnElement[Any]: ...

        def reverse_operate(
            self, op: OperatorType, other: Any, **kwargs: Any
        ) -> ColumnElement[Any]: ...

    def of_type(self, class_: _EntityType[Any]) -> PropComparator[_T_co]:
        r"""Redefine this object in terms of a polymorphic subclass,
        :func:`_orm.with_polymorphic` construct, or :func:`_orm.aliased`
        construct.

        Returns a new PropComparator from which further criterion can be
        evaluated.

        e.g.::

            query.join(Company.employees.of_type(Engineer)).\
               filter(Engineer.name=='foo')

        :param \class_: a class or mapper indicating that criterion will be
            against this specific subclass.

        .. seealso::

            :ref:`orm_queryguide_joining_relationships_aliased` - in the
            :ref:`queryguide_toplevel`

            :ref:`inheritance_of_type`

        """

        return self.operate(PropComparator.of_type_op, class_)  # type: ignore

    def and_(
        self, *criteria: _ColumnExpressionArgument[bool]
    ) -> PropComparator[bool]:
        """Add additional criteria to the ON clause that's represented by this
        relationship attribute.

        E.g.::


            stmt = select(User).join(
                User.addresses.and_(Address.email_address != 'foo')
            )

            stmt = select(User).options(
                joinedload(User.addresses.and_(Address.email_address != 'foo'))
            )

        .. versionadded:: 1.4

        .. seealso::

            :ref:`orm_queryguide_join_on_augmented`

            :ref:`loader_option_criteria`

            :func:`.with_loader_criteria`

        """
        return self.operate(operators.and_, *criteria)  # type: ignore

    def any(
        self,
        criterion: Optional[_ColumnExpressionArgument[bool]] = None,
        **kwargs: Any,
    ) -> ColumnElement[bool]:
        r"""Return a SQL expression representing true if this element
        references a member which meets the given criterion.

        The usual implementation of ``any()`` is
        :meth:`.Relationship.Comparator.any`.

        :param criterion: an optional ClauseElement formulated against the
          member class' table or attributes.

        :param \**kwargs: key/value pairs corresponding to member class
          attribute names which will be compared via equality to the
          corresponding values.

        """

        return self.operate(PropComparator.any_op, criterion, **kwargs)

    def has(
        self,
        criterion: Optional[_ColumnExpressionArgument[bool]] = None,
        **kwargs: Any,
    ) -> ColumnElement[bool]:
        r"""Return a SQL expression representing true if this element
        references a member which meets the given criterion.

        The usual implementation of ``has()`` is
        :meth:`.Relationship.Comparator.has`.

        :param criterion: an optional ClauseElement formulated against the
          member class' table or attributes.

        :param \**kwargs: key/value pairs corresponding to member class
          attribute names which will be compared via equality to the
          corresponding values.

        """

        return self.operate(PropComparator.has_op, criterion, **kwargs)


class StrategizedProperty(MapperProperty[_T]):
    """A MapperProperty which uses selectable strategies to affect
    loading behavior.

    There is a single strategy selected by default.  Alternate
    strategies can be selected at Query time through the usage of
    ``StrategizedOption`` objects via the Query.options() method.

    The mechanics of StrategizedProperty are used for every Query
    invocation for every mapped attribute participating in that Query,
    to determine first how the attribute will be rendered in SQL
    and secondly how the attribute will retrieve a value from a result
    row and apply it to a mapped object.  The routines here are very
    performance-critical.

    """

    __slots__ = (
        "_strategies",
        "strategy",
        "_wildcard_token",
        "_default_path_loader_key",
        "strategy_key",
    )
    inherit_cache = True
    strategy_wildcard_key: ClassVar[str]

    strategy_key: _StrategyKey

    _strategies: Dict[_StrategyKey, LoaderStrategy]

    def _memoized_attr__wildcard_token(self) -> Tuple[str]:
        return (
            f"{self.strategy_wildcard_key}:{path_registry._WILDCARD_TOKEN}",
        )

    def _memoized_attr__default_path_loader_key(
        self,
    ) -> Tuple[str, Tuple[str]]:
        return (
            "loader",
            (f"{self.strategy_wildcard_key}:{path_registry._DEFAULT_TOKEN}",),
        )

    def _get_context_loader(
        self, context: ORMCompileState, path: AbstractEntityRegistry
    ) -> Optional[_LoadElement]:
        load: Optional[_LoadElement] = None

        search_path = path[self]

        # search among: exact match, "attr.*", "default" strategy
        # if any.
        for path_key in (
            search_path._loader_key,
            search_path._wildcard_path_loader_key,
            search_path._default_path_loader_key,
        ):
            if path_key in context.attributes:
                load = context.attributes[path_key]
                break

                # note that if strategy_options.Load is placing non-actionable
                # objects in the context like defaultload(), we would
                # need to continue the loop here if we got such an
                # option as below.
                # if load.strategy or load.local_opts:
                #    break

        return load

    def _get_strategy(self, key: _StrategyKey) -> LoaderStrategy:
        try:
            return self._strategies[key]
        except KeyError:
            pass

        # run outside to prevent transfer of exception context
        cls = self._strategy_lookup(self, *key)
        # this previously was setting self._strategies[cls], that's
        # a bad idea; should use strategy key at all times because every
        # strategy has multiple keys at this point
        self._strategies[key] = strategy = cls(self, key)
        return strategy

    def setup(
        self,
        context: ORMCompileState,
        query_entity: _MapperEntity,
        path: AbstractEntityRegistry,
        adapter: Optional[ORMAdapter],
        **kwargs: Any,
    ) -> None:
        loader = self._get_context_loader(context, path)
        if loader and loader.strategy:
            strat = self._get_strategy(loader.strategy)
        else:
            strat = self.strategy
        strat.setup_query(
            context, query_entity, path, loader, adapter, **kwargs
        )

    def create_row_processor(
        self,
        context: ORMCompileState,
        query_entity: _MapperEntity,
        path: AbstractEntityRegistry,
        mapper: Mapper[Any],
        result: Result[Any],
        adapter: Optional[ORMAdapter],
        populators: _PopulatorDict,
    ) -> None:
        loader = self._get_context_loader(context, path)
        if loader and loader.strategy:
            strat = self._get_strategy(loader.strategy)
        else:
            strat = self.strategy
        strat.create_row_processor(
            context,
            query_entity,
            path,
            loader,
            mapper,
            result,
            adapter,
            populators,
        )

    def do_init(self) -> None:
        self._strategies = {}
        self.strategy = self._get_strategy(self.strategy_key)

    def post_instrument_class(self, mapper: Mapper[Any]) -> None:
        if (
            not self.parent.non_primary
            and not mapper.class_manager._attr_has_impl(self.key)
        ):
            self.strategy.init_class_attribute(mapper)

    _all_strategies: collections.defaultdict[
        Type[MapperProperty[Any]], Dict[_StrategyKey, Type[LoaderStrategy]]
    ] = collections.defaultdict(dict)

    @classmethod
    def strategy_for(cls, **kw: Any) -> Callable[[_TLS], _TLS]:
        def decorate(dec_cls: _TLS) -> _TLS:
            # ensure each subclass of the strategy has its
            # own _strategy_keys collection
            if "_strategy_keys" not in dec_cls.__dict__:
                dec_cls._strategy_keys = []
            key = tuple(sorted(kw.items()))
            cls._all_strategies[cls][key] = dec_cls
            dec_cls._strategy_keys.append(key)
            return dec_cls

        return decorate

    @classmethod
    def _strategy_lookup(
        cls, requesting_property: MapperProperty[Any], *key: Any
    ) -> Type[LoaderStrategy]:
        requesting_property.parent._with_polymorphic_mappers

        for prop_cls in cls.__mro__:
            if prop_cls in cls._all_strategies:
                if TYPE_CHECKING:
                    assert issubclass(prop_cls, MapperProperty)
                strategies = cls._all_strategies[prop_cls]
                try:
                    return strategies[key]
                except KeyError:
                    pass

        for property_type, strats in cls._all_strategies.items():
            if key in strats:
                intended_property_type = property_type
                actual_strategy = strats[key]
                break
        else:
            intended_property_type = None
            actual_strategy = None

        raise orm_exc.LoaderStrategyException(
            cls,
            requesting_property,
            intended_property_type,
            actual_strategy,
            key,
        )


class ORMOption(ExecutableOption):
    """Base class for option objects that are passed to ORM queries.

    These options may be consumed by :meth:`.Query.options`,
    :meth:`.Select.options`, or in a more general sense by any
    :meth:`.Executable.options` method.   They are interpreted at
    statement compile time or execution time in modern use.  The
    deprecated :class:`.MapperOption` is consumed at ORM query construction
    time.

    .. versionadded:: 1.4

    """

    __slots__ = ()

    _is_legacy_option = False

    propagate_to_loaders = False
    """if True, indicate this option should be carried along
    to "secondary" SELECT statements that occur for relationship
    lazy loaders as well as attribute load / refresh operations.

    """

    _is_core = False

    _is_user_defined = False

    _is_compile_state = False

    _is_criteria_option = False

    _is_strategy_option = False

    def _adapt_cached_option_to_uncached_option(
        self, context: QueryContext, uncached_opt: ORMOption
    ) -> ORMOption:
        """adapt this option to the "uncached" version of itself in a
        loader strategy context.

        given "self" which is an option from a cached query, as well as the
        corresponding option from the uncached version of the same query,
        return the option we should use in a new query, in the context of a
        loader strategy being asked to load related rows on behalf of that
        cached query, which is assumed to be building a new query based on
        entities passed to us from the cached query.

        Currently this routine chooses between "self" and "uncached" without
        manufacturing anything new. If the option is itself a loader strategy
        option which has a path, that path needs to match to the entities being
        passed to us by the cached query, so the :class:`_orm.Load` subclass
        overrides this to return "self". For all other options, we return the
        uncached form which may have changing state, such as a
        with_loader_criteria() option which will very often have new state.

        This routine could in the future involve
        generating a new option based on both inputs if use cases arise,
        such as if with_loader_criteria() needed to match up to
        ``AliasedClass`` instances given in the parent query.

        However, longer term it might be better to restructure things such that
        ``AliasedClass`` entities are always matched up on their cache key,
        instead of identity, in things like paths and such, so that this whole
        issue of "the uncached option does not match the entities" goes away.
        However this would make ``PathRegistry`` more complicated and difficult
        to debug as well as potentially less performant in that it would be
        hashing enormous cache keys rather than a simple AliasedInsp. UNLESS,
        we could get cache keys overall to be reliably hashed into something
        like an md5 key.

        .. versionadded:: 1.4.41

        """
        if uncached_opt is not None:
            return uncached_opt
        else:
            return self


class CompileStateOption(HasCacheKey, ORMOption):
    """base for :class:`.ORMOption` classes that affect the compilation of
    a SQL query and therefore need to be part of the cache key.

    .. note::  :class:`.CompileStateOption` is generally non-public and
       should not be used as a base class for user-defined options; instead,
       use :class:`.UserDefinedOption`, which is easier to use as it does not
       interact with ORM compilation internals or caching.

    :class:`.CompileStateOption` defines an internal attribute
    ``_is_compile_state=True`` which has the effect of the ORM compilation
    routines for SELECT and other statements will call upon these options when
    a SQL string is being compiled. As such, these classes implement
    :class:`.HasCacheKey` and need to provide robust ``_cache_key_traversal``
    structures.

    The :class:`.CompileStateOption` class is used to implement the ORM
    :class:`.LoaderOption` and :class:`.CriteriaOption` classes.

    .. versionadded:: 1.4.28


    """

    __slots__ = ()

    _is_compile_state = True

    def process_compile_state(self, compile_state: ORMCompileState) -> None:
        """Apply a modification to a given :class:`.ORMCompileState`.

        This method is part of the implementation of a particular
        :class:`.CompileStateOption` and is only invoked internally
        when an ORM query is compiled.

        """

    def process_compile_state_replaced_entities(
        self,
        compile_state: ORMCompileState,
        mapper_entities: Sequence[_MapperEntity],
    ) -> None:
        """Apply a modification to a given :class:`.ORMCompileState`,
        given entities that were replaced by with_only_columns() or
        with_entities().

        This method is part of the implementation of a particular
        :class:`.CompileStateOption` and is only invoked internally
        when an ORM query is compiled.

        .. versionadded:: 1.4.19

        """


class LoaderOption(CompileStateOption):
    """Describe a loader modification to an ORM statement at compilation time.

    .. versionadded:: 1.4

    """

    __slots__ = ()

    def process_compile_state_replaced_entities(
        self,
        compile_state: ORMCompileState,
        mapper_entities: Sequence[_MapperEntity],
    ) -> None:
        self.process_compile_state(compile_state)


class CriteriaOption(CompileStateOption):
    """Describe a WHERE criteria modification to an ORM statement at
    compilation time.

    .. versionadded:: 1.4

    """

    __slots__ = ()

    _is_criteria_option = True

    def get_global_criteria(self, attributes: Dict[str, Any]) -> None:
        """update additional entity criteria options in the given
        attributes dictionary.

        """


class UserDefinedOption(ORMOption):
    """Base class for a user-defined option that can be consumed from the
    :meth:`.SessionEvents.do_orm_execute` event hook.

    """

    __slots__ = ("payload",)

    _is_legacy_option = False

    _is_user_defined = True

    propagate_to_loaders = False
    """if True, indicate this option should be carried along
    to "secondary" Query objects produced during lazy loads
    or refresh operations.

    """

    def __init__(self, payload: Optional[Any] = None):
        self.payload = payload


@util.deprecated_cls(
    "1.4",
    "The :class:`.MapperOption class is deprecated and will be removed "
    "in a future release.   For "
    "modifications to queries on a per-execution basis, use the "
    ":class:`.UserDefinedOption` class to establish state within a "
    ":class:`.Query` or other Core statement, then use the "
    ":meth:`.SessionEvents.before_orm_execute` hook to consume them.",
    constructor=None,
)
class MapperOption(ORMOption):
    """Describe a modification to a Query"""

    __slots__ = ()

    _is_legacy_option = True

    propagate_to_loaders = False
    """if True, indicate this option should be carried along
    to "secondary" Query objects produced during lazy loads
    or refresh operations.

    """

    def process_query(self, query: Query[Any]) -> None:
        """Apply a modification to the given :class:`_query.Query`."""

    def process_query_conditionally(self, query: Query[Any]) -> None:
        """same as process_query(), except that this option may not
        apply to the given query.

        This is typically applied during a lazy load or scalar refresh
        operation to propagate options stated in the original Query to the
        new Query being used for the load.  It occurs for those options that
        specify propagate_to_loaders=True.

        """

        self.process_query(query)


class LoaderStrategy:
    """Describe the loading behavior of a StrategizedProperty object.

    The ``LoaderStrategy`` interacts with the querying process in three
    ways:

    * it controls the configuration of the ``InstrumentedAttribute``
      placed on a class to handle the behavior of the attribute.  this
      may involve setting up class-level callable functions to fire
      off a select operation when the attribute is first accessed
      (i.e. a lazy load)

    * it processes the ``QueryContext`` at statement construction time,
      where it can modify the SQL statement that is being produced.
      For example, simple column attributes will add their represented
      column to the list of selected columns, a joined eager loader
      may establish join clauses to add to the statement.

    * It produces "row processor" functions at result fetching time.
      These "row processor" functions populate a particular attribute
      on a particular mapped instance.

    """

    __slots__ = (
        "parent_property",
        "is_class_level",
        "parent",
        "key",
        "strategy_key",
        "strategy_opts",
    )

    _strategy_keys: ClassVar[List[_StrategyKey]]

    def __init__(
        self, parent: MapperProperty[Any], strategy_key: _StrategyKey
    ):
        self.parent_property = parent
        self.is_class_level = False
        self.parent = self.parent_property.parent
        self.key = self.parent_property.key
        self.strategy_key = strategy_key
        self.strategy_opts = dict(strategy_key)

    def init_class_attribute(self, mapper: Mapper[Any]) -> None:
        pass

    def setup_query(
        self,
        compile_state: ORMCompileState,
        query_entity: _MapperEntity,
        path: AbstractEntityRegistry,
        loadopt: Optional[_LoadElement],
        adapter: Optional[ORMAdapter],
        **kwargs: Any,
    ) -> None:
        """Establish column and other state for a given QueryContext.

        This method fulfills the contract specified by MapperProperty.setup().

        StrategizedProperty delegates its setup() method
        directly to this method.

        """

    def create_row_processor(
        self,
        context: ORMCompileState,
        query_entity: _MapperEntity,
        path: AbstractEntityRegistry,
        loadopt: Optional[_LoadElement],
        mapper: Mapper[Any],
        result: Result[Any],
        adapter: Optional[ORMAdapter],
        populators: _PopulatorDict,
    ) -> None:
        """Establish row processing functions for a given QueryContext.

        This method fulfills the contract specified by
        MapperProperty.create_row_processor().

        StrategizedProperty delegates its create_row_processor() method
        directly to this method.

        """

    def __str__(self) -> str:
        return str(self.parent_property)