gooderp18绿色标准版
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1088 行
45KB

  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. """ Models registries.
  4. """
  5. from __future__ import annotations
  6. import inspect
  7. import logging
  8. import os
  9. import threading
  10. import time
  11. import typing
  12. import warnings
  13. from collections import defaultdict, deque
  14. from collections.abc import Mapping
  15. from contextlib import closing, contextmanager, nullcontext
  16. from functools import partial
  17. from operator import attrgetter
  18. import psycopg2
  19. import odoo
  20. from odoo.modules.db import FunctionStatus
  21. from .. import SUPERUSER_ID
  22. from odoo.sql_db import TestCursor
  23. from odoo.tools import (
  24. config, lazy_classproperty,
  25. lazy_property, sql, OrderedSet, SQL,
  26. remove_accents,
  27. )
  28. from odoo.tools.func import locked
  29. from odoo.tools.lru import LRU
  30. from odoo.tools.misc import Collector, format_frame
  31. if typing.TYPE_CHECKING:
  32. from odoo.models import BaseModel
  33. _logger = logging.getLogger(__name__)
  34. _schema = logging.getLogger('odoo.schema')
  35. _REGISTRY_CACHES = {
  36. 'default': 8192,
  37. 'assets': 512, # arbitrary
  38. 'templates': 1024, # arbitrary
  39. 'routing': 1024, # 2 entries per website
  40. 'routing.rewrites': 8192, # url_rewrite entries
  41. 'templates.cached_values': 2048, # arbitrary
  42. 'groups': 1, # contains all res.groups
  43. }
  44. # cache invalidation dependencies, as follows:
  45. # { 'cache_key': ('cache_container_1', 'cache_container_3', ...) }
  46. _CACHES_BY_KEY = {
  47. 'default': ('default', 'templates.cached_values'),
  48. 'assets': ('assets', 'templates.cached_values'),
  49. 'templates': ('templates', 'templates.cached_values'),
  50. 'routing': ('routing', 'routing.rewrites', 'templates.cached_values'),
  51. 'groups': ('groups', 'templates', 'templates.cached_values'), # The processing of groups is saved in the view
  52. }
  53. def _unaccent(x):
  54. if isinstance(x, SQL):
  55. return SQL("unaccent(%s)", x)
  56. if isinstance(x, psycopg2.sql.Composable):
  57. return psycopg2.sql.SQL('unaccent({})').format(x)
  58. return f'unaccent({x})'
  59. class Registry(Mapping):
  60. """ Model registry for a particular database.
  61. The registry is essentially a mapping between model names and model classes.
  62. There is one registry instance per database.
  63. """
  64. _lock = threading.RLock()
  65. _saved_lock = None
  66. @lazy_classproperty
  67. def registries(cls):
  68. """ A mapping from database names to registries. """
  69. size = config.get('registry_lru_size', None)
  70. if not size:
  71. # Size the LRU depending of the memory limits
  72. if os.name != 'posix':
  73. # cannot specify the memory limit soft on windows...
  74. size = 42
  75. else:
  76. # A registry takes 10MB of memory on average, so we reserve
  77. # 10Mb (registry) + 5Mb (working memory) per registry
  78. avgsz = 15 * 1024 * 1024
  79. size = int(config['limit_memory_soft'] / avgsz)
  80. return LRU(size)
  81. def __new__(cls, db_name):
  82. """ Return the registry for the given database name."""
  83. assert db_name, "Missing database name"
  84. with cls._lock:
  85. try:
  86. return cls.registries[db_name]
  87. except KeyError:
  88. return cls.new(db_name)
  89. @classmethod
  90. @locked
  91. def new(cls, db_name, force_demo=False, status=None, update_module=False):
  92. """ Create and return a new registry for the given database name. """
  93. t0 = time.time()
  94. registry = object.__new__(cls)
  95. registry.init(db_name)
  96. registry.new = registry.init = registry.registries = None
  97. # Initializing a registry will call general code which will in
  98. # turn call Registry() to obtain the registry being initialized.
  99. # Make it available in the registries dictionary then remove it
  100. # if an exception is raised.
  101. cls.delete(db_name)
  102. cls.registries[db_name] = registry # pylint: disable=unsupported-assignment-operation
  103. try:
  104. registry.setup_signaling()
  105. # This should be a method on Registry
  106. try:
  107. odoo.modules.load_modules(registry, force_demo, status, update_module)
  108. except Exception:
  109. odoo.modules.reset_modules_state(db_name)
  110. raise
  111. except Exception:
  112. _logger.error('Failed to load registry')
  113. del cls.registries[db_name] # pylint: disable=unsupported-delete-operation
  114. raise
  115. # load_modules() above can replace the registry by calling
  116. # indirectly new() again (when modules have to be uninstalled).
  117. # Yeah, crazy.
  118. registry = cls.registries[db_name] # pylint: disable=unsubscriptable-object
  119. registry._init = False
  120. registry.ready = True
  121. registry.registry_invalidated = bool(update_module)
  122. registry.signal_changes()
  123. _logger.info("Registry loaded in %.3fs", time.time() - t0)
  124. return registry
  125. def init(self, db_name):
  126. self.models: dict[str, type[BaseModel]] = {} # model name/model instance mapping
  127. self._sql_constraints = set()
  128. self._init = True
  129. self._database_translated_fields = () # names of translated fields in database
  130. if config['test_enable'] or config['test_file']:
  131. from odoo.tests.result import OdooTestResult # noqa: PLC0415
  132. self._assertion_report = OdooTestResult()
  133. else:
  134. self._assertion_report = None
  135. self._fields_by_model = None
  136. self._ordinary_tables = None
  137. self._constraint_queue = deque()
  138. self.__caches = {cache_name: LRU(cache_size) for cache_name, cache_size in _REGISTRY_CACHES.items()}
  139. # modules fully loaded (maintained during init phase by `loading` module)
  140. self._init_modules = set()
  141. self.updated_modules = [] # installed/updated modules
  142. self.loaded_xmlids = set()
  143. self.db_name = db_name
  144. self._db = odoo.sql_db.db_connect(db_name, readonly=False)
  145. self._db_readonly = None
  146. if config['db_replica_host'] is not False or config['test_enable']: # by default, only use readonly pool if we have a db_replica_host defined. Allows to have an empty replica host for testing
  147. self._db_readonly = odoo.sql_db.db_connect(db_name, readonly=True)
  148. # cursor for test mode; None means "normal" mode
  149. self.test_cr = None
  150. self.test_lock = None
  151. # Indicates that the registry is
  152. self.loaded = False # whether all modules are loaded
  153. self.ready = False # whether everything is set up
  154. # field dependencies
  155. self.field_depends = Collector()
  156. self.field_depends_context = Collector()
  157. self.field_inverses = Collector()
  158. # company dependent
  159. self.many2one_company_dependents = Collector() # {model_name: (field1, field2, ...)}
  160. # cache of methods get_field_trigger_tree() and is_modifying_relations()
  161. self._field_trigger_trees = {}
  162. self._is_modifying_relations = {}
  163. # Inter-process signaling:
  164. # The `base_registry_signaling` sequence indicates the whole registry
  165. # must be reloaded.
  166. # The `base_cache_signaling sequence` indicates all caches must be
  167. # invalidated (i.e. cleared).
  168. self.registry_sequence = None
  169. self.cache_sequences = {}
  170. # Flags indicating invalidation of the registry or the cache.
  171. self._invalidation_flags = threading.local()
  172. with closing(self.cursor()) as cr:
  173. self.has_unaccent = odoo.modules.db.has_unaccent(cr)
  174. self.has_trigram = odoo.modules.db.has_trigram(cr)
  175. self.unaccent = _unaccent if self.has_unaccent else lambda x: x
  176. self.unaccent_python = remove_accents if self.has_unaccent else lambda x: x
  177. @classmethod
  178. @locked
  179. def delete(cls, db_name):
  180. """ Delete the registry linked to a given database. """
  181. if db_name in cls.registries: # pylint: disable=unsupported-membership-test
  182. del cls.registries[db_name] # pylint: disable=unsupported-delete-operation
  183. @classmethod
  184. @locked
  185. def delete_all(cls):
  186. """ Delete all the registries. """
  187. cls.registries.clear()
  188. #
  189. # Mapping abstract methods implementation
  190. # => mixin provides methods keys, items, values, get, __eq__, and __ne__
  191. #
  192. def __len__(self):
  193. """ Return the size of the registry. """
  194. return len(self.models)
  195. def __iter__(self):
  196. """ Return an iterator over all model names. """
  197. return iter(self.models)
  198. def __getitem__(self, model_name: str) -> type[BaseModel]:
  199. """ Return the model with the given name or raise KeyError if it doesn't exist."""
  200. return self.models[model_name]
  201. def __call__(self, model_name):
  202. """ Same as ``self[model_name]``. """
  203. return self.models[model_name]
  204. def __setitem__(self, model_name, model):
  205. """ Add or replace a model in the registry."""
  206. self.models[model_name] = model
  207. def __delitem__(self, model_name):
  208. """ Remove a (custom) model from the registry. """
  209. del self.models[model_name]
  210. # the custom model can inherit from mixins ('mail.thread', ...)
  211. for Model in self.models.values():
  212. Model._inherit_children.discard(model_name)
  213. def descendants(self, model_names, *kinds):
  214. """ Return the models corresponding to ``model_names`` and all those
  215. that inherit/inherits from them.
  216. """
  217. assert all(kind in ('_inherit', '_inherits') for kind in kinds)
  218. funcs = [attrgetter(kind + '_children') for kind in kinds]
  219. models = OrderedSet()
  220. queue = deque(model_names)
  221. while queue:
  222. model = self[queue.popleft()]
  223. models.add(model._name)
  224. for func in funcs:
  225. queue.extend(func(model))
  226. return models
  227. def load(self, cr, module):
  228. """ Load a given module in the registry, and return the names of the
  229. modified models.
  230. At the Python level, the modules are already loaded, but not yet on a
  231. per-registry level. This method populates a registry with the given
  232. modules, i.e. it instantiates all the classes of a the given module
  233. and registers them in the registry.
  234. """
  235. from .. import models
  236. # clear cache to ensure consistency, but do not signal it
  237. for cache in self.__caches.values():
  238. cache.clear()
  239. lazy_property.reset_all(self)
  240. self._field_trigger_trees.clear()
  241. self._is_modifying_relations.clear()
  242. # Instantiate registered classes (via the MetaModel automatic discovery
  243. # or via explicit constructor call), and add them to the pool.
  244. model_names = []
  245. for cls in models.MetaModel.module_to_models.get(module.name, []):
  246. # models register themselves in self.models
  247. model = cls._build_model(self, cr)
  248. model_names.append(model._name)
  249. return self.descendants(model_names, '_inherit', '_inherits')
  250. @locked
  251. def setup_models(self, cr):
  252. """ Complete the setup of models.
  253. This must be called after loading modules and before using the ORM.
  254. """
  255. env = odoo.api.Environment(cr, SUPERUSER_ID, {})
  256. env.invalidate_all()
  257. # Uninstall registry hooks. Because of the condition, this only happens
  258. # on a fully loaded registry, and not on a registry being loaded.
  259. if self.ready:
  260. for model in env.values():
  261. model._unregister_hook()
  262. # clear cache to ensure consistency, but do not signal it
  263. for cache in self.__caches.values():
  264. cache.clear()
  265. lazy_property.reset_all(self)
  266. self._field_trigger_trees.clear()
  267. self._is_modifying_relations.clear()
  268. self.registry_invalidated = True
  269. # we must setup ir.model before adding manual fields because _add_manual_models may
  270. # depend on behavior that is implemented through overrides, such as is_mail_thread which
  271. # is implemented through an override to env['ir.model']._instanciate
  272. env['ir.model']._prepare_setup()
  273. # add manual models
  274. if self._init_modules:
  275. env['ir.model']._add_manual_models()
  276. # prepare the setup on all models
  277. models = list(env.values())
  278. for model in models:
  279. model._prepare_setup()
  280. self.field_depends.clear()
  281. self.field_depends_context.clear()
  282. self.field_inverses.clear()
  283. self.many2one_company_dependents.clear()
  284. # do the actual setup
  285. for model in models:
  286. model._setup_base()
  287. self._m2m = defaultdict(list)
  288. for model in models:
  289. model._setup_fields()
  290. del self._m2m
  291. for model in models:
  292. model._setup_complete()
  293. # determine field_depends and field_depends_context
  294. for model in models:
  295. for field in model._fields.values():
  296. depends, depends_context = field.get_depends(model)
  297. self.field_depends[field] = tuple(depends)
  298. self.field_depends_context[field] = tuple(depends_context)
  299. # clean the lazy_property again in case they are cached by another ongoing registry readonly request
  300. lazy_property.reset_all(self)
  301. # Reinstall registry hooks. Because of the condition, this only happens
  302. # on a fully loaded registry, and not on a registry being loaded.
  303. if self.ready:
  304. for model in env.values():
  305. model._register_hook()
  306. env.flush_all()
  307. @lazy_property
  308. def field_computed(self):
  309. """ Return a dict mapping each field to the fields computed by the same method. """
  310. computed = {}
  311. for model_name, Model in self.models.items():
  312. groups = defaultdict(list)
  313. for field in Model._fields.values():
  314. if field.compute:
  315. computed[field] = group = groups[field.compute]
  316. group.append(field)
  317. for fields in groups.values():
  318. if len(fields) < 2:
  319. continue
  320. if len({field.compute_sudo for field in fields}) > 1:
  321. fnames = ", ".join(field.name for field in fields)
  322. warnings.warn(
  323. f"{model_name}: inconsistent 'compute_sudo' for computed fields {fnames}. "
  324. f"Either set 'compute_sudo' to the same value on all those fields, or "
  325. f"use distinct compute methods for sudoed and non-sudoed fields."
  326. )
  327. if len({field.precompute for field in fields}) > 1:
  328. fnames = ", ".join(field.name for field in fields)
  329. warnings.warn(
  330. f"{model_name}: inconsistent 'precompute' for computed fields {fnames}. "
  331. f"Either set all fields as precompute=True (if possible), or "
  332. f"use distinct compute methods for precomputed and non-precomputed fields."
  333. )
  334. if len({field.store for field in fields}) > 1:
  335. fnames1 = ", ".join(field.name for field in fields if not field.store)
  336. fnames2 = ", ".join(field.name for field in fields if field.store)
  337. warnings.warn(
  338. f"{model_name}: inconsistent 'store' for computed fields, "
  339. f"accessing {fnames1} may recompute and update {fnames2}. "
  340. f"Use distinct compute methods for stored and non-stored fields."
  341. )
  342. return computed
  343. def get_trigger_tree(self, fields: list, select=bool) -> "TriggerTree":
  344. """ Return the trigger tree to traverse when ``fields`` have been modified.
  345. The function ``select`` is called on every field to determine which fields
  346. should be kept in the tree nodes. This enables to discard some unnecessary
  347. fields from the tree nodes.
  348. """
  349. trees = [
  350. self.get_field_trigger_tree(field)
  351. for field in fields
  352. if field in self._field_triggers
  353. ]
  354. return TriggerTree.merge(trees, select)
  355. def get_dependent_fields(self, field):
  356. """ Return an iterable on the fields that depend on ``field``. """
  357. if field not in self._field_triggers:
  358. return ()
  359. return (
  360. dependent
  361. for tree in self.get_field_trigger_tree(field).depth_first()
  362. for dependent in tree.root
  363. )
  364. def _discard_fields(self, fields: list):
  365. """ Discard the given fields from the registry's internal data structures. """
  366. for f in fields:
  367. # tests usually don't reload the registry, so when they create
  368. # custom fields those may not have the entire dependency setup, and
  369. # may be missing from these maps
  370. self.field_depends.pop(f, None)
  371. # discard fields from field triggers
  372. self.__dict__.pop('_field_triggers', None)
  373. self._field_trigger_trees.clear()
  374. self._is_modifying_relations.clear()
  375. # discard fields from field inverses
  376. self.field_inverses.discard_keys_and_values(fields)
  377. def get_field_trigger_tree(self, field) -> "TriggerTree":
  378. """ Return the trigger tree of a field by computing it from the transitive
  379. closure of field triggers.
  380. """
  381. try:
  382. return self._field_trigger_trees[field]
  383. except KeyError:
  384. pass
  385. triggers = self._field_triggers
  386. if field not in triggers:
  387. return TriggerTree()
  388. def transitive_triggers(field, prefix=(), seen=()):
  389. if field in seen or field not in triggers:
  390. return
  391. for path, targets in triggers[field].items():
  392. full_path = concat(prefix, path)
  393. yield full_path, targets
  394. for target in targets:
  395. yield from transitive_triggers(target, full_path, seen + (field,))
  396. def concat(seq1, seq2):
  397. if seq1 and seq2:
  398. f1, f2 = seq1[-1], seq2[0]
  399. if (
  400. f1.type == 'many2one' and f2.type == 'one2many'
  401. and f1.name == f2.inverse_name
  402. and f1.model_name == f2.comodel_name
  403. and f1.comodel_name == f2.model_name
  404. ):
  405. return concat(seq1[:-1], seq2[1:])
  406. return seq1 + seq2
  407. tree = TriggerTree()
  408. for path, targets in transitive_triggers(field):
  409. current = tree
  410. for label in path:
  411. current = current.increase(label)
  412. if current.root:
  413. current.root.update(targets)
  414. else:
  415. current.root = OrderedSet(targets)
  416. self._field_trigger_trees[field] = tree
  417. return tree
  418. @lazy_property
  419. def _field_triggers(self):
  420. """ Return the field triggers, i.e., the inverse of field dependencies,
  421. as a dictionary like ``{field: {path: fields}}``, where ``field`` is a
  422. dependency, ``path`` is a sequence of fields to inverse and ``fields``
  423. is a collection of fields that depend on ``field``.
  424. """
  425. triggers = defaultdict(lambda: defaultdict(OrderedSet))
  426. for Model in self.models.values():
  427. if Model._abstract:
  428. continue
  429. for field in Model._fields.values():
  430. try:
  431. dependencies = list(field.resolve_depends(self))
  432. except Exception:
  433. # dependencies of custom fields may not exist; ignore that case
  434. if not field.base_field.manual:
  435. raise
  436. else:
  437. for dependency in dependencies:
  438. *path, dep_field = dependency
  439. triggers[dep_field][tuple(reversed(path))].add(field)
  440. return triggers
  441. def is_modifying_relations(self, field):
  442. """ Return whether ``field`` has dependent fields on some records, and
  443. that modifying ``field`` might change the dependent records.
  444. """
  445. try:
  446. return self._is_modifying_relations[field]
  447. except KeyError:
  448. result = field in self._field_triggers and (
  449. field.relational or self.field_inverses[field] or any(
  450. dep.relational or self.field_inverses[dep]
  451. for dep in self.get_dependent_fields(field)
  452. )
  453. )
  454. self._is_modifying_relations[field] = result
  455. return result
  456. def post_init(self, func, *args, **kwargs):
  457. """ Register a function to call at the end of :meth:`~.init_models`. """
  458. self._post_init_queue.append(partial(func, *args, **kwargs))
  459. def post_constraint(self, func, *args, **kwargs):
  460. """ Call the given function, and delay it if it fails during an upgrade. """
  461. try:
  462. if (func, args, kwargs) not in self._constraint_queue:
  463. # Module A may try to apply a constraint and fail but another module B inheriting
  464. # from Module A may try to reapply the same constraint and succeed, however the
  465. # constraint would already be in the _constraint_queue and would be executed again
  466. # at the end of the registry cycle, this would fail (already-existing constraint)
  467. # and generate an error, therefore a constraint should only be applied if it's
  468. # not already marked as "to be applied".
  469. func(*args, **kwargs)
  470. except Exception as e:
  471. if self._is_install:
  472. _schema.error(*e.args)
  473. else:
  474. _schema.info(*e.args)
  475. self._constraint_queue.append((func, args, kwargs))
  476. def finalize_constraints(self):
  477. """ Call the delayed functions from above. """
  478. while self._constraint_queue:
  479. func, args, kwargs = self._constraint_queue.popleft()
  480. try:
  481. func(*args, **kwargs)
  482. except Exception as e:
  483. # warn only, this is not a deployment showstopper, and
  484. # can sometimes be a transient error
  485. _schema.warning(*e.args)
  486. def init_models(self, cr, model_names, context, install=True):
  487. """ Initialize a list of models (given by their name). Call methods
  488. ``_auto_init`` and ``init`` on each model to create or update the
  489. database tables supporting the models.
  490. The ``context`` may contain the following items:
  491. - ``module``: the name of the module being installed/updated, if any;
  492. - ``update_custom_fields``: whether custom fields should be updated.
  493. """
  494. if not model_names:
  495. return
  496. if 'module' in context:
  497. _logger.info('module %s: creating or updating database tables', context['module'])
  498. elif context.get('models_to_check', False):
  499. _logger.info("verifying fields for every extended model")
  500. env = odoo.api.Environment(cr, SUPERUSER_ID, context)
  501. models = [env[model_name] for model_name in model_names]
  502. try:
  503. self._post_init_queue = deque()
  504. self._foreign_keys = {}
  505. self._is_install = install
  506. for model in models:
  507. model._auto_init()
  508. model.init()
  509. env['ir.model']._reflect_models(model_names)
  510. env['ir.model.fields']._reflect_fields(model_names)
  511. env['ir.model.fields.selection']._reflect_selections(model_names)
  512. env['ir.model.constraint']._reflect_constraints(model_names)
  513. env['ir.model.inherit']._reflect_inherits(model_names)
  514. self._ordinary_tables = None
  515. while self._post_init_queue:
  516. func = self._post_init_queue.popleft()
  517. func()
  518. self.check_indexes(cr, model_names)
  519. self.check_foreign_keys(cr)
  520. env.flush_all()
  521. # make sure all tables are present
  522. self.check_tables_exist(cr)
  523. finally:
  524. del self._post_init_queue
  525. del self._foreign_keys
  526. del self._is_install
  527. def check_indexes(self, cr, model_names):
  528. """ Create or drop column indexes for the given models. """
  529. expected = [
  530. (sql.make_index_name(Model._table, field.name), Model._table, field)
  531. for model_name in model_names
  532. for Model in [self.models[model_name]]
  533. if Model._auto and not Model._abstract
  534. for field in Model._fields.values()
  535. if field.column_type and field.store
  536. ]
  537. if not expected:
  538. return
  539. # retrieve existing indexes with their corresponding table
  540. cr.execute("SELECT indexname, tablename FROM pg_indexes WHERE indexname IN %s",
  541. [tuple(row[0] for row in expected)])
  542. existing = dict(cr.fetchall())
  543. for indexname, tablename, field in expected:
  544. index = field.index
  545. assert index in ('btree', 'btree_not_null', 'trigram', True, False, None)
  546. if index and indexname not in existing and \
  547. ((not field.translate and index != 'trigram') or (index == 'trigram' and self.has_trigram)):
  548. column_expression = f'"{field.name}"'
  549. if index == 'trigram':
  550. if field.translate:
  551. column_expression = f'''(jsonb_path_query_array({column_expression}, '$.*')::text)'''
  552. # add `unaccent` to the trigram index only because the
  553. # trigram indexes are mainly used for (=)ilike search and
  554. # unaccent is added only in these cases when searching
  555. if self.has_unaccent == FunctionStatus.INDEXABLE:
  556. column_expression = self.unaccent(column_expression)
  557. elif self.has_unaccent:
  558. warnings.warn(
  559. "PostgreSQL function 'unaccent' is present but not immutable, "
  560. "therefore trigram indexes may not be effective.",
  561. )
  562. expression = f'{column_expression} gin_trgm_ops'
  563. method = 'gin'
  564. where = ''
  565. elif index == 'btree_not_null' and field.company_dependent:
  566. # company dependent condition will use extra
  567. # `AND col IS NOT NULL` to use the index.
  568. expression = f'({column_expression} IS NOT NULL)'
  569. method = 'btree'
  570. where = f'{column_expression} IS NOT NULL'
  571. else: # index in ['btree', 'btree_not_null', True]
  572. expression = f'{column_expression}'
  573. method = 'btree'
  574. where = f'{column_expression} IS NOT NULL' if index == 'btree_not_null' else ''
  575. try:
  576. with cr.savepoint(flush=False):
  577. sql.create_index(cr, indexname, tablename, [expression], method, where)
  578. except psycopg2.OperationalError:
  579. _schema.error("Unable to add index for %s", self)
  580. elif not index and tablename == existing.get(indexname):
  581. _schema.info("Keep unexpected index %s on table %s", indexname, tablename)
  582. def add_foreign_key(self, table1, column1, table2, column2, ondelete,
  583. model, module, force=True):
  584. """ Specify an expected foreign key. """
  585. key = (table1, column1)
  586. val = (table2, column2, ondelete, model, module)
  587. if force:
  588. self._foreign_keys[key] = val
  589. else:
  590. self._foreign_keys.setdefault(key, val)
  591. def check_foreign_keys(self, cr):
  592. """ Create or update the expected foreign keys. """
  593. if not self._foreign_keys:
  594. return
  595. # determine existing foreign keys on the tables
  596. query = """
  597. SELECT fk.conname, c1.relname, a1.attname, c2.relname, a2.attname, fk.confdeltype
  598. FROM pg_constraint AS fk
  599. JOIN pg_class AS c1 ON fk.conrelid = c1.oid
  600. JOIN pg_class AS c2 ON fk.confrelid = c2.oid
  601. JOIN pg_attribute AS a1 ON a1.attrelid = c1.oid AND fk.conkey[1] = a1.attnum
  602. JOIN pg_attribute AS a2 ON a2.attrelid = c2.oid AND fk.confkey[1] = a2.attnum
  603. WHERE fk.contype = 'f' AND c1.relname IN %s
  604. """
  605. cr.execute(query, [tuple({table for table, column in self._foreign_keys})])
  606. existing = {
  607. (table1, column1): (name, table2, column2, deltype)
  608. for name, table1, column1, table2, column2, deltype in cr.fetchall()
  609. }
  610. # create or update foreign keys
  611. for key, val in self._foreign_keys.items():
  612. table1, column1 = key
  613. table2, column2, ondelete, model, module = val
  614. deltype = sql._CONFDELTYPES[ondelete.upper()]
  615. spec = existing.get(key)
  616. if spec is None:
  617. sql.add_foreign_key(cr, table1, column1, table2, column2, ondelete)
  618. conname = sql.get_foreign_keys(cr, table1, column1, table2, column2, ondelete)[0]
  619. model.env['ir.model.constraint']._reflect_constraint(model, conname, 'f', None, module)
  620. elif (spec[1], spec[2], spec[3]) != (table2, column2, deltype):
  621. sql.drop_constraint(cr, table1, spec[0])
  622. sql.add_foreign_key(cr, table1, column1, table2, column2, ondelete)
  623. conname = sql.get_foreign_keys(cr, table1, column1, table2, column2, ondelete)[0]
  624. model.env['ir.model.constraint']._reflect_constraint(model, conname, 'f', None, module)
  625. def check_tables_exist(self, cr):
  626. """
  627. Verify that all tables are present and try to initialize those that are missing.
  628. """
  629. env = odoo.api.Environment(cr, SUPERUSER_ID, {})
  630. table2model = {
  631. model._table: name
  632. for name, model in env.registry.items()
  633. if not model._abstract and model._table_query is None
  634. }
  635. missing_tables = set(table2model).difference(sql.existing_tables(cr, table2model))
  636. if missing_tables:
  637. missing = {table2model[table] for table in missing_tables}
  638. _logger.info("Models have no table: %s.", ", ".join(missing))
  639. # recreate missing tables
  640. for name in missing:
  641. _logger.info("Recreate table of model %s.", name)
  642. env[name].init()
  643. env.flush_all()
  644. # check again, and log errors if tables are still missing
  645. missing_tables = set(table2model).difference(sql.existing_tables(cr, table2model))
  646. for table in missing_tables:
  647. _logger.error("Model %s has no table.", table2model[table])
  648. def clear_cache(self, *cache_names):
  649. """ Clear the caches associated to methods decorated with
  650. ``tools.ormcache``if cache is in `cache_name` subset. """
  651. cache_names = cache_names or ('default',)
  652. assert not any('.' in cache_name for cache_name in cache_names)
  653. for cache_name in cache_names:
  654. for cache in _CACHES_BY_KEY[cache_name]:
  655. self.__caches[cache].clear()
  656. self.cache_invalidated.add(cache_name)
  657. # log information about invalidation_cause
  658. if _logger.isEnabledFor(logging.DEBUG):
  659. # could be interresting to log in info but this will need to minimize invalidation first,
  660. # mainly in some setupclass and crons
  661. caller_info = format_frame(inspect.currentframe().f_back)
  662. _logger.debug('Invalidating %s model caches from %s', ','.join(cache_names), caller_info)
  663. def clear_all_caches(self):
  664. """ Clear the caches associated to methods decorated with
  665. ``tools.ormcache``.
  666. """
  667. for cache_name, caches in _CACHES_BY_KEY.items():
  668. for cache in caches:
  669. self.__caches[cache].clear()
  670. self.cache_invalidated.add(cache_name)
  671. caller_info = format_frame(inspect.currentframe().f_back)
  672. log = _logger.info if self.loaded else _logger.debug
  673. log('Invalidating all model caches from %s', caller_info)
  674. def is_an_ordinary_table(self, model):
  675. """ Return whether the given model has an ordinary table. """
  676. if self._ordinary_tables is None:
  677. cr = model.env.cr
  678. query = """
  679. SELECT c.relname
  680. FROM pg_class c
  681. JOIN pg_namespace n ON (n.oid = c.relnamespace)
  682. WHERE c.relname IN %s
  683. AND c.relkind = 'r'
  684. AND n.nspname = 'public'
  685. """
  686. tables = tuple(m._table for m in self.models.values())
  687. cr.execute(query, [tables])
  688. self._ordinary_tables = {row[0] for row in cr.fetchall()}
  689. return model._table in self._ordinary_tables
  690. @property
  691. def registry_invalidated(self):
  692. """ Determine whether the current thread has modified the registry. """
  693. return getattr(self._invalidation_flags, 'registry', False)
  694. @registry_invalidated.setter
  695. def registry_invalidated(self, value):
  696. self._invalidation_flags.registry = value
  697. @property
  698. def cache_invalidated(self):
  699. """ Determine whether the current thread has modified the cache. """
  700. try:
  701. return self._invalidation_flags.cache
  702. except AttributeError:
  703. names = self._invalidation_flags.cache = set()
  704. return names
  705. def setup_signaling(self):
  706. """ Setup the inter-process signaling on this registry. """
  707. if self.in_test_mode():
  708. return
  709. with self.cursor() as cr:
  710. # The `base_registry_signaling` sequence indicates when the registry
  711. # must be reloaded.
  712. # The `base_cache_signaling_...` sequences indicates when caches must
  713. # be invalidated (i.e. cleared).
  714. sequence_names = ('base_registry_signaling', *(f'base_cache_signaling_{cache_name}' for cache_name in _CACHES_BY_KEY))
  715. cr.execute("SELECT sequence_name FROM information_schema.sequences WHERE sequence_name IN %s", [sequence_names])
  716. existing_sequences = tuple(s[0] for s in cr.fetchall()) # could be a set but not efficient with such a little list
  717. for sequence_name in sequence_names:
  718. if sequence_name not in existing_sequences:
  719. cr.execute(SQL(
  720. "CREATE SEQUENCE %s INCREMENT BY 1 START WITH 1",
  721. SQL.identifier(sequence_name),
  722. ))
  723. cr.execute(SQL("SELECT nextval(%s)", sequence_name))
  724. db_registry_sequence, db_cache_sequences = self.get_sequences(cr)
  725. self.registry_sequence = db_registry_sequence
  726. self.cache_sequences.update(db_cache_sequences)
  727. _logger.debug("Multiprocess load registry signaling: [Registry: %s] %s",
  728. self.registry_sequence, ' '.join('[Cache %s: %s]' % cs for cs in self.cache_sequences.items()))
  729. def get_sequences(self, cr):
  730. assert cr.readonly is False, "can't use replica, sequence data is not replicated"
  731. cache_sequences_query = ', '.join([f'base_cache_signaling_{cache_name}' for cache_name in _CACHES_BY_KEY])
  732. cache_sequences_values_query = ',\n'.join([f'base_cache_signaling_{cache_name}.last_value' for cache_name in _CACHES_BY_KEY])
  733. cr.execute(f"""
  734. SELECT base_registry_signaling.last_value, {cache_sequences_values_query}
  735. FROM base_registry_signaling, {cache_sequences_query}
  736. """)
  737. registry_sequence, *cache_sequences_values = cr.fetchone()
  738. cache_sequences = dict(zip(_CACHES_BY_KEY, cache_sequences_values))
  739. return registry_sequence, cache_sequences
  740. def check_signaling(self, cr=None):
  741. """ Check whether the registry has changed, and performs all necessary
  742. operations to update the registry. Return an up-to-date registry.
  743. """
  744. if self.in_test_mode():
  745. return self
  746. with nullcontext(cr) if cr is not None else closing(self.cursor()) as cr:
  747. db_registry_sequence, db_cache_sequences = self.get_sequences(cr)
  748. changes = ''
  749. # Check if the model registry must be reloaded
  750. if self.registry_sequence != db_registry_sequence:
  751. _logger.info("Reloading the model registry after database signaling.")
  752. self = Registry.new(self.db_name)
  753. self.registry_sequence = db_registry_sequence
  754. if _logger.isEnabledFor(logging.DEBUG):
  755. changes += "[Registry - %s -> %s]" % (self.registry_sequence, db_registry_sequence)
  756. # Check if the model caches must be invalidated.
  757. else:
  758. invalidated = []
  759. for cache_name, cache_sequence in self.cache_sequences.items():
  760. expected_sequence = db_cache_sequences[cache_name]
  761. if cache_sequence != expected_sequence:
  762. for cache in _CACHES_BY_KEY[cache_name]: # don't call clear_cache to avoid signal loop
  763. if cache not in invalidated:
  764. invalidated.append(cache)
  765. self.__caches[cache].clear()
  766. self.cache_sequences[cache_name] = expected_sequence
  767. if _logger.isEnabledFor(logging.DEBUG):
  768. changes += "[Cache %s - %s -> %s]" % (cache_name, cache_sequence, expected_sequence)
  769. if invalidated:
  770. _logger.info("Invalidating caches after database signaling: %s", sorted(invalidated))
  771. if changes:
  772. _logger.debug("Multiprocess signaling check: %s", changes)
  773. return self
  774. def signal_changes(self):
  775. """ Notifies other processes if registry or cache has been invalidated. """
  776. if not self.ready:
  777. _logger.warning('Calling signal_changes when registry is not ready is not suported')
  778. return
  779. if self.registry_invalidated:
  780. _logger.info("Registry changed, signaling through the database")
  781. with closing(self.cursor()) as cr:
  782. cr.execute("select nextval('base_registry_signaling')")
  783. # If another process concurrently updates the registry,
  784. # self.registry_sequence will actually be out-of-date,
  785. # and the next call to check_signaling() will detect that and trigger a registry reload.
  786. # otherwise, self.registry_sequence should be equal to cr.fetchone()[0]
  787. self.registry_sequence += 1
  788. # no need to notify cache invalidation in case of registry invalidation,
  789. # because reloading the registry implies starting with an empty cache
  790. elif self.cache_invalidated:
  791. _logger.info("Caches invalidated, signaling through the database: %s", sorted(self.cache_invalidated))
  792. with closing(self.cursor()) as cr:
  793. for cache_name in self.cache_invalidated:
  794. cr.execute("select nextval(%s)", [f'base_cache_signaling_{cache_name}'])
  795. # If another process concurrently updates the cache,
  796. # self.cache_sequences[cache_name] will actually be out-of-date,
  797. # and the next call to check_signaling() will detect that and trigger cache invalidation.
  798. # otherwise, self.cache_sequences[cache_name] should be equal to cr.fetchone()[0]
  799. self.cache_sequences[cache_name] += 1
  800. self.registry_invalidated = False
  801. self.cache_invalidated.clear()
  802. def reset_changes(self):
  803. """ Reset the registry and cancel all invalidations. """
  804. if self.registry_invalidated:
  805. with closing(self.cursor()) as cr:
  806. self.setup_models(cr)
  807. self.registry_invalidated = False
  808. if self.cache_invalidated:
  809. for cache_name in self.cache_invalidated:
  810. for cache in _CACHES_BY_KEY[cache_name]:
  811. self.__caches[cache].clear()
  812. self.cache_invalidated.clear()
  813. @contextmanager
  814. def manage_changes(self):
  815. """ Context manager to signal/discard registry and cache invalidations. """
  816. try:
  817. yield self
  818. self.signal_changes()
  819. except Exception:
  820. self.reset_changes()
  821. raise
  822. def in_test_mode(self):
  823. """ Test whether the registry is in 'test' mode. """
  824. return self.test_cr is not None
  825. def enter_test_mode(self, cr, test_readonly_enabled=True):
  826. """ Enter the 'test' mode, where one cursor serves several requests. """
  827. assert self.test_cr is None
  828. self.test_cr = cr
  829. self.test_readonly_enabled = test_readonly_enabled
  830. self.test_lock = threading.RLock()
  831. assert Registry._saved_lock is None
  832. Registry._saved_lock = Registry._lock
  833. Registry._lock = DummyRLock()
  834. def leave_test_mode(self):
  835. """ Leave the test mode. """
  836. assert self.test_cr is not None
  837. self.test_cr = None
  838. del self.test_readonly_enabled
  839. del self.test_lock
  840. assert Registry._saved_lock is not None
  841. Registry._lock = Registry._saved_lock
  842. Registry._saved_lock = None
  843. def cursor(self, /, readonly=False):
  844. """ Return a new cursor for the database. The cursor itself may be used
  845. as a context manager to commit/rollback and close automatically.
  846. :param readonly: Attempt to acquire a cursor on a replica database.
  847. Acquire a read/write cursor on the primary database in case no
  848. replica exists or that no readonly cursor could be acquired.
  849. """
  850. if self.test_cr is not None:
  851. # in test mode we use a proxy object that uses 'self.test_cr' underneath
  852. if readonly and not self.test_readonly_enabled:
  853. _logger.info('Explicitly ignoring readonly flag when generating a cursor')
  854. return TestCursor(self.test_cr, self.test_lock, readonly and self.test_readonly_enabled)
  855. if readonly and self._db_readonly is not None:
  856. try:
  857. return self._db_readonly.cursor()
  858. except psycopg2.OperationalError:
  859. # Setting _db_readonly to None will deactivate the readonly mode until
  860. # worker restart / recycling.
  861. self._db_readonly = None
  862. _logger.warning('Failed to open a readonly cursor, falling back to read-write cursor')
  863. return self._db.cursor()
  864. class DummyRLock(object):
  865. """ Dummy reentrant lock, to be used while running rpc and js tests """
  866. def acquire(self):
  867. pass
  868. def release(self):
  869. pass
  870. def __enter__(self):
  871. self.acquire()
  872. def __exit__(self, type, value, traceback):
  873. self.release()
  874. class TriggerTree(dict):
  875. """ The triggers of a field F is a tree that contains the fields that
  876. depend on F, together with the fields to inverse to find out which records
  877. to recompute.
  878. For instance, assume that G depends on F, H depends on X.F, I depends on
  879. W.X.F, and J depends on Y.F. The triggers of F will be the tree:
  880. [G]
  881. X/ \\Y
  882. [H] [J]
  883. W/
  884. [I]
  885. This tree provides perfect support for the trigger mechanism:
  886. when F is # modified on records,
  887. - mark G to recompute on records,
  888. - mark H to recompute on inverse(X, records),
  889. - mark I to recompute on inverse(W, inverse(X, records)),
  890. - mark J to recompute on inverse(Y, records).
  891. """
  892. __slots__ = ['root']
  893. # pylint: disable=keyword-arg-before-vararg
  894. def __init__(self, root=(), *args, **kwargs):
  895. super().__init__(*args, **kwargs)
  896. self.root = root
  897. def __bool__(self):
  898. return bool(self.root or len(self))
  899. def __repr__(self) -> str:
  900. return f"TriggerTree(root={self.root!r}, {super().__repr__()})"
  901. def increase(self, key):
  902. try:
  903. return self[key]
  904. except KeyError:
  905. subtree = self[key] = TriggerTree()
  906. return subtree
  907. def depth_first(self):
  908. yield self
  909. for subtree in self.values():
  910. yield from subtree.depth_first()
  911. @classmethod
  912. def merge(cls, trees: list, select=bool) -> "TriggerTree":
  913. """ Merge trigger trees into a single tree. The function ``select`` is
  914. called on every field to determine which fields should be kept in the
  915. tree nodes. This enables to discard some fields from the tree nodes.
  916. """
  917. root_fields = OrderedSet() # fields in the root node
  918. subtrees_to_merge = defaultdict(list) # subtrees to merge grouped by key
  919. for tree in trees:
  920. root_fields.update(tree.root)
  921. for label, subtree in tree.items():
  922. subtrees_to_merge[label].append(subtree)
  923. # the root node contains the collected fields for which select is true
  924. result = cls([field for field in root_fields if select(field)])
  925. for label, subtrees in subtrees_to_merge.items():
  926. subtree = cls.merge(subtrees, select)
  927. if subtree:
  928. result[label] = subtree
  929. return result
上海开阖软件有限公司 沪ICP备12045867号-1