SQLAlchemy 2.0.36__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (273) hide show
  1. SQLAlchemy-2.0.36.dist-info/LICENSE +19 -0
  2. SQLAlchemy-2.0.36.dist-info/METADATA +243 -0
  3. SQLAlchemy-2.0.36.dist-info/RECORD +273 -0
  4. SQLAlchemy-2.0.36.dist-info/WHEEL +5 -0
  5. SQLAlchemy-2.0.36.dist-info/top_level.txt +1 -0
  6. sqlalchemy/__init__.py +294 -0
  7. sqlalchemy/connectors/__init__.py +18 -0
  8. sqlalchemy/connectors/aioodbc.py +174 -0
  9. sqlalchemy/connectors/asyncio.py +213 -0
  10. sqlalchemy/connectors/pyodbc.py +249 -0
  11. sqlalchemy/cyextension/__init__.py +6 -0
  12. sqlalchemy/cyextension/collections.cp313-win_amd64.pyd +0 -0
  13. sqlalchemy/cyextension/collections.pyx +409 -0
  14. sqlalchemy/cyextension/immutabledict.cp313-win_amd64.pyd +0 -0
  15. sqlalchemy/cyextension/immutabledict.pxd +8 -0
  16. sqlalchemy/cyextension/immutabledict.pyx +133 -0
  17. sqlalchemy/cyextension/processors.cp313-win_amd64.pyd +0 -0
  18. sqlalchemy/cyextension/processors.pyx +68 -0
  19. sqlalchemy/cyextension/resultproxy.cp313-win_amd64.pyd +0 -0
  20. sqlalchemy/cyextension/resultproxy.pyx +102 -0
  21. sqlalchemy/cyextension/util.cp313-win_amd64.pyd +0 -0
  22. sqlalchemy/cyextension/util.pyx +91 -0
  23. sqlalchemy/dialects/__init__.py +61 -0
  24. sqlalchemy/dialects/_typing.py +25 -0
  25. sqlalchemy/dialects/mssql/__init__.py +88 -0
  26. sqlalchemy/dialects/mssql/aioodbc.py +64 -0
  27. sqlalchemy/dialects/mssql/base.py +4010 -0
  28. sqlalchemy/dialects/mssql/information_schema.py +254 -0
  29. sqlalchemy/dialects/mssql/json.py +133 -0
  30. sqlalchemy/dialects/mssql/provision.py +162 -0
  31. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  32. sqlalchemy/dialects/mssql/pyodbc.py +745 -0
  33. sqlalchemy/dialects/mysql/__init__.py +101 -0
  34. sqlalchemy/dialects/mysql/aiomysql.py +333 -0
  35. sqlalchemy/dialects/mysql/asyncmy.py +337 -0
  36. sqlalchemy/dialects/mysql/base.py +3494 -0
  37. sqlalchemy/dialects/mysql/cymysql.py +84 -0
  38. sqlalchemy/dialects/mysql/dml.py +219 -0
  39. sqlalchemy/dialects/mysql/enumerated.py +244 -0
  40. sqlalchemy/dialects/mysql/expression.py +141 -0
  41. sqlalchemy/dialects/mysql/json.py +81 -0
  42. sqlalchemy/dialects/mysql/mariadb.py +32 -0
  43. sqlalchemy/dialects/mysql/mariadbconnector.py +277 -0
  44. sqlalchemy/dialects/mysql/mysqlconnector.py +180 -0
  45. sqlalchemy/dialects/mysql/mysqldb.py +303 -0
  46. sqlalchemy/dialects/mysql/provision.py +110 -0
  47. sqlalchemy/dialects/mysql/pymysql.py +137 -0
  48. sqlalchemy/dialects/mysql/pyodbc.py +138 -0
  49. sqlalchemy/dialects/mysql/reflection.py +677 -0
  50. sqlalchemy/dialects/mysql/reserved_words.py +571 -0
  51. sqlalchemy/dialects/mysql/types.py +774 -0
  52. sqlalchemy/dialects/oracle/__init__.py +67 -0
  53. sqlalchemy/dialects/oracle/base.py +3271 -0
  54. sqlalchemy/dialects/oracle/cx_oracle.py +1483 -0
  55. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  56. sqlalchemy/dialects/oracle/oracledb.py +431 -0
  57. sqlalchemy/dialects/oracle/provision.py +220 -0
  58. sqlalchemy/dialects/oracle/types.py +287 -0
  59. sqlalchemy/dialects/postgresql/__init__.py +167 -0
  60. sqlalchemy/dialects/postgresql/_psycopg_common.py +187 -0
  61. sqlalchemy/dialects/postgresql/array.py +425 -0
  62. sqlalchemy/dialects/postgresql/asyncpg.py +1274 -0
  63. sqlalchemy/dialects/postgresql/base.py +5008 -0
  64. sqlalchemy/dialects/postgresql/dml.py +310 -0
  65. sqlalchemy/dialects/postgresql/ext.py +496 -0
  66. sqlalchemy/dialects/postgresql/hstore.py +397 -0
  67. sqlalchemy/dialects/postgresql/json.py +333 -0
  68. sqlalchemy/dialects/postgresql/named_types.py +509 -0
  69. sqlalchemy/dialects/postgresql/operators.py +129 -0
  70. sqlalchemy/dialects/postgresql/pg8000.py +662 -0
  71. sqlalchemy/dialects/postgresql/pg_catalog.py +300 -0
  72. sqlalchemy/dialects/postgresql/provision.py +175 -0
  73. sqlalchemy/dialects/postgresql/psycopg.py +772 -0
  74. sqlalchemy/dialects/postgresql/psycopg2.py +886 -0
  75. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  76. sqlalchemy/dialects/postgresql/ranges.py +1029 -0
  77. sqlalchemy/dialects/postgresql/types.py +303 -0
  78. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  79. sqlalchemy/dialects/sqlite/aiosqlite.py +396 -0
  80. sqlalchemy/dialects/sqlite/base.py +2805 -0
  81. sqlalchemy/dialects/sqlite/dml.py +240 -0
  82. sqlalchemy/dialects/sqlite/json.py +92 -0
  83. sqlalchemy/dialects/sqlite/provision.py +198 -0
  84. sqlalchemy/dialects/sqlite/pysqlcipher.py +155 -0
  85. sqlalchemy/dialects/sqlite/pysqlite.py +756 -0
  86. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  87. sqlalchemy/engine/__init__.py +62 -0
  88. sqlalchemy/engine/_py_processors.py +136 -0
  89. sqlalchemy/engine/_py_row.py +128 -0
  90. sqlalchemy/engine/_py_util.py +74 -0
  91. sqlalchemy/engine/base.py +3375 -0
  92. sqlalchemy/engine/characteristics.py +155 -0
  93. sqlalchemy/engine/create.py +875 -0
  94. sqlalchemy/engine/cursor.py +2181 -0
  95. sqlalchemy/engine/default.py +2365 -0
  96. sqlalchemy/engine/events.py +951 -0
  97. sqlalchemy/engine/interfaces.py +3403 -0
  98. sqlalchemy/engine/mock.py +131 -0
  99. sqlalchemy/engine/processors.py +61 -0
  100. sqlalchemy/engine/reflection.py +2098 -0
  101. sqlalchemy/engine/result.py +2382 -0
  102. sqlalchemy/engine/row.py +401 -0
  103. sqlalchemy/engine/strategies.py +19 -0
  104. sqlalchemy/engine/url.py +910 -0
  105. sqlalchemy/engine/util.py +167 -0
  106. sqlalchemy/event/__init__.py +25 -0
  107. sqlalchemy/event/api.py +225 -0
  108. sqlalchemy/event/attr.py +655 -0
  109. sqlalchemy/event/base.py +470 -0
  110. sqlalchemy/event/legacy.py +246 -0
  111. sqlalchemy/event/registry.py +386 -0
  112. sqlalchemy/events.py +17 -0
  113. sqlalchemy/exc.py +830 -0
  114. sqlalchemy/ext/__init__.py +11 -0
  115. sqlalchemy/ext/associationproxy.py +2013 -0
  116. sqlalchemy/ext/asyncio/__init__.py +25 -0
  117. sqlalchemy/ext/asyncio/base.py +279 -0
  118. sqlalchemy/ext/asyncio/engine.py +1466 -0
  119. sqlalchemy/ext/asyncio/exc.py +21 -0
  120. sqlalchemy/ext/asyncio/result.py +961 -0
  121. sqlalchemy/ext/asyncio/scoping.py +1614 -0
  122. sqlalchemy/ext/asyncio/session.py +1936 -0
  123. sqlalchemy/ext/automap.py +1691 -0
  124. sqlalchemy/ext/baked.py +574 -0
  125. sqlalchemy/ext/compiler.py +570 -0
  126. sqlalchemy/ext/declarative/__init__.py +65 -0
  127. sqlalchemy/ext/declarative/extensions.py +548 -0
  128. sqlalchemy/ext/horizontal_shard.py +481 -0
  129. sqlalchemy/ext/hybrid.py +1514 -0
  130. sqlalchemy/ext/indexable.py +341 -0
  131. sqlalchemy/ext/instrumentation.py +450 -0
  132. sqlalchemy/ext/mutable.py +1073 -0
  133. sqlalchemy/ext/mypy/__init__.py +6 -0
  134. sqlalchemy/ext/mypy/apply.py +320 -0
  135. sqlalchemy/ext/mypy/decl_class.py +515 -0
  136. sqlalchemy/ext/mypy/infer.py +590 -0
  137. sqlalchemy/ext/mypy/names.py +335 -0
  138. sqlalchemy/ext/mypy/plugin.py +303 -0
  139. sqlalchemy/ext/mypy/util.py +357 -0
  140. sqlalchemy/ext/orderinglist.py +416 -0
  141. sqlalchemy/ext/serializer.py +181 -0
  142. sqlalchemy/future/__init__.py +16 -0
  143. sqlalchemy/future/engine.py +15 -0
  144. sqlalchemy/inspection.py +174 -0
  145. sqlalchemy/log.py +288 -0
  146. sqlalchemy/orm/__init__.py +170 -0
  147. sqlalchemy/orm/_orm_constructors.py +2571 -0
  148. sqlalchemy/orm/_typing.py +179 -0
  149. sqlalchemy/orm/attributes.py +2835 -0
  150. sqlalchemy/orm/base.py +973 -0
  151. sqlalchemy/orm/bulk_persistence.py +2123 -0
  152. sqlalchemy/orm/clsregistry.py +571 -0
  153. sqlalchemy/orm/collections.py +1620 -0
  154. sqlalchemy/orm/context.py +3268 -0
  155. sqlalchemy/orm/decl_api.py +1883 -0
  156. sqlalchemy/orm/decl_base.py +2190 -0
  157. sqlalchemy/orm/dependency.py +1304 -0
  158. sqlalchemy/orm/descriptor_props.py +1076 -0
  159. sqlalchemy/orm/dynamic.py +300 -0
  160. sqlalchemy/orm/evaluator.py +379 -0
  161. sqlalchemy/orm/events.py +3261 -0
  162. sqlalchemy/orm/exc.py +228 -0
  163. sqlalchemy/orm/identity.py +302 -0
  164. sqlalchemy/orm/instrumentation.py +754 -0
  165. sqlalchemy/orm/interfaces.py +1474 -0
  166. sqlalchemy/orm/loading.py +1682 -0
  167. sqlalchemy/orm/mapped_collection.py +557 -0
  168. sqlalchemy/orm/mapper.py +4432 -0
  169. sqlalchemy/orm/path_registry.py +811 -0
  170. sqlalchemy/orm/persistence.py +1782 -0
  171. sqlalchemy/orm/properties.py +886 -0
  172. sqlalchemy/orm/query.py +3396 -0
  173. sqlalchemy/orm/relationships.py +3500 -0
  174. sqlalchemy/orm/scoping.py +2165 -0
  175. sqlalchemy/orm/session.py +5301 -0
  176. sqlalchemy/orm/state.py +1143 -0
  177. sqlalchemy/orm/state_changes.py +198 -0
  178. sqlalchemy/orm/strategies.py +3473 -0
  179. sqlalchemy/orm/strategy_options.py +2569 -0
  180. sqlalchemy/orm/sync.py +164 -0
  181. sqlalchemy/orm/unitofwork.py +796 -0
  182. sqlalchemy/orm/util.py +2424 -0
  183. sqlalchemy/orm/writeonly.py +678 -0
  184. sqlalchemy/pool/__init__.py +44 -0
  185. sqlalchemy/pool/base.py +1515 -0
  186. sqlalchemy/pool/events.py +370 -0
  187. sqlalchemy/pool/impl.py +581 -0
  188. sqlalchemy/py.typed +0 -0
  189. sqlalchemy/schema.py +70 -0
  190. sqlalchemy/sql/__init__.py +145 -0
  191. sqlalchemy/sql/_dml_constructors.py +140 -0
  192. sqlalchemy/sql/_elements_constructors.py +1850 -0
  193. sqlalchemy/sql/_orm_types.py +20 -0
  194. sqlalchemy/sql/_py_util.py +75 -0
  195. sqlalchemy/sql/_selectable_constructors.py +635 -0
  196. sqlalchemy/sql/_typing.py +460 -0
  197. sqlalchemy/sql/annotation.py +585 -0
  198. sqlalchemy/sql/base.py +2185 -0
  199. sqlalchemy/sql/cache_key.py +1057 -0
  200. sqlalchemy/sql/coercions.py +1405 -0
  201. sqlalchemy/sql/compiler.py +7818 -0
  202. sqlalchemy/sql/crud.py +1669 -0
  203. sqlalchemy/sql/ddl.py +1378 -0
  204. sqlalchemy/sql/default_comparator.py +552 -0
  205. sqlalchemy/sql/dml.py +1817 -0
  206. sqlalchemy/sql/elements.py +5499 -0
  207. sqlalchemy/sql/events.py +455 -0
  208. sqlalchemy/sql/expression.py +162 -0
  209. sqlalchemy/sql/functions.py +2055 -0
  210. sqlalchemy/sql/lambdas.py +1449 -0
  211. sqlalchemy/sql/naming.py +212 -0
  212. sqlalchemy/sql/operators.py +2579 -0
  213. sqlalchemy/sql/roles.py +323 -0
  214. sqlalchemy/sql/schema.py +6158 -0
  215. sqlalchemy/sql/selectable.py +7004 -0
  216. sqlalchemy/sql/sqltypes.py +3827 -0
  217. sqlalchemy/sql/traversals.py +1024 -0
  218. sqlalchemy/sql/type_api.py +2339 -0
  219. sqlalchemy/sql/util.py +1486 -0
  220. sqlalchemy/sql/visitors.py +1165 -0
  221. sqlalchemy/testing/__init__.py +96 -0
  222. sqlalchemy/testing/assertions.py +989 -0
  223. sqlalchemy/testing/assertsql.py +516 -0
  224. sqlalchemy/testing/asyncio.py +135 -0
  225. sqlalchemy/testing/config.py +427 -0
  226. sqlalchemy/testing/engines.py +472 -0
  227. sqlalchemy/testing/entities.py +117 -0
  228. sqlalchemy/testing/exclusions.py +435 -0
  229. sqlalchemy/testing/fixtures/__init__.py +28 -0
  230. sqlalchemy/testing/fixtures/base.py +366 -0
  231. sqlalchemy/testing/fixtures/mypy.py +312 -0
  232. sqlalchemy/testing/fixtures/orm.py +227 -0
  233. sqlalchemy/testing/fixtures/sql.py +503 -0
  234. sqlalchemy/testing/pickleable.py +155 -0
  235. sqlalchemy/testing/plugin/__init__.py +6 -0
  236. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  237. sqlalchemy/testing/plugin/plugin_base.py +779 -0
  238. sqlalchemy/testing/plugin/pytestplugin.py +868 -0
  239. sqlalchemy/testing/profiling.py +324 -0
  240. sqlalchemy/testing/provision.py +496 -0
  241. sqlalchemy/testing/requirements.py +1818 -0
  242. sqlalchemy/testing/schema.py +224 -0
  243. sqlalchemy/testing/suite/__init__.py +19 -0
  244. sqlalchemy/testing/suite/test_cte.py +211 -0
  245. sqlalchemy/testing/suite/test_ddl.py +389 -0
  246. sqlalchemy/testing/suite/test_deprecations.py +153 -0
  247. sqlalchemy/testing/suite/test_dialect.py +740 -0
  248. sqlalchemy/testing/suite/test_insert.py +630 -0
  249. sqlalchemy/testing/suite/test_reflection.py +3225 -0
  250. sqlalchemy/testing/suite/test_results.py +502 -0
  251. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  252. sqlalchemy/testing/suite/test_select.py +1999 -0
  253. sqlalchemy/testing/suite/test_sequence.py +317 -0
  254. sqlalchemy/testing/suite/test_types.py +2141 -0
  255. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  256. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  257. sqlalchemy/testing/util.py +537 -0
  258. sqlalchemy/testing/warnings.py +52 -0
  259. sqlalchemy/types.py +76 -0
  260. sqlalchemy/util/__init__.py +160 -0
  261. sqlalchemy/util/_collections.py +715 -0
  262. sqlalchemy/util/_concurrency_py3k.py +288 -0
  263. sqlalchemy/util/_has_cy.py +40 -0
  264. sqlalchemy/util/_py_collections.py +541 -0
  265. sqlalchemy/util/compat.py +301 -0
  266. sqlalchemy/util/concurrency.py +108 -0
  267. sqlalchemy/util/deprecations.py +401 -0
  268. sqlalchemy/util/langhelpers.py +2218 -0
  269. sqlalchemy/util/preloaded.py +150 -0
  270. sqlalchemy/util/queue.py +322 -0
  271. sqlalchemy/util/tool_support.py +201 -0
  272. sqlalchemy/util/topological.py +120 -0
  273. sqlalchemy/util/typing.py +629 -0
@@ -0,0 +1,1514 @@
1
+ # ext/hybrid.py
2
+ # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
3
+ # <see AUTHORS file>
4
+ #
5
+ # This module is part of SQLAlchemy and is released under
6
+ # the MIT License: https://www.opensource.org/licenses/mit-license.php
7
+
8
+ r"""Define attributes on ORM-mapped classes that have "hybrid" behavior.
9
+
10
+ "hybrid" means the attribute has distinct behaviors defined at the
11
+ class level and at the instance level.
12
+
13
+ The :mod:`~sqlalchemy.ext.hybrid` extension provides a special form of
14
+ method decorator and has minimal dependencies on the rest of SQLAlchemy.
15
+ Its basic theory of operation can work with any descriptor-based expression
16
+ system.
17
+
18
+ Consider a mapping ``Interval``, representing integer ``start`` and ``end``
19
+ values. We can define higher level functions on mapped classes that produce SQL
20
+ expressions at the class level, and Python expression evaluation at the
21
+ instance level. Below, each function decorated with :class:`.hybrid_method` or
22
+ :class:`.hybrid_property` may receive ``self`` as an instance of the class, or
23
+ may receive the class directly, depending on context::
24
+
25
+ from __future__ import annotations
26
+
27
+ from sqlalchemy.ext.hybrid import hybrid_method
28
+ from sqlalchemy.ext.hybrid import hybrid_property
29
+ from sqlalchemy.orm import DeclarativeBase
30
+ from sqlalchemy.orm import Mapped
31
+ from sqlalchemy.orm import mapped_column
32
+
33
+
34
+ class Base(DeclarativeBase):
35
+ pass
36
+
37
+ class Interval(Base):
38
+ __tablename__ = 'interval'
39
+
40
+ id: Mapped[int] = mapped_column(primary_key=True)
41
+ start: Mapped[int]
42
+ end: Mapped[int]
43
+
44
+ def __init__(self, start: int, end: int):
45
+ self.start = start
46
+ self.end = end
47
+
48
+ @hybrid_property
49
+ def length(self) -> int:
50
+ return self.end - self.start
51
+
52
+ @hybrid_method
53
+ def contains(self, point: int) -> bool:
54
+ return (self.start <= point) & (point <= self.end)
55
+
56
+ @hybrid_method
57
+ def intersects(self, other: Interval) -> bool:
58
+ return self.contains(other.start) | self.contains(other.end)
59
+
60
+
61
+ Above, the ``length`` property returns the difference between the
62
+ ``end`` and ``start`` attributes. With an instance of ``Interval``,
63
+ this subtraction occurs in Python, using normal Python descriptor
64
+ mechanics::
65
+
66
+ >>> i1 = Interval(5, 10)
67
+ >>> i1.length
68
+ 5
69
+
70
+ When dealing with the ``Interval`` class itself, the :class:`.hybrid_property`
71
+ descriptor evaluates the function body given the ``Interval`` class as
72
+ the argument, which when evaluated with SQLAlchemy expression mechanics
73
+ returns a new SQL expression:
74
+
75
+ .. sourcecode:: pycon+sql
76
+
77
+ >>> from sqlalchemy import select
78
+ >>> print(select(Interval.length))
79
+ {printsql}SELECT interval."end" - interval.start AS length
80
+ FROM interval{stop}
81
+
82
+
83
+ >>> print(select(Interval).filter(Interval.length > 10))
84
+ {printsql}SELECT interval.id, interval.start, interval."end"
85
+ FROM interval
86
+ WHERE interval."end" - interval.start > :param_1
87
+
88
+ Filtering methods such as :meth:`.Select.filter_by` are supported
89
+ with hybrid attributes as well:
90
+
91
+ .. sourcecode:: pycon+sql
92
+
93
+ >>> print(select(Interval).filter_by(length=5))
94
+ {printsql}SELECT interval.id, interval.start, interval."end"
95
+ FROM interval
96
+ WHERE interval."end" - interval.start = :param_1
97
+
98
+ The ``Interval`` class example also illustrates two methods,
99
+ ``contains()`` and ``intersects()``, decorated with
100
+ :class:`.hybrid_method`. This decorator applies the same idea to
101
+ methods that :class:`.hybrid_property` applies to attributes. The
102
+ methods return boolean values, and take advantage of the Python ``|``
103
+ and ``&`` bitwise operators to produce equivalent instance-level and
104
+ SQL expression-level boolean behavior:
105
+
106
+ .. sourcecode:: pycon+sql
107
+
108
+ >>> i1.contains(6)
109
+ True
110
+ >>> i1.contains(15)
111
+ False
112
+ >>> i1.intersects(Interval(7, 18))
113
+ True
114
+ >>> i1.intersects(Interval(25, 29))
115
+ False
116
+
117
+ >>> print(select(Interval).filter(Interval.contains(15)))
118
+ {printsql}SELECT interval.id, interval.start, interval."end"
119
+ FROM interval
120
+ WHERE interval.start <= :start_1 AND interval."end" > :end_1{stop}
121
+
122
+ >>> ia = aliased(Interval)
123
+ >>> print(select(Interval, ia).filter(Interval.intersects(ia)))
124
+ {printsql}SELECT interval.id, interval.start,
125
+ interval."end", interval_1.id AS interval_1_id,
126
+ interval_1.start AS interval_1_start, interval_1."end" AS interval_1_end
127
+ FROM interval, interval AS interval_1
128
+ WHERE interval.start <= interval_1.start
129
+ AND interval."end" > interval_1.start
130
+ OR interval.start <= interval_1."end"
131
+ AND interval."end" > interval_1."end"{stop}
132
+
133
+ .. _hybrid_distinct_expression:
134
+
135
+ Defining Expression Behavior Distinct from Attribute Behavior
136
+ --------------------------------------------------------------
137
+
138
+ In the previous section, our usage of the ``&`` and ``|`` bitwise operators
139
+ within the ``Interval.contains`` and ``Interval.intersects`` methods was
140
+ fortunate, considering our functions operated on two boolean values to return a
141
+ new one. In many cases, the construction of an in-Python function and a
142
+ SQLAlchemy SQL expression have enough differences that two separate Python
143
+ expressions should be defined. The :mod:`~sqlalchemy.ext.hybrid` decorator
144
+ defines a **modifier** :meth:`.hybrid_property.expression` for this purpose. As an
145
+ example we'll define the radius of the interval, which requires the usage of
146
+ the absolute value function::
147
+
148
+ from sqlalchemy import ColumnElement
149
+ from sqlalchemy import Float
150
+ from sqlalchemy import func
151
+ from sqlalchemy import type_coerce
152
+
153
+ class Interval(Base):
154
+ # ...
155
+
156
+ @hybrid_property
157
+ def radius(self) -> float:
158
+ return abs(self.length) / 2
159
+
160
+ @radius.inplace.expression
161
+ @classmethod
162
+ def _radius_expression(cls) -> ColumnElement[float]:
163
+ return type_coerce(func.abs(cls.length) / 2, Float)
164
+
165
+ In the above example, the :class:`.hybrid_property` first assigned to the
166
+ name ``Interval.radius`` is amended by a subsequent method called
167
+ ``Interval._radius_expression``, using the decorator
168
+ ``@radius.inplace.expression``, which chains together two modifiers
169
+ :attr:`.hybrid_property.inplace` and :attr:`.hybrid_property.expression`.
170
+ The use of :attr:`.hybrid_property.inplace` indicates that the
171
+ :meth:`.hybrid_property.expression` modifier should mutate the
172
+ existing hybrid object at ``Interval.radius`` in place, without creating a
173
+ new object. Notes on this modifier and its
174
+ rationale are discussed in the next section :ref:`hybrid_pep484_naming`.
175
+ The use of ``@classmethod`` is optional, and is strictly to give typing
176
+ tools a hint that ``cls`` in this case is expected to be the ``Interval``
177
+ class, and not an instance of ``Interval``.
178
+
179
+ .. note:: :attr:`.hybrid_property.inplace` as well as the use of ``@classmethod``
180
+ for proper typing support are available as of SQLAlchemy 2.0.4, and will
181
+ not work in earlier versions.
182
+
183
+ With ``Interval.radius`` now including an expression element, the SQL
184
+ function ``ABS()`` is returned when accessing ``Interval.radius``
185
+ at the class level:
186
+
187
+ .. sourcecode:: pycon+sql
188
+
189
+ >>> from sqlalchemy import select
190
+ >>> print(select(Interval).filter(Interval.radius > 5))
191
+ {printsql}SELECT interval.id, interval.start, interval."end"
192
+ FROM interval
193
+ WHERE abs(interval."end" - interval.start) / :abs_1 > :param_1
194
+
195
+
196
+ .. _hybrid_pep484_naming:
197
+
198
+ Using ``inplace`` to create pep-484 compliant hybrid properties
199
+ ---------------------------------------------------------------
200
+
201
+ In the previous section, a :class:`.hybrid_property` decorator is illustrated
202
+ which includes two separate method-level functions being decorated, both
203
+ to produce a single object attribute referenced as ``Interval.radius``.
204
+ There are actually several different modifiers we can use for
205
+ :class:`.hybrid_property` including :meth:`.hybrid_property.expression`,
206
+ :meth:`.hybrid_property.setter` and :meth:`.hybrid_property.update_expression`.
207
+
208
+ SQLAlchemy's :class:`.hybrid_property` decorator intends that adding on these
209
+ methods may be done in the identical manner as Python's built-in
210
+ ``@property`` decorator, where idiomatic use is to continue to redefine the
211
+ attribute repeatedly, using the **same attribute name** each time, as in the
212
+ example below that illustrates the use of :meth:`.hybrid_property.setter` and
213
+ :meth:`.hybrid_property.expression` for the ``Interval.radius`` descriptor::
214
+
215
+ # correct use, however is not accepted by pep-484 tooling
216
+
217
+ class Interval(Base):
218
+ # ...
219
+
220
+ @hybrid_property
221
+ def radius(self):
222
+ return abs(self.length) / 2
223
+
224
+ @radius.setter
225
+ def radius(self, value):
226
+ self.length = value * 2
227
+
228
+ @radius.expression
229
+ def radius(cls):
230
+ return type_coerce(func.abs(cls.length) / 2, Float)
231
+
232
+ Above, there are three ``Interval.radius`` methods, but as each are decorated,
233
+ first by the :class:`.hybrid_property` decorator and then by the
234
+ ``@radius`` name itself, the end effect is that ``Interval.radius`` is
235
+ a single attribute with three different functions contained within it.
236
+ This style of use is taken from `Python's documented use of @property
237
+ <https://docs.python.org/3/library/functions.html#property>`_.
238
+ It is important to note that the way both ``@property`` as well as
239
+ :class:`.hybrid_property` work, a **copy of the descriptor is made each time**.
240
+ That is, each call to ``@radius.expression``, ``@radius.setter`` etc.
241
+ make a new object entirely. This allows the attribute to be re-defined in
242
+ subclasses without issue (see :ref:`hybrid_reuse_subclass` later in this
243
+ section for how this is used).
244
+
245
+ However, the above approach is not compatible with typing tools such as
246
+ mypy and pyright. Python's own ``@property`` decorator does not have this
247
+ limitation only because
248
+ `these tools hardcode the behavior of @property
249
+ <https://github.com/python/typing/discussions/1102>`_, meaning this syntax
250
+ is not available to SQLAlchemy under :pep:`484` compliance.
251
+
252
+ In order to produce a reasonable syntax while remaining typing compliant,
253
+ the :attr:`.hybrid_property.inplace` decorator allows the same
254
+ decorator to be re-used with different method names, while still producing
255
+ a single decorator under one name::
256
+
257
+ # correct use which is also accepted by pep-484 tooling
258
+
259
+ class Interval(Base):
260
+ # ...
261
+
262
+ @hybrid_property
263
+ def radius(self) -> float:
264
+ return abs(self.length) / 2
265
+
266
+ @radius.inplace.setter
267
+ def _radius_setter(self, value: float) -> None:
268
+ # for example only
269
+ self.length = value * 2
270
+
271
+ @radius.inplace.expression
272
+ @classmethod
273
+ def _radius_expression(cls) -> ColumnElement[float]:
274
+ return type_coerce(func.abs(cls.length) / 2, Float)
275
+
276
+ Using :attr:`.hybrid_property.inplace` further qualifies the use of the
277
+ decorator that a new copy should not be made, thereby maintaining the
278
+ ``Interval.radius`` name while allowing additional methods
279
+ ``Interval._radius_setter`` and ``Interval._radius_expression`` to be
280
+ differently named.
281
+
282
+
283
+ .. versionadded:: 2.0.4 Added :attr:`.hybrid_property.inplace` to allow
284
+ less verbose construction of composite :class:`.hybrid_property` objects
285
+ while not having to use repeated method names. Additionally allowed the
286
+ use of ``@classmethod`` within :attr:`.hybrid_property.expression`,
287
+ :attr:`.hybrid_property.update_expression`, and
288
+ :attr:`.hybrid_property.comparator` to allow typing tools to identify
289
+ ``cls`` as a class and not an instance in the method signature.
290
+
291
+
292
+ Defining Setters
293
+ ----------------
294
+
295
+ The :meth:`.hybrid_property.setter` modifier allows the construction of a
296
+ custom setter method, that can modify values on the object::
297
+
298
+ class Interval(Base):
299
+ # ...
300
+
301
+ @hybrid_property
302
+ def length(self) -> int:
303
+ return self.end - self.start
304
+
305
+ @length.inplace.setter
306
+ def _length_setter(self, value: int) -> None:
307
+ self.end = self.start + value
308
+
309
+ The ``length(self, value)`` method is now called upon set::
310
+
311
+ >>> i1 = Interval(5, 10)
312
+ >>> i1.length
313
+ 5
314
+ >>> i1.length = 12
315
+ >>> i1.end
316
+ 17
317
+
318
+ .. _hybrid_bulk_update:
319
+
320
+ Allowing Bulk ORM Update
321
+ ------------------------
322
+
323
+ A hybrid can define a custom "UPDATE" handler for when using
324
+ ORM-enabled updates, allowing the hybrid to be used in the
325
+ SET clause of the update.
326
+
327
+ Normally, when using a hybrid with :func:`_sql.update`, the SQL
328
+ expression is used as the column that's the target of the SET. If our
329
+ ``Interval`` class had a hybrid ``start_point`` that linked to
330
+ ``Interval.start``, this could be substituted directly::
331
+
332
+ from sqlalchemy import update
333
+ stmt = update(Interval).values({Interval.start_point: 10})
334
+
335
+ However, when using a composite hybrid like ``Interval.length``, this
336
+ hybrid represents more than one column. We can set up a handler that will
337
+ accommodate a value passed in the VALUES expression which can affect
338
+ this, using the :meth:`.hybrid_property.update_expression` decorator.
339
+ A handler that works similarly to our setter would be::
340
+
341
+ from typing import List, Tuple, Any
342
+
343
+ class Interval(Base):
344
+ # ...
345
+
346
+ @hybrid_property
347
+ def length(self) -> int:
348
+ return self.end - self.start
349
+
350
+ @length.inplace.setter
351
+ def _length_setter(self, value: int) -> None:
352
+ self.end = self.start + value
353
+
354
+ @length.inplace.update_expression
355
+ def _length_update_expression(cls, value: Any) -> List[Tuple[Any, Any]]:
356
+ return [
357
+ (cls.end, cls.start + value)
358
+ ]
359
+
360
+ Above, if we use ``Interval.length`` in an UPDATE expression, we get
361
+ a hybrid SET expression:
362
+
363
+ .. sourcecode:: pycon+sql
364
+
365
+
366
+ >>> from sqlalchemy import update
367
+ >>> print(update(Interval).values({Interval.length: 25}))
368
+ {printsql}UPDATE interval SET "end"=(interval.start + :start_1)
369
+
370
+ This SET expression is accommodated by the ORM automatically.
371
+
372
+ .. seealso::
373
+
374
+ :ref:`orm_expression_update_delete` - includes background on ORM-enabled
375
+ UPDATE statements
376
+
377
+
378
+ Working with Relationships
379
+ --------------------------
380
+
381
+ There's no essential difference when creating hybrids that work with
382
+ related objects as opposed to column-based data. The need for distinct
383
+ expressions tends to be greater. The two variants we'll illustrate
384
+ are the "join-dependent" hybrid, and the "correlated subquery" hybrid.
385
+
386
+ Join-Dependent Relationship Hybrid
387
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
388
+
389
+ Consider the following declarative
390
+ mapping which relates a ``User`` to a ``SavingsAccount``::
391
+
392
+ from __future__ import annotations
393
+
394
+ from decimal import Decimal
395
+ from typing import cast
396
+ from typing import List
397
+ from typing import Optional
398
+
399
+ from sqlalchemy import ForeignKey
400
+ from sqlalchemy import Numeric
401
+ from sqlalchemy import String
402
+ from sqlalchemy import SQLColumnExpression
403
+ from sqlalchemy.ext.hybrid import hybrid_property
404
+ from sqlalchemy.orm import DeclarativeBase
405
+ from sqlalchemy.orm import Mapped
406
+ from sqlalchemy.orm import mapped_column
407
+ from sqlalchemy.orm import relationship
408
+
409
+
410
+ class Base(DeclarativeBase):
411
+ pass
412
+
413
+
414
+ class SavingsAccount(Base):
415
+ __tablename__ = 'account'
416
+ id: Mapped[int] = mapped_column(primary_key=True)
417
+ user_id: Mapped[int] = mapped_column(ForeignKey('user.id'))
418
+ balance: Mapped[Decimal] = mapped_column(Numeric(15, 5))
419
+
420
+ owner: Mapped[User] = relationship(back_populates="accounts")
421
+
422
+ class User(Base):
423
+ __tablename__ = 'user'
424
+ id: Mapped[int] = mapped_column(primary_key=True)
425
+ name: Mapped[str] = mapped_column(String(100))
426
+
427
+ accounts: Mapped[List[SavingsAccount]] = relationship(
428
+ back_populates="owner", lazy="selectin"
429
+ )
430
+
431
+ @hybrid_property
432
+ def balance(self) -> Optional[Decimal]:
433
+ if self.accounts:
434
+ return self.accounts[0].balance
435
+ else:
436
+ return None
437
+
438
+ @balance.inplace.setter
439
+ def _balance_setter(self, value: Optional[Decimal]) -> None:
440
+ assert value is not None
441
+
442
+ if not self.accounts:
443
+ account = SavingsAccount(owner=self)
444
+ else:
445
+ account = self.accounts[0]
446
+ account.balance = value
447
+
448
+ @balance.inplace.expression
449
+ @classmethod
450
+ def _balance_expression(cls) -> SQLColumnExpression[Optional[Decimal]]:
451
+ return cast("SQLColumnExpression[Optional[Decimal]]", SavingsAccount.balance)
452
+
453
+ The above hybrid property ``balance`` works with the first
454
+ ``SavingsAccount`` entry in the list of accounts for this user. The
455
+ in-Python getter/setter methods can treat ``accounts`` as a Python
456
+ list available on ``self``.
457
+
458
+ .. tip:: The ``User.balance`` getter in the above example accesses the
459
+ ``self.acccounts`` collection, which will normally be loaded via the
460
+ :func:`.selectinload` loader strategy configured on the ``User.balance``
461
+ :func:`_orm.relationship`. The default loader strategy when not otherwise
462
+ stated on :func:`_orm.relationship` is :func:`.lazyload`, which emits SQL on
463
+ demand. When using asyncio, on-demand loaders such as :func:`.lazyload` are
464
+ not supported, so care should be taken to ensure the ``self.accounts``
465
+ collection is accessible to this hybrid accessor when using asyncio.
466
+
467
+ At the expression level, it's expected that the ``User`` class will
468
+ be used in an appropriate context such that an appropriate join to
469
+ ``SavingsAccount`` will be present:
470
+
471
+ .. sourcecode:: pycon+sql
472
+
473
+ >>> from sqlalchemy import select
474
+ >>> print(select(User, User.balance).
475
+ ... join(User.accounts).filter(User.balance > 5000))
476
+ {printsql}SELECT "user".id AS user_id, "user".name AS user_name,
477
+ account.balance AS account_balance
478
+ FROM "user" JOIN account ON "user".id = account.user_id
479
+ WHERE account.balance > :balance_1
480
+
481
+ Note however, that while the instance level accessors need to worry
482
+ about whether ``self.accounts`` is even present, this issue expresses
483
+ itself differently at the SQL expression level, where we basically
484
+ would use an outer join:
485
+
486
+ .. sourcecode:: pycon+sql
487
+
488
+ >>> from sqlalchemy import select
489
+ >>> from sqlalchemy import or_
490
+ >>> print (select(User, User.balance).outerjoin(User.accounts).
491
+ ... filter(or_(User.balance < 5000, User.balance == None)))
492
+ {printsql}SELECT "user".id AS user_id, "user".name AS user_name,
493
+ account.balance AS account_balance
494
+ FROM "user" LEFT OUTER JOIN account ON "user".id = account.user_id
495
+ WHERE account.balance < :balance_1 OR account.balance IS NULL
496
+
497
+ Correlated Subquery Relationship Hybrid
498
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
499
+
500
+ We can, of course, forego being dependent on the enclosing query's usage
501
+ of joins in favor of the correlated subquery, which can portably be packed
502
+ into a single column expression. A correlated subquery is more portable, but
503
+ often performs more poorly at the SQL level. Using the same technique
504
+ illustrated at :ref:`mapper_column_property_sql_expressions`,
505
+ we can adjust our ``SavingsAccount`` example to aggregate the balances for
506
+ *all* accounts, and use a correlated subquery for the column expression::
507
+
508
+ from __future__ import annotations
509
+
510
+ from decimal import Decimal
511
+ from typing import List
512
+
513
+ from sqlalchemy import ForeignKey
514
+ from sqlalchemy import func
515
+ from sqlalchemy import Numeric
516
+ from sqlalchemy import select
517
+ from sqlalchemy import SQLColumnExpression
518
+ from sqlalchemy import String
519
+ from sqlalchemy.ext.hybrid import hybrid_property
520
+ from sqlalchemy.orm import DeclarativeBase
521
+ from sqlalchemy.orm import Mapped
522
+ from sqlalchemy.orm import mapped_column
523
+ from sqlalchemy.orm import relationship
524
+
525
+
526
+ class Base(DeclarativeBase):
527
+ pass
528
+
529
+
530
+ class SavingsAccount(Base):
531
+ __tablename__ = 'account'
532
+ id: Mapped[int] = mapped_column(primary_key=True)
533
+ user_id: Mapped[int] = mapped_column(ForeignKey('user.id'))
534
+ balance: Mapped[Decimal] = mapped_column(Numeric(15, 5))
535
+
536
+ owner: Mapped[User] = relationship(back_populates="accounts")
537
+
538
+ class User(Base):
539
+ __tablename__ = 'user'
540
+ id: Mapped[int] = mapped_column(primary_key=True)
541
+ name: Mapped[str] = mapped_column(String(100))
542
+
543
+ accounts: Mapped[List[SavingsAccount]] = relationship(
544
+ back_populates="owner", lazy="selectin"
545
+ )
546
+
547
+ @hybrid_property
548
+ def balance(self) -> Decimal:
549
+ return sum((acc.balance for acc in self.accounts), start=Decimal("0"))
550
+
551
+ @balance.inplace.expression
552
+ @classmethod
553
+ def _balance_expression(cls) -> SQLColumnExpression[Decimal]:
554
+ return (
555
+ select(func.sum(SavingsAccount.balance))
556
+ .where(SavingsAccount.user_id == cls.id)
557
+ .label("total_balance")
558
+ )
559
+
560
+
561
+ The above recipe will give us the ``balance`` column which renders
562
+ a correlated SELECT:
563
+
564
+ .. sourcecode:: pycon+sql
565
+
566
+ >>> from sqlalchemy import select
567
+ >>> print(select(User).filter(User.balance > 400))
568
+ {printsql}SELECT "user".id, "user".name
569
+ FROM "user"
570
+ WHERE (
571
+ SELECT sum(account.balance) AS sum_1 FROM account
572
+ WHERE account.user_id = "user".id
573
+ ) > :param_1
574
+
575
+
576
+ .. _hybrid_custom_comparators:
577
+
578
+ Building Custom Comparators
579
+ ---------------------------
580
+
581
+ The hybrid property also includes a helper that allows construction of
582
+ custom comparators. A comparator object allows one to customize the
583
+ behavior of each SQLAlchemy expression operator individually. They
584
+ are useful when creating custom types that have some highly
585
+ idiosyncratic behavior on the SQL side.
586
+
587
+ .. note:: The :meth:`.hybrid_property.comparator` decorator introduced
588
+ in this section **replaces** the use of the
589
+ :meth:`.hybrid_property.expression` decorator.
590
+ They cannot be used together.
591
+
592
+ The example class below allows case-insensitive comparisons on the attribute
593
+ named ``word_insensitive``::
594
+
595
+ from __future__ import annotations
596
+
597
+ from typing import Any
598
+
599
+ from sqlalchemy import ColumnElement
600
+ from sqlalchemy import func
601
+ from sqlalchemy.ext.hybrid import Comparator
602
+ from sqlalchemy.ext.hybrid import hybrid_property
603
+ from sqlalchemy.orm import DeclarativeBase
604
+ from sqlalchemy.orm import Mapped
605
+ from sqlalchemy.orm import mapped_column
606
+
607
+ class Base(DeclarativeBase):
608
+ pass
609
+
610
+
611
+ class CaseInsensitiveComparator(Comparator[str]):
612
+ def __eq__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501
613
+ return func.lower(self.__clause_element__()) == func.lower(other)
614
+
615
+ class SearchWord(Base):
616
+ __tablename__ = 'searchword'
617
+
618
+ id: Mapped[int] = mapped_column(primary_key=True)
619
+ word: Mapped[str]
620
+
621
+ @hybrid_property
622
+ def word_insensitive(self) -> str:
623
+ return self.word.lower()
624
+
625
+ @word_insensitive.inplace.comparator
626
+ @classmethod
627
+ def _word_insensitive_comparator(cls) -> CaseInsensitiveComparator:
628
+ return CaseInsensitiveComparator(cls.word)
629
+
630
+ Above, SQL expressions against ``word_insensitive`` will apply the ``LOWER()``
631
+ SQL function to both sides:
632
+
633
+ .. sourcecode:: pycon+sql
634
+
635
+ >>> from sqlalchemy import select
636
+ >>> print(select(SearchWord).filter_by(word_insensitive="Trucks"))
637
+ {printsql}SELECT searchword.id, searchword.word
638
+ FROM searchword
639
+ WHERE lower(searchword.word) = lower(:lower_1)
640
+
641
+
642
+ The ``CaseInsensitiveComparator`` above implements part of the
643
+ :class:`.ColumnOperators` interface. A "coercion" operation like
644
+ lowercasing can be applied to all comparison operations (i.e. ``eq``,
645
+ ``lt``, ``gt``, etc.) using :meth:`.Operators.operate`::
646
+
647
+ class CaseInsensitiveComparator(Comparator):
648
+ def operate(self, op, other, **kwargs):
649
+ return op(
650
+ func.lower(self.__clause_element__()),
651
+ func.lower(other),
652
+ **kwargs,
653
+ )
654
+
655
+ .. _hybrid_reuse_subclass:
656
+
657
+ Reusing Hybrid Properties across Subclasses
658
+ -------------------------------------------
659
+
660
+ A hybrid can be referred to from a superclass, to allow modifying
661
+ methods like :meth:`.hybrid_property.getter`, :meth:`.hybrid_property.setter`
662
+ to be used to redefine those methods on a subclass. This is similar to
663
+ how the standard Python ``@property`` object works::
664
+
665
+ class FirstNameOnly(Base):
666
+ # ...
667
+
668
+ first_name: Mapped[str]
669
+
670
+ @hybrid_property
671
+ def name(self) -> str:
672
+ return self.first_name
673
+
674
+ @name.inplace.setter
675
+ def _name_setter(self, value: str) -> None:
676
+ self.first_name = value
677
+
678
+ class FirstNameLastName(FirstNameOnly):
679
+ # ...
680
+
681
+ last_name: Mapped[str]
682
+
683
+ # 'inplace' is not used here; calling getter creates a copy
684
+ # of FirstNameOnly.name that is local to FirstNameLastName
685
+ @FirstNameOnly.name.getter
686
+ def name(self) -> str:
687
+ return self.first_name + ' ' + self.last_name
688
+
689
+ @name.inplace.setter
690
+ def _name_setter(self, value: str) -> None:
691
+ self.first_name, self.last_name = value.split(' ', 1)
692
+
693
+ Above, the ``FirstNameLastName`` class refers to the hybrid from
694
+ ``FirstNameOnly.name`` to repurpose its getter and setter for the subclass.
695
+
696
+ When overriding :meth:`.hybrid_property.expression` and
697
+ :meth:`.hybrid_property.comparator` alone as the first reference to the
698
+ superclass, these names conflict with the same-named accessors on the class-
699
+ level :class:`.QueryableAttribute` object returned at the class level. To
700
+ override these methods when referring directly to the parent class descriptor,
701
+ add the special qualifier :attr:`.hybrid_property.overrides`, which will de-
702
+ reference the instrumented attribute back to the hybrid object::
703
+
704
+ class FirstNameLastName(FirstNameOnly):
705
+ # ...
706
+
707
+ last_name: Mapped[str]
708
+
709
+ @FirstNameOnly.name.overrides.expression
710
+ @classmethod
711
+ def name(cls):
712
+ return func.concat(cls.first_name, ' ', cls.last_name)
713
+
714
+
715
+ Hybrid Value Objects
716
+ --------------------
717
+
718
+ Note in our previous example, if we were to compare the ``word_insensitive``
719
+ attribute of a ``SearchWord`` instance to a plain Python string, the plain
720
+ Python string would not be coerced to lower case - the
721
+ ``CaseInsensitiveComparator`` we built, being returned by
722
+ ``@word_insensitive.comparator``, only applies to the SQL side.
723
+
724
+ A more comprehensive form of the custom comparator is to construct a *Hybrid
725
+ Value Object*. This technique applies the target value or expression to a value
726
+ object which is then returned by the accessor in all cases. The value object
727
+ allows control of all operations upon the value as well as how compared values
728
+ are treated, both on the SQL expression side as well as the Python value side.
729
+ Replacing the previous ``CaseInsensitiveComparator`` class with a new
730
+ ``CaseInsensitiveWord`` class::
731
+
732
+ class CaseInsensitiveWord(Comparator):
733
+ "Hybrid value representing a lower case representation of a word."
734
+
735
+ def __init__(self, word):
736
+ if isinstance(word, basestring):
737
+ self.word = word.lower()
738
+ elif isinstance(word, CaseInsensitiveWord):
739
+ self.word = word.word
740
+ else:
741
+ self.word = func.lower(word)
742
+
743
+ def operate(self, op, other, **kwargs):
744
+ if not isinstance(other, CaseInsensitiveWord):
745
+ other = CaseInsensitiveWord(other)
746
+ return op(self.word, other.word, **kwargs)
747
+
748
+ def __clause_element__(self):
749
+ return self.word
750
+
751
+ def __str__(self):
752
+ return self.word
753
+
754
+ key = 'word'
755
+ "Label to apply to Query tuple results"
756
+
757
+ Above, the ``CaseInsensitiveWord`` object represents ``self.word``, which may
758
+ be a SQL function, or may be a Python native. By overriding ``operate()`` and
759
+ ``__clause_element__()`` to work in terms of ``self.word``, all comparison
760
+ operations will work against the "converted" form of ``word``, whether it be
761
+ SQL side or Python side. Our ``SearchWord`` class can now deliver the
762
+ ``CaseInsensitiveWord`` object unconditionally from a single hybrid call::
763
+
764
+ class SearchWord(Base):
765
+ __tablename__ = 'searchword'
766
+ id: Mapped[int] = mapped_column(primary_key=True)
767
+ word: Mapped[str]
768
+
769
+ @hybrid_property
770
+ def word_insensitive(self) -> CaseInsensitiveWord:
771
+ return CaseInsensitiveWord(self.word)
772
+
773
+ The ``word_insensitive`` attribute now has case-insensitive comparison behavior
774
+ universally, including SQL expression vs. Python expression (note the Python
775
+ value is converted to lower case on the Python side here):
776
+
777
+ .. sourcecode:: pycon+sql
778
+
779
+ >>> print(select(SearchWord).filter_by(word_insensitive="Trucks"))
780
+ {printsql}SELECT searchword.id AS searchword_id, searchword.word AS searchword_word
781
+ FROM searchword
782
+ WHERE lower(searchword.word) = :lower_1
783
+
784
+ SQL expression versus SQL expression:
785
+
786
+ .. sourcecode:: pycon+sql
787
+
788
+ >>> from sqlalchemy.orm import aliased
789
+ >>> sw1 = aliased(SearchWord)
790
+ >>> sw2 = aliased(SearchWord)
791
+ >>> print(
792
+ ... select(sw1.word_insensitive, sw2.word_insensitive).filter(
793
+ ... sw1.word_insensitive > sw2.word_insensitive
794
+ ... )
795
+ ... )
796
+ {printsql}SELECT lower(searchword_1.word) AS lower_1,
797
+ lower(searchword_2.word) AS lower_2
798
+ FROM searchword AS searchword_1, searchword AS searchword_2
799
+ WHERE lower(searchword_1.word) > lower(searchword_2.word)
800
+
801
+ Python only expression::
802
+
803
+ >>> ws1 = SearchWord(word="SomeWord")
804
+ >>> ws1.word_insensitive == "sOmEwOrD"
805
+ True
806
+ >>> ws1.word_insensitive == "XOmEwOrX"
807
+ False
808
+ >>> print(ws1.word_insensitive)
809
+ someword
810
+
811
+ The Hybrid Value pattern is very useful for any kind of value that may have
812
+ multiple representations, such as timestamps, time deltas, units of
813
+ measurement, currencies and encrypted passwords.
814
+
815
+ .. seealso::
816
+
817
+ `Hybrids and Value Agnostic Types
818
+ <https://techspot.zzzeek.org/2011/10/21/hybrids-and-value-agnostic-types/>`_
819
+ - on the techspot.zzzeek.org blog
820
+
821
+ `Value Agnostic Types, Part II
822
+ <https://techspot.zzzeek.org/2011/10/29/value-agnostic-types-part-ii/>`_ -
823
+ on the techspot.zzzeek.org blog
824
+
825
+
826
+ """ # noqa
827
+
828
+ from __future__ import annotations
829
+
830
+ from typing import Any
831
+ from typing import Callable
832
+ from typing import cast
833
+ from typing import Generic
834
+ from typing import List
835
+ from typing import Optional
836
+ from typing import overload
837
+ from typing import Sequence
838
+ from typing import Tuple
839
+ from typing import Type
840
+ from typing import TYPE_CHECKING
841
+ from typing import TypeVar
842
+ from typing import Union
843
+
844
+ from .. import util
845
+ from ..orm import attributes
846
+ from ..orm import InspectionAttrExtensionType
847
+ from ..orm import interfaces
848
+ from ..orm import ORMDescriptor
849
+ from ..orm.attributes import QueryableAttribute
850
+ from ..sql import roles
851
+ from ..sql._typing import is_has_clause_element
852
+ from ..sql.elements import ColumnElement
853
+ from ..sql.elements import SQLCoreOperations
854
+ from ..util.typing import Concatenate
855
+ from ..util.typing import Literal
856
+ from ..util.typing import ParamSpec
857
+ from ..util.typing import Protocol
858
+ from ..util.typing import Self
859
+
860
+ if TYPE_CHECKING:
861
+ from ..orm.interfaces import MapperProperty
862
+ from ..orm.util import AliasedInsp
863
+ from ..sql import SQLColumnExpression
864
+ from ..sql._typing import _ColumnExpressionArgument
865
+ from ..sql._typing import _DMLColumnArgument
866
+ from ..sql._typing import _HasClauseElement
867
+ from ..sql._typing import _InfoType
868
+ from ..sql.operators import OperatorType
869
+
870
+ _P = ParamSpec("_P")
871
+ _R = TypeVar("_R")
872
+ _T = TypeVar("_T", bound=Any)
873
+ _TE = TypeVar("_TE", bound=Any)
874
+ _T_co = TypeVar("_T_co", bound=Any, covariant=True)
875
+ _T_con = TypeVar("_T_con", bound=Any, contravariant=True)
876
+
877
+
878
+ class HybridExtensionType(InspectionAttrExtensionType):
879
+ HYBRID_METHOD = "HYBRID_METHOD"
880
+ """Symbol indicating an :class:`InspectionAttr` that's
881
+ of type :class:`.hybrid_method`.
882
+
883
+ Is assigned to the :attr:`.InspectionAttr.extension_type`
884
+ attribute.
885
+
886
+ .. seealso::
887
+
888
+ :attr:`_orm.Mapper.all_orm_attributes`
889
+
890
+ """
891
+
892
+ HYBRID_PROPERTY = "HYBRID_PROPERTY"
893
+ """Symbol indicating an :class:`InspectionAttr` that's
894
+ of type :class:`.hybrid_method`.
895
+
896
+ Is assigned to the :attr:`.InspectionAttr.extension_type`
897
+ attribute.
898
+
899
+ .. seealso::
900
+
901
+ :attr:`_orm.Mapper.all_orm_attributes`
902
+
903
+ """
904
+
905
+
906
+ class _HybridGetterType(Protocol[_T_co]):
907
+ def __call__(s, self: Any) -> _T_co: ...
908
+
909
+
910
+ class _HybridSetterType(Protocol[_T_con]):
911
+ def __call__(s, self: Any, value: _T_con) -> None: ...
912
+
913
+
914
+ class _HybridUpdaterType(Protocol[_T_con]):
915
+ def __call__(
916
+ s,
917
+ cls: Any,
918
+ value: Union[_T_con, _ColumnExpressionArgument[_T_con]],
919
+ ) -> List[Tuple[_DMLColumnArgument, Any]]: ...
920
+
921
+
922
+ class _HybridDeleterType(Protocol[_T_co]):
923
+ def __call__(s, self: Any) -> None: ...
924
+
925
+
926
+ class _HybridExprCallableType(Protocol[_T_co]):
927
+ def __call__(
928
+ s, cls: Any
929
+ ) -> Union[_HasClauseElement[_T_co], SQLColumnExpression[_T_co]]: ...
930
+
931
+
932
+ class _HybridComparatorCallableType(Protocol[_T]):
933
+ def __call__(self, cls: Any) -> Comparator[_T]: ...
934
+
935
+
936
+ class _HybridClassLevelAccessor(QueryableAttribute[_T]):
937
+ """Describe the object returned by a hybrid_property() when
938
+ called as a class-level descriptor.
939
+
940
+ """
941
+
942
+ if TYPE_CHECKING:
943
+
944
+ def getter(
945
+ self, fget: _HybridGetterType[_T]
946
+ ) -> hybrid_property[_T]: ...
947
+
948
+ def setter(
949
+ self, fset: _HybridSetterType[_T]
950
+ ) -> hybrid_property[_T]: ...
951
+
952
+ def deleter(
953
+ self, fdel: _HybridDeleterType[_T]
954
+ ) -> hybrid_property[_T]: ...
955
+
956
+ @property
957
+ def overrides(self) -> hybrid_property[_T]: ...
958
+
959
+ def update_expression(
960
+ self, meth: _HybridUpdaterType[_T]
961
+ ) -> hybrid_property[_T]: ...
962
+
963
+
964
+ class hybrid_method(interfaces.InspectionAttrInfo, Generic[_P, _R]):
965
+ """A decorator which allows definition of a Python object method with both
966
+ instance-level and class-level behavior.
967
+
968
+ """
969
+
970
+ is_attribute = True
971
+ extension_type = HybridExtensionType.HYBRID_METHOD
972
+
973
+ def __init__(
974
+ self,
975
+ func: Callable[Concatenate[Any, _P], _R],
976
+ expr: Optional[
977
+ Callable[Concatenate[Any, _P], SQLCoreOperations[_R]]
978
+ ] = None,
979
+ ):
980
+ """Create a new :class:`.hybrid_method`.
981
+
982
+ Usage is typically via decorator::
983
+
984
+ from sqlalchemy.ext.hybrid import hybrid_method
985
+
986
+ class SomeClass:
987
+ @hybrid_method
988
+ def value(self, x, y):
989
+ return self._value + x + y
990
+
991
+ @value.expression
992
+ @classmethod
993
+ def value(cls, x, y):
994
+ return func.some_function(cls._value, x, y)
995
+
996
+ """
997
+ self.func = func
998
+ if expr is not None:
999
+ self.expression(expr)
1000
+ else:
1001
+ self.expression(func) # type: ignore
1002
+
1003
+ @property
1004
+ def inplace(self) -> Self:
1005
+ """Return the inplace mutator for this :class:`.hybrid_method`.
1006
+
1007
+ The :class:`.hybrid_method` class already performs "in place" mutation
1008
+ when the :meth:`.hybrid_method.expression` decorator is called,
1009
+ so this attribute returns Self.
1010
+
1011
+ .. versionadded:: 2.0.4
1012
+
1013
+ .. seealso::
1014
+
1015
+ :ref:`hybrid_pep484_naming`
1016
+
1017
+ """
1018
+ return self
1019
+
1020
+ @overload
1021
+ def __get__(
1022
+ self, instance: Literal[None], owner: Type[object]
1023
+ ) -> Callable[_P, SQLCoreOperations[_R]]: ...
1024
+
1025
+ @overload
1026
+ def __get__(
1027
+ self, instance: object, owner: Type[object]
1028
+ ) -> Callable[_P, _R]: ...
1029
+
1030
+ def __get__(
1031
+ self, instance: Optional[object], owner: Type[object]
1032
+ ) -> Union[Callable[_P, _R], Callable[_P, SQLCoreOperations[_R]]]:
1033
+ if instance is None:
1034
+ return self.expr.__get__(owner, owner) # type: ignore
1035
+ else:
1036
+ return self.func.__get__(instance, owner) # type: ignore
1037
+
1038
+ def expression(
1039
+ self, expr: Callable[Concatenate[Any, _P], SQLCoreOperations[_R]]
1040
+ ) -> hybrid_method[_P, _R]:
1041
+ """Provide a modifying decorator that defines a
1042
+ SQL-expression producing method."""
1043
+
1044
+ self.expr = expr
1045
+ if not self.expr.__doc__:
1046
+ self.expr.__doc__ = self.func.__doc__
1047
+ return self
1048
+
1049
+
1050
+ def _unwrap_classmethod(meth: _T) -> _T:
1051
+ if isinstance(meth, classmethod):
1052
+ return meth.__func__ # type: ignore
1053
+ else:
1054
+ return meth
1055
+
1056
+
1057
+ class hybrid_property(interfaces.InspectionAttrInfo, ORMDescriptor[_T]):
1058
+ """A decorator which allows definition of a Python descriptor with both
1059
+ instance-level and class-level behavior.
1060
+
1061
+ """
1062
+
1063
+ is_attribute = True
1064
+ extension_type = HybridExtensionType.HYBRID_PROPERTY
1065
+
1066
+ __name__: str
1067
+
1068
+ def __init__(
1069
+ self,
1070
+ fget: _HybridGetterType[_T],
1071
+ fset: Optional[_HybridSetterType[_T]] = None,
1072
+ fdel: Optional[_HybridDeleterType[_T]] = None,
1073
+ expr: Optional[_HybridExprCallableType[_T]] = None,
1074
+ custom_comparator: Optional[Comparator[_T]] = None,
1075
+ update_expr: Optional[_HybridUpdaterType[_T]] = None,
1076
+ ):
1077
+ """Create a new :class:`.hybrid_property`.
1078
+
1079
+ Usage is typically via decorator::
1080
+
1081
+ from sqlalchemy.ext.hybrid import hybrid_property
1082
+
1083
+ class SomeClass:
1084
+ @hybrid_property
1085
+ def value(self):
1086
+ return self._value
1087
+
1088
+ @value.setter
1089
+ def value(self, value):
1090
+ self._value = value
1091
+
1092
+ """
1093
+ self.fget = fget
1094
+ self.fset = fset
1095
+ self.fdel = fdel
1096
+ self.expr = _unwrap_classmethod(expr)
1097
+ self.custom_comparator = _unwrap_classmethod(custom_comparator)
1098
+ self.update_expr = _unwrap_classmethod(update_expr)
1099
+ util.update_wrapper(self, fget) # type: ignore[arg-type]
1100
+
1101
+ @overload
1102
+ def __get__(self, instance: Any, owner: Literal[None]) -> Self: ...
1103
+
1104
+ @overload
1105
+ def __get__(
1106
+ self, instance: Literal[None], owner: Type[object]
1107
+ ) -> _HybridClassLevelAccessor[_T]: ...
1108
+
1109
+ @overload
1110
+ def __get__(self, instance: object, owner: Type[object]) -> _T: ...
1111
+
1112
+ def __get__(
1113
+ self, instance: Optional[object], owner: Optional[Type[object]]
1114
+ ) -> Union[hybrid_property[_T], _HybridClassLevelAccessor[_T], _T]:
1115
+ if owner is None:
1116
+ return self
1117
+ elif instance is None:
1118
+ return self._expr_comparator(owner)
1119
+ else:
1120
+ return self.fget(instance)
1121
+
1122
+ def __set__(self, instance: object, value: Any) -> None:
1123
+ if self.fset is None:
1124
+ raise AttributeError("can't set attribute")
1125
+ self.fset(instance, value)
1126
+
1127
+ def __delete__(self, instance: object) -> None:
1128
+ if self.fdel is None:
1129
+ raise AttributeError("can't delete attribute")
1130
+ self.fdel(instance)
1131
+
1132
+ def _copy(self, **kw: Any) -> hybrid_property[_T]:
1133
+ defaults = {
1134
+ key: value
1135
+ for key, value in self.__dict__.items()
1136
+ if not key.startswith("_")
1137
+ }
1138
+ defaults.update(**kw)
1139
+ return type(self)(**defaults)
1140
+
1141
+ @property
1142
+ def overrides(self) -> Self:
1143
+ """Prefix for a method that is overriding an existing attribute.
1144
+
1145
+ The :attr:`.hybrid_property.overrides` accessor just returns
1146
+ this hybrid object, which when called at the class level from
1147
+ a parent class, will de-reference the "instrumented attribute"
1148
+ normally returned at this level, and allow modifying decorators
1149
+ like :meth:`.hybrid_property.expression` and
1150
+ :meth:`.hybrid_property.comparator`
1151
+ to be used without conflicting with the same-named attributes
1152
+ normally present on the :class:`.QueryableAttribute`::
1153
+
1154
+ class SuperClass:
1155
+ # ...
1156
+
1157
+ @hybrid_property
1158
+ def foobar(self):
1159
+ return self._foobar
1160
+
1161
+ class SubClass(SuperClass):
1162
+ # ...
1163
+
1164
+ @SuperClass.foobar.overrides.expression
1165
+ def foobar(cls):
1166
+ return func.subfoobar(self._foobar)
1167
+
1168
+ .. versionadded:: 1.2
1169
+
1170
+ .. seealso::
1171
+
1172
+ :ref:`hybrid_reuse_subclass`
1173
+
1174
+ """
1175
+ return self
1176
+
1177
+ class _InPlace(Generic[_TE]):
1178
+ """A builder helper for .hybrid_property.
1179
+
1180
+ .. versionadded:: 2.0.4
1181
+
1182
+ """
1183
+
1184
+ __slots__ = ("attr",)
1185
+
1186
+ def __init__(self, attr: hybrid_property[_TE]):
1187
+ self.attr = attr
1188
+
1189
+ def _set(self, **kw: Any) -> hybrid_property[_TE]:
1190
+ for k, v in kw.items():
1191
+ setattr(self.attr, k, _unwrap_classmethod(v))
1192
+ return self.attr
1193
+
1194
+ def getter(self, fget: _HybridGetterType[_TE]) -> hybrid_property[_TE]:
1195
+ return self._set(fget=fget)
1196
+
1197
+ def setter(self, fset: _HybridSetterType[_TE]) -> hybrid_property[_TE]:
1198
+ return self._set(fset=fset)
1199
+
1200
+ def deleter(
1201
+ self, fdel: _HybridDeleterType[_TE]
1202
+ ) -> hybrid_property[_TE]:
1203
+ return self._set(fdel=fdel)
1204
+
1205
+ def expression(
1206
+ self, expr: _HybridExprCallableType[_TE]
1207
+ ) -> hybrid_property[_TE]:
1208
+ return self._set(expr=expr)
1209
+
1210
+ def comparator(
1211
+ self, comparator: _HybridComparatorCallableType[_TE]
1212
+ ) -> hybrid_property[_TE]:
1213
+ return self._set(custom_comparator=comparator)
1214
+
1215
+ def update_expression(
1216
+ self, meth: _HybridUpdaterType[_TE]
1217
+ ) -> hybrid_property[_TE]:
1218
+ return self._set(update_expr=meth)
1219
+
1220
+ @property
1221
+ def inplace(self) -> _InPlace[_T]:
1222
+ """Return the inplace mutator for this :class:`.hybrid_property`.
1223
+
1224
+ This is to allow in-place mutation of the hybrid, allowing the first
1225
+ hybrid method of a certain name to be re-used in order to add
1226
+ more methods without having to name those methods the same, e.g.::
1227
+
1228
+ class Interval(Base):
1229
+ # ...
1230
+
1231
+ @hybrid_property
1232
+ def radius(self) -> float:
1233
+ return abs(self.length) / 2
1234
+
1235
+ @radius.inplace.setter
1236
+ def _radius_setter(self, value: float) -> None:
1237
+ self.length = value * 2
1238
+
1239
+ @radius.inplace.expression
1240
+ def _radius_expression(cls) -> ColumnElement[float]:
1241
+ return type_coerce(func.abs(cls.length) / 2, Float)
1242
+
1243
+ .. versionadded:: 2.0.4
1244
+
1245
+ .. seealso::
1246
+
1247
+ :ref:`hybrid_pep484_naming`
1248
+
1249
+ """
1250
+ return hybrid_property._InPlace(self)
1251
+
1252
+ def getter(self, fget: _HybridGetterType[_T]) -> hybrid_property[_T]:
1253
+ """Provide a modifying decorator that defines a getter method.
1254
+
1255
+ .. versionadded:: 1.2
1256
+
1257
+ """
1258
+
1259
+ return self._copy(fget=fget)
1260
+
1261
+ def setter(self, fset: _HybridSetterType[_T]) -> hybrid_property[_T]:
1262
+ """Provide a modifying decorator that defines a setter method."""
1263
+
1264
+ return self._copy(fset=fset)
1265
+
1266
+ def deleter(self, fdel: _HybridDeleterType[_T]) -> hybrid_property[_T]:
1267
+ """Provide a modifying decorator that defines a deletion method."""
1268
+
1269
+ return self._copy(fdel=fdel)
1270
+
1271
+ def expression(
1272
+ self, expr: _HybridExprCallableType[_T]
1273
+ ) -> hybrid_property[_T]:
1274
+ """Provide a modifying decorator that defines a SQL-expression
1275
+ producing method.
1276
+
1277
+ When a hybrid is invoked at the class level, the SQL expression given
1278
+ here is wrapped inside of a specialized :class:`.QueryableAttribute`,
1279
+ which is the same kind of object used by the ORM to represent other
1280
+ mapped attributes. The reason for this is so that other class-level
1281
+ attributes such as docstrings and a reference to the hybrid itself may
1282
+ be maintained within the structure that's returned, without any
1283
+ modifications to the original SQL expression passed in.
1284
+
1285
+ .. note::
1286
+
1287
+ When referring to a hybrid property from an owning class (e.g.
1288
+ ``SomeClass.some_hybrid``), an instance of
1289
+ :class:`.QueryableAttribute` is returned, representing the
1290
+ expression or comparator object as well as this hybrid object.
1291
+ However, that object itself has accessors called ``expression`` and
1292
+ ``comparator``; so when attempting to override these decorators on a
1293
+ subclass, it may be necessary to qualify it using the
1294
+ :attr:`.hybrid_property.overrides` modifier first. See that
1295
+ modifier for details.
1296
+
1297
+ .. seealso::
1298
+
1299
+ :ref:`hybrid_distinct_expression`
1300
+
1301
+ """
1302
+
1303
+ return self._copy(expr=expr)
1304
+
1305
+ def comparator(
1306
+ self, comparator: _HybridComparatorCallableType[_T]
1307
+ ) -> hybrid_property[_T]:
1308
+ """Provide a modifying decorator that defines a custom
1309
+ comparator producing method.
1310
+
1311
+ The return value of the decorated method should be an instance of
1312
+ :class:`~.hybrid.Comparator`.
1313
+
1314
+ .. note:: The :meth:`.hybrid_property.comparator` decorator
1315
+ **replaces** the use of the :meth:`.hybrid_property.expression`
1316
+ decorator. They cannot be used together.
1317
+
1318
+ When a hybrid is invoked at the class level, the
1319
+ :class:`~.hybrid.Comparator` object given here is wrapped inside of a
1320
+ specialized :class:`.QueryableAttribute`, which is the same kind of
1321
+ object used by the ORM to represent other mapped attributes. The
1322
+ reason for this is so that other class-level attributes such as
1323
+ docstrings and a reference to the hybrid itself may be maintained
1324
+ within the structure that's returned, without any modifications to the
1325
+ original comparator object passed in.
1326
+
1327
+ .. note::
1328
+
1329
+ When referring to a hybrid property from an owning class (e.g.
1330
+ ``SomeClass.some_hybrid``), an instance of
1331
+ :class:`.QueryableAttribute` is returned, representing the
1332
+ expression or comparator object as this hybrid object. However,
1333
+ that object itself has accessors called ``expression`` and
1334
+ ``comparator``; so when attempting to override these decorators on a
1335
+ subclass, it may be necessary to qualify it using the
1336
+ :attr:`.hybrid_property.overrides` modifier first. See that
1337
+ modifier for details.
1338
+
1339
+ """
1340
+ return self._copy(custom_comparator=comparator)
1341
+
1342
+ def update_expression(
1343
+ self, meth: _HybridUpdaterType[_T]
1344
+ ) -> hybrid_property[_T]:
1345
+ """Provide a modifying decorator that defines an UPDATE tuple
1346
+ producing method.
1347
+
1348
+ The method accepts a single value, which is the value to be
1349
+ rendered into the SET clause of an UPDATE statement. The method
1350
+ should then process this value into individual column expressions
1351
+ that fit into the ultimate SET clause, and return them as a
1352
+ sequence of 2-tuples. Each tuple
1353
+ contains a column expression as the key and a value to be rendered.
1354
+
1355
+ E.g.::
1356
+
1357
+ class Person(Base):
1358
+ # ...
1359
+
1360
+ first_name = Column(String)
1361
+ last_name = Column(String)
1362
+
1363
+ @hybrid_property
1364
+ def fullname(self):
1365
+ return first_name + " " + last_name
1366
+
1367
+ @fullname.update_expression
1368
+ def fullname(cls, value):
1369
+ fname, lname = value.split(" ", 1)
1370
+ return [
1371
+ (cls.first_name, fname),
1372
+ (cls.last_name, lname)
1373
+ ]
1374
+
1375
+ .. versionadded:: 1.2
1376
+
1377
+ """
1378
+ return self._copy(update_expr=meth)
1379
+
1380
+ @util.memoized_property
1381
+ def _expr_comparator(
1382
+ self,
1383
+ ) -> Callable[[Any], _HybridClassLevelAccessor[_T]]:
1384
+ if self.custom_comparator is not None:
1385
+ return self._get_comparator(self.custom_comparator)
1386
+ elif self.expr is not None:
1387
+ return self._get_expr(self.expr)
1388
+ else:
1389
+ return self._get_expr(cast(_HybridExprCallableType[_T], self.fget))
1390
+
1391
+ def _get_expr(
1392
+ self, expr: _HybridExprCallableType[_T]
1393
+ ) -> Callable[[Any], _HybridClassLevelAccessor[_T]]:
1394
+ def _expr(cls: Any) -> ExprComparator[_T]:
1395
+ return ExprComparator(cls, expr(cls), self)
1396
+
1397
+ util.update_wrapper(_expr, expr)
1398
+
1399
+ return self._get_comparator(_expr)
1400
+
1401
+ def _get_comparator(
1402
+ self, comparator: Any
1403
+ ) -> Callable[[Any], _HybridClassLevelAccessor[_T]]:
1404
+ proxy_attr = attributes.create_proxied_attribute(self)
1405
+
1406
+ def expr_comparator(
1407
+ owner: Type[object],
1408
+ ) -> _HybridClassLevelAccessor[_T]:
1409
+ # because this is the descriptor protocol, we don't really know
1410
+ # what our attribute name is. so search for it through the
1411
+ # MRO.
1412
+ for lookup in owner.__mro__:
1413
+ if self.__name__ in lookup.__dict__:
1414
+ if lookup.__dict__[self.__name__] is self:
1415
+ name = self.__name__
1416
+ break
1417
+ else:
1418
+ name = attributes._UNKNOWN_ATTR_KEY # type: ignore[assignment]
1419
+
1420
+ return cast(
1421
+ "_HybridClassLevelAccessor[_T]",
1422
+ proxy_attr(
1423
+ owner,
1424
+ name,
1425
+ self,
1426
+ comparator(owner),
1427
+ doc=comparator.__doc__ or self.__doc__,
1428
+ ),
1429
+ )
1430
+
1431
+ return expr_comparator
1432
+
1433
+
1434
+ class Comparator(interfaces.PropComparator[_T]):
1435
+ """A helper class that allows easy construction of custom
1436
+ :class:`~.orm.interfaces.PropComparator`
1437
+ classes for usage with hybrids."""
1438
+
1439
+ def __init__(
1440
+ self, expression: Union[_HasClauseElement[_T], SQLColumnExpression[_T]]
1441
+ ):
1442
+ self.expression = expression
1443
+
1444
+ def __clause_element__(self) -> roles.ColumnsClauseRole:
1445
+ expr = self.expression
1446
+ if is_has_clause_element(expr):
1447
+ ret_expr = expr.__clause_element__()
1448
+ else:
1449
+ if TYPE_CHECKING:
1450
+ assert isinstance(expr, ColumnElement)
1451
+ ret_expr = expr
1452
+
1453
+ if TYPE_CHECKING:
1454
+ # see test_hybrid->test_expression_isnt_clause_element
1455
+ # that exercises the usual place this is caught if not
1456
+ # true
1457
+ assert isinstance(ret_expr, ColumnElement)
1458
+ return ret_expr
1459
+
1460
+ @util.non_memoized_property
1461
+ def property(self) -> interfaces.MapperProperty[_T]:
1462
+ raise NotImplementedError()
1463
+
1464
+ def adapt_to_entity(
1465
+ self, adapt_to_entity: AliasedInsp[Any]
1466
+ ) -> Comparator[_T]:
1467
+ # interesting....
1468
+ return self
1469
+
1470
+
1471
+ class ExprComparator(Comparator[_T]):
1472
+ def __init__(
1473
+ self,
1474
+ cls: Type[Any],
1475
+ expression: Union[_HasClauseElement[_T], SQLColumnExpression[_T]],
1476
+ hybrid: hybrid_property[_T],
1477
+ ):
1478
+ self.cls = cls
1479
+ self.expression = expression
1480
+ self.hybrid = hybrid
1481
+
1482
+ def __getattr__(self, key: str) -> Any:
1483
+ return getattr(self.expression, key)
1484
+
1485
+ @util.ro_non_memoized_property
1486
+ def info(self) -> _InfoType:
1487
+ return self.hybrid.info
1488
+
1489
+ def _bulk_update_tuples(
1490
+ self, value: Any
1491
+ ) -> Sequence[Tuple[_DMLColumnArgument, Any]]:
1492
+ if isinstance(self.expression, attributes.QueryableAttribute):
1493
+ return self.expression._bulk_update_tuples(value)
1494
+ elif self.hybrid.update_expr is not None:
1495
+ return self.hybrid.update_expr(self.cls, value)
1496
+ else:
1497
+ return [(self.expression, value)]
1498
+
1499
+ @util.non_memoized_property
1500
+ def property(self) -> MapperProperty[_T]:
1501
+ # this accessor is not normally used, however is accessed by things
1502
+ # like ORM synonyms if the hybrid is used in this context; the
1503
+ # .property attribute is not necessarily accessible
1504
+ return self.expression.property # type: ignore
1505
+
1506
+ def operate(
1507
+ self, op: OperatorType, *other: Any, **kwargs: Any
1508
+ ) -> ColumnElement[Any]:
1509
+ return op(self.expression, *other, **kwargs)
1510
+
1511
+ def reverse_operate(
1512
+ self, op: OperatorType, other: Any, **kwargs: Any
1513
+ ) -> ColumnElement[Any]:
1514
+ return op(other, self.expression, **kwargs) # type: ignore