operators.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600
  1. # sql/operators.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. # This module is part of SQLAlchemy and is released under
  8. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  9. """Defines operators used in SQL expressions."""
  10. from __future__ import annotations
  11. from enum import IntEnum
  12. from operator import add as _uncast_add
  13. from operator import and_ as _uncast_and_
  14. from operator import contains as _uncast_contains
  15. from operator import eq as _uncast_eq
  16. from operator import floordiv as _uncast_floordiv
  17. from operator import ge as _uncast_ge
  18. from operator import getitem as _uncast_getitem
  19. from operator import gt as _uncast_gt
  20. from operator import inv as _uncast_inv
  21. from operator import le as _uncast_le
  22. from operator import lshift as _uncast_lshift
  23. from operator import lt as _uncast_lt
  24. from operator import mod as _uncast_mod
  25. from operator import mul as _uncast_mul
  26. from operator import ne as _uncast_ne
  27. from operator import neg as _uncast_neg
  28. from operator import or_ as _uncast_or_
  29. from operator import rshift as _uncast_rshift
  30. from operator import sub as _uncast_sub
  31. from operator import truediv as _uncast_truediv
  32. import typing
  33. from typing import Any
  34. from typing import Callable
  35. from typing import cast
  36. from typing import Dict
  37. from typing import Generic
  38. from typing import Optional
  39. from typing import overload
  40. from typing import Set
  41. from typing import Tuple
  42. from typing import Type
  43. from typing import TYPE_CHECKING
  44. from typing import TypeVar
  45. from typing import Union
  46. from .. import exc
  47. from .. import util
  48. from ..util.typing import Literal
  49. from ..util.typing import Protocol
  50. if typing.TYPE_CHECKING:
  51. from ._typing import ColumnExpressionArgument
  52. from .cache_key import CacheConst
  53. from .elements import ColumnElement
  54. from .type_api import TypeEngine
  55. _T = TypeVar("_T", bound=Any)
  56. _FN = TypeVar("_FN", bound=Callable[..., Any])
  57. class OperatorType(Protocol):
  58. """describe an op() function."""
  59. __slots__ = ()
  60. __name__: str
  61. @overload
  62. def __call__(
  63. self,
  64. left: ColumnExpressionArgument[Any],
  65. right: Optional[Any] = None,
  66. *other: Any,
  67. **kwargs: Any,
  68. ) -> ColumnElement[Any]:
  69. ...
  70. @overload
  71. def __call__(
  72. self,
  73. left: Operators,
  74. right: Optional[Any] = None,
  75. *other: Any,
  76. **kwargs: Any,
  77. ) -> Operators:
  78. ...
  79. def __call__(
  80. self,
  81. left: Any,
  82. right: Optional[Any] = None,
  83. *other: Any,
  84. **kwargs: Any,
  85. ) -> Operators:
  86. ...
  87. add = cast(OperatorType, _uncast_add)
  88. and_ = cast(OperatorType, _uncast_and_)
  89. contains = cast(OperatorType, _uncast_contains)
  90. eq = cast(OperatorType, _uncast_eq)
  91. floordiv = cast(OperatorType, _uncast_floordiv)
  92. ge = cast(OperatorType, _uncast_ge)
  93. getitem = cast(OperatorType, _uncast_getitem)
  94. gt = cast(OperatorType, _uncast_gt)
  95. inv = cast(OperatorType, _uncast_inv)
  96. le = cast(OperatorType, _uncast_le)
  97. lshift = cast(OperatorType, _uncast_lshift)
  98. lt = cast(OperatorType, _uncast_lt)
  99. mod = cast(OperatorType, _uncast_mod)
  100. mul = cast(OperatorType, _uncast_mul)
  101. ne = cast(OperatorType, _uncast_ne)
  102. neg = cast(OperatorType, _uncast_neg)
  103. or_ = cast(OperatorType, _uncast_or_)
  104. rshift = cast(OperatorType, _uncast_rshift)
  105. sub = cast(OperatorType, _uncast_sub)
  106. truediv = cast(OperatorType, _uncast_truediv)
  107. class Operators:
  108. """Base of comparison and logical operators.
  109. Implements base methods
  110. :meth:`~sqlalchemy.sql.operators.Operators.operate` and
  111. :meth:`~sqlalchemy.sql.operators.Operators.reverse_operate`, as well as
  112. :meth:`~sqlalchemy.sql.operators.Operators.__and__`,
  113. :meth:`~sqlalchemy.sql.operators.Operators.__or__`,
  114. :meth:`~sqlalchemy.sql.operators.Operators.__invert__`.
  115. Usually is used via its most common subclass
  116. :class:`.ColumnOperators`.
  117. """
  118. __slots__ = ()
  119. def __and__(self, other: Any) -> Operators:
  120. """Implement the ``&`` operator.
  121. When used with SQL expressions, results in an
  122. AND operation, equivalent to
  123. :func:`_expression.and_`, that is::
  124. a & b
  125. is equivalent to::
  126. from sqlalchemy import and_
  127. and_(a, b)
  128. Care should be taken when using ``&`` regarding
  129. operator precedence; the ``&`` operator has the highest precedence.
  130. The operands should be enclosed in parenthesis if they contain
  131. further sub expressions::
  132. (a == 2) & (b == 4)
  133. """
  134. return self.operate(and_, other)
  135. def __or__(self, other: Any) -> Operators:
  136. """Implement the ``|`` operator.
  137. When used with SQL expressions, results in an
  138. OR operation, equivalent to
  139. :func:`_expression.or_`, that is::
  140. a | b
  141. is equivalent to::
  142. from sqlalchemy import or_
  143. or_(a, b)
  144. Care should be taken when using ``|`` regarding
  145. operator precedence; the ``|`` operator has the highest precedence.
  146. The operands should be enclosed in parenthesis if they contain
  147. further sub expressions::
  148. (a == 2) | (b == 4)
  149. """
  150. return self.operate(or_, other)
  151. def __invert__(self) -> Operators:
  152. """Implement the ``~`` operator.
  153. When used with SQL expressions, results in a
  154. NOT operation, equivalent to
  155. :func:`_expression.not_`, that is::
  156. ~a
  157. is equivalent to::
  158. from sqlalchemy import not_
  159. not_(a)
  160. """
  161. return self.operate(inv)
  162. def op(
  163. self,
  164. opstring: str,
  165. precedence: int = 0,
  166. is_comparison: bool = False,
  167. return_type: Optional[
  168. Union[Type[TypeEngine[Any]], TypeEngine[Any]]
  169. ] = None,
  170. python_impl: Optional[Callable[..., Any]] = None,
  171. ) -> Callable[[Any], Operators]:
  172. """Produce a generic operator function.
  173. e.g.::
  174. somecolumn.op("*")(5)
  175. produces::
  176. somecolumn * 5
  177. This function can also be used to make bitwise operators explicit. For
  178. example::
  179. somecolumn.op('&')(0xff)
  180. is a bitwise AND of the value in ``somecolumn``.
  181. :param opstring: a string which will be output as the infix operator
  182. between this element and the expression passed to the
  183. generated function.
  184. :param precedence: precedence which the database is expected to apply
  185. to the operator in SQL expressions. This integer value acts as a hint
  186. for the SQL compiler to know when explicit parenthesis should be
  187. rendered around a particular operation. A lower number will cause the
  188. expression to be parenthesized when applied against another operator
  189. with higher precedence. The default value of ``0`` is lower than all
  190. operators except for the comma (``,``) and ``AS`` operators. A value
  191. of 100 will be higher or equal to all operators, and -100 will be
  192. lower than or equal to all operators.
  193. .. seealso::
  194. :ref:`faq_sql_expression_op_parenthesis` - detailed description
  195. of how the SQLAlchemy SQL compiler renders parenthesis
  196. :param is_comparison: legacy; if True, the operator will be considered
  197. as a "comparison" operator, that is which evaluates to a boolean
  198. true/false value, like ``==``, ``>``, etc. This flag is provided
  199. so that ORM relationships can establish that the operator is a
  200. comparison operator when used in a custom join condition.
  201. Using the ``is_comparison`` parameter is superseded by using the
  202. :meth:`.Operators.bool_op` method instead; this more succinct
  203. operator sets this parameter automatically, but also provides
  204. correct :pep:`484` typing support as the returned object will
  205. express a "boolean" datatype, i.e. ``BinaryExpression[bool]``.
  206. :param return_type: a :class:`.TypeEngine` class or object that will
  207. force the return type of an expression produced by this operator
  208. to be of that type. By default, operators that specify
  209. :paramref:`.Operators.op.is_comparison` will resolve to
  210. :class:`.Boolean`, and those that do not will be of the same
  211. type as the left-hand operand.
  212. :param python_impl: an optional Python function that can evaluate
  213. two Python values in the same way as this operator works when
  214. run on the database server. Useful for in-Python SQL expression
  215. evaluation functions, such as for ORM hybrid attributes, and the
  216. ORM "evaluator" used to match objects in a session after a multi-row
  217. update or delete.
  218. e.g.::
  219. >>> expr = column('x').op('+', python_impl=lambda a, b: a + b)('y')
  220. The operator for the above expression will also work for non-SQL
  221. left and right objects::
  222. >>> expr.operator(5, 10)
  223. 15
  224. .. versionadded:: 2.0
  225. .. seealso::
  226. :meth:`.Operators.bool_op`
  227. :ref:`types_operators`
  228. :ref:`relationship_custom_operator`
  229. """
  230. operator = custom_op(
  231. opstring,
  232. precedence,
  233. is_comparison,
  234. return_type,
  235. python_impl=python_impl,
  236. )
  237. def against(other: Any) -> Operators:
  238. return operator(self, other)
  239. return against
  240. def bool_op(
  241. self,
  242. opstring: str,
  243. precedence: int = 0,
  244. python_impl: Optional[Callable[..., Any]] = None,
  245. ) -> Callable[[Any], Operators]:
  246. """Return a custom boolean operator.
  247. This method is shorthand for calling
  248. :meth:`.Operators.op` and passing the
  249. :paramref:`.Operators.op.is_comparison`
  250. flag with True. A key advantage to using :meth:`.Operators.bool_op`
  251. is that when using column constructs, the "boolean" nature of the
  252. returned expression will be present for :pep:`484` purposes.
  253. .. seealso::
  254. :meth:`.Operators.op`
  255. """
  256. return self.op(
  257. opstring,
  258. precedence=precedence,
  259. is_comparison=True,
  260. python_impl=python_impl,
  261. )
  262. def operate(
  263. self, op: OperatorType, *other: Any, **kwargs: Any
  264. ) -> Operators:
  265. r"""Operate on an argument.
  266. This is the lowest level of operation, raises
  267. :class:`NotImplementedError` by default.
  268. Overriding this on a subclass can allow common
  269. behavior to be applied to all operations.
  270. For example, overriding :class:`.ColumnOperators`
  271. to apply ``func.lower()`` to the left and right
  272. side::
  273. class MyComparator(ColumnOperators):
  274. def operate(self, op, other, **kwargs):
  275. return op(func.lower(self), func.lower(other), **kwargs)
  276. :param op: Operator callable.
  277. :param \*other: the 'other' side of the operation. Will
  278. be a single scalar for most operations.
  279. :param \**kwargs: modifiers. These may be passed by special
  280. operators such as :meth:`ColumnOperators.contains`.
  281. """
  282. raise NotImplementedError(str(op))
  283. __sa_operate__ = operate
  284. def reverse_operate(
  285. self, op: OperatorType, other: Any, **kwargs: Any
  286. ) -> Operators:
  287. """Reverse operate on an argument.
  288. Usage is the same as :meth:`operate`.
  289. """
  290. raise NotImplementedError(str(op))
  291. class custom_op(OperatorType, Generic[_T]):
  292. """Represent a 'custom' operator.
  293. :class:`.custom_op` is normally instantiated when the
  294. :meth:`.Operators.op` or :meth:`.Operators.bool_op` methods
  295. are used to create a custom operator callable. The class can also be
  296. used directly when programmatically constructing expressions. E.g.
  297. to represent the "factorial" operation::
  298. from sqlalchemy.sql import UnaryExpression
  299. from sqlalchemy.sql import operators
  300. from sqlalchemy import Numeric
  301. unary = UnaryExpression(table.c.somecolumn,
  302. modifier=operators.custom_op("!"),
  303. type_=Numeric)
  304. .. seealso::
  305. :meth:`.Operators.op`
  306. :meth:`.Operators.bool_op`
  307. """
  308. __name__ = "custom_op"
  309. __slots__ = (
  310. "opstring",
  311. "precedence",
  312. "is_comparison",
  313. "natural_self_precedent",
  314. "eager_grouping",
  315. "return_type",
  316. "python_impl",
  317. )
  318. def __init__(
  319. self,
  320. opstring: str,
  321. precedence: int = 0,
  322. is_comparison: bool = False,
  323. return_type: Optional[
  324. Union[Type[TypeEngine[_T]], TypeEngine[_T]]
  325. ] = None,
  326. natural_self_precedent: bool = False,
  327. eager_grouping: bool = False,
  328. python_impl: Optional[Callable[..., Any]] = None,
  329. ):
  330. self.opstring = opstring
  331. self.precedence = precedence
  332. self.is_comparison = is_comparison
  333. self.natural_self_precedent = natural_self_precedent
  334. self.eager_grouping = eager_grouping
  335. self.return_type = (
  336. return_type._to_instance(return_type) if return_type else None
  337. )
  338. self.python_impl = python_impl
  339. def __eq__(self, other: Any) -> bool:
  340. return (
  341. isinstance(other, custom_op)
  342. and other._hash_key() == self._hash_key()
  343. )
  344. def __hash__(self) -> int:
  345. return hash(self._hash_key())
  346. def _hash_key(self) -> Union[CacheConst, Tuple[Any, ...]]:
  347. return (
  348. self.__class__,
  349. self.opstring,
  350. self.precedence,
  351. self.is_comparison,
  352. self.natural_self_precedent,
  353. self.eager_grouping,
  354. self.return_type._static_cache_key if self.return_type else None,
  355. )
  356. @overload
  357. def __call__(
  358. self,
  359. left: ColumnExpressionArgument[Any],
  360. right: Optional[Any] = None,
  361. *other: Any,
  362. **kwargs: Any,
  363. ) -> ColumnElement[Any]:
  364. ...
  365. @overload
  366. def __call__(
  367. self,
  368. left: Operators,
  369. right: Optional[Any] = None,
  370. *other: Any,
  371. **kwargs: Any,
  372. ) -> Operators:
  373. ...
  374. def __call__(
  375. self,
  376. left: Any,
  377. right: Optional[Any] = None,
  378. *other: Any,
  379. **kwargs: Any,
  380. ) -> Operators:
  381. if hasattr(left, "__sa_operate__"):
  382. return left.operate(self, right, *other, **kwargs) # type: ignore
  383. elif self.python_impl:
  384. return self.python_impl(left, right, *other, **kwargs) # type: ignore # noqa: E501
  385. else:
  386. raise exc.InvalidRequestError(
  387. f"Custom operator {self.opstring!r} can't be used with "
  388. "plain Python objects unless it includes the "
  389. "'python_impl' parameter."
  390. )
  391. class ColumnOperators(Operators):
  392. """Defines boolean, comparison, and other operators for
  393. :class:`_expression.ColumnElement` expressions.
  394. By default, all methods call down to
  395. :meth:`.operate` or :meth:`.reverse_operate`,
  396. passing in the appropriate operator function from the
  397. Python builtin ``operator`` module or
  398. a SQLAlchemy-specific operator function from
  399. :mod:`sqlalchemy.expression.operators`. For example
  400. the ``__eq__`` function::
  401. def __eq__(self, other):
  402. return self.operate(operators.eq, other)
  403. Where ``operators.eq`` is essentially::
  404. def eq(a, b):
  405. return a == b
  406. The core column expression unit :class:`_expression.ColumnElement`
  407. overrides :meth:`.Operators.operate` and others
  408. to return further :class:`_expression.ColumnElement` constructs,
  409. so that the ``==`` operation above is replaced by a clause
  410. construct.
  411. .. seealso::
  412. :ref:`types_operators`
  413. :attr:`.TypeEngine.comparator_factory`
  414. :class:`.ColumnOperators`
  415. :class:`.PropComparator`
  416. """
  417. __slots__ = ()
  418. timetuple: Literal[None] = None
  419. """Hack, allows datetime objects to be compared on the LHS."""
  420. if typing.TYPE_CHECKING:
  421. def operate(
  422. self, op: OperatorType, *other: Any, **kwargs: Any
  423. ) -> ColumnOperators:
  424. ...
  425. def reverse_operate(
  426. self, op: OperatorType, other: Any, **kwargs: Any
  427. ) -> ColumnOperators:
  428. ...
  429. def __lt__(self, other: Any) -> ColumnOperators:
  430. """Implement the ``<`` operator.
  431. In a column context, produces the clause ``a < b``.
  432. """
  433. return self.operate(lt, other)
  434. def __le__(self, other: Any) -> ColumnOperators:
  435. """Implement the ``<=`` operator.
  436. In a column context, produces the clause ``a <= b``.
  437. """
  438. return self.operate(le, other)
  439. # ColumnOperators defines an __eq__ so it must explicitly declare also
  440. # an hash or it's set to None by python:
  441. # https://docs.python.org/3/reference/datamodel.html#object.__hash__
  442. if TYPE_CHECKING:
  443. def __hash__(self) -> int:
  444. ...
  445. else:
  446. __hash__ = Operators.__hash__
  447. def __eq__(self, other: Any) -> ColumnOperators: # type: ignore[override]
  448. """Implement the ``==`` operator.
  449. In a column context, produces the clause ``a = b``.
  450. If the target is ``None``, produces ``a IS NULL``.
  451. """
  452. return self.operate(eq, other)
  453. def __ne__(self, other: Any) -> ColumnOperators: # type: ignore[override]
  454. """Implement the ``!=`` operator.
  455. In a column context, produces the clause ``a != b``.
  456. If the target is ``None``, produces ``a IS NOT NULL``.
  457. """
  458. return self.operate(ne, other)
  459. def is_distinct_from(self, other: Any) -> ColumnOperators:
  460. """Implement the ``IS DISTINCT FROM`` operator.
  461. Renders "a IS DISTINCT FROM b" on most platforms;
  462. on some such as SQLite may render "a IS NOT b".
  463. """
  464. return self.operate(is_distinct_from, other)
  465. def is_not_distinct_from(self, other: Any) -> ColumnOperators:
  466. """Implement the ``IS NOT DISTINCT FROM`` operator.
  467. Renders "a IS NOT DISTINCT FROM b" on most platforms;
  468. on some such as SQLite may render "a IS b".
  469. .. versionchanged:: 1.4 The ``is_not_distinct_from()`` operator is
  470. renamed from ``isnot_distinct_from()`` in previous releases.
  471. The previous name remains available for backwards compatibility.
  472. """
  473. return self.operate(is_not_distinct_from, other)
  474. # deprecated 1.4; see #5435
  475. if TYPE_CHECKING:
  476. def isnot_distinct_from(self, other: Any) -> ColumnOperators:
  477. ...
  478. else:
  479. isnot_distinct_from = is_not_distinct_from
  480. def __gt__(self, other: Any) -> ColumnOperators:
  481. """Implement the ``>`` operator.
  482. In a column context, produces the clause ``a > b``.
  483. """
  484. return self.operate(gt, other)
  485. def __ge__(self, other: Any) -> ColumnOperators:
  486. """Implement the ``>=`` operator.
  487. In a column context, produces the clause ``a >= b``.
  488. """
  489. return self.operate(ge, other)
  490. def __neg__(self) -> ColumnOperators:
  491. """Implement the ``-`` operator.
  492. In a column context, produces the clause ``-a``.
  493. """
  494. return self.operate(neg)
  495. def __contains__(self, other: Any) -> ColumnOperators:
  496. return self.operate(contains, other)
  497. def __getitem__(self, index: Any) -> ColumnOperators:
  498. """Implement the [] operator.
  499. This can be used by some database-specific types
  500. such as PostgreSQL ARRAY and HSTORE.
  501. """
  502. return self.operate(getitem, index)
  503. def __lshift__(self, other: Any) -> ColumnOperators:
  504. """implement the << operator.
  505. Not used by SQLAlchemy core, this is provided
  506. for custom operator systems which want to use
  507. << as an extension point.
  508. """
  509. return self.operate(lshift, other)
  510. def __rshift__(self, other: Any) -> ColumnOperators:
  511. """implement the >> operator.
  512. Not used by SQLAlchemy core, this is provided
  513. for custom operator systems which want to use
  514. >> as an extension point.
  515. """
  516. return self.operate(rshift, other)
  517. def concat(self, other: Any) -> ColumnOperators:
  518. """Implement the 'concat' operator.
  519. In a column context, produces the clause ``a || b``,
  520. or uses the ``concat()`` operator on MySQL.
  521. """
  522. return self.operate(concat_op, other)
  523. def _rconcat(self, other: Any) -> ColumnOperators:
  524. """Implement an 'rconcat' operator.
  525. this is for internal use at the moment
  526. .. versionadded:: 1.4.40
  527. """
  528. return self.reverse_operate(concat_op, other)
  529. def like(
  530. self, other: Any, escape: Optional[str] = None
  531. ) -> ColumnOperators:
  532. r"""Implement the ``like`` operator.
  533. In a column context, produces the expression::
  534. a LIKE other
  535. E.g.::
  536. stmt = select(sometable).\
  537. where(sometable.c.column.like("%foobar%"))
  538. :param other: expression to be compared
  539. :param escape: optional escape character, renders the ``ESCAPE``
  540. keyword, e.g.::
  541. somecolumn.like("foo/%bar", escape="/")
  542. .. seealso::
  543. :meth:`.ColumnOperators.ilike`
  544. """
  545. return self.operate(like_op, other, escape=escape)
  546. def ilike(
  547. self, other: Any, escape: Optional[str] = None
  548. ) -> ColumnOperators:
  549. r"""Implement the ``ilike`` operator, e.g. case insensitive LIKE.
  550. In a column context, produces an expression either of the form::
  551. lower(a) LIKE lower(other)
  552. Or on backends that support the ILIKE operator::
  553. a ILIKE other
  554. E.g.::
  555. stmt = select(sometable).\
  556. where(sometable.c.column.ilike("%foobar%"))
  557. :param other: expression to be compared
  558. :param escape: optional escape character, renders the ``ESCAPE``
  559. keyword, e.g.::
  560. somecolumn.ilike("foo/%bar", escape="/")
  561. .. seealso::
  562. :meth:`.ColumnOperators.like`
  563. """
  564. return self.operate(ilike_op, other, escape=escape)
  565. def bitwise_xor(self, other: Any) -> ColumnOperators:
  566. """Produce a bitwise XOR operation, typically via the ``^``
  567. operator, or ``#`` for PostgreSQL.
  568. .. versionadded:: 2.0.2
  569. .. seealso::
  570. :ref:`operators_bitwise`
  571. """
  572. return self.operate(bitwise_xor_op, other)
  573. def bitwise_or(self, other: Any) -> ColumnOperators:
  574. """Produce a bitwise OR operation, typically via the ``|``
  575. operator.
  576. .. versionadded:: 2.0.2
  577. .. seealso::
  578. :ref:`operators_bitwise`
  579. """
  580. return self.operate(bitwise_or_op, other)
  581. def bitwise_and(self, other: Any) -> ColumnOperators:
  582. """Produce a bitwise AND operation, typically via the ``&``
  583. operator.
  584. .. versionadded:: 2.0.2
  585. .. seealso::
  586. :ref:`operators_bitwise`
  587. """
  588. return self.operate(bitwise_and_op, other)
  589. def bitwise_not(self) -> ColumnOperators:
  590. """Produce a bitwise NOT operation, typically via the ``~``
  591. operator.
  592. .. versionadded:: 2.0.2
  593. .. seealso::
  594. :ref:`operators_bitwise`
  595. """
  596. return self.operate(bitwise_not_op)
  597. def bitwise_lshift(self, other: Any) -> ColumnOperators:
  598. """Produce a bitwise LSHIFT operation, typically via the ``<<``
  599. operator.
  600. .. versionadded:: 2.0.2
  601. .. seealso::
  602. :ref:`operators_bitwise`
  603. """
  604. return self.operate(bitwise_lshift_op, other)
  605. def bitwise_rshift(self, other: Any) -> ColumnOperators:
  606. """Produce a bitwise RSHIFT operation, typically via the ``>>``
  607. operator.
  608. .. versionadded:: 2.0.2
  609. .. seealso::
  610. :ref:`operators_bitwise`
  611. """
  612. return self.operate(bitwise_rshift_op, other)
  613. def in_(self, other: Any) -> ColumnOperators:
  614. """Implement the ``in`` operator.
  615. In a column context, produces the clause ``column IN <other>``.
  616. The given parameter ``other`` may be:
  617. * A list of literal values, e.g.::
  618. stmt.where(column.in_([1, 2, 3]))
  619. In this calling form, the list of items is converted to a set of
  620. bound parameters the same length as the list given::
  621. WHERE COL IN (?, ?, ?)
  622. * A list of tuples may be provided if the comparison is against a
  623. :func:`.tuple_` containing multiple expressions::
  624. from sqlalchemy import tuple_
  625. stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
  626. * An empty list, e.g.::
  627. stmt.where(column.in_([]))
  628. In this calling form, the expression renders an "empty set"
  629. expression. These expressions are tailored to individual backends
  630. and are generally trying to get an empty SELECT statement as a
  631. subquery. Such as on SQLite, the expression is::
  632. WHERE col IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)
  633. .. versionchanged:: 1.4 empty IN expressions now use an
  634. execution-time generated SELECT subquery in all cases.
  635. * A bound parameter, e.g. :func:`.bindparam`, may be used if it
  636. includes the :paramref:`.bindparam.expanding` flag::
  637. stmt.where(column.in_(bindparam('value', expanding=True)))
  638. In this calling form, the expression renders a special non-SQL
  639. placeholder expression that looks like::
  640. WHERE COL IN ([EXPANDING_value])
  641. This placeholder expression is intercepted at statement execution
  642. time to be converted into the variable number of bound parameter
  643. form illustrated earlier. If the statement were executed as::
  644. connection.execute(stmt, {"value": [1, 2, 3]})
  645. The database would be passed a bound parameter for each value::
  646. WHERE COL IN (?, ?, ?)
  647. .. versionadded:: 1.2 added "expanding" bound parameters
  648. If an empty list is passed, a special "empty list" expression,
  649. which is specific to the database in use, is rendered. On
  650. SQLite this would be::
  651. WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)
  652. .. versionadded:: 1.3 "expanding" bound parameters now support
  653. empty lists
  654. * a :func:`_expression.select` construct, which is usually a
  655. correlated scalar select::
  656. stmt.where(
  657. column.in_(
  658. select(othertable.c.y).
  659. where(table.c.x == othertable.c.x)
  660. )
  661. )
  662. In this calling form, :meth:`.ColumnOperators.in_` renders as given::
  663. WHERE COL IN (SELECT othertable.y
  664. FROM othertable WHERE othertable.x = table.x)
  665. :param other: a list of literals, a :func:`_expression.select`
  666. construct, or a :func:`.bindparam` construct that includes the
  667. :paramref:`.bindparam.expanding` flag set to True.
  668. """
  669. return self.operate(in_op, other)
  670. def not_in(self, other: Any) -> ColumnOperators:
  671. """implement the ``NOT IN`` operator.
  672. This is equivalent to using negation with
  673. :meth:`.ColumnOperators.in_`, i.e. ``~x.in_(y)``.
  674. In the case that ``other`` is an empty sequence, the compiler
  675. produces an "empty not in" expression. This defaults to the
  676. expression "1 = 1" to produce true in all cases. The
  677. :paramref:`_sa.create_engine.empty_in_strategy` may be used to
  678. alter this behavior.
  679. .. versionchanged:: 1.4 The ``not_in()`` operator is renamed from
  680. ``notin_()`` in previous releases. The previous name remains
  681. available for backwards compatibility.
  682. .. versionchanged:: 1.2 The :meth:`.ColumnOperators.in_` and
  683. :meth:`.ColumnOperators.not_in` operators
  684. now produce a "static" expression for an empty IN sequence
  685. by default.
  686. .. seealso::
  687. :meth:`.ColumnOperators.in_`
  688. """
  689. return self.operate(not_in_op, other)
  690. # deprecated 1.4; see #5429
  691. if TYPE_CHECKING:
  692. def notin_(self, other: Any) -> ColumnOperators:
  693. ...
  694. else:
  695. notin_ = not_in
  696. def not_like(
  697. self, other: Any, escape: Optional[str] = None
  698. ) -> ColumnOperators:
  699. """implement the ``NOT LIKE`` operator.
  700. This is equivalent to using negation with
  701. :meth:`.ColumnOperators.like`, i.e. ``~x.like(y)``.
  702. .. versionchanged:: 1.4 The ``not_like()`` operator is renamed from
  703. ``notlike()`` in previous releases. The previous name remains
  704. available for backwards compatibility.
  705. .. seealso::
  706. :meth:`.ColumnOperators.like`
  707. """
  708. return self.operate(not_like_op, other, escape=escape)
  709. # deprecated 1.4; see #5435
  710. if TYPE_CHECKING:
  711. def notlike(
  712. self, other: Any, escape: Optional[str] = None
  713. ) -> ColumnOperators:
  714. ...
  715. else:
  716. notlike = not_like
  717. def not_ilike(
  718. self, other: Any, escape: Optional[str] = None
  719. ) -> ColumnOperators:
  720. """implement the ``NOT ILIKE`` operator.
  721. This is equivalent to using negation with
  722. :meth:`.ColumnOperators.ilike`, i.e. ``~x.ilike(y)``.
  723. .. versionchanged:: 1.4 The ``not_ilike()`` operator is renamed from
  724. ``notilike()`` in previous releases. The previous name remains
  725. available for backwards compatibility.
  726. .. seealso::
  727. :meth:`.ColumnOperators.ilike`
  728. """
  729. return self.operate(not_ilike_op, other, escape=escape)
  730. # deprecated 1.4; see #5435
  731. if TYPE_CHECKING:
  732. def notilike(
  733. self, other: Any, escape: Optional[str] = None
  734. ) -> ColumnOperators:
  735. ...
  736. else:
  737. notilike = not_ilike
  738. def is_(self, other: Any) -> ColumnOperators:
  739. """Implement the ``IS`` operator.
  740. Normally, ``IS`` is generated automatically when comparing to a
  741. value of ``None``, which resolves to ``NULL``. However, explicit
  742. usage of ``IS`` may be desirable if comparing to boolean values
  743. on certain platforms.
  744. .. seealso:: :meth:`.ColumnOperators.is_not`
  745. """
  746. return self.operate(is_, other)
  747. def is_not(self, other: Any) -> ColumnOperators:
  748. """Implement the ``IS NOT`` operator.
  749. Normally, ``IS NOT`` is generated automatically when comparing to a
  750. value of ``None``, which resolves to ``NULL``. However, explicit
  751. usage of ``IS NOT`` may be desirable if comparing to boolean values
  752. on certain platforms.
  753. .. versionchanged:: 1.4 The ``is_not()`` operator is renamed from
  754. ``isnot()`` in previous releases. The previous name remains
  755. available for backwards compatibility.
  756. .. seealso:: :meth:`.ColumnOperators.is_`
  757. """
  758. return self.operate(is_not, other)
  759. # deprecated 1.4; see #5429
  760. if TYPE_CHECKING:
  761. def isnot(self, other: Any) -> ColumnOperators:
  762. ...
  763. else:
  764. isnot = is_not
  765. def startswith(
  766. self,
  767. other: Any,
  768. escape: Optional[str] = None,
  769. autoescape: bool = False,
  770. ) -> ColumnOperators:
  771. r"""Implement the ``startswith`` operator.
  772. Produces a LIKE expression that tests against a match for the start
  773. of a string value::
  774. column LIKE <other> || '%'
  775. E.g.::
  776. stmt = select(sometable).\
  777. where(sometable.c.column.startswith("foobar"))
  778. Since the operator uses ``LIKE``, wildcard characters
  779. ``"%"`` and ``"_"`` that are present inside the <other> expression
  780. will behave like wildcards as well. For literal string
  781. values, the :paramref:`.ColumnOperators.startswith.autoescape` flag
  782. may be set to ``True`` to apply escaping to occurrences of these
  783. characters within the string value so that they match as themselves
  784. and not as wildcard characters. Alternatively, the
  785. :paramref:`.ColumnOperators.startswith.escape` parameter will establish
  786. a given character as an escape character which can be of use when
  787. the target expression is not a literal string.
  788. :param other: expression to be compared. This is usually a plain
  789. string value, but can also be an arbitrary SQL expression. LIKE
  790. wildcard characters ``%`` and ``_`` are not escaped by default unless
  791. the :paramref:`.ColumnOperators.startswith.autoescape` flag is
  792. set to True.
  793. :param autoescape: boolean; when True, establishes an escape character
  794. within the LIKE expression, then applies it to all occurrences of
  795. ``"%"``, ``"_"`` and the escape character itself within the
  796. comparison value, which is assumed to be a literal string and not a
  797. SQL expression.
  798. An expression such as::
  799. somecolumn.startswith("foo%bar", autoescape=True)
  800. Will render as::
  801. somecolumn LIKE :param || '%' ESCAPE '/'
  802. With the value of ``:param`` as ``"foo/%bar"``.
  803. :param escape: a character which when given will render with the
  804. ``ESCAPE`` keyword to establish that character as the escape
  805. character. This character can then be placed preceding occurrences
  806. of ``%`` and ``_`` to allow them to act as themselves and not
  807. wildcard characters.
  808. An expression such as::
  809. somecolumn.startswith("foo/%bar", escape="^")
  810. Will render as::
  811. somecolumn LIKE :param || '%' ESCAPE '^'
  812. The parameter may also be combined with
  813. :paramref:`.ColumnOperators.startswith.autoescape`::
  814. somecolumn.startswith("foo%bar^bat", escape="^", autoescape=True)
  815. Where above, the given literal parameter will be converted to
  816. ``"foo^%bar^^bat"`` before being passed to the database.
  817. .. seealso::
  818. :meth:`.ColumnOperators.endswith`
  819. :meth:`.ColumnOperators.contains`
  820. :meth:`.ColumnOperators.like`
  821. """
  822. return self.operate(
  823. startswith_op, other, escape=escape, autoescape=autoescape
  824. )
  825. def istartswith(
  826. self,
  827. other: Any,
  828. escape: Optional[str] = None,
  829. autoescape: bool = False,
  830. ) -> ColumnOperators:
  831. r"""Implement the ``istartswith`` operator, e.g. case insensitive
  832. version of :meth:`.ColumnOperators.startswith`.
  833. Produces a LIKE expression that tests against an insensitive
  834. match for the start of a string value::
  835. lower(column) LIKE lower(<other>) || '%'
  836. E.g.::
  837. stmt = select(sometable).\
  838. where(sometable.c.column.istartswith("foobar"))
  839. Since the operator uses ``LIKE``, wildcard characters
  840. ``"%"`` and ``"_"`` that are present inside the <other> expression
  841. will behave like wildcards as well. For literal string
  842. values, the :paramref:`.ColumnOperators.istartswith.autoescape` flag
  843. may be set to ``True`` to apply escaping to occurrences of these
  844. characters within the string value so that they match as themselves
  845. and not as wildcard characters. Alternatively, the
  846. :paramref:`.ColumnOperators.istartswith.escape` parameter will
  847. establish a given character as an escape character which can be of
  848. use when the target expression is not a literal string.
  849. :param other: expression to be compared. This is usually a plain
  850. string value, but can also be an arbitrary SQL expression. LIKE
  851. wildcard characters ``%`` and ``_`` are not escaped by default unless
  852. the :paramref:`.ColumnOperators.istartswith.autoescape` flag is
  853. set to True.
  854. :param autoescape: boolean; when True, establishes an escape character
  855. within the LIKE expression, then applies it to all occurrences of
  856. ``"%"``, ``"_"`` and the escape character itself within the
  857. comparison value, which is assumed to be a literal string and not a
  858. SQL expression.
  859. An expression such as::
  860. somecolumn.istartswith("foo%bar", autoescape=True)
  861. Will render as::
  862. lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '/'
  863. With the value of ``:param`` as ``"foo/%bar"``.
  864. :param escape: a character which when given will render with the
  865. ``ESCAPE`` keyword to establish that character as the escape
  866. character. This character can then be placed preceding occurrences
  867. of ``%`` and ``_`` to allow them to act as themselves and not
  868. wildcard characters.
  869. An expression such as::
  870. somecolumn.istartswith("foo/%bar", escape="^")
  871. Will render as::
  872. lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '^'
  873. The parameter may also be combined with
  874. :paramref:`.ColumnOperators.istartswith.autoescape`::
  875. somecolumn.istartswith("foo%bar^bat", escape="^", autoescape=True)
  876. Where above, the given literal parameter will be converted to
  877. ``"foo^%bar^^bat"`` before being passed to the database.
  878. .. seealso::
  879. :meth:`.ColumnOperators.startswith`
  880. """
  881. return self.operate(
  882. istartswith_op, other, escape=escape, autoescape=autoescape
  883. )
  884. def endswith(
  885. self,
  886. other: Any,
  887. escape: Optional[str] = None,
  888. autoescape: bool = False,
  889. ) -> ColumnOperators:
  890. r"""Implement the 'endswith' operator.
  891. Produces a LIKE expression that tests against a match for the end
  892. of a string value::
  893. column LIKE '%' || <other>
  894. E.g.::
  895. stmt = select(sometable).\
  896. where(sometable.c.column.endswith("foobar"))
  897. Since the operator uses ``LIKE``, wildcard characters
  898. ``"%"`` and ``"_"`` that are present inside the <other> expression
  899. will behave like wildcards as well. For literal string
  900. values, the :paramref:`.ColumnOperators.endswith.autoescape` flag
  901. may be set to ``True`` to apply escaping to occurrences of these
  902. characters within the string value so that they match as themselves
  903. and not as wildcard characters. Alternatively, the
  904. :paramref:`.ColumnOperators.endswith.escape` parameter will establish
  905. a given character as an escape character which can be of use when
  906. the target expression is not a literal string.
  907. :param other: expression to be compared. This is usually a plain
  908. string value, but can also be an arbitrary SQL expression. LIKE
  909. wildcard characters ``%`` and ``_`` are not escaped by default unless
  910. the :paramref:`.ColumnOperators.endswith.autoescape` flag is
  911. set to True.
  912. :param autoescape: boolean; when True, establishes an escape character
  913. within the LIKE expression, then applies it to all occurrences of
  914. ``"%"``, ``"_"`` and the escape character itself within the
  915. comparison value, which is assumed to be a literal string and not a
  916. SQL expression.
  917. An expression such as::
  918. somecolumn.endswith("foo%bar", autoescape=True)
  919. Will render as::
  920. somecolumn LIKE '%' || :param ESCAPE '/'
  921. With the value of ``:param`` as ``"foo/%bar"``.
  922. :param escape: a character which when given will render with the
  923. ``ESCAPE`` keyword to establish that character as the escape
  924. character. This character can then be placed preceding occurrences
  925. of ``%`` and ``_`` to allow them to act as themselves and not
  926. wildcard characters.
  927. An expression such as::
  928. somecolumn.endswith("foo/%bar", escape="^")
  929. Will render as::
  930. somecolumn LIKE '%' || :param ESCAPE '^'
  931. The parameter may also be combined with
  932. :paramref:`.ColumnOperators.endswith.autoescape`::
  933. somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)
  934. Where above, the given literal parameter will be converted to
  935. ``"foo^%bar^^bat"`` before being passed to the database.
  936. .. seealso::
  937. :meth:`.ColumnOperators.startswith`
  938. :meth:`.ColumnOperators.contains`
  939. :meth:`.ColumnOperators.like`
  940. """
  941. return self.operate(
  942. endswith_op, other, escape=escape, autoescape=autoescape
  943. )
  944. def iendswith(
  945. self,
  946. other: Any,
  947. escape: Optional[str] = None,
  948. autoescape: bool = False,
  949. ) -> ColumnOperators:
  950. r"""Implement the ``iendswith`` operator, e.g. case insensitive
  951. version of :meth:`.ColumnOperators.endswith`.
  952. Produces a LIKE expression that tests against an insensitive match
  953. for the end of a string value::
  954. lower(column) LIKE '%' || lower(<other>)
  955. E.g.::
  956. stmt = select(sometable).\
  957. where(sometable.c.column.iendswith("foobar"))
  958. Since the operator uses ``LIKE``, wildcard characters
  959. ``"%"`` and ``"_"`` that are present inside the <other> expression
  960. will behave like wildcards as well. For literal string
  961. values, the :paramref:`.ColumnOperators.iendswith.autoescape` flag
  962. may be set to ``True`` to apply escaping to occurrences of these
  963. characters within the string value so that they match as themselves
  964. and not as wildcard characters. Alternatively, the
  965. :paramref:`.ColumnOperators.iendswith.escape` parameter will establish
  966. a given character as an escape character which can be of use when
  967. the target expression is not a literal string.
  968. :param other: expression to be compared. This is usually a plain
  969. string value, but can also be an arbitrary SQL expression. LIKE
  970. wildcard characters ``%`` and ``_`` are not escaped by default unless
  971. the :paramref:`.ColumnOperators.iendswith.autoescape` flag is
  972. set to True.
  973. :param autoescape: boolean; when True, establishes an escape character
  974. within the LIKE expression, then applies it to all occurrences of
  975. ``"%"``, ``"_"`` and the escape character itself within the
  976. comparison value, which is assumed to be a literal string and not a
  977. SQL expression.
  978. An expression such as::
  979. somecolumn.iendswith("foo%bar", autoescape=True)
  980. Will render as::
  981. lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '/'
  982. With the value of ``:param`` as ``"foo/%bar"``.
  983. :param escape: a character which when given will render with the
  984. ``ESCAPE`` keyword to establish that character as the escape
  985. character. This character can then be placed preceding occurrences
  986. of ``%`` and ``_`` to allow them to act as themselves and not
  987. wildcard characters.
  988. An expression such as::
  989. somecolumn.iendswith("foo/%bar", escape="^")
  990. Will render as::
  991. lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '^'
  992. The parameter may also be combined with
  993. :paramref:`.ColumnOperators.iendswith.autoescape`::
  994. somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)
  995. Where above, the given literal parameter will be converted to
  996. ``"foo^%bar^^bat"`` before being passed to the database.
  997. .. seealso::
  998. :meth:`.ColumnOperators.endswith`
  999. """
  1000. return self.operate(
  1001. iendswith_op, other, escape=escape, autoescape=autoescape
  1002. )
  1003. def contains(self, other: Any, **kw: Any) -> ColumnOperators:
  1004. r"""Implement the 'contains' operator.
  1005. Produces a LIKE expression that tests against a match for the middle
  1006. of a string value::
  1007. column LIKE '%' || <other> || '%'
  1008. E.g.::
  1009. stmt = select(sometable).\
  1010. where(sometable.c.column.contains("foobar"))
  1011. Since the operator uses ``LIKE``, wildcard characters
  1012. ``"%"`` and ``"_"`` that are present inside the <other> expression
  1013. will behave like wildcards as well. For literal string
  1014. values, the :paramref:`.ColumnOperators.contains.autoescape` flag
  1015. may be set to ``True`` to apply escaping to occurrences of these
  1016. characters within the string value so that they match as themselves
  1017. and not as wildcard characters. Alternatively, the
  1018. :paramref:`.ColumnOperators.contains.escape` parameter will establish
  1019. a given character as an escape character which can be of use when
  1020. the target expression is not a literal string.
  1021. :param other: expression to be compared. This is usually a plain
  1022. string value, but can also be an arbitrary SQL expression. LIKE
  1023. wildcard characters ``%`` and ``_`` are not escaped by default unless
  1024. the :paramref:`.ColumnOperators.contains.autoescape` flag is
  1025. set to True.
  1026. :param autoescape: boolean; when True, establishes an escape character
  1027. within the LIKE expression, then applies it to all occurrences of
  1028. ``"%"``, ``"_"`` and the escape character itself within the
  1029. comparison value, which is assumed to be a literal string and not a
  1030. SQL expression.
  1031. An expression such as::
  1032. somecolumn.contains("foo%bar", autoescape=True)
  1033. Will render as::
  1034. somecolumn LIKE '%' || :param || '%' ESCAPE '/'
  1035. With the value of ``:param`` as ``"foo/%bar"``.
  1036. :param escape: a character which when given will render with the
  1037. ``ESCAPE`` keyword to establish that character as the escape
  1038. character. This character can then be placed preceding occurrences
  1039. of ``%`` and ``_`` to allow them to act as themselves and not
  1040. wildcard characters.
  1041. An expression such as::
  1042. somecolumn.contains("foo/%bar", escape="^")
  1043. Will render as::
  1044. somecolumn LIKE '%' || :param || '%' ESCAPE '^'
  1045. The parameter may also be combined with
  1046. :paramref:`.ColumnOperators.contains.autoescape`::
  1047. somecolumn.contains("foo%bar^bat", escape="^", autoescape=True)
  1048. Where above, the given literal parameter will be converted to
  1049. ``"foo^%bar^^bat"`` before being passed to the database.
  1050. .. seealso::
  1051. :meth:`.ColumnOperators.startswith`
  1052. :meth:`.ColumnOperators.endswith`
  1053. :meth:`.ColumnOperators.like`
  1054. """
  1055. return self.operate(contains_op, other, **kw)
  1056. def icontains(self, other: Any, **kw: Any) -> ColumnOperators:
  1057. r"""Implement the ``icontains`` operator, e.g. case insensitive
  1058. version of :meth:`.ColumnOperators.contains`.
  1059. Produces a LIKE expression that tests against an insensitive match
  1060. for the middle of a string value::
  1061. lower(column) LIKE '%' || lower(<other>) || '%'
  1062. E.g.::
  1063. stmt = select(sometable).\
  1064. where(sometable.c.column.icontains("foobar"))
  1065. Since the operator uses ``LIKE``, wildcard characters
  1066. ``"%"`` and ``"_"`` that are present inside the <other> expression
  1067. will behave like wildcards as well. For literal string
  1068. values, the :paramref:`.ColumnOperators.icontains.autoescape` flag
  1069. may be set to ``True`` to apply escaping to occurrences of these
  1070. characters within the string value so that they match as themselves
  1071. and not as wildcard characters. Alternatively, the
  1072. :paramref:`.ColumnOperators.icontains.escape` parameter will establish
  1073. a given character as an escape character which can be of use when
  1074. the target expression is not a literal string.
  1075. :param other: expression to be compared. This is usually a plain
  1076. string value, but can also be an arbitrary SQL expression. LIKE
  1077. wildcard characters ``%`` and ``_`` are not escaped by default unless
  1078. the :paramref:`.ColumnOperators.icontains.autoescape` flag is
  1079. set to True.
  1080. :param autoescape: boolean; when True, establishes an escape character
  1081. within the LIKE expression, then applies it to all occurrences of
  1082. ``"%"``, ``"_"`` and the escape character itself within the
  1083. comparison value, which is assumed to be a literal string and not a
  1084. SQL expression.
  1085. An expression such as::
  1086. somecolumn.icontains("foo%bar", autoescape=True)
  1087. Will render as::
  1088. lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '/'
  1089. With the value of ``:param`` as ``"foo/%bar"``.
  1090. :param escape: a character which when given will render with the
  1091. ``ESCAPE`` keyword to establish that character as the escape
  1092. character. This character can then be placed preceding occurrences
  1093. of ``%`` and ``_`` to allow them to act as themselves and not
  1094. wildcard characters.
  1095. An expression such as::
  1096. somecolumn.icontains("foo/%bar", escape="^")
  1097. Will render as::
  1098. lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '^'
  1099. The parameter may also be combined with
  1100. :paramref:`.ColumnOperators.contains.autoescape`::
  1101. somecolumn.icontains("foo%bar^bat", escape="^", autoescape=True)
  1102. Where above, the given literal parameter will be converted to
  1103. ``"foo^%bar^^bat"`` before being passed to the database.
  1104. .. seealso::
  1105. :meth:`.ColumnOperators.contains`
  1106. """
  1107. return self.operate(icontains_op, other, **kw)
  1108. def match(self, other: Any, **kwargs: Any) -> ColumnOperators:
  1109. """Implements a database-specific 'match' operator.
  1110. :meth:`_sql.ColumnOperators.match` attempts to resolve to
  1111. a MATCH-like function or operator provided by the backend.
  1112. Examples include:
  1113. * PostgreSQL - renders ``x @@ plainto_tsquery(y)``
  1114. .. versionchanged:: 2.0 ``plainto_tsquery()`` is used instead
  1115. of ``to_tsquery()`` for PostgreSQL now; for compatibility with
  1116. other forms, see :ref:`postgresql_match`.
  1117. * MySQL - renders ``MATCH (x) AGAINST (y IN BOOLEAN MODE)``
  1118. .. seealso::
  1119. :class:`_mysql.match` - MySQL specific construct with
  1120. additional features.
  1121. * Oracle - renders ``CONTAINS(x, y)``
  1122. * other backends may provide special implementations.
  1123. * Backends without any special implementation will emit
  1124. the operator as "MATCH". This is compatible with SQLite, for
  1125. example.
  1126. """
  1127. return self.operate(match_op, other, **kwargs)
  1128. def regexp_match(
  1129. self, pattern: Any, flags: Optional[str] = None
  1130. ) -> ColumnOperators:
  1131. """Implements a database-specific 'regexp match' operator.
  1132. E.g.::
  1133. stmt = select(table.c.some_column).where(
  1134. table.c.some_column.regexp_match('^(b|c)')
  1135. )
  1136. :meth:`_sql.ColumnOperators.regexp_match` attempts to resolve to
  1137. a REGEXP-like function or operator provided by the backend, however
  1138. the specific regular expression syntax and flags available are
  1139. **not backend agnostic**.
  1140. Examples include:
  1141. * PostgreSQL - renders ``x ~ y`` or ``x !~ y`` when negated.
  1142. * Oracle - renders ``REGEXP_LIKE(x, y)``
  1143. * SQLite - uses SQLite's ``REGEXP`` placeholder operator and calls into
  1144. the Python ``re.match()`` builtin.
  1145. * other backends may provide special implementations.
  1146. * Backends without any special implementation will emit
  1147. the operator as "REGEXP" or "NOT REGEXP". This is compatible with
  1148. SQLite and MySQL, for example.
  1149. Regular expression support is currently implemented for Oracle,
  1150. PostgreSQL, MySQL and MariaDB. Partial support is available for
  1151. SQLite. Support among third-party dialects may vary.
  1152. :param pattern: The regular expression pattern string or column
  1153. clause.
  1154. :param flags: Any regular expression string flags to apply, passed as
  1155. plain Python string only. These flags are backend specific.
  1156. Some backends, like PostgreSQL and MariaDB, may alternatively
  1157. specify the flags as part of the pattern.
  1158. When using the ignore case flag 'i' in PostgreSQL, the ignore case
  1159. regexp match operator ``~*`` or ``!~*`` will be used.
  1160. .. versionadded:: 1.4
  1161. .. versionchanged:: 1.4.48, 2.0.18 Note that due to an implementation
  1162. error, the "flags" parameter previously accepted SQL expression
  1163. objects such as column expressions in addition to plain Python
  1164. strings. This implementation did not work correctly with caching
  1165. and was removed; strings only should be passed for the "flags"
  1166. parameter, as these flags are rendered as literal inline values
  1167. within SQL expressions.
  1168. .. seealso::
  1169. :meth:`_sql.ColumnOperators.regexp_replace`
  1170. """
  1171. return self.operate(regexp_match_op, pattern, flags=flags)
  1172. def regexp_replace(
  1173. self, pattern: Any, replacement: Any, flags: Optional[str] = None
  1174. ) -> ColumnOperators:
  1175. """Implements a database-specific 'regexp replace' operator.
  1176. E.g.::
  1177. stmt = select(
  1178. table.c.some_column.regexp_replace(
  1179. 'b(..)',
  1180. 'X\1Y',
  1181. flags='g'
  1182. )
  1183. )
  1184. :meth:`_sql.ColumnOperators.regexp_replace` attempts to resolve to
  1185. a REGEXP_REPLACE-like function provided by the backend, that
  1186. usually emit the function ``REGEXP_REPLACE()``. However,
  1187. the specific regular expression syntax and flags available are
  1188. **not backend agnostic**.
  1189. Regular expression replacement support is currently implemented for
  1190. Oracle, PostgreSQL, MySQL 8 or greater and MariaDB. Support among
  1191. third-party dialects may vary.
  1192. :param pattern: The regular expression pattern string or column
  1193. clause.
  1194. :param pattern: The replacement string or column clause.
  1195. :param flags: Any regular expression string flags to apply, passed as
  1196. plain Python string only. These flags are backend specific.
  1197. Some backends, like PostgreSQL and MariaDB, may alternatively
  1198. specify the flags as part of the pattern.
  1199. .. versionadded:: 1.4
  1200. .. versionchanged:: 1.4.48, 2.0.18 Note that due to an implementation
  1201. error, the "flags" parameter previously accepted SQL expression
  1202. objects such as column expressions in addition to plain Python
  1203. strings. This implementation did not work correctly with caching
  1204. and was removed; strings only should be passed for the "flags"
  1205. parameter, as these flags are rendered as literal inline values
  1206. within SQL expressions.
  1207. .. seealso::
  1208. :meth:`_sql.ColumnOperators.regexp_match`
  1209. """
  1210. return self.operate(
  1211. regexp_replace_op,
  1212. pattern,
  1213. replacement=replacement,
  1214. flags=flags,
  1215. )
  1216. def desc(self) -> ColumnOperators:
  1217. """Produce a :func:`_expression.desc` clause against the
  1218. parent object."""
  1219. return self.operate(desc_op)
  1220. def asc(self) -> ColumnOperators:
  1221. """Produce a :func:`_expression.asc` clause against the
  1222. parent object."""
  1223. return self.operate(asc_op)
  1224. def nulls_first(self) -> ColumnOperators:
  1225. """Produce a :func:`_expression.nulls_first` clause against the
  1226. parent object.
  1227. .. versionchanged:: 1.4 The ``nulls_first()`` operator is
  1228. renamed from ``nullsfirst()`` in previous releases.
  1229. The previous name remains available for backwards compatibility.
  1230. """
  1231. return self.operate(nulls_first_op)
  1232. # deprecated 1.4; see #5435
  1233. if TYPE_CHECKING:
  1234. def nullsfirst(self) -> ColumnOperators:
  1235. ...
  1236. else:
  1237. nullsfirst = nulls_first
  1238. def nulls_last(self) -> ColumnOperators:
  1239. """Produce a :func:`_expression.nulls_last` clause against the
  1240. parent object.
  1241. .. versionchanged:: 1.4 The ``nulls_last()`` operator is
  1242. renamed from ``nullslast()`` in previous releases.
  1243. The previous name remains available for backwards compatibility.
  1244. """
  1245. return self.operate(nulls_last_op)
  1246. # deprecated 1.4; see #5429
  1247. if TYPE_CHECKING:
  1248. def nullslast(self) -> ColumnOperators:
  1249. ...
  1250. else:
  1251. nullslast = nulls_last
  1252. def collate(self, collation: str) -> ColumnOperators:
  1253. """Produce a :func:`_expression.collate` clause against
  1254. the parent object, given the collation string.
  1255. .. seealso::
  1256. :func:`_expression.collate`
  1257. """
  1258. return self.operate(collate, collation)
  1259. def __radd__(self, other: Any) -> ColumnOperators:
  1260. """Implement the ``+`` operator in reverse.
  1261. See :meth:`.ColumnOperators.__add__`.
  1262. """
  1263. return self.reverse_operate(add, other)
  1264. def __rsub__(self, other: Any) -> ColumnOperators:
  1265. """Implement the ``-`` operator in reverse.
  1266. See :meth:`.ColumnOperators.__sub__`.
  1267. """
  1268. return self.reverse_operate(sub, other)
  1269. def __rmul__(self, other: Any) -> ColumnOperators:
  1270. """Implement the ``*`` operator in reverse.
  1271. See :meth:`.ColumnOperators.__mul__`.
  1272. """
  1273. return self.reverse_operate(mul, other)
  1274. def __rmod__(self, other: Any) -> ColumnOperators:
  1275. """Implement the ``%`` operator in reverse.
  1276. See :meth:`.ColumnOperators.__mod__`.
  1277. """
  1278. return self.reverse_operate(mod, other)
  1279. def between(
  1280. self, cleft: Any, cright: Any, symmetric: bool = False
  1281. ) -> ColumnOperators:
  1282. """Produce a :func:`_expression.between` clause against
  1283. the parent object, given the lower and upper range.
  1284. """
  1285. return self.operate(between_op, cleft, cright, symmetric=symmetric)
  1286. def distinct(self) -> ColumnOperators:
  1287. """Produce a :func:`_expression.distinct` clause against the
  1288. parent object.
  1289. """
  1290. return self.operate(distinct_op)
  1291. def any_(self) -> ColumnOperators:
  1292. """Produce an :func:`_expression.any_` clause against the
  1293. parent object.
  1294. See the documentation for :func:`_sql.any_` for examples.
  1295. .. note:: be sure to not confuse the newer
  1296. :meth:`_sql.ColumnOperators.any_` method with the **legacy**
  1297. version of this method, the :meth:`_types.ARRAY.Comparator.any`
  1298. method that's specific to :class:`_types.ARRAY`, which uses a
  1299. different calling style.
  1300. """
  1301. return self.operate(any_op)
  1302. def all_(self) -> ColumnOperators:
  1303. """Produce an :func:`_expression.all_` clause against the
  1304. parent object.
  1305. See the documentation for :func:`_sql.all_` for examples.
  1306. .. note:: be sure to not confuse the newer
  1307. :meth:`_sql.ColumnOperators.all_` method with the **legacy**
  1308. version of this method, the :meth:`_types.ARRAY.Comparator.all`
  1309. method that's specific to :class:`_types.ARRAY`, which uses a
  1310. different calling style.
  1311. """
  1312. return self.operate(all_op)
  1313. def __add__(self, other: Any) -> ColumnOperators:
  1314. """Implement the ``+`` operator.
  1315. In a column context, produces the clause ``a + b``
  1316. if the parent object has non-string affinity.
  1317. If the parent object has a string affinity,
  1318. produces the concatenation operator, ``a || b`` -
  1319. see :meth:`.ColumnOperators.concat`.
  1320. """
  1321. return self.operate(add, other)
  1322. def __sub__(self, other: Any) -> ColumnOperators:
  1323. """Implement the ``-`` operator.
  1324. In a column context, produces the clause ``a - b``.
  1325. """
  1326. return self.operate(sub, other)
  1327. def __mul__(self, other: Any) -> ColumnOperators:
  1328. """Implement the ``*`` operator.
  1329. In a column context, produces the clause ``a * b``.
  1330. """
  1331. return self.operate(mul, other)
  1332. def __mod__(self, other: Any) -> ColumnOperators:
  1333. """Implement the ``%`` operator.
  1334. In a column context, produces the clause ``a % b``.
  1335. """
  1336. return self.operate(mod, other)
  1337. def __truediv__(self, other: Any) -> ColumnOperators:
  1338. """Implement the ``/`` operator.
  1339. In a column context, produces the clause ``a / b``, and
  1340. considers the result type to be numeric.
  1341. .. versionchanged:: 2.0 The truediv operator against two integers
  1342. is now considered to return a numeric value. Behavior on specific
  1343. backends may vary.
  1344. """
  1345. return self.operate(truediv, other)
  1346. def __rtruediv__(self, other: Any) -> ColumnOperators:
  1347. """Implement the ``/`` operator in reverse.
  1348. See :meth:`.ColumnOperators.__truediv__`.
  1349. """
  1350. return self.reverse_operate(truediv, other)
  1351. def __floordiv__(self, other: Any) -> ColumnOperators:
  1352. """Implement the ``//`` operator.
  1353. In a column context, produces the clause ``a / b``,
  1354. which is the same as "truediv", but considers the result
  1355. type to be integer.
  1356. .. versionadded:: 2.0
  1357. """
  1358. return self.operate(floordiv, other)
  1359. def __rfloordiv__(self, other: Any) -> ColumnOperators:
  1360. """Implement the ``//`` operator in reverse.
  1361. See :meth:`.ColumnOperators.__floordiv__`.
  1362. """
  1363. return self.reverse_operate(floordiv, other)
  1364. _commutative: Set[Any] = {eq, ne, add, mul}
  1365. _comparison: Set[Any] = {eq, ne, lt, gt, ge, le}
  1366. def _operator_fn(fn: Callable[..., Any]) -> OperatorType:
  1367. return cast(OperatorType, fn)
  1368. def commutative_op(fn: _FN) -> _FN:
  1369. _commutative.add(fn)
  1370. return fn
  1371. def comparison_op(fn: _FN) -> _FN:
  1372. _comparison.add(fn)
  1373. return fn
  1374. @_operator_fn
  1375. def from_() -> Any:
  1376. raise NotImplementedError()
  1377. @_operator_fn
  1378. @comparison_op
  1379. def function_as_comparison_op() -> Any:
  1380. raise NotImplementedError()
  1381. @_operator_fn
  1382. def as_() -> Any:
  1383. raise NotImplementedError()
  1384. @_operator_fn
  1385. def exists() -> Any:
  1386. raise NotImplementedError()
  1387. @_operator_fn
  1388. def is_true(a: Any) -> Any:
  1389. raise NotImplementedError()
  1390. # 1.4 deprecated; see #5435
  1391. if TYPE_CHECKING:
  1392. @_operator_fn
  1393. def istrue(a: Any) -> Any:
  1394. ...
  1395. else:
  1396. istrue = is_true
  1397. @_operator_fn
  1398. def is_false(a: Any) -> Any:
  1399. raise NotImplementedError()
  1400. # 1.4 deprecated; see #5435
  1401. if TYPE_CHECKING:
  1402. @_operator_fn
  1403. def isfalse(a: Any) -> Any:
  1404. ...
  1405. else:
  1406. isfalse = is_false
  1407. @comparison_op
  1408. @_operator_fn
  1409. def is_distinct_from(a: Any, b: Any) -> Any:
  1410. return a.is_distinct_from(b)
  1411. @comparison_op
  1412. @_operator_fn
  1413. def is_not_distinct_from(a: Any, b: Any) -> Any:
  1414. return a.is_not_distinct_from(b)
  1415. # deprecated 1.4; see #5435
  1416. if TYPE_CHECKING:
  1417. @_operator_fn
  1418. def isnot_distinct_from(a: Any, b: Any) -> Any:
  1419. ...
  1420. else:
  1421. isnot_distinct_from = is_not_distinct_from
  1422. @comparison_op
  1423. @_operator_fn
  1424. def is_(a: Any, b: Any) -> Any:
  1425. return a.is_(b)
  1426. @comparison_op
  1427. @_operator_fn
  1428. def is_not(a: Any, b: Any) -> Any:
  1429. return a.is_not(b)
  1430. # 1.4 deprecated; see #5429
  1431. if TYPE_CHECKING:
  1432. @_operator_fn
  1433. def isnot(a: Any, b: Any) -> Any:
  1434. ...
  1435. else:
  1436. isnot = is_not
  1437. @_operator_fn
  1438. def collate(a: Any, b: Any) -> Any:
  1439. return a.collate(b)
  1440. @_operator_fn
  1441. def op(a: Any, opstring: str, b: Any) -> Any:
  1442. return a.op(opstring)(b)
  1443. @comparison_op
  1444. @_operator_fn
  1445. def like_op(a: Any, b: Any, escape: Optional[str] = None) -> Any:
  1446. return a.like(b, escape=escape)
  1447. @comparison_op
  1448. @_operator_fn
  1449. def not_like_op(a: Any, b: Any, escape: Optional[str] = None) -> Any:
  1450. return a.notlike(b, escape=escape)
  1451. # 1.4 deprecated; see #5435
  1452. if TYPE_CHECKING:
  1453. @_operator_fn
  1454. def notlike_op(a: Any, b: Any, escape: Optional[str] = None) -> Any:
  1455. ...
  1456. else:
  1457. notlike_op = not_like_op
  1458. @comparison_op
  1459. @_operator_fn
  1460. def ilike_op(a: Any, b: Any, escape: Optional[str] = None) -> Any:
  1461. return a.ilike(b, escape=escape)
  1462. @comparison_op
  1463. @_operator_fn
  1464. def not_ilike_op(a: Any, b: Any, escape: Optional[str] = None) -> Any:
  1465. return a.not_ilike(b, escape=escape)
  1466. # 1.4 deprecated; see #5435
  1467. if TYPE_CHECKING:
  1468. @_operator_fn
  1469. def notilike_op(a: Any, b: Any, escape: Optional[str] = None) -> Any:
  1470. ...
  1471. else:
  1472. notilike_op = not_ilike_op
  1473. @comparison_op
  1474. @_operator_fn
  1475. def between_op(a: Any, b: Any, c: Any, symmetric: bool = False) -> Any:
  1476. return a.between(b, c, symmetric=symmetric)
  1477. @comparison_op
  1478. @_operator_fn
  1479. def not_between_op(a: Any, b: Any, c: Any, symmetric: bool = False) -> Any:
  1480. return ~a.between(b, c, symmetric=symmetric)
  1481. # 1.4 deprecated; see #5435
  1482. if TYPE_CHECKING:
  1483. @_operator_fn
  1484. def notbetween_op(a: Any, b: Any, c: Any, symmetric: bool = False) -> Any:
  1485. ...
  1486. else:
  1487. notbetween_op = not_between_op
  1488. @comparison_op
  1489. @_operator_fn
  1490. def in_op(a: Any, b: Any) -> Any:
  1491. return a.in_(b)
  1492. @comparison_op
  1493. @_operator_fn
  1494. def not_in_op(a: Any, b: Any) -> Any:
  1495. return a.not_in(b)
  1496. # 1.4 deprecated; see #5429
  1497. if TYPE_CHECKING:
  1498. @_operator_fn
  1499. def notin_op(a: Any, b: Any) -> Any:
  1500. ...
  1501. else:
  1502. notin_op = not_in_op
  1503. @_operator_fn
  1504. def distinct_op(a: Any) -> Any:
  1505. return a.distinct()
  1506. @_operator_fn
  1507. def any_op(a: Any) -> Any:
  1508. return a.any_()
  1509. @_operator_fn
  1510. def all_op(a: Any) -> Any:
  1511. return a.all_()
  1512. def _escaped_like_impl(
  1513. fn: Callable[..., Any], other: Any, escape: Optional[str], autoescape: bool
  1514. ) -> Any:
  1515. if autoescape:
  1516. if autoescape is not True:
  1517. util.warn(
  1518. "The autoescape parameter is now a simple boolean True/False"
  1519. )
  1520. if escape is None:
  1521. escape = "/"
  1522. if not isinstance(other, str):
  1523. raise TypeError("String value expected when autoescape=True")
  1524. if escape not in ("%", "_"):
  1525. other = other.replace(escape, escape + escape)
  1526. other = other.replace("%", escape + "%").replace("_", escape + "_")
  1527. return fn(other, escape=escape)
  1528. @comparison_op
  1529. @_operator_fn
  1530. def startswith_op(
  1531. a: Any, b: Any, escape: Optional[str] = None, autoescape: bool = False
  1532. ) -> Any:
  1533. return _escaped_like_impl(a.startswith, b, escape, autoescape)
  1534. @comparison_op
  1535. @_operator_fn
  1536. def not_startswith_op(
  1537. a: Any, b: Any, escape: Optional[str] = None, autoescape: bool = False
  1538. ) -> Any:
  1539. return ~_escaped_like_impl(a.startswith, b, escape, autoescape)
  1540. # 1.4 deprecated; see #5435
  1541. if TYPE_CHECKING:
  1542. @_operator_fn
  1543. def notstartswith_op(
  1544. a: Any, b: Any, escape: Optional[str] = None, autoescape: bool = False
  1545. ) -> Any:
  1546. ...
  1547. else:
  1548. notstartswith_op = not_startswith_op
  1549. @comparison_op
  1550. @_operator_fn
  1551. def istartswith_op(
  1552. a: Any, b: Any, escape: Optional[str] = None, autoescape: bool = False
  1553. ) -> Any:
  1554. return _escaped_like_impl(a.istartswith, b, escape, autoescape)
  1555. @comparison_op
  1556. @_operator_fn
  1557. def not_istartswith_op(
  1558. a: Any, b: Any, escape: Optional[str] = None, autoescape: bool = False
  1559. ) -> Any:
  1560. return ~_escaped_like_impl(a.istartswith, b, escape, autoescape)
  1561. @comparison_op
  1562. @_operator_fn
  1563. def endswith_op(
  1564. a: Any, b: Any, escape: Optional[str] = None, autoescape: bool = False
  1565. ) -> Any:
  1566. return _escaped_like_impl(a.endswith, b, escape, autoescape)
  1567. @comparison_op
  1568. @_operator_fn
  1569. def not_endswith_op(
  1570. a: Any, b: Any, escape: Optional[str] = None, autoescape: bool = False
  1571. ) -> Any:
  1572. return ~_escaped_like_impl(a.endswith, b, escape, autoescape)
  1573. # 1.4 deprecated; see #5435
  1574. if TYPE_CHECKING:
  1575. @_operator_fn
  1576. def notendswith_op(
  1577. a: Any, b: Any, escape: Optional[str] = None, autoescape: bool = False
  1578. ) -> Any:
  1579. ...
  1580. else:
  1581. notendswith_op = not_endswith_op
  1582. @comparison_op
  1583. @_operator_fn
  1584. def iendswith_op(
  1585. a: Any, b: Any, escape: Optional[str] = None, autoescape: bool = False
  1586. ) -> Any:
  1587. return _escaped_like_impl(a.iendswith, b, escape, autoescape)
  1588. @comparison_op
  1589. @_operator_fn
  1590. def not_iendswith_op(
  1591. a: Any, b: Any, escape: Optional[str] = None, autoescape: bool = False
  1592. ) -> Any:
  1593. return ~_escaped_like_impl(a.iendswith, b, escape, autoescape)
  1594. @comparison_op
  1595. @_operator_fn
  1596. def contains_op(
  1597. a: Any, b: Any, escape: Optional[str] = None, autoescape: bool = False
  1598. ) -> Any:
  1599. return _escaped_like_impl(a.contains, b, escape, autoescape)
  1600. @comparison_op
  1601. @_operator_fn
  1602. def not_contains_op(
  1603. a: Any, b: Any, escape: Optional[str] = None, autoescape: bool = False
  1604. ) -> Any:
  1605. return ~_escaped_like_impl(a.contains, b, escape, autoescape)
  1606. # 1.4 deprecated; see #5435
  1607. if TYPE_CHECKING:
  1608. @_operator_fn
  1609. def notcontains_op(
  1610. a: Any, b: Any, escape: Optional[str] = None, autoescape: bool = False
  1611. ) -> Any:
  1612. ...
  1613. else:
  1614. notcontains_op = not_contains_op
  1615. @comparison_op
  1616. @_operator_fn
  1617. def icontains_op(
  1618. a: Any, b: Any, escape: Optional[str] = None, autoescape: bool = False
  1619. ) -> Any:
  1620. return _escaped_like_impl(a.icontains, b, escape, autoescape)
  1621. @comparison_op
  1622. @_operator_fn
  1623. def not_icontains_op(
  1624. a: Any, b: Any, escape: Optional[str] = None, autoescape: bool = False
  1625. ) -> Any:
  1626. return ~_escaped_like_impl(a.icontains, b, escape, autoescape)
  1627. @comparison_op
  1628. @_operator_fn
  1629. def match_op(a: Any, b: Any, **kw: Any) -> Any:
  1630. return a.match(b, **kw)
  1631. @comparison_op
  1632. @_operator_fn
  1633. def regexp_match_op(a: Any, b: Any, flags: Optional[str] = None) -> Any:
  1634. return a.regexp_match(b, flags=flags)
  1635. @comparison_op
  1636. @_operator_fn
  1637. def not_regexp_match_op(a: Any, b: Any, flags: Optional[str] = None) -> Any:
  1638. return ~a.regexp_match(b, flags=flags)
  1639. @_operator_fn
  1640. def regexp_replace_op(
  1641. a: Any, b: Any, replacement: Any, flags: Optional[str] = None
  1642. ) -> Any:
  1643. return a.regexp_replace(b, replacement=replacement, flags=flags)
  1644. @comparison_op
  1645. @_operator_fn
  1646. def not_match_op(a: Any, b: Any, **kw: Any) -> Any:
  1647. return ~a.match(b, **kw)
  1648. # 1.4 deprecated; see #5429
  1649. if TYPE_CHECKING:
  1650. @_operator_fn
  1651. def notmatch_op(a: Any, b: Any, **kw: Any) -> Any:
  1652. ...
  1653. else:
  1654. notmatch_op = not_match_op
  1655. @_operator_fn
  1656. def comma_op(a: Any, b: Any) -> Any:
  1657. raise NotImplementedError()
  1658. @_operator_fn
  1659. def filter_op(a: Any, b: Any) -> Any:
  1660. raise NotImplementedError()
  1661. @_operator_fn
  1662. def concat_op(a: Any, b: Any) -> Any:
  1663. try:
  1664. concat = a.concat
  1665. except AttributeError:
  1666. return b._rconcat(a)
  1667. else:
  1668. return concat(b)
  1669. @_operator_fn
  1670. def desc_op(a: Any) -> Any:
  1671. return a.desc()
  1672. @_operator_fn
  1673. def asc_op(a: Any) -> Any:
  1674. return a.asc()
  1675. @_operator_fn
  1676. def nulls_first_op(a: Any) -> Any:
  1677. return a.nulls_first()
  1678. # 1.4 deprecated; see #5435
  1679. if TYPE_CHECKING:
  1680. @_operator_fn
  1681. def nullsfirst_op(a: Any) -> Any:
  1682. ...
  1683. else:
  1684. nullsfirst_op = nulls_first_op
  1685. @_operator_fn
  1686. def nulls_last_op(a: Any) -> Any:
  1687. return a.nulls_last()
  1688. # 1.4 deprecated; see #5435
  1689. if TYPE_CHECKING:
  1690. @_operator_fn
  1691. def nullslast_op(a: Any) -> Any:
  1692. ...
  1693. else:
  1694. nullslast_op = nulls_last_op
  1695. @_operator_fn
  1696. def json_getitem_op(a: Any, b: Any) -> Any:
  1697. raise NotImplementedError()
  1698. @_operator_fn
  1699. def json_path_getitem_op(a: Any, b: Any) -> Any:
  1700. raise NotImplementedError()
  1701. @_operator_fn
  1702. def bitwise_xor_op(a: Any, b: Any) -> Any:
  1703. return a.bitwise_xor(b)
  1704. @_operator_fn
  1705. def bitwise_or_op(a: Any, b: Any) -> Any:
  1706. return a.bitwise_or(b)
  1707. @_operator_fn
  1708. def bitwise_and_op(a: Any, b: Any) -> Any:
  1709. return a.bitwise_and(b)
  1710. @_operator_fn
  1711. def bitwise_not_op(a: Any) -> Any:
  1712. return a.bitwise_not()
  1713. @_operator_fn
  1714. def bitwise_lshift_op(a: Any, b: Any) -> Any:
  1715. return a.bitwise_lshift(b)
  1716. @_operator_fn
  1717. def bitwise_rshift_op(a: Any, b: Any) -> Any:
  1718. return a.bitwise_rshift(b)
  1719. def is_comparison(op: OperatorType) -> bool:
  1720. return op in _comparison or isinstance(op, custom_op) and op.is_comparison
  1721. def is_commutative(op: OperatorType) -> bool:
  1722. return op in _commutative
  1723. def is_ordering_modifier(op: OperatorType) -> bool:
  1724. return op in (asc_op, desc_op, nulls_first_op, nulls_last_op)
  1725. def is_natural_self_precedent(op: OperatorType) -> bool:
  1726. return (
  1727. op in _natural_self_precedent
  1728. or isinstance(op, custom_op)
  1729. and op.natural_self_precedent
  1730. )
  1731. _booleans = (inv, is_true, is_false, and_, or_)
  1732. def is_boolean(op: OperatorType) -> bool:
  1733. return is_comparison(op) or op in _booleans
  1734. _mirror = {gt: lt, ge: le, lt: gt, le: ge}
  1735. def mirror(op: OperatorType) -> OperatorType:
  1736. """rotate a comparison operator 180 degrees.
  1737. Note this is not the same as negation.
  1738. """
  1739. return _mirror.get(op, op)
  1740. _associative = _commutative.union([concat_op, and_, or_]).difference([eq, ne])
  1741. def is_associative(op: OperatorType) -> bool:
  1742. return op in _associative
  1743. _natural_self_precedent = _associative.union(
  1744. [getitem, json_getitem_op, json_path_getitem_op]
  1745. )
  1746. """Operators where if we have (a op b) op c, we don't want to
  1747. parenthesize (a op b).
  1748. """
  1749. @_operator_fn
  1750. def _asbool(a: Any) -> Any:
  1751. raise NotImplementedError()
  1752. class _OpLimit(IntEnum):
  1753. _smallest = -100
  1754. _largest = 100
  1755. _PRECEDENCE: Dict[OperatorType, int] = {
  1756. from_: 15,
  1757. function_as_comparison_op: 15,
  1758. any_op: 15,
  1759. all_op: 15,
  1760. getitem: 15,
  1761. json_getitem_op: 15,
  1762. json_path_getitem_op: 15,
  1763. mul: 8,
  1764. truediv: 8,
  1765. floordiv: 8,
  1766. mod: 8,
  1767. neg: 8,
  1768. bitwise_not_op: 8,
  1769. add: 7,
  1770. sub: 7,
  1771. bitwise_xor_op: 7,
  1772. bitwise_or_op: 7,
  1773. bitwise_and_op: 7,
  1774. bitwise_lshift_op: 7,
  1775. bitwise_rshift_op: 7,
  1776. filter_op: 6,
  1777. concat_op: 5,
  1778. match_op: 5,
  1779. not_match_op: 5,
  1780. regexp_match_op: 5,
  1781. not_regexp_match_op: 5,
  1782. regexp_replace_op: 5,
  1783. ilike_op: 5,
  1784. not_ilike_op: 5,
  1785. like_op: 5,
  1786. not_like_op: 5,
  1787. in_op: 5,
  1788. not_in_op: 5,
  1789. is_: 5,
  1790. is_not: 5,
  1791. eq: 5,
  1792. ne: 5,
  1793. is_distinct_from: 5,
  1794. is_not_distinct_from: 5,
  1795. gt: 5,
  1796. lt: 5,
  1797. ge: 5,
  1798. le: 5,
  1799. between_op: 5,
  1800. not_between_op: 5,
  1801. distinct_op: 5,
  1802. inv: 5,
  1803. is_true: 5,
  1804. is_false: 5,
  1805. and_: 3,
  1806. or_: 2,
  1807. comma_op: -1,
  1808. desc_op: 3,
  1809. asc_op: 3,
  1810. collate: 4,
  1811. as_: -1,
  1812. exists: 0,
  1813. _asbool: -10,
  1814. }
  1815. def is_precedent(
  1816. operator: OperatorType, against: Optional[OperatorType]
  1817. ) -> bool:
  1818. if operator is against and is_natural_self_precedent(operator):
  1819. return False
  1820. elif against is None:
  1821. return True
  1822. else:
  1823. return bool(
  1824. _PRECEDENCE.get(
  1825. operator, getattr(operator, "precedence", _OpLimit._smallest)
  1826. )
  1827. <= _PRECEDENCE.get(
  1828. against, getattr(against, "precedence", _OpLimit._largest)
  1829. )
  1830. )