gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1443 lines
61KB

  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. Odoo will use the SQL function 'unaccent' when available for the
  46. 'ilike', 'not ilike' and '=ilike' operators, and enabled in the configuration.
  47. .. todo: The following explanation should be moved in some external
  48. installation guide
  49. The steps to install the module might differ on specific PostgreSQL
  50. versions. We give here some instruction for PostgreSQL 9.x on a
  51. Ubuntu system.
  52. Ubuntu doesn't come yet with PostgreSQL 9.x, so an alternative package
  53. source is used. We use Martin Pitt's PPA available at
  54. `ppa:pitti/postgresql
  55. <https://launchpad.net/~pitti/+archive/postgresql>`_.
  56. .. code-block:: sh
  57. > sudo add-apt-repository ppa:pitti/postgresql
  58. > sudo apt-get update
  59. Once the package list is up-to-date, you have to install PostgreSQL
  60. 9.0 and its contrib modules.
  61. .. code-block:: sh
  62. > sudo apt-get install postgresql-9.0 postgresql-contrib-9.0
  63. When you want to enable unaccent on some database:
  64. .. code-block:: sh
  65. > psql9 <database> -f /usr/share/postgresql/9.0/contrib/unaccent.sql
  66. Here :program:`psql9` is an alias for the newly installed PostgreSQL
  67. 9.0 tool, together with the correct port if necessary (for instance if
  68. PostgreSQL 8.4 is running on 5432). (Other aliases can be used for
  69. createdb and dropdb.)
  70. .. code-block:: sh
  71. > alias psql9='/usr/lib/postgresql/9.0/bin/psql -p 5433'
  72. You can check unaccent is working:
  73. .. code-block:: sh
  74. > psql9 <database> -c"select unaccent('hélène')"
  75. Finally, to instruct OpenERP to really use the unaccent function, you have to
  76. start the server specifying the ``--unaccent`` flag.
  77. """
  78. import collections
  79. import collections.abc
  80. import json
  81. import logging
  82. import pytz
  83. import reprlib
  84. import traceback
  85. import warnings
  86. from datetime import date, datetime, time
  87. import odoo.modules
  88. from odoo.models import check_property_field_value_name, READ_GROUP_NUMBER_GRANULARITY
  89. from odoo.tools import Query, SQL, get_lang
  90. from odoo.tools.sql import pattern_to_translated_trigram_pattern, value_to_translated_trigram_pattern
  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. TERM_OPERATORS = ('=', '!=', '<=', '<', '>', '>=', '=?', '=like', '=ilike',
  102. 'like', 'not like', 'ilike', 'not ilike', 'in', 'not in',
  103. 'child_of', 'parent_of', 'any', 'not any')
  104. # A subset of the above operators, with a 'negative' semantic. When the
  105. # expressions 'in NEGATIVE_TERM_OPERATORS' or 'not in NEGATIVE_TERM_OPERATORS' are used in the code
  106. # below, this doesn't necessarily mean that any of those NEGATIVE_TERM_OPERATORS is
  107. # legal in the processed term.
  108. NEGATIVE_TERM_OPERATORS = ('!=', 'not like', 'not ilike', 'not in')
  109. # Negation of domain expressions
  110. DOMAIN_OPERATORS_NEGATION = {
  111. AND_OPERATOR: OR_OPERATOR,
  112. OR_OPERATOR: AND_OPERATOR,
  113. }
  114. TERM_OPERATORS_NEGATION = {
  115. '<': '>=',
  116. '>': '<=',
  117. '<=': '>',
  118. '>=': '<',
  119. '=': '!=',
  120. '!=': '=',
  121. 'in': 'not in',
  122. 'like': 'not like',
  123. 'ilike': 'not ilike',
  124. 'not in': 'in',
  125. 'not like': 'like',
  126. 'not ilike': 'ilike',
  127. 'any': 'not any',
  128. 'not any': 'any',
  129. }
  130. WILDCARD_OPERATORS = ('like', 'ilike', 'not like', 'not ilike')
  131. ANY_IN = {'any': 'in', 'not any': 'not in'}
  132. TRUE_LEAF = (1, '=', 1)
  133. FALSE_LEAF = (0, '=', 1)
  134. TRUE_DOMAIN = [TRUE_LEAF]
  135. FALSE_DOMAIN = [FALSE_LEAF]
  136. SQL_OPERATORS = {
  137. '=': SQL('='),
  138. '!=': SQL('!='),
  139. '<=': SQL('<='),
  140. '<': SQL('<'),
  141. '>': SQL('>'),
  142. '>=': SQL('>='),
  143. 'in': SQL('IN'),
  144. 'not in': SQL('NOT IN'),
  145. '=like': SQL('LIKE'),
  146. '=ilike': SQL('ILIKE'),
  147. 'like': SQL('LIKE'),
  148. 'ilike': SQL('ILIKE'),
  149. 'not like': SQL('NOT LIKE'),
  150. 'not ilike': SQL('NOT ILIKE'),
  151. }
  152. _logger = logging.getLogger(__name__)
  153. # --------------------------------------------------
  154. # Generic domain manipulation
  155. # --------------------------------------------------
  156. def normalize_domain(domain):
  157. """Returns a normalized version of ``domain_expr``, where all implicit '&' operators
  158. have been made explicit. One property of normalized domain expressions is that they
  159. can be easily combined together as if they were single domain components.
  160. """
  161. assert isinstance(domain, (list, tuple)), "Domains to normalize must have a 'domain' form: a list or tuple of domain components"
  162. if not domain:
  163. return [TRUE_LEAF]
  164. result = []
  165. expected = 1 # expected number of expressions
  166. op_arity = {NOT_OPERATOR: 1, AND_OPERATOR: 2, OR_OPERATOR: 2}
  167. for token in domain:
  168. if expected == 0: # more than expected, like in [A, B]
  169. result[0:0] = [AND_OPERATOR] # put an extra '&' in front
  170. expected = 1
  171. if isinstance(token, (list, tuple)): # domain term
  172. expected -= 1
  173. if len(token) == 3 and token[1] in ('any', 'not any'):
  174. token = (token[0], token[1], normalize_domain(token[2]))
  175. else:
  176. token = tuple(token)
  177. else:
  178. expected += op_arity.get(token, 0) - 1
  179. result.append(token)
  180. if expected:
  181. raise ValueError(f'Domain {domain} is syntactically not correct.')
  182. return result
  183. def is_false(model, domain):
  184. """ Return whether ``domain`` is logically equivalent to false. """
  185. # use three-valued logic: -1 is false, 0 is unknown, +1 is true
  186. stack = []
  187. for token in reversed(normalize_domain(domain)):
  188. if token == '&':
  189. stack.append(min(stack.pop(), stack.pop()))
  190. elif token == '|':
  191. stack.append(max(stack.pop(), stack.pop()))
  192. elif token == '!':
  193. stack.append(-stack.pop())
  194. elif token == TRUE_LEAF:
  195. stack.append(+1)
  196. elif token == FALSE_LEAF:
  197. stack.append(-1)
  198. elif token[1] == 'in' and not (isinstance(token[2], Query) or token[2]):
  199. stack.append(-1)
  200. elif token[1] == 'not in' and not (isinstance(token[2], Query) or token[2]):
  201. stack.append(+1)
  202. else:
  203. stack.append(0)
  204. return stack.pop() == -1
  205. def combine(operator, unit, zero, domains):
  206. """Returns a new domain expression where all domain components from ``domains``
  207. have been added together using the binary operator ``operator``.
  208. It is guaranteed to return a normalized domain.
  209. :param operator:
  210. :param unit: the identity element of the domains "set" with regard to the operation
  211. performed by ``operator``, i.e the domain component ``i`` which, when
  212. combined with any domain ``x`` via ``operator``, yields ``x``.
  213. E.g. [(1,'=',1)] is the typical unit for AND_OPERATOR: adding it
  214. to any domain component gives the same domain.
  215. :param zero: the absorbing element of the domains "set" with regard to the operation
  216. performed by ``operator``, i.e the domain component ``z`` which, when
  217. combined with any domain ``x`` via ``operator``, yields ``z``.
  218. E.g. [(1,'=',1)] is the typical zero for OR_OPERATOR: as soon as
  219. you see it in a domain component the resulting domain is the zero.
  220. :param domains: a list of normalized domains.
  221. """
  222. result = []
  223. count = 0
  224. for domain in domains:
  225. domain = normalize_domain(domain)
  226. if domain == unit:
  227. continue
  228. if domain == zero:
  229. return zero
  230. result += domain
  231. count += 1
  232. result = [operator] * (count - 1) + result
  233. return result or unit
  234. def AND(domains):
  235. """AND([D1,D2,...]) returns a domain representing D1 and D2 and ... """
  236. return combine(AND_OPERATOR, [TRUE_LEAF], [FALSE_LEAF], domains)
  237. def OR(domains):
  238. """OR([D1,D2,...]) returns a domain representing D1 or D2 or ... """
  239. return combine(OR_OPERATOR, [FALSE_LEAF], [TRUE_LEAF], domains)
  240. def distribute_not(domain):
  241. """ Distribute any '!' domain operators found inside a normalized domain.
  242. Because we don't use SQL semantic for processing a 'left not in right'
  243. query (i.e. our 'not in' is not simply translated to a SQL 'not in'),
  244. it means that a '! left in right' can not be simply processed
  245. by model._condition_to_sql by first emitting code for 'left in right' then wrapping
  246. the result with 'not (...)', as it would result in a 'not in' at the SQL
  247. level.
  248. This function is thus responsible for pushing any '!' domain operators
  249. inside the terms themselves. For example::
  250. ['!','&',('user_id','=',4),('partner_id','in',[1,2])]
  251. will be turned into:
  252. ['|',('user_id','!=',4),('partner_id','not in',[1,2])]
  253. """
  254. # This is an iterative version of a recursive function that split domain
  255. # into subdomains, processes them and combine the results. The "stack" below
  256. # represents the recursive calls to be done.
  257. result = []
  258. stack = [False]
  259. for token in domain:
  260. negate = stack.pop()
  261. # negate tells whether the subdomain starting with token must be negated
  262. if is_leaf(token):
  263. if negate:
  264. left, operator, right = token
  265. if operator in TERM_OPERATORS_NEGATION and (isinstance(left, int) or "." not in left):
  266. # rewrite using the negated operator, except for relationship traversal
  267. # because not ('a.b', '=', x) should become ('a', 'not any', ('b', '=', x))
  268. if token in (TRUE_LEAF, FALSE_LEAF):
  269. result.append(FALSE_LEAF if token == TRUE_LEAF else TRUE_LEAF)
  270. else:
  271. result.append((left, TERM_OPERATORS_NEGATION[operator], right))
  272. else:
  273. result.append(NOT_OPERATOR)
  274. result.append(token)
  275. else:
  276. result.append(token)
  277. elif token == NOT_OPERATOR:
  278. stack.append(not negate)
  279. elif token in DOMAIN_OPERATORS_NEGATION:
  280. result.append(DOMAIN_OPERATORS_NEGATION[token] if negate else token)
  281. stack.append(negate)
  282. stack.append(negate)
  283. else:
  284. result.append(token)
  285. return result
  286. def _anyfy_leaves(domain, model):
  287. """ Return the domain where all conditions on field sequences have been
  288. transformed into 'any' conditions.
  289. """
  290. result = []
  291. for item in domain:
  292. if is_operator(item):
  293. result.append(item)
  294. continue
  295. left, operator, right = item = tuple(item)
  296. if is_boolean(item):
  297. result.append(item)
  298. continue
  299. path = left.split('.', 1)
  300. field = model._fields.get(path[0])
  301. if not field:
  302. raise ValueError(f"Invalid field {model._name}.{path[0]} in leaf {item}")
  303. if len(path) > 1 and field.relational: # skip properties
  304. subdomain = [(path[1], operator, right)]
  305. comodel = model.env[field.comodel_name]
  306. result.append((path[0], 'any', _anyfy_leaves(subdomain, comodel)))
  307. elif operator in ('any', 'not any'):
  308. comodel = model.env[field.comodel_name]
  309. result.append((left, operator, _anyfy_leaves(right, comodel)))
  310. else:
  311. result.append(item)
  312. return result
  313. def _tree_from_domain(domain):
  314. """ Return the domain as a tree, with the following structure::
  315. <tree> ::= ('?', <boolean>)
  316. | ('!', <tree>)
  317. | ('&', <tree>, <tree>, ...)
  318. | ('|', <tree>, <tree>, ...)
  319. | (<comparator>, <fname>, <value>)
  320. By construction, AND (``&``) and OR (``|``) nodes are n-ary and have at
  321. least two children. Moreover, AND nodes (respectively OR nodes) do not have
  322. AND nodes (resp. OR nodes) in their children.
  323. """
  324. stack = []
  325. for item in reversed(domain):
  326. if item == '!':
  327. stack.append(_tree_not(stack.pop()))
  328. elif item == '&':
  329. stack.append(_tree_and((stack.pop(), stack.pop())))
  330. elif item == '|':
  331. stack.append(_tree_or((stack.pop(), stack.pop())))
  332. elif item == TRUE_LEAF:
  333. stack.append(('?', True))
  334. elif item == FALSE_LEAF:
  335. stack.append(('?', False))
  336. else:
  337. lhs, comparator, rhs = item
  338. if comparator in ('any', 'not any'):
  339. rhs = _tree_from_domain(rhs)
  340. stack.append((comparator, lhs, rhs))
  341. return _tree_and(reversed(stack))
  342. def _tree_not(tree):
  343. """ Negate a tree node. """
  344. if tree[0] == '=?':
  345. # already update operator '=?' here, so that '!' is distributed correctly
  346. assert len(tree) == 3
  347. if tree[2]:
  348. tree = ('=', tree[1], tree[2])
  349. else:
  350. return ('?', False)
  351. if tree[0] == '?':
  352. return ('?', not tree[1])
  353. if tree[0] == '!':
  354. return tree[1]
  355. if tree[0] == '&':
  356. return ('|', *(_tree_not(item) for item in tree[1:]))
  357. if tree[0] == '|':
  358. return ('&', *(_tree_not(item) for item in tree[1:]))
  359. if tree[0] in TERM_OPERATORS_NEGATION:
  360. return (TERM_OPERATORS_NEGATION[tree[0]], tree[1], tree[2])
  361. return ('!', tree)
  362. def _tree_and(trees):
  363. """ Return the tree given by AND-ing all the given trees. """
  364. children = []
  365. for tree in trees:
  366. if tree == ('?', True):
  367. pass
  368. elif tree == ('?', False):
  369. return tree
  370. elif tree[0] == '&':
  371. children.extend(tree[1:])
  372. else:
  373. children.append(tree)
  374. if not children:
  375. return ('?', True)
  376. if len(children) == 1:
  377. return children[0]
  378. return ('&', *children)
  379. def _tree_or(trees):
  380. """ Return the tree given by OR-ing all the given trees. """
  381. children = []
  382. for tree in trees:
  383. if tree == ('?', True):
  384. return tree
  385. elif tree == ('?', False):
  386. pass
  387. elif tree[0] == '|':
  388. children.extend(tree[1:])
  389. else:
  390. children.append(tree)
  391. if not children:
  392. return ('?', False)
  393. if len(children) == 1:
  394. return children[0]
  395. return ('|', *children)
  396. def _tree_combine_anies(tree, model):
  397. """ Return the tree given by recursively merging 'any' and 'not any' nodes,
  398. according to the following logical equivalences:
  399. * (fname ANY dom1) OR (fname ANY dom2) == (fname ANY (dom1 OR dom2))
  400. * (fname NOT ANY dom1) AND (fname NOT ANY dom2) == (fname NOT ANY (dom1 OR dom2))
  401. We also merge 'any' and 'not any' nodes according to the following logical
  402. equivalences *for many2one fields only*:
  403. * (fname NOT ANY dom1) OR (fname NOT ANY dom2) == (fname NOT ANY (dom1 AND dom2))
  404. * (fname ANY dom1) AND (fname ANY dom2) == (fname ANY (dom1 AND dom2))
  405. """
  406. # first proceed recursively on subtrees
  407. if tree[0] == '!':
  408. tree = _tree_not(_tree_combine_anies(tree[1], model))
  409. elif tree[0] == '&':
  410. temp = [_tree_combine_anies(subtree, model) for subtree in tree[1:]]
  411. tree = _tree_and(temp)
  412. elif tree[0] == '|':
  413. temp = [_tree_combine_anies(subtree, model) for subtree in tree[1:]]
  414. tree = _tree_or(temp)
  415. # proceed recursively on subdomains
  416. if tree[0] == 'any':
  417. field = model._fields[tree[1]]
  418. comodel = model.env[field.comodel_name]
  419. return ('any', tree[1], _tree_combine_anies(tree[2], comodel))
  420. if tree[0] == 'not any':
  421. field = model._fields[tree[1]]
  422. comodel = model.env[field.comodel_name]
  423. return ('not any', tree[1], _tree_combine_anies(tree[2], comodel))
  424. if tree[0] not in ('&', '|'):
  425. return tree
  426. # tree is either an '&' or an '|' tree; group leaves using 'any' or 'not any'
  427. children = []
  428. any_children = collections.defaultdict(list)
  429. not_any_children = collections.defaultdict(list)
  430. for subtree in tree[1:]:
  431. if subtree[0] == 'any':
  432. any_children[subtree[1]].append(subtree[2])
  433. elif subtree[0] == 'not any':
  434. not_any_children[subtree[1]].append(subtree[2])
  435. else:
  436. children.append(subtree)
  437. if tree[0] == '&':
  438. # merge subdomains where possible
  439. for fname, subtrees in any_children.items():
  440. field = model._fields[fname]
  441. comodel = model.env[field.comodel_name]
  442. if field.type == 'many2one' and len(subtrees) > 1:
  443. # (fname ANY dom1) AND (fname ANY dom2) == (fname ANY (dom1 AND dom2))
  444. children.append(('any', fname, _tree_combine_anies(_tree_and(subtrees), comodel)))
  445. else:
  446. for subtree in subtrees:
  447. children.append(('any', fname, _tree_combine_anies(subtree, comodel)))
  448. for fname, subtrees in not_any_children.items():
  449. # (fname NOT ANY dom1) AND (fname NOT ANY dom2) == (fname NOT ANY (dom1 OR dom2))
  450. field = model._fields[fname]
  451. comodel = model.env[field.comodel_name]
  452. children.append(('not any', fname, _tree_combine_anies(_tree_or(subtrees), comodel)))
  453. return _tree_and(children)
  454. else:
  455. # merge subdomains where possible
  456. for fname, subtrees in any_children.items():
  457. # (fname ANY dom1) OR (fname ANY dom2) == (fname ANY (dom1 OR dom2))
  458. field = model._fields[fname]
  459. comodel = model.env[field.comodel_name]
  460. children.append(('any', fname, _tree_combine_anies(_tree_or(subtrees), comodel)))
  461. for fname, subtrees in not_any_children.items():
  462. field = model._fields[fname]
  463. comodel = model.env[field.comodel_name]
  464. if field.type == 'many2one' and len(subtrees) > 1:
  465. # (fname NOT ANY dom1) OR (fname NOT ANY dom2) == (fname NOT ANY (dom1 AND dom2))
  466. children.append(('not any', fname, _tree_combine_anies(_tree_and(subtrees), comodel)))
  467. else:
  468. for subtree in subtrees:
  469. children.append(('not any', fname, _tree_combine_anies(subtree, comodel)))
  470. return _tree_or(children)
  471. def _tree_as_domain(tree):
  472. """ Return the domain list represented by the given domain tree. """
  473. def _flatten(tree):
  474. if tree[0] == '?':
  475. yield TRUE_LEAF if tree[1] else FALSE_LEAF
  476. elif tree[0] == '!':
  477. yield tree[0]
  478. yield from _flatten(tree[1])
  479. elif tree[0] in ('&', '|'):
  480. yield from tree[0] * (len(tree) - 2)
  481. for subtree in tree[1:]:
  482. yield from _flatten(subtree)
  483. elif tree[0] in ('any', 'not any'):
  484. yield (tree[1], tree[0], _tree_as_domain(tree[2]))
  485. else:
  486. yield (tree[1], tree[0], tree[2])
  487. return list(_flatten(tree))
  488. def domain_combine_anies(domain, model):
  489. """ Return a domain equivalent to the given one where 'any' and 'not any'
  490. conditions have been combined in order to generate less subqueries.
  491. """
  492. domain_any = _anyfy_leaves(domain, model)
  493. tree = _tree_from_domain(domain_any)
  494. merged_tree = _tree_combine_anies(tree, model)
  495. new_domain = _tree_as_domain(merged_tree)
  496. return new_domain
  497. def prettify_domain(domain, pre_indent=0):
  498. """
  499. Pretty-format a domain into a string by separating each leaf on a
  500. separated line and by including some indentation. Works with ``any``
  501. and ``not any`` too. The domain must be normalized.
  502. :param list domain: a normalized domain
  503. :param int pre_indent: (optinal) a starting indentation level
  504. :return: the domain prettified
  505. :rtype: str
  506. """
  507. # The ``stack`` is a stack of layers, each layer accumulates the
  508. # ``terms`` (leaves/operators) that share a same indentation
  509. # level (the depth of the layer inside the stack). ``left_count``
  510. # tracks how many terms should still appear on each layer before the
  511. # layer is considered complete.
  512. #
  513. # When a layer is completed, it is removed from the stack and
  514. # commited, i.e. its terms added to the ``commits`` list along with
  515. # the indentation for those terms.
  516. #
  517. # When a new operator is added to the layer terms, the current layer
  518. # is commited (but not removed from the stack if there are still
  519. # some terms that must be added) and a new (empty) layer is added on
  520. # top of the stack.
  521. #
  522. # When the domain has been fully iterated, the commits are used to
  523. # craft the final string. All terms are indented according to their
  524. # commit indentation level and separated by a new line.
  525. stack = [{'left_count': 1, 'terms': []}]
  526. commits = []
  527. for term in domain:
  528. top = stack[-1]
  529. if is_operator(term):
  530. # when a same operator appears twice in a row, we want to
  531. # include the second one on the same line as the former one
  532. if (not top['terms'] and commits
  533. and (commits[-1]['terms'] or [''])[-1].startswith(repr(term))):
  534. commits[-1]['terms'][-1] += f", {term!r}" # hack
  535. top['left_count'] += 0 if term == NOT_OPERATOR else 1
  536. else:
  537. commits.append({
  538. 'indent': len(stack) - 1,
  539. 'terms': top['terms'] + [repr(term)]
  540. })
  541. top['terms'] = []
  542. top['left_count'] -= 1
  543. stack.append({
  544. 'left_count': 1 if term == NOT_OPERATOR else 2,
  545. 'terms': [],
  546. })
  547. top = stack[-1]
  548. elif term[1] in ('any', 'not any'):
  549. top['terms'].append('({!r}, {!r}, {})'.format(
  550. term[0], term[1], prettify_domain(term[2], pre_indent + len(stack) - 1)))
  551. top['left_count'] -= 1
  552. else:
  553. top['terms'].append(repr(term))
  554. top['left_count'] -= 1
  555. if not top['left_count']:
  556. commits.append({
  557. 'indent': len(stack) - 1,
  558. 'terms': top['terms']
  559. })
  560. stack.pop()
  561. return '[{}]'.format(
  562. f",\n{' ' * pre_indent}".join([
  563. f"{' ' * commit['indent']}{term}"
  564. for commit in commits
  565. for term in commit['terms']
  566. ])
  567. )
  568. # --------------------------------------------------
  569. # Generic leaf manipulation
  570. # --------------------------------------------------
  571. def normalize_leaf(element):
  572. """ Change a term's operator to some canonical form, simplifying later
  573. processing. """
  574. if not is_leaf(element):
  575. return element
  576. left, operator, right = element
  577. original = operator
  578. operator = operator.lower()
  579. if operator == '<>':
  580. operator = '!='
  581. if isinstance(right, bool) and operator in ('in', 'not in'):
  582. _logger.warning("The domain term '%s' should use the '=' or '!=' operator." % ((left, original, right),))
  583. operator = '=' if operator == 'in' else '!='
  584. if isinstance(right, (list, tuple)) and operator in ('=', '!='):
  585. _logger.warning("The domain term '%s' should use the 'in' or 'not in' operator." % ((left, original, right),))
  586. operator = 'in' if operator == '=' else 'not in'
  587. return left, operator, right
  588. def is_operator(element):
  589. """ Test whether an object is a valid domain operator. """
  590. return isinstance(element, str) and element in DOMAIN_OPERATORS
  591. def is_leaf(element):
  592. """ Test whether an object is a valid domain term:
  593. - is a list or tuple
  594. - with 3 elements
  595. - second element if a valid op
  596. :param tuple element: a leaf in form (left, operator, right)
  597. Note: OLD TODO change the share wizard to use this function.
  598. """
  599. INTERNAL_OPS = TERM_OPERATORS + ('<>',)
  600. return (isinstance(element, tuple) or isinstance(element, list)) \
  601. and len(element) == 3 \
  602. and element[1] in INTERNAL_OPS \
  603. and ((isinstance(element[0], str) and element[0])
  604. or tuple(element) in (TRUE_LEAF, FALSE_LEAF))
  605. def is_boolean(element):
  606. return element == TRUE_LEAF or element == FALSE_LEAF
  607. def check_leaf(element):
  608. if not is_operator(element) and not is_leaf(element):
  609. raise ValueError("Invalid leaf %s" % str(element))
  610. # --------------------------------------------------
  611. # SQL utils
  612. # --------------------------------------------------
  613. def get_unaccent_wrapper(cr):
  614. warnings.warn(
  615. "Since 18.0, deprecated method, use env.registry.unaccent instead",
  616. DeprecationWarning, 2,
  617. )
  618. return odoo.modules.registry.Registry(cr.dbname).unaccent
  619. class expression(object):
  620. """ Parse a domain expression
  621. Use a real polish notation
  622. Leafs are still in a ('foo', '=', 'bar') format
  623. For more info: http://christophe-simonis-at-tiny.blogspot.com/2008/08/new-new-domain-notation.html
  624. """
  625. def __init__(self, domain, model, alias=None, query=None):
  626. """ Initialize expression object and automatically parse the expression
  627. right after initialization.
  628. :param domain: expression (using domain ('foo', '=', 'bar') format)
  629. :param model: root model
  630. :param alias: alias for the model table if query is provided
  631. :param query: optional query object holding the final result
  632. :attr root_model: base model for the query
  633. :attr expression: the domain to parse, normalized and prepared
  634. :attr result: the result of the parsing, as a pair (query, params)
  635. :attr query: Query object holding the final result
  636. """
  637. self._unaccent = model.pool.unaccent
  638. self._has_trigram = model.pool.has_trigram
  639. self.root_model = model
  640. self.root_alias = alias or model._table
  641. # normalize and prepare the expression for parsing
  642. self.expression = domain_combine_anies(domain, model)
  643. # this object handles all the joins
  644. self.query = Query(model.env, model._table, model._table_sql) if query is None else query
  645. # parse the domain expression
  646. self.parse()
  647. # ----------------------------------------
  648. # Parsing
  649. # ----------------------------------------
  650. def parse(self):
  651. """ Transform the leaves of the expression
  652. The principle is to pop elements from a leaf stack one at a time.
  653. Each leaf is processed. The processing is a if/elif list of various
  654. cases that appear in the leafs (many2one, function fields, ...).
  655. Three things can happen as a processing result:
  656. - the leaf is a logic operator, and updates the result stack
  657. accordingly;
  658. - the leaf has been modified and/or new leafs have to be introduced
  659. in the expression; they are pushed into the leaf stack, to be
  660. processed right after;
  661. - the leaf is converted to SQL and added to the result stack
  662. Example:
  663. =================== =================== =====================
  664. step stack result_stack
  665. =================== =================== =====================
  666. ['&', A, B] []
  667. substitute B ['&', A, B1] []
  668. convert B1 in SQL ['&', A] ["B1"]
  669. substitute A ['&', '|', A1, A2] ["B1"]
  670. convert A2 in SQL ['&', '|', A1] ["B1", "A2"]
  671. convert A1 in SQL ['&', '|'] ["B1", "A2", "A1"]
  672. apply operator OR ['&'] ["B1", "A1 or A2"]
  673. apply operator AND [] ["(A1 or A2) and B1"]
  674. =================== =================== =====================
  675. Some internal var explanation:
  676. :var list path: left operand seen as a sequence of field names
  677. ("foo.bar" -> ["foo", "bar"])
  678. :var obj model: model object, model containing the field
  679. (the name provided in the left operand)
  680. :var obj field: the field corresponding to `path[0]`
  681. :var obj column: the column corresponding to `path[0]`
  682. :var obj comodel: relational model of field (field.comodel)
  683. (res_partner.bank_ids -> res.partner.bank)
  684. """
  685. def to_ids(value, comodel, leaf):
  686. """ Normalize a single id or name, or a list of those, into a list of ids
  687. :param comodel:
  688. :param leaf:
  689. :param int|str|list|tuple value:
  690. - if int, long -> return [value]
  691. - if basestring, convert it into a list of basestrings, then
  692. - if list of basestring ->
  693. - perform a name_search on comodel for each name
  694. - return the list of related ids
  695. """
  696. names = []
  697. if isinstance(value, str):
  698. names = [value]
  699. elif value and isinstance(value, (tuple, list)) and all(isinstance(item, str) for item in value):
  700. names = value
  701. elif isinstance(value, int):
  702. if not value:
  703. # given this nonsensical domain, it is generally cheaper to
  704. # interpret False as [], so that "X child_of False" will
  705. # match nothing
  706. _logger.warning("Unexpected domain [%s], interpreted as False", leaf)
  707. return []
  708. return [value]
  709. if names:
  710. return list({
  711. rid
  712. for name in names
  713. for rid in comodel._search([('display_name', 'ilike', name)])
  714. })
  715. return list(value)
  716. def child_of_domain(left, ids, left_model, parent=None, prefix=''):
  717. """ Return a domain implementing the child_of operator for [(left,child_of,ids)],
  718. either as a range using the parent_path tree lookup field
  719. (when available), or as an expanded [(left,in,child_ids)] """
  720. if not ids:
  721. return [FALSE_LEAF]
  722. left_model_sudo = left_model.sudo().with_context(active_test=False)
  723. if left_model._parent_store:
  724. domain = OR([
  725. [('parent_path', '=like', rec.parent_path + '%')]
  726. for rec in left_model_sudo.browse(ids)
  727. ])
  728. else:
  729. # recursively retrieve all children nodes with sudo(); the
  730. # filtering of forbidden records is done by the rest of the
  731. # domain
  732. parent_name = parent or left_model._parent_name
  733. if (left_model._name != left_model._fields[parent_name].comodel_name):
  734. raise ValueError(f"Invalid parent field: {left_model._fields[parent_name]}")
  735. child_ids = set()
  736. records = left_model_sudo.browse(ids)
  737. while records:
  738. child_ids.update(records._ids)
  739. records = records.search([(parent_name, 'in', records.ids)], order='id') - records.browse(child_ids)
  740. domain = [('id', 'in', list(child_ids))]
  741. if prefix:
  742. return [(left, 'in', left_model_sudo._search(domain))]
  743. return domain
  744. def parent_of_domain(left, ids, left_model, parent=None, prefix=''):
  745. """ Return a domain implementing the parent_of operator for [(left,parent_of,ids)],
  746. either as a range using the parent_path tree lookup field
  747. (when available), or as an expanded [(left,in,parent_ids)] """
  748. ids = [id for id in ids if id] # ignore (left, 'parent_of', [False])
  749. if not ids:
  750. return [FALSE_LEAF]
  751. left_model_sudo = left_model.sudo().with_context(active_test=False)
  752. if left_model._parent_store:
  753. parent_ids = [
  754. int(label)
  755. for rec in left_model_sudo.browse(ids)
  756. for label in rec.parent_path.split('/')[:-1]
  757. ]
  758. domain = [('id', 'in', parent_ids)]
  759. else:
  760. # recursively retrieve all parent nodes with sudo() to avoid
  761. # access rights errors; the filtering of forbidden records is
  762. # done by the rest of the domain
  763. parent_name = parent or left_model._parent_name
  764. parent_ids = set()
  765. records = left_model_sudo.browse(ids)
  766. while records:
  767. parent_ids.update(records._ids)
  768. records = records[parent_name] - records.browse(parent_ids)
  769. domain = [('id', 'in', list(parent_ids))]
  770. if prefix:
  771. return [(left, 'in', left_model_sudo._search(domain))]
  772. return domain
  773. HIERARCHY_FUNCS = {'child_of': child_of_domain,
  774. 'parent_of': parent_of_domain}
  775. def pop():
  776. """ Pop a leaf to process. """
  777. return stack.pop()
  778. def push(leaf, model, alias):
  779. """ Push a leaf to be processed right after. """
  780. leaf = normalize_leaf(leaf)
  781. check_leaf(leaf)
  782. stack.append((leaf, model, alias))
  783. def pop_result():
  784. return result_stack.pop()
  785. def push_result(sql):
  786. result_stack.append(sql)
  787. # process domain from right to left; stack contains domain leaves, in
  788. # the form: (leaf, corresponding model, corresponding table alias)
  789. stack = []
  790. for leaf in self.expression:
  791. push(leaf, self.root_model, self.root_alias)
  792. # stack of SQL expressions
  793. result_stack = []
  794. while stack:
  795. # Get the next leaf to process
  796. leaf, model, alias = pop()
  797. # ----------------------------------------
  798. # SIMPLE CASE
  799. # 1. leaf is an operator
  800. # 2. leaf is a true/false leaf
  801. # -> convert and add directly to result
  802. # ----------------------------------------
  803. if is_operator(leaf):
  804. if leaf == NOT_OPERATOR:
  805. push_result(SQL("(NOT (%s))", pop_result()))
  806. elif leaf == AND_OPERATOR:
  807. push_result(SQL("(%s AND %s)", pop_result(), pop_result()))
  808. else:
  809. push_result(SQL("(%s OR %s)", pop_result(), pop_result()))
  810. continue
  811. if leaf == TRUE_LEAF:
  812. push_result(SQL("TRUE"))
  813. continue
  814. if leaf == FALSE_LEAF:
  815. push_result(SQL("FALSE"))
  816. continue
  817. # Get working variables
  818. left, operator, right = leaf
  819. path = left.split('.', 1)
  820. field = model._fields[path[0]]
  821. if field.type == 'many2one':
  822. comodel = model.env[field.comodel_name].with_context(active_test=False)
  823. elif field.type in ('one2many', 'many2many'):
  824. comodel = model.env[field.comodel_name].with_context(**field.context)
  825. if (
  826. field.company_dependent
  827. and field.index == 'btree_not_null'
  828. and not isinstance(right, (SQL, Query))
  829. and not (field.type in ('datetime', 'date') and len(path) > 1) # READ_GROUP_NUMBER_GRANULARITY is not supported
  830. and model.env['ir.default']._evaluate_condition_with_fallback(model._name, leaf) is False
  831. ):
  832. push('&', model, alias)
  833. sql_col_is_not_null = SQL('%s.%s IS NOT NULL', SQL.identifier(alias), SQL.identifier(field.name))
  834. push_result(sql_col_is_not_null)
  835. if field.inherited:
  836. parent_model = model.env[field.related_field.model_name]
  837. parent_fname = model._inherits[parent_model._name]
  838. # LEFT JOIN parent_model._table AS parent_alias ON alias.parent_fname = parent_alias.id
  839. parent_alias = self.query.make_alias(alias, parent_fname)
  840. self.query.add_join('LEFT JOIN', parent_alias, parent_model._table, SQL(
  841. "%s = %s",
  842. model._field_to_sql(alias, parent_fname, self.query),
  843. SQL.identifier(parent_alias, 'id'),
  844. ))
  845. push(leaf, parent_model, parent_alias)
  846. elif left == 'id' and operator in HIERARCHY_FUNCS:
  847. ids2 = to_ids(right, model, leaf)
  848. dom = HIERARCHY_FUNCS[operator](left, ids2, model)
  849. for dom_leaf in dom:
  850. push(dom_leaf, model, alias)
  851. elif field.type == 'properties':
  852. if len(path) != 2 or "." in path[1]:
  853. raise ValueError(f"Wrong path {path}")
  854. elif operator not in ('=', '!=', '>', '>=', '<', '<=', 'in', 'not in', 'like', 'ilike', 'not like', 'not ilike'):
  855. raise ValueError(f"Wrong search operator {operator!r}")
  856. property_name = path[1]
  857. check_property_field_value_name(property_name)
  858. if (isinstance(right, bool) or right is None) and operator in ('=', '!='):
  859. # check for boolean value but also for key existence
  860. if right:
  861. # inverse the condition
  862. right = False
  863. operator = '!=' if operator == '=' else '='
  864. sql_field = model._field_to_sql(alias, field.name, self.query)
  865. sql_operator = SQL_OPERATORS[operator]
  866. sql_extra = SQL()
  867. if operator == '=': # property == False
  868. sql_extra = SQL(
  869. "OR (%s IS NULL) OR NOT (%s ? %s)",
  870. sql_field, sql_field, property_name,
  871. )
  872. push_result(SQL(
  873. "((%s -> %s) %s '%s' %s)",
  874. sql_field, property_name, sql_operator, right, sql_extra,
  875. ))
  876. else:
  877. sql_field = model._field_to_sql(alias, field.name, self.query)
  878. if operator in ('in', 'not in'):
  879. sql_not = SQL('NOT') if operator == 'not in' else SQL()
  880. sql_left = SQL("%s -> %s", sql_field, property_name) # raw value
  881. sql_operator = SQL('<@') if isinstance(right, (list, tuple)) else SQL('@>')
  882. sql_right = SQL("%s", json.dumps(right))
  883. push_result(SQL(
  884. "(%s (%s) %s (%s))",
  885. sql_not, sql_left, sql_operator, sql_right,
  886. ))
  887. elif isinstance(right, str):
  888. if operator in ('ilike', 'not ilike'):
  889. right = f'%{right}%'
  890. unaccent = self._unaccent
  891. else:
  892. unaccent = lambda x: x # noqa: E731
  893. sql_left = SQL("%s ->> %s", sql_field, property_name) # JSONified value
  894. sql_operator = SQL_OPERATORS[operator]
  895. sql_right = SQL("%s", right)
  896. push_result(SQL(
  897. "((%s) %s (%s))",
  898. unaccent(sql_left), sql_operator, unaccent(sql_right),
  899. ))
  900. else:
  901. sql_left = SQL("%s -> %s", sql_field, property_name) # raw value
  902. sql_operator = SQL_OPERATORS[operator]
  903. sql_right = SQL("%s", json.dumps(right))
  904. push_result(SQL(
  905. "((%s) %s (%s))",
  906. sql_left, sql_operator, sql_right,
  907. ))
  908. elif field.type in ('datetime', 'date') and len(path) == 2:
  909. if path[1] not in READ_GROUP_NUMBER_GRANULARITY:
  910. raise ValueError(f'Error when processing the field {field!r}, the granularity {path[1]} is not supported. Only {", ".join(READ_GROUP_NUMBER_GRANULARITY.keys())} are supported')
  911. sql_field = model._field_to_sql(alias, field.name, self.query)
  912. if model._context.get('tz') in pytz.all_timezones_set and field.type == 'datetime':
  913. sql_field = SQL("timezone(%s, timezone('UTC', %s))", model._context['tz'], sql_field)
  914. if path[1] == 'day_of_week':
  915. first_week_day = int(get_lang(model.env, model._context.get('tz')).week_start)
  916. sql = SQL("mod(7 - %s + date_part(%s, %s)::int, 7) %s %s", first_week_day, READ_GROUP_NUMBER_GRANULARITY[path[1]], sql_field, SQL_OPERATORS[operator], right)
  917. else:
  918. sql = SQL('date_part(%s, %s) %s %s', READ_GROUP_NUMBER_GRANULARITY[path[1]], sql_field, SQL_OPERATORS[operator], right)
  919. push_result(sql)
  920. # ----------------------------------------
  921. # PATH SPOTTED
  922. # -> many2one or one2many with _auto_join:
  923. # - add a join, then jump into linked column: column.remaining on
  924. # src_table is replaced by remaining on dst_table, and set for re-evaluation
  925. # - if a domain is defined on the column, add it into evaluation
  926. # on the relational table
  927. # -> many2one, many2many, one2many: replace by an equivalent computed
  928. # domain, given by recursively searching on the remaining of the path
  929. # -> note: hack about columns.property should not be necessary anymore
  930. # as after transforming the column, it will go through this loop once again
  931. # ----------------------------------------
  932. elif operator in ('any', 'not any') and field.store and field.type == 'many2one' and field.auto_join:
  933. # res_partner.state_id = res_partner__state_id.id
  934. coalias = self.query.make_alias(alias, field.name)
  935. self.query.add_join('LEFT JOIN', coalias, comodel._table, SQL(
  936. "%s = %s",
  937. model._field_to_sql(alias, field.name, self.query),
  938. SQL.identifier(coalias, 'id'),
  939. ))
  940. if operator == 'not any':
  941. right = ['|', ('id', '=', False), '!', *right]
  942. for leaf in right:
  943. push(leaf, comodel, coalias)
  944. elif operator in ('any', 'not any') and field.store and field.type == 'one2many' and field.auto_join:
  945. # use a subquery bypassing access rules and business logic
  946. domain = right + field.get_domain_list(model)
  947. query = comodel._where_calc(domain)
  948. sql = query.subselect(
  949. comodel._field_to_sql(comodel._table, field.inverse_name, query),
  950. )
  951. push(('id', ANY_IN[operator], sql), model, alias)
  952. elif operator in ('any', 'not any') and field.store and field.auto_join:
  953. raise NotImplementedError('auto_join attribute not supported on field %s' % field)
  954. elif operator in ('any', 'not any') and field.type == 'many2one':
  955. right_ids = comodel._search(right)
  956. if operator == 'any':
  957. push((left, 'in', right_ids), model, alias)
  958. else:
  959. for dom_leaf in ('|', (left, 'not in', right_ids), (left, '=', False)):
  960. push(dom_leaf, model, alias)
  961. # Making search easier when there is a left operand as one2many or many2many
  962. elif operator in ('any', 'not any') and field.type in ('many2many', 'one2many'):
  963. domain = field.get_domain_list(model)
  964. domain = AND([domain, right])
  965. right_ids = comodel._search(domain)
  966. push((left, ANY_IN[operator], right_ids), model, alias)
  967. elif not field.store:
  968. # Non-stored field should provide an implementation of search.
  969. if not field.search:
  970. # field does not support search!
  971. _logger.error("Non-stored field %s cannot be searched.", field, exc_info=True)
  972. if _logger.isEnabledFor(logging.DEBUG):
  973. _logger.debug(''.join(traceback.format_stack()))
  974. # Ignore it: generate a dummy leaf.
  975. domain = []
  976. else:
  977. # Let the field generate a domain.
  978. if len(path) > 1:
  979. right = comodel._search([(path[1], operator, right)])
  980. operator = 'in'
  981. domain = field.determine_domain(model, operator, right)
  982. for elem in domain_combine_anies(domain, model):
  983. push(elem, model, alias)
  984. # -------------------------------------------------
  985. # RELATIONAL FIELDS
  986. # -------------------------------------------------
  987. # Applying recursivity on field(one2many)
  988. elif field.type == 'one2many' and operator in HIERARCHY_FUNCS:
  989. ids2 = to_ids(right, comodel, leaf)
  990. if field.comodel_name != model._name:
  991. dom = HIERARCHY_FUNCS[operator](left, ids2, comodel, prefix=field.comodel_name)
  992. else:
  993. dom = HIERARCHY_FUNCS[operator]('id', ids2, comodel, parent=left)
  994. for dom_leaf in dom:
  995. push(dom_leaf, model, alias)
  996. elif field.type == 'one2many':
  997. domain = field.get_domain_list(model)
  998. inverse_field = comodel._fields[field.inverse_name]
  999. inverse_is_int = inverse_field.type in ('integer', 'many2one_reference')
  1000. unwrap_inverse = (lambda ids: ids) if inverse_is_int else (lambda recs: recs.ids)
  1001. if right is not False:
  1002. # determine ids2 in comodel
  1003. if isinstance(right, str):
  1004. op2 = (TERM_OPERATORS_NEGATION[operator]
  1005. if operator in NEGATIVE_TERM_OPERATORS else operator)
  1006. ids2 = comodel._search(AND([domain or [], [('display_name', op2, right)]]))
  1007. elif isinstance(right, collections.abc.Iterable):
  1008. ids2 = right
  1009. else:
  1010. ids2 = [right]
  1011. if inverse_is_int and domain:
  1012. ids2 = comodel._search([('id', 'in', ids2)] + domain)
  1013. if inverse_field.store:
  1014. # In the condition, one must avoid subqueries to return
  1015. # NULL values, since it makes the IN test NULL instead
  1016. # of FALSE. This may discard expected results, as for
  1017. # instance "id NOT IN (42, NULL)" is never TRUE.
  1018. sql_in = SQL('NOT IN') if operator in NEGATIVE_TERM_OPERATORS else SQL('IN')
  1019. if not isinstance(ids2, Query):
  1020. ids2 = comodel.browse(ids2)._as_query(ordered=False)
  1021. sql_inverse = comodel._field_to_sql(ids2.table, inverse_field.name, ids2)
  1022. if not inverse_field.required:
  1023. ids2.add_where(SQL("%s IS NOT NULL", sql_inverse))
  1024. if (inverse_field.company_dependent and inverse_field.index == 'btree_not_null'
  1025. and not inverse_field.get_company_dependent_fallback(comodel)):
  1026. ids2.add_where(SQL('%s IS NOT NULL', SQL.identifier(ids2.table, inverse_field.name)))
  1027. push_result(SQL(
  1028. "(%s %s %s)",
  1029. SQL.identifier(alias, 'id'),
  1030. sql_in,
  1031. ids2.subselect(sql_inverse),
  1032. ))
  1033. else:
  1034. # determine ids1 in model related to ids2
  1035. recs = comodel.browse(ids2).sudo().with_context(prefetch_fields=False)
  1036. ids1 = unwrap_inverse(recs.mapped(inverse_field.name))
  1037. # rewrite condition in terms of ids1
  1038. op1 = 'not in' if operator in NEGATIVE_TERM_OPERATORS else 'in'
  1039. push(('id', op1, ids1), model, alias)
  1040. else:
  1041. if inverse_field.store and not (inverse_is_int and domain):
  1042. # rewrite condition to match records with/without lines
  1043. sub_op = 'in' if operator in NEGATIVE_TERM_OPERATORS else 'not in'
  1044. comodel_domain = [(inverse_field.name, '!=', False)]
  1045. query = comodel._where_calc(comodel_domain)
  1046. sql_inverse = comodel._field_to_sql(query.table, inverse_field.name, query)
  1047. sql = query.subselect(sql_inverse)
  1048. push(('id', sub_op, sql), model, alias)
  1049. else:
  1050. comodel_domain = [(inverse_field.name, '!=', False)]
  1051. if inverse_is_int and domain:
  1052. comodel_domain += domain
  1053. recs = comodel.search(comodel_domain, order='id').sudo().with_context(prefetch_fields=False)
  1054. # determine ids1 = records with lines
  1055. ids1 = unwrap_inverse(recs.mapped(inverse_field.name))
  1056. # rewrite condition to match records with/without lines
  1057. op1 = 'in' if operator in NEGATIVE_TERM_OPERATORS else 'not in'
  1058. push(('id', op1, ids1), model, alias)
  1059. elif field.type == 'many2many':
  1060. rel_table, rel_id1, rel_id2 = field.relation, field.column1, field.column2
  1061. if operator in HIERARCHY_FUNCS:
  1062. # determine ids2 in comodel
  1063. ids2 = to_ids(right, comodel, leaf)
  1064. domain = HIERARCHY_FUNCS[operator]('id', ids2, comodel)
  1065. ids2 = comodel._search(domain)
  1066. rel_alias = self.query.make_alias(alias, field.name)
  1067. push_result(SQL(
  1068. "EXISTS (SELECT 1 FROM %s AS %s WHERE %s = %s AND %s IN %s)",
  1069. SQL.identifier(rel_table),
  1070. SQL.identifier(rel_alias),
  1071. SQL.identifier(rel_alias, rel_id1),
  1072. SQL.identifier(alias, 'id'),
  1073. SQL.identifier(rel_alias, rel_id2),
  1074. tuple(ids2) or (None,),
  1075. ))
  1076. elif right is not False:
  1077. # determine ids2 in comodel
  1078. if isinstance(right, str):
  1079. domain = field.get_domain_list(model)
  1080. op2 = (TERM_OPERATORS_NEGATION[operator]
  1081. if operator in NEGATIVE_TERM_OPERATORS else operator)
  1082. ids2 = comodel._search(AND([domain or [], [('display_name', op2, right)]]))
  1083. elif isinstance(right, collections.abc.Iterable):
  1084. ids2 = right
  1085. else:
  1086. ids2 = [right]
  1087. if isinstance(ids2, Query):
  1088. # rewrite condition in terms of ids2
  1089. sql_ids2 = ids2.subselect()
  1090. else:
  1091. # rewrite condition in terms of ids2
  1092. sql_ids2 = SQL("%s", tuple(it for it in ids2 if it) or (None,))
  1093. if operator in NEGATIVE_TERM_OPERATORS:
  1094. sql_exists = SQL('NOT EXISTS')
  1095. else:
  1096. sql_exists = SQL('EXISTS')
  1097. rel_alias = self.query.make_alias(alias, field.name)
  1098. push_result(SQL(
  1099. "%s (SELECT 1 FROM %s AS %s WHERE %s = %s AND %s IN %s)",
  1100. sql_exists,
  1101. SQL.identifier(rel_table),
  1102. SQL.identifier(rel_alias),
  1103. SQL.identifier(rel_alias, rel_id1),
  1104. SQL.identifier(alias, 'id'),
  1105. SQL.identifier(rel_alias, rel_id2),
  1106. sql_ids2,
  1107. ))
  1108. else:
  1109. # rewrite condition to match records with/without relations
  1110. if operator in NEGATIVE_TERM_OPERATORS:
  1111. sql_exists = SQL('EXISTS')
  1112. else:
  1113. sql_exists = SQL('NOT EXISTS')
  1114. rel_alias = self.query.make_alias(alias, field.name)
  1115. push_result(SQL(
  1116. "%s (SELECT 1 FROM %s AS %s WHERE %s = %s)",
  1117. sql_exists,
  1118. SQL.identifier(rel_table),
  1119. SQL.identifier(rel_alias),
  1120. SQL.identifier(rel_alias, rel_id1),
  1121. SQL.identifier(alias, 'id'),
  1122. ))
  1123. elif field.type == 'many2one':
  1124. if operator in HIERARCHY_FUNCS:
  1125. ids2 = to_ids(right, comodel, leaf)
  1126. if field.comodel_name != model._name:
  1127. dom = HIERARCHY_FUNCS[operator](left, ids2, comodel, prefix=field.comodel_name)
  1128. else:
  1129. dom = HIERARCHY_FUNCS[operator]('id', ids2, comodel, parent=left)
  1130. for dom_leaf in dom:
  1131. push(dom_leaf, model, alias)
  1132. elif (
  1133. isinstance(right, str)
  1134. or isinstance(right, (tuple, list)) and right and all(isinstance(item, str) for item in right)
  1135. ):
  1136. # resolve string-based m2o criterion into IDs subqueries
  1137. # Special treatment to ill-formed domains
  1138. operator = 'in' if operator in ('<', '>', '<=', '>=') else operator
  1139. dict_op = {'not in': '!=', 'in': '=', '=': 'in', '!=': 'not in'}
  1140. if isinstance(right, tuple):
  1141. right = list(right)
  1142. if not isinstance(right, list) and operator in ('not in', 'in'):
  1143. operator = dict_op[operator]
  1144. elif isinstance(right, list) and operator in ('!=', '='): # for domain (FIELD,'=',['value1','value2'])
  1145. operator = dict_op[operator]
  1146. if operator in NEGATIVE_TERM_OPERATORS:
  1147. res_ids = comodel._search([('display_name', TERM_OPERATORS_NEGATION[operator], right)])
  1148. for dom_leaf in ('|', (left, 'not in', res_ids), (left, '=', False)):
  1149. push(dom_leaf, model, alias)
  1150. else:
  1151. res_ids = comodel._search([('display_name', operator, right)])
  1152. push((left, 'in', res_ids), model, alias)
  1153. else:
  1154. # right == [] or right == False and all other cases are handled by _condition_to_sql()
  1155. push_result(model._condition_to_sql(alias, left, operator, right, self.query))
  1156. # -------------------------------------------------
  1157. # BINARY FIELDS STORED IN ATTACHMENT
  1158. # -> check for null only
  1159. # -------------------------------------------------
  1160. elif field.type == 'binary' and field.attachment:
  1161. if operator in ('=', '!=') and not right:
  1162. sub_op = 'in' if operator in NEGATIVE_TERM_OPERATORS else 'not in'
  1163. sql = SQL(
  1164. "(SELECT res_id FROM ir_attachment WHERE res_model = %s AND res_field = %s)",
  1165. model._name, left,
  1166. )
  1167. push(('id', sub_op, sql), model, alias)
  1168. else:
  1169. _logger.error("Binary field '%s' stored in attachment: ignore %s %s %s",
  1170. field.string, left, operator, reprlib.repr(right))
  1171. push(TRUE_LEAF, model, alias)
  1172. # -------------------------------------------------
  1173. # OTHER FIELDS
  1174. # -> datetime fields: manage time part of the datetime
  1175. # column when it is not there
  1176. # -> manage translatable fields
  1177. # -------------------------------------------------
  1178. else:
  1179. if field.type == 'datetime' and right:
  1180. if isinstance(right, str) and len(right) == 10:
  1181. if operator in ('>', '<='):
  1182. right += ' 23:59:59'
  1183. else:
  1184. right += ' 00:00:00'
  1185. push((left, operator, right), model, alias)
  1186. elif isinstance(right, date) and not isinstance(right, datetime):
  1187. if operator in ('>', '<='):
  1188. right = datetime.combine(right, time.max)
  1189. else:
  1190. right = datetime.combine(right, time.min)
  1191. push((left, operator, right), model, alias)
  1192. else:
  1193. push_result(model._condition_to_sql(alias, left, operator, right, self.query))
  1194. elif field.translate and (isinstance(right, str) or right is False) and left == field.name and \
  1195. self._has_trigram and field.index == 'trigram' and operator in ('=', 'like', 'ilike', '=like', '=ilike'):
  1196. right = right or ''
  1197. sql_operator = SQL_OPERATORS[operator]
  1198. need_wildcard = operator in WILDCARD_OPERATORS
  1199. if need_wildcard and not right:
  1200. push_result(SQL("FALSE") if operator in NEGATIVE_TERM_OPERATORS else SQL("TRUE"))
  1201. continue
  1202. push_result(model._condition_to_sql(alias, left, operator, right, self.query))
  1203. if not need_wildcard:
  1204. right = field.convert_to_column(right, model, validate=False)
  1205. # a prefilter using trigram index to speed up '=', 'like', 'ilike'
  1206. # '!=', '<=', '<', '>', '>=', 'in', 'not in', 'not like', 'not ilike' cannot use this trick
  1207. if operator == '=':
  1208. _right = value_to_translated_trigram_pattern(right)
  1209. else:
  1210. _right = pattern_to_translated_trigram_pattern(right)
  1211. if _right != '%':
  1212. # combine both generated SQL expressions (above and below) with an AND
  1213. push('&', model, alias)
  1214. sql_column = SQL('%s.%s', SQL.identifier(alias), SQL.identifier(field.name))
  1215. indexed_value = self._unaccent(SQL("jsonb_path_query_array(%s, '$.*')::text", sql_column))
  1216. _sql_operator = SQL('LIKE') if operator == '=' else sql_operator
  1217. push_result(SQL("%s %s %s", indexed_value, _sql_operator, self._unaccent(SQL("%s", _right))))
  1218. else:
  1219. push_result(model._condition_to_sql(alias, left, operator, right, self.query))
  1220. # ----------------------------------------
  1221. # END OF PARSING FULL DOMAIN
  1222. # -> put result in self.result and self.query
  1223. # ----------------------------------------
  1224. [self.result] = result_stack
  1225. self.query.add_where(self.result)
上海开阖软件有限公司 沪ICP备12045867号-1