operators.py 48 KB

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