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.

1545 lines
60KB

  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. """The Odoo API module defines Odoo Environments and method decorators.
  4. .. todo:: Document this module
  5. """
  6. from __future__ import annotations
  7. __all__ = [
  8. 'Environment',
  9. 'Meta',
  10. 'model',
  11. 'constrains', 'depends', 'onchange', 'returns',
  12. 'call_kw',
  13. ]
  14. import logging
  15. import warnings
  16. from collections import defaultdict
  17. from collections.abc import Mapping
  18. from contextlib import contextmanager
  19. from inspect import signature
  20. from pprint import pformat
  21. from weakref import WeakSet
  22. try:
  23. from decorator import decoratorx as decorator
  24. except ImportError:
  25. from decorator import decorator
  26. from .exceptions import AccessError, UserError, CacheMiss
  27. from .tools import clean_context, frozendict, lazy_property, OrderedSet, Query, SQL
  28. from .tools.translate import get_translation, get_translated_module, LazyGettext
  29. from odoo.tools.misc import StackMap
  30. import typing
  31. if typing.TYPE_CHECKING:
  32. from collections.abc import Callable
  33. from odoo.sql_db import BaseCursor
  34. from odoo.models import BaseModel
  35. try:
  36. from typing_extensions import Self # noqa: F401
  37. except ImportError:
  38. from typing import Self # noqa: F401
  39. M = typing.TypeVar("M", bound=BaseModel)
  40. else:
  41. Self = None
  42. M = typing.TypeVar("M")
  43. DomainType = list[str | tuple[str, str, typing.Any]]
  44. ContextType = Mapping[str, typing.Any]
  45. ValuesType = dict[str, typing.Any]
  46. T = typing.TypeVar('T')
  47. _logger = logging.getLogger(__name__)
  48. class NewId:
  49. """ Pseudo-ids for new records, encapsulating an optional origin id (actual
  50. record id) and an optional reference (any value).
  51. """
  52. __slots__ = ['origin', 'ref']
  53. def __init__(self, origin=None, ref=None):
  54. self.origin = origin
  55. self.ref = ref
  56. def __bool__(self):
  57. return False
  58. def __eq__(self, other):
  59. return isinstance(other, NewId) and (
  60. (self.origin and other.origin and self.origin == other.origin)
  61. or (self.ref and other.ref and self.ref == other.ref)
  62. )
  63. def __hash__(self):
  64. return hash(self.origin or self.ref or id(self))
  65. def __repr__(self):
  66. return (
  67. "<NewId origin=%r>" % self.origin if self.origin else
  68. "<NewId ref=%r>" % self.ref if self.ref else
  69. "<NewId 0x%x>" % id(self)
  70. )
  71. def __str__(self):
  72. if self.origin or self.ref:
  73. id_part = repr(self.origin or self.ref)
  74. else:
  75. id_part = hex(id(self))
  76. return "NewId_%s" % id_part
  77. IdType: typing.TypeAlias = int | NewId
  78. class Params(object):
  79. def __init__(self, args, kwargs):
  80. self.args = args
  81. self.kwargs = kwargs
  82. def __str__(self):
  83. params = []
  84. for arg in self.args:
  85. params.append(repr(arg))
  86. for item in sorted(self.kwargs.items()):
  87. params.append("%s=%r" % item)
  88. return ', '.join(params)
  89. class Meta(type):
  90. """ Metaclass that automatically decorates traditional-style methods by
  91. guessing their API. It also implements the inheritance of the
  92. :func:`returns` decorators.
  93. """
  94. def __new__(meta, name, bases, attrs):
  95. # dummy parent class to catch overridden methods decorated with 'returns'
  96. parent = type.__new__(meta, name, bases, {})
  97. for key, value in list(attrs.items()):
  98. if not key.startswith('__') and callable(value):
  99. # make the method inherit from decorators
  100. value = propagate(getattr(parent, key, None), value)
  101. attrs[key] = value
  102. return type.__new__(meta, name, bases, attrs)
  103. # The following attributes are used, and reflected on wrapping methods:
  104. # - method._constrains: set by @constrains, specifies constraint dependencies
  105. # - method._depends: set by @depends, specifies compute dependencies
  106. # - method._returns: set by @returns, specifies return model
  107. # - method._onchange: set by @onchange, specifies onchange fields
  108. # - method.clear_cache: set by @ormcache, used to clear the cache
  109. # - method._ondelete: set by @ondelete, used to raise errors for unlink operations
  110. #
  111. # On wrapping method only:
  112. # - method._api: decorator function, used for re-applying decorator
  113. #
  114. def attrsetter(attr, value):
  115. """ Return a function that sets ``attr`` on its argument and returns it. """
  116. return lambda method: setattr(method, attr, value) or method
  117. def propagate(method1, method2):
  118. """ Propagate decorators from ``method1`` to ``method2``, and return the
  119. resulting method.
  120. """
  121. if method1:
  122. for attr in ('_returns',):
  123. if hasattr(method1, attr) and not hasattr(method2, attr):
  124. setattr(method2, attr, getattr(method1, attr))
  125. return method2
  126. def constrains(*args: str) -> Callable[[T], T]:
  127. """Decorate a constraint checker.
  128. Each argument must be a field name used in the check::
  129. @api.constrains('name', 'description')
  130. def _check_description(self):
  131. for record in self:
  132. if record.name == record.description:
  133. raise ValidationError("Fields name and description must be different")
  134. Invoked on the records on which one of the named fields has been modified.
  135. Should raise :exc:`~odoo.exceptions.ValidationError` if the
  136. validation failed.
  137. .. warning::
  138. ``@constrains`` only supports simple field names, dotted names
  139. (fields of relational fields e.g. ``partner_id.customer``) are not
  140. supported and will be ignored.
  141. ``@constrains`` will be triggered only if the declared fields in the
  142. decorated method are included in the ``create`` or ``write`` call.
  143. It implies that fields not present in a view will not trigger a call
  144. during a record creation. A override of ``create`` is necessary to make
  145. sure a constraint will always be triggered (e.g. to test the absence of
  146. value).
  147. One may also pass a single function as argument. In that case, the field
  148. names are given by calling the function with a model instance.
  149. """
  150. if args and callable(args[0]):
  151. args = args[0]
  152. return attrsetter('_constrains', args)
  153. def ondelete(*, at_uninstall):
  154. """
  155. Mark a method to be executed during :meth:`~odoo.models.BaseModel.unlink`.
  156. The goal of this decorator is to allow client-side errors when unlinking
  157. records if, from a business point of view, it does not make sense to delete
  158. such records. For instance, a user should not be able to delete a validated
  159. sales order.
  160. While this could be implemented by simply overriding the method ``unlink``
  161. on the model, it has the drawback of not being compatible with module
  162. uninstallation. When uninstalling the module, the override could raise user
  163. errors, but we shouldn't care because the module is being uninstalled, and
  164. thus **all** records related to the module should be removed anyway.
  165. This means that by overriding ``unlink``, there is a big chance that some
  166. tables/records may remain as leftover data from the uninstalled module. This
  167. leaves the database in an inconsistent state. Moreover, there is a risk of
  168. conflicts if the module is ever reinstalled on that database.
  169. Methods decorated with ``@ondelete`` should raise an error following some
  170. conditions, and by convention, the method should be named either
  171. ``_unlink_if_<condition>`` or ``_unlink_except_<not_condition>``.
  172. .. code-block:: python
  173. @api.ondelete(at_uninstall=False)
  174. def _unlink_if_user_inactive(self):
  175. if any(user.active for user in self):
  176. raise UserError("Can't delete an active user!")
  177. # same as above but with _unlink_except_* as method name
  178. @api.ondelete(at_uninstall=False)
  179. def _unlink_except_active_user(self):
  180. if any(user.active for user in self):
  181. raise UserError("Can't delete an active user!")
  182. :param bool at_uninstall: Whether the decorated method should be called if
  183. the module that implements said method is being uninstalled. Should
  184. almost always be ``False``, so that module uninstallation does not
  185. trigger those errors.
  186. .. danger::
  187. The parameter ``at_uninstall`` should only be set to ``True`` if the
  188. check you are implementing also applies when uninstalling the module.
  189. For instance, it doesn't matter if when uninstalling ``sale``, validated
  190. sales orders are being deleted because all data pertaining to ``sale``
  191. should be deleted anyway, in that case ``at_uninstall`` should be set to
  192. ``False``.
  193. However, it makes sense to prevent the removal of the default language
  194. if no other languages are installed, since deleting the default language
  195. will break a lot of basic behavior. In this case, ``at_uninstall``
  196. should be set to ``True``.
  197. """
  198. return attrsetter('_ondelete', at_uninstall)
  199. def onchange(*args):
  200. """Return a decorator to decorate an onchange method for given fields.
  201. In the form views where the field appears, the method will be called
  202. when one of the given fields is modified. The method is invoked on a
  203. pseudo-record that contains the values present in the form. Field
  204. assignments on that record are automatically sent back to the client.
  205. Each argument must be a field name::
  206. @api.onchange('partner_id')
  207. def _onchange_partner(self):
  208. self.message = "Dear %s" % (self.partner_id.name or "")
  209. .. code-block:: python
  210. return {
  211. 'warning': {'title': "Warning", 'message': "What is this?", 'type': 'notification'},
  212. }
  213. If the type is set to notification, the warning will be displayed in a notification.
  214. Otherwise it will be displayed in a dialog as default.
  215. .. warning::
  216. ``@onchange`` only supports simple field names, dotted names
  217. (fields of relational fields e.g. ``partner_id.tz``) are not
  218. supported and will be ignored
  219. .. danger::
  220. Since ``@onchange`` returns a recordset of pseudo-records,
  221. calling any one of the CRUD methods
  222. (:meth:`create`, :meth:`read`, :meth:`write`, :meth:`unlink`)
  223. on the aforementioned recordset is undefined behaviour,
  224. as they potentially do not exist in the database yet.
  225. Instead, simply set the record's field like shown in the example
  226. above or call the :meth:`update` method.
  227. .. warning::
  228. It is not possible for a ``one2many`` or ``many2many`` field to modify
  229. itself via onchange. This is a webclient limitation - see `#2693 <https://github.com/odoo/odoo/issues/2693>`_.
  230. """
  231. return attrsetter('_onchange', args)
  232. def depends(*args: str) -> Callable[[T], T]:
  233. """ Return a decorator that specifies the field dependencies of a "compute"
  234. method (for new-style function fields). Each argument must be a string
  235. that consists in a dot-separated sequence of field names::
  236. pname = fields.Char(compute='_compute_pname')
  237. @api.depends('partner_id.name', 'partner_id.is_company')
  238. def _compute_pname(self):
  239. for record in self:
  240. if record.partner_id.is_company:
  241. record.pname = (record.partner_id.name or "").upper()
  242. else:
  243. record.pname = record.partner_id.name
  244. One may also pass a single function as argument. In that case, the
  245. dependencies are given by calling the function with the field's model.
  246. """
  247. if args and callable(args[0]):
  248. args = args[0]
  249. elif any('id' in arg.split('.') for arg in args):
  250. raise NotImplementedError("Compute method cannot depend on field 'id'.")
  251. return attrsetter('_depends', args)
  252. def depends_context(*args):
  253. """ Return a decorator that specifies the context dependencies of a
  254. non-stored "compute" method. Each argument is a key in the context's
  255. dictionary::
  256. price = fields.Float(compute='_compute_product_price')
  257. @api.depends_context('pricelist')
  258. def _compute_product_price(self):
  259. for product in self:
  260. if product.env.context.get('pricelist'):
  261. pricelist = self.env['product.pricelist'].browse(product.env.context['pricelist'])
  262. else:
  263. pricelist = self.env['product.pricelist'].get_default_pricelist()
  264. product.price = pricelist._get_products_price(product).get(product.id, 0.0)
  265. All dependencies must be hashable. The following keys have special
  266. support:
  267. * `company` (value in context or current company id),
  268. * `uid` (current user id and superuser flag),
  269. * `active_test` (value in env.context or value in field.context).
  270. """
  271. return attrsetter('_depends_context', args)
  272. def returns(model, downgrade=None, upgrade=None):
  273. """ Return a decorator for methods that return instances of ``model``.
  274. :param model: a model name, or ``'self'`` for the current model
  275. :param downgrade: a function ``downgrade(self, value, *args, **kwargs)``
  276. to convert the record-style ``value`` to a traditional-style output
  277. :param upgrade: a function ``upgrade(self, value, *args, **kwargs)``
  278. to convert the traditional-style ``value`` to a record-style output
  279. The arguments ``self``, ``*args`` and ``**kwargs`` are the ones passed
  280. to the method in the record-style.
  281. The decorator adapts the method output to the api style: ``id``, ``ids`` or
  282. ``False`` for the traditional style, and recordset for the record style::
  283. @model
  284. @returns('res.partner')
  285. def find_partner(self, arg):
  286. ... # return some record
  287. # output depends on call style: traditional vs record style
  288. partner_id = model.find_partner(cr, uid, arg, context=context)
  289. # recs = model.browse(cr, uid, ids, context)
  290. partner_record = recs.find_partner(arg)
  291. Note that the decorated method must satisfy that convention.
  292. Those decorators are automatically *inherited*: a method that overrides
  293. a decorated existing method will be decorated with the same
  294. ``@returns(model)``.
  295. """
  296. return attrsetter('_returns', (model, downgrade, upgrade))
  297. def downgrade(method, value, self, args, kwargs):
  298. """ Convert ``value`` returned by ``method`` on ``self`` to traditional style. """
  299. spec = getattr(method, '_returns', None)
  300. if not spec:
  301. return value
  302. _, convert, _ = spec
  303. if convert and len(signature(convert).parameters) > 1:
  304. return convert(self, value, *args, **kwargs)
  305. elif convert:
  306. return convert(value)
  307. else:
  308. return value.ids
  309. def autovacuum(method):
  310. """
  311. Decorate a method so that it is called by the daily vacuum cron job (model
  312. ``ir.autovacuum``). This is typically used for garbage-collection-like
  313. tasks that do not deserve a specific cron job.
  314. """
  315. assert method.__name__.startswith('_'), "%s: autovacuum methods must be private" % method.__name__
  316. method._autovacuum = True
  317. return method
  318. def model(method: T) -> T:
  319. """ Decorate a record-style method where ``self`` is a recordset, but its
  320. contents is not relevant, only the model is. Such a method::
  321. @api.model
  322. def method(self, args):
  323. ...
  324. """
  325. if method.__name__ == 'create':
  326. return model_create_single(method)
  327. method._api = 'model'
  328. return method
  329. def readonly(method: T) -> T:
  330. """ Decorate a record-style method where ``self.env.cr`` can be a
  331. readonly cursor when called trough a rpc call.
  332. @api.readonly
  333. def method(self, args):
  334. ...
  335. """
  336. method._readonly = True
  337. return method
  338. _create_logger = logging.getLogger(__name__ + '.create')
  339. @decorator
  340. def _model_create_single(create, self, arg):
  341. # 'create' expects a dict and returns a record
  342. if isinstance(arg, Mapping):
  343. return create(self, arg)
  344. if len(arg) > 1:
  345. _create_logger.debug("%s.create() called with %d dicts", self, len(arg))
  346. return self.browse().concat(*(create(self, vals) for vals in arg))
  347. def model_create_single(method: T) -> T:
  348. """ Decorate a method that takes a dictionary and creates a single record.
  349. The method may be called with either a single dict or a list of dicts::
  350. record = model.create(vals)
  351. records = model.create([vals, ...])
  352. """
  353. warnings.warn(
  354. f"The model {method.__module__} is not overriding the create method in batch",
  355. DeprecationWarning
  356. )
  357. wrapper = _model_create_single(method) # pylint: disable=no-value-for-parameter
  358. wrapper._api = 'model_create'
  359. return wrapper
  360. @decorator
  361. def _model_create_multi(create, self, arg):
  362. # 'create' expects a list of dicts and returns a recordset
  363. if isinstance(arg, Mapping):
  364. return create(self, [arg])
  365. return create(self, arg)
  366. def model_create_multi(method: T) -> T:
  367. """ Decorate a method that takes a list of dictionaries and creates multiple
  368. records. The method may be called with either a single dict or a list of
  369. dicts::
  370. record = model.create(vals)
  371. records = model.create([vals, ...])
  372. """
  373. wrapper = _model_create_multi(method) # pylint: disable=no-value-for-parameter
  374. wrapper._api = 'model_create'
  375. return wrapper
  376. def call_kw(model, name, args, kwargs):
  377. """ Invoke the given method ``name`` on the recordset ``model``. """
  378. method = getattr(model, name, None)
  379. if not method:
  380. raise AttributeError(f"The method '{name}' does not exist on the model '{model._name}'")
  381. api = getattr(method, '_api', None)
  382. if api:
  383. # @api.model, @api.model_create -> no ids
  384. recs = model
  385. else:
  386. ids, args = args[0], args[1:]
  387. recs = model.browse(ids)
  388. # altering kwargs is a cause of errors, for instance when retrying a request
  389. # after a serialization error: the retry is done without context!
  390. kwargs = dict(kwargs)
  391. context = kwargs.pop('context', None) or {}
  392. recs = recs.with_context(context)
  393. _logger.debug("call %s.%s(%s)", recs, method.__name__, Params(args, kwargs))
  394. result = getattr(recs, name)(*args, **kwargs)
  395. if api == "model_create":
  396. # special case for method 'create'
  397. result = result.id if isinstance(args[0], Mapping) else result.ids
  398. else:
  399. result = downgrade(method, result, recs, args, kwargs)
  400. return result
  401. class Environment(Mapping):
  402. """ The environment stores various contextual data used by the ORM:
  403. - :attr:`cr`: the current database cursor (for database queries);
  404. - :attr:`uid`: the current user id (for access rights checks);
  405. - :attr:`context`: the current context dictionary (arbitrary metadata);
  406. - :attr:`su`: whether in superuser mode.
  407. It provides access to the registry by implementing a mapping from model
  408. names to models. It also holds a cache for records, and a data
  409. structure to manage recomputations.
  410. """
  411. cr: BaseCursor
  412. uid: int
  413. context: frozendict
  414. su: bool
  415. registry: Registry
  416. cache: Cache
  417. transaction: Transaction
  418. def reset(self):
  419. """ Reset the transaction, see :meth:`Transaction.reset`. """
  420. self.transaction.reset()
  421. def __new__(cls, cr, uid, context, su=False, uid_origin=None):
  422. assert isinstance(cr, BaseCursor)
  423. if uid == SUPERUSER_ID:
  424. su = True
  425. # isinstance(uid, int) is to handle `RequestUID`
  426. uid_origin = uid_origin or (uid if isinstance(uid, int) else None)
  427. if uid_origin == SUPERUSER_ID:
  428. uid_origin = None
  429. # determine transaction object
  430. transaction = cr.transaction
  431. if transaction is None:
  432. transaction = cr.transaction = Transaction(Registry(cr.dbname))
  433. # if env already exists, return it
  434. for env in transaction.envs:
  435. if (env.cr, env.uid, env.su, env.uid_origin, env.context) == (cr, uid, su, uid_origin, context):
  436. return env
  437. # otherwise create environment, and add it in the set
  438. self = object.__new__(cls)
  439. self.cr, self.uid, self.su, self.uid_origin = cr, uid, su, uid_origin
  440. self.context = frozendict(context)
  441. self.transaction = transaction
  442. self.registry = transaction.registry
  443. self.cache = transaction.cache
  444. self._cache_key = {} # memo {field: cache_key}
  445. self._protected = transaction.protected
  446. transaction.envs.add(self)
  447. return self
  448. #
  449. # Mapping methods
  450. #
  451. def __contains__(self, model_name):
  452. """ Test whether the given model exists. """
  453. return model_name in self.registry
  454. def __getitem__(self, model_name: str) -> BaseModel:
  455. """ Return an empty recordset from the given model. """
  456. return self.registry[model_name](self, (), ())
  457. def __iter__(self):
  458. """ Return an iterator on model names. """
  459. return iter(self.registry)
  460. def __len__(self):
  461. """ Return the size of the model registry. """
  462. return len(self.registry)
  463. def __eq__(self, other):
  464. return self is other
  465. def __ne__(self, other):
  466. return self is not other
  467. def __hash__(self):
  468. return object.__hash__(self)
  469. def __call__(self, cr=None, user=None, context=None, su=None):
  470. """ Return an environment based on ``self`` with modified parameters.
  471. :param cr: optional database cursor to change the current cursor
  472. :type cursor: :class:`~odoo.sql_db.Cursor`
  473. :param user: optional user/user id to change the current user
  474. :type user: int or :class:`res.users record<~odoo.addons.base.models.res_users.Users>`
  475. :param dict context: optional context dictionary to change the current context
  476. :param bool su: optional boolean to change the superuser mode
  477. :returns: environment with specified args (new or existing one)
  478. :rtype: :class:`Environment`
  479. """
  480. cr = self.cr if cr is None else cr
  481. uid = self.uid if user is None else int(user)
  482. if context is None:
  483. context = clean_context(self.context) if su and not self.su else self.context
  484. su = (user is None and self.su) if su is None else su
  485. return Environment(cr, uid, context, su, self.uid_origin)
  486. def ref(self, xml_id, raise_if_not_found=True):
  487. """ Return the record corresponding to the given ``xml_id``.
  488. :param str xml_id: record xml_id, under the format ``<module.id>``
  489. :param bool raise_if_not_found: whether the method should raise if record is not found
  490. :returns: Found record or None
  491. :raise ValueError: if record wasn't found and ``raise_if_not_found`` is True
  492. """
  493. res_model, res_id = self['ir.model.data']._xmlid_to_res_model_res_id(
  494. xml_id, raise_if_not_found=raise_if_not_found
  495. )
  496. if res_model and res_id:
  497. record = self[res_model].browse(res_id)
  498. if record.exists():
  499. return record
  500. if raise_if_not_found:
  501. raise ValueError('No record found for unique ID %s. It may have been deleted.' % (xml_id))
  502. return None
  503. def is_superuser(self):
  504. """ Return whether the environment is in superuser mode. """
  505. return self.su
  506. def is_admin(self):
  507. """ Return whether the current user has group "Access Rights", or is in
  508. superuser mode. """
  509. return self.su or self.user._is_admin()
  510. def is_system(self):
  511. """ Return whether the current user has group "Settings", or is in
  512. superuser mode. """
  513. return self.su or self.user._is_system()
  514. @lazy_property
  515. def user(self):
  516. """Return the current user (as an instance).
  517. :returns: current user - sudoed
  518. :rtype: :class:`res.users record<~odoo.addons.base.models.res_users.Users>`"""
  519. return self(su=True)['res.users'].browse(self.uid)
  520. @lazy_property
  521. def company(self):
  522. """Return the current company (as an instance).
  523. If not specified in the context (`allowed_company_ids`),
  524. fallback on current user main company.
  525. :raise AccessError: invalid or unauthorized `allowed_company_ids` context key content.
  526. :return: current company (default=`self.user.company_id`), with the current environment
  527. :rtype: :class:`res.company record<~odoo.addons.base.models.res_company.Company>`
  528. .. warning::
  529. No sanity checks applied in sudo mode!
  530. When in sudo mode, a user can access any company,
  531. even if not in his allowed companies.
  532. This allows to trigger inter-company modifications,
  533. even if the current user doesn't have access to
  534. the targeted company.
  535. """
  536. company_ids = self.context.get('allowed_company_ids', [])
  537. if company_ids:
  538. if not self.su:
  539. user_company_ids = self.user._get_company_ids()
  540. if set(company_ids) - set(user_company_ids):
  541. raise AccessError(self._("Access to unauthorized or invalid companies."))
  542. return self['res.company'].browse(company_ids[0])
  543. return self.user.company_id.with_env(self)
  544. @lazy_property
  545. def companies(self):
  546. """Return a recordset of the enabled companies by the user.
  547. If not specified in the context(`allowed_company_ids`),
  548. fallback on current user companies.
  549. :raise AccessError: invalid or unauthorized `allowed_company_ids` context key content.
  550. :return: current companies (default=`self.user.company_ids`), with the current environment
  551. :rtype: :class:`res.company recordset<~odoo.addons.base.models.res_company.Company>`
  552. .. warning::
  553. No sanity checks applied in sudo mode !
  554. When in sudo mode, a user can access any company,
  555. even if not in his allowed companies.
  556. This allows to trigger inter-company modifications,
  557. even if the current user doesn't have access to
  558. the targeted company.
  559. """
  560. company_ids = self.context.get('allowed_company_ids', [])
  561. user_company_ids = self.user._get_company_ids()
  562. if company_ids:
  563. if not self.su:
  564. if set(company_ids) - set(user_company_ids):
  565. raise AccessError(self._("Access to unauthorized or invalid companies."))
  566. return self['res.company'].browse(company_ids)
  567. # By setting the default companies to all user companies instead of the main one
  568. # we save a lot of potential trouble in all "out of context" calls, such as
  569. # /mail/redirect or /web/image, etc. And it is not unsafe because the user does
  570. # have access to these other companies. The risk of exposing foreign records
  571. # (wrt to the context) is low because all normal RPCs will have a proper
  572. # allowed_company_ids.
  573. # Examples:
  574. # - when printing a report for several records from several companies
  575. # - when accessing to a record from the notification email template
  576. # - when loading an binary image on a template
  577. return self['res.company'].browse(user_company_ids)
  578. @lazy_property
  579. def lang(self):
  580. """Return the current language code.
  581. :rtype: str
  582. """
  583. lang = self.context.get('lang')
  584. if lang and lang != 'en_US' and not self['res.lang']._get_data(code=lang):
  585. # cannot translate here because we do not have a valid language
  586. raise UserError(f'Invalid language code: {lang}') # pylint: disable
  587. return lang or None
  588. @lazy_property
  589. def _lang(self):
  590. """Return the technical language code of the current context for **model_terms** translated field
  591. :rtype: str
  592. """
  593. context = self.context
  594. lang = self.lang or 'en_US'
  595. if context.get('edit_translations') or context.get('check_translations'):
  596. lang = '_' + lang
  597. return lang
  598. def _(self, source: str | LazyGettext, *args, **kwargs) -> str:
  599. """Translate the term using current environment's language.
  600. Usage:
  601. ```
  602. self.env._("hello world") # dynamically get module name
  603. self.env._("hello %s", "test")
  604. self.env._(LAZY_TRANSLATION)
  605. ```
  606. :param source: String to translate or lazy translation
  607. :param ...: args or kwargs for templating
  608. :return: The transalted string
  609. """
  610. lang = self.lang or 'en_US'
  611. if isinstance(source, str):
  612. assert not (args and kwargs), "Use args or kwargs, not both"
  613. args = args or kwargs
  614. elif isinstance(source, LazyGettext):
  615. # translate a lazy text evaluation
  616. assert not args and not kwargs, "All args should come from the lazy text"
  617. return source._translate(lang)
  618. else:
  619. raise TypeError(f"Cannot translate {source!r}")
  620. if lang == 'en_US':
  621. # we ignore the module as en_US is not translated
  622. return get_translation('base', 'en_US', source, args)
  623. try:
  624. module = get_translated_module(2)
  625. return get_translation(module, lang, source, args)
  626. except Exception: # noqa: BLE001
  627. _logger.debug('translation went wrong for "%r", skipped', source, exc_info=True)
  628. return source
  629. def clear(self):
  630. """ Clear all record caches, and discard all fields to recompute.
  631. This may be useful when recovering from a failed ORM operation.
  632. """
  633. lazy_property.reset_all(self)
  634. self._cache_key.clear()
  635. self.transaction.clear()
  636. def invalidate_all(self, flush=True):
  637. """ Invalidate the cache of all records.
  638. :param flush: whether pending updates should be flushed before invalidation.
  639. It is ``True`` by default, which ensures cache consistency.
  640. Do not use this parameter unless you know what you are doing.
  641. """
  642. if flush:
  643. self.flush_all()
  644. self.cache.invalidate()
  645. def _recompute_all(self):
  646. """ Process all pending computations. """
  647. for field in list(self.fields_to_compute()):
  648. self[field.model_name]._recompute_field(field)
  649. def flush_all(self):
  650. """ Flush all pending computations and updates to the database. """
  651. self._recompute_all()
  652. for model_name in OrderedSet(field.model_name for field in self.cache.get_dirty_fields()):
  653. self[model_name].flush_model()
  654. def is_protected(self, field, record):
  655. """ Return whether `record` is protected against invalidation or
  656. recomputation for `field`.
  657. """
  658. return record.id in self._protected.get(field, ())
  659. def protected(self, field):
  660. """ Return the recordset for which ``field`` should not be invalidated or recomputed. """
  661. return self[field.model_name].browse(self._protected.get(field, ()))
  662. @contextmanager
  663. def protecting(self, what, records=None):
  664. """ Prevent the invalidation or recomputation of fields on records.
  665. The parameters are either:
  666. - ``what`` a collection of fields and ``records`` a recordset, or
  667. - ``what`` a collection of pairs ``(fields, records)``.
  668. """
  669. protected = self._protected
  670. try:
  671. protected.pushmap()
  672. if records is not None: # Handle first signature
  673. ids_by_field = {field: records._ids for field in what}
  674. else: # Handle second signature
  675. ids_by_field = defaultdict(list)
  676. for fields, what_records in what:
  677. for field in fields:
  678. ids_by_field[field].extend(what_records._ids)
  679. for field, rec_ids in ids_by_field.items():
  680. ids = protected.get(field)
  681. protected[field] = ids.union(rec_ids) if ids else frozenset(rec_ids)
  682. yield
  683. finally:
  684. protected.popmap()
  685. def fields_to_compute(self):
  686. """ Return a view on the field to compute. """
  687. return self.transaction.tocompute.keys()
  688. def records_to_compute(self, field):
  689. """ Return the records to compute for ``field``. """
  690. ids = self.transaction.tocompute.get(field, ())
  691. return self[field.model_name].browse(ids)
  692. def is_to_compute(self, field, record):
  693. """ Return whether ``field`` must be computed on ``record``. """
  694. return record.id in self.transaction.tocompute.get(field, ())
  695. def not_to_compute(self, field, records):
  696. """ Return the subset of ``records`` for which ``field`` must not be computed. """
  697. ids = self.transaction.tocompute.get(field, ())
  698. return records.browse(id_ for id_ in records._ids if id_ not in ids)
  699. def add_to_compute(self, field, records):
  700. """ Mark ``field`` to be computed on ``records``. """
  701. if not records:
  702. return records
  703. assert field.store and field.compute, "Cannot add to recompute no-store or no-computed field"
  704. self.transaction.tocompute[field].update(records._ids)
  705. def remove_to_compute(self, field, records):
  706. """ Mark ``field`` as computed on ``records``. """
  707. if not records:
  708. return
  709. ids = self.transaction.tocompute.get(field, None)
  710. if ids is None:
  711. return
  712. ids.difference_update(records._ids)
  713. if not ids:
  714. del self.transaction.tocompute[field]
  715. def cache_key(self, field):
  716. """ Return the cache key of the given ``field``. """
  717. try:
  718. return self._cache_key[field]
  719. except KeyError:
  720. def get(key, get_context=self.context.get):
  721. if key == 'company':
  722. return self.company.id
  723. elif key == 'uid':
  724. return self.uid if field.compute_sudo else (self.uid, self.su)
  725. elif key == 'lang':
  726. return get_context('lang') or None
  727. elif key == 'active_test':
  728. return get_context('active_test', field.context.get('active_test', True))
  729. elif key.startswith('bin_size'):
  730. return bool(get_context(key))
  731. else:
  732. val = get_context(key)
  733. if type(val) is list:
  734. val = tuple(val)
  735. try:
  736. hash(val)
  737. except TypeError:
  738. raise TypeError(
  739. "Can only create cache keys from hashable values, "
  740. "got non-hashable value {!r} at context key {!r} "
  741. "(dependency of field {})".format(val, key, field)
  742. ) from None # we don't need to chain the exception created 2 lines above
  743. else:
  744. return val
  745. result = tuple(get(key) for key in self.registry.field_depends_context[field])
  746. self._cache_key[field] = result
  747. return result
  748. def flush_query(self, query: SQL):
  749. """ Flush all the fields in the metadata of ``query``. """
  750. fields_to_flush = tuple(query.to_flush)
  751. if not fields_to_flush:
  752. return
  753. fnames_to_flush = defaultdict(OrderedSet)
  754. for field in fields_to_flush:
  755. fnames_to_flush[field.model_name].add(field.name)
  756. for model_name, field_names in fnames_to_flush.items():
  757. self[model_name].flush_model(field_names)
  758. def execute_query(self, query: SQL) -> list[tuple]:
  759. """ Execute the given query, fetch its result and it as a list of tuples
  760. (or an empty list if no result to fetch). The method automatically
  761. flushes all the fields in the metadata of the query.
  762. """
  763. assert isinstance(query, SQL)
  764. self.flush_query(query)
  765. self.cr.execute(query)
  766. return [] if self.cr.description is None else self.cr.fetchall()
  767. def execute_query_dict(self, query: SQL) -> list[dict]:
  768. """ Execute the given query, fetch its results as a list of dicts.
  769. The method automatically flushes fields in the metadata of the query.
  770. """
  771. rows = self.execute_query(query)
  772. if not rows:
  773. return rows
  774. description = self.cr.description
  775. return [
  776. {column.name: row[index] for index, column in enumerate(description)}
  777. for row in rows
  778. ]
  779. class Transaction:
  780. """ A object holding ORM data structures for a transaction. """
  781. __slots__ = ('_Transaction__file_open_tmp_paths', 'cache', 'envs', 'protected', 'registry', 'tocompute')
  782. def __init__(self, registry):
  783. self.registry = registry
  784. # weak set of environments
  785. self.envs = WeakSet()
  786. self.envs.data = OrderedSet() # make the weakset OrderedWeakSet
  787. # cache for all records
  788. self.cache = Cache()
  789. # fields to protect {field: ids}
  790. self.protected = StackMap()
  791. # pending computations {field: ids}
  792. self.tocompute = defaultdict(OrderedSet)
  793. # temporary directories (managed in odoo.tools.file_open_temporary_directory)
  794. self.__file_open_tmp_paths = () # noqa: PLE0237
  795. def flush(self):
  796. """ Flush pending computations and updates in the transaction. """
  797. env_to_flush = None
  798. for env in self.envs:
  799. if isinstance(env.uid, int) or env.uid is None:
  800. env_to_flush = env
  801. if env.uid is not None:
  802. break
  803. if env_to_flush is not None:
  804. env_to_flush.flush_all()
  805. def clear(self):
  806. """ Clear the caches and pending computations and updates in the translations. """
  807. self.cache.clear()
  808. self.tocompute.clear()
  809. def reset(self):
  810. """ Reset the transaction. This clears the transaction, and reassigns
  811. the registry on all its environments. This operation is strongly
  812. recommended after reloading the registry.
  813. """
  814. self.registry = Registry(self.registry.db_name)
  815. for env in self.envs:
  816. env.registry = self.registry
  817. lazy_property.reset_all(env)
  818. env._cache_key.clear()
  819. self.clear()
  820. # sentinel value for optional parameters
  821. NOTHING = object()
  822. EMPTY_DICT = frozendict()
  823. class Cache:
  824. """ Implementation of the cache of records.
  825. For most fields, the cache is simply a mapping from a record and a field to
  826. a value. In the case of context-dependent fields, the mapping also depends
  827. on the environment of the given record. For the sake of performance, the
  828. cache is first partitioned by field, then by record. This makes some
  829. common ORM operations pretty fast, like determining which records have a
  830. value for a given field, or invalidating a given field on all possible
  831. records.
  832. The cache can also mark some entries as "dirty". Dirty entries essentially
  833. marks values that are different from the database. They represent database
  834. updates that haven't been done yet. Note that dirty entries only make
  835. sense for stored fields. Note also that if a field is dirty on a given
  836. record, and the field is context-dependent, then all the values of the
  837. record for that field are considered dirty. For the sake of consistency,
  838. the values that should be in the database must be in a context where all
  839. the field's context keys are ``None``.
  840. """
  841. __slots__ = ('_data', '_dirty', '_patches')
  842. def __init__(self):
  843. # {field: {record_id: value}, field: {context_key: {record_id: value}}}
  844. self._data = defaultdict(dict)
  845. # {field: set[id]} stores the fields and ids that are changed in the
  846. # cache, but not yet written in the database; their changed values are
  847. # in `_data`
  848. self._dirty = defaultdict(OrderedSet)
  849. # {field: {record_id: ids}} record ids to be added to the values of
  850. # x2many fields if they are not in cache yet
  851. self._patches = defaultdict(lambda: defaultdict(list))
  852. def __repr__(self):
  853. # for debugging: show the cache content and dirty flags as stars
  854. data = {}
  855. for field, field_cache in sorted(self._data.items(), key=lambda item: str(item[0])):
  856. dirty_ids = self._dirty.get(field, ())
  857. if field_cache and isinstance(next(iter(field_cache)), tuple):
  858. data[field] = {
  859. key: {
  860. Starred(id_) if id_ in dirty_ids else id_: val if field.type != 'binary' else '<binary>'
  861. for id_, val in key_cache.items()
  862. }
  863. for key, key_cache in field_cache.items()
  864. }
  865. else:
  866. data[field] = {
  867. Starred(id_) if id_ in dirty_ids else id_: val if field.type != 'binary' else '<binary>'
  868. for id_, val in field_cache.items()
  869. }
  870. return repr(data)
  871. def _get_field_cache(self, model, field):
  872. """ Return the field cache of the given field, but not for modifying it. """
  873. field_cache = self._data.get(field, EMPTY_DICT)
  874. if field_cache and field in model.pool.field_depends_context:
  875. field_cache = field_cache.get(model.env.cache_key(field), EMPTY_DICT)
  876. return field_cache
  877. def _set_field_cache(self, model, field):
  878. """ Return the field cache of the given field for modifying it. """
  879. field_cache = self._data[field]
  880. if field in model.pool.field_depends_context:
  881. field_cache = field_cache.setdefault(model.env.cache_key(field), {})
  882. return field_cache
  883. def contains(self, record, field):
  884. """ Return whether ``record`` has a value for ``field``. """
  885. field_cache = self._get_field_cache(record, field)
  886. if field.translate:
  887. cache_value = field_cache.get(record.id, EMPTY_DICT)
  888. if cache_value is None:
  889. return True
  890. lang = (record.env.lang or 'en_US') if field.translate is True else record.env._lang
  891. return lang in cache_value
  892. return record.id in field_cache
  893. def contains_field(self, field):
  894. """ Return whether ``field`` has a value for at least one record. """
  895. cache = self._data.get(field)
  896. if not cache:
  897. return False
  898. # 'cache' keys are tuples if 'field' is context-dependent, record ids otherwise
  899. if isinstance(next(iter(cache)), tuple):
  900. return any(value for value in cache.values())
  901. return True
  902. def get(self, record, field, default=NOTHING):
  903. """ Return the value of ``field`` for ``record``. """
  904. try:
  905. field_cache = self._get_field_cache(record, field)
  906. cache_value = field_cache[record._ids[0]]
  907. if field.translate and cache_value is not None:
  908. lang = (record.env.lang or 'en_US') if field.translate is True else record.env._lang
  909. return cache_value[lang]
  910. return cache_value
  911. except KeyError:
  912. if default is NOTHING:
  913. raise CacheMiss(record, field) from None
  914. return default
  915. def set(self, record, field, value, dirty=False, check_dirty=True):
  916. """ Set the value of ``field`` for ``record``.
  917. One can normally make a clean field dirty but not the other way around.
  918. Updating a dirty field without ``dirty=True`` is a programming error and
  919. raises an exception.
  920. :param dirty: whether ``field`` must be made dirty on ``record`` after
  921. the update
  922. :param check_dirty: whether updating a dirty field without making it
  923. dirty must raise an exception
  924. """
  925. field_cache = self._set_field_cache(record, field)
  926. record_id = record.id
  927. if field.translate and value is not None:
  928. # only for model translated fields
  929. lang = record.env.lang or 'en_US'
  930. cache_value = field_cache.get(record_id) or {}
  931. cache_value[lang] = value
  932. value = cache_value
  933. field_cache[record_id] = value
  934. if not check_dirty:
  935. return
  936. if dirty:
  937. assert field.column_type and field.store and record_id
  938. self._dirty[field].add(record_id)
  939. if field in record.pool.field_depends_context:
  940. # put the values under conventional context key values {'context_key': None},
  941. # in order to ease the retrieval of those values to flush them
  942. record = record.with_env(record.env(context={}))
  943. field_cache = self._set_field_cache(record, field)
  944. field_cache[record_id] = value
  945. elif record_id in self._dirty.get(field, ()):
  946. _logger.error("cache.set() removing flag dirty on %s.%s", record, field.name, stack_info=True)
  947. def update(self, records, field, values, dirty=False, check_dirty=True):
  948. """ Set the values of ``field`` for several ``records``.
  949. One can normally make a clean field dirty but not the other way around.
  950. Updating a dirty field without ``dirty=True`` is a programming error and
  951. raises an exception.
  952. :param dirty: whether ``field`` must be made dirty on ``record`` after
  953. the update
  954. :param check_dirty: whether updating a dirty field without making it
  955. dirty must raise an exception
  956. """
  957. if field.translate:
  958. # only for model translated fields
  959. lang = records.env.lang or 'en_US'
  960. field_cache = self._get_field_cache(records, field)
  961. cache_values = []
  962. for id_, value in zip(records._ids, values):
  963. if value is None:
  964. cache_values.append(None)
  965. else:
  966. cache_value = field_cache.get(id_) or {}
  967. cache_value[lang] = value
  968. cache_values.append(cache_value)
  969. values = cache_values
  970. self.update_raw(records, field, values, dirty, check_dirty)
  971. def update_raw(self, records, field, values, dirty=False, check_dirty=True):
  972. """ This is a variant of method :meth:`~update` without the logic for
  973. translated fields.
  974. """
  975. field_cache = self._set_field_cache(records, field)
  976. field_cache.update(zip(records._ids, values))
  977. if not check_dirty:
  978. return
  979. if dirty:
  980. assert field.column_type and field.store and all(records._ids)
  981. self._dirty[field].update(records._ids)
  982. if not field.company_dependent and field in records.pool.field_depends_context:
  983. # put the values under conventional context key values {'context_key': None},
  984. # in order to ease the retrieval of those values to flush them
  985. records = records.with_env(records.env(context={}))
  986. field_cache = self._set_field_cache(records, field)
  987. field_cache.update(zip(records._ids, values))
  988. else:
  989. dirty_ids = self._dirty.get(field)
  990. if dirty_ids and not dirty_ids.isdisjoint(records._ids):
  991. _logger.error("cache.update() removing flag dirty on %s.%s", records, field.name, stack_info=True)
  992. def insert_missing(self, records, field, values):
  993. """ Set the values of ``field`` for the records in ``records`` that
  994. don't have a value yet. In other words, this does not overwrite
  995. existing values in cache.
  996. """
  997. field_cache = self._set_field_cache(records, field)
  998. env = records.env
  999. if field.translate:
  1000. if env.context.get('prefetch_langs'):
  1001. installed = [lang for lang, _ in env['res.lang'].get_installed()]
  1002. langs = OrderedSet(installed + ['en_US'])
  1003. _langs = [f'_{l}' for l in langs] if field.translate is not True and env._lang.startswith('_') else []
  1004. for id_, val in zip(records._ids, values):
  1005. if val is None:
  1006. field_cache.setdefault(id_, None)
  1007. else:
  1008. if _langs: # fallback missing _lang to lang if exists
  1009. val.update({f'_{k}': v for k, v in val.items() if k in langs and f'_{k}' not in val})
  1010. field_cache[id_] = {
  1011. **dict.fromkeys(langs, val['en_US']), # fallback missing lang to en_US
  1012. **dict.fromkeys(_langs, val.get('_en_US')), # fallback missing _lang to _en_US
  1013. **val
  1014. }
  1015. else:
  1016. lang = (env.lang or 'en_US') if field.translate is True else env._lang
  1017. for id_, val in zip(records._ids, values):
  1018. if val is None:
  1019. field_cache.setdefault(id_, None)
  1020. else:
  1021. cache_value = field_cache.setdefault(id_, {})
  1022. if cache_value is not None:
  1023. cache_value.setdefault(lang, val)
  1024. else:
  1025. for id_, val in zip(records._ids, values):
  1026. field_cache.setdefault(id_, val)
  1027. def patch(self, records, field, new_id):
  1028. """ Apply a patch to an x2many field on new records. The patch consists
  1029. in adding new_id to its value in cache. If the value is not in cache
  1030. yet, it will be applied once the value is put in cache with method
  1031. :meth:`patch_and_set`.
  1032. """
  1033. assert not new_id, "Cache.patch can only be called with a new id"
  1034. field_cache = self._set_field_cache(records, field)
  1035. for id_ in records._ids:
  1036. assert not id_, "Cache.patch can only be called with new records"
  1037. if id_ in field_cache:
  1038. field_cache[id_] = tuple(dict.fromkeys(field_cache[id_] + (new_id,)))
  1039. else:
  1040. self._patches[field][id_].append(new_id)
  1041. def patch_and_set(self, record, field, value):
  1042. """ Set the value of ``field`` for ``record``, like :meth:`set`, but
  1043. apply pending patches to ``value`` and return the value actually put
  1044. in cache.
  1045. """
  1046. field_patches = self._patches.get(field)
  1047. if field_patches:
  1048. ids = field_patches.pop(record.id, ())
  1049. if ids:
  1050. value = tuple(dict.fromkeys(value + tuple(ids)))
  1051. self.set(record, field, value)
  1052. return value
  1053. def remove(self, record, field):
  1054. """ Remove the value of ``field`` for ``record``. """
  1055. assert record.id not in self._dirty.get(field, ())
  1056. try:
  1057. field_cache = self._set_field_cache(record, field)
  1058. del field_cache[record._ids[0]]
  1059. except KeyError:
  1060. pass
  1061. def get_values(self, records, field):
  1062. """ Return the cached values of ``field`` for ``records``. """
  1063. field_cache = self._get_field_cache(records, field)
  1064. for record_id in records._ids:
  1065. try:
  1066. yield field_cache[record_id]
  1067. except KeyError:
  1068. pass
  1069. def get_until_miss(self, records, field):
  1070. """ Return the cached values of ``field`` for ``records`` until a value is not found. """
  1071. field_cache = self._get_field_cache(records, field)
  1072. if field.translate:
  1073. lang = (records.env.lang or 'en_US') if field.translate is True else records.env._lang
  1074. def get_value(id_):
  1075. cache_value = field_cache[id_]
  1076. return None if cache_value is None else cache_value[lang]
  1077. else:
  1078. get_value = field_cache.__getitem__
  1079. vals = []
  1080. for record_id in records._ids:
  1081. try:
  1082. vals.append(get_value(record_id))
  1083. except KeyError:
  1084. break
  1085. return vals
  1086. def get_records_different_from(self, records, field, value):
  1087. """ Return the subset of ``records`` that has not ``value`` for ``field``. """
  1088. field_cache = self._get_field_cache(records, field)
  1089. if field.translate:
  1090. lang = records.env.lang or 'en_US'
  1091. def get_value(id_):
  1092. cache_value = field_cache[id_]
  1093. return None if cache_value is None else cache_value[lang]
  1094. else:
  1095. get_value = field_cache.__getitem__
  1096. ids = []
  1097. for record_id in records._ids:
  1098. try:
  1099. val = get_value(record_id)
  1100. except KeyError:
  1101. ids.append(record_id)
  1102. else:
  1103. if field.type == "monetary":
  1104. value = field.convert_to_cache(value, records.browse(record_id))
  1105. if val != value:
  1106. ids.append(record_id)
  1107. return records.browse(ids)
  1108. def get_fields(self, record):
  1109. """ Return the fields with a value for ``record``. """
  1110. for name, field in record._fields.items():
  1111. if name != 'id' and record.id in self._get_field_cache(record, field):
  1112. yield field
  1113. def get_records(self, model, field, all_contexts=False):
  1114. """ Return the records of ``model`` that have a value for ``field``.
  1115. By default the method checks for values in the current context of ``model``.
  1116. But when ``all_contexts`` is true, it checks for values *in all contexts*.
  1117. """
  1118. if all_contexts and field in model.pool.field_depends_context:
  1119. field_cache = self._data.get(field, EMPTY_DICT)
  1120. ids = OrderedSet(id_ for sub_cache in field_cache.values() for id_ in sub_cache)
  1121. else:
  1122. ids = self._get_field_cache(model, field)
  1123. return model.browse(ids)
  1124. def get_missing_ids(self, records, field):
  1125. """ Return the ids of ``records`` that have no value for ``field``. """
  1126. field_cache = self._get_field_cache(records, field)
  1127. if field.translate:
  1128. lang = (records.env.lang or 'en_US') if field.translate is True else records.env._lang
  1129. for record_id in records._ids:
  1130. cache_value = field_cache.get(record_id, False)
  1131. if cache_value is False or not (cache_value is None or lang in cache_value):
  1132. yield record_id
  1133. else:
  1134. for record_id in records._ids:
  1135. if record_id not in field_cache:
  1136. yield record_id
  1137. def get_dirty_fields(self):
  1138. """ Return the fields that have dirty records in cache. """
  1139. return self._dirty.keys()
  1140. def get_dirty_records(self, model, field):
  1141. """ Return the records that for which ``field`` is dirty in cache. """
  1142. return model.browse(self._dirty.get(field, ()))
  1143. def has_dirty_fields(self, records, fields=None):
  1144. """ Return whether any of the given records has dirty fields.
  1145. :param fields: a collection of fields or ``None``; the value ``None`` is
  1146. interpreted as any field on ``records``
  1147. """
  1148. if fields is None:
  1149. return any(
  1150. not ids.isdisjoint(records._ids)
  1151. for field, ids in self._dirty.items()
  1152. if field.model_name == records._name
  1153. )
  1154. else:
  1155. return any(
  1156. field in self._dirty and not self._dirty[field].isdisjoint(records._ids)
  1157. for field in fields
  1158. )
  1159. def clear_dirty_field(self, field):
  1160. """ Make the given field clean on all records, and return the ids of the
  1161. formerly dirty records for the field.
  1162. """
  1163. return self._dirty.pop(field, ())
  1164. def invalidate(self, spec=None):
  1165. """ Invalidate the cache, partially or totally depending on ``spec``.
  1166. If a field is context-dependent, invalidating it for a given record
  1167. actually invalidates all the values of that field on the record. In
  1168. other words, the field is invalidated for the record in all
  1169. environments.
  1170. This operation is unsafe by default, and must be used with care.
  1171. Indeed, invalidating a dirty field on a record may lead to an error,
  1172. because doing so drops the value to be written in database.
  1173. spec = [(field, ids), (field, None), ...]
  1174. """
  1175. if spec is None:
  1176. self._data.clear()
  1177. elif spec:
  1178. for field, ids in spec:
  1179. if ids is None:
  1180. self._data.pop(field, None)
  1181. continue
  1182. cache = self._data.get(field)
  1183. if not cache:
  1184. continue
  1185. caches = cache.values() if isinstance(next(iter(cache)), tuple) else [cache]
  1186. for field_cache in caches:
  1187. for id_ in ids:
  1188. field_cache.pop(id_, None)
  1189. def clear(self):
  1190. """ Invalidate the cache and its dirty flags. """
  1191. self._data.clear()
  1192. self._dirty.clear()
  1193. self._patches.clear()
  1194. def check(self, env):
  1195. """ Check the consistency of the cache for the given environment. """
  1196. depends_context = env.registry.field_depends_context
  1197. invalids = []
  1198. def process(model, field, field_cache):
  1199. # ignore new records and records to flush
  1200. dirty_ids = self._dirty.get(field, ())
  1201. ids = [id_ for id_ in field_cache if id_ and id_ not in dirty_ids]
  1202. if not ids:
  1203. return
  1204. # select the column for the given ids
  1205. query = Query(env, model._table, model._table_sql)
  1206. sql_id = SQL.identifier(model._table, 'id')
  1207. sql_field = model._field_to_sql(model._table, field.name, query)
  1208. if field.type == 'binary' and (
  1209. model.env.context.get('bin_size') or model.env.context.get('bin_size_' + field.name)
  1210. ):
  1211. sql_field = SQL('pg_size_pretty(length(%s)::bigint)', sql_field)
  1212. query.add_where(SQL("%s IN %s", sql_id, tuple(ids)))
  1213. env.cr.execute(query.select(sql_id, sql_field))
  1214. # compare returned values with corresponding values in cache
  1215. for id_, value in env.cr.fetchall():
  1216. cached = field_cache[id_]
  1217. if value == cached or (not value and not cached):
  1218. continue
  1219. invalids.append((model.browse(id_), field, {'cached': cached, 'fetched': value}))
  1220. for field, field_cache in self._data.items():
  1221. # check column fields only
  1222. if not field.store or not field.column_type or field.translate or field.company_dependent:
  1223. continue
  1224. model = env[field.model_name]
  1225. if field in depends_context:
  1226. for context_keys, inner_cache in field_cache.items():
  1227. context = dict(zip(depends_context[field], context_keys))
  1228. if 'company' in context:
  1229. # the cache key 'company' actually comes from context
  1230. # key 'allowed_company_ids' (see property env.company
  1231. # and method env.cache_key())
  1232. context['allowed_company_ids'] = [context.pop('company')]
  1233. process(model.with_context(context), field, inner_cache)
  1234. else:
  1235. process(model, field, field_cache)
  1236. if invalids:
  1237. _logger.warning("Invalid cache: %s", pformat(invalids))
  1238. def _get_grouped_company_dependent_field_cache(self, field):
  1239. """
  1240. get a field cache proxy to group up field cache value for a company
  1241. dependent field
  1242. cache data: {field: {(company_id,): {id: value}}}
  1243. :param field: a company dependent field
  1244. :return: a dict like field cache proxy which is logically similar to
  1245. {id: {company_id, value}}
  1246. """
  1247. field_caches = self._data.get(field, EMPTY_DICT)
  1248. company_field_cache = {
  1249. context_key[0]: field_cache
  1250. for context_key, field_cache in field_caches.items()
  1251. }
  1252. return GroupedCompanyDependentFieldCache(company_field_cache)
  1253. class GroupedCompanyDependentFieldCache:
  1254. def __init__(self, company_field_cache):
  1255. self._company_field_cache = company_field_cache
  1256. def __getitem__(self, id_):
  1257. return {
  1258. company_id: field_cache[id_]
  1259. for company_id, field_cache in self._company_field_cache.items()
  1260. if id_ in field_cache
  1261. }
  1262. class Starred:
  1263. """ Simple helper class to ``repr`` a value with a star suffix. """
  1264. __slots__ = ['value']
  1265. def __init__(self, value):
  1266. self.value = value
  1267. def __repr__(self):
  1268. return f"{self.value!r}*"
  1269. # keep those imports here in order to handle cyclic dependencies correctly
  1270. from odoo import SUPERUSER_ID
  1271. from odoo.modules.registry import Registry
  1272. from .sql_db import BaseCursor
上海开阖软件有限公司 沪ICP备12045867号-1