hybrid.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533
  1. # ext/hybrid.py
  2. # Copyright (C) 2005-2025 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. r"""Define attributes on ORM-mapped classes that have "hybrid" behavior.
  8. "hybrid" means the attribute has distinct behaviors defined at the
  9. class level and at the instance level.
  10. The :mod:`~sqlalchemy.ext.hybrid` extension provides a special form of
  11. method decorator and has minimal dependencies on the rest of SQLAlchemy.
  12. Its basic theory of operation can work with any descriptor-based expression
  13. system.
  14. Consider a mapping ``Interval``, representing integer ``start`` and ``end``
  15. values. We can define higher level functions on mapped classes that produce SQL
  16. expressions at the class level, and Python expression evaluation at the
  17. instance level. Below, each function decorated with :class:`.hybrid_method` or
  18. :class:`.hybrid_property` may receive ``self`` as an instance of the class, or
  19. may receive the class directly, depending on context::
  20. from __future__ import annotations
  21. from sqlalchemy.ext.hybrid import hybrid_method
  22. from sqlalchemy.ext.hybrid import hybrid_property
  23. from sqlalchemy.orm import DeclarativeBase
  24. from sqlalchemy.orm import Mapped
  25. from sqlalchemy.orm import mapped_column
  26. class Base(DeclarativeBase):
  27. pass
  28. class Interval(Base):
  29. __tablename__ = "interval"
  30. id: Mapped[int] = mapped_column(primary_key=True)
  31. start: Mapped[int]
  32. end: Mapped[int]
  33. def __init__(self, start: int, end: int):
  34. self.start = start
  35. self.end = end
  36. @hybrid_property
  37. def length(self) -> int:
  38. return self.end - self.start
  39. @hybrid_method
  40. def contains(self, point: int) -> bool:
  41. return (self.start <= point) & (point <= self.end)
  42. @hybrid_method
  43. def intersects(self, other: Interval) -> bool:
  44. return self.contains(other.start) | self.contains(other.end)
  45. Above, the ``length`` property returns the difference between the
  46. ``end`` and ``start`` attributes. With an instance of ``Interval``,
  47. this subtraction occurs in Python, using normal Python descriptor
  48. mechanics::
  49. >>> i1 = Interval(5, 10)
  50. >>> i1.length
  51. 5
  52. When dealing with the ``Interval`` class itself, the :class:`.hybrid_property`
  53. descriptor evaluates the function body given the ``Interval`` class as
  54. the argument, which when evaluated with SQLAlchemy expression mechanics
  55. returns a new SQL expression:
  56. .. sourcecode:: pycon+sql
  57. >>> from sqlalchemy import select
  58. >>> print(select(Interval.length))
  59. {printsql}SELECT interval."end" - interval.start AS length
  60. FROM interval{stop}
  61. >>> print(select(Interval).filter(Interval.length > 10))
  62. {printsql}SELECT interval.id, interval.start, interval."end"
  63. FROM interval
  64. WHERE interval."end" - interval.start > :param_1
  65. Filtering methods such as :meth:`.Select.filter_by` are supported
  66. with hybrid attributes as well:
  67. .. sourcecode:: pycon+sql
  68. >>> print(select(Interval).filter_by(length=5))
  69. {printsql}SELECT interval.id, interval.start, interval."end"
  70. FROM interval
  71. WHERE interval."end" - interval.start = :param_1
  72. The ``Interval`` class example also illustrates two methods,
  73. ``contains()`` and ``intersects()``, decorated with
  74. :class:`.hybrid_method`. This decorator applies the same idea to
  75. methods that :class:`.hybrid_property` applies to attributes. The
  76. methods return boolean values, and take advantage of the Python ``|``
  77. and ``&`` bitwise operators to produce equivalent instance-level and
  78. SQL expression-level boolean behavior:
  79. .. sourcecode:: pycon+sql
  80. >>> i1.contains(6)
  81. True
  82. >>> i1.contains(15)
  83. False
  84. >>> i1.intersects(Interval(7, 18))
  85. True
  86. >>> i1.intersects(Interval(25, 29))
  87. False
  88. >>> print(select(Interval).filter(Interval.contains(15)))
  89. {printsql}SELECT interval.id, interval.start, interval."end"
  90. FROM interval
  91. WHERE interval.start <= :start_1 AND interval."end" > :end_1{stop}
  92. >>> ia = aliased(Interval)
  93. >>> print(select(Interval, ia).filter(Interval.intersects(ia)))
  94. {printsql}SELECT interval.id, interval.start,
  95. interval."end", interval_1.id AS interval_1_id,
  96. interval_1.start AS interval_1_start, interval_1."end" AS interval_1_end
  97. FROM interval, interval AS interval_1
  98. WHERE interval.start <= interval_1.start
  99. AND interval."end" > interval_1.start
  100. OR interval.start <= interval_1."end"
  101. AND interval."end" > interval_1."end"{stop}
  102. .. _hybrid_distinct_expression:
  103. Defining Expression Behavior Distinct from Attribute Behavior
  104. --------------------------------------------------------------
  105. In the previous section, our usage of the ``&`` and ``|`` bitwise operators
  106. within the ``Interval.contains`` and ``Interval.intersects`` methods was
  107. fortunate, considering our functions operated on two boolean values to return a
  108. new one. In many cases, the construction of an in-Python function and a
  109. SQLAlchemy SQL expression have enough differences that two separate Python
  110. expressions should be defined. The :mod:`~sqlalchemy.ext.hybrid` decorator
  111. defines a **modifier** :meth:`.hybrid_property.expression` for this purpose. As an
  112. example we'll define the radius of the interval, which requires the usage of
  113. the absolute value function::
  114. from sqlalchemy import ColumnElement
  115. from sqlalchemy import Float
  116. from sqlalchemy import func
  117. from sqlalchemy import type_coerce
  118. class Interval(Base):
  119. # ...
  120. @hybrid_property
  121. def radius(self) -> float:
  122. return abs(self.length) / 2
  123. @radius.inplace.expression
  124. @classmethod
  125. def _radius_expression(cls) -> ColumnElement[float]:
  126. return type_coerce(func.abs(cls.length) / 2, Float)
  127. In the above example, the :class:`.hybrid_property` first assigned to the
  128. name ``Interval.radius`` is amended by a subsequent method called
  129. ``Interval._radius_expression``, using the decorator
  130. ``@radius.inplace.expression``, which chains together two modifiers
  131. :attr:`.hybrid_property.inplace` and :attr:`.hybrid_property.expression`.
  132. The use of :attr:`.hybrid_property.inplace` indicates that the
  133. :meth:`.hybrid_property.expression` modifier should mutate the
  134. existing hybrid object at ``Interval.radius`` in place, without creating a
  135. new object. Notes on this modifier and its
  136. rationale are discussed in the next section :ref:`hybrid_pep484_naming`.
  137. The use of ``@classmethod`` is optional, and is strictly to give typing
  138. tools a hint that ``cls`` in this case is expected to be the ``Interval``
  139. class, and not an instance of ``Interval``.
  140. .. note:: :attr:`.hybrid_property.inplace` as well as the use of ``@classmethod``
  141. for proper typing support are available as of SQLAlchemy 2.0.4, and will
  142. not work in earlier versions.
  143. With ``Interval.radius`` now including an expression element, the SQL
  144. function ``ABS()`` is returned when accessing ``Interval.radius``
  145. at the class level:
  146. .. sourcecode:: pycon+sql
  147. >>> from sqlalchemy import select
  148. >>> print(select(Interval).filter(Interval.radius > 5))
  149. {printsql}SELECT interval.id, interval.start, interval."end"
  150. FROM interval
  151. WHERE abs(interval."end" - interval.start) / :abs_1 > :param_1
  152. .. _hybrid_pep484_naming:
  153. Using ``inplace`` to create pep-484 compliant hybrid properties
  154. ---------------------------------------------------------------
  155. In the previous section, a :class:`.hybrid_property` decorator is illustrated
  156. which includes two separate method-level functions being decorated, both
  157. to produce a single object attribute referenced as ``Interval.radius``.
  158. There are actually several different modifiers we can use for
  159. :class:`.hybrid_property` including :meth:`.hybrid_property.expression`,
  160. :meth:`.hybrid_property.setter` and :meth:`.hybrid_property.update_expression`.
  161. SQLAlchemy's :class:`.hybrid_property` decorator intends that adding on these
  162. methods may be done in the identical manner as Python's built-in
  163. ``@property`` decorator, where idiomatic use is to continue to redefine the
  164. attribute repeatedly, using the **same attribute name** each time, as in the
  165. example below that illustrates the use of :meth:`.hybrid_property.setter` and
  166. :meth:`.hybrid_property.expression` for the ``Interval.radius`` descriptor::
  167. # correct use, however is not accepted by pep-484 tooling
  168. class Interval(Base):
  169. # ...
  170. @hybrid_property
  171. def radius(self):
  172. return abs(self.length) / 2
  173. @radius.setter
  174. def radius(self, value):
  175. self.length = value * 2
  176. @radius.expression
  177. def radius(cls):
  178. return type_coerce(func.abs(cls.length) / 2, Float)
  179. Above, there are three ``Interval.radius`` methods, but as each are decorated,
  180. first by the :class:`.hybrid_property` decorator and then by the
  181. ``@radius`` name itself, the end effect is that ``Interval.radius`` is
  182. a single attribute with three different functions contained within it.
  183. This style of use is taken from `Python's documented use of @property
  184. <https://docs.python.org/3/library/functions.html#property>`_.
  185. It is important to note that the way both ``@property`` as well as
  186. :class:`.hybrid_property` work, a **copy of the descriptor is made each time**.
  187. That is, each call to ``@radius.expression``, ``@radius.setter`` etc.
  188. make a new object entirely. This allows the attribute to be re-defined in
  189. subclasses without issue (see :ref:`hybrid_reuse_subclass` later in this
  190. section for how this is used).
  191. However, the above approach is not compatible with typing tools such as
  192. mypy and pyright. Python's own ``@property`` decorator does not have this
  193. limitation only because
  194. `these tools hardcode the behavior of @property
  195. <https://github.com/python/typing/discussions/1102>`_, meaning this syntax
  196. is not available to SQLAlchemy under :pep:`484` compliance.
  197. In order to produce a reasonable syntax while remaining typing compliant,
  198. the :attr:`.hybrid_property.inplace` decorator allows the same
  199. decorator to be re-used with different method names, while still producing
  200. a single decorator under one name::
  201. # correct use which is also accepted by pep-484 tooling
  202. class Interval(Base):
  203. # ...
  204. @hybrid_property
  205. def radius(self) -> float:
  206. return abs(self.length) / 2
  207. @radius.inplace.setter
  208. def _radius_setter(self, value: float) -> None:
  209. # for example only
  210. self.length = value * 2
  211. @radius.inplace.expression
  212. @classmethod
  213. def _radius_expression(cls) -> ColumnElement[float]:
  214. return type_coerce(func.abs(cls.length) / 2, Float)
  215. Using :attr:`.hybrid_property.inplace` further qualifies the use of the
  216. decorator that a new copy should not be made, thereby maintaining the
  217. ``Interval.radius`` name while allowing additional methods
  218. ``Interval._radius_setter`` and ``Interval._radius_expression`` to be
  219. differently named.
  220. .. versionadded:: 2.0.4 Added :attr:`.hybrid_property.inplace` to allow
  221. less verbose construction of composite :class:`.hybrid_property` objects
  222. while not having to use repeated method names. Additionally allowed the
  223. use of ``@classmethod`` within :attr:`.hybrid_property.expression`,
  224. :attr:`.hybrid_property.update_expression`, and
  225. :attr:`.hybrid_property.comparator` to allow typing tools to identify
  226. ``cls`` as a class and not an instance in the method signature.
  227. Defining Setters
  228. ----------------
  229. The :meth:`.hybrid_property.setter` modifier allows the construction of a
  230. custom setter method, that can modify values on the object::
  231. class Interval(Base):
  232. # ...
  233. @hybrid_property
  234. def length(self) -> int:
  235. return self.end - self.start
  236. @length.inplace.setter
  237. def _length_setter(self, value: int) -> None:
  238. self.end = self.start + value
  239. The ``length(self, value)`` method is now called upon set::
  240. >>> i1 = Interval(5, 10)
  241. >>> i1.length
  242. 5
  243. >>> i1.length = 12
  244. >>> i1.end
  245. 17
  246. .. _hybrid_bulk_update:
  247. Allowing Bulk ORM Update
  248. ------------------------
  249. A hybrid can define a custom "UPDATE" handler for when using
  250. ORM-enabled updates, allowing the hybrid to be used in the
  251. SET clause of the update.
  252. Normally, when using a hybrid with :func:`_sql.update`, the SQL
  253. expression is used as the column that's the target of the SET. If our
  254. ``Interval`` class had a hybrid ``start_point`` that linked to
  255. ``Interval.start``, this could be substituted directly::
  256. from sqlalchemy import update
  257. stmt = update(Interval).values({Interval.start_point: 10})
  258. However, when using a composite hybrid like ``Interval.length``, this
  259. hybrid represents more than one column. We can set up a handler that will
  260. accommodate a value passed in the VALUES expression which can affect
  261. this, using the :meth:`.hybrid_property.update_expression` decorator.
  262. A handler that works similarly to our setter would be::
  263. from typing import List, Tuple, Any
  264. class Interval(Base):
  265. # ...
  266. @hybrid_property
  267. def length(self) -> int:
  268. return self.end - self.start
  269. @length.inplace.setter
  270. def _length_setter(self, value: int) -> None:
  271. self.end = self.start + value
  272. @length.inplace.update_expression
  273. def _length_update_expression(
  274. cls, value: Any
  275. ) -> List[Tuple[Any, Any]]:
  276. return [(cls.end, cls.start + value)]
  277. Above, if we use ``Interval.length`` in an UPDATE expression, we get
  278. a hybrid SET expression:
  279. .. sourcecode:: pycon+sql
  280. >>> from sqlalchemy import update
  281. >>> print(update(Interval).values({Interval.length: 25}))
  282. {printsql}UPDATE interval SET "end"=(interval.start + :start_1)
  283. This SET expression is accommodated by the ORM automatically.
  284. .. seealso::
  285. :ref:`orm_expression_update_delete` - includes background on ORM-enabled
  286. UPDATE statements
  287. Working with Relationships
  288. --------------------------
  289. There's no essential difference when creating hybrids that work with
  290. related objects as opposed to column-based data. The need for distinct
  291. expressions tends to be greater. The two variants we'll illustrate
  292. are the "join-dependent" hybrid, and the "correlated subquery" hybrid.
  293. Join-Dependent Relationship Hybrid
  294. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  295. Consider the following declarative
  296. mapping which relates a ``User`` to a ``SavingsAccount``::
  297. from __future__ import annotations
  298. from decimal import Decimal
  299. from typing import cast
  300. from typing import List
  301. from typing import Optional
  302. from sqlalchemy import ForeignKey
  303. from sqlalchemy import Numeric
  304. from sqlalchemy import String
  305. from sqlalchemy import SQLColumnExpression
  306. from sqlalchemy.ext.hybrid import hybrid_property
  307. from sqlalchemy.orm import DeclarativeBase
  308. from sqlalchemy.orm import Mapped
  309. from sqlalchemy.orm import mapped_column
  310. from sqlalchemy.orm import relationship
  311. class Base(DeclarativeBase):
  312. pass
  313. class SavingsAccount(Base):
  314. __tablename__ = "account"
  315. id: Mapped[int] = mapped_column(primary_key=True)
  316. user_id: Mapped[int] = mapped_column(ForeignKey("user.id"))
  317. balance: Mapped[Decimal] = mapped_column(Numeric(15, 5))
  318. owner: Mapped[User] = relationship(back_populates="accounts")
  319. class User(Base):
  320. __tablename__ = "user"
  321. id: Mapped[int] = mapped_column(primary_key=True)
  322. name: Mapped[str] = mapped_column(String(100))
  323. accounts: Mapped[List[SavingsAccount]] = relationship(
  324. back_populates="owner", lazy="selectin"
  325. )
  326. @hybrid_property
  327. def balance(self) -> Optional[Decimal]:
  328. if self.accounts:
  329. return self.accounts[0].balance
  330. else:
  331. return None
  332. @balance.inplace.setter
  333. def _balance_setter(self, value: Optional[Decimal]) -> None:
  334. assert value is not None
  335. if not self.accounts:
  336. account = SavingsAccount(owner=self)
  337. else:
  338. account = self.accounts[0]
  339. account.balance = value
  340. @balance.inplace.expression
  341. @classmethod
  342. def _balance_expression(cls) -> SQLColumnExpression[Optional[Decimal]]:
  343. return cast(
  344. "SQLColumnExpression[Optional[Decimal]]",
  345. SavingsAccount.balance,
  346. )
  347. The above hybrid property ``balance`` works with the first
  348. ``SavingsAccount`` entry in the list of accounts for this user. The
  349. in-Python getter/setter methods can treat ``accounts`` as a Python
  350. list available on ``self``.
  351. .. tip:: The ``User.balance`` getter in the above example accesses the
  352. ``self.acccounts`` collection, which will normally be loaded via the
  353. :func:`.selectinload` loader strategy configured on the ``User.balance``
  354. :func:`_orm.relationship`. The default loader strategy when not otherwise
  355. stated on :func:`_orm.relationship` is :func:`.lazyload`, which emits SQL on
  356. demand. When using asyncio, on-demand loaders such as :func:`.lazyload` are
  357. not supported, so care should be taken to ensure the ``self.accounts``
  358. collection is accessible to this hybrid accessor when using asyncio.
  359. At the expression level, it's expected that the ``User`` class will
  360. be used in an appropriate context such that an appropriate join to
  361. ``SavingsAccount`` will be present:
  362. .. sourcecode:: pycon+sql
  363. >>> from sqlalchemy import select
  364. >>> print(
  365. ... select(User, User.balance)
  366. ... .join(User.accounts)
  367. ... .filter(User.balance > 5000)
  368. ... )
  369. {printsql}SELECT "user".id AS user_id, "user".name AS user_name,
  370. account.balance AS account_balance
  371. FROM "user" JOIN account ON "user".id = account.user_id
  372. WHERE account.balance > :balance_1
  373. Note however, that while the instance level accessors need to worry
  374. about whether ``self.accounts`` is even present, this issue expresses
  375. itself differently at the SQL expression level, where we basically
  376. would use an outer join:
  377. .. sourcecode:: pycon+sql
  378. >>> from sqlalchemy import select
  379. >>> from sqlalchemy import or_
  380. >>> print(
  381. ... select(User, User.balance)
  382. ... .outerjoin(User.accounts)
  383. ... .filter(or_(User.balance < 5000, User.balance == None))
  384. ... )
  385. {printsql}SELECT "user".id AS user_id, "user".name AS user_name,
  386. account.balance AS account_balance
  387. FROM "user" LEFT OUTER JOIN account ON "user".id = account.user_id
  388. WHERE account.balance < :balance_1 OR account.balance IS NULL
  389. Correlated Subquery Relationship Hybrid
  390. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  391. We can, of course, forego being dependent on the enclosing query's usage
  392. of joins in favor of the correlated subquery, which can portably be packed
  393. into a single column expression. A correlated subquery is more portable, but
  394. often performs more poorly at the SQL level. Using the same technique
  395. illustrated at :ref:`mapper_column_property_sql_expressions`,
  396. we can adjust our ``SavingsAccount`` example to aggregate the balances for
  397. *all* accounts, and use a correlated subquery for the column expression::
  398. from __future__ import annotations
  399. from decimal import Decimal
  400. from typing import List
  401. from sqlalchemy import ForeignKey
  402. from sqlalchemy import func
  403. from sqlalchemy import Numeric
  404. from sqlalchemy import select
  405. from sqlalchemy import SQLColumnExpression
  406. from sqlalchemy import String
  407. from sqlalchemy.ext.hybrid import hybrid_property
  408. from sqlalchemy.orm import DeclarativeBase
  409. from sqlalchemy.orm import Mapped
  410. from sqlalchemy.orm import mapped_column
  411. from sqlalchemy.orm import relationship
  412. class Base(DeclarativeBase):
  413. pass
  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. owner: Mapped[User] = relationship(back_populates="accounts")
  420. class User(Base):
  421. __tablename__ = "user"
  422. id: Mapped[int] = mapped_column(primary_key=True)
  423. name: Mapped[str] = mapped_column(String(100))
  424. accounts: Mapped[List[SavingsAccount]] = relationship(
  425. back_populates="owner", lazy="selectin"
  426. )
  427. @hybrid_property
  428. def balance(self) -> Decimal:
  429. return sum(
  430. (acc.balance for acc in self.accounts), start=Decimal("0")
  431. )
  432. @balance.inplace.expression
  433. @classmethod
  434. def _balance_expression(cls) -> SQLColumnExpression[Decimal]:
  435. return (
  436. select(func.sum(SavingsAccount.balance))
  437. .where(SavingsAccount.user_id == cls.id)
  438. .label("total_balance")
  439. )
  440. The above recipe will give us the ``balance`` column which renders
  441. a correlated SELECT:
  442. .. sourcecode:: pycon+sql
  443. >>> from sqlalchemy import select
  444. >>> print(select(User).filter(User.balance > 400))
  445. {printsql}SELECT "user".id, "user".name
  446. FROM "user"
  447. WHERE (
  448. SELECT sum(account.balance) AS sum_1 FROM account
  449. WHERE account.user_id = "user".id
  450. ) > :param_1
  451. .. _hybrid_custom_comparators:
  452. Building Custom Comparators
  453. ---------------------------
  454. The hybrid property also includes a helper that allows construction of
  455. custom comparators. A comparator object allows one to customize the
  456. behavior of each SQLAlchemy expression operator individually. They
  457. are useful when creating custom types that have some highly
  458. idiosyncratic behavior on the SQL side.
  459. .. note:: The :meth:`.hybrid_property.comparator` decorator introduced
  460. in this section **replaces** the use of the
  461. :meth:`.hybrid_property.expression` decorator.
  462. They cannot be used together.
  463. The example class below allows case-insensitive comparisons on the attribute
  464. named ``word_insensitive``::
  465. from __future__ import annotations
  466. from typing import Any
  467. from sqlalchemy import ColumnElement
  468. from sqlalchemy import func
  469. from sqlalchemy.ext.hybrid import Comparator
  470. from sqlalchemy.ext.hybrid import hybrid_property
  471. from sqlalchemy.orm import DeclarativeBase
  472. from sqlalchemy.orm import Mapped
  473. from sqlalchemy.orm import mapped_column
  474. class Base(DeclarativeBase):
  475. pass
  476. class CaseInsensitiveComparator(Comparator[str]):
  477. def __eq__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501
  478. return func.lower(self.__clause_element__()) == func.lower(other)
  479. class SearchWord(Base):
  480. __tablename__ = "searchword"
  481. id: Mapped[int] = mapped_column(primary_key=True)
  482. word: Mapped[str]
  483. @hybrid_property
  484. def word_insensitive(self) -> str:
  485. return self.word.lower()
  486. @word_insensitive.inplace.comparator
  487. @classmethod
  488. def _word_insensitive_comparator(cls) -> CaseInsensitiveComparator:
  489. return CaseInsensitiveComparator(cls.word)
  490. Above, SQL expressions against ``word_insensitive`` will apply the ``LOWER()``
  491. SQL function to both sides:
  492. .. sourcecode:: pycon+sql
  493. >>> from sqlalchemy import select
  494. >>> print(select(SearchWord).filter_by(word_insensitive="Trucks"))
  495. {printsql}SELECT searchword.id, searchword.word
  496. FROM searchword
  497. WHERE lower(searchword.word) = lower(:lower_1)
  498. The ``CaseInsensitiveComparator`` above implements part of the
  499. :class:`.ColumnOperators` interface. A "coercion" operation like
  500. lowercasing can be applied to all comparison operations (i.e. ``eq``,
  501. ``lt``, ``gt``, etc.) using :meth:`.Operators.operate`::
  502. class CaseInsensitiveComparator(Comparator):
  503. def operate(self, op, other, **kwargs):
  504. return op(
  505. func.lower(self.__clause_element__()),
  506. func.lower(other),
  507. **kwargs,
  508. )
  509. .. _hybrid_reuse_subclass:
  510. Reusing Hybrid Properties across Subclasses
  511. -------------------------------------------
  512. A hybrid can be referred to from a superclass, to allow modifying
  513. methods like :meth:`.hybrid_property.getter`, :meth:`.hybrid_property.setter`
  514. to be used to redefine those methods on a subclass. This is similar to
  515. how the standard Python ``@property`` object works::
  516. class FirstNameOnly(Base):
  517. # ...
  518. first_name: Mapped[str]
  519. @hybrid_property
  520. def name(self) -> str:
  521. return self.first_name
  522. @name.inplace.setter
  523. def _name_setter(self, value: str) -> None:
  524. self.first_name = value
  525. class FirstNameLastName(FirstNameOnly):
  526. # ...
  527. last_name: Mapped[str]
  528. # 'inplace' is not used here; calling getter creates a copy
  529. # of FirstNameOnly.name that is local to FirstNameLastName
  530. @FirstNameOnly.name.getter
  531. def name(self) -> str:
  532. return self.first_name + " " + self.last_name
  533. @name.inplace.setter
  534. def _name_setter(self, value: str) -> None:
  535. self.first_name, self.last_name = value.split(" ", 1)
  536. Above, the ``FirstNameLastName`` class refers to the hybrid from
  537. ``FirstNameOnly.name`` to repurpose its getter and setter for the subclass.
  538. When overriding :meth:`.hybrid_property.expression` and
  539. :meth:`.hybrid_property.comparator` alone as the first reference to the
  540. superclass, these names conflict with the same-named accessors on the class-
  541. level :class:`.QueryableAttribute` object returned at the class level. To
  542. override these methods when referring directly to the parent class descriptor,
  543. add the special qualifier :attr:`.hybrid_property.overrides`, which will de-
  544. reference the instrumented attribute back to the hybrid object::
  545. class FirstNameLastName(FirstNameOnly):
  546. # ...
  547. last_name: Mapped[str]
  548. @FirstNameOnly.name.overrides.expression
  549. @classmethod
  550. def name(cls):
  551. return func.concat(cls.first_name, " ", cls.last_name)
  552. Hybrid Value Objects
  553. --------------------
  554. Note in our previous example, if we were to compare the ``word_insensitive``
  555. attribute of a ``SearchWord`` instance to a plain Python string, the plain
  556. Python string would not be coerced to lower case - the
  557. ``CaseInsensitiveComparator`` we built, being returned by
  558. ``@word_insensitive.comparator``, only applies to the SQL side.
  559. A more comprehensive form of the custom comparator is to construct a *Hybrid
  560. Value Object*. This technique applies the target value or expression to a value
  561. object which is then returned by the accessor in all cases. The value object
  562. allows control of all operations upon the value as well as how compared values
  563. are treated, both on the SQL expression side as well as the Python value side.
  564. Replacing the previous ``CaseInsensitiveComparator`` class with a new
  565. ``CaseInsensitiveWord`` class::
  566. class CaseInsensitiveWord(Comparator):
  567. "Hybrid value representing a lower case representation of a word."
  568. def __init__(self, word):
  569. if isinstance(word, basestring):
  570. self.word = word.lower()
  571. elif isinstance(word, CaseInsensitiveWord):
  572. self.word = word.word
  573. else:
  574. self.word = func.lower(word)
  575. def operate(self, op, other, **kwargs):
  576. if not isinstance(other, CaseInsensitiveWord):
  577. other = CaseInsensitiveWord(other)
  578. return op(self.word, other.word, **kwargs)
  579. def __clause_element__(self):
  580. return self.word
  581. def __str__(self):
  582. return self.word
  583. key = "word"
  584. "Label to apply to Query tuple results"
  585. Above, the ``CaseInsensitiveWord`` object represents ``self.word``, which may
  586. be a SQL function, or may be a Python native. By overriding ``operate()`` and
  587. ``__clause_element__()`` to work in terms of ``self.word``, all comparison
  588. operations will work against the "converted" form of ``word``, whether it be
  589. SQL side or Python side. Our ``SearchWord`` class can now deliver the
  590. ``CaseInsensitiveWord`` object unconditionally from a single hybrid call::
  591. class SearchWord(Base):
  592. __tablename__ = "searchword"
  593. id: Mapped[int] = mapped_column(primary_key=True)
  594. word: Mapped[str]
  595. @hybrid_property
  596. def word_insensitive(self) -> CaseInsensitiveWord:
  597. return CaseInsensitiveWord(self.word)
  598. The ``word_insensitive`` attribute now has case-insensitive comparison behavior
  599. universally, including SQL expression vs. Python expression (note the Python
  600. value is converted to lower case on the Python side here):
  601. .. sourcecode:: pycon+sql
  602. >>> print(select(SearchWord).filter_by(word_insensitive="Trucks"))
  603. {printsql}SELECT searchword.id AS searchword_id, searchword.word AS searchword_word
  604. FROM searchword
  605. WHERE lower(searchword.word) = :lower_1
  606. SQL expression versus SQL expression:
  607. .. sourcecode:: pycon+sql
  608. >>> from sqlalchemy.orm import aliased
  609. >>> sw1 = aliased(SearchWord)
  610. >>> sw2 = aliased(SearchWord)
  611. >>> print(
  612. ... select(sw1.word_insensitive, sw2.word_insensitive).filter(
  613. ... sw1.word_insensitive > sw2.word_insensitive
  614. ... )
  615. ... )
  616. {printsql}SELECT lower(searchword_1.word) AS lower_1,
  617. lower(searchword_2.word) AS lower_2
  618. FROM searchword AS searchword_1, searchword AS searchword_2
  619. WHERE lower(searchword_1.word) > lower(searchword_2.word)
  620. Python only expression::
  621. >>> ws1 = SearchWord(word="SomeWord")
  622. >>> ws1.word_insensitive == "sOmEwOrD"
  623. True
  624. >>> ws1.word_insensitive == "XOmEwOrX"
  625. False
  626. >>> print(ws1.word_insensitive)
  627. someword
  628. The Hybrid Value pattern is very useful for any kind of value that may have
  629. multiple representations, such as timestamps, time deltas, units of
  630. measurement, currencies and encrypted passwords.
  631. .. seealso::
  632. `Hybrids and Value Agnostic Types
  633. <https://techspot.zzzeek.org/2011/10/21/hybrids-and-value-agnostic-types/>`_
  634. - on the techspot.zzzeek.org blog
  635. `Value Agnostic Types, Part II
  636. <https://techspot.zzzeek.org/2011/10/29/value-agnostic-types-part-ii/>`_ -
  637. on the techspot.zzzeek.org blog
  638. """ # noqa
  639. from __future__ import annotations
  640. from typing import Any
  641. from typing import Callable
  642. from typing import cast
  643. from typing import Generic
  644. from typing import List
  645. from typing import Optional
  646. from typing import overload
  647. from typing import Sequence
  648. from typing import Tuple
  649. from typing import Type
  650. from typing import TYPE_CHECKING
  651. from typing import TypeVar
  652. from typing import Union
  653. from .. import util
  654. from ..orm import attributes
  655. from ..orm import InspectionAttrExtensionType
  656. from ..orm import interfaces
  657. from ..orm import ORMDescriptor
  658. from ..orm.attributes import QueryableAttribute
  659. from ..sql import roles
  660. from ..sql._typing import is_has_clause_element
  661. from ..sql.elements import ColumnElement
  662. from ..sql.elements import SQLCoreOperations
  663. from ..util.typing import Concatenate
  664. from ..util.typing import Literal
  665. from ..util.typing import ParamSpec
  666. from ..util.typing import Protocol
  667. from ..util.typing import Self
  668. if TYPE_CHECKING:
  669. from ..orm.interfaces import MapperProperty
  670. from ..orm.util import AliasedInsp
  671. from ..sql import SQLColumnExpression
  672. from ..sql._typing import _ColumnExpressionArgument
  673. from ..sql._typing import _DMLColumnArgument
  674. from ..sql._typing import _HasClauseElement
  675. from ..sql._typing import _InfoType
  676. from ..sql.operators import OperatorType
  677. _P = ParamSpec("_P")
  678. _R = TypeVar("_R")
  679. _T = TypeVar("_T", bound=Any)
  680. _TE = TypeVar("_TE", bound=Any)
  681. _T_co = TypeVar("_T_co", bound=Any, covariant=True)
  682. _T_con = TypeVar("_T_con", bound=Any, contravariant=True)
  683. class HybridExtensionType(InspectionAttrExtensionType):
  684. HYBRID_METHOD = "HYBRID_METHOD"
  685. """Symbol indicating an :class:`InspectionAttr` that's
  686. of type :class:`.hybrid_method`.
  687. Is assigned to the :attr:`.InspectionAttr.extension_type`
  688. attribute.
  689. .. seealso::
  690. :attr:`_orm.Mapper.all_orm_attributes`
  691. """
  692. HYBRID_PROPERTY = "HYBRID_PROPERTY"
  693. """Symbol indicating an :class:`InspectionAttr` that's
  694. of type :class:`.hybrid_method`.
  695. Is assigned to the :attr:`.InspectionAttr.extension_type`
  696. attribute.
  697. .. seealso::
  698. :attr:`_orm.Mapper.all_orm_attributes`
  699. """
  700. class _HybridGetterType(Protocol[_T_co]):
  701. def __call__(s, self: Any) -> _T_co: ...
  702. class _HybridSetterType(Protocol[_T_con]):
  703. def __call__(s, self: Any, value: _T_con) -> None: ...
  704. class _HybridUpdaterType(Protocol[_T_con]):
  705. def __call__(
  706. s,
  707. cls: Any,
  708. value: Union[_T_con, _ColumnExpressionArgument[_T_con]],
  709. ) -> List[Tuple[_DMLColumnArgument, Any]]: ...
  710. class _HybridDeleterType(Protocol[_T_co]):
  711. def __call__(s, self: Any) -> None: ...
  712. class _HybridExprCallableType(Protocol[_T_co]):
  713. def __call__(
  714. s, cls: Any
  715. ) -> Union[_HasClauseElement[_T_co], SQLColumnExpression[_T_co]]: ...
  716. class _HybridComparatorCallableType(Protocol[_T]):
  717. def __call__(self, cls: Any) -> Comparator[_T]: ...
  718. class _HybridClassLevelAccessor(QueryableAttribute[_T]):
  719. """Describe the object returned by a hybrid_property() when
  720. called as a class-level descriptor.
  721. """
  722. if TYPE_CHECKING:
  723. def getter(
  724. self, fget: _HybridGetterType[_T]
  725. ) -> hybrid_property[_T]: ...
  726. def setter(
  727. self, fset: _HybridSetterType[_T]
  728. ) -> hybrid_property[_T]: ...
  729. def deleter(
  730. self, fdel: _HybridDeleterType[_T]
  731. ) -> hybrid_property[_T]: ...
  732. @property
  733. def overrides(self) -> hybrid_property[_T]: ...
  734. def update_expression(
  735. self, meth: _HybridUpdaterType[_T]
  736. ) -> hybrid_property[_T]: ...
  737. class hybrid_method(interfaces.InspectionAttrInfo, Generic[_P, _R]):
  738. """A decorator which allows definition of a Python object method with both
  739. instance-level and class-level behavior.
  740. """
  741. is_attribute = True
  742. extension_type = HybridExtensionType.HYBRID_METHOD
  743. def __init__(
  744. self,
  745. func: Callable[Concatenate[Any, _P], _R],
  746. expr: Optional[
  747. Callable[Concatenate[Any, _P], SQLCoreOperations[_R]]
  748. ] = None,
  749. ):
  750. """Create a new :class:`.hybrid_method`.
  751. Usage is typically via decorator::
  752. from sqlalchemy.ext.hybrid import hybrid_method
  753. class SomeClass:
  754. @hybrid_method
  755. def value(self, x, y):
  756. return self._value + x + y
  757. @value.expression
  758. @classmethod
  759. def value(cls, x, y):
  760. return func.some_function(cls._value, x, y)
  761. """
  762. self.func = func
  763. if expr is not None:
  764. self.expression(expr)
  765. else:
  766. self.expression(func) # type: ignore
  767. @property
  768. def inplace(self) -> Self:
  769. """Return the inplace mutator for this :class:`.hybrid_method`.
  770. The :class:`.hybrid_method` class already performs "in place" mutation
  771. when the :meth:`.hybrid_method.expression` decorator is called,
  772. so this attribute returns Self.
  773. .. versionadded:: 2.0.4
  774. .. seealso::
  775. :ref:`hybrid_pep484_naming`
  776. """
  777. return self
  778. @overload
  779. def __get__(
  780. self, instance: Literal[None], owner: Type[object]
  781. ) -> Callable[_P, SQLCoreOperations[_R]]: ...
  782. @overload
  783. def __get__(
  784. self, instance: object, owner: Type[object]
  785. ) -> Callable[_P, _R]: ...
  786. def __get__(
  787. self, instance: Optional[object], owner: Type[object]
  788. ) -> Union[Callable[_P, _R], Callable[_P, SQLCoreOperations[_R]]]:
  789. if instance is None:
  790. return self.expr.__get__(owner, owner) # type: ignore
  791. else:
  792. return self.func.__get__(instance, owner) # type: ignore
  793. def expression(
  794. self, expr: Callable[Concatenate[Any, _P], SQLCoreOperations[_R]]
  795. ) -> hybrid_method[_P, _R]:
  796. """Provide a modifying decorator that defines a
  797. SQL-expression producing method."""
  798. self.expr = expr
  799. if not self.expr.__doc__:
  800. self.expr.__doc__ = self.func.__doc__
  801. return self
  802. def _unwrap_classmethod(meth: _T) -> _T:
  803. if isinstance(meth, classmethod):
  804. return meth.__func__ # type: ignore
  805. else:
  806. return meth
  807. class hybrid_property(interfaces.InspectionAttrInfo, ORMDescriptor[_T]):
  808. """A decorator which allows definition of a Python descriptor with both
  809. instance-level and class-level behavior.
  810. """
  811. is_attribute = True
  812. extension_type = HybridExtensionType.HYBRID_PROPERTY
  813. __name__: str
  814. def __init__(
  815. self,
  816. fget: _HybridGetterType[_T],
  817. fset: Optional[_HybridSetterType[_T]] = None,
  818. fdel: Optional[_HybridDeleterType[_T]] = None,
  819. expr: Optional[_HybridExprCallableType[_T]] = None,
  820. custom_comparator: Optional[Comparator[_T]] = None,
  821. update_expr: Optional[_HybridUpdaterType[_T]] = None,
  822. ):
  823. """Create a new :class:`.hybrid_property`.
  824. Usage is typically via decorator::
  825. from sqlalchemy.ext.hybrid import hybrid_property
  826. class SomeClass:
  827. @hybrid_property
  828. def value(self):
  829. return self._value
  830. @value.setter
  831. def value(self, value):
  832. self._value = value
  833. """
  834. self.fget = fget
  835. self.fset = fset
  836. self.fdel = fdel
  837. self.expr = _unwrap_classmethod(expr)
  838. self.custom_comparator = _unwrap_classmethod(custom_comparator)
  839. self.update_expr = _unwrap_classmethod(update_expr)
  840. util.update_wrapper(self, fget) # type: ignore[arg-type]
  841. @overload
  842. def __get__(self, instance: Any, owner: Literal[None]) -> Self: ...
  843. @overload
  844. def __get__(
  845. self, instance: Literal[None], owner: Type[object]
  846. ) -> _HybridClassLevelAccessor[_T]: ...
  847. @overload
  848. def __get__(self, instance: object, owner: Type[object]) -> _T: ...
  849. def __get__(
  850. self, instance: Optional[object], owner: Optional[Type[object]]
  851. ) -> Union[hybrid_property[_T], _HybridClassLevelAccessor[_T], _T]:
  852. if owner is None:
  853. return self
  854. elif instance is None:
  855. return self._expr_comparator(owner)
  856. else:
  857. return self.fget(instance)
  858. def __set__(self, instance: object, value: Any) -> None:
  859. if self.fset is None:
  860. raise AttributeError("can't set attribute")
  861. self.fset(instance, value)
  862. def __delete__(self, instance: object) -> None:
  863. if self.fdel is None:
  864. raise AttributeError("can't delete attribute")
  865. self.fdel(instance)
  866. def _copy(self, **kw: Any) -> hybrid_property[_T]:
  867. defaults = {
  868. key: value
  869. for key, value in self.__dict__.items()
  870. if not key.startswith("_")
  871. }
  872. defaults.update(**kw)
  873. return type(self)(**defaults)
  874. @property
  875. def overrides(self) -> Self:
  876. """Prefix for a method that is overriding an existing attribute.
  877. The :attr:`.hybrid_property.overrides` accessor just returns
  878. this hybrid object, which when called at the class level from
  879. a parent class, will de-reference the "instrumented attribute"
  880. normally returned at this level, and allow modifying decorators
  881. like :meth:`.hybrid_property.expression` and
  882. :meth:`.hybrid_property.comparator`
  883. to be used without conflicting with the same-named attributes
  884. normally present on the :class:`.QueryableAttribute`::
  885. class SuperClass:
  886. # ...
  887. @hybrid_property
  888. def foobar(self):
  889. return self._foobar
  890. class SubClass(SuperClass):
  891. # ...
  892. @SuperClass.foobar.overrides.expression
  893. def foobar(cls):
  894. return func.subfoobar(self._foobar)
  895. .. versionadded:: 1.2
  896. .. seealso::
  897. :ref:`hybrid_reuse_subclass`
  898. """
  899. return self
  900. class _InPlace(Generic[_TE]):
  901. """A builder helper for .hybrid_property.
  902. .. versionadded:: 2.0.4
  903. """
  904. __slots__ = ("attr",)
  905. def __init__(self, attr: hybrid_property[_TE]):
  906. self.attr = attr
  907. def _set(self, **kw: Any) -> hybrid_property[_TE]:
  908. for k, v in kw.items():
  909. setattr(self.attr, k, _unwrap_classmethod(v))
  910. return self.attr
  911. def getter(self, fget: _HybridGetterType[_TE]) -> hybrid_property[_TE]:
  912. return self._set(fget=fget)
  913. def setter(self, fset: _HybridSetterType[_TE]) -> hybrid_property[_TE]:
  914. return self._set(fset=fset)
  915. def deleter(
  916. self, fdel: _HybridDeleterType[_TE]
  917. ) -> hybrid_property[_TE]:
  918. return self._set(fdel=fdel)
  919. def expression(
  920. self, expr: _HybridExprCallableType[_TE]
  921. ) -> hybrid_property[_TE]:
  922. return self._set(expr=expr)
  923. def comparator(
  924. self, comparator: _HybridComparatorCallableType[_TE]
  925. ) -> hybrid_property[_TE]:
  926. return self._set(custom_comparator=comparator)
  927. def update_expression(
  928. self, meth: _HybridUpdaterType[_TE]
  929. ) -> hybrid_property[_TE]:
  930. return self._set(update_expr=meth)
  931. @property
  932. def inplace(self) -> _InPlace[_T]:
  933. """Return the inplace mutator for this :class:`.hybrid_property`.
  934. This is to allow in-place mutation of the hybrid, allowing the first
  935. hybrid method of a certain name to be re-used in order to add
  936. more methods without having to name those methods the same, e.g.::
  937. class Interval(Base):
  938. # ...
  939. @hybrid_property
  940. def radius(self) -> float:
  941. return abs(self.length) / 2
  942. @radius.inplace.setter
  943. def _radius_setter(self, value: float) -> None:
  944. self.length = value * 2
  945. @radius.inplace.expression
  946. def _radius_expression(cls) -> ColumnElement[float]:
  947. return type_coerce(func.abs(cls.length) / 2, Float)
  948. .. versionadded:: 2.0.4
  949. .. seealso::
  950. :ref:`hybrid_pep484_naming`
  951. """
  952. return hybrid_property._InPlace(self)
  953. def getter(self, fget: _HybridGetterType[_T]) -> hybrid_property[_T]:
  954. """Provide a modifying decorator that defines a getter method.
  955. .. versionadded:: 1.2
  956. """
  957. return self._copy(fget=fget)
  958. def setter(self, fset: _HybridSetterType[_T]) -> hybrid_property[_T]:
  959. """Provide a modifying decorator that defines a setter method."""
  960. return self._copy(fset=fset)
  961. def deleter(self, fdel: _HybridDeleterType[_T]) -> hybrid_property[_T]:
  962. """Provide a modifying decorator that defines a deletion method."""
  963. return self._copy(fdel=fdel)
  964. def expression(
  965. self, expr: _HybridExprCallableType[_T]
  966. ) -> hybrid_property[_T]:
  967. """Provide a modifying decorator that defines a SQL-expression
  968. producing method.
  969. When a hybrid is invoked at the class level, the SQL expression given
  970. here is wrapped inside of a specialized :class:`.QueryableAttribute`,
  971. which is the same kind of object used by the ORM to represent other
  972. mapped attributes. The reason for this is so that other class-level
  973. attributes such as docstrings and a reference to the hybrid itself may
  974. be maintained within the structure that's returned, without any
  975. modifications to the original SQL expression passed in.
  976. .. note::
  977. When referring to a hybrid property from an owning class (e.g.
  978. ``SomeClass.some_hybrid``), an instance of
  979. :class:`.QueryableAttribute` is returned, representing the
  980. expression or comparator object as well as this hybrid object.
  981. However, that object itself has accessors called ``expression`` and
  982. ``comparator``; so when attempting to override these decorators on a
  983. subclass, it may be necessary to qualify it using the
  984. :attr:`.hybrid_property.overrides` modifier first. See that
  985. modifier for details.
  986. .. seealso::
  987. :ref:`hybrid_distinct_expression`
  988. """
  989. return self._copy(expr=expr)
  990. def comparator(
  991. self, comparator: _HybridComparatorCallableType[_T]
  992. ) -> hybrid_property[_T]:
  993. """Provide a modifying decorator that defines a custom
  994. comparator producing method.
  995. The return value of the decorated method should be an instance of
  996. :class:`~.hybrid.Comparator`.
  997. .. note:: The :meth:`.hybrid_property.comparator` decorator
  998. **replaces** the use of the :meth:`.hybrid_property.expression`
  999. decorator. They cannot be used together.
  1000. When a hybrid is invoked at the class level, the
  1001. :class:`~.hybrid.Comparator` object given here is wrapped inside of a
  1002. specialized :class:`.QueryableAttribute`, which is the same kind of
  1003. object used by the ORM to represent other mapped attributes. The
  1004. reason for this is so that other class-level attributes such as
  1005. docstrings and a reference to the hybrid itself may be maintained
  1006. within the structure that's returned, without any modifications to the
  1007. original comparator object passed in.
  1008. .. note::
  1009. When referring to a hybrid property from an owning class (e.g.
  1010. ``SomeClass.some_hybrid``), an instance of
  1011. :class:`.QueryableAttribute` is returned, representing the
  1012. expression or comparator object as this hybrid object. However,
  1013. that object itself has accessors called ``expression`` and
  1014. ``comparator``; so when attempting to override these decorators on a
  1015. subclass, it may be necessary to qualify it using the
  1016. :attr:`.hybrid_property.overrides` modifier first. See that
  1017. modifier for details.
  1018. """
  1019. return self._copy(custom_comparator=comparator)
  1020. def update_expression(
  1021. self, meth: _HybridUpdaterType[_T]
  1022. ) -> hybrid_property[_T]:
  1023. """Provide a modifying decorator that defines an UPDATE tuple
  1024. producing method.
  1025. The method accepts a single value, which is the value to be
  1026. rendered into the SET clause of an UPDATE statement. The method
  1027. should then process this value into individual column expressions
  1028. that fit into the ultimate SET clause, and return them as a
  1029. sequence of 2-tuples. Each tuple
  1030. contains a column expression as the key and a value to be rendered.
  1031. E.g.::
  1032. class Person(Base):
  1033. # ...
  1034. first_name = Column(String)
  1035. last_name = Column(String)
  1036. @hybrid_property
  1037. def fullname(self):
  1038. return first_name + " " + last_name
  1039. @fullname.update_expression
  1040. def fullname(cls, value):
  1041. fname, lname = value.split(" ", 1)
  1042. return [(cls.first_name, fname), (cls.last_name, lname)]
  1043. .. versionadded:: 1.2
  1044. """
  1045. return self._copy(update_expr=meth)
  1046. @util.memoized_property
  1047. def _expr_comparator(
  1048. self,
  1049. ) -> Callable[[Any], _HybridClassLevelAccessor[_T]]:
  1050. if self.custom_comparator is not None:
  1051. return self._get_comparator(self.custom_comparator)
  1052. elif self.expr is not None:
  1053. return self._get_expr(self.expr)
  1054. else:
  1055. return self._get_expr(cast(_HybridExprCallableType[_T], self.fget))
  1056. def _get_expr(
  1057. self, expr: _HybridExprCallableType[_T]
  1058. ) -> Callable[[Any], _HybridClassLevelAccessor[_T]]:
  1059. def _expr(cls: Any) -> ExprComparator[_T]:
  1060. return ExprComparator(cls, expr(cls), self)
  1061. util.update_wrapper(_expr, expr)
  1062. return self._get_comparator(_expr)
  1063. def _get_comparator(
  1064. self, comparator: Any
  1065. ) -> Callable[[Any], _HybridClassLevelAccessor[_T]]:
  1066. proxy_attr = attributes.create_proxied_attribute(self)
  1067. def expr_comparator(
  1068. owner: Type[object],
  1069. ) -> _HybridClassLevelAccessor[_T]:
  1070. # because this is the descriptor protocol, we don't really know
  1071. # what our attribute name is. so search for it through the
  1072. # MRO.
  1073. for lookup in owner.__mro__:
  1074. if self.__name__ in lookup.__dict__:
  1075. if lookup.__dict__[self.__name__] is self:
  1076. name = self.__name__
  1077. break
  1078. else:
  1079. name = attributes._UNKNOWN_ATTR_KEY # type: ignore[assignment]
  1080. return cast(
  1081. "_HybridClassLevelAccessor[_T]",
  1082. proxy_attr(
  1083. owner,
  1084. name,
  1085. self,
  1086. comparator(owner),
  1087. doc=comparator.__doc__ or self.__doc__,
  1088. ),
  1089. )
  1090. return expr_comparator
  1091. class Comparator(interfaces.PropComparator[_T]):
  1092. """A helper class that allows easy construction of custom
  1093. :class:`~.orm.interfaces.PropComparator`
  1094. classes for usage with hybrids."""
  1095. def __init__(
  1096. self, expression: Union[_HasClauseElement[_T], SQLColumnExpression[_T]]
  1097. ):
  1098. self.expression = expression
  1099. def __clause_element__(self) -> roles.ColumnsClauseRole:
  1100. expr = self.expression
  1101. if is_has_clause_element(expr):
  1102. ret_expr = expr.__clause_element__()
  1103. else:
  1104. if TYPE_CHECKING:
  1105. assert isinstance(expr, ColumnElement)
  1106. ret_expr = expr
  1107. if TYPE_CHECKING:
  1108. # see test_hybrid->test_expression_isnt_clause_element
  1109. # that exercises the usual place this is caught if not
  1110. # true
  1111. assert isinstance(ret_expr, ColumnElement)
  1112. return ret_expr
  1113. @util.non_memoized_property
  1114. def property(self) -> interfaces.MapperProperty[_T]:
  1115. raise NotImplementedError()
  1116. def adapt_to_entity(
  1117. self, adapt_to_entity: AliasedInsp[Any]
  1118. ) -> Comparator[_T]:
  1119. # interesting....
  1120. return self
  1121. class ExprComparator(Comparator[_T]):
  1122. def __init__(
  1123. self,
  1124. cls: Type[Any],
  1125. expression: Union[_HasClauseElement[_T], SQLColumnExpression[_T]],
  1126. hybrid: hybrid_property[_T],
  1127. ):
  1128. self.cls = cls
  1129. self.expression = expression
  1130. self.hybrid = hybrid
  1131. def __getattr__(self, key: str) -> Any:
  1132. return getattr(self.expression, key)
  1133. @util.ro_non_memoized_property
  1134. def info(self) -> _InfoType:
  1135. return self.hybrid.info
  1136. def _bulk_update_tuples(
  1137. self, value: Any
  1138. ) -> Sequence[Tuple[_DMLColumnArgument, Any]]:
  1139. if isinstance(self.expression, attributes.QueryableAttribute):
  1140. return self.expression._bulk_update_tuples(value)
  1141. elif self.hybrid.update_expr is not None:
  1142. return self.hybrid.update_expr(self.cls, value)
  1143. else:
  1144. return [(self.expression, value)]
  1145. @util.non_memoized_property
  1146. def property(self) -> MapperProperty[_T]:
  1147. # this accessor is not normally used, however is accessed by things
  1148. # like ORM synonyms if the hybrid is used in this context; the
  1149. # .property attribute is not necessarily accessible
  1150. return self.expression.property # type: ignore
  1151. def operate(
  1152. self, op: OperatorType, *other: Any, **kwargs: Any
  1153. ) -> ColumnElement[Any]:
  1154. return op(self.expression, *other, **kwargs)
  1155. def reverse_operate(
  1156. self, op: OperatorType, other: Any, **kwargs: Any
  1157. ) -> ColumnElement[Any]:
  1158. return op(other, self.expression, **kwargs) # type: ignore