-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathdecl_base.py
More file actions
2309 lines (1960 loc) · 85.1 KB
/
decl_base.py
File metadata and controls
2309 lines (1960 loc) · 85.1 KB
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
# orm/decl_base.py
# Copyright (C) 2005-2026 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
"""Internal implementation for declarative."""
from __future__ import annotations
import collections
import dataclasses
import itertools
import re
from typing import Any
from typing import Callable
from typing import cast
from typing import Dict
from typing import get_args
from typing import Iterable
from typing import List
from typing import Mapping
from typing import NamedTuple
from typing import NoReturn
from typing import Optional
from typing import Protocol
from typing import Sequence
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union
import weakref
from . import attributes
from . import clsregistry
from . import exc as orm_exc
from . import instrumentation
from . import mapperlib
from ._typing import _O
from ._typing import attr_is_internal_proxy
from .attributes import InstrumentedAttribute
from .attributes import QueryableAttribute
from .base import _is_mapped_class
from .base import InspectionAttr
from .descriptor_props import CompositeProperty
from .descriptor_props import SynonymProperty
from .interfaces import _AttributeOptions
from .interfaces import _DataclassArguments
from .interfaces import _DCAttributeOptions
from .interfaces import _IntrospectsAnnotations
from .interfaces import _MappedAttribute
from .interfaces import _MapsColumns
from .interfaces import MapperProperty
from .mapper import Mapper
from .properties import ColumnProperty
from .properties import MappedColumn
from .util import _extract_mapped_subtype
from .util import _is_mapped_annotation
from .util import class_mapper
from .util import de_stringify_annotation
from .. import event
from .. import exc
from .. import util
from ..sql import expression
from ..sql._annotated_cols import TypedColumns
from ..sql.base import _NoArg
from ..sql.schema import Column
from ..sql.schema import Table
from ..util import topological
from ..util.typing import _AnnotationScanType
from ..util.typing import is_fwd_ref
from ..util.typing import is_literal
if TYPE_CHECKING:
from ._typing import _ClassDict
from ._typing import _RegistryType
from .base import Mapped
from .decl_api import declared_attr
from .instrumentation import ClassManager
from ..sql.elements import NamedColumn
from ..sql.schema import MetaData
from ..sql.selectable import FromClause
_T = TypeVar("_T", bound=Any)
_MapperKwArgs = Mapping[str, Any]
_TableArgsType = Union[Tuple[Any, ...], Dict[str, Any]]
class MappedClassProtocol(Protocol[_O]):
"""A protocol representing a SQLAlchemy mapped class.
The protocol is generic on the type of class, use
``MappedClassProtocol[Any]`` to allow any mapped class.
"""
__name__: str
__mapper__: Mapper[_O]
__table__: FromClause
def __call__(self, **kw: Any) -> _O: ...
class _DeclMappedClassProtocol(MappedClassProtocol[_O], Protocol):
"Internal more detailed version of ``MappedClassProtocol``."
metadata: MetaData
__tablename__: str
__mapper_args__: _MapperKwArgs
__table_args__: Optional[_TableArgsType]
_sa_apply_dc_transforms: Optional[_DataclassArguments]
def __declare_first__(self) -> None: ...
def __declare_last__(self) -> None: ...
def _declared_mapping_info(
cls: Type[Any],
) -> Optional[Union[_DeferredDeclarativeConfig, Mapper[Any]]]:
# deferred mapping
if _DeferredDeclarativeConfig.has_cls(cls):
return _DeferredDeclarativeConfig.config_for_cls(cls)
# regular mapping
elif _is_mapped_class(cls):
return class_mapper(cls, configure=False)
else:
return None
def _is_supercls_for_inherits(cls: Type[Any]) -> bool:
"""return True if this class will be used as a superclass to set in
'inherits'.
This includes deferred mapper configs that aren't mapped yet, however does
not include classes with _sa_decl_prepare_nocascade (e.g.
``AbstractConcreteBase``); these concrete-only classes are not set up as
"inherits" until after mappers are configured using
mapper._set_concrete_base()
"""
if _DeferredDeclarativeConfig.has_cls(cls):
return not _get_immediate_cls_attr(
cls, "_sa_decl_prepare_nocascade", strict=True
)
# regular mapping
elif _is_mapped_class(cls):
return True
else:
return False
def _resolve_for_abstract_or_classical(cls: Type[Any]) -> Optional[Type[Any]]:
if cls is object:
return None
sup: Optional[Type[Any]]
if cls.__dict__.get("__abstract__", False):
for base_ in cls.__bases__:
sup = _resolve_for_abstract_or_classical(base_)
if sup is not None:
return sup
else:
return None
else:
clsmanager = _dive_for_cls_manager(cls)
if clsmanager:
return clsmanager.class_
else:
return cls
def _get_immediate_cls_attr(
cls: Type[Any], attrname: str, strict: bool = False
) -> Optional[Any]:
"""return an attribute of the class that is either present directly
on the class, e.g. not on a superclass, or is from a superclass but
this superclass is a non-mapped mixin, that is, not a descendant of
the declarative base and is also not classically mapped.
This is used to detect attributes that indicate something about
a mapped class independently from any mapped classes that it may
inherit from.
"""
# the rules are different for this name than others,
# make sure we've moved it out. transitional
assert attrname != "__abstract__"
if not issubclass(cls, object):
return None
if attrname in cls.__dict__:
return getattr(cls, attrname)
for base in cls.__mro__[1:]:
_is_classical_inherits = _dive_for_cls_manager(base) is not None
if attrname in base.__dict__ and (
base is cls
or (
(base in cls.__bases__ if strict else True)
and not _is_classical_inherits
)
):
return getattr(base, attrname)
else:
return None
def _dive_for_cls_manager(cls: Type[_O]) -> Optional[ClassManager[_O]]:
# because the class manager registration is pluggable,
# we need to do the search for every class in the hierarchy,
# rather than just a simple "cls._sa_class_manager"
for base in cls.__mro__:
manager: Optional[ClassManager[_O]] = attributes.opt_manager_of_class(
base
)
if manager:
return manager
return None
@util.preload_module("sqlalchemy.orm.decl_api")
def _is_declarative_props(obj: Any) -> bool:
_declared_attr_common = util.preloaded.orm_decl_api._declared_attr_common
return isinstance(obj, (_declared_attr_common, util.classproperty))
def _check_declared_props_nocascade(
obj: Any, name: str, cls: Type[_O]
) -> bool:
if _is_declarative_props(obj):
if getattr(obj, "_cascading", False):
util.warn(
"@declared_attr.cascading is not supported on the %s "
"attribute on class %s. This attribute invokes for "
"subclasses in any case." % (name, cls)
)
return True
else:
return False
class _ORMClassConfigurator:
"""Object that configures a class that's potentially going to be
mapped, and/or turned into an ORM dataclass.
This is the base class for all the configurator objects.
"""
__slots__ = ("cls", "classname", "__weakref__")
cls: Type[Any]
classname: str
def __init__(self, cls_: Type[Any]):
self.cls = util.assert_arg_type(cls_, type, "cls_")
self.classname = cls_.__name__
@classmethod
def _as_declarative(
cls, registry: _RegistryType, cls_: Type[Any], dict_: _ClassDict
) -> Optional[_MapperConfig]:
manager = attributes.opt_manager_of_class(cls_)
if manager and manager.class_ is cls_:
raise exc.InvalidRequestError(
f"Class {cls_!r} already has been instrumented declaratively"
)
# allow subclassing an orm class with typed columns without
# generating an orm class
if cls_.__dict__.get("__abstract__", False) or issubclass(
cls_, TypedColumns
):
return None
defer_map = _get_immediate_cls_attr(
cls_, "_sa_decl_prepare_nocascade", strict=True
) or hasattr(cls_, "_sa_decl_prepare")
if defer_map:
return _DeferredDeclarativeConfig(registry, cls_, dict_)
else:
return _DeclarativeMapperConfig(registry, cls_, dict_)
@classmethod
def _as_unmapped_dataclass(
cls, cls_: Type[Any], dict_: _ClassDict
) -> _UnmappedDataclassConfig:
return _UnmappedDataclassConfig(cls_, dict_)
@classmethod
def _mapper(
cls,
registry: _RegistryType,
cls_: Type[_O],
table: Optional[FromClause],
mapper_kw: _MapperKwArgs,
) -> Mapper[_O]:
_ImperativeMapperConfig(registry, cls_, table, mapper_kw)
return cast("MappedClassProtocol[_O]", cls_).__mapper__
class _MapperConfig(_ORMClassConfigurator):
"""Configurator that configures a class that's potentially going to be
mapped, and optionally turned into a dataclass as well."""
__slots__ = (
"properties",
"declared_attr_reg",
)
properties: util.OrderedDict[
str,
Union[
Sequence[NamedColumn[Any]], NamedColumn[Any], MapperProperty[Any]
],
]
declared_attr_reg: Dict[declared_attr[Any], Any]
def __init__(
self,
registry: _RegistryType,
cls_: Type[Any],
):
super().__init__(cls_)
self.properties = util.OrderedDict()
self.declared_attr_reg = {}
instrumentation.register_class(
self.cls,
finalize=False,
registry=registry,
declarative_scan=self,
init_method=registry.constructor,
)
def set_cls_attribute(self, attrname: str, value: _T) -> _T:
manager = instrumentation.manager_of_class(self.cls)
manager.install_member(attrname, value)
return value
def map(self, mapper_kw: _MapperKwArgs) -> Mapper[Any]:
raise NotImplementedError()
def _early_mapping(self, mapper_kw: _MapperKwArgs) -> None:
self.map(mapper_kw)
class _ImperativeMapperConfig(_MapperConfig):
"""Configurator that configures a class for an imperative mapping."""
__slots__ = ("local_table", "inherits")
def __init__(
self,
registry: _RegistryType,
cls_: Type[_O],
table: Optional[FromClause],
mapper_kw: _MapperKwArgs,
):
super().__init__(registry, cls_)
self.local_table = self.set_cls_attribute("__table__", table)
with mapperlib._CONFIGURE_MUTEX:
clsregistry._add_class(
self.classname, self.cls, registry._class_registry
)
self._setup_inheritance(mapper_kw)
self._early_mapping(mapper_kw)
def map(self, mapper_kw: _MapperKwArgs = util.EMPTY_DICT) -> Mapper[Any]:
mapper_cls = Mapper
return self.set_cls_attribute(
"__mapper__",
mapper_cls(self.cls, self.local_table, **mapper_kw),
)
def _setup_inheritance(self, mapper_kw: _MapperKwArgs) -> None:
cls = self.cls
inherits = None
inherits_search = []
# since we search for classical mappings now, search for
# multiple mapped bases as well and raise an error.
for base_ in cls.__bases__:
c = _resolve_for_abstract_or_classical(base_)
if c is None:
continue
if _is_supercls_for_inherits(c) and c not in inherits_search:
inherits_search.append(c)
if inherits_search:
if len(inherits_search) > 1:
raise exc.InvalidRequestError(
"Class %s has multiple mapped bases: %r"
% (cls, inherits_search)
)
inherits = inherits_search[0]
self.inherits = inherits
class _CollectedAnnotation(NamedTuple):
raw_annotation: _AnnotationScanType
mapped_container: Optional[Type[Mapped[Any]]]
extracted_mapped_annotation: Union[_AnnotationScanType, str]
is_dataclass: bool
attr_value: Any
originating_module: str
originating_class: Type[Any]
class _ClassScanAbstractConfig(_ORMClassConfigurator):
"""Abstract base for a configurator that configures a class for a
declarative mapping, or an unmapped ORM dataclass.
Defines scanning of pep-484 annotations as well as ORM dataclass
applicators
"""
__slots__ = ()
clsdict_view: _ClassDict
collected_annotations: Dict[str, _CollectedAnnotation]
collected_attributes: Dict[str, Any]
is_dataclass_prior_to_mapping: bool
allow_unmapped_annotations: bool
dataclass_setup_arguments: Optional[_DataclassArguments]
"""if the class has SQLAlchemy native dataclass parameters, where
we will turn the class into a dataclass within the declarative mapping
process.
"""
allow_dataclass_fields: bool
"""if true, look for dataclass-processed Field objects on the target
class as well as superclasses and extract ORM mapping directives from
the "metadata" attribute of each Field.
if False, dataclass fields can still be used, however they won't be
mapped.
"""
_include_dunders = {
"__table__",
"__mapper_args__",
"__tablename__",
"__table_args__",
}
_match_exclude_dunders = re.compile(r"^(?:_sa_|__)")
def _scan_attributes(self) -> None:
raise NotImplementedError()
def _setup_dataclasses_transforms(
self, *, enable_descriptor_defaults: bool, revert: bool = False
) -> None:
dataclass_setup_arguments = self.dataclass_setup_arguments
if not dataclass_setup_arguments:
return
# can't use is_dataclass since it uses hasattr
if "__dataclass_fields__" in self.cls.__dict__:
raise exc.InvalidRequestError(
f"Class {self.cls} is already a dataclass; ensure that "
"base classes / decorator styles of establishing dataclasses "
"are not being mixed. "
"This can happen if a class that inherits from "
"'MappedAsDataclass', even indirectly, is been mapped with "
"'@registry.mapped_as_dataclass'"
)
# can't create a dataclass if __table__ is already there. This would
# fail an assertion when calling _get_arguments_for_make_dataclass:
# assert False, "Mapped[] received without a mapping declaration"
if "__table__" in self.cls.__dict__:
raise exc.InvalidRequestError(
f"Class {self.cls} already defines a '__table__'. "
"ORM Annotated Dataclasses do not support a pre-existing "
"'__table__' element"
)
raise_for_non_dc_attrs = collections.defaultdict(list)
def _allow_dataclass_field(
key: str, originating_class: Type[Any]
) -> bool:
if (
originating_class is not self.cls
and "__dataclass_fields__" not in originating_class.__dict__
):
raise_for_non_dc_attrs[originating_class].append(key)
return True
field_list = [
_AttributeOptions._get_arguments_for_make_dataclass(
self,
key,
anno,
mapped_container,
self.collected_attributes.get(key, _NoArg.NO_ARG),
dataclass_setup_arguments,
enable_descriptor_defaults,
)
for key, anno, mapped_container in (
(
key,
raw_anno,
mapped_container,
)
for key, (
raw_anno,
mapped_container,
mapped_anno,
is_dc,
attr_value,
originating_module,
originating_class,
) in self.collected_annotations.items()
if _allow_dataclass_field(key, originating_class)
and (
key not in self.collected_attributes
# issue #9226; check for attributes that we've collected
# which are already instrumented, which we would assume
# mean we are in an ORM inheritance mapping and this
# attribute is already mapped on the superclass. Under
# no circumstance should any QueryableAttribute be sent to
# the dataclass() function; anything that's mapped should
# be Field and that's it
or not isinstance(
self.collected_attributes[key], QueryableAttribute
)
)
)
]
if raise_for_non_dc_attrs:
for (
originating_class,
non_dc_attrs,
) in raise_for_non_dc_attrs.items():
raise exc.InvalidRequestError(
f"When transforming {self.cls} to a dataclass, "
f"attribute(s) "
f"{', '.join(repr(key) for key in non_dc_attrs)} "
f"originates from superclass "
f"{originating_class}, which is not a dataclass. When "
f"declaring SQLAlchemy Declarative "
f"Dataclasses, ensure that all mixin classes and other "
f"superclasses which include attributes are also a "
f"subclass of MappedAsDataclass or make use of the "
f"@unmapped_dataclass decorator.",
code="dcmx",
)
if revert:
# the "revert" case is used only by an unmapped mixin class
# that is nonetheless using Mapped construct and needs to
# itself be a dataclass
revert_dict = {
name: self.cls.__dict__[name]
for name in (item[0] for item in field_list)
if name in self.cls.__dict__
}
else:
revert_dict = None
# get original annotations using ForwardRef for symbols that
# are unresolvable
orig_annotations = util.get_annotations(self.cls)
# build a new __annotations__ dict from the fields we have.
# this has to be done carefully since we have to maintain
# the correct order! wow
swap_annotations = {}
defaults = {}
for item in field_list:
if len(item) == 2:
name, tp = item
elif len(item) == 3:
name, tp, spec = item
defaults[name] = spec
else:
assert False
# add the annotation to the new dict we are creating.
# note that if name is in orig_annotations, we expect
# tp and orig_annotations[name] to be identical.
swap_annotations[name] = orig_annotations.get(name, tp)
for k, v in defaults.items():
setattr(self.cls, k, v)
self._assert_dc_arguments(dataclass_setup_arguments)
dataclass_callable = dataclass_setup_arguments["dataclass_callable"]
if dataclass_callable is _NoArg.NO_ARG:
dataclass_callable = dataclasses.dataclass
# create a merged __annotations__ dictionary, maintaining order
# as best we can:
# 1. merge all keys in orig_annotations that occur before
# we see any of our mapped fields (this can be attributes like
# __table_args__ etc.)
new_annotations = {
k: orig_annotations[k]
for k in itertools.takewhile(
lambda k: k not in swap_annotations, orig_annotations
)
}
# 2. then put in all the dataclass annotations we have
new_annotations |= swap_annotations
# 3. them merge all of orig_annotations which will add remaining
# keys
new_annotations |= orig_annotations
# 4. this becomes the new class annotations.
restore_anno = util.restore_annotations(self.cls, new_annotations)
try:
dataclass_callable( # type: ignore[call-overload]
self.cls,
**{ # type: ignore[call-overload,unused-ignore]
k: v
for k, v in dataclass_setup_arguments.items()
if v is not _NoArg.NO_ARG
and k not in ("dataclass_callable",)
},
)
except (TypeError, ValueError) as ex:
raise exc.InvalidRequestError(
f"Python dataclasses error encountered when creating "
f"dataclass for {self.cls.__name__!r}: "
f"{ex!r}. Please refer to Python dataclasses "
"documentation for additional information.",
code="dcte",
) from ex
finally:
if revert and revert_dict:
# used for mixin dataclasses; we have to restore the
# mapped_column(), relationship() etc. to the class so these
# take place for a mapped class scan
for k, v in revert_dict.items():
setattr(self.cls, k, v)
restore_anno()
def _collect_annotation(
self,
name: str,
raw_annotation: _AnnotationScanType,
originating_class: Type[Any],
expect_mapped: Optional[bool],
attr_value: Any,
) -> Optional[_CollectedAnnotation]:
if name in self.collected_annotations:
return self.collected_annotations[name]
if raw_annotation is None:
return None
is_dataclass = self.is_dataclass_prior_to_mapping
allow_unmapped = self.allow_unmapped_annotations
if expect_mapped is None:
is_dataclass_field = isinstance(attr_value, dataclasses.Field)
expect_mapped = (
not is_dataclass_field
and not allow_unmapped
and (
attr_value is None
or isinstance(attr_value, _MappedAttribute)
)
)
is_dataclass_field = False
extracted = _extract_mapped_subtype(
raw_annotation,
self.cls,
originating_class.__module__,
name,
type(attr_value),
required=False,
is_dataclass_field=is_dataclass_field,
expect_mapped=expect_mapped and not is_dataclass,
)
if extracted is None:
# ClassVar can come out here
return None
extracted_mapped_annotation, mapped_container = extracted
if attr_value is None and not is_literal(extracted_mapped_annotation):
for elem in get_args(extracted_mapped_annotation):
if is_fwd_ref(
elem, check_generic=True, check_for_plain_string=True
):
elem = de_stringify_annotation(
self.cls,
elem,
originating_class.__module__,
include_generic=True,
)
# look in Annotated[...] for an ORM construct,
# such as Annotated[int, mapped_column(primary_key=True)]
if isinstance(elem, _IntrospectsAnnotations):
attr_value = elem.found_in_pep593_annotated()
self.collected_annotations[name] = ca = _CollectedAnnotation(
raw_annotation,
mapped_container,
extracted_mapped_annotation,
is_dataclass,
attr_value,
originating_class.__module__,
originating_class,
)
return ca
@classmethod
def _assert_dc_arguments(cls, arguments: _DataclassArguments) -> None:
allowed = {
"init",
"repr",
"order",
"eq",
"unsafe_hash",
"kw_only",
"match_args",
"dataclass_callable",
}
disallowed_args = set(arguments).difference(allowed)
if disallowed_args:
msg = ", ".join(f"{arg!r}" for arg in sorted(disallowed_args))
raise exc.ArgumentError(
f"Dataclass argument(s) {msg} are not accepted"
)
def _cls_attr_override_checker(
self, cls: Type[_O]
) -> Callable[[str, Any], bool]:
"""Produce a function that checks if a class has overridden an
attribute, taking SQLAlchemy-enabled dataclass fields into account.
"""
if self.allow_dataclass_fields:
sa_dataclass_metadata_key = _get_immediate_cls_attr(
cls, "__sa_dataclass_metadata_key__"
)
else:
sa_dataclass_metadata_key = None
if not sa_dataclass_metadata_key:
def attribute_is_overridden(key: str, obj: Any) -> bool:
return getattr(cls, key, obj) is not obj
else:
all_datacls_fields = {
f.name: f.metadata[sa_dataclass_metadata_key]
for f in util.dataclass_fields(cls)
if sa_dataclass_metadata_key in f.metadata
}
local_datacls_fields = {
f.name: f.metadata[sa_dataclass_metadata_key]
for f in util.local_dataclass_fields(cls)
if sa_dataclass_metadata_key in f.metadata
}
absent = object()
def attribute_is_overridden(key: str, obj: Any) -> bool:
if _is_declarative_props(obj):
obj = obj.fget
# this function likely has some failure modes still if
# someone is doing a deep mixing of the same attribute
# name as plain Python attribute vs. dataclass field.
ret = local_datacls_fields.get(key, absent)
if _is_declarative_props(ret):
ret = ret.fget
if ret is obj:
return False
elif ret is not absent:
return True
all_field = all_datacls_fields.get(key, absent)
ret = getattr(cls, key, obj)
if ret is obj:
return False
# for dataclasses, this could be the
# 'default' of the field. so filter more specifically
# for an already-mapped InstrumentedAttribute
if ret is not absent and isinstance(
ret, InstrumentedAttribute
):
return True
if all_field is obj:
return False
elif all_field is not absent:
return True
# can't find another attribute
return False
return attribute_is_overridden
def _cls_attr_resolver(
self, cls: Type[Any]
) -> Callable[[], Iterable[Tuple[str, Any, Any, bool]]]:
"""produce a function to iterate the "attributes" of a class
which we want to consider for mapping, adjusting for SQLAlchemy fields
embedded in dataclass fields.
"""
cls_annotations = util.get_annotations(cls)
cls_vars = vars(cls)
_include_dunders = self._include_dunders
_match_exclude_dunders = self._match_exclude_dunders
names = [
n
for n in util.merge_lists_w_ordering(
list(cls_vars), list(cls_annotations)
)
if not _match_exclude_dunders.match(n) or n in _include_dunders
]
if self.allow_dataclass_fields:
sa_dataclass_metadata_key: Optional[str] = _get_immediate_cls_attr(
cls, "__sa_dataclass_metadata_key__"
)
else:
sa_dataclass_metadata_key = None
if not sa_dataclass_metadata_key:
def local_attributes_for_class() -> (
Iterable[Tuple[str, Any, Any, bool]]
):
return (
(
name,
cls_vars.get(name),
cls_annotations.get(name),
False,
)
for name in names
)
else:
dataclass_fields = {
field.name: field for field in util.local_dataclass_fields(cls)
}
fixed_sa_dataclass_metadata_key = sa_dataclass_metadata_key
def local_attributes_for_class() -> (
Iterable[Tuple[str, Any, Any, bool]]
):
for name in names:
field = dataclass_fields.get(name, None)
if field and sa_dataclass_metadata_key in field.metadata:
yield field.name, _as_dc_declaredattr(
field.metadata, fixed_sa_dataclass_metadata_key
), cls_annotations.get(field.name), True
else:
yield name, cls_vars.get(name), cls_annotations.get(
name
), False
return local_attributes_for_class
class _DeclarativeMapperConfig(_MapperConfig, _ClassScanAbstractConfig):
"""Configurator that will produce a declarative mapped class"""
__slots__ = (
"registry",
"local_table",
"persist_selectable",
"declared_columns",
"column_ordering",
"column_copies",
"table_args",
"tablename",
"mapper_args",
"mapper_args_fn",
"table_fn",
"inherits",
"single",
"clsdict_view",
"collected_attributes",
"collected_annotations",
"allow_dataclass_fields",
"dataclass_setup_arguments",
"is_dataclass_prior_to_mapping",
"allow_unmapped_annotations",
)
is_deferred = False
registry: _RegistryType
local_table: Optional[FromClause]
persist_selectable: Optional[FromClause]
declared_columns: util.OrderedSet[Column[Any]]
column_ordering: Dict[Column[Any], int]
column_copies: Dict[
Union[MappedColumn[Any], Column[Any]],
Union[MappedColumn[Any], Column[Any]],
]
tablename: Optional[str]
mapper_args: Mapping[str, Any]
table_args: Optional[_TableArgsType]
mapper_args_fn: Optional[Callable[[], Dict[str, Any]]]
inherits: Optional[Type[Any]]
single: bool
def __init__(
self,
registry: _RegistryType,
cls_: Type[_O],
dict_: _ClassDict,
):
# grab class dict before the instrumentation manager has been added.
# reduces cycles
self.clsdict_view = (
util.immutabledict(dict_) if dict_ else util.EMPTY_DICT
)
super().__init__(registry, cls_)
self.registry = registry
self.persist_selectable = None
self.collected_attributes = {}
self.collected_annotations = {}
self.declared_columns = util.OrderedSet()
self.column_ordering = {}
self.column_copies = {}
self.single = False
self.dataclass_setup_arguments = dca = getattr(
self.cls, "_sa_apply_dc_transforms", None
)
self.allow_unmapped_annotations = getattr(
self.cls, "__allow_unmapped__", False
) or bool(self.dataclass_setup_arguments)
self.is_dataclass_prior_to_mapping = cld = dataclasses.is_dataclass(
cls_
)
sdk = _get_immediate_cls_attr(cls_, "__sa_dataclass_metadata_key__")
# we don't want to consume Field objects from a not-already-dataclass.
# the Field objects won't have their "name" or "type" populated,
# and while it seems like we could just set these on Field as we
# read them, Field is documented as "user read only" and we need to
# stay far away from any off-label use of dataclasses APIs.
if (not cld or dca) and sdk:
raise exc.InvalidRequestError(
"SQLAlchemy mapped dataclasses can't consume mapping "
"information from dataclass.Field() objects if the immediate "
"class is not already a dataclass."
)
# if already a dataclass, and __sa_dataclass_metadata_key__ present,