registry.py 37 KB

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