operators.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726
  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 operator import add
  11. from operator import and_
  12. from operator import contains
  13. from operator import eq
  14. from operator import ge
  15. from operator import getitem
  16. from operator import gt
  17. from operator import inv
  18. from operator import le
  19. from operator import lshift
  20. from operator import lt
  21. from operator import mod
  22. from operator import mul
  23. from operator import ne
  24. from operator import neg
  25. from operator import or_
  26. from operator import rshift
  27. from operator import sub
  28. from operator import truediv
  29. from .. import util
  30. if util.py2k:
  31. from operator import div
  32. else:
  33. div = truediv
  34. class Operators(object):
  35. """Base of comparison and logical operators.
  36. Implements base methods
  37. :meth:`~sqlalchemy.sql.operators.Operators.operate` and
  38. :meth:`~sqlalchemy.sql.operators.Operators.reverse_operate`, as well as
  39. :meth:`~sqlalchemy.sql.operators.Operators.__and__`,
  40. :meth:`~sqlalchemy.sql.operators.Operators.__or__`,
  41. :meth:`~sqlalchemy.sql.operators.Operators.__invert__`.
  42. Usually is used via its most common subclass
  43. :class:`.ColumnOperators`.
  44. """
  45. __slots__ = ()
  46. def __and__(self, other):
  47. """Implement the ``&`` operator.
  48. When used with SQL expressions, results in an
  49. AND operation, equivalent to
  50. :func:`_expression.and_`, that is::
  51. a & b
  52. is equivalent to::
  53. from sqlalchemy import and_
  54. and_(a, b)
  55. Care should be taken when using ``&`` regarding
  56. operator precedence; the ``&`` operator has the highest precedence.
  57. The operands should be enclosed in parenthesis if they contain
  58. further sub expressions::
  59. (a == 2) & (b == 4)
  60. """
  61. return self.operate(and_, other)
  62. def __or__(self, other):
  63. """Implement the ``|`` operator.
  64. When used with SQL expressions, results in an
  65. OR operation, equivalent to
  66. :func:`_expression.or_`, that is::
  67. a | b
  68. is equivalent to::
  69. from sqlalchemy import or_
  70. or_(a, b)
  71. Care should be taken when using ``|`` regarding
  72. operator precedence; the ``|`` operator has the highest precedence.
  73. The operands should be enclosed in parenthesis if they contain
  74. further sub expressions::
  75. (a == 2) | (b == 4)
  76. """
  77. return self.operate(or_, other)
  78. def __invert__(self):
  79. """Implement the ``~`` operator.
  80. When used with SQL expressions, results in a
  81. NOT operation, equivalent to
  82. :func:`_expression.not_`, that is::
  83. ~a
  84. is equivalent to::
  85. from sqlalchemy import not_
  86. not_(a)
  87. """
  88. return self.operate(inv)
  89. def op(
  90. self, opstring, precedence=0, is_comparison=False, return_type=None
  91. ):
  92. """Produce a generic operator function.
  93. e.g.::
  94. somecolumn.op("*")(5)
  95. produces::
  96. somecolumn * 5
  97. This function can also be used to make bitwise operators explicit. For
  98. example::
  99. somecolumn.op('&')(0xff)
  100. is a bitwise AND of the value in ``somecolumn``.
  101. :param operator: a string which will be output as the infix operator
  102. between this element and the expression passed to the
  103. generated function.
  104. :param precedence: precedence which the database is expected to apply
  105. to the operator in SQL expressions. This integer value acts as a hint
  106. for the SQL compiler to know when explicit parenthesis should be
  107. rendered around a particular operation. A lower number will cause the
  108. expression to be parenthesized when applied against another operator
  109. with higher precedence. The default value of ``0`` is lower than all
  110. operators except for the comma (``,``) and ``AS`` operators. A value
  111. of 100 will be higher or equal to all operators, and -100 will be
  112. lower than or equal to all operators.
  113. .. seealso::
  114. :ref:`faq_sql_expression_op_parenthesis` - detailed description
  115. of how the SQLAlchemy SQL compiler renders parenthesis
  116. :param is_comparison: legacy; if True, the operator will be considered
  117. as a "comparison" operator, that is which evaluates to a boolean
  118. true/false value, like ``==``, ``>``, etc. This flag is provided
  119. so that ORM relationships can establish that the operator is a
  120. comparison operator when used in a custom join condition.
  121. Using the ``is_comparison`` parameter is superseded by using the
  122. :meth:`.Operators.bool_op` method instead; this more succinct
  123. operator sets this parameter automatically. In SQLAlchemy 2.0 it
  124. will also provide for improved typing support.
  125. :param return_type: a :class:`.TypeEngine` class or object that will
  126. force the return type of an expression produced by this operator
  127. to be of that type. By default, operators that specify
  128. :paramref:`.Operators.op.is_comparison` will resolve to
  129. :class:`.Boolean`, and those that do not will be of the same
  130. type as the left-hand operand.
  131. .. seealso::
  132. :meth:`.Operators.bool_op`
  133. :ref:`types_operators`
  134. :ref:`relationship_custom_operator`
  135. """
  136. operator = custom_op(opstring, precedence, is_comparison, return_type)
  137. def against(other):
  138. return operator(self, other)
  139. return against
  140. def bool_op(self, opstring, precedence=0):
  141. """Return a custom boolean operator.
  142. This method is shorthand for calling
  143. :meth:`.Operators.op` and passing the
  144. :paramref:`.Operators.op.is_comparison`
  145. flag with True. A key advantage to using :meth:`.Operators.bool_op`
  146. is that when using column constructs, the "boolean" nature of the
  147. returned expression will be present for :pep:`484` purposes.
  148. .. seealso::
  149. :meth:`.Operators.op`
  150. """
  151. return self.op(opstring, precedence=precedence, is_comparison=True)
  152. def operate(self, op, *other, **kwargs):
  153. r"""Operate on an argument.
  154. This is the lowest level of operation, raises
  155. :class:`NotImplementedError` by default.
  156. Overriding this on a subclass can allow common
  157. behavior to be applied to all operations.
  158. For example, overriding :class:`.ColumnOperators`
  159. to apply ``func.lower()`` to the left and right
  160. side::
  161. class MyComparator(ColumnOperators):
  162. def operate(self, op, other, **kwargs):
  163. return op(func.lower(self), func.lower(other), **kwargs)
  164. :param op: Operator callable.
  165. :param \*other: the 'other' side of the operation. Will
  166. be a single scalar for most operations.
  167. :param \**kwargs: modifiers. These may be passed by special
  168. operators such as :meth:`ColumnOperators.contains`.
  169. """
  170. raise NotImplementedError(str(op))
  171. def reverse_operate(self, op, other, **kwargs):
  172. """Reverse operate on an argument.
  173. Usage is the same as :meth:`operate`.
  174. """
  175. raise NotImplementedError(str(op))
  176. class custom_op(object):
  177. """Represent a 'custom' operator.
  178. :class:`.custom_op` is normally instantiated when the
  179. :meth:`.Operators.op` or :meth:`.Operators.bool_op` methods
  180. are used to create a custom operator callable. The class can also be
  181. used directly when programmatically constructing expressions. E.g.
  182. to represent the "factorial" operation::
  183. from sqlalchemy.sql import UnaryExpression
  184. from sqlalchemy.sql import operators
  185. from sqlalchemy import Numeric
  186. unary = UnaryExpression(table.c.somecolumn,
  187. modifier=operators.custom_op("!"),
  188. type_=Numeric)
  189. .. seealso::
  190. :meth:`.Operators.op`
  191. :meth:`.Operators.bool_op`
  192. """
  193. __name__ = "custom_op"
  194. def __init__(
  195. self,
  196. opstring,
  197. precedence=0,
  198. is_comparison=False,
  199. return_type=None,
  200. natural_self_precedent=False,
  201. eager_grouping=False,
  202. ):
  203. self.opstring = opstring
  204. self.precedence = precedence
  205. self.is_comparison = is_comparison
  206. self.natural_self_precedent = natural_self_precedent
  207. self.eager_grouping = eager_grouping
  208. self.return_type = (
  209. return_type._to_instance(return_type) if return_type else None
  210. )
  211. def __eq__(self, other):
  212. return (
  213. isinstance(other, custom_op)
  214. and other._hash_key() == self._hash_key()
  215. )
  216. def __hash__(self):
  217. return hash(self._hash_key())
  218. def _hash_key(self):
  219. return (
  220. self.__class__,
  221. self.opstring,
  222. self.precedence,
  223. self.is_comparison,
  224. self.natural_self_precedent,
  225. self.eager_grouping,
  226. self.return_type._static_cache_key if self.return_type else None,
  227. )
  228. def __call__(self, left, right, **kw):
  229. return left.operate(self, right, **kw)
  230. class ColumnOperators(Operators):
  231. """Defines boolean, comparison, and other operators for
  232. :class:`_expression.ColumnElement` expressions.
  233. By default, all methods call down to
  234. :meth:`.operate` or :meth:`.reverse_operate`,
  235. passing in the appropriate operator function from the
  236. Python builtin ``operator`` module or
  237. a SQLAlchemy-specific operator function from
  238. :mod:`sqlalchemy.expression.operators`. For example
  239. the ``__eq__`` function::
  240. def __eq__(self, other):
  241. return self.operate(operators.eq, other)
  242. Where ``operators.eq`` is essentially::
  243. def eq(a, b):
  244. return a == b
  245. The core column expression unit :class:`_expression.ColumnElement`
  246. overrides :meth:`.Operators.operate` and others
  247. to return further :class:`_expression.ColumnElement` constructs,
  248. so that the ``==`` operation above is replaced by a clause
  249. construct.
  250. .. seealso::
  251. :ref:`types_operators`
  252. :attr:`.TypeEngine.comparator_factory`
  253. :class:`.ColumnOperators`
  254. :class:`.PropComparator`
  255. """
  256. __slots__ = ()
  257. timetuple = None
  258. """Hack, allows datetime objects to be compared on the LHS."""
  259. def __lt__(self, other):
  260. """Implement the ``<`` operator.
  261. In a column context, produces the clause ``a < b``.
  262. """
  263. return self.operate(lt, other)
  264. def __le__(self, other):
  265. """Implement the ``<=`` operator.
  266. In a column context, produces the clause ``a <= b``.
  267. """
  268. return self.operate(le, other)
  269. __hash__ = Operators.__hash__
  270. def __eq__(self, other):
  271. """Implement the ``==`` operator.
  272. In a column context, produces the clause ``a = b``.
  273. If the target is ``None``, produces ``a IS NULL``.
  274. """
  275. return self.operate(eq, other)
  276. def __ne__(self, other):
  277. """Implement the ``!=`` operator.
  278. In a column context, produces the clause ``a != b``.
  279. If the target is ``None``, produces ``a IS NOT NULL``.
  280. """
  281. return self.operate(ne, other)
  282. def is_distinct_from(self, other):
  283. """Implement the ``IS DISTINCT FROM`` operator.
  284. Renders "a IS DISTINCT FROM b" on most platforms;
  285. on some such as SQLite may render "a IS NOT b".
  286. .. versionadded:: 1.1
  287. """
  288. return self.operate(is_distinct_from, other)
  289. def is_not_distinct_from(self, other):
  290. """Implement the ``IS NOT DISTINCT FROM`` operator.
  291. Renders "a IS NOT DISTINCT FROM b" on most platforms;
  292. on some such as SQLite may render "a IS b".
  293. .. versionchanged:: 1.4 The ``is_not_distinct_from()`` operator is
  294. renamed from ``isnot_distinct_from()`` in previous releases.
  295. The previous name remains available for backwards compatibility.
  296. .. versionadded:: 1.1
  297. """
  298. return self.operate(is_not_distinct_from, other)
  299. # deprecated 1.4; see #5435
  300. isnot_distinct_from = is_not_distinct_from
  301. def __gt__(self, other):
  302. """Implement the ``>`` operator.
  303. In a column context, produces the clause ``a > b``.
  304. """
  305. return self.operate(gt, other)
  306. def __ge__(self, other):
  307. """Implement the ``>=`` operator.
  308. In a column context, produces the clause ``a >= b``.
  309. """
  310. return self.operate(ge, other)
  311. def __neg__(self):
  312. """Implement the ``-`` operator.
  313. In a column context, produces the clause ``-a``.
  314. """
  315. return self.operate(neg)
  316. def __contains__(self, other):
  317. return self.operate(contains, other)
  318. def __getitem__(self, index):
  319. """Implement the [] operator.
  320. This can be used by some database-specific types
  321. such as PostgreSQL ARRAY and HSTORE.
  322. """
  323. return self.operate(getitem, index)
  324. def __lshift__(self, other):
  325. """implement the << operator.
  326. Not used by SQLAlchemy core, this is provided
  327. for custom operator systems which want to use
  328. << as an extension point.
  329. """
  330. return self.operate(lshift, other)
  331. def __rshift__(self, other):
  332. """implement the >> operator.
  333. Not used by SQLAlchemy core, this is provided
  334. for custom operator systems which want to use
  335. >> as an extension point.
  336. """
  337. return self.operate(rshift, other)
  338. def concat(self, other):
  339. """Implement the 'concat' operator.
  340. In a column context, produces the clause ``a || b``,
  341. or uses the ``concat()`` operator on MySQL.
  342. """
  343. return self.operate(concat_op, other)
  344. def _rconcat(self, other):
  345. """Implement an 'rconcat' operator.
  346. this is for internal use at the moment
  347. .. versionadded:: 1.4.40
  348. """
  349. return self.reverse_operate(concat_op, other)
  350. def like(self, other, escape=None):
  351. r"""Implement the ``like`` operator.
  352. In a column context, produces the expression::
  353. a LIKE other
  354. E.g.::
  355. stmt = select(sometable).\
  356. where(sometable.c.column.like("%foobar%"))
  357. :param other: expression to be compared
  358. :param escape: optional escape character, renders the ``ESCAPE``
  359. keyword, e.g.::
  360. somecolumn.like("foo/%bar", escape="/")
  361. .. seealso::
  362. :meth:`.ColumnOperators.ilike`
  363. """
  364. return self.operate(like_op, other, escape=escape)
  365. def ilike(self, other, escape=None):
  366. r"""Implement the ``ilike`` operator, e.g. case insensitive LIKE.
  367. In a column context, produces an expression either of the form::
  368. lower(a) LIKE lower(other)
  369. Or on backends that support the ILIKE operator::
  370. a ILIKE other
  371. E.g.::
  372. stmt = select(sometable).\
  373. where(sometable.c.column.ilike("%foobar%"))
  374. :param other: expression to be compared
  375. :param escape: optional escape character, renders the ``ESCAPE``
  376. keyword, e.g.::
  377. somecolumn.ilike("foo/%bar", escape="/")
  378. .. seealso::
  379. :meth:`.ColumnOperators.like`
  380. """
  381. return self.operate(ilike_op, other, escape=escape)
  382. def in_(self, other):
  383. """Implement the ``in`` operator.
  384. In a column context, produces the clause ``column IN <other>``.
  385. The given parameter ``other`` may be:
  386. * A list of literal values, e.g.::
  387. stmt.where(column.in_([1, 2, 3]))
  388. In this calling form, the list of items is converted to a set of
  389. bound parameters the same length as the list given::
  390. WHERE COL IN (?, ?, ?)
  391. * A list of tuples may be provided if the comparison is against a
  392. :func:`.tuple_` containing multiple expressions::
  393. from sqlalchemy import tuple_
  394. stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
  395. * An empty list, e.g.::
  396. stmt.where(column.in_([]))
  397. In this calling form, the expression renders an "empty set"
  398. expression. These expressions are tailored to individual backends
  399. and are generally trying to get an empty SELECT statement as a
  400. subquery. Such as on SQLite, the expression is::
  401. WHERE col IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)
  402. .. versionchanged:: 1.4 empty IN expressions now use an
  403. execution-time generated SELECT subquery in all cases.
  404. * A bound parameter, e.g. :func:`.bindparam`, may be used if it
  405. includes the :paramref:`.bindparam.expanding` flag::
  406. stmt.where(column.in_(bindparam('value', expanding=True)))
  407. In this calling form, the expression renders a special non-SQL
  408. placeholder expression that looks like::
  409. WHERE COL IN ([EXPANDING_value])
  410. This placeholder expression is intercepted at statement execution
  411. time to be converted into the variable number of bound parameter
  412. form illustrated earlier. If the statement were executed as::
  413. connection.execute(stmt, {"value": [1, 2, 3]})
  414. The database would be passed a bound parameter for each value::
  415. WHERE COL IN (?, ?, ?)
  416. .. versionadded:: 1.2 added "expanding" bound parameters
  417. If an empty list is passed, a special "empty list" expression,
  418. which is specific to the database in use, is rendered. On
  419. SQLite this would be::
  420. WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)
  421. .. versionadded:: 1.3 "expanding" bound parameters now support
  422. empty lists
  423. * a :func:`_expression.select` construct, which is usually a
  424. correlated scalar select::
  425. stmt.where(
  426. column.in_(
  427. select(othertable.c.y).
  428. where(table.c.x == othertable.c.x)
  429. )
  430. )
  431. In this calling form, :meth:`.ColumnOperators.in_` renders as given::
  432. WHERE COL IN (SELECT othertable.y
  433. FROM othertable WHERE othertable.x = table.x)
  434. :param other: a list of literals, a :func:`_expression.select`
  435. construct, or a :func:`.bindparam` construct that includes the
  436. :paramref:`.bindparam.expanding` flag set to True.
  437. """
  438. return self.operate(in_op, other)
  439. def not_in(self, other):
  440. """implement the ``NOT IN`` operator.
  441. This is equivalent to using negation with
  442. :meth:`.ColumnOperators.in_`, i.e. ``~x.in_(y)``.
  443. In the case that ``other`` is an empty sequence, the compiler
  444. produces an "empty not in" expression. This defaults to the
  445. expression "1 = 1" to produce true in all cases. The
  446. :paramref:`_sa.create_engine.empty_in_strategy` may be used to
  447. alter this behavior.
  448. .. versionchanged:: 1.4 The ``not_in()`` operator is renamed from
  449. ``notin_()`` in previous releases. The previous name remains
  450. available for backwards compatibility.
  451. .. versionchanged:: 1.2 The :meth:`.ColumnOperators.in_` and
  452. :meth:`.ColumnOperators.not_in` operators
  453. now produce a "static" expression for an empty IN sequence
  454. by default.
  455. .. seealso::
  456. :meth:`.ColumnOperators.in_`
  457. """
  458. return self.operate(not_in_op, other)
  459. # deprecated 1.4; see #5429
  460. notin_ = not_in
  461. def not_like(self, other, escape=None):
  462. """implement the ``NOT LIKE`` operator.
  463. This is equivalent to using negation with
  464. :meth:`.ColumnOperators.like`, i.e. ``~x.like(y)``.
  465. .. versionchanged:: 1.4 The ``not_like()`` operator is renamed from
  466. ``notlike()`` in previous releases. The previous name remains
  467. available for backwards compatibility.
  468. .. seealso::
  469. :meth:`.ColumnOperators.like`
  470. """
  471. return self.operate(notlike_op, other, escape=escape)
  472. # deprecated 1.4; see #5435
  473. notlike = not_like
  474. def not_ilike(self, other, escape=None):
  475. """implement the ``NOT ILIKE`` operator.
  476. This is equivalent to using negation with
  477. :meth:`.ColumnOperators.ilike`, i.e. ``~x.ilike(y)``.
  478. .. versionchanged:: 1.4 The ``not_ilike()`` operator is renamed from
  479. ``notilike()`` in previous releases. The previous name remains
  480. available for backwards compatibility.
  481. .. seealso::
  482. :meth:`.ColumnOperators.ilike`
  483. """
  484. return self.operate(notilike_op, other, escape=escape)
  485. # deprecated 1.4; see #5435
  486. notilike = not_ilike
  487. def is_(self, other):
  488. """Implement the ``IS`` operator.
  489. Normally, ``IS`` is generated automatically when comparing to a
  490. value of ``None``, which resolves to ``NULL``. However, explicit
  491. usage of ``IS`` may be desirable if comparing to boolean values
  492. on certain platforms.
  493. .. seealso:: :meth:`.ColumnOperators.is_not`
  494. """
  495. return self.operate(is_, other)
  496. def is_not(self, other):
  497. """Implement the ``IS NOT`` operator.
  498. Normally, ``IS NOT`` is generated automatically when comparing to a
  499. value of ``None``, which resolves to ``NULL``. However, explicit
  500. usage of ``IS NOT`` may be desirable if comparing to boolean values
  501. on certain platforms.
  502. .. versionchanged:: 1.4 The ``is_not()`` operator is renamed from
  503. ``isnot()`` in previous releases. The previous name remains
  504. available for backwards compatibility.
  505. .. seealso:: :meth:`.ColumnOperators.is_`
  506. """
  507. return self.operate(is_not, other)
  508. # deprecated 1.4; see #5429
  509. isnot = is_not
  510. def startswith(self, other, **kwargs):
  511. r"""Implement the ``startswith`` operator.
  512. Produces a LIKE expression that tests against a match for the start
  513. of a string value::
  514. column LIKE <other> || '%'
  515. E.g.::
  516. stmt = select(sometable).\
  517. where(sometable.c.column.startswith("foobar"))
  518. Since the operator uses ``LIKE``, wildcard characters
  519. ``"%"`` and ``"_"`` that are present inside the <other> expression
  520. will behave like wildcards as well. For literal string
  521. values, the :paramref:`.ColumnOperators.startswith.autoescape` flag
  522. may be set to ``True`` to apply escaping to occurrences of these
  523. characters within the string value so that they match as themselves
  524. and not as wildcard characters. Alternatively, the
  525. :paramref:`.ColumnOperators.startswith.escape` parameter will establish
  526. a given character as an escape character which can be of use when
  527. the target expression is not a literal string.
  528. :param other: expression to be compared. This is usually a plain
  529. string value, but can also be an arbitrary SQL expression. LIKE
  530. wildcard characters ``%`` and ``_`` are not escaped by default unless
  531. the :paramref:`.ColumnOperators.startswith.autoescape` flag is
  532. set to True.
  533. :param autoescape: boolean; when True, establishes an escape character
  534. within the LIKE expression, then applies it to all occurrences of
  535. ``"%"``, ``"_"`` and the escape character itself within the
  536. comparison value, which is assumed to be a literal string and not a
  537. SQL expression.
  538. An expression such as::
  539. somecolumn.startswith("foo%bar", autoescape=True)
  540. Will render as::
  541. somecolumn LIKE :param || '%' ESCAPE '/'
  542. With the value of ``:param`` as ``"foo/%bar"``.
  543. :param escape: a character which when given will render with the
  544. ``ESCAPE`` keyword to establish that character as the escape
  545. character. This character can then be placed preceding occurrences
  546. of ``%`` and ``_`` to allow them to act as themselves and not
  547. wildcard characters.
  548. An expression such as::
  549. somecolumn.startswith("foo/%bar", escape="^")
  550. Will render as::
  551. somecolumn LIKE :param || '%' ESCAPE '^'
  552. The parameter may also be combined with
  553. :paramref:`.ColumnOperators.startswith.autoescape`::
  554. somecolumn.startswith("foo%bar^bat", escape="^", autoescape=True)
  555. Where above, the given literal parameter will be converted to
  556. ``"foo^%bar^^bat"`` before being passed to the database.
  557. .. seealso::
  558. :meth:`.ColumnOperators.endswith`
  559. :meth:`.ColumnOperators.contains`
  560. :meth:`.ColumnOperators.like`
  561. """
  562. return self.operate(startswith_op, other, **kwargs)
  563. def endswith(self, other, **kwargs):
  564. r"""Implement the 'endswith' operator.
  565. Produces a LIKE expression that tests against a match for the end
  566. of a string value::
  567. column LIKE '%' || <other>
  568. E.g.::
  569. stmt = select(sometable).\
  570. where(sometable.c.column.endswith("foobar"))
  571. Since the operator uses ``LIKE``, wildcard characters
  572. ``"%"`` and ``"_"`` that are present inside the <other> expression
  573. will behave like wildcards as well. For literal string
  574. values, the :paramref:`.ColumnOperators.endswith.autoescape` flag
  575. may be set to ``True`` to apply escaping to occurrences of these
  576. characters within the string value so that they match as themselves
  577. and not as wildcard characters. Alternatively, the
  578. :paramref:`.ColumnOperators.endswith.escape` parameter will establish
  579. a given character as an escape character which can be of use when
  580. the target expression is not a literal string.
  581. :param other: expression to be compared. This is usually a plain
  582. string value, but can also be an arbitrary SQL expression. LIKE
  583. wildcard characters ``%`` and ``_`` are not escaped by default unless
  584. the :paramref:`.ColumnOperators.endswith.autoescape` flag is
  585. set to True.
  586. :param autoescape: boolean; when True, establishes an escape character
  587. within the LIKE expression, then applies it to all occurrences of
  588. ``"%"``, ``"_"`` and the escape character itself within the
  589. comparison value, which is assumed to be a literal string and not a
  590. SQL expression.
  591. An expression such as::
  592. somecolumn.endswith("foo%bar", autoescape=True)
  593. Will render as::
  594. somecolumn LIKE '%' || :param ESCAPE '/'
  595. With the value of ``:param`` as ``"foo/%bar"``.
  596. :param escape: a character which when given will render with the
  597. ``ESCAPE`` keyword to establish that character as the escape
  598. character. This character can then be placed preceding occurrences
  599. of ``%`` and ``_`` to allow them to act as themselves and not
  600. wildcard characters.
  601. An expression such as::
  602. somecolumn.endswith("foo/%bar", escape="^")
  603. Will render as::
  604. somecolumn LIKE '%' || :param ESCAPE '^'
  605. The parameter may also be combined with
  606. :paramref:`.ColumnOperators.endswith.autoescape`::
  607. somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)
  608. Where above, the given literal parameter will be converted to
  609. ``"foo^%bar^^bat"`` before being passed to the database.
  610. .. seealso::
  611. :meth:`.ColumnOperators.startswith`
  612. :meth:`.ColumnOperators.contains`
  613. :meth:`.ColumnOperators.like`
  614. """
  615. return self.operate(endswith_op, other, **kwargs)
  616. def contains(self, other, **kwargs):
  617. r"""Implement the 'contains' operator.
  618. Produces a LIKE expression that tests against a match for the middle
  619. of a string value::
  620. column LIKE '%' || <other> || '%'
  621. E.g.::
  622. stmt = select(sometable).\
  623. where(sometable.c.column.contains("foobar"))
  624. Since the operator uses ``LIKE``, wildcard characters
  625. ``"%"`` and ``"_"`` that are present inside the <other> expression
  626. will behave like wildcards as well. For literal string
  627. values, the :paramref:`.ColumnOperators.contains.autoescape` flag
  628. may be set to ``True`` to apply escaping to occurrences of these
  629. characters within the string value so that they match as themselves
  630. and not as wildcard characters. Alternatively, the
  631. :paramref:`.ColumnOperators.contains.escape` parameter will establish
  632. a given character as an escape character which can be of use when
  633. the target expression is not a literal string.
  634. :param other: expression to be compared. This is usually a plain
  635. string value, but can also be an arbitrary SQL expression. LIKE
  636. wildcard characters ``%`` and ``_`` are not escaped by default unless
  637. the :paramref:`.ColumnOperators.contains.autoescape` flag is
  638. set to True.
  639. :param autoescape: boolean; when True, establishes an escape character
  640. within the LIKE expression, then applies it to all occurrences of
  641. ``"%"``, ``"_"`` and the escape character itself within the
  642. comparison value, which is assumed to be a literal string and not a
  643. SQL expression.
  644. An expression such as::
  645. somecolumn.contains("foo%bar", autoescape=True)
  646. Will render as::
  647. somecolumn LIKE '%' || :param || '%' ESCAPE '/'
  648. With the value of ``:param`` as ``"foo/%bar"``.
  649. :param escape: a character which when given will render with the
  650. ``ESCAPE`` keyword to establish that character as the escape
  651. character. This character can then be placed preceding occurrences
  652. of ``%`` and ``_`` to allow them to act as themselves and not
  653. wildcard characters.
  654. An expression such as::
  655. somecolumn.contains("foo/%bar", escape="^")
  656. Will render as::
  657. somecolumn LIKE '%' || :param || '%' ESCAPE '^'
  658. The parameter may also be combined with
  659. :paramref:`.ColumnOperators.contains.autoescape`::
  660. somecolumn.contains("foo%bar^bat", escape="^", autoescape=True)
  661. Where above, the given literal parameter will be converted to
  662. ``"foo^%bar^^bat"`` before being passed to the database.
  663. .. seealso::
  664. :meth:`.ColumnOperators.startswith`
  665. :meth:`.ColumnOperators.endswith`
  666. :meth:`.ColumnOperators.like`
  667. """
  668. return self.operate(contains_op, other, **kwargs)
  669. def match(self, other, **kwargs):
  670. """Implements a database-specific 'match' operator.
  671. :meth:`_sql.ColumnOperators.match` attempts to resolve to
  672. a MATCH-like function or operator provided by the backend.
  673. Examples include:
  674. * PostgreSQL - renders ``x @@ to_tsquery(y)``
  675. * MySQL - renders ``MATCH (x) AGAINST (y IN BOOLEAN MODE)``
  676. .. seealso::
  677. :class:`_mysql.match` - MySQL specific construct with
  678. additional features.
  679. * Oracle - renders ``CONTAINS(x, y)``
  680. * other backends may provide special implementations.
  681. * Backends without any special implementation will emit
  682. the operator as "MATCH". This is compatible with SQLite, for
  683. example.
  684. """
  685. return self.operate(match_op, other, **kwargs)
  686. def regexp_match(self, pattern, flags=None):
  687. """Implements a database-specific 'regexp match' operator.
  688. E.g.::
  689. stmt = select(table.c.some_column).where(
  690. table.c.some_column.regexp_match('^(b|c)')
  691. )
  692. :meth:`_sql.ColumnOperators.regexp_match` attempts to resolve to
  693. a REGEXP-like function or operator provided by the backend, however
  694. the specific regular expression syntax and flags available are
  695. **not backend agnostic**.
  696. Examples include:
  697. * PostgreSQL - renders ``x ~ y`` or ``x !~ y`` when negated.
  698. * Oracle - renders ``REGEXP_LIKE(x, y)``
  699. * SQLite - uses SQLite's ``REGEXP`` placeholder operator and calls into
  700. the Python ``re.match()`` builtin.
  701. * other backends may provide special implementations.
  702. * Backends without any special implementation will emit
  703. the operator as "REGEXP" or "NOT REGEXP". This is compatible with
  704. SQLite and MySQL, for example.
  705. Regular expression support is currently implemented for Oracle,
  706. PostgreSQL, MySQL and MariaDB. Partial support is available for
  707. SQLite. Support among third-party dialects may vary.
  708. :param pattern: The regular expression pattern string or column
  709. clause.
  710. :param flags: Any regular expression string flags to apply, passed as
  711. plain Python string only. These flags are backend specific.
  712. Some backends, like PostgreSQL and MariaDB, may alternatively
  713. specify the flags as part of the pattern.
  714. When using the ignore case flag 'i' in PostgreSQL, the ignore case
  715. regexp match operator ``~*`` or ``!~*`` will be used.
  716. .. versionadded:: 1.4
  717. .. versionchanged:: 1.4.48, 2.0.18 Note that due to an implementation
  718. error, the "flags" parameter previously accepted SQL expression
  719. objects such as column expressions in addition to plain Python
  720. strings. This implementation did not work correctly with caching
  721. and was removed; strings only should be passed for the "flags"
  722. parameter, as these flags are rendered as literal inline values
  723. within SQL expressions.
  724. .. seealso::
  725. :meth:`_sql.ColumnOperators.regexp_replace`
  726. """
  727. return self.operate(regexp_match_op, pattern, flags=flags)
  728. def regexp_replace(self, pattern, replacement, flags=None):
  729. """Implements a database-specific 'regexp replace' operator.
  730. E.g.::
  731. stmt = select(
  732. table.c.some_column.regexp_replace(
  733. 'b(..)',
  734. 'X\1Y',
  735. flags='g'
  736. )
  737. )
  738. :meth:`_sql.ColumnOperators.regexp_replace` attempts to resolve to
  739. a REGEXP_REPLACE-like function provided by the backend, that
  740. usually emit the function ``REGEXP_REPLACE()``. However,
  741. the specific regular expression syntax and flags available are
  742. **not backend agnostic**.
  743. Regular expression replacement support is currently implemented for
  744. Oracle, PostgreSQL, MySQL 8 or greater and MariaDB. Support among
  745. third-party dialects may vary.
  746. :param pattern: The regular expression pattern string or column
  747. clause.
  748. :param pattern: The replacement string or column clause.
  749. :param flags: Any regular expression string flags to apply, passed as
  750. plain Python string only. These flags are backend specific.
  751. Some backends, like PostgreSQL and MariaDB, may alternatively
  752. specify the flags as part of the pattern.
  753. .. versionadded:: 1.4
  754. .. versionchanged:: 1.4.48, 2.0.18 Note that due to an implementation
  755. error, the "flags" parameter previously accepted SQL expression
  756. objects such as column expressions in addition to plain Python
  757. strings. This implementation did not work correctly with caching
  758. and was removed; strings only should be passed for the "flags"
  759. parameter, as these flags are rendered as literal inline values
  760. within SQL expressions.
  761. .. seealso::
  762. :meth:`_sql.ColumnOperators.regexp_match`
  763. """
  764. return self.operate(
  765. regexp_replace_op, pattern, replacement=replacement, flags=flags
  766. )
  767. def desc(self):
  768. """Produce a :func:`_expression.desc` clause against the
  769. parent object."""
  770. return self.operate(desc_op)
  771. def asc(self):
  772. """Produce a :func:`_expression.asc` clause against the
  773. parent object."""
  774. return self.operate(asc_op)
  775. def nulls_first(self):
  776. """Produce a :func:`_expression.nulls_first` clause against the
  777. parent object.
  778. .. versionchanged:: 1.4 The ``nulls_first()`` operator is
  779. renamed from ``nullsfirst()`` in previous releases.
  780. The previous name remains available for backwards compatibility.
  781. """
  782. return self.operate(nulls_first_op)
  783. # deprecated 1.4; see #5435
  784. nullsfirst = nulls_first
  785. def nulls_last(self):
  786. """Produce a :func:`_expression.nulls_last` clause against the
  787. parent object.
  788. .. versionchanged:: 1.4 The ``nulls_last()`` operator is
  789. renamed from ``nullslast()`` in previous releases.
  790. The previous name remains available for backwards compatibility.
  791. """
  792. return self.operate(nulls_last_op)
  793. # deprecated 1.4; see #5429
  794. nullslast = nulls_last
  795. def collate(self, collation):
  796. """Produce a :func:`_expression.collate` clause against
  797. the parent object, given the collation string.
  798. .. seealso::
  799. :func:`_expression.collate`
  800. """
  801. return self.operate(collate, collation)
  802. def __radd__(self, other):
  803. """Implement the ``+`` operator in reverse.
  804. See :meth:`.ColumnOperators.__add__`.
  805. """
  806. return self.reverse_operate(add, other)
  807. def __rsub__(self, other):
  808. """Implement the ``-`` operator in reverse.
  809. See :meth:`.ColumnOperators.__sub__`.
  810. """
  811. return self.reverse_operate(sub, other)
  812. def __rmul__(self, other):
  813. """Implement the ``*`` operator in reverse.
  814. See :meth:`.ColumnOperators.__mul__`.
  815. """
  816. return self.reverse_operate(mul, other)
  817. def __rdiv__(self, other):
  818. """Implement the ``/`` operator in reverse.
  819. See :meth:`.ColumnOperators.__div__`.
  820. """
  821. return self.reverse_operate(div, other)
  822. def __rmod__(self, other):
  823. """Implement the ``%`` operator in reverse.
  824. See :meth:`.ColumnOperators.__mod__`.
  825. """
  826. return self.reverse_operate(mod, other)
  827. def between(self, cleft, cright, symmetric=False):
  828. """Produce a :func:`_expression.between` clause against
  829. the parent object, given the lower and upper range.
  830. """
  831. return self.operate(between_op, cleft, cright, symmetric=symmetric)
  832. def distinct(self):
  833. """Produce a :func:`_expression.distinct` clause against the
  834. parent object.
  835. """
  836. return self.operate(distinct_op)
  837. def any_(self):
  838. """Produce an :func:`_expression.any_` clause against the
  839. parent object.
  840. See the documentation for :func:`_sql.any_` for examples.
  841. .. note:: be sure to not confuse the newer
  842. :meth:`_sql.ColumnOperators.any_` method with its older
  843. :class:`_types.ARRAY`-specific counterpart, the
  844. :meth:`_types.ARRAY.Comparator.any` method, which a different
  845. calling syntax and usage pattern.
  846. .. versionadded:: 1.1
  847. """
  848. return self.operate(any_op)
  849. def all_(self):
  850. """Produce an :func:`_expression.all_` clause against the
  851. parent object.
  852. See the documentation for :func:`_sql.all_` for examples.
  853. .. note:: be sure to not confuse the newer
  854. :meth:`_sql.ColumnOperators.all_` method with its older
  855. :class:`_types.ARRAY`-specific counterpart, the
  856. :meth:`_types.ARRAY.Comparator.all` method, which a different
  857. calling syntax and usage pattern.
  858. .. versionadded:: 1.1
  859. """
  860. return self.operate(all_op)
  861. def __add__(self, other):
  862. """Implement the ``+`` operator.
  863. In a column context, produces the clause ``a + b``
  864. if the parent object has non-string affinity.
  865. If the parent object has a string affinity,
  866. produces the concatenation operator, ``a || b`` -
  867. see :meth:`.ColumnOperators.concat`.
  868. """
  869. return self.operate(add, other)
  870. def __sub__(self, other):
  871. """Implement the ``-`` operator.
  872. In a column context, produces the clause ``a - b``.
  873. """
  874. return self.operate(sub, other)
  875. def __mul__(self, other):
  876. """Implement the ``*`` operator.
  877. In a column context, produces the clause ``a * b``.
  878. """
  879. return self.operate(mul, other)
  880. def __div__(self, other):
  881. """Implement the ``/`` operator.
  882. In a column context, produces the clause ``a / b``.
  883. """
  884. return self.operate(div, other)
  885. def __mod__(self, other):
  886. """Implement the ``%`` operator.
  887. In a column context, produces the clause ``a % b``.
  888. """
  889. return self.operate(mod, other)
  890. def __truediv__(self, other):
  891. """Implement the ``//`` operator.
  892. In a column context, produces the clause ``a / b``.
  893. """
  894. return self.operate(truediv, other)
  895. def __rtruediv__(self, other):
  896. """Implement the ``//`` operator in reverse.
  897. See :meth:`.ColumnOperators.__truediv__`.
  898. """
  899. return self.reverse_operate(truediv, other)
  900. _commutative = {eq, ne, add, mul}
  901. _comparison = {eq, ne, lt, gt, ge, le}
  902. def commutative_op(fn):
  903. _commutative.add(fn)
  904. return fn
  905. def comparison_op(fn):
  906. _comparison.add(fn)
  907. return fn
  908. def from_():
  909. raise NotImplementedError()
  910. @comparison_op
  911. def function_as_comparison_op():
  912. raise NotImplementedError()
  913. def as_():
  914. raise NotImplementedError()
  915. def exists():
  916. raise NotImplementedError()
  917. def is_true(a):
  918. raise NotImplementedError()
  919. # 1.4 deprecated; see #5435
  920. istrue = is_true
  921. def is_false(a):
  922. raise NotImplementedError()
  923. # 1.4 deprecated; see #5435
  924. isfalse = is_false
  925. @comparison_op
  926. def is_distinct_from(a, b):
  927. return a.is_distinct_from(b)
  928. @comparison_op
  929. def is_not_distinct_from(a, b):
  930. return a.is_not_distinct_from(b)
  931. # deprecated 1.4; see #5435
  932. isnot_distinct_from = is_not_distinct_from
  933. @comparison_op
  934. def is_(a, b):
  935. return a.is_(b)
  936. @comparison_op
  937. def is_not(a, b):
  938. return a.is_not(b)
  939. # 1.4 deprecated; see #5429
  940. isnot = is_not
  941. def collate(a, b):
  942. return a.collate(b)
  943. def op(a, opstring, b):
  944. return a.op(opstring)(b)
  945. @comparison_op
  946. def like_op(a, b, escape=None):
  947. return a.like(b, escape=escape)
  948. @comparison_op
  949. def not_like_op(a, b, escape=None):
  950. return a.notlike(b, escape=escape)
  951. # 1.4 deprecated; see #5435
  952. notlike_op = not_like_op
  953. @comparison_op
  954. def ilike_op(a, b, escape=None):
  955. return a.ilike(b, escape=escape)
  956. @comparison_op
  957. def not_ilike_op(a, b, escape=None):
  958. return a.not_ilike(b, escape=escape)
  959. # 1.4 deprecated; see #5435
  960. notilike_op = not_ilike_op
  961. @comparison_op
  962. def between_op(a, b, c, symmetric=False):
  963. return a.between(b, c, symmetric=symmetric)
  964. @comparison_op
  965. def not_between_op(a, b, c, symmetric=False):
  966. return ~a.between(b, c, symmetric=symmetric)
  967. # 1.4 deprecated; see #5435
  968. notbetween_op = not_between_op
  969. @comparison_op
  970. def in_op(a, b):
  971. return a.in_(b)
  972. @comparison_op
  973. def not_in_op(a, b):
  974. return a.not_in(b)
  975. # 1.4 deprecated; see #5429
  976. notin_op = not_in_op
  977. def distinct_op(a):
  978. return a.distinct()
  979. def any_op(a):
  980. return a.any_()
  981. def all_op(a):
  982. return a.all_()
  983. def _escaped_like_impl(fn, other, escape, autoescape):
  984. if autoescape:
  985. if autoescape is not True:
  986. util.warn(
  987. "The autoescape parameter is now a simple boolean True/False"
  988. )
  989. if escape is None:
  990. escape = "/"
  991. if not isinstance(other, util.compat.string_types):
  992. raise TypeError("String value expected when autoescape=True")
  993. if escape not in ("%", "_"):
  994. other = other.replace(escape, escape + escape)
  995. other = other.replace("%", escape + "%").replace("_", escape + "_")
  996. return fn(other, escape=escape)
  997. @comparison_op
  998. def startswith_op(a, b, escape=None, autoescape=False):
  999. return _escaped_like_impl(a.startswith, b, escape, autoescape)
  1000. @comparison_op
  1001. def not_startswith_op(a, b, escape=None, autoescape=False):
  1002. return ~_escaped_like_impl(a.startswith, b, escape, autoescape)
  1003. # 1.4 deprecated; see #5435
  1004. notstartswith_op = not_startswith_op
  1005. @comparison_op
  1006. def endswith_op(a, b, escape=None, autoescape=False):
  1007. return _escaped_like_impl(a.endswith, b, escape, autoescape)
  1008. @comparison_op
  1009. def not_endswith_op(a, b, escape=None, autoescape=False):
  1010. return ~_escaped_like_impl(a.endswith, b, escape, autoescape)
  1011. # 1.4 deprecated; see #5435
  1012. notendswith_op = not_endswith_op
  1013. @comparison_op
  1014. def contains_op(a, b, escape=None, autoescape=False):
  1015. return _escaped_like_impl(a.contains, b, escape, autoescape)
  1016. @comparison_op
  1017. def not_contains_op(a, b, escape=None, autoescape=False):
  1018. return ~_escaped_like_impl(a.contains, b, escape, autoescape)
  1019. # 1.4 deprecated; see #5435
  1020. notcontains_op = not_contains_op
  1021. @comparison_op
  1022. def match_op(a, b, **kw):
  1023. return a.match(b, **kw)
  1024. @comparison_op
  1025. def regexp_match_op(a, b, flags=None):
  1026. return a.regexp_match(b, flags=flags)
  1027. @comparison_op
  1028. def not_regexp_match_op(a, b, flags=None):
  1029. return ~a.regexp_match(b, flags=flags)
  1030. def regexp_replace_op(a, b, replacement, flags=None):
  1031. return a.regexp_replace(b, replacement=replacement, flags=flags)
  1032. @comparison_op
  1033. def not_match_op(a, b, **kw):
  1034. return ~a.match(b, **kw)
  1035. # 1.4 deprecated; see #5429
  1036. notmatch_op = not_match_op
  1037. def comma_op(a, b):
  1038. raise NotImplementedError()
  1039. def filter_op(a, b):
  1040. raise NotImplementedError()
  1041. def concat_op(a, b):
  1042. try:
  1043. concat = a.concat
  1044. except AttributeError:
  1045. return b._rconcat(a)
  1046. else:
  1047. return concat(b)
  1048. def desc_op(a):
  1049. return a.desc()
  1050. def asc_op(a):
  1051. return a.asc()
  1052. def nulls_first_op(a):
  1053. return a.nulls_first()
  1054. # 1.4 deprecated; see #5435
  1055. nullsfirst_op = nulls_first_op
  1056. def nulls_last_op(a):
  1057. return a.nulls_last()
  1058. # 1.4 deprecated; see #5435
  1059. nullslast_op = nulls_last_op
  1060. def json_getitem_op(a, b):
  1061. raise NotImplementedError()
  1062. def json_path_getitem_op(a, b):
  1063. raise NotImplementedError()
  1064. def is_comparison(op):
  1065. return op in _comparison or isinstance(op, custom_op) and op.is_comparison
  1066. def is_commutative(op):
  1067. return op in _commutative
  1068. def is_ordering_modifier(op):
  1069. return op in (asc_op, desc_op, nulls_first_op, nulls_last_op)
  1070. def is_natural_self_precedent(op):
  1071. return (
  1072. op in _natural_self_precedent
  1073. or isinstance(op, custom_op)
  1074. and op.natural_self_precedent
  1075. )
  1076. _booleans = (inv, is_true, is_false, and_, or_)
  1077. def is_boolean(op):
  1078. return is_comparison(op) or op in _booleans
  1079. _mirror = {gt: lt, ge: le, lt: gt, le: ge}
  1080. def mirror(op):
  1081. """rotate a comparison operator 180 degrees.
  1082. Note this is not the same as negation.
  1083. """
  1084. return _mirror.get(op, op)
  1085. _associative = _commutative.union([concat_op, and_, or_]).difference([eq, ne])
  1086. def is_associative(op):
  1087. return op in _associative
  1088. _natural_self_precedent = _associative.union(
  1089. [getitem, json_getitem_op, json_path_getitem_op]
  1090. )
  1091. """Operators where if we have (a op b) op c, we don't want to
  1092. parenthesize (a op b).
  1093. """
  1094. _asbool = util.symbol("_asbool", canonical=-10)
  1095. _smallest = util.symbol("_smallest", canonical=-100)
  1096. _largest = util.symbol("_largest", canonical=100)
  1097. _PRECEDENCE = {
  1098. from_: 15,
  1099. function_as_comparison_op: 15,
  1100. any_op: 15,
  1101. all_op: 15,
  1102. getitem: 15,
  1103. json_getitem_op: 15,
  1104. json_path_getitem_op: 15,
  1105. mul: 8,
  1106. truediv: 8,
  1107. div: 8,
  1108. mod: 8,
  1109. neg: 8,
  1110. add: 7,
  1111. sub: 7,
  1112. concat_op: 6,
  1113. filter_op: 6,
  1114. match_op: 5,
  1115. not_match_op: 5,
  1116. regexp_match_op: 5,
  1117. not_regexp_match_op: 5,
  1118. regexp_replace_op: 5,
  1119. ilike_op: 5,
  1120. not_ilike_op: 5,
  1121. like_op: 5,
  1122. not_like_op: 5,
  1123. in_op: 5,
  1124. not_in_op: 5,
  1125. is_: 5,
  1126. is_not: 5,
  1127. eq: 5,
  1128. ne: 5,
  1129. is_distinct_from: 5,
  1130. is_not_distinct_from: 5,
  1131. gt: 5,
  1132. lt: 5,
  1133. ge: 5,
  1134. le: 5,
  1135. between_op: 5,
  1136. not_between_op: 5,
  1137. distinct_op: 5,
  1138. inv: 5,
  1139. is_true: 5,
  1140. is_false: 5,
  1141. and_: 3,
  1142. or_: 2,
  1143. comma_op: -1,
  1144. desc_op: 3,
  1145. asc_op: 3,
  1146. collate: 4,
  1147. as_: -1,
  1148. exists: 0,
  1149. _asbool: -10,
  1150. _smallest: _smallest,
  1151. _largest: _largest,
  1152. }
  1153. def is_precedent(operator, against):
  1154. if operator is against and is_natural_self_precedent(operator):
  1155. return False
  1156. else:
  1157. return _PRECEDENCE.get(
  1158. operator, getattr(operator, "precedence", _smallest)
  1159. ) <= _PRECEDENCE.get(against, getattr(against, "precedence", _largest))