expression.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. """ Domain expression processing
  4. The main duty of this module is to compile a domain expression into a
  5. SQL query. A lot of things should be documented here, but as a first
  6. step in the right direction, some tests in test_expression.py
  7. might give you some additional information.
  8. For legacy reasons, a domain uses an inconsistent two-levels abstract
  9. syntax (domains are regular Python data structures). At the first
  10. level, a domain is an expression made of terms (sometimes called
  11. leaves) and (domain) operators used in prefix notation. The available
  12. operators at this level are '!', '&', and '|'. '!' is a unary 'not',
  13. '&' is a binary 'and', and '|' is a binary 'or'. For instance, here
  14. is a possible domain. (<term> stands for an arbitrary term, more on
  15. this later.)::
  16. ['&', '!', <term1>, '|', <term2>, <term3>]
  17. It is equivalent to this pseudo code using infix notation::
  18. (not <term1>) and (<term2> or <term3>)
  19. The second level of syntax deals with the term representation. A term
  20. is a triple of the form (left, operator, right). That is, a term uses
  21. an infix notation, and the available operators, and possible left and
  22. right operands differ with those of the previous level. Here is a
  23. possible term::
  24. ('company_id.name', '=', 'OpenERP')
  25. The left and right operand don't have the same possible values. The
  26. left operand is field name (related to the model for which the domain
  27. applies). Actually, the field name can use the dot-notation to
  28. traverse relationships. The right operand is a Python value whose
  29. type should match the used operator and field type. In the above
  30. example, a string is used because the name field of a company has type
  31. string, and because we use the '=' operator. When appropriate, a 'in'
  32. operator can be used, and thus the right operand should be a list.
  33. Note: the non-uniform syntax could have been more uniform, but this
  34. would hide an important limitation of the domain syntax. Say that the
  35. term representation was ['=', 'company_id.name', 'OpenERP']. Used in a
  36. complete domain, this would look like::
  37. ['!', ['=', 'company_id.name', 'OpenERP']]
  38. and you would be tempted to believe something like this would be
  39. possible::
  40. ['!', ['=', 'company_id.name', ['&', ..., ...]]]
  41. That is, a domain could be a valid operand. But this is not the
  42. case. A domain is really limited to a two-level nature, and can not
  43. take a recursive form: a domain is not a valid second-level operand.
  44. Unaccent - Accent-insensitive search
  45. OpenERP will use the SQL function 'unaccent' when available for the
  46. 'ilike' and 'not ilike' operators, and enabled in the configuration.
  47. Normally the 'unaccent' function is obtained from `the PostgreSQL
  48. 'unaccent' contrib module
  49. <http://developer.postgresql.org/pgdocs/postgres/unaccent.html>`_.
  50. .. todo: The following explanation should be moved in some external
  51. installation guide
  52. The steps to install the module might differ on specific PostgreSQL
  53. versions. We give here some instruction for PostgreSQL 9.x on a
  54. Ubuntu system.
  55. Ubuntu doesn't come yet with PostgreSQL 9.x, so an alternative package
  56. source is used. We use Martin Pitt's PPA available at
  57. `ppa:pitti/postgresql
  58. <https://launchpad.net/~pitti/+archive/postgresql>`_.
  59. .. code-block:: sh
  60. > sudo add-apt-repository ppa:pitti/postgresql
  61. > sudo apt-get update
  62. Once the package list is up-to-date, you have to install PostgreSQL
  63. 9.0 and its contrib modules.
  64. .. code-block:: sh
  65. > sudo apt-get install postgresql-9.0 postgresql-contrib-9.0
  66. When you want to enable unaccent on some database:
  67. .. code-block:: sh
  68. > psql9 <database> -f /usr/share/postgresql/9.0/contrib/unaccent.sql
  69. Here :program:`psql9` is an alias for the newly installed PostgreSQL
  70. 9.0 tool, together with the correct port if necessary (for instance if
  71. PostgreSQL 8.4 is running on 5432). (Other aliases can be used for
  72. createdb and dropdb.)
  73. .. code-block:: sh
  74. > alias psql9='/usr/lib/postgresql/9.0/bin/psql -p 5433'
  75. You can check unaccent is working:
  76. .. code-block:: sh
  77. > psql9 <database> -c"select unaccent('hélène')"
  78. Finally, to instruct OpenERP to really use the unaccent function, you have to
  79. start the server specifying the ``--unaccent`` flag.
  80. """
  81. import collections.abc
  82. import logging
  83. import reprlib
  84. import traceback
  85. import warnings
  86. from datetime import date, datetime, time
  87. from psycopg2.sql import Composable, SQL
  88. import odoo.modules
  89. from ..models import BaseModel
  90. from odoo.tools import pycompat, Query, _generate_table_alias, sql
  91. # Domain operators.
  92. NOT_OPERATOR = '!'
  93. OR_OPERATOR = '|'
  94. AND_OPERATOR = '&'
  95. DOMAIN_OPERATORS = (NOT_OPERATOR, OR_OPERATOR, AND_OPERATOR)
  96. # List of available term operators. It is also possible to use the '<>'
  97. # operator, which is strictly the same as '!='; the later should be preferred
  98. # for consistency. This list doesn't contain '<>' as it is simplified to '!='
  99. # by the normalize_operator() function (so later part of the code deals with
  100. # only one representation).
  101. # Internals (i.e. not available to the user) 'inselect' and 'not inselect'
  102. # operators are also used. In this case its right operand has the form (subselect, params).
  103. TERM_OPERATORS = ('=', '!=', '<=', '<', '>', '>=', '=?', '=like', '=ilike',
  104. 'like', 'not like', 'ilike', 'not ilike', 'in', 'not in',
  105. 'child_of', 'parent_of')
  106. # A subset of the above operators, with a 'negative' semantic. When the
  107. # expressions 'in NEGATIVE_TERM_OPERATORS' or 'not in NEGATIVE_TERM_OPERATORS' are used in the code
  108. # below, this doesn't necessarily mean that any of those NEGATIVE_TERM_OPERATORS is
  109. # legal in the processed term.
  110. NEGATIVE_TERM_OPERATORS = ('!=', 'not like', 'not ilike', 'not in')
  111. # Negation of domain expressions
  112. DOMAIN_OPERATORS_NEGATION = {
  113. AND_OPERATOR: OR_OPERATOR,
  114. OR_OPERATOR: AND_OPERATOR,
  115. }
  116. TERM_OPERATORS_NEGATION = {
  117. '<': '>=',
  118. '>': '<=',
  119. '<=': '>',
  120. '>=': '<',
  121. '=': '!=',
  122. '!=': '=',
  123. 'in': 'not in',
  124. 'like': 'not like',
  125. 'ilike': 'not ilike',
  126. 'not in': 'in',
  127. 'not like': 'like',
  128. 'not ilike': 'ilike',
  129. }
  130. TRUE_LEAF = (1, '=', 1)
  131. FALSE_LEAF = (0, '=', 1)
  132. TRUE_DOMAIN = [TRUE_LEAF]
  133. FALSE_DOMAIN = [FALSE_LEAF]
  134. _logger = logging.getLogger(__name__)
  135. # --------------------------------------------------
  136. # Generic domain manipulation
  137. # --------------------------------------------------
  138. def normalize_domain(domain):
  139. """Returns a normalized version of ``domain_expr``, where all implicit '&' operators
  140. have been made explicit. One property of normalized domain expressions is that they
  141. can be easily combined together as if they were single domain components.
  142. """
  143. assert isinstance(domain, (list, tuple)), "Domains to normalize must have a 'domain' form: a list or tuple of domain components"
  144. if not domain:
  145. return [TRUE_LEAF]
  146. result = []
  147. expected = 1 # expected number of expressions
  148. op_arity = {NOT_OPERATOR: 1, AND_OPERATOR: 2, OR_OPERATOR: 2}
  149. for token in domain:
  150. if expected == 0: # more than expected, like in [A, B]
  151. result[0:0] = [AND_OPERATOR] # put an extra '&' in front
  152. expected = 1
  153. if isinstance(token, (list, tuple)): # domain term
  154. expected -= 1
  155. token = tuple(token)
  156. else:
  157. expected += op_arity.get(token, 0) - 1
  158. result.append(token)
  159. assert expected == 0, 'This domain is syntactically not correct: %s' % (domain)
  160. return result
  161. def is_false(model, domain):
  162. """ Return whether ``domain`` is logically equivalent to false. """
  163. # use three-valued logic: -1 is false, 0 is unknown, +1 is true
  164. stack = []
  165. for token in reversed(normalize_domain(domain)):
  166. if token == '&':
  167. stack.append(min(stack.pop(), stack.pop()))
  168. elif token == '|':
  169. stack.append(max(stack.pop(), stack.pop()))
  170. elif token == '!':
  171. stack.append(-stack.pop())
  172. elif token == TRUE_LEAF:
  173. stack.append(+1)
  174. elif token == FALSE_LEAF:
  175. stack.append(-1)
  176. elif token[1] == 'in' and not (isinstance(token[2], Query) or token[2]):
  177. stack.append(-1)
  178. elif token[1] == 'not in' and not (isinstance(token[2], Query) or token[2]):
  179. stack.append(+1)
  180. else:
  181. stack.append(0)
  182. return stack.pop() == -1
  183. def combine(operator, unit, zero, domains):
  184. """Returns a new domain expression where all domain components from ``domains``
  185. have been added together using the binary operator ``operator``.
  186. It is guaranteed to return a normalized domain.
  187. :param operator:
  188. :param unit: the identity element of the domains "set" with regard to the operation
  189. performed by ``operator``, i.e the domain component ``i`` which, when
  190. combined with any domain ``x`` via ``operator``, yields ``x``.
  191. E.g. [(1,'=',1)] is the typical unit for AND_OPERATOR: adding it
  192. to any domain component gives the same domain.
  193. :param zero: the absorbing element of the domains "set" with regard to the operation
  194. performed by ``operator``, i.e the domain component ``z`` which, when
  195. combined with any domain ``x`` via ``operator``, yields ``z``.
  196. E.g. [(1,'=',1)] is the typical zero for OR_OPERATOR: as soon as
  197. you see it in a domain component the resulting domain is the zero.
  198. :param domains: a list of normalized domains.
  199. """
  200. result = []
  201. count = 0
  202. if domains == [unit]:
  203. return unit
  204. for domain in domains:
  205. if domain == unit:
  206. continue
  207. if domain == zero:
  208. return zero
  209. if domain:
  210. result += normalize_domain(domain)
  211. count += 1
  212. result = [operator] * (count - 1) + result
  213. return result or unit
  214. def AND(domains):
  215. """AND([D1,D2,...]) returns a domain representing D1 and D2 and ... """
  216. return combine(AND_OPERATOR, [TRUE_LEAF], [FALSE_LEAF], domains)
  217. def OR(domains):
  218. """OR([D1,D2,...]) returns a domain representing D1 or D2 or ... """
  219. return combine(OR_OPERATOR, [FALSE_LEAF], [TRUE_LEAF], domains)
  220. def distribute_not(domain):
  221. """ Distribute any '!' domain operators found inside a normalized domain.
  222. Because we don't use SQL semantic for processing a 'left not in right'
  223. query (i.e. our 'not in' is not simply translated to a SQL 'not in'),
  224. it means that a '! left in right' can not be simply processed
  225. by __leaf_to_sql by first emitting code for 'left in right' then wrapping
  226. the result with 'not (...)', as it would result in a 'not in' at the SQL
  227. level.
  228. This function is thus responsible for pushing any '!' domain operators
  229. inside the terms themselves. For example::
  230. ['!','&',('user_id','=',4),('partner_id','in',[1,2])]
  231. will be turned into:
  232. ['|',('user_id','!=',4),('partner_id','not in',[1,2])]
  233. """
  234. # This is an iterative version of a recursive function that split domain
  235. # into subdomains, processes them and combine the results. The "stack" below
  236. # represents the recursive calls to be done.
  237. result = []
  238. stack = [False]
  239. for token in domain:
  240. negate = stack.pop()
  241. # negate tells whether the subdomain starting with token must be negated
  242. if is_leaf(token):
  243. if negate:
  244. left, operator, right = token
  245. if operator in TERM_OPERATORS_NEGATION:
  246. if token in (TRUE_LEAF, FALSE_LEAF):
  247. result.append(FALSE_LEAF if token == TRUE_LEAF else TRUE_LEAF)
  248. else:
  249. result.append((left, TERM_OPERATORS_NEGATION[operator], right))
  250. else:
  251. result.append(NOT_OPERATOR)
  252. result.append(token)
  253. else:
  254. result.append(token)
  255. elif token == NOT_OPERATOR:
  256. stack.append(not negate)
  257. elif token in DOMAIN_OPERATORS_NEGATION:
  258. result.append(DOMAIN_OPERATORS_NEGATION[token] if negate else token)
  259. stack.append(negate)
  260. stack.append(negate)
  261. else:
  262. result.append(token)
  263. return result
  264. # --------------------------------------------------
  265. # Generic leaf manipulation
  266. # --------------------------------------------------
  267. def _quote(to_quote):
  268. if '"' not in to_quote:
  269. return '"%s"' % to_quote
  270. return to_quote
  271. def normalize_leaf(element):
  272. """ Change a term's operator to some canonical form, simplifying later
  273. processing. """
  274. if not is_leaf(element):
  275. return element
  276. left, operator, right = element
  277. original = operator
  278. operator = operator.lower()
  279. if operator == '<>':
  280. operator = '!='
  281. if isinstance(right, bool) and operator in ('in', 'not in'):
  282. _logger.warning("The domain term '%s' should use the '=' or '!=' operator." % ((left, original, right),))
  283. operator = '=' if operator == 'in' else '!='
  284. if isinstance(right, (list, tuple)) and operator in ('=', '!='):
  285. _logger.warning("The domain term '%s' should use the 'in' or 'not in' operator." % ((left, original, right),))
  286. operator = 'in' if operator == '=' else 'not in'
  287. return left, operator, right
  288. def is_operator(element):
  289. """ Test whether an object is a valid domain operator. """
  290. return isinstance(element, str) and element in DOMAIN_OPERATORS
  291. def is_leaf(element, internal=False):
  292. """ Test whether an object is a valid domain term:
  293. - is a list or tuple
  294. - with 3 elements
  295. - second element if a valid op
  296. :param tuple element: a leaf in form (left, operator, right)
  297. :param bool internal: allow or not the 'inselect' internal operator
  298. in the term. This should be always left to False.
  299. Note: OLD TODO change the share wizard to use this function.
  300. """
  301. INTERNAL_OPS = TERM_OPERATORS + ('<>',)
  302. if internal:
  303. INTERNAL_OPS += ('inselect', 'not inselect')
  304. return (isinstance(element, tuple) or isinstance(element, list)) \
  305. and len(element) == 3 \
  306. and element[1] in INTERNAL_OPS \
  307. and ((isinstance(element[0], str) and element[0])
  308. or tuple(element) in (TRUE_LEAF, FALSE_LEAF))
  309. def is_boolean(element):
  310. return element == TRUE_LEAF or element == FALSE_LEAF
  311. def check_leaf(element, internal=False):
  312. if not is_operator(element) and not is_leaf(element, internal):
  313. raise ValueError("Invalid leaf %s" % str(element))
  314. # --------------------------------------------------
  315. # SQL utils
  316. # --------------------------------------------------
  317. def _unaccent_wrapper(x):
  318. if isinstance(x, Composable):
  319. return SQL('unaccent({})').format(x)
  320. return 'unaccent({})'.format(x)
  321. def get_unaccent_wrapper(cr):
  322. if odoo.registry(cr.dbname).has_unaccent:
  323. return _unaccent_wrapper
  324. return lambda x: x
  325. class expression(object):
  326. """ Parse a domain expression
  327. Use a real polish notation
  328. Leafs are still in a ('foo', '=', 'bar') format
  329. For more info: http://christophe-simonis-at-tiny.blogspot.com/2008/08/new-new-domain-notation.html
  330. """
  331. def __init__(self, domain, model, alias=None, query=None):
  332. """ Initialize expression object and automatically parse the expression
  333. right after initialization.
  334. :param domain: expression (using domain ('foo', '=', 'bar') format)
  335. :param model: root model
  336. :param alias: alias for the model table if query is provided
  337. :param query: optional query object holding the final result
  338. :attr root_model: base model for the query
  339. :attr expression: the domain to parse, normalized and prepared
  340. :attr result: the result of the parsing, as a pair (query, params)
  341. :attr query: Query object holding the final result
  342. """
  343. self._unaccent_wrapper = get_unaccent_wrapper(model._cr)
  344. self._has_trigram = model.pool.has_trigram
  345. self.root_model = model
  346. self.root_alias = alias or model._table
  347. # normalize and prepare the expression for parsing
  348. self.expression = distribute_not(normalize_domain(domain))
  349. # this object handles all the joins
  350. self.query = Query(model.env.cr, model._table, model._table_query) if query is None else query
  351. # parse the domain expression
  352. self.parse()
  353. def _unaccent(self, field):
  354. if getattr(field, 'unaccent', False):
  355. return self._unaccent_wrapper
  356. return lambda x: x
  357. # ----------------------------------------
  358. # Leafs management
  359. # ----------------------------------------
  360. def get_tables(self):
  361. warnings.warn("deprecated expression.get_tables(), use expression.query instead",
  362. DeprecationWarning)
  363. return self.query.tables
  364. # ----------------------------------------
  365. # Parsing
  366. # ----------------------------------------
  367. def parse(self):
  368. """ Transform the leaves of the expression
  369. The principle is to pop elements from a leaf stack one at a time.
  370. Each leaf is processed. The processing is a if/elif list of various
  371. cases that appear in the leafs (many2one, function fields, ...).
  372. Three things can happen as a processing result:
  373. - the leaf is a logic operator, and updates the result stack
  374. accordingly;
  375. - the leaf has been modified and/or new leafs have to be introduced
  376. in the expression; they are pushed into the leaf stack, to be
  377. processed right after;
  378. - the leaf is converted to SQL and added to the result stack
  379. Example:
  380. =================== =================== =====================
  381. step stack result_stack
  382. =================== =================== =====================
  383. ['&', A, B] []
  384. substitute B ['&', A, B1] []
  385. convert B1 in SQL ['&', A] ["B1"]
  386. substitute A ['&', '|', A1, A2] ["B1"]
  387. convert A2 in SQL ['&', '|', A1] ["B1", "A2"]
  388. convert A1 in SQL ['&', '|'] ["B1", "A2", "A1"]
  389. apply operator OR ['&'] ["B1", "A1 or A2"]
  390. apply operator AND [] ["(A1 or A2) and B1"]
  391. =================== =================== =====================
  392. Some internal var explanation:
  393. :var list path: left operand seen as a sequence of field names
  394. ("foo.bar" -> ["foo", "bar"])
  395. :var obj model: model object, model containing the field
  396. (the name provided in the left operand)
  397. :var obj field: the field corresponding to `path[0]`
  398. :var obj column: the column corresponding to `path[0]`
  399. :var obj comodel: relational model of field (field.comodel)
  400. (res_partner.bank_ids -> res.partner.bank)
  401. """
  402. def to_ids(value, comodel, leaf):
  403. """ Normalize a single id or name, or a list of those, into a list of ids
  404. :param comodel:
  405. :param leaf:
  406. :param int|str|list|tuple value:
  407. - if int, long -> return [value]
  408. - if basestring, convert it into a list of basestrings, then
  409. - if list of basestring ->
  410. - perform a name_search on comodel for each name
  411. - return the list of related ids
  412. """
  413. names = []
  414. if isinstance(value, str):
  415. names = [value]
  416. elif value and isinstance(value, (tuple, list)) and all(isinstance(item, str) for item in value):
  417. names = value
  418. elif isinstance(value, int):
  419. if not value:
  420. # given this nonsensical domain, it is generally cheaper to
  421. # interpret False as [], so that "X child_of False" will
  422. # match nothing
  423. _logger.warning("Unexpected domain [%s], interpreted as False", leaf)
  424. return []
  425. return [value]
  426. if names:
  427. return list({
  428. rid
  429. for name in names
  430. for rid in comodel._name_search(name, [], 'ilike', limit=None)
  431. })
  432. return list(value)
  433. def child_of_domain(left, ids, left_model, parent=None, prefix=''):
  434. """ Return a domain implementing the child_of operator for [(left,child_of,ids)],
  435. either as a range using the parent_path tree lookup field
  436. (when available), or as an expanded [(left,in,child_ids)] """
  437. if not ids:
  438. return [FALSE_LEAF]
  439. if left_model._parent_store:
  440. domain = OR([
  441. [('parent_path', '=like', rec.parent_path + '%')]
  442. for rec in left_model.sudo().browse(ids)
  443. ])
  444. else:
  445. # recursively retrieve all children nodes with sudo(); the
  446. # filtering of forbidden records is done by the rest of the
  447. # domain
  448. parent_name = parent or left_model._parent_name
  449. if (left_model._name != left_model._fields[parent_name].comodel_name):
  450. raise ValueError(f"Invalid parent field: {left_model._fields[parent_name]}")
  451. child_ids = set()
  452. records = left_model.sudo().browse(ids)
  453. while records:
  454. child_ids.update(records._ids)
  455. records = records.search([(parent_name, 'in', records.ids)], order='id') - records.browse(child_ids)
  456. domain = [('id', 'in', list(child_ids))]
  457. if prefix:
  458. return [(left, 'in', left_model._search(domain, order='id'))]
  459. return domain
  460. def parent_of_domain(left, ids, left_model, parent=None, prefix=''):
  461. """ Return a domain implementing the parent_of operator for [(left,parent_of,ids)],
  462. either as a range using the parent_path tree lookup field
  463. (when available), or as an expanded [(left,in,parent_ids)] """
  464. if not ids:
  465. return [FALSE_LEAF]
  466. if left_model._parent_store:
  467. parent_ids = [
  468. int(label)
  469. for rec in left_model.sudo().browse(ids)
  470. for label in rec.parent_path.split('/')[:-1]
  471. ]
  472. domain = [('id', 'in', parent_ids)]
  473. else:
  474. # recursively retrieve all parent nodes with sudo() to avoid
  475. # access rights errors; the filtering of forbidden records is
  476. # done by the rest of the domain
  477. parent_name = parent or left_model._parent_name
  478. parent_ids = set()
  479. records = left_model.sudo().browse(ids)
  480. while records:
  481. parent_ids.update(records._ids)
  482. records = records[parent_name] - records.browse(parent_ids)
  483. domain = [('id', 'in', list(parent_ids))]
  484. if prefix:
  485. return [(left, 'in', left_model._search(domain, order='id'))]
  486. return domain
  487. HIERARCHY_FUNCS = {'child_of': child_of_domain,
  488. 'parent_of': parent_of_domain}
  489. def pop():
  490. """ Pop a leaf to process. """
  491. return stack.pop()
  492. def push(leaf, model, alias, internal=False):
  493. """ Push a leaf to be processed right after. """
  494. leaf = normalize_leaf(leaf)
  495. check_leaf(leaf, internal)
  496. stack.append((leaf, model, alias))
  497. def pop_result():
  498. return result_stack.pop()
  499. def push_result(query, params):
  500. result_stack.append((query, params))
  501. # process domain from right to left; stack contains domain leaves, in
  502. # the form: (leaf, corresponding model, corresponding table alias)
  503. stack = []
  504. for leaf in self.expression:
  505. push(leaf, self.root_model, self.root_alias)
  506. # stack of SQL expressions in the form: (expr, params)
  507. result_stack = []
  508. while stack:
  509. # Get the next leaf to process
  510. leaf, model, alias = pop()
  511. # ----------------------------------------
  512. # SIMPLE CASE
  513. # 1. leaf is an operator
  514. # 2. leaf is a true/false leaf
  515. # -> convert and add directly to result
  516. # ----------------------------------------
  517. if is_operator(leaf):
  518. if leaf == NOT_OPERATOR:
  519. expr, params = pop_result()
  520. push_result('(NOT (%s))' % expr, params)
  521. else:
  522. ops = {AND_OPERATOR: '(%s AND %s)', OR_OPERATOR: '(%s OR %s)'}
  523. lhs, lhs_params = pop_result()
  524. rhs, rhs_params = pop_result()
  525. push_result(ops[leaf] % (lhs, rhs), lhs_params + rhs_params)
  526. continue
  527. if is_boolean(leaf):
  528. expr, params = self.__leaf_to_sql(leaf, model, alias)
  529. push_result(expr, params)
  530. continue
  531. # Get working variables
  532. left, operator, right = leaf
  533. path = left.split('.', 1)
  534. field = model._fields.get(path[0])
  535. comodel = model.env.get(getattr(field, 'comodel_name', None))
  536. # ----------------------------------------
  537. # FIELD NOT FOUND
  538. # -> from inherits'd fields -> work on the related model, and add
  539. # a join condition
  540. # -> ('id', 'child_of', '..') -> use a 'to_ids'
  541. # -> but is one on the _log_access special fields, add directly to
  542. # result
  543. # TODO: make these fields explicitly available in self.columns instead!
  544. # -> else: crash
  545. # ----------------------------------------
  546. if not field:
  547. raise ValueError("Invalid field %s.%s in leaf %s" % (model._name, path[0], str(leaf)))
  548. elif field.inherited:
  549. parent_model = model.env[field.related_field.model_name]
  550. parent_fname = model._inherits[parent_model._name]
  551. parent_alias = self.query.left_join(
  552. alias, parent_fname, parent_model._table, 'id', parent_fname,
  553. )
  554. push(leaf, parent_model, parent_alias)
  555. elif left == 'id' and operator in HIERARCHY_FUNCS:
  556. ids2 = to_ids(right, model, leaf)
  557. dom = HIERARCHY_FUNCS[operator](left, ids2, model)
  558. for dom_leaf in dom:
  559. push(dom_leaf, model, alias)
  560. # ----------------------------------------
  561. # PATH SPOTTED
  562. # -> many2one or one2many with _auto_join:
  563. # - add a join, then jump into linked column: column.remaining on
  564. # src_table is replaced by remaining on dst_table, and set for re-evaluation
  565. # - if a domain is defined on the column, add it into evaluation
  566. # on the relational table
  567. # -> many2one, many2many, one2many: replace by an equivalent computed
  568. # domain, given by recursively searching on the remaining of the path
  569. # -> note: hack about columns.property should not be necessary anymore
  570. # as after transforming the column, it will go through this loop once again
  571. # ----------------------------------------
  572. elif len(path) > 1 and field.store and field.type == 'many2one' and field.auto_join:
  573. # res_partner.state_id = res_partner__state_id.id
  574. coalias = self.query.left_join(
  575. alias, path[0], comodel._table, 'id', path[0],
  576. )
  577. push((path[1], operator, right), comodel, coalias)
  578. elif len(path) > 1 and field.store and field.type == 'one2many' and field.auto_join:
  579. # use a subquery bypassing access rules and business logic
  580. domain = [(path[1], operator, right)] + field.get_domain_list(model)
  581. query = comodel.with_context(**field.context)._where_calc(domain)
  582. subquery, subparams = query.select('"%s"."%s"' % (comodel._table, field.inverse_name))
  583. push(('id', 'inselect', (subquery, subparams)), model, alias, internal=True)
  584. elif len(path) > 1 and field.store and field.auto_join:
  585. raise NotImplementedError('auto_join attribute not supported on field %s' % field)
  586. elif len(path) > 1 and field.store and field.type == 'many2one':
  587. right_ids = comodel.with_context(active_test=False)._search([(path[1], operator, right)], order='id')
  588. push((path[0], 'in', right_ids), model, alias)
  589. # Making search easier when there is a left operand as one2many or many2many
  590. elif len(path) > 1 and field.store and field.type in ('many2many', 'one2many'):
  591. right_ids = comodel.with_context(**field.context)._search([(path[1], operator, right)], order='id')
  592. push((path[0], 'in', right_ids), model, alias)
  593. elif not field.store:
  594. # Non-stored field should provide an implementation of search.
  595. if not field.search:
  596. # field does not support search!
  597. _logger.error("Non-stored field %s cannot be searched.", field, exc_info=True)
  598. if _logger.isEnabledFor(logging.DEBUG):
  599. _logger.debug(''.join(traceback.format_stack()))
  600. # Ignore it: generate a dummy leaf.
  601. domain = []
  602. else:
  603. # Let the field generate a domain.
  604. if len(path) > 1:
  605. right = comodel._search([(path[1], operator, right)], order='id')
  606. operator = 'in'
  607. domain = field.determine_domain(model, operator, right)
  608. model._flush_search(domain, order='id')
  609. for elem in normalize_domain(domain):
  610. push(elem, model, alias, internal=True)
  611. # -------------------------------------------------
  612. # RELATIONAL FIELDS
  613. # -------------------------------------------------
  614. # Applying recursivity on field(one2many)
  615. elif field.type == 'one2many' and operator in HIERARCHY_FUNCS:
  616. ids2 = to_ids(right, comodel, leaf)
  617. if field.comodel_name != model._name:
  618. dom = HIERARCHY_FUNCS[operator](left, ids2, comodel, prefix=field.comodel_name)
  619. else:
  620. dom = HIERARCHY_FUNCS[operator]('id', ids2, model, parent=left)
  621. for dom_leaf in dom:
  622. push(dom_leaf, model, alias)
  623. elif field.type == 'one2many':
  624. domain = field.get_domain_list(model)
  625. inverse_field = comodel._fields[field.inverse_name]
  626. inverse_is_int = inverse_field.type in ('integer', 'many2one_reference')
  627. unwrap_inverse = (lambda ids: ids) if inverse_is_int else (lambda recs: recs.ids)
  628. if right is not False:
  629. # determine ids2 in comodel
  630. if isinstance(right, str):
  631. op2 = (TERM_OPERATORS_NEGATION[operator]
  632. if operator in NEGATIVE_TERM_OPERATORS else operator)
  633. ids2 = comodel._name_search(right, domain or [], op2, limit=None)
  634. elif isinstance(right, collections.abc.Iterable):
  635. ids2 = right
  636. else:
  637. ids2 = [right]
  638. if inverse_is_int and domain:
  639. ids2 = comodel._search([('id', 'in', ids2)] + domain, order='id')
  640. if inverse_field.store:
  641. # In the condition, one must avoid subqueries to return
  642. # NULL values, since it makes the IN test NULL instead
  643. # of FALSE. This may discard expected results, as for
  644. # instance "id NOT IN (42, NULL)" is never TRUE.
  645. in_ = 'NOT IN' if operator in NEGATIVE_TERM_OPERATORS else 'IN'
  646. if isinstance(ids2, Query):
  647. if not inverse_field.required:
  648. ids2.add_where(f'"{comodel._table}"."{inverse_field.name}" IS NOT NULL')
  649. subquery, subparams = ids2.subselect(f'"{comodel._table}"."{inverse_field.name}"')
  650. else:
  651. subquery = f'SELECT "{inverse_field.name}" FROM "{comodel._table}" WHERE "id" IN %s'
  652. if not inverse_field.required:
  653. subquery += f' AND "{inverse_field.name}" IS NOT NULL'
  654. subparams = [tuple(ids2) or (None,)]
  655. push_result(f'("{alias}"."id" {in_} ({subquery}))', subparams)
  656. else:
  657. # determine ids1 in model related to ids2
  658. recs = comodel.browse(ids2).sudo().with_context(prefetch_fields=False)
  659. ids1 = unwrap_inverse(recs.mapped(inverse_field.name))
  660. # rewrite condition in terms of ids1
  661. op1 = 'not in' if operator in NEGATIVE_TERM_OPERATORS else 'in'
  662. push(('id', op1, ids1), model, alias)
  663. else:
  664. if inverse_field.store and not (inverse_is_int and domain):
  665. # rewrite condition to match records with/without lines
  666. op1 = 'inselect' if operator in NEGATIVE_TERM_OPERATORS else 'not inselect'
  667. subquery = f'SELECT "{inverse_field.name}" FROM "{comodel._table}" WHERE "{inverse_field.name}" IS NOT NULL'
  668. push(('id', op1, (subquery, [])), model, alias, internal=True)
  669. else:
  670. comodel_domain = [(inverse_field.name, '!=', False)]
  671. if inverse_is_int and domain:
  672. comodel_domain += domain
  673. recs = comodel.search(comodel_domain, order='id').sudo().with_context(prefetch_fields=False)
  674. # determine ids1 = records with lines
  675. ids1 = unwrap_inverse(recs.mapped(inverse_field.name))
  676. # rewrite condition to match records with/without lines
  677. op1 = 'in' if operator in NEGATIVE_TERM_OPERATORS else 'not in'
  678. push(('id', op1, ids1), model, alias)
  679. elif field.type == 'many2many':
  680. rel_table, rel_id1, rel_id2 = field.relation, field.column1, field.column2
  681. if operator in HIERARCHY_FUNCS:
  682. # determine ids2 in comodel
  683. ids2 = to_ids(right, comodel, leaf)
  684. domain = HIERARCHY_FUNCS[operator]('id', ids2, comodel)
  685. ids2 = comodel._search(domain, order='id')
  686. # rewrite condition in terms of ids2
  687. if comodel == model:
  688. push(('id', 'in', ids2), model, alias)
  689. else:
  690. rel_alias = _generate_table_alias(alias, field.name)
  691. push_result(f"""
  692. EXISTS (
  693. SELECT 1 FROM "{rel_table}" AS "{rel_alias}"
  694. WHERE "{rel_alias}"."{rel_id1}" = "{alias}".id
  695. AND "{rel_alias}"."{rel_id2}" IN %s
  696. )
  697. """, [tuple(ids2) or (None,)])
  698. elif right is not False:
  699. # determine ids2 in comodel
  700. if isinstance(right, str):
  701. domain = field.get_domain_list(model)
  702. op2 = (TERM_OPERATORS_NEGATION[operator]
  703. if operator in NEGATIVE_TERM_OPERATORS else operator)
  704. ids2 = comodel._name_search(right, domain or [], op2, limit=None)
  705. elif isinstance(right, collections.abc.Iterable):
  706. ids2 = right
  707. else:
  708. ids2 = [right]
  709. if isinstance(ids2, Query):
  710. # rewrite condition in terms of ids2
  711. subquery, params = ids2.subselect()
  712. term_id2 = f"({subquery})"
  713. else:
  714. # rewrite condition in terms of ids2
  715. term_id2 = "%s"
  716. params = [tuple(it for it in ids2 if it) or (None,)]
  717. exists = 'NOT EXISTS' if operator in NEGATIVE_TERM_OPERATORS else 'EXISTS'
  718. rel_alias = _generate_table_alias(alias, field.name)
  719. push_result(f"""
  720. {exists} (
  721. SELECT 1 FROM "{rel_table}" AS "{rel_alias}"
  722. WHERE "{rel_alias}"."{rel_id1}" = "{alias}".id
  723. AND "{rel_alias}"."{rel_id2}" IN {term_id2}
  724. )
  725. """, params)
  726. else:
  727. # rewrite condition to match records with/without relations
  728. exists = 'EXISTS' if operator in NEGATIVE_TERM_OPERATORS else 'NOT EXISTS'
  729. rel_alias = _generate_table_alias(alias, field.name)
  730. push_result(f"""
  731. {exists} (
  732. SELECT 1 FROM "{rel_table}" AS "{rel_alias}"
  733. WHERE "{rel_alias}"."{rel_id1}" = "{alias}".id
  734. )
  735. """, [])
  736. elif field.type == 'many2one':
  737. if operator in HIERARCHY_FUNCS:
  738. ids2 = to_ids(right, comodel, leaf)
  739. if field.comodel_name != model._name:
  740. dom = HIERARCHY_FUNCS[operator](left, ids2, comodel, prefix=field.comodel_name)
  741. else:
  742. dom = HIERARCHY_FUNCS[operator]('id', ids2, model, parent=left)
  743. for dom_leaf in dom:
  744. push(dom_leaf, model, alias)
  745. elif (
  746. isinstance(right, str)
  747. or isinstance(right, (tuple, list)) and right and all(isinstance(item, str) for item in right)
  748. ):
  749. # resolve string-based m2o criterion into IDs subqueries
  750. # Special treatment to ill-formed domains
  751. operator = 'in' if operator in ('<', '>', '<=', '>=') else operator
  752. dict_op = {'not in': '!=', 'in': '=', '=': 'in', '!=': 'not in'}
  753. if isinstance(right, tuple):
  754. right = list(right)
  755. if not isinstance(right, list) and operator in ('not in', 'in'):
  756. operator = dict_op[operator]
  757. elif isinstance(right, list) and operator in ('!=', '='): # for domain (FIELD,'=',['value1','value2'])
  758. operator = dict_op[operator]
  759. res_ids = comodel.with_context(active_test=False)._name_search(right, [], operator, limit=None)
  760. if operator in NEGATIVE_TERM_OPERATORS:
  761. for dom_leaf in ('|', (left, 'in', res_ids), (left, '=', False)):
  762. push(dom_leaf, model, alias)
  763. else:
  764. push((left, 'in', res_ids), model, alias)
  765. else:
  766. # right == [] or right == False and all other cases are handled by __leaf_to_sql()
  767. expr, params = self.__leaf_to_sql(leaf, model, alias)
  768. push_result(expr, params)
  769. # -------------------------------------------------
  770. # BINARY FIELDS STORED IN ATTACHMENT
  771. # -> check for null only
  772. # -------------------------------------------------
  773. elif field.type == 'binary' and field.attachment:
  774. if operator in ('=', '!=') and not right:
  775. inselect_operator = 'inselect' if operator in NEGATIVE_TERM_OPERATORS else 'not inselect'
  776. subselect = "SELECT res_id FROM ir_attachment WHERE res_model=%s AND res_field=%s"
  777. params = (model._name, left)
  778. push(('id', inselect_operator, (subselect, params)), model, alias, internal=True)
  779. else:
  780. _logger.error("Binary field '%s' stored in attachment: ignore %s %s %s",
  781. field.string, left, operator, reprlib.repr(right))
  782. push(TRUE_LEAF, model, alias)
  783. # -------------------------------------------------
  784. # OTHER FIELDS
  785. # -> datetime fields: manage time part of the datetime
  786. # column when it is not there
  787. # -> manage translatable fields
  788. # -------------------------------------------------
  789. else:
  790. if field.type == 'datetime' and right:
  791. if isinstance(right, str) and len(right) == 10:
  792. if operator in ('>', '<='):
  793. right += ' 23:59:59'
  794. else:
  795. right += ' 00:00:00'
  796. push((left, operator, right), model, alias)
  797. elif isinstance(right, date) and not isinstance(right, datetime):
  798. if operator in ('>', '<='):
  799. right = datetime.combine(right, time.max)
  800. else:
  801. right = datetime.combine(right, time.min)
  802. push((left, operator, right), model, alias)
  803. else:
  804. expr, params = self.__leaf_to_sql(leaf, model, alias)
  805. push_result(expr, params)
  806. elif field.translate and isinstance(right, str):
  807. sql_operator = {'=like': 'like', '=ilike': 'ilike'}.get(operator, operator)
  808. expr = ''
  809. params = []
  810. need_wildcard = operator in ('like', 'ilike', 'not like', 'not ilike')
  811. if not need_wildcard:
  812. right = field.convert_to_column(right, model, validate=False).adapted['en_US']
  813. if (need_wildcard and not right) or (right and sql_operator in NEGATIVE_TERM_OPERATORS):
  814. expr += f'"{alias}"."{left}" is NULL OR '
  815. if self._has_trigram and field.index == 'trigram' and sql_operator in ('=', 'like', 'ilike'):
  816. # a prefilter using trigram index to speed up '=', 'like', 'ilike'
  817. # '!=', '<=', '<', '>', '>=', 'in', 'not in', 'not like', 'not ilike' cannot use this trick
  818. if sql_operator == '=':
  819. _right = sql.value_to_translated_trigram_pattern(right)
  820. else:
  821. _right = sql.pattern_to_translated_trigram_pattern(right)
  822. if _right != '%':
  823. _unaccent = self._unaccent(field)
  824. _left = _unaccent(f'''jsonb_path_query_array("{alias}"."{left}", '$.*')::text''')
  825. _sql_operator = 'like' if sql_operator == '=' else sql_operator
  826. expr += f"{_left} {_sql_operator} {_unaccent('%s')} AND "
  827. params.append(_right)
  828. unaccent = self._unaccent(field) if sql_operator.endswith('like') else lambda x: x
  829. lang = model.env.lang or 'en_US'
  830. if lang == 'en_US':
  831. left = unaccent(f""""{alias}"."{left}"->>'en_US'""")
  832. else:
  833. left = unaccent(f'''COALESCE("{alias}"."{left}"->>'{lang}', "{alias}"."{left}"->>'en_US')''')
  834. if need_wildcard:
  835. right = f'%{right}%'
  836. expr += f"{left} {sql_operator} {unaccent('%s')}"
  837. params.append(right)
  838. push_result(f'({expr})', params)
  839. elif field.translate and operator in ['in', 'not in'] and isinstance(right, (list, tuple)):
  840. params = [it for it in right if it is not False and it is not None]
  841. check_null = len(params) < len(right)
  842. if params:
  843. params = [field.convert_to_column(p, model, validate=False).adapted['en_US'] for p in params]
  844. lang = model.env.lang or 'en_US'
  845. if lang == 'en_US':
  846. query = f'''("{alias}"."{left}"->>'en_US' {operator} %s)'''
  847. else:
  848. query = f'''(COALESCE("{alias}"."{left}"->>'{lang}', "{alias}"."{left}"->>'en_US') {operator} %s)'''
  849. params = [tuple(params)]
  850. else:
  851. # The case for (left, 'in', []) or (left, 'not in', []).
  852. query = 'FALSE' if operator == 'in' else 'TRUE'
  853. if (operator == 'in' and check_null) or (operator == 'not in' and not check_null):
  854. query = '(%s OR %s."%s" IS NULL)' % (query, alias, left)
  855. elif operator == 'not in' and check_null:
  856. query = '(%s AND %s."%s" IS NOT NULL)' % (query, alias, left) # needed only for TRUE.
  857. push_result(query, params)
  858. else:
  859. expr, params = self.__leaf_to_sql(leaf, model, alias)
  860. push_result(expr, params)
  861. # ----------------------------------------
  862. # END OF PARSING FULL DOMAIN
  863. # -> put result in self.result and self.query
  864. # ----------------------------------------
  865. [self.result] = result_stack
  866. where_clause, where_params = self.result
  867. self.query.add_where(where_clause, where_params)
  868. def __leaf_to_sql(self, leaf, model, alias):
  869. left, operator, right = leaf
  870. # final sanity checks - should never fail
  871. assert operator in (TERM_OPERATORS + ('inselect', 'not inselect')), \
  872. "Invalid operator %r in domain term %r" % (operator, leaf)
  873. assert leaf in (TRUE_LEAF, FALSE_LEAF) or left in model._fields, \
  874. "Invalid field %r in domain term %r" % (left, leaf)
  875. assert not isinstance(right, BaseModel), \
  876. "Invalid value %r in domain term %r" % (right, leaf)
  877. table_alias = '"%s"' % alias
  878. if leaf == TRUE_LEAF:
  879. query = 'TRUE'
  880. params = []
  881. elif leaf == FALSE_LEAF:
  882. query = 'FALSE'
  883. params = []
  884. elif operator == 'inselect':
  885. query = '(%s."%s" in (%s))' % (table_alias, left, right[0])
  886. params = list(right[1])
  887. elif operator == 'not inselect':
  888. query = '(%s."%s" not in (%s))' % (table_alias, left, right[0])
  889. params = list(right[1])
  890. elif operator in ['in', 'not in']:
  891. # Two cases: right is a boolean or a list. The boolean case is an
  892. # abuse and handled for backward compatibility.
  893. if isinstance(right, bool):
  894. _logger.warning("The domain term '%s' should use the '=' or '!=' operator." % (leaf,))
  895. if (operator == 'in' and right) or (operator == 'not in' and not right):
  896. query = '(%s."%s" IS NOT NULL)' % (table_alias, left)
  897. else:
  898. query = '(%s."%s" IS NULL)' % (table_alias, left)
  899. params = []
  900. elif isinstance(right, Query):
  901. subquery, subparams = right.subselect()
  902. query = '(%s."%s" %s (%s))' % (table_alias, left, operator, subquery)
  903. params = subparams
  904. elif isinstance(right, (list, tuple)):
  905. if model._fields[left].type == "boolean":
  906. params = [it for it in (True, False) if it in right]
  907. check_null = False in right
  908. else:
  909. params = [it for it in right if it is not False and it is not None]
  910. check_null = len(params) < len(right)
  911. if params:
  912. if left != 'id':
  913. field = model._fields[left]
  914. params = [field.convert_to_column(p, model, validate=False) for p in params]
  915. query = f'({table_alias}."{left}" {operator} %s)'
  916. params = [tuple(params)]
  917. else:
  918. # The case for (left, 'in', []) or (left, 'not in', []).
  919. query = 'FALSE' if operator == 'in' else 'TRUE'
  920. if (operator == 'in' and check_null) or (operator == 'not in' and not check_null):
  921. query = '(%s OR %s."%s" IS NULL)' % (query, table_alias, left)
  922. elif operator == 'not in' and check_null:
  923. query = '(%s AND %s."%s" IS NOT NULL)' % (query, table_alias, left) # needed only for TRUE.
  924. else: # Must not happen
  925. raise ValueError("Invalid domain term %r" % (leaf,))
  926. elif left in model and model._fields[left].type == "boolean" and ((operator == '=' and right is False) or (operator == '!=' and right is True)):
  927. query = '(%s."%s" IS NULL or %s."%s" = false )' % (table_alias, left, table_alias, left)
  928. params = []
  929. elif (right is False or right is None) and (operator == '='):
  930. query = '%s."%s" IS NULL ' % (table_alias, left)
  931. params = []
  932. elif left in model and model._fields[left].type == "boolean" and ((operator == '!=' and right is False) or (operator == '==' and right is True)):
  933. query = '(%s."%s" IS NOT NULL and %s."%s" != false)' % (table_alias, left, table_alias, left)
  934. params = []
  935. elif (right is False or right is None) and (operator == '!='):
  936. query = '%s."%s" IS NOT NULL' % (table_alias, left)
  937. params = []
  938. elif operator == '=?':
  939. if right is False or right is None:
  940. # '=?' is a short-circuit that makes the term TRUE if right is None or False
  941. query = 'TRUE'
  942. params = []
  943. else:
  944. # '=?' behaves like '=' in other cases
  945. query, params = self.__leaf_to_sql((left, '=', right), model, alias)
  946. else:
  947. field = model._fields.get(left)
  948. if field is None:
  949. raise ValueError("Invalid field %r in domain term %r" % (left, leaf))
  950. need_wildcard = operator in ('like', 'ilike', 'not like', 'not ilike')
  951. sql_operator = {'=like': 'like', '=ilike': 'ilike'}.get(operator, operator)
  952. cast = '::text' if sql_operator.endswith('like') else ''
  953. unaccent = self._unaccent(field) if sql_operator.endswith('like') else lambda x: x
  954. column = '%s.%s' % (table_alias, _quote(left))
  955. query = f'({unaccent(column + cast)} {sql_operator} {unaccent("%s")})'
  956. if (need_wildcard and not right) or (right and operator in NEGATIVE_TERM_OPERATORS):
  957. query = '(%s OR %s."%s" IS NULL)' % (query, table_alias, left)
  958. if need_wildcard:
  959. params = ['%%%s%%' % pycompat.to_text(right)]
  960. else:
  961. params = [field.convert_to_column(right, model, validate=False)]
  962. return query, params
  963. def to_sql(self):
  964. warnings.warn("deprecated expression.to_sql(), use expression.query instead",
  965. DeprecationWarning)
  966. return self.result