zmc
2023-08-08 e792e9a60d958b93aef96050644f369feb25d61b
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
U
¸ý°d%Óã@sdZddlmZddlmZddlmZddlmZddlmZddlmZddlm    Z    dd    lm
Z
dd
lm Z dd lm Z dd lm Z dd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddl!m"Z"ddl!m#Z#ddl!m$Z$ddl!m%Z%ddl!m&Z&erÆdd l'm(Z(dd!l)m*Z*dd"lm+Z+dd#lm,Z,dd$lm-Z-dd%lm.Z.dd&lm/Z/dd'l0m1Z1e$d(ƒZ2ed)ƒZ3ed*ed+Z4ed,ed+Z5ed-ed.d/Z6ed0ed.d1Z7Gd2d3„d3eƒZ8Gd4d5„d5e%e6ƒZ9Gd6d7„d7e%e7ƒZ:Gd8d9„d9e%e7ƒZ;Gd:d;„d;e%e6ƒZ<Gd<d=„d=e%e4ƒZ=Gd>d?„d?e%e4ƒZ>Gd@dA„dAee4ƒZ?GdBdC„dCej@ee2e3fƒZAd*d*dDœdEdF„ZBGdGdH„dHej@ee4ƒZCGdIdJ„dJejDe4ƒZEGdKdL„dLeEe4ƒZFdMS)NaouDefine attributes on ORM-mapped classes that have "hybrid" behavior.
 
"hybrid" means the attribute has distinct behaviors defined at the
class level and at the instance level.
 
The :mod:`~sqlalchemy.ext.hybrid` extension provides a special form of
method decorator and has minimal dependencies on the rest of SQLAlchemy.
Its basic theory of operation can work with any descriptor-based expression
system.
 
Consider a mapping ``Interval``, representing integer ``start`` and ``end``
values. We can define higher level functions on mapped classes that produce SQL
expressions at the class level, and Python expression evaluation at the
instance level.  Below, each function decorated with :class:`.hybrid_method` or
:class:`.hybrid_property` may receive ``self`` as an instance of the class, or
may receive the class directly, depending on context::
 
    from __future__ import annotations
 
    from sqlalchemy.ext.hybrid import hybrid_method
    from sqlalchemy.ext.hybrid import hybrid_property
    from sqlalchemy.orm import DeclarativeBase
    from sqlalchemy.orm import Mapped
    from sqlalchemy.orm import mapped_column
 
 
    class Base(DeclarativeBase):
        pass
 
    class Interval(Base):
        __tablename__ = 'interval'
 
        id: Mapped[int] = mapped_column(primary_key=True)
        start: Mapped[int]
        end: Mapped[int]
 
        def __init__(self, start: int, end: int):
            self.start = start
            self.end = end
 
        @hybrid_property
        def length(self) -> int:
            return self.end - self.start
 
        @hybrid_method
        def contains(self, point: int) -> bool:
            return (self.start <= point) & (point <= self.end)
 
        @hybrid_method
        def intersects(self, other: Interval) -> bool:
            return self.contains(other.start) | self.contains(other.end)
 
 
Above, the ``length`` property returns the difference between the
``end`` and ``start`` attributes.  With an instance of ``Interval``,
this subtraction occurs in Python, using normal Python descriptor
mechanics::
 
    >>> i1 = Interval(5, 10)
    >>> i1.length
    5
 
When dealing with the ``Interval`` class itself, the :class:`.hybrid_property`
descriptor evaluates the function body given the ``Interval`` class as
the argument, which when evaluated with SQLAlchemy expression mechanics
returns a new SQL expression:
 
.. sourcecode:: pycon+sql
 
    >>> from sqlalchemy import select
    >>> print(select(Interval.length))
    {printsql}SELECT interval."end" - interval.start AS length
    FROM interval{stop}
 
 
    >>> print(select(Interval).filter(Interval.length > 10))
    {printsql}SELECT interval.id, interval.start, interval."end"
    FROM interval
    WHERE interval."end" - interval.start > :param_1
 
Filtering methods such as :meth:`.Select.filter_by` are supported
with hybrid attributes as well:
 
.. sourcecode:: pycon+sql
 
    >>> print(select(Interval).filter_by(length=5))
    {printsql}SELECT interval.id, interval.start, interval."end"
    FROM interval
    WHERE interval."end" - interval.start = :param_1
 
The ``Interval`` class example also illustrates two methods,
``contains()`` and ``intersects()``, decorated with
:class:`.hybrid_method`. This decorator applies the same idea to
methods that :class:`.hybrid_property` applies to attributes.   The
methods return boolean values, and take advantage of the Python ``|``
and ``&`` bitwise operators to produce equivalent instance-level and
SQL expression-level boolean behavior:
 
.. sourcecode:: pycon+sql
 
    >>> i1.contains(6)
    True
    >>> i1.contains(15)
    False
    >>> i1.intersects(Interval(7, 18))
    True
    >>> i1.intersects(Interval(25, 29))
    False
 
    >>> print(select(Interval).filter(Interval.contains(15)))
    {printsql}SELECT interval.id, interval.start, interval."end"
    FROM interval
    WHERE interval.start <= :start_1 AND interval."end" > :end_1{stop}
 
    >>> ia = aliased(Interval)
    >>> print(select(Interval, ia).filter(Interval.intersects(ia)))
    {printsql}SELECT interval.id, interval.start,
    interval."end", interval_1.id AS interval_1_id,
    interval_1.start AS interval_1_start, interval_1."end" AS interval_1_end
    FROM interval, interval AS interval_1
    WHERE interval.start <= interval_1.start
        AND interval."end" > interval_1.start
        OR interval.start <= interval_1."end"
        AND interval."end" > interval_1."end"{stop}
 
.. _hybrid_distinct_expression:
 
Defining Expression Behavior Distinct from Attribute Behavior
--------------------------------------------------------------
 
In the previous section, our usage of the ``&`` and ``|`` bitwise operators
within the ``Interval.contains`` and ``Interval.intersects`` methods was
fortunate, considering our functions operated on two boolean values to return a
new one. In many cases, the construction of an in-Python function and a
SQLAlchemy SQL expression have enough differences that two separate Python
expressions should be defined. The :mod:`~sqlalchemy.ext.hybrid` decorator
defines a **modifier** :meth:`.hybrid_property.expression` for this purpose. As an
example we'll define the radius of the interval, which requires the usage of
the absolute value function::
 
    from sqlalchemy import ColumnElement
    from sqlalchemy import Float
    from sqlalchemy import func
    from sqlalchemy import type_coerce
 
    class Interval(Base):
        # ...
 
        @hybrid_property
        def radius(self) -> float:
            return abs(self.length) / 2
 
        @radius.inplace.expression
        @classmethod
        def _radius_expression(cls) -> ColumnElement[float]:
            return type_coerce(func.abs(cls.length) / 2, Float)
 
In the above example, the :class:`.hybrid_property` first assigned to the
name ``Interval.radius`` is amended by a subsequent method called
``Interval._radius_expression``, using the decorator
``@radius.inplace.expression``, which chains together two modifiers
:attr:`.hybrid_property.inplace` and :attr:`.hybrid_property.expression`.
The use of :attr:`.hybrid_property.inplace` indicates that the
:meth:`.hybrid_property.expression` modifier should mutate the
existing hybrid object at ``Interval.radius`` in place, without creating a
new object.   Notes on this modifier and its
rationale are discussed in the next section :ref:`hybrid_pep484_naming`.
The use of ``@classmethod`` is optional, and is strictly to give typing
tools a hint that ``cls`` in this case is expected to be the ``Interval``
class, and not an instance of ``Interval``.
 
.. note:: :attr:`.hybrid_property.inplace` as well as the use of ``@classmethod``
   for proper typing support are available as of SQLAlchemy 2.0.4, and will
   not work in earlier versions.
 
With ``Interval.radius`` now including an expression element, the SQL
function ``ABS()`` is returned when accessing ``Interval.radius``
at the class level:
 
.. sourcecode:: pycon+sql
 
    >>> from sqlalchemy import select
    >>> print(select(Interval).filter(Interval.radius > 5))
    {printsql}SELECT interval.id, interval.start, interval."end"
    FROM interval
    WHERE abs(interval."end" - interval.start) / :abs_1 > :param_1
 
 
.. _hybrid_pep484_naming:
 
Using ``inplace`` to create pep-484 compliant hybrid properties
---------------------------------------------------------------
 
In the previous section, a :class:`.hybrid_property` decorator is illustrated
which includes two separate method-level functions being decorated, both
to produce a single object attribute referred towards as ``Interval.radius``.
There are actually several different modifiers we can use for
:class:`.hybrid_property` including :meth:`.hybrid_property.expression`,
:meth:`.hybrid_property.setter` and :meth:`.hybrid_property.update_expression`.
 
SQLAlchemy's :class:`.hybrid_property` decorator intends that adding on these
methods may be done in the identical manner as Python's built-in
``@property`` decorator, where idiomatic use is to continue to redefine the
attribute repeatedly, using the **same attribute name** each time, as in the
example below that illustrates the use of :meth:`.hybrid_property.setter` and
:meth:`.hybrid_property.expression` for the ``Interval.radius`` descriptor::
 
    # correct use, however is not accepted by pep-484 tooling
 
    class Interval(Base):
        # ...
 
        @hybrid_property
        def radius(self):
            return abs(self.length) / 2
 
        @radius.setter
        def radius(self, value):
            self.length = value * 2
 
        @radius.expression
        def radius(cls):
            return type_coerce(func.abs(cls.length) / 2, Float)
 
Above, there are three ``Interval.radius`` methods, but as each are decorated,
first by the :class:`.hybrid_property` decorator and then by the
``@radius`` name itself, the end effect is that ``Interval.radius`` is
a single attribute with three different functions contained within it.
This style of use is taken from `Python's documented use of @property
<https://docs.python.org/3/library/functions.html#property>`_.
It is important to note that the way both ``@property`` as well as
:class:`.hybrid_property` work, a **copy of the descriptor is made each time**.
That is, each call to ``@radius.expression``, ``@radius.setter`` etc.
make a new object entirely.  This allows the attribute to be re-defined in
subclasses without issue (see :ref:`hybrid_reuse_subclass` later in this
section for how this is used).
 
However, the above approach is not compatible with typing tools such as
mypy and pyright.  Python's own ``@property`` decorator does not have this
limitation only because
`these tools hardcode the behavior of @property
<https://github.com/python/typing/discussions/1102>`_, meaning this syntax
is not available to SQLAlchemy under :pep:`484` compliance.
 
In order to produce a reasonable syntax while remaining typing compliant,
the :attr:`.hybrid_property.inplace` decorator allows the same
decorator to be re-used with different method names, while still producing
a single decorator under one name::
 
    # correct use which is also accepted by pep-484 tooling
 
    class Interval(Base):
        # ...
 
        @hybrid_property
        def radius(self) -> float:
            return abs(self.length) / 2
 
        @radius.inplace.setter
        def _radius_setter(self, value: float) -> None:
            # for example only
            self.length = value * 2
 
        @radius.inplace.expression
        @classmethod
        def _radius_expression(cls) -> ColumnElement[float]:
            return type_coerce(func.abs(cls.length) / 2, Float)
 
Using :attr:`.hybrid_property.inplace` further qualifies the use of the
decorator that a new copy should not be made, thereby maintaining the
``Interval.radius`` name while allowing additional methods
``Interval._radius_setter`` and ``Interval._radius_expression`` to be
differently named.
 
 
.. versionadded:: 2.0.4 Added :attr:`.hybrid_property.inplace` to allow
   less verbose construction of composite :class:`.hybrid_property` objects
   while not having to use repeated method names.   Additionally allowed the
   use of ``@classmethod`` within :attr:`.hybrid_property.expression`,
   :attr:`.hybrid_property.update_expression`, and
   :attr:`.hybrid_property.comparator` to allow typing tools to identify
   ``cls`` as a class and not an instance in the method signature.
 
 
Defining Setters
----------------
 
The :meth:`.hybrid_property.setter` modifier allows the construction of a
custom setter method, that can modify values on the object::
 
    class Interval(Base):
        # ...
 
        @hybrid_property
        def length(self) -> int:
            return self.end - self.start
 
        @length.inplace.setter
        def _length_setter(self, value: int) -> None:
            self.end = self.start + value
 
The ``length(self, value)`` method is now called upon set::
 
    >>> i1 = Interval(5, 10)
    >>> i1.length
    5
    >>> i1.length = 12
    >>> i1.end
    17
 
.. _hybrid_bulk_update:
 
Allowing Bulk ORM Update
------------------------
 
A hybrid can define a custom "UPDATE" handler for when using
ORM-enabled updates, allowing the hybrid to be used in the
SET clause of the update.
 
Normally, when using a hybrid with :func:`_sql.update`, the SQL
expression is used as the column that's the target of the SET.  If our
``Interval`` class had a hybrid ``start_point`` that linked to
``Interval.start``, this could be substituted directly::
 
    from sqlalchemy import update
    stmt = update(Interval).values({Interval.start_point: 10})
 
However, when using a composite hybrid like ``Interval.length``, this
hybrid represents more than one column.   We can set up a handler that will
accommodate a value passed in the VALUES expression which can affect
this, using the :meth:`.hybrid_property.update_expression` decorator.
A handler that works similarly to our setter would be::
 
    from typing import List, Tuple, Any
 
    class Interval(Base):
        # ...
 
        @hybrid_property
        def length(self) -> int:
            return self.end - self.start
 
        @length.inplace.setter
        def _length_setter(self, value: int) -> None:
            self.end = self.start + value
 
        @length.inplace.update_expression
        def _length_update_expression(cls, value: Any) -> List[Tuple[Any, Any]]:
            return [
                (cls.end, cls.start + value)
            ]
 
Above, if we use ``Interval.length`` in an UPDATE expression, we get
a hybrid SET expression:
 
.. sourcecode:: pycon+sql
 
 
    >>> from sqlalchemy import update
    >>> print(update(Interval).values({Interval.length: 25}))
    {printsql}UPDATE interval SET "end"=(interval.start + :start_1)
 
This SET expression is accommodated by the ORM automatically.
 
.. seealso::
 
    :ref:`orm_expression_update_delete` - includes background on ORM-enabled
    UPDATE statements
 
 
Working with Relationships
--------------------------
 
There's no essential difference when creating hybrids that work with
related objects as opposed to column-based data. The need for distinct
expressions tends to be greater.  The two variants we'll illustrate
are the "join-dependent" hybrid, and the "correlated subquery" hybrid.
 
Join-Dependent Relationship Hybrid
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
Consider the following declarative
mapping which relates a ``User`` to a ``SavingsAccount``::
 
    from __future__ import annotations
 
    from decimal import Decimal
    from typing import cast
    from typing import List
    from typing import Optional
 
    from sqlalchemy import ForeignKey
    from sqlalchemy import Numeric
    from sqlalchemy import String
    from sqlalchemy import SQLColumnExpression
    from sqlalchemy.ext.hybrid import hybrid_property
    from sqlalchemy.orm import DeclarativeBase
    from sqlalchemy.orm import Mapped
    from sqlalchemy.orm import mapped_column
    from sqlalchemy.orm import relationship
 
 
    class Base(DeclarativeBase):
        pass
 
 
    class SavingsAccount(Base):
        __tablename__ = 'account'
        id: Mapped[int] = mapped_column(primary_key=True)
        user_id: Mapped[int] = mapped_column(ForeignKey('user.id'))
        balance: Mapped[Decimal] = mapped_column(Numeric(15, 5))
 
        owner: Mapped[User] = relationship(back_populates="accounts")
 
    class User(Base):
        __tablename__ = 'user'
        id: Mapped[int] = mapped_column(primary_key=True)
        name: Mapped[str] = mapped_column(String(100))
 
        accounts: Mapped[List[SavingsAccount]] = relationship(
            back_populates="owner", lazy="selectin"
        )
 
        @hybrid_property
        def balance(self) -> Optional[Decimal]:
            if self.accounts:
                return self.accounts[0].balance
            else:
                return None
 
        @balance.inplace.setter
        def _balance_setter(self, value: Optional[Decimal]) -> None:
            assert value is not None
 
            if not self.accounts:
                account = SavingsAccount(owner=self)
            else:
                account = self.accounts[0]
            account.balance = value
 
        @balance.inplace.expression
        @classmethod
        def _balance_expression(cls) -> SQLColumnExpression[Optional[Decimal]]:
            return cast("SQLColumnExpression[Optional[Decimal]]", SavingsAccount.balance)
 
The above hybrid property ``balance`` works with the first
``SavingsAccount`` entry in the list of accounts for this user.   The
in-Python getter/setter methods can treat ``accounts`` as a Python
list available on ``self``.
 
.. tip:: The ``User.balance`` getter in the above example accesses the
   ``self.acccounts`` collection, which will normally be loaded via the
   :func:`.selectinload` loader strategy configured on the ``User.balance``
   :func:`_orm.relationship`. The default loader strategy when not otherwise
   stated on :func:`_orm.relationship` is :func:`.lazyload`, which emits SQL on
   demand. When using asyncio, on-demand loaders such as :func:`.lazyload` are
   not supported, so care should be taken to ensure the ``self.accounts``
   collection is accessible to this hybrid accessor when using asyncio.
 
At the expression level, it's expected that the ``User`` class will
be used in an appropriate context such that an appropriate join to
``SavingsAccount`` will be present:
 
.. sourcecode:: pycon+sql
 
    >>> from sqlalchemy import select
    >>> print(select(User, User.balance).
    ...       join(User.accounts).filter(User.balance > 5000))
    {printsql}SELECT "user".id AS user_id, "user".name AS user_name,
    account.balance AS account_balance
    FROM "user" JOIN account ON "user".id = account.user_id
    WHERE account.balance > :balance_1
 
Note however, that while the instance level accessors need to worry
about whether ``self.accounts`` is even present, this issue expresses
itself differently at the SQL expression level, where we basically
would use an outer join:
 
.. sourcecode:: pycon+sql
 
    >>> from sqlalchemy import select
    >>> from sqlalchemy import or_
    >>> print (select(User, User.balance).outerjoin(User.accounts).
    ...         filter(or_(User.balance < 5000, User.balance == None)))
    {printsql}SELECT "user".id AS user_id, "user".name AS user_name,
    account.balance AS account_balance
    FROM "user" LEFT OUTER JOIN account ON "user".id = account.user_id
    WHERE account.balance <  :balance_1 OR account.balance IS NULL
 
Correlated Subquery Relationship Hybrid
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
We can, of course, forego being dependent on the enclosing query's usage
of joins in favor of the correlated subquery, which can portably be packed
into a single column expression. A correlated subquery is more portable, but
often performs more poorly at the SQL level. Using the same technique
illustrated at :ref:`mapper_column_property_sql_expressions`,
we can adjust our ``SavingsAccount`` example to aggregate the balances for
*all* accounts, and use a correlated subquery for the column expression::
 
    from __future__ import annotations
 
    from decimal import Decimal
    from typing import List
 
    from sqlalchemy import ForeignKey
    from sqlalchemy import func
    from sqlalchemy import Numeric
    from sqlalchemy import select
    from sqlalchemy import SQLColumnExpression
    from sqlalchemy import String
    from sqlalchemy.ext.hybrid import hybrid_property
    from sqlalchemy.orm import DeclarativeBase
    from sqlalchemy.orm import Mapped
    from sqlalchemy.orm import mapped_column
    from sqlalchemy.orm import relationship
 
 
    class Base(DeclarativeBase):
        pass
 
 
    class SavingsAccount(Base):
        __tablename__ = 'account'
        id: Mapped[int] = mapped_column(primary_key=True)
        user_id: Mapped[int] = mapped_column(ForeignKey('user.id'))
        balance: Mapped[Decimal] = mapped_column(Numeric(15, 5))
 
        owner: Mapped[User] = relationship(back_populates="accounts")
 
    class User(Base):
        __tablename__ = 'user'
        id: Mapped[int] = mapped_column(primary_key=True)
        name: Mapped[str] = mapped_column(String(100))
 
        accounts: Mapped[List[SavingsAccount]] = relationship(
            back_populates="owner", lazy="selectin"
        )
 
        @hybrid_property
        def balance(self) -> Decimal:
            return sum((acc.balance for acc in self.accounts), start=Decimal("0"))
 
        @balance.inplace.expression
        @classmethod
        def _balance_expression(cls) -> SQLColumnExpression[Decimal]:
            return (
                select(func.sum(SavingsAccount.balance))
                .where(SavingsAccount.user_id == cls.id)
                .label("total_balance")
            )
 
 
The above recipe will give us the ``balance`` column which renders
a correlated SELECT:
 
.. sourcecode:: pycon+sql
 
    >>> from sqlalchemy import select
    >>> print(select(User).filter(User.balance > 400))
    {printsql}SELECT "user".id, "user".name
    FROM "user"
    WHERE (
        SELECT sum(account.balance) AS sum_1 FROM account
        WHERE account.user_id = "user".id
    ) > :param_1
 
 
.. _hybrid_custom_comparators:
 
Building Custom Comparators
---------------------------
 
The hybrid property also includes a helper that allows construction of
custom comparators. A comparator object allows one to customize the
behavior of each SQLAlchemy expression operator individually.  They
are useful when creating custom types that have some highly
idiosyncratic behavior on the SQL side.
 
.. note::  The :meth:`.hybrid_property.comparator` decorator introduced
   in this section **replaces** the use of the
   :meth:`.hybrid_property.expression` decorator.
   They cannot be used together.
 
The example class below allows case-insensitive comparisons on the attribute
named ``word_insensitive``::
 
    from __future__ import annotations
 
    from typing import Any
 
    from sqlalchemy import ColumnElement
    from sqlalchemy import func
    from sqlalchemy.ext.hybrid import Comparator
    from sqlalchemy.ext.hybrid import hybrid_property
    from sqlalchemy.orm import DeclarativeBase
    from sqlalchemy.orm import Mapped
    from sqlalchemy.orm import mapped_column
 
    class Base(DeclarativeBase):
        pass
 
 
    class CaseInsensitiveComparator(Comparator[str]):
        def __eq__(self, other: Any) -> ColumnElement[bool]:  # type: ignore[override]  # noqa: E501
            return func.lower(self.__clause_element__()) == func.lower(other)
 
    class SearchWord(Base):
        __tablename__ = 'searchword'
 
        id: Mapped[int] = mapped_column(primary_key=True)
        word: Mapped[str]
 
        @hybrid_property
        def word_insensitive(self) -> str:
            return self.word.lower()
 
        @word_insensitive.inplace.comparator
        @classmethod
        def _word_insensitive_comparator(cls) -> CaseInsensitiveComparator:
            return CaseInsensitiveComparator(cls.word)
 
Above, SQL expressions against ``word_insensitive`` will apply the ``LOWER()``
SQL function to both sides:
 
.. sourcecode:: pycon+sql
 
    >>> from sqlalchemy import select
    >>> print(select(SearchWord).filter_by(word_insensitive="Trucks"))
    {printsql}SELECT searchword.id, searchword.word
    FROM searchword
    WHERE lower(searchword.word) = lower(:lower_1)
 
 
The ``CaseInsensitiveComparator`` above implements part of the
:class:`.ColumnOperators` interface.   A "coercion" operation like
lowercasing can be applied to all comparison operations (i.e. ``eq``,
``lt``, ``gt``, etc.) using :meth:`.Operators.operate`::
 
    class CaseInsensitiveComparator(Comparator):
        def operate(self, op, other, **kwargs):
            return op(
                func.lower(self.__clause_element__()),
                func.lower(other),
                **kwargs,
            )
 
.. _hybrid_reuse_subclass:
 
Reusing Hybrid Properties across Subclasses
-------------------------------------------
 
A hybrid can be referred to from a superclass, to allow modifying
methods like :meth:`.hybrid_property.getter`, :meth:`.hybrid_property.setter`
to be used to redefine those methods on a subclass.  This is similar to
how the standard Python ``@property`` object works::
 
    class FirstNameOnly(Base):
        # ...
 
        first_name: Mapped[str]
 
        @hybrid_property
        def name(self) -> str:
            return self.first_name
 
        @name.inplace.setter
        def _name_setter(self, value: str) -> None:
            self.first_name = value
 
    class FirstNameLastName(FirstNameOnly):
        # ...
 
        last_name: Mapped[str]
 
        # 'inplace' is not used here; calling getter creates a copy
        # of FirstNameOnly.name that is local to FirstNameLastName
        @FirstNameOnly.name.getter
        def name(self) -> str:
            return self.first_name + ' ' + self.last_name
 
        @name.inplace.setter
        def _name_setter(self, value: str) -> None:
            self.first_name, self.last_name = value.split(' ', 1)
 
Above, the ``FirstNameLastName`` class refers to the hybrid from
``FirstNameOnly.name`` to repurpose its getter and setter for the subclass.
 
When overriding :meth:`.hybrid_property.expression` and
:meth:`.hybrid_property.comparator` alone as the first reference to the
superclass, these names conflict with the same-named accessors on the class-
level :class:`.QueryableAttribute` object returned at the class level.  To
override these methods when referring directly to the parent class descriptor,
add the special qualifier :attr:`.hybrid_property.overrides`, which will de-
reference the instrumented attribute back to the hybrid object::
 
    class FirstNameLastName(FirstNameOnly):
        # ...
 
        last_name: Mapped[str]
 
        @FirstNameOnly.name.overrides.expression
        @classmethod
        def name(cls):
            return func.concat(cls.first_name, ' ', cls.last_name)
 
 
Hybrid Value Objects
--------------------
 
Note in our previous example, if we were to compare the ``word_insensitive``
attribute of a ``SearchWord`` instance to a plain Python string, the plain
Python string would not be coerced to lower case - the
``CaseInsensitiveComparator`` we built, being returned by
``@word_insensitive.comparator``, only applies to the SQL side.
 
A more comprehensive form of the custom comparator is to construct a *Hybrid
Value Object*. This technique applies the target value or expression to a value
object which is then returned by the accessor in all cases.   The value object
allows control of all operations upon the value as well as how compared values
are treated, both on the SQL expression side as well as the Python value side.
Replacing the previous ``CaseInsensitiveComparator`` class with a new
``CaseInsensitiveWord`` class::
 
    class CaseInsensitiveWord(Comparator):
        "Hybrid value representing a lower case representation of a word."
 
        def __init__(self, word):
            if isinstance(word, basestring):
                self.word = word.lower()
            elif isinstance(word, CaseInsensitiveWord):
                self.word = word.word
            else:
                self.word = func.lower(word)
 
        def operate(self, op, other, **kwargs):
            if not isinstance(other, CaseInsensitiveWord):
                other = CaseInsensitiveWord(other)
            return op(self.word, other.word, **kwargs)
 
        def __clause_element__(self):
            return self.word
 
        def __str__(self):
            return self.word
 
        key = 'word'
        "Label to apply to Query tuple results"
 
Above, the ``CaseInsensitiveWord`` object represents ``self.word``, which may
be a SQL function, or may be a Python native.   By overriding ``operate()`` and
``__clause_element__()`` to work in terms of ``self.word``, all comparison
operations will work against the "converted" form of ``word``, whether it be
SQL side or Python side. Our ``SearchWord`` class can now deliver the
``CaseInsensitiveWord`` object unconditionally from a single hybrid call::
 
    class SearchWord(Base):
        __tablename__ = 'searchword'
        id: Mapped[int] = mapped_column(primary_key=True)
        word: Mapped[str]
 
        @hybrid_property
        def word_insensitive(self) -> CaseInsensitiveWord:
            return CaseInsensitiveWord(self.word)
 
The ``word_insensitive`` attribute now has case-insensitive comparison behavior
universally, including SQL expression vs. Python expression (note the Python
value is converted to lower case on the Python side here):
 
.. sourcecode:: pycon+sql
 
    >>> print(select(SearchWord).filter_by(word_insensitive="Trucks"))
    {printsql}SELECT searchword.id AS searchword_id, searchword.word AS searchword_word
    FROM searchword
    WHERE lower(searchword.word) = :lower_1
 
SQL expression versus SQL expression:
 
.. sourcecode:: pycon+sql
 
    >>> from sqlalchemy.orm import aliased
    >>> sw1 = aliased(SearchWord)
    >>> sw2 = aliased(SearchWord)
    >>> print(
    ...     select(sw1.word_insensitive, sw2.word_insensitive).filter(
    ...         sw1.word_insensitive > sw2.word_insensitive
    ...     )
    ... )
    {printsql}SELECT lower(searchword_1.word) AS lower_1,
    lower(searchword_2.word) AS lower_2
    FROM searchword AS searchword_1, searchword AS searchword_2
    WHERE lower(searchword_1.word) > lower(searchword_2.word)
 
Python only expression::
 
    >>> ws1 = SearchWord(word="SomeWord")
    >>> ws1.word_insensitive == "sOmEwOrD"
    True
    >>> ws1.word_insensitive == "XOmEwOrX"
    False
    >>> print(ws1.word_insensitive)
    someword
 
The Hybrid Value pattern is very useful for any kind of value that may have
multiple representations, such as timestamps, time deltas, units of
measurement, currencies and encrypted passwords.
 
.. seealso::
 
    `Hybrids and Value Agnostic Types
    <https://techspot.zzzeek.org/2011/10/21/hybrids-and-value-agnostic-types/>`_
    - on the techspot.zzzeek.org blog
 
    `Value Agnostic Types, Part II
    <https://techspot.zzzeek.org/2011/10/29/value-agnostic-types-part-ii/>`_ -
    on the techspot.zzzeek.org blog
 
 
é)Ú annotations)ÚAny)ÚCallable)Úcast)ÚGeneric)ÚList)ÚOptional)Úoverload)ÚSequence)ÚTuple)ÚType)Ú TYPE_CHECKING)ÚTypeVar)ÚUnioné)Úutil)Ú
attributes)ÚInspectionAttrExtensionType)Ú
interfaces)Ú ORMDescriptor)ÚQueryableAttribute)Úroles)Úis_has_clause_element)Ú ColumnElement)ÚSQLCoreOperations)Ú Concatenate)ÚLiteral)Ú    ParamSpec)ÚProtocol)ÚSelf)ÚMapperProperty)Ú AliasedInsp)ÚSQLColumnExpression)Ú_ColumnExpressionArgument)Ú_DMLColumnArgument)Ú_HasClauseElement)Ú    _InfoType)Ú OperatorTypeÚ_PÚ_RÚ_T)ÚboundÚ_TEÚ_T_coT)r+Ú    covariantÚ_T_con)r+Ú contravariantc@seZdZdZdZdS)ÚHybridExtensionTypeÚ HYBRID_METHODÚHYBRID_PROPERTYN)Ú__name__Ú
__module__Ú __qualname__r2r3©r7r7úLd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\sqlalchemy/ext/hybrid.pyr1ns r1c@seZdZdddœdd„ZdS)Ú_HybridGetterTyperr-)ÚselfÚreturncCsdS©Nr7)Úsr:r7r7r8Ú__call__Œsz_HybridGetterType.__call__N©r4r5r6r>r7r7r7r8r9‹sr9c@seZdZddddœdd„ZdS)Ú_HybridSetterTyperr/ÚNone)r:Úvaluer;cCsdSr<r7)r=r:rBr7r7r8r>‘sz_HybridSetterType.__call__Nr?r7r7r7r8r@sr@c@seZdZddddœdd„ZdS)Ú_HybridUpdaterTyperz0Union[_T_con, _ColumnExpressionArgument[_T_con]]z$List[Tuple[_DMLColumnArgument, Any]])ÚclsrBr;cCsdSr<r7)r=rDrBr7r7r8r>–sz_HybridUpdaterType.__call__Nr?r7r7r7r8rC•srCc@seZdZdddœdd„ZdS)Ú_HybridDeleterTyperrA©Úinstancer;cCsdSr<r7©r:rGr7r7r8r>Ÿsz_HybridDeleterType.__call__Nr?r7r7r7r8rEžsrEc@seZdZdddœdd„ZdS)Ú_HybridExprCallableTyperú1Union[_HasClauseElement, SQLColumnExpression[_T]]©rDr;cCsdSr<r7©r:rDr7r7r8r>¤sz _HybridExprCallableType.__call__Nr?r7r7r7r8rI£srIc@seZdZdddœdd„ZdS)Ú_HybridComparatorCallableTyperúComparator[_T]rKcCsdSr<r7rLr7r7r8r>«sz&_HybridComparatorCallableType.__call__Nr?r7r7r7r8rMªsrMc@sfeZdZdZerbdddœdd„Zdddœd    d
„Zd dd œd d„Zeddœdd„ƒZ    dddœdd„Z
dS)Ú_HybridClassLevelAccessorzfDescribe the object returned by a hybrid_property() when
    called as a class-level descriptor.
 
    ú_HybridGetterType[_T]úhybrid_property[_T]©Úfgetr;cCsdSr<r7©r:rSr7r7r8Úgetter·sz _HybridClassLevelAccessor.getterú_HybridSetterType[_T]©Úfsetr;cCsdSr<r7©r:rXr7r7r8Úsetterºsz _HybridClassLevelAccessor.setterú_HybridDeleterType[_T]©Úfdelr;cCsdSr<r7©r:r]r7r7r8Údeleter½sz!_HybridClassLevelAccessor.deleter©r;cCsdSr<r7©r:r7r7r8Ú    overridesÀsz#_HybridClassLevelAccessor.overridesú_HybridUpdaterType[_T]©Úmethr;cCsdSr<r7©r:rer7r7r8Úupdate_expressionÄsz+_HybridClassLevelAccessor.update_expressionN) r4r5r6Ú__doc__r rUrZr_Úpropertyrbrgr7r7r7r8rO¯srOc@sŒeZdZdZdZejZddddœdd„Ze    d    d
œd d „ƒZ
e d dddœdd„ƒZ e ddddœdd„ƒZ ddddœdd„Z dddœdd„Z dS)Ú hybrid_methodzzA decorator which allows definition of a Python object method with both
    instance-level and class-level behavior.
 
    TNz"Callable[Concatenate[Any, _P], _R]z?Optional[Callable[Concatenate[Any, _P], SQLCoreOperations[_R]]])ÚfuncÚexprcCs(||_|dk    r| |¡n
| |¡dS)aÑCreate a new :class:`.hybrid_method`.
 
        Usage is typically via decorator::
 
            from sqlalchemy.ext.hybrid import hybrid_method
 
            class SomeClass:
                @hybrid_method
                def value(self, x, y):
                    return self._value + x + y
 
                @value.expression
                @classmethod
                def value(cls, x, y):
                    return func.some_function(cls._value, x, y)
 
        N)rkÚ
expression)r:rkrlr7r7r8Ú__init__Ós zhybrid_method.__init__rr`cCs|S)afReturn the inplace mutator for this :class:`.hybrid_method`.
 
        The :class:`.hybrid_method` class already performs "in place" mutation
        when the :meth:`.hybrid_method.expression` decorator is called,
        so this attribute returns Self.
 
        .. versionadded:: 2.0.4
 
        .. seealso::
 
            :ref:`hybrid_pep484_naming`
 
        r7rar7r7r8Úinplaceñszhybrid_method.inplaceú Literal[None]ú Type[object]z#Callable[_P, SQLCoreOperations[_R]]©rGÚownerr;cCsdSr<r7©r:rGrsr7r7r8Ú__get__szhybrid_method.__get__ÚobjectzCallable[_P, _R]cCsdSr<r7rtr7r7r8rusúOptional[object]z<Union[Callable[_P, _R], Callable[_P, SQLCoreOperations[_R]]]cCs(|dkr|j ||¡S|j ||¡SdSr<)rlrurkrtr7r7r8rusz5Callable[Concatenate[Any, _P], SQLCoreOperations[_R]]zhybrid_method[_P, _R]©rlr;cCs||_|jjs|jj|j_|S)zUProvide a modifying decorator that defines a
        SQL-expression producing method.)rlrhrk©r:rlr7r7r8rms zhybrid_method.expression)N)r4r5r6rhÚ is_attributer1r2Úextension_typernriror    rurmr7r7r7r8rjÊsûrjrdcCst|tƒr|jS|SdSr<)Ú
isinstanceÚ classmethodÚ__func__)rer7r7r8Ú_unwrap_classmethod"s
rc@seZdZUdZdZejZded<dPdddd    d
d d œd d„Z    e
ddddœdd„ƒZ e
ddddœdd„ƒZ e
ddddœdd„ƒZ ddddœdd„Z dddd œd!d"„Z ddd#œd$d%„Z dd&d'œd(d)„Zedd*œd+d,„ƒZGd-d.„d.eeƒZed/d*œd0d1„ƒZdd&d2œd3d4„Zd5d&d6œd7d8„Zd9d&d:œd;d<„Zd=d&d>œd?d@„ZdAd&dBœdCdD„ZdEd&dFœdGdH„ZejdId*œdJdK„ƒZd=dId>œdLdM„ZddIdBœdNdO„ZdS)QÚhybrid_propertyzwA decorator which allows definition of a Python descriptor with both
    instance-level and class-level behavior.
 
    TÚstrr4NrPzOptional[_HybridSetterType[_T]]z Optional[_HybridDeleterType[_T]]z%Optional[_HybridExprCallableType[_T]]zOptional[Comparator[_T]]z Optional[_HybridUpdaterType[_T]])rSrXr]rlÚcustom_comparatorÚ update_exprcCs@||_||_||_t|ƒ|_t|ƒ|_t|ƒ|_t ||¡dS)a’Create a new :class:`.hybrid_property`.
 
        Usage is typically via decorator::
 
            from sqlalchemy.ext.hybrid import hybrid_property
 
            class SomeClass:
                @hybrid_property
                def value(self):
                    return self._value
 
                @value.setter
                def value(self, value):
                    self._value = value
 
        N)    rSrXr]rrlr‚rƒrÚupdate_wrapper)r:rSrXr]rlr‚rƒr7r7r8rn4s
 
 
zhybrid_property.__init__rrprrrcCsdSr<r7rtr7r7r8ruUszhybrid_property.__get__rqú_HybridClassLevelAccessor[_T]cCsdSr<r7rtr7r7r8ruYsrvr*cCsdSr<r7rtr7r7r8ru_srwzOptional[Type[object]]z=Union[hybrid_property[_T], _HybridClassLevelAccessor[_T], _T]cCs,|dkr |S|dkr| |¡S| |¡SdSr<)Ú_expr_comparatorrSrtr7r7r8rucs
 
rA)rGrBr;cCs"|jdkrtdƒ‚| ||¡dS)Nzcan't set attribute)rXÚAttributeError)r:rGrBr7r7r8Ú__set__ms
zhybrid_property.__set__rFcCs |jdkrtdƒ‚| |¡dS)Nzcan't delete attribute)r]r‡rHr7r7r8Ú
__delete__rs
zhybrid_property.__delete__rQ©Úkwr;cKs.dd„|j ¡Dƒ}|jf|Žt|ƒf|ŽS)NcSs i|]\}}| d¡s||“qS)Ú_)Ú
startswith)Ú.0ÚkeyrBr7r7r8Ú
<dictcomp>xs
þz)hybrid_property._copy.<locals>.<dictcomp>)Ú__dict__ÚitemsÚupdateÚtype)r:r‹Údefaultsr7r7r8Ú_copyws
þ zhybrid_property._copyr`cCs|S)aPrefix for a method that is overriding an existing attribute.
 
        The :attr:`.hybrid_property.overrides` accessor just returns
        this hybrid object, which when called at the class level from
        a parent class, will de-reference the "instrumented attribute"
        normally returned at this level, and allow modifying decorators
        like :meth:`.hybrid_property.expression` and
        :meth:`.hybrid_property.comparator`
        to be used without conflicting with the same-named attributes
        normally present on the :class:`.QueryableAttribute`::
 
            class SuperClass:
                # ...
 
                @hybrid_property
                def foobar(self):
                    return self._foobar
 
            class SubClass(SuperClass):
                # ...
 
                @SuperClass.foobar.overrides.expression
                def foobar(cls):
                    return func.subfoobar(self._foobar)
 
        .. versionadded:: 1.2
 
        .. seealso::
 
            :ref:`hybrid_reuse_subclass`
 
        r7rar7r7r8rb€s"zhybrid_property.overridesc@s’eZdZdZdZddœdd„Zdddœdd    „Zd
dd œd d „Zdddœdd„Zdddœdd„Z    dddœdd„Z
dddœdd„Z dddœd d!„Z d"S)#zhybrid_property._InPlacezQA builder helper for .hybrid_property.
 
        .. versionadded:: 2.0.4
 
        ©Úattrzhybrid_property[_TE]cCs
||_dSr<r—)r:r˜r7r7r8rn­sz!hybrid_property._InPlace.__init__rrŠcKs*| ¡D]\}}t|j|t|ƒƒq|jSr<)r’Úsetattrr˜r)r:r‹ÚkÚvr7r7r8Ú_set°szhybrid_property._InPlace._setz_HybridGetterType[_TE]rRcCs |j|dS)N©rS©rœrTr7r7r8rUµszhybrid_property._InPlace.getterz_HybridSetterType[_TE]rWcCs |j|dS)N©rXržrYr7r7r8rZ¸szhybrid_property._InPlace.setterz_HybridDeleterType[_TE]r\cCs |j|dS)N©r]ržr^r7r7r8r_»sz hybrid_property._InPlace.deleterz_HybridExprCallableType[_TE]rxcCs |j|dS)N©rlržryr7r7r8rmÀsz#hybrid_property._InPlace.expressionz"_HybridComparatorCallableType[_TE]©Ú
comparatorr;cCs |j|dS)N©r‚rž©r:r£r7r7r8r£Åsz#hybrid_property._InPlace.comparatorz_HybridUpdaterType[_TE]rdcCs |j|dS)N©rƒržrfr7r7r8rgÊsz*hybrid_property._InPlace.update_expressionN) r4r5r6rhÚ    __slots__rnrœrUrZr_rmr£rgr7r7r7r8Ú_InPlace¤sr¨z _InPlace[_T]cCs
t |¡S)aŠReturn the inplace mutator for this :class:`.hybrid_property`.
 
        This is to allow in-place mutation of the hybrid, allowing the first
        hybrid method of a certain name to be re-used in order to add
        more methods without having to name those methods the same, e.g.::
 
            class Interval(Base):
                # ...
 
                @hybrid_property
                def radius(self) -> float:
                    return abs(self.length) / 2
 
                @radius.inplace.setter
                def _radius_setter(self, value: float) -> None:
                    self.length = value * 2
 
                @radius.inplace.expression
                def _radius_expression(cls) -> ColumnElement[float]:
                    return type_coerce(func.abs(cls.length) / 2, Float)
 
        .. versionadded:: 2.0.4
 
        .. seealso::
 
            :ref:`hybrid_pep484_naming`
 
        )r€r¨rar7r7r8roÏszhybrid_property.inplacerRcCs |j|dS)zdProvide a modifying decorator that defines a getter method.
 
        .. versionadded:: 1.2
 
        r©r–rTr7r7r8rUïszhybrid_property.getterrVrWcCs |j|dS)z;Provide a modifying decorator that defines a setter method.rŸr©rYr7r7r8rZøszhybrid_property.setterr[r\cCs |j|dS)z=Provide a modifying decorator that defines a deletion method.r r©r^r7r7r8r_ýszhybrid_property.deleterz_HybridExprCallableType[_T]rxcCs |j|dS)a!Provide a modifying decorator that defines a SQL-expression
        producing method.
 
        When a hybrid is invoked at the class level, the SQL expression given
        here is wrapped inside of a specialized :class:`.QueryableAttribute`,
        which is the same kind of object used by the ORM to represent other
        mapped attributes.   The reason for this is so that other class-level
        attributes such as docstrings and a reference to the hybrid itself may
        be maintained within the structure that's returned, without any
        modifications to the original SQL expression passed in.
 
        .. note::
 
           When referring to a hybrid property  from an owning class (e.g.
           ``SomeClass.some_hybrid``), an instance of
           :class:`.QueryableAttribute` is returned, representing the
           expression or comparator object as well as this  hybrid object.
           However, that object itself has accessors called ``expression`` and
           ``comparator``; so when attempting to override these decorators on a
           subclass, it may be necessary to qualify it using the
           :attr:`.hybrid_property.overrides` modifier first.  See that
           modifier for details.
 
        .. seealso::
 
            :ref:`hybrid_distinct_expression`
 
        r¡r©ryr7r7r8rms zhybrid_property.expressionz!_HybridComparatorCallableType[_T]r¢cCs |j|dS)a/Provide a modifying decorator that defines a custom
        comparator producing method.
 
        The return value of the decorated method should be an instance of
        :class:`~.hybrid.Comparator`.
 
        .. note::  The :meth:`.hybrid_property.comparator` decorator
           **replaces** the use of the :meth:`.hybrid_property.expression`
           decorator.  They cannot be used together.
 
        When a hybrid is invoked at the class level, the
        :class:`~.hybrid.Comparator` object given here is wrapped inside of a
        specialized :class:`.QueryableAttribute`, which is the same kind of
        object used by the ORM to represent other mapped attributes.   The
        reason for this is so that other class-level attributes such as
        docstrings and a reference to the hybrid itself may be maintained
        within the structure that's returned, without any modifications to the
        original comparator object passed in.
 
        .. note::
 
           When referring to a hybrid property  from an owning class (e.g.
           ``SomeClass.some_hybrid``), an instance of
           :class:`.QueryableAttribute` is returned, representing the
           expression or comparator object as this  hybrid object.  However,
           that object itself has accessors called ``expression`` and
           ``comparator``; so when attempting to override these decorators on a
           subclass, it may be necessary to qualify it using the
           :attr:`.hybrid_property.overrides` modifier first.  See that
           modifier for details.
 
        r¤r©r¥r7r7r8r£$s#zhybrid_property.comparatorrcrdcCs |j|dS)aMProvide a modifying decorator that defines an UPDATE tuple
        producing method.
 
        The method accepts a single value, which is the value to be
        rendered into the SET clause of an UPDATE statement.  The method
        should then process this value into individual column expressions
        that fit into the ultimate SET clause, and return them as a
        sequence of 2-tuples.  Each tuple
        contains a column expression as the key and a value to be rendered.
 
        E.g.::
 
            class Person(Base):
                # ...
 
                first_name = Column(String)
                last_name = Column(String)
 
                @hybrid_property
                def fullname(self):
                    return first_name + " " + last_name
 
                @fullname.update_expression
                def fullname(cls, value):
                    fname, lname = value.split(" ", 1)
                    return [
                        (cls.first_name, fname),
                        (cls.last_name, lname)
                    ]
 
        .. versionadded:: 1.2
 
        r¦r©rfr7r7r8rgIs$z!hybrid_property.update_expressionz.Callable[[Any], _HybridClassLevelAccessor[_T]]cCsF|jdk    r| |j¡S|jdk    r,| |j¡S| ttt|jƒ¡SdSr<)r‚Ú_get_comparatorrlÚ    _get_exprrrIr*rSrar7r7r8r†os
 
 
 z hybrid_property._expr_comparatorcs,dddœ‡‡fdd„ }t |ˆ¡ˆ |¡S)NrzExprComparator[_T]rKcst|ˆ|ƒˆƒSr<)ÚExprComparator)rD©rlr:r7r8Ú_expr}sz(hybrid_property._get_expr.<locals>._expr)rr„rª)r:rlr®r7r­r8r«zs zhybrid_property._get_exprcs&t ˆ¡‰dddœ‡‡‡fdd„ }|S)Nrqr…)rsr;c    s\|jD]*}ˆj|jkr|jˆjˆkrˆj}q8qtj}tdˆ||ˆˆ|ƒˆjpTˆjdƒS)Nr…)Údoc)Ú__mro__r4r‘rZ_UNKNOWN_ATTR_KEYrrh)rsÚlookupÚname©r£Z
proxy_attrr:r7r8Úexpr_comparatorŠs 
 
ûþz8hybrid_property._get_comparator.<locals>.expr_comparator)rZcreate_proxied_attribute)r:r£r´r7r³r8rª„s
zhybrid_property._get_comparator)NNNNN) r4r5r6rhrzr1r3r{Ú__annotations__rnr    rurˆr‰r–rirbrr,r¨rorUrZr_rmr£rgrZmemoized_propertyr†r«rªr7r7r7r8r€)sF
ù!
    #+    "%&
 
r€c@sPeZdZdZddœdd„Zddœdd    „Zejd
dœd d „ƒZd ddœdd„Z    dS)Ú
Comparatorz‡A helper class that allows easy construction of custom
    :class:`~.orm.interfaces.PropComparator`
    classes for usage with hybrids.rJ©rmcCs
||_dSr<r·)r:rmr7r7r8rn«szComparator.__init__zroles.ColumnsClauseRoler`cCsD|j}t|ƒr| ¡}ntr*t|tƒs*t‚|}tr@t|tƒs@t‚|Sr<)rmrÚ__clause_element__r r|rÚAssertionError)r:rlZret_exprr7r7r8r¸°s
zComparator.__clause_element__zinterfaces.MapperProperty[_T]cCs
tƒ‚dSr<)ÚNotImplementedErrorrar7r7r8riÀszComparator.propertyzAliasedInsp[Any]rN)Úadapt_to_entityr;cCs|Sr<r7)r:r»r7r7r8r»ÄszComparator.adapt_to_entityN)
r4r5r6rhrnr¸rÚnon_memoized_propertyrir»r7r7r7r8r¶¦s r¶c@sŽeZdZddddœdd„Zddd    œd
d „Zejd d œdd„ƒZdddœdd„Zej    dd œdd„ƒZ
dddddœdd„Z dddddœdd„Z dS)r¬z    Type[Any]rJrQ©rDrmÚhybridcCs||_||_||_dSr<r½)r:rDrmr¾r7r7r8rnÌszExprComparator.__init__rr)rr;cCs t|j|ƒSr<)Úgetattrrm)r:rr7r7r8Ú __getattr__ÖszExprComparator.__getattr__r&r`cCs|jjSr<)r¾Úinforar7r7r8rÁÙszExprComparator.infoz(Sequence[Tuple[_DMLColumnArgument, Any]])rBr;cCsFt|jtjƒr|j |¡S|jjdk    r6|j |j|¡S|j|fgSdSr<)r|rmrrÚ_bulk_update_tuplesr¾rƒrD)r:rBr7r7r8rÂÝs
  z"ExprComparator._bulk_update_tupleszMapperProperty[_T]cCs|jjSr<)rmrirar7r7r8riçszExprComparator.propertyr'zColumnElement[Any])ÚopÚotherÚkwargsr;cOs||jf|ž|ŽSr<r·©r:rÃrÄrÅr7r7r8ÚoperateîszExprComparator.operatecKs|||jf|ŽSr<r·rÆr7r7r8Úreverse_operateószExprComparator.reverse_operateN) r4r5r6rnrÀrZro_non_memoized_propertyrÁrÂr¼rirÇrÈr7r7r7r8r¬Ës
 
r¬N)GrhÚ
__future__rÚtypingrrrrrrr    r
r r r rrÚrZormrrrrZorm.attributesrZsqlrZ sql._typingrZ sql.elementsrrZ util.typingrrrrrZorm.interfacesr Zorm.utilr!r"r#r$r%r&Z sql.operatorsr'r(r)r*r,r-r/r1r9r@rCrErIrMrOZInspectionAttrInforjrr€ZPropComparatorr¶r¬r7r7r7r8Ú<module>s„:                                           X%