/models.py

https://bitbucket.org/testbenchtech/odoo · Python · 5244 lines · 4687 code · 164 blank · 393 comment · 287 complexity · b074a17e02c9ec26df76b769ff4f964a MD5 · raw file

  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. """
  4. Object Relational Mapping module:
  5. * Hierarchical structure
  6. * Constraints consistency and validation
  7. * Object metadata depends on its status
  8. * Optimised processing by complex query (multiple actions at once)
  9. * Default field values
  10. * Permissions optimisation
  11. * Persistant object: DB postgresql
  12. * Data conversion
  13. * Multi-level caching system
  14. * Two different inheritance mechanisms
  15. * Rich set of field types:
  16. - classical (varchar, integer, boolean, ...)
  17. - relational (one2many, many2one, many2many)
  18. - functional
  19. """
  20. import datetime
  21. import collections
  22. import dateutil
  23. import functools
  24. import itertools
  25. import logging
  26. import operator
  27. import pytz
  28. import re
  29. from collections import defaultdict, MutableMapping, OrderedDict
  30. from contextlib import closing
  31. from inspect import getmembers, currentframe
  32. from operator import attrgetter, itemgetter
  33. import babel.dates
  34. import dateutil.relativedelta
  35. import psycopg2
  36. from lxml import etree
  37. from lxml.builder import E
  38. import odoo
  39. from . import SUPERUSER_ID
  40. from . import api
  41. from . import tools
  42. from .exceptions import AccessError, MissingError, ValidationError, UserError
  43. from .osv.query import Query
  44. from .tools import frozendict, lazy_classproperty, lazy_property, ormcache, \
  45. Collector, LastOrderedSet, OrderedSet, pycompat
  46. from .tools.config import config
  47. from .tools.func import frame_codeinfo
  48. from .tools.misc import CountingStream, DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT
  49. from .tools.safe_eval import safe_eval
  50. from .tools.translate import _
  51. _logger = logging.getLogger(__name__)
  52. _schema = logging.getLogger(__name__ + '.schema')
  53. _unlink = logging.getLogger(__name__ + '.unlink')
  54. regex_order = re.compile('^(\s*([a-z0-9:_]+|"[a-z0-9:_]+")(\s+(desc|asc))?\s*(,|$))+(?<!,)$', re.I)
  55. regex_object_name = re.compile(r'^[a-z0-9_.]+$')
  56. regex_pg_name = re.compile(r'^[a-z_][a-z0-9_$]*$', re.I)
  57. onchange_v7 = re.compile(r"^(\w+)\((.*)\)$")
  58. AUTOINIT_RECALCULATE_STORED_FIELDS = 1000
  59. def check_object_name(name):
  60. """ Check if the given name is a valid model name.
  61. The _name attribute in osv and osv_memory object is subject to
  62. some restrictions. This function returns True or False whether
  63. the given name is allowed or not.
  64. TODO: this is an approximation. The goal in this approximation
  65. is to disallow uppercase characters (in some places, we quote
  66. table/column names and in other not, which leads to this kind
  67. of errors:
  68. psycopg2.ProgrammingError: relation "xxx" does not exist).
  69. The same restriction should apply to both osv and osv_memory
  70. objects for consistency.
  71. """
  72. if regex_object_name.match(name) is None:
  73. return False
  74. return True
  75. def raise_on_invalid_object_name(name):
  76. if not check_object_name(name):
  77. msg = "The _name attribute %s is not valid." % name
  78. raise ValueError(msg)
  79. def check_pg_name(name):
  80. """ Check whether the given name is a valid PostgreSQL identifier name. """
  81. if not regex_pg_name.match(name):
  82. raise ValidationError("Invalid characters in table name %r" % name)
  83. if len(name) > 63:
  84. raise ValidationError("Table name %r is too long" % name)
  85. # match private methods, to prevent their remote invocation
  86. regex_private = re.compile(r'^(_.*|init)$')
  87. def check_method_name(name):
  88. """ Raise an ``AccessError`` if ``name`` is a private method name. """
  89. if regex_private.match(name):
  90. raise AccessError(_('Private methods (such as %s) cannot be called remotely.') % (name,))
  91. def same_name(f, g):
  92. """ Test whether functions ``f`` and ``g`` are identical or have the same name """
  93. return f == g or getattr(f, '__name__', 0) == getattr(g, '__name__', 1)
  94. def fix_import_export_id_paths(fieldname):
  95. """
  96. Fixes the id fields in import and exports, and splits field paths
  97. on '/'.
  98. :param str fieldname: name of the field to import/export
  99. :return: split field name
  100. :rtype: list of str
  101. """
  102. fixed_db_id = re.sub(r'([^/])\.id', r'\1/.id', fieldname)
  103. fixed_external_id = re.sub(r'([^/]):id', r'\1/id', fixed_db_id)
  104. return fixed_external_id.split('/')
  105. class MetaModel(api.Meta):
  106. """ The metaclass of all model classes.
  107. Its main purpose is to register the models per module.
  108. """
  109. module_to_models = defaultdict(list)
  110. def __init__(self, name, bases, attrs):
  111. if not self._register:
  112. self._register = True
  113. super(MetaModel, self).__init__(name, bases, attrs)
  114. return
  115. if not hasattr(self, '_module'):
  116. self._module = self._get_addon_name(self.__module__)
  117. # Remember which models to instanciate for this module.
  118. if not self._custom:
  119. self.module_to_models[self._module].append(self)
  120. # check for new-api conversion error: leave comma after field definition
  121. for key, val in attrs.items():
  122. if type(val) is tuple and len(val) == 1 and isinstance(val[0], Field):
  123. _logger.error("Trailing comma after field definition: %s.%s", self, key)
  124. if isinstance(val, Field):
  125. val.args = dict(val.args, _module=self._module)
  126. def _get_addon_name(self, full_name):
  127. # The (OpenERP) module name can be in the ``odoo.addons`` namespace
  128. # or not. For instance, module ``sale`` can be imported as
  129. # ``odoo.addons.sale`` (the right way) or ``sale`` (for backward
  130. # compatibility).
  131. module_parts = full_name.split('.')
  132. if len(module_parts) > 2 and module_parts[:2] == ['odoo', 'addons']:
  133. addon_name = full_name.split('.')[2]
  134. else:
  135. addon_name = full_name.split('.')[0]
  136. return addon_name
  137. class NewId(object):
  138. """ Pseudo-ids for new records, encapsulating an optional reference. """
  139. __slots__ = ['ref']
  140. def __init__(self, ref=None):
  141. self.ref = ref
  142. def __bool__(self):
  143. return False
  144. __nonzero__ = __bool__
  145. IdType = pycompat.integer_types + pycompat.string_types + (NewId,)
  146. # maximum number of prefetched records
  147. PREFETCH_MAX = 1000
  148. # special columns automatically created by the ORM
  149. LOG_ACCESS_COLUMNS = ['create_uid', 'create_date', 'write_uid', 'write_date']
  150. MAGIC_COLUMNS = ['id'] + LOG_ACCESS_COLUMNS
  151. @pycompat.implements_to_string
  152. class BaseModel(MetaModel('DummyModel', (object,), {'_register': False})):
  153. """ Base class for Odoo models.
  154. Odoo models are created by inheriting:
  155. * :class:`Model` for regular database-persisted models
  156. * :class:`TransientModel` for temporary data, stored in the database but
  157. automatically vacuumed every so often
  158. * :class:`AbstractModel` for abstract super classes meant to be shared by
  159. multiple inheriting models
  160. The system automatically instantiates every model once per database. Those
  161. instances represent the available models on each database, and depend on
  162. which modules are installed on that database. The actual class of each
  163. instance is built from the Python classes that create and inherit from the
  164. corresponding model.
  165. Every model instance is a "recordset", i.e., an ordered collection of
  166. records of the model. Recordsets are returned by methods like
  167. :meth:`~.browse`, :meth:`~.search`, or field accesses. Records have no
  168. explicit representation: a record is represented as a recordset of one
  169. record.
  170. To create a class that should not be instantiated, the _register class
  171. attribute may be set to False.
  172. """
  173. _auto = False # don't create any database backend
  174. _register = False # not visible in ORM registry
  175. _abstract = True # whether model is abstract
  176. _transient = False # whether model is transient
  177. _name = None # the model name
  178. _description = None # the model's informal name
  179. _custom = False # should be True for custom models only
  180. _inherit = None # Python-inherited models ('model' or ['model'])
  181. _inherits = {} # inherited models {'parent_model': 'm2o_field'}
  182. _constraints = [] # Python constraints (old API)
  183. _table = None # SQL table name used by model
  184. _sequence = None # SQL sequence to use for ID field
  185. _sql_constraints = [] # SQL constraints [(name, sql_def, message)]
  186. _rec_name = None # field to use for labeling records
  187. _order = 'id' # default order for searching results
  188. _parent_name = 'parent_id' # the many2one field used as parent field
  189. _parent_store = False # set to True to compute MPTT (parent_left, parent_right)
  190. _parent_order = False # order to use for siblings in MPTT
  191. _date_name = 'date' # field to use for default calendar view
  192. _fold_name = 'fold' # field to determine folded groups in kanban views
  193. _needaction = False # whether the model supports "need actions" (see mail)
  194. _translate = True # False disables translations export for this model
  195. _depends = {} # dependencies of models backed up by sql views
  196. # {model_name: field_names, ...}
  197. # default values for _transient_vacuum()
  198. _transient_check_count = 0
  199. _transient_max_count = lazy_classproperty(lambda _: config.get('osv_memory_count_limit'))
  200. _transient_max_hours = lazy_classproperty(lambda _: config.get('osv_memory_age_limit'))
  201. CONCURRENCY_CHECK_FIELD = '__last_update'
  202. @api.model
  203. def view_init(self, fields_list):
  204. """ Override this method to do specific things when a form view is
  205. opened. This method is invoked by :meth:`~default_get`.
  206. """
  207. pass
  208. @api.model_cr_context
  209. def _reflect(self):
  210. """ Reflect the model and its fields in the models 'ir.model' and
  211. 'ir.model.fields'. Also create entries in 'ir.model.data' if the key
  212. 'module' is passed to the context.
  213. """
  214. self.env['ir.model']._reflect_model(self)
  215. self.env['ir.model.fields']._reflect_model(self)
  216. self.env['ir.model.constraint']._reflect_model(self)
  217. self.invalidate_cache()
  218. @api.model
  219. def _add_field(self, name, field):
  220. """ Add the given ``field`` under the given ``name`` in the class """
  221. cls = type(self)
  222. # add field as an attribute and in cls._fields (for reflection)
  223. if not isinstance(getattr(cls, name, field), Field):
  224. _logger.warning("In model %r, field %r overriding existing value", cls._name, name)
  225. setattr(cls, name, field)
  226. cls._fields[name] = field
  227. # basic setup of field
  228. field.setup_base(self, name)
  229. @api.model
  230. def _pop_field(self, name):
  231. """ Remove the field with the given ``name`` from the model.
  232. This method should only be used for manual fields.
  233. """
  234. cls = type(self)
  235. field = cls._fields.pop(name, None)
  236. if hasattr(cls, name):
  237. delattr(cls, name)
  238. return field
  239. @api.model
  240. def _add_magic_fields(self):
  241. """ Introduce magic fields on the current class
  242. * id is a "normal" field (with a specific getter)
  243. * create_uid, create_date, write_uid and write_date have become
  244. "normal" fields
  245. * $CONCURRENCY_CHECK_FIELD is a computed field with its computing
  246. method defined dynamically. Uses ``str(datetime.datetime.utcnow())``
  247. to get the same structure as the previous
  248. ``(now() at time zone 'UTC')::timestamp``::
  249. # select (now() at time zone 'UTC')::timestamp;
  250. timezone
  251. ----------------------------
  252. 2013-06-18 08:30:37.292809
  253. >>> str(datetime.datetime.utcnow())
  254. '2013-06-18 08:31:32.821177'
  255. """
  256. def add(name, field):
  257. """ add ``field`` with the given ``name`` if it does not exist yet """
  258. if name not in self._fields:
  259. self._add_field(name, field)
  260. # cyclic import
  261. from . import fields
  262. # this field 'id' must override any other column or field
  263. self._add_field('id', fields.Id(automatic=True))
  264. add('display_name', fields.Char(string='Display Name', automatic=True,
  265. compute='_compute_display_name'))
  266. if self._log_access:
  267. add('create_uid', fields.Many2one('res.users', string='Created by', automatic=True))
  268. add('create_date', fields.Datetime(string='Created on', automatic=True))
  269. add('write_uid', fields.Many2one('res.users', string='Last Updated by', automatic=True))
  270. add('write_date', fields.Datetime(string='Last Updated on', automatic=True))
  271. last_modified_name = 'compute_concurrency_field_with_access'
  272. else:
  273. last_modified_name = 'compute_concurrency_field'
  274. # this field must override any other column or field
  275. self._add_field(self.CONCURRENCY_CHECK_FIELD, fields.Datetime(
  276. string='Last Modified on', compute=last_modified_name, automatic=True))
  277. def compute_concurrency_field(self):
  278. for record in self:
  279. record[self.CONCURRENCY_CHECK_FIELD] = odoo.fields.Datetime.now()
  280. @api.depends('create_date', 'write_date')
  281. def compute_concurrency_field_with_access(self):
  282. for record in self:
  283. record[self.CONCURRENCY_CHECK_FIELD] = \
  284. record.write_date or record.create_date or odoo.fields.Datetime.now()
  285. #
  286. # Goal: try to apply inheritance at the instantiation level and
  287. # put objects in the pool var
  288. #
  289. @classmethod
  290. def _build_model(cls, pool, cr):
  291. """ Instantiate a given model in the registry.
  292. This method creates or extends a "registry" class for the given model.
  293. This "registry" class carries inferred model metadata, and inherits (in
  294. the Python sense) from all classes that define the model, and possibly
  295. other registry classes.
  296. """
  297. # In the simplest case, the model's registry class inherits from cls and
  298. # the other classes that define the model in a flat hierarchy. The
  299. # registry contains the instance ``model`` (on the left). Its class,
  300. # ``ModelClass``, carries inferred metadata that is shared between all
  301. # the model's instances for this registry only.
  302. #
  303. # class A1(Model): Model
  304. # _name = 'a' / | \
  305. # A3 A2 A1
  306. # class A2(Model): \ | /
  307. # _inherit = 'a' ModelClass
  308. # / \
  309. # class A3(Model): model recordset
  310. # _inherit = 'a'
  311. #
  312. # When a model is extended by '_inherit', its base classes are modified
  313. # to include the current class and the other inherited model classes.
  314. # Note that we actually inherit from other ``ModelClass``, so that
  315. # extensions to an inherited model are immediately visible in the
  316. # current model class, like in the following example:
  317. #
  318. # class A1(Model):
  319. # _name = 'a' Model
  320. # / / \ \
  321. # class B1(Model): / A2 A1 \
  322. # _name = 'b' / \ / \
  323. # B2 ModelA B1
  324. # class B2(Model): \ | /
  325. # _name = 'b' \ | /
  326. # _inherit = ['a', 'b'] \ | /
  327. # ModelB
  328. # class A2(Model):
  329. # _inherit = 'a'
  330. # Keep links to non-inherited constraints in cls; this is useful for
  331. # instance when exporting translations
  332. cls._local_constraints = cls.__dict__.get('_constraints', [])
  333. cls._local_sql_constraints = cls.__dict__.get('_sql_constraints', [])
  334. # determine inherited models
  335. parents = cls._inherit
  336. parents = [parents] if isinstance(parents, pycompat.string_types) else (parents or [])
  337. # determine the model's name
  338. name = cls._name or (len(parents) == 1 and parents[0]) or cls.__name__
  339. # all models except 'base' implicitly inherit from 'base'
  340. if name != 'base':
  341. parents = list(parents) + ['base']
  342. # create or retrieve the model's class
  343. if name in parents:
  344. if name not in pool:
  345. raise TypeError("Model %r does not exist in registry." % name)
  346. ModelClass = pool[name]
  347. ModelClass._build_model_check_base(cls)
  348. check_parent = ModelClass._build_model_check_parent
  349. else:
  350. ModelClass = type(name, (BaseModel,), {
  351. '_name': name,
  352. '_register': False,
  353. '_original_module': cls._module,
  354. '_inherit_children': OrderedSet(), # names of children models
  355. '_inherits_children': set(), # names of children models
  356. '_fields': OrderedDict(), # populated in _setup_base()
  357. })
  358. check_parent = cls._build_model_check_parent
  359. # determine all the classes the model should inherit from
  360. bases = LastOrderedSet([cls])
  361. for parent in parents:
  362. if parent not in pool:
  363. raise TypeError("Model %r inherits from non-existing model %r." % (name, parent))
  364. parent_class = pool[parent]
  365. if parent == name:
  366. for base in parent_class.__bases__:
  367. bases.add(base)
  368. else:
  369. check_parent(cls, parent_class)
  370. bases.add(parent_class)
  371. parent_class._inherit_children.add(name)
  372. ModelClass.__bases__ = tuple(bases)
  373. # determine the attributes of the model's class
  374. ModelClass._build_model_attributes(pool)
  375. check_pg_name(ModelClass._table)
  376. # Transience
  377. if ModelClass._transient:
  378. assert ModelClass._log_access, \
  379. "TransientModels must have log_access turned on, " \
  380. "in order to implement their access rights policy"
  381. # link the class to the registry, and update the registry
  382. ModelClass.pool = pool
  383. pool[name] = ModelClass
  384. # backward compatibility: instantiate the model, and initialize it
  385. model = object.__new__(ModelClass)
  386. model.__init__(pool, cr)
  387. return ModelClass
  388. @classmethod
  389. def _build_model_check_base(model_class, cls):
  390. """ Check whether ``model_class`` can be extended with ``cls``. """
  391. if model_class._abstract and not cls._abstract:
  392. msg = ("%s transforms the abstract model %r into a non-abstract model. "
  393. "That class should either inherit from AbstractModel, or set a different '_name'.")
  394. raise TypeError(msg % (cls, model_class._name))
  395. if model_class._transient != cls._transient:
  396. if model_class._transient:
  397. msg = ("%s transforms the transient model %r into a non-transient model. "
  398. "That class should either inherit from TransientModel, or set a different '_name'.")
  399. else:
  400. msg = ("%s transforms the model %r into a transient model. "
  401. "That class should either inherit from Model, or set a different '_name'.")
  402. raise TypeError(msg % (cls, model_class._name))
  403. @classmethod
  404. def _build_model_check_parent(model_class, cls, parent_class):
  405. """ Check whether ``model_class`` can inherit from ``parent_class``. """
  406. if model_class._abstract and not parent_class._abstract:
  407. msg = ("In %s, the abstract model %r cannot inherit from the non-abstract model %r.")
  408. raise TypeError(msg % (cls, model_class._name, parent_class._name))
  409. @classmethod
  410. def _build_model_attributes(cls, pool):
  411. """ Initialize base model attributes. """
  412. cls._description = cls._name
  413. cls._table = cls._name.replace('.', '_')
  414. cls._sequence = None
  415. cls._log_access = cls._auto
  416. cls._inherits = {}
  417. cls._depends = {}
  418. cls._constraints = {}
  419. cls._sql_constraints = []
  420. for base in reversed(cls.__bases__):
  421. if not getattr(base, 'pool', None):
  422. # the following attributes are not taken from model classes
  423. cls._description = base._description or cls._description
  424. cls._table = base._table or cls._table
  425. cls._sequence = base._sequence or cls._sequence
  426. cls._log_access = getattr(base, '_log_access', cls._log_access)
  427. cls._inherits.update(base._inherits)
  428. for mname, fnames in base._depends.items():
  429. cls._depends[mname] = cls._depends.get(mname, []) + fnames
  430. for cons in base._constraints:
  431. # cons may override a constraint with the same function name
  432. cls._constraints[getattr(cons[0], '__name__', id(cons[0]))] = cons
  433. cls._sql_constraints += base._sql_constraints
  434. cls._sequence = cls._sequence or (cls._table + '_id_seq')
  435. cls._constraints = list(cls._constraints.values())
  436. # update _inherits_children of parent models
  437. for parent_name in cls._inherits:
  438. pool[parent_name]._inherits_children.add(cls._name)
  439. # recompute attributes of _inherit_children models
  440. for child_name in cls._inherit_children:
  441. child_class = pool[child_name]
  442. child_class._build_model_attributes(pool)
  443. @classmethod
  444. def _init_constraints_onchanges(cls):
  445. # store sql constraint error messages
  446. for (key, _, msg) in cls._sql_constraints:
  447. cls.pool._sql_error[cls._table + '_' + key] = msg
  448. # reset properties memoized on cls
  449. cls._constraint_methods = BaseModel._constraint_methods
  450. cls._onchange_methods = BaseModel._onchange_methods
  451. @property
  452. def _constraint_methods(self):
  453. """ Return a list of methods implementing Python constraints. """
  454. def is_constraint(func):
  455. return callable(func) and hasattr(func, '_constrains')
  456. cls = type(self)
  457. methods = []
  458. for attr, func in getmembers(cls, is_constraint):
  459. for name in func._constrains:
  460. field = cls._fields.get(name)
  461. if not field:
  462. _logger.warning("method %s.%s: @constrains parameter %r is not a field name", cls._name, attr, name)
  463. elif not (field.store or field.inverse or field.inherited):
  464. _logger.warning("method %s.%s: @constrains parameter %r is not writeable", cls._name, attr, name)
  465. methods.append(func)
  466. # optimization: memoize result on cls, it will not be recomputed
  467. cls._constraint_methods = methods
  468. return methods
  469. @property
  470. def _onchange_methods(self):
  471. """ Return a dictionary mapping field names to onchange methods. """
  472. def is_onchange(func):
  473. return callable(func) and hasattr(func, '_onchange')
  474. # collect onchange methods on the model's class
  475. cls = type(self)
  476. methods = defaultdict(list)
  477. for attr, func in getmembers(cls, is_onchange):
  478. for name in func._onchange:
  479. if name not in cls._fields:
  480. _logger.warning("@onchange%r parameters must be field names", func._onchange)
  481. methods[name].append(func)
  482. # add onchange methods to implement "change_default" on fields
  483. def onchange_default(field, self):
  484. value = field.convert_to_write(self[field.name], self)
  485. condition = "%s=%s" % (field.name, value)
  486. defaults = self.env['ir.default'].get_model_defaults(self._name, condition)
  487. self.update(defaults)
  488. for name, field in cls._fields.items():
  489. if field.change_default:
  490. methods[name].append(functools.partial(onchange_default, field))
  491. # optimization: memoize result on cls, it will not be recomputed
  492. cls._onchange_methods = methods
  493. return methods
  494. def __new__(cls):
  495. # In the past, this method was registering the model class in the server.
  496. # This job is now done entirely by the metaclass MetaModel.
  497. return None
  498. def __init__(self, pool, cr):
  499. """ Deprecated method to initialize the model. """
  500. pass
  501. @api.model
  502. @ormcache()
  503. def _is_an_ordinary_table(self):
  504. return tools.table_kind(self.env.cr, self._table) == 'r'
  505. def __export_xml_id(self):
  506. """ Return a valid xml_id for the record ``self``. """
  507. if not self._is_an_ordinary_table():
  508. raise Exception(
  509. "You can not export the column ID of model %s, because the "
  510. "table %s is not an ordinary table."
  511. % (self._name, self._table))
  512. ir_model_data = self.sudo().env['ir.model.data']
  513. data = ir_model_data.search([('model', '=', self._name), ('res_id', '=', self.id)])
  514. if data:
  515. if data[0].module:
  516. return '%s.%s' % (data[0].module, data[0].name)
  517. else:
  518. return data[0].name
  519. else:
  520. postfix = 0
  521. name = '%s_%s' % (self._table, self.id)
  522. while ir_model_data.search([('module', '=', '__export__'), ('name', '=', name)]):
  523. postfix += 1
  524. name = '%s_%s_%s' % (self._table, self.id, postfix)
  525. ir_model_data.create({
  526. 'model': self._name,
  527. 'res_id': self.id,
  528. 'module': '__export__',
  529. 'name': name,
  530. })
  531. return '__export__.' + name
  532. @api.multi
  533. def _export_rows(self, fields):
  534. """ Export fields of the records in ``self``.
  535. :param fields: list of lists of fields to traverse
  536. :return: list of lists of corresponding values
  537. """
  538. import_compatible = self.env.context.get('import_compat', True)
  539. lines = []
  540. def splittor(rs):
  541. """ Splits the self recordset in batches of 1000 (to avoid
  542. entire-recordset-prefetch-effects) & removes the previous batch
  543. from the cache after it's been iterated in full
  544. """
  545. for idx in range(0, len(rs), 1000):
  546. sub = rs[idx: idx+1000]
  547. for rec in sub:
  548. yield rec
  549. rs.invalidate_cache(ids=sub.ids)
  550. # memory stable but ends up prefetching 275 fields (???)
  551. for idx, record in enumerate(splittor(self)):
  552. # main line of record, initially empty
  553. current = [''] * len(fields)
  554. lines.append(current)
  555. # list of primary fields followed by secondary field(s)
  556. primary_done = []
  557. # process column by column
  558. for i, path in enumerate(fields):
  559. if not path:
  560. continue
  561. name = path[0]
  562. if name in primary_done:
  563. continue
  564. if name == '.id':
  565. current[i] = str(record.id)
  566. elif name == 'id':
  567. current[i] = record.__export_xml_id()
  568. else:
  569. field = record._fields[name]
  570. value = record[name]
  571. # this part could be simpler, but it has to be done this way
  572. # in order to reproduce the former behavior
  573. if not isinstance(value, BaseModel):
  574. current[i] = field.convert_to_export(value, record)
  575. else:
  576. primary_done.append(name)
  577. # in import_compat mode, m2m should always be exported as
  578. # a comma-separated list of xids in a single cell
  579. if import_compatible and field.type == 'many2many' and len(path) > 1 and path[1] == 'id':
  580. xml_ids = [r.__export_xml_id() for r in value]
  581. current[i] = ','.join(xml_ids) or False
  582. continue
  583. # recursively export the fields that follow name; use
  584. # 'display_name' where no subfield is exported
  585. fields2 = [(p[1:] or ['display_name'] if p and p[0] == name else [])
  586. for p in fields]
  587. lines2 = value._export_rows(fields2)
  588. if lines2:
  589. # merge first line with record's main line
  590. for j, val in enumerate(lines2[0]):
  591. if val or isinstance(val, bool):
  592. current[j] = val
  593. # append the other lines at the end
  594. lines += lines2[1:]
  595. else:
  596. current[i] = False
  597. return lines
  598. # backward compatibility
  599. __export_rows = _export_rows
  600. @api.multi
  601. def export_data(self, fields_to_export, raw_data=False):
  602. """ Export fields for selected objects
  603. :param fields_to_export: list of fields
  604. :param raw_data: True to return value in native Python type
  605. :rtype: dictionary with a *datas* matrix
  606. This method is used when exporting data via client menu
  607. """
  608. fields_to_export = [fix_import_export_id_paths(f) for f in fields_to_export]
  609. if raw_data:
  610. self = self.with_context(export_raw_data=True)
  611. return {'datas': self._export_rows(fields_to_export)}
  612. @api.model
  613. def load(self, fields, data):
  614. """
  615. Attempts to load the data matrix, and returns a list of ids (or
  616. ``False`` if there was an error and no id could be generated) and a
  617. list of messages.
  618. The ids are those of the records created and saved (in database), in
  619. the same order they were extracted from the file. They can be passed
  620. directly to :meth:`~read`
  621. :param fields: list of fields to import, at the same index as the corresponding data
  622. :type fields: list(str)
  623. :param data: row-major matrix of data to import
  624. :type data: list(list(str))
  625. :returns: {ids: list(int)|False, messages: [Message]}
  626. """
  627. # determine values of mode, current_module and noupdate
  628. mode = self._context.get('mode', 'init')
  629. current_module = self._context.get('module', '')
  630. noupdate = self._context.get('noupdate', False)
  631. # add current module in context for the conversion of xml ids
  632. self = self.with_context(_import_current_module=current_module)
  633. cr = self._cr
  634. cr.execute('SAVEPOINT model_load')
  635. fields = [fix_import_export_id_paths(f) for f in fields]
  636. fg = self.fields_get()
  637. ids = []
  638. messages = []
  639. ModelData = self.env['ir.model.data']
  640. ModelData.clear_caches()
  641. extracted = self._extract_records(fields, data, log=messages.append)
  642. converted = self._convert_records(extracted, log=messages.append)
  643. for id, xid, record, info in converted:
  644. try:
  645. cr.execute('SAVEPOINT model_load_save')
  646. except psycopg2.InternalError as e:
  647. # broken transaction, exit and hope the source error was
  648. # already logged
  649. if not any(message['type'] == 'error' for message in messages):
  650. messages.append(dict(info, type='error',message=u"Unknown database error: '%s'" % e))
  651. break
  652. try:
  653. ids.append(ModelData._update(self._name, current_module, record, mode=mode,
  654. xml_id=xid, noupdate=noupdate, res_id=id))
  655. cr.execute('RELEASE SAVEPOINT model_load_save')
  656. except psycopg2.Warning as e:
  657. messages.append(dict(info, type='warning', message=str(e)))
  658. cr.execute('ROLLBACK TO SAVEPOINT model_load_save')
  659. except psycopg2.Error as e:
  660. messages.append(dict(info, type='error', **PGERROR_TO_OE[e.pgcode](self, fg, info, e)))
  661. # Failed to write, log to messages, rollback savepoint (to
  662. # avoid broken transaction) and keep going
  663. cr.execute('ROLLBACK TO SAVEPOINT model_load_save')
  664. except Exception as e:
  665. message = (_(u'Unknown error during import:') + u' %s: %s' % (type(e), e))
  666. moreinfo = _('Resolve other errors first')
  667. messages.append(dict(info, type='error', message=message, moreinfo=moreinfo))
  668. # Failed for some reason, perhaps due to invalid data supplied,
  669. # rollback savepoint and keep going
  670. cr.execute('ROLLBACK TO SAVEPOINT model_load_save')
  671. if any(message['type'] == 'error' for message in messages):
  672. cr.execute('ROLLBACK TO SAVEPOINT model_load')
  673. ids = False
  674. if ids and self._context.get('defer_parent_store_computation'):
  675. self._parent_store_compute()
  676. return {'ids': ids, 'messages': messages}
  677. def _add_fake_fields(self, fields):
  678. from odoo.fields import Char, Integer
  679. fields[None] = Char('rec_name')
  680. fields['id'] = Char('External ID')
  681. fields['.id'] = Integer('Database ID')
  682. return fields
  683. @api.model
  684. def _extract_records(self, fields_, data, log=lambda a: None):
  685. """ Generates record dicts from the data sequence.
  686. The result is a generator of dicts mapping field names to raw
  687. (unconverted, unvalidated) values.
  688. For relational fields, if sub-fields were provided the value will be
  689. a list of sub-records
  690. The following sub-fields may be set on the record (by key):
  691. * None is the name_get for the record (to use with name_create/name_search)
  692. * "id" is the External ID for the record
  693. * ".id" is the Database ID for the record
  694. """
  695. fields = dict(self._fields)
  696. # Fake fields to avoid special cases in extractor
  697. fields = self._add_fake_fields(fields)
  698. # m2o fields can't be on multiple lines so exclude them from the
  699. # is_relational field rows filter, but special-case it later on to
  700. # be handled with relational fields (as it can have subfields)
  701. is_relational = lambda field: fields[field].relational
  702. get_o2m_values = itemgetter_tuple([
  703. index
  704. for index, fnames in enumerate(fields_)
  705. if fields[fnames[0]].type == 'one2many'
  706. ])
  707. get_nono2m_values = itemgetter_tuple([
  708. index
  709. for index, fnames in enumerate(fields_)
  710. if fields[fnames[0]].type != 'one2many'
  711. ])
  712. # Checks if the provided row has any non-empty one2many fields
  713. def only_o2m_values(row):
  714. return any(get_o2m_values(row)) and not any(get_nono2m_values(row))
  715. index = 0
  716. while index < len(data):
  717. row = data[index]
  718. # copy non-relational fields to record dict
  719. record = {fnames[0]: value
  720. for fnames, value in pycompat.izip(fields_, row)
  721. if not is_relational(fnames[0])}
  722. # Get all following rows which have relational values attached to
  723. # the current record (no non-relational values)
  724. record_span = itertools.takewhile(
  725. only_o2m_values, itertools.islice(data, index + 1, None))
  726. # stitch record row back on for relational fields
  727. record_span = list(itertools.chain([row], record_span))
  728. for relfield in set(fnames[0] for fnames in fields_ if is_relational(fnames[0])):
  729. comodel = self.env[fields[relfield].comodel_name]
  730. # get only cells for this sub-field, should be strictly
  731. # non-empty, field path [None] is for name_get field
  732. indices, subfields = pycompat.izip(*((index, fnames[1:] or [None])
  733. for index, fnames in enumerate(fields_)
  734. if fnames[0] == relfield))
  735. # return all rows which have at least one value for the
  736. # subfields of relfield
  737. relfield_data = [it for it in pycompat.imap(itemgetter_tuple(indices), record_span) if any(it)]
  738. record[relfield] = [
  739. subrecord
  740. for subrecord, _subinfo in comodel._extract_records(subfields, relfield_data, log=log)
  741. ]
  742. yield record, {'rows': {
  743. 'from': index,
  744. 'to': index + len(record_span) - 1,
  745. }}
  746. index += len(record_span)
  747. @api.model
  748. def _convert_records(self, records, log=lambda a: None):
  749. """ Converts records from the source iterable (recursive dicts of
  750. strings) into forms which can be written to the database (via
  751. self.create or (ir.model.data)._update)
  752. :returns: a list of triplets of (id, xid, record)
  753. :rtype: list((int|None, str|None, dict))
  754. """
  755. field_names = {name: field.string for name, field in self._fields.items()}
  756. if self.env.lang:
  757. field_names.update(self.env['ir.translation'].get_field_string(self._name))
  758. convert = self.env['ir.fields.converter'].for_model(self)
  759. def _log(base, record, field, exception):
  760. type = 'warning' if isinstance(exception, Warning) else 'error'
  761. # logs the logical (not human-readable) field name for automated
  762. # processing of response, but injects human readable in message
  763. exc_vals = dict(base, record=record, field=field_names[field])
  764. record = dict(base, type=type, record=record, field=field,
  765. message=pycompat.text_type(exception.args[0]) % exc_vals)
  766. if len(exception.args) > 1 and exception.args[1]:
  767. record.update(exception.args[1])
  768. log(record)
  769. stream = CountingStream(records)
  770. for record, extras in stream:
  771. # xid
  772. xid = record.get('id', False)
  773. # dbid
  774. dbid = False
  775. if '.id' in record:
  776. try:
  777. dbid = int(record['.id'])
  778. except ValueError:
  779. # in case of overridden id column
  780. dbid = record['.id']
  781. if not self.search([('id', '=', dbid)]):
  782. log(dict(extras,
  783. type='error',
  784. record=stream.index,
  785. field='.id',
  786. message=_(u"Unknown database identifier '%s'") % dbid))
  787. dbid = False
  788. converted = convert(record, functools.partial(_log, extras, stream.index))
  789. yield dbid, xid, converted, dict(extras, record=stream.index)
  790. @api.multi
  791. def _validate_fields(self, field_names):
  792. field_names = set(field_names)
  793. # old-style constraint methods
  794. trans = self.env['ir.translation']
  795. errors = []
  796. for func, msg, names in self._constraints:
  797. try:
  798. # validation must be context-independent; call ``func`` without context
  799. valid = names and not (set(names) & field_names)
  800. valid = valid or func(self)
  801. extra_error = None
  802. except Exception as e:
  803. _logger.debug('Exception while validating constraint', exc_info=True)
  804. valid = False
  805. extra_error = tools.ustr(e)
  806. if not valid:
  807. if callable(msg):
  808. res_msg = msg(self)
  809. if isinstance(res_msg, tuple):
  810. template, params = res_msg
  811. res_msg = template % params
  812. else:
  813. res_msg = trans._get_source(self._name, 'constraint', self.env.lang, msg)
  814. if extra_error:
  815. res_msg += "\n\n%s\n%s" % (_('Error details:'), extra_error)
  816. errors.append(res_msg)
  817. if errors:
  818. raise ValidationError('\n'.join(errors))
  819. # new-style constraint methods
  820. for check in self._constraint_methods:
  821. if set(check._constrains) & field_names:
  822. try:
  823. check(self)
  824. except ValidationError as e:
  825. raise
  826. except Exception as e:
  827. raise ValidationError("%s\n\n%s" % (_("Error while validating constraint"), tools.ustr(e)))
  828. @api.model
  829. def default_get(self, fields_list):
  830. """ default_get(fields) -> default_values
  831. Return default values for the fields in ``fields_list``. Default
  832. values are determined by the context, user defaults, and the model
  833. itself.
  834. :param fields_list: a list of field names
  835. :return: a dictionary mapping each field name to its corresponding
  836. default value, if it has one.
  837. """
  838. # trigger view init hook
  839. self.view_init(fields_list)
  840. defaults = {}
  841. parent_fields = defaultdict(list)
  842. ir_defaults = self.env['ir.default'].get_model_defaults(self._name)
  843. for name in fields_list:
  844. # 1. look up context
  845. key = 'default_' + name
  846. if key in self._context:
  847. defaults[name] = self._context[key]
  848. continue
  849. # 2. look up ir.default
  850. if name in ir_defaults:
  851. defaults[name] = ir_defaults[name]
  852. continue
  853. field = self._fields.get(name)
  854. # 3. look up field.default
  855. if field and field.default:
  856. defaults[name] = field.default(self)
  857. continue
  858. # 4. delegate to parent model
  859. if field and field.inherited:
  860. field = field.related_field
  861. parent_fields[field.model_name].append(field.name)
  862. # convert default values to the right format
  863. defaults = self._convert_to_write(defaults)
  864. # add default values for inherited fields
  865. for model, names in parent_fields.items():
  866. defaults.update(self.env[model].default_get(names))
  867. return defaults
  868. @api.model
  869. def fields_get_keys(self):
  870. return list(self._fields)
  871. @api.model
  872. def _rec_name_fallback(self):
  873. # if self._rec_name is set, it belongs to self._fields
  874. return self._rec_name or 'id'
  875. #
  876. # Override this method if you need a window title that depends on the context
  877. #
  878. @api.model
  879. def view_header_get(self, view_id=None, view_type='form'):
  880. return False
  881. @api.model
  882. def user_has_groups(self, groups):
  883. """Return true if the user is member of at least one of the groups in
  884. ``groups``, and is not a member of any of the groups in ``groups``
  885. preceded by ``!``. Typically used to resolve ``groups`` attribute in
  886. view and model definitions.
  887. :param str groups: comma-separated list of fully-qualified group
  888. external IDs, e.g., ``base.group_user,base.group_system``,
  889. optionally preceded by ``!``
  890. :return: True if the current user is a member of one of the given groups
  891. not preceded by ``!`` and is not member of any of the groups
  892. preceded by ``!``
  893. """
  894. from odoo.http import request
  895. user = self.env.user
  896. has_groups = []
  897. not_has_groups = []
  898. for group_ext_id in groups.split(','):
  899. group_ext_id = group_ext_id.strip()
  900. if group_ext_id[0] == '!':
  901. not_has_groups.append(group_ext_id[1:])
  902. else:
  903. has_groups.append(group_ext_id)
  904. for group_ext_id in not_has_groups:
  905. if group_ext_id == 'base.group_no_one':
  906. # check: the group_no_one is effective in debug mode only
  907. if user.has_group(group_ext_id) and request and request.debug:
  908. return False
  909. else:
  910. if user.has_group(group_ext_id):
  911. return False
  912. for group_ext_id in has_groups:
  913. if group_ext_id == 'base.group_no_one':
  914. # check: the group_no_one is effective in debug mode only
  915. if user.has_group(group_ext_id) and request and request.debug:
  916. return True
  917. else:
  918. if user.has_group(group_ext_id):
  919. return True
  920. return not has_groups
  921. @api.model
  922. def _get_default_form_view(self):
  923. """ Generates a default single-line form view using all fields
  924. of the current model.
  925. :returns: a form view as an lxml document
  926. :rtype: etree._Element
  927. """
  928. group = E.group(col="4")
  929. for fname, field in self._fields.items():
  930. if field.automatic:
  931. continue
  932. elif field.type in ('one2many', 'many2many', 'text', 'html'):
  933. group.append(E.newline())
  934. group.append(E.field(name=fname, colspan="4"))
  935. group.append(E.newline())
  936. else:
  937. group.append(E.field(name=fname))
  938. group.append(E.separator())
  939. return E.form(E.sheet(group, string=self._description))
  940. @api.model
  941. def _get_default_search_view(self):
  942. """ Generates a single-field search view, based on _rec_name.
  943. :returns: a tree view as an lxml document
  944. :rtype: etree._Element
  945. """
  946. element = E.field(name=self._rec_name_fallback())
  947. return E.search(element, string=self._description)
  948. @api.model
  949. def _get_default_tree_view(self):
  950. """ Generates a single-field tree view, based on _rec_name.
  951. :returns: a tree view as an lxml document
  952. :rtype: etree._Element
  953. """
  954. element = E.field(name=self._rec_name_fallback())
  955. return E.tree(element, string=self._description)
  956. @api.model
  957. def _get_default_pivot_view(self):
  958. """ Generates an empty pivot view.
  959. :returns: a pivot view as an lxml document
  960. :rtype: etree._Element
  961. """
  962. return E.pivot(string=self._description)
  963. @api.model
  964. def _get_default_kanban_view(self):
  965. """ Generates a single-field kanban view, based on _rec_name.
  966. :returns: a kanban view as an lxml document
  967. :rtype: etree._Element
  968. """
  969. field = E.field(name=self._rec_name_fallback())
  970. content_div = E.div(field, {'class': "o_kanban_card_content"})
  971. card_div = E.div(content_div, {'t-attf-class': "oe_kanban_card oe_kanban_global_click"})
  972. kanban_box = E.t(card_div, {'t-name': "kanban-box"})
  973. templates = E.templates(kanban_box)
  974. return E.kanban(templates, string=self._description)
  975. @api.model
  976. def _get_default_graph_view(self):
  977. """ Generates a single-field graph view, based on _rec_name.
  978. :returns: a graph view as an lxml document
  979. :rtype: etree._Element
  980. """
  981. element = E.field(name=self._rec_name_fallback())
  982. return E.graph(element, string=self._description)
  983. @api.model
  984. def _get_default_calendar_view(self):
  985. """ Generates a default calendar view by trying to infer
  986. calendar fields from a number of pre-set attribute names
  987. :returns: a calendar view
  988. :rtype: etree._Element
  989. """
  990. def set_first_of(seq, in_, to):
  991. """Sets the first value of ``seq`` also found in ``in_`` to
  992. the ``to`` attribute of the ``view`` being closed over.
  993. Returns whether it's found a suitable value (and set it on
  994. the attribute) or not
  995. """
  996. for item in seq:
  997. if item in in_:
  998. view.set(to, item)
  999. return True
  1000. return False
  1001. view = E.calendar(string=self._description)
  1002. view.append(E.field(name=self._rec_name_fallback()))
  1003. if self._date_name not in self._fields:
  1004. date_found = False
  1005. for dt in ['date', 'date_start', 'x_date', 'x_date_start']:
  1006. if dt in self._fields:
  1007. self._date_name = dt
  1008. break
  1009. else:
  1010. raise UserError(_("Insufficient fields for Calendar View!"))
  1011. view.set('date_start', self._date_name)
  1012. set_first_of(["user_id", "partner_id", "x_user_id", "x_partner_id"],
  1013. self._fields, 'color')
  1014. if not set_first_of(["date_stop", "date_end", "x_date_stop", "x_date_end"],
  1015. self._fields, 'date_stop'):
  1016. if not set_first_of(["date_delay", "planned_hours", "x_date_delay", "x_planned_hours"],
  1017. self._fields, 'date_delay'):
  1018. raise UserError(_("Insufficient fields to generate a Calendar View for %s, missing a date_stop or a date_delay") % self._name)
  1019. return view
  1020. @api.model
  1021. def load_views(self, views, options=None):
  1022. """ Returns the fields_views of given views, along with the fields of
  1023. the current model, and optionally its filters for the given action.
  1024. :param views: list of [view_id, view_type]
  1025. :param options['toolbar']: True to include contextual actions when loading fields_views
  1026. :param options['load_filters']: True to return the model's filters
  1027. :param options['action_id']: id of the action to get the filters
  1028. :return: dictionary with fields_views, fields and optionally filters
  1029. """
  1030. options = options or {}
  1031. result = {}
  1032. toolbar = options.get('toolbar')
  1033. result['fields_views'] = {
  1034. v_type: self.fields_view_get(v_id, v_type if v_type != 'list' else 'tree',
  1035. toolbar=toolbar if v_type != 'search' else False)
  1036. for [v_id, v_type] in views
  1037. }
  1038. result['fields'] = self.fields_get()
  1039. if options.get('load_filters'):
  1040. result['filters'] = self.env['ir.filters'].get_filters(self._name, options.get('action_id'))
  1041. return result
  1042. @api.model
  1043. def _fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
  1044. View = self.env['ir.ui.view']
  1045. result = {
  1046. 'model': self._name,
  1047. 'field_parent': False,
  1048. }
  1049. # try to find a view_id if none provided
  1050. if not view_id:
  1051. # <view_type>_view_ref in context can be used to overrride the default view
  1052. view_ref_key = view_type + '_view_ref'
  1053. view_ref = self._context.get(view_ref_key)
  1054. if view_ref:
  1055. if '.' in view_ref:
  1056. module, view_ref = view_ref.split('.', 1)
  1057. query = "SELECT res_id FROM ir_model_data WHERE model='ir.ui.view' AND module=%s AND name=%s"
  1058. self._cr.execute(query, (module, view_ref))
  1059. view_ref_res = self._cr.fetchone()
  1060. if view_ref_res:
  1061. view_id = view_ref_res[0]
  1062. else:
  1063. _logger.warning('%r requires a fully-qualified external id (got: %r for model %s). '
  1064. 'Please use the complete `module.view_id` form instead.', view_ref_key, view_ref,
  1065. self._name)
  1066. if not view_id:
  1067. # otherwise try to find the lowest priority matching ir.ui.view
  1068. view_id = View.default_view(self._name, view_type)
  1069. if view_id:
  1070. # read the view with inherited views applied
  1071. root_view = View.browse(view_id).read_combined(['id', 'name', 'field_parent', 'type', 'model', 'arch'])
  1072. result['arch'] = root_view['arch']
  1073. result['name'] = root_view['name']
  1074. result['type'] = root_view['type']
  1075. result['view_id'] = root_view['id']
  1076. result['field_parent'] = root_view['field_parent']
  1077. result['base_model'] = root_view['model']
  1078. else:
  1079. # fallback on default views methods if no ir.ui.view could be found
  1080. try:
  1081. arch_etree = getattr(self, '_get_default_%s_view' % view_type)()
  1082. result['arch'] = etree.tostring(arch_etree, encoding='unicode')
  1083. result['type'] = view_type
  1084. result['name'] = 'default'
  1085. except AttributeError:
  1086. raise UserError(_("No default view of type '%s' could be found !") % view_type)
  1087. return result
  1088. @api.model
  1089. def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
  1090. """ fields_view_get([view_id | view_type='form'])
  1091. Get the detailed composition of the requested view like fields, model, view architecture
  1092. :param view_id: id of the view or None
  1093. :param view_type: type of the view to return if view_id is None ('form', 'tree', ...)
  1094. :param toolbar: true to include contextual actions
  1095. :param submenu: deprecated
  1096. :return: dictionary describing the composition of the requested view (including inherited views and extensions)
  1097. :raise AttributeError:
  1098. * if the inherited view has unknown position to work with other than 'before', 'after', 'inside', 'replace'
  1099. * if some tag other than 'position' is found in parent view
  1100. :raise Invalid ArchitectureError: if there is view type other than form, tree, calendar, search etc defined on the structure
  1101. """
  1102. View = self.env['ir.ui.view']
  1103. # Get the view arch and all other attributes describing the composition of the view
  1104. result = self._fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
  1105. # Override context for postprocessing
  1106. if view_id and result.get('base_model', self._name) != self._name:
  1107. View = View.with_context(base_model_name=result['base_model'])
  1108. # Apply post processing, groups and modifiers etc...
  1109. xarch, xfields = View.postprocess_and_fields(self._name, etree.fromstring(result['arch']), view_id)
  1110. result['arch'] = xarch
  1111. result['fields'] = xfields
  1112. # Add related action information if aksed
  1113. if toolbar:
  1114. bindings = self.env['ir.actions.actions'].get_bindings(self._name)
  1115. resreport = [action
  1116. for action in bindings['report']
  1117. if view_type == 'tree' or not action.get('multi')]
  1118. resaction = [action
  1119. for action in bindings['action']
  1120. if view_type == 'tree' or not action.get('multi')]
  1121. for res in itertools.chain(resreport, resaction):
  1122. res['string'] = res['name']
  1123. result['toolbar'] = {
  1124. 'print': resreport,
  1125. 'action': resaction,
  1126. }
  1127. return result
  1128. @api.multi
  1129. def get_formview_id(self, access_uid=None):
  1130. """ Return an view id to open the document ``self`` with. This method is
  1131. meant to be overridden in addons that want to give specific view ids
  1132. for example.
  1133. Optional access_uid holds the user that would access the form view
  1134. id different from the current environment user.
  1135. """
  1136. return False
  1137. @api.multi
  1138. def get_formview_action(self, access_uid=None):
  1139. """ Return an action to open the document ``self``. This method is meant
  1140. to be overridden in addons that want to give specific view ids for
  1141. example.
  1142. An optional access_uid holds the user that will access the document
  1143. that could be different from the current user. """
  1144. view_id = self.sudo().get_formview_id(access_uid=access_uid)
  1145. return {
  1146. 'type': 'ir.actions.act_window',
  1147. 'res_model': self._name,
  1148. 'view_type': 'form',
  1149. 'view_mode': 'form',
  1150. 'views': [(view_id, 'form')],
  1151. 'target': 'current',
  1152. 'res_id': self.id,
  1153. 'context': dict(self._context),
  1154. }
  1155. @api.multi
  1156. def get_access_action(self, access_uid=None):
  1157. """ Return an action to open the document. This method is meant to be
  1158. overridden in addons that want to give specific access to the document.
  1159. By default it opens the formview of the document.
  1160. An optional access_uid holds the user that will access the document
  1161. that could be different from the current user.
  1162. """
  1163. return self[0].get_formview_action(access_uid=access_uid)
  1164. @api.model
  1165. def search_count(self, args):
  1166. """ search_count(args) -> int
  1167. Returns the number of records in the current model matching :ref:`the
  1168. provided domain <reference/orm/domains>`.
  1169. """
  1170. res = self.search(args, count=True)
  1171. return res if isinstance(res, pycompat.integer_types) else len(res)
  1172. @api.model
  1173. @api.returns('self',
  1174. upgrade=lambda self, value, args, offset=0, limit=None, order=None, count=False: value if count else self.browse(value),
  1175. downgrade=lambda self, value, args, offset=0, limit=None, order=None, count=False: value if count else value.ids)
  1176. def search(self, args, offset=0, limit=None, order=None, count=False):
  1177. """ search(args[, offset=0][, limit=None][, order=None][, count=False])
  1178. Searches for records based on the ``args``
  1179. :ref:`search domain <reference/orm/domains>`.
  1180. :param args: :ref:`A search domain <reference/orm/domains>`. Use an empty
  1181. list to match all records.
  1182. :param int offset: number of results to ignore (default: none)
  1183. :param int limit: maximum number of records to return (default: all)
  1184. :param str order: sort string
  1185. :param bool count: if True, only counts and returns the number of matching records (default: False)
  1186. :returns: at most ``limit`` records matching the search criteria
  1187. :raise AccessError: * if user tries to bypass access rules for read on the requested object.
  1188. """
  1189. res = self._search(args, offset=offset, limit=limit, order=order, count=count)
  1190. return res if count else self.browse(res)
  1191. #
  1192. # display_name, name_get, name_create, name_search
  1193. #
  1194. @api.depends(lambda self: (self._rec_name,) if self._rec_name else ())
  1195. def _compute_display_name(self):
  1196. names = dict(self.name_get())
  1197. for record in self:
  1198. record.display_name = names.get(record.id, False)
  1199. @api.multi
  1200. def name_get(self):
  1201. """ name_get() -> [(id, name), ...]
  1202. Returns a textual representation for the records in ``self``.
  1203. By default this is the value of the ``display_name`` field.
  1204. :return: list of pairs ``(id, text_repr)`` for each records
  1205. :rtype: list(tuple)
  1206. """
  1207. result = []
  1208. name = self._rec_name
  1209. if name in self._fields:
  1210. convert = self._fields[name].convert_to_display_name
  1211. for record in self:
  1212. result.append((record.id, convert(record[name], record)))
  1213. else:
  1214. for record in self:
  1215. result.append((record.id, "%s,%s" % (record._name, record.id)))
  1216. return result
  1217. @api.model
  1218. def name_create(self, name):
  1219. """ name_create(name) -> record
  1220. Create a new record by calling :meth:`~.create` with only one value
  1221. provided: the display name of the new record.
  1222. The new record will be initialized with any default values
  1223. applicable to this model, or provided through the context. The usual
  1224. behavior of :meth:`~.create` applies.
  1225. :param name: display name of the record to create
  1226. :rtype: tuple
  1227. :return: the :meth:`~.name_get` pair value of the created record
  1228. """
  1229. if self._rec_name:
  1230. record = self.create({self._rec_name: name})
  1231. return record.name_get()[0]
  1232. else:
  1233. _logger.warning("Cannot execute name_create, no _rec_name defined on %s", self._name)
  1234. return False
  1235. @api.model
  1236. def name_search(self, name='', args=None, operator='ilike', limit=100):
  1237. """ name_search(name='', args=None, operator='ilike', limit=100) -> records
  1238. Search for records that have a display name matching the given
  1239. ``name`` pattern when compared with the given ``operator``, while also
  1240. matching the optional search domain (``args``).
  1241. This is used for example to provide suggestions based on a partial
  1242. value for a relational field. Sometimes be seen as the inverse
  1243. function of :meth:`~.name_get`, but it is not guaranteed to be.
  1244. This method is equivalent to calling :meth:`~.search` with a search
  1245. domain based on ``display_name`` and then :meth:`~.name_get` on the
  1246. result of the search.
  1247. :param str name: the name pattern to match
  1248. :param list args: optional search domain (see :meth:`~.search` for
  1249. syntax), specifying further restrictions
  1250. :param str operator: domain operator for matching ``name``, such as
  1251. ``'like'`` or ``'='``.
  1252. :param int limit: optional max number of records to return
  1253. :rtype: list
  1254. :return: list of pairs ``(id, text_repr)`` for all matching records.
  1255. """
  1256. return self._name_search(name, args, operator, limit=limit)
  1257. @api.model
  1258. def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None):
  1259. # private implementation of name_search, allows passing a dedicated user
  1260. # for the name_get part to solve some access rights issues
  1261. args = list(args or [])
  1262. # optimize out the default criterion of ``ilike ''`` that matches everything
  1263. if not self._rec_name:
  1264. _logger.warning("Cannot execute name_search, no _rec_name defined on %s", self._name)
  1265. elif not (name == '' and operator == 'ilike'):
  1266. args += [(self._rec_name, operator, name)]
  1267. access_rights_uid = name_get_uid or self._uid
  1268. ids = self._search(args, limit=limit, access_rights_uid=access_rights_uid)
  1269. recs = self.browse(ids)
  1270. return recs.sudo(access_rights_uid).name_get()
  1271. @api.model
  1272. def _add_missing_default_values(self, values):
  1273. # avoid overriding inherited values when parent is set
  1274. avoid_models = {
  1275. parent_model
  1276. for parent_model, parent_field in self._inherits.items()
  1277. if parent_field in values
  1278. }
  1279. # compute missing fields
  1280. missing_defaults = {
  1281. name
  1282. for name, field in self._fields.items()
  1283. if name not in values
  1284. if self._log_access and name not in MAGIC_COLUMNS
  1285. if not (field.inherited and field.related_field.model_name in avoid_models)
  1286. }
  1287. if not missing_defaults:
  1288. return values
  1289. # override defaults with the provided values, never allow the other way around
  1290. defaults = self.default_get(list(missing_defaults))
  1291. for name, value in defaults.items():
  1292. if self._fields[name].type == 'many2many' and value and isinstance(value[0], pycompat.integer_types):
  1293. # convert a list of ids into a list of commands
  1294. defaults[name] = [(6, 0, value)]
  1295. elif self._fields[name].type == 'one2many' and value and isinstance(value[0], dict):
  1296. # convert a list of dicts into a list of commands
  1297. defaults[name] = [(0, 0, x) for x in value]
  1298. defaults.update(values)
  1299. return defaults
  1300. @classmethod
  1301. def clear_caches(cls):
  1302. """ Clear the caches
  1303. This clears the caches associated to methods decorated with
  1304. ``tools.ormcache`` or ``tools.ormcache_multi``.
  1305. """
  1306. cls.pool._clear_cache()
  1307. @api.model
  1308. def _read_group_fill_results(self, domain, groupby, remaining_groupbys,
  1309. aggregated_fields, count_field,
  1310. read_group_result, read_group_order=None):
  1311. """Helper method for filling in empty groups for all possible values of
  1312. the field being grouped by"""
  1313. field = self._fields[groupby]
  1314. if not field.group_expand:
  1315. return read_group_result
  1316. # field.group_expand is the name of a method that returns the groups
  1317. # that we want to display for this field, in the form of a recordset or
  1318. # a list of values (depending on the type of the field). This is useful
  1319. # to implement kanban views for instance, where some columns should be
  1320. # displayed even if they don't contain any record.
  1321. # determine all groups that should be returned
  1322. values = [line[groupby] for line in read_group_result if line[groupby]]
  1323. if field.relational:
  1324. # groups is a recordset; determine order on groups's model
  1325. groups = self.env[field.comodel_name].browse([value[0] for value in values])
  1326. order = groups._order
  1327. if read_group_order == groupby + ' desc':
  1328. order = tools.reverse_order(order)
  1329. groups = getattr(self, field.group_expand)(groups, domain, order)
  1330. groups = groups.sudo()
  1331. values = groups.name_get()
  1332. value2key = lambda value: value and value[0]
  1333. else:
  1334. # groups is a list of values
  1335. values = getattr(self, field.group_expand)(values, domain, None)
  1336. if read_group_order == groupby + ' desc':
  1337. values.reverse()
  1338. value2key = lambda value: value
  1339. # Merge the current results (list of dicts) with all groups. Determine
  1340. # the global order of results groups, which is supposed to be in the
  1341. # same order as read_group_result (in the case of a many2one field).
  1342. result = OrderedDict((value2key(value), {}) for value in values)
  1343. # fill in results from read_group_result
  1344. for line in read_group_result:
  1345. key = value2key(line[groupby])
  1346. if not result.get(key):
  1347. result[key] = line
  1348. else:
  1349. result[key][count_field] = line[count_field]
  1350. # fill in missing results from all groups
  1351. for value in values:
  1352. key = value2key(value)
  1353. if not result[key]:
  1354. line = dict.fromkeys(aggregated_fields, False)
  1355. line[groupby] = value
  1356. line[groupby + '_count'] = 0
  1357. line['__domain'] = [(groupby, '=', key)] + domain
  1358. if remaining_groupbys:
  1359. line['__context'] = {'group_by': remaining_groupbys}
  1360. result[key] = line
  1361. # add folding information if present
  1362. if field.relational and groups._fold_name in groups._fields:
  1363. fold = {group.id: group[groups._fold_name]
  1364. for group in groups.browse([key for key in result if key])}
  1365. for key, line in result.items():
  1366. line['__fold'] = fold.get(key, False)
  1367. return list(result.values())
  1368. @api.model
  1369. def _read_group_prepare(self, orderby, aggregated_fields, annotated_groupbys, query):
  1370. """
  1371. Prepares the GROUP BY and ORDER BY terms for the read_group method. Adds the missing JOIN clause
  1372. to the query if order should be computed against m2o field.
  1373. :param orderby: the orderby definition in the form "%(field)s %(order)s"
  1374. :param aggregated_fields: list of aggregated fields in the query
  1375. :param annotated_groupbys: list of dictionaries returned by _read_group_process_groupby
  1376. These dictionaries contains the qualified name of each groupby
  1377. (fully qualified SQL name for the corresponding field),
  1378. and the (non raw) field name.
  1379. :param osv.Query query: the query under construction
  1380. :return: (groupby_terms, orderby_terms)
  1381. """
  1382. orderby_terms = []
  1383. groupby_terms = [gb['qualified_field'] for gb in annotated_groupbys]
  1384. groupby_fields = [gb['groupby'] for gb in annotated_groupbys]
  1385. if not orderby:
  1386. return groupby_terms, orderby_terms
  1387. self._check_qorder(orderby)
  1388. for order_part in orderby.split(','):
  1389. order_split = order_part.split()
  1390. order_field = order_split[0]
  1391. if order_field == 'id' or order_field in groupby_fields:
  1392. if self._fields[order_field.split(':')[0]].type == 'many2one':
  1393. order_clause = self._generate_order_by(order_part, query).replace('ORDER BY ', '')
  1394. if order_clause:
  1395. orderby_terms.append(order_clause)
  1396. groupby_terms += [order_term.split()[0] for order_term in order_clause.split(',')]
  1397. else:
  1398. order = '"%s" %s' % (order_field, '' if len(order_split) == 1 else order_split[1])
  1399. orderby_terms.append(order)
  1400. elif order_field in aggregated_fields:
  1401. order_split[0] = '"' + order_field + '"'
  1402. orderby_terms.append(' '.join(order_split))
  1403. else:
  1404. # Cannot order by a field that will not appear in the results (needs to be grouped or aggregated)
  1405. _logger.warn('%s: read_group order by `%s` ignored, cannot sort on empty columns (not grouped/aggregated)',
  1406. self._name, order_part)
  1407. return groupby_terms, orderby_terms
  1408. @api.model
  1409. def _read_group_process_groupby(self, gb, query):
  1410. """
  1411. Helper method to collect important information about groupbys: raw
  1412. field name, type, time information, qualified name, ...
  1413. """
  1414. split = gb.split(':')
  1415. field_type = self._fields[split[0]].type
  1416. gb_function = split[1] if len(split) == 2 else None
  1417. temporal = field_type in ('date', 'datetime')
  1418. tz_convert = field_type == 'datetime' and self._context.get('tz') in pytz.all_timezones
  1419. qualified_field = self._inherits_join_calc(self._table, split[0], query)
  1420. if temporal:
  1421. display_formats = {
  1422. # Careful with week/year formats:
  1423. # - yyyy (lower) must always be used, *except* for week+year formats
  1424. # - YYYY (upper) must always be used for week+year format
  1425. # e.g. 2006-01-01 is W52 2005 in some locales (de_DE),
  1426. # and W1 2006 for others
  1427. #
  1428. # Mixing both formats, e.g. 'MMM YYYY' would yield wrong results,
  1429. # such as 2006-01-01 being formatted as "January 2005" in some locales.
  1430. # Cfr: http://babel.pocoo.org/docs/dates/#date-fields
  1431. 'day': 'dd MMM yyyy', # yyyy = normal year
  1432. 'week': "'W'w YYYY", # w YYYY = ISO week-year
  1433. 'month': 'MMMM yyyy',
  1434. 'quarter': 'QQQ yyyy',
  1435. 'year': 'yyyy',
  1436. }
  1437. time_intervals = {
  1438. 'day': dateutil.relativedelta.relativedelta(days=1),
  1439. 'week': datetime.timedelta(days=7),
  1440. 'month': dateutil.relativedelta.relativedelta(months=1),
  1441. 'quarter': dateutil.relativedelta.relativedelta(months=3),
  1442. 'year': dateutil.relativedelta.relativedelta(years=1)
  1443. }
  1444. if tz_convert:
  1445. qualified_field = "timezone('%s', timezone('UTC',%s))" % (self._context.get('tz', 'UTC'), qualified_field)
  1446. qualified_field = "date_trunc('%s', %s)" % (gb_function or 'month', qualified_field)
  1447. if field_type == 'boolean':
  1448. qualified_field = "coalesce(%s,false)" % qualified_field
  1449. return {
  1450. 'field': split[0],
  1451. 'groupby': gb,
  1452. 'type': field_type,
  1453. 'display_format': display_formats[gb_function or 'month'] if temporal else None,
  1454. 'interval': time_intervals[gb_function or 'month'] if temporal else None,
  1455. 'tz_convert': tz_convert,
  1456. 'qualified_field': qualified_field
  1457. }
  1458. @api.model
  1459. def _read_group_prepare_data(self, key, value, groupby_dict):
  1460. """
  1461. Helper method to sanitize the data received by read_group. The None
  1462. values are converted to False, and the date/datetime are formatted,
  1463. and corrected according to the timezones.
  1464. """
  1465. value = False if value is None else value
  1466. gb = groupby_dict.get(key)
  1467. if gb and gb['type'] in ('date', 'datetime') and value:
  1468. if isinstance(value, pycompat.string_types):
  1469. dt_format = DEFAULT_SERVER_DATETIME_FORMAT if gb['type'] == 'datetime' else DEFAULT_SERVER_DATE_FORMAT
  1470. value = datetime.datetime.strptime(value, dt_format)
  1471. if gb['tz_convert']:
  1472. value = pytz.timezone(self._context['tz']).localize(value)
  1473. return value
  1474. @api.model
  1475. def _read_group_format_result(self, data, annotated_groupbys, groupby, domain):
  1476. """
  1477. Helper method to format the data contained in the dictionary data by
  1478. adding the domain corresponding to its values, the groupbys in the
  1479. context and by properly formatting the date/datetime values.
  1480. :param data: a single group
  1481. :param annotated_groupbys: expanded grouping metainformation
  1482. :param groupby: original grouping metainformation
  1483. :param domain: original domain for read_group
  1484. """
  1485. sections = []
  1486. for gb in annotated_groupbys:
  1487. ftype = gb['type']
  1488. value = data[gb['groupby']]
  1489. # full domain for this groupby spec
  1490. d = None
  1491. if value:
  1492. if ftype == 'many2one':
  1493. value = value[0]
  1494. elif ftype in ('date', 'datetime'):
  1495. locale = self._context.get('lang') or 'en_US'
  1496. fmt = DEFAULT_SERVER_DATETIME_FORMAT if ftype == 'datetime' else DEFAULT_SERVER_DATE_FORMAT
  1497. tzinfo = None
  1498. range_start = value
  1499. range_end = value + gb['interval']
  1500. # value from postgres is in local tz (so range is
  1501. # considered in local tz e.g. "day" is [00:00, 00:00[
  1502. # local rather than UTC which could be [11:00, 11:00]
  1503. # local) but domain and raw value should be in UTC
  1504. if gb['tz_convert']:
  1505. tzinfo = range_start.tzinfo
  1506. range_start = range_start.astimezone(pytz.utc)
  1507. range_end = range_end.astimezone(pytz.utc)
  1508. range_start = range_start.strftime(fmt)
  1509. range_end = range_end.strftime(fmt)
  1510. if ftype == 'datetime':
  1511. label = babel.dates.format_datetime(
  1512. value, format=gb['display_format'],
  1513. tzinfo=tzinfo, locale=locale
  1514. )
  1515. else:
  1516. label = babel.dates.format_date(
  1517. value, format=gb['display_format'],
  1518. locale=locale
  1519. )
  1520. data[gb['groupby']] = ('%s/%s' % (range_start, range_end), label)
  1521. d = [
  1522. '&',
  1523. (gb['field'], '>=', range_start),
  1524. (gb['field'], '<', range_end),
  1525. ]
  1526. if d is None:
  1527. d = [(gb['field'], '=', value)]
  1528. sections.append(d)
  1529. sections.append(domain)
  1530. data['__domain'] = expression.AND(sections)
  1531. if len(groupby) - len(annotated_groupbys) >= 1:
  1532. data['__context'] = { 'group_by': groupby[len(annotated_groupbys):]}
  1533. del data['id']
  1534. return data
  1535. @api.model
  1536. def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
  1537. """
  1538. Get the list of records in list view grouped by the given ``groupby`` fields
  1539. :param domain: list specifying search criteria [['field_name', 'operator', 'value'], ...]
  1540. :param list fields: list of fields present in the list view specified on the object
  1541. :param list groupby: list of groupby descriptions by which the records will be grouped.
  1542. A groupby description is either a field (then it will be grouped by that field)
  1543. or a string 'field:groupby_function'. Right now, the only functions supported
  1544. are 'day', 'week', 'month', 'quarter' or 'year', and they only make sense for
  1545. date/datetime fields.
  1546. :param int offset: optional number of records to skip
  1547. :param int limit: optional max number of records to return
  1548. :param list orderby: optional ``order by`` specification, for
  1549. overriding the natural sort ordering of the
  1550. groups, see also :py:meth:`~osv.osv.osv.search`
  1551. (supported only for many2one fields currently)
  1552. :param bool lazy: if true, the results are only grouped by the first groupby and the
  1553. remaining groupbys are put in the __context key. If false, all the groupbys are
  1554. done in one call.
  1555. :return: list of dictionaries(one dictionary for each record) containing:
  1556. * the values of fields grouped by the fields in ``groupby`` argument
  1557. * __domain: list of tuples specifying the search criteria
  1558. * __context: dictionary with argument like ``groupby``
  1559. :rtype: [{'field_name_1': value, ...]
  1560. :raise AccessError: * if user has no read rights on the requested object
  1561. * if user tries to bypass access rules for read on the requested object
  1562. """
  1563. result = self._read_group_raw(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
  1564. groupby = [groupby] if isinstance(groupby, pycompat.string_types) else list(OrderedSet(groupby))
  1565. dt = [
  1566. f for f in groupby
  1567. if self._fields[f.split(':')[0]].type in ('date', 'datetime')
  1568. ]
  1569. # iterate on all results and replace the "full" date/datetime value
  1570. # (range, label) by just the formatted label, in-place
  1571. for group in result:
  1572. for df in dt:
  1573. # could group on a date(time) field which is empty in some
  1574. # records, in which case as with m2o the _raw value will be
  1575. # `False` instead of a (value, label) pair. In that case,
  1576. # leave the `False` value alone
  1577. if group.get(df):
  1578. group[df] = group[df][1]
  1579. return result
  1580. @api.model
  1581. def _read_group_raw(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
  1582. self.check_access_rights('read')
  1583. query = self._where_calc(domain)
  1584. fields = fields or [f.name for f in self._fields.values() if f.store]
  1585. groupby = [groupby] if isinstance(groupby, pycompat.string_types) else list(OrderedSet(groupby))
  1586. groupby_list = groupby[:1] if lazy else groupby
  1587. annotated_groupbys = [self._read_group_process_groupby(gb, query) for gb in groupby_list]
  1588. groupby_fields = [g['field'] for g in annotated_groupbys]
  1589. order = orderby or ','.join([g for g in groupby_list])
  1590. groupby_dict = {gb['groupby']: gb for gb in annotated_groupbys}
  1591. self._apply_ir_rules(query, 'read')
  1592. for gb in groupby_fields:
  1593. assert gb in fields, "Fields in 'groupby' must appear in the list of fields to read (perhaps it's missing in the list view?)"
  1594. assert gb in self._fields, "Unknown field %r in 'groupby'" % gb
  1595. gb_field = self._fields[gb].base_field
  1596. assert gb_field.store and gb_field.column_type, "Fields in 'groupby' must be regular database-persisted fields (no function or related fields), or function fields with store=True"
  1597. aggregated_fields = [
  1598. f for f in fields
  1599. if f != 'sequence'
  1600. if f not in groupby_fields
  1601. for field in [self._fields.get(f)]
  1602. if field
  1603. if field.group_operator
  1604. if field.base_field.store and field.base_field.column_type
  1605. ]
  1606. field_formatter = lambda f: (
  1607. self._fields[f].group_operator,
  1608. self._inherits_join_calc(self._table, f, query),
  1609. f,
  1610. )
  1611. select_terms = ['%s(%s) AS "%s" ' % field_formatter(f) for f in aggregated_fields]
  1612. for gb in annotated_groupbys:
  1613. select_terms.append('%s as "%s" ' % (gb['qualified_field'], gb['groupby']))
  1614. groupby_terms, orderby_terms = self._read_group_prepare(order, aggregated_fields, annotated_groupbys, query)
  1615. from_clause, where_clause, where_clause_params = query.get_sql()
  1616. if lazy and (len(groupby_fields) >= 2 or not self._context.get('group_by_no_leaf')):
  1617. count_field = groupby_fields[0] if len(groupby_fields) >= 1 else '_'
  1618. else:
  1619. count_field = '_'
  1620. count_field += '_count'
  1621. prefix_terms = lambda prefix, terms: (prefix + " " + ",".join(terms)) if terms else ''
  1622. prefix_term = lambda prefix, term: ('%s %s' % (prefix, term)) if term else ''
  1623. query = """
  1624. SELECT min("%(table)s".id) AS id, count("%(table)s".id) AS "%(count_field)s" %(extra_fields)s
  1625. FROM %(from)s
  1626. %(where)s
  1627. %(groupby)s
  1628. %(orderby)s
  1629. %(limit)s
  1630. %(offset)s
  1631. """ % {
  1632. 'table': self._table,
  1633. 'count_field': count_field,
  1634. 'extra_fields': prefix_terms(',', select_terms),
  1635. 'from': from_clause,
  1636. 'where': prefix_term('WHERE', where_clause),
  1637. 'groupby': prefix_terms('GROUP BY', groupby_terms),
  1638. 'orderby': prefix_terms('ORDER BY', orderby_terms),
  1639. 'limit': prefix_term('LIMIT', int(limit) if limit else None),
  1640. 'offset': prefix_term('OFFSET', int(offset) if limit else None),
  1641. }
  1642. self._cr.execute(query, where_clause_params)
  1643. fetched_data = self._cr.dictfetchall()
  1644. if not groupby_fields:
  1645. return fetched_data
  1646. self._read_group_resolve_many2one_fields(fetched_data, annotated_groupbys)
  1647. data = ({k: self._read_group_prepare_data(k,v, groupby_dict) for k,v in r.items()} for r in fetched_data)
  1648. result = [self._read_group_format_result(d, annotated_groupbys, groupby, domain) for d in data]
  1649. if lazy:
  1650. # Right now, read_group only fill results in lazy mode (by default).
  1651. # If you need to have the empty groups in 'eager' mode, then the
  1652. # method _read_group_fill_results need to be completely reimplemented
  1653. # in a sane way
  1654. result = self._read_group_fill_results(
  1655. domain, groupby_fields[0], groupby[len(annotated_groupbys):],
  1656. aggregated_fields, count_field, result, read_group_order=order,
  1657. )
  1658. return result
  1659. def _read_group_resolve_many2one_fields(self, data, fields):
  1660. many2onefields = {field['field'] for field in fields if field['type'] == 'many2one'}
  1661. for field in many2onefields:
  1662. ids_set = {d[field] for d in data if d[field]}
  1663. m2o_records = self.env[self._fields[field].comodel_name].browse(ids_set)
  1664. data_dict = dict(m2o_records.name_get())
  1665. for d in data:
  1666. d[field] = (d[field], data_dict[d[field]]) if d[field] else False
  1667. def _inherits_join_add(self, current_model, parent_model_name, query):
  1668. """
  1669. Add missing table SELECT and JOIN clause to ``query`` for reaching the parent table (no duplicates)
  1670. :param current_model: current model object
  1671. :param parent_model_name: name of the parent model for which the clauses should be added
  1672. :param query: query object on which the JOIN should be added
  1673. """
  1674. inherits_field = current_model._inherits[parent_model_name]
  1675. parent_model = self.env[parent_model_name]
  1676. parent_alias, parent_alias_statement = query.add_join((current_model._table, parent_model._table, inherits_field, 'id', inherits_field), implicit=True)
  1677. return parent_alias
  1678. @api.model
  1679. def _inherits_join_calc(self, alias, fname, query, implicit=True, outer=False):
  1680. """
  1681. Adds missing table select and join clause(s) to ``query`` for reaching
  1682. the field coming from an '_inherits' parent table (no duplicates).
  1683. :param alias: name of the initial SQL alias
  1684. :param fname: name of inherited field to reach
  1685. :param query: query object on which the JOIN should be added
  1686. :return: qualified name of field, to be used in SELECT clause
  1687. """
  1688. # INVARIANT: alias is the SQL alias of model._table in query
  1689. model, field = self, self._fields[fname]
  1690. while field.inherited:
  1691. # retrieve the parent model where field is inherited from
  1692. parent_model = self.env[field.related_field.model_name]
  1693. parent_fname = field.related[0]
  1694. # JOIN parent_model._table AS parent_alias ON alias.parent_fname = parent_alias.id
  1695. parent_alias, _ = query.add_join(
  1696. (alias, parent_model._table, parent_fname, 'id', parent_fname),
  1697. implicit=implicit, outer=outer,
  1698. )
  1699. model, alias, field = parent_model, parent_alias, field.related_field
  1700. # handle the case where the field is translated
  1701. if field.translate is True:
  1702. return model._generate_translated_field(alias, fname, query)
  1703. else:
  1704. return '"%s"."%s"' % (alias, fname)
  1705. @api.model_cr
  1706. def _parent_store_compute(self):
  1707. if not self._parent_store:
  1708. return
  1709. _logger.info('Computing parent left and right for table %s...', self._table)
  1710. cr = self._cr
  1711. select = "SELECT id FROM %s WHERE %s=%%s ORDER BY %s" % \
  1712. (self._table, self._parent_name, self._parent_order)
  1713. update = "UPDATE %s SET parent_left=%%s, parent_right=%%s WHERE id=%%s" % self._table
  1714. def process(root, left):
  1715. """ Set root.parent_left to ``left``, and return root.parent_right + 1 """
  1716. cr.execute(select, (root,))
  1717. right = left + 1
  1718. for (id,) in cr.fetchall():
  1719. right = process(id, right)
  1720. cr.execute(update, (left, right, root))
  1721. return right + 1
  1722. select0 = "SELECT id FROM %s WHERE %s IS NULL ORDER BY %s" % \
  1723. (self._table, self._parent_name, self._parent_order)
  1724. cr.execute(select0)
  1725. pos = 0
  1726. for (id,) in cr.fetchall():
  1727. pos = process(id, pos)
  1728. self.invalidate_cache(['parent_left', 'parent_right'])
  1729. return True
  1730. @api.model
  1731. def _check_selection_field_value(self, field, value):
  1732. """ Check whether value is among the valid values for the given
  1733. selection/reference field, and raise an exception if not.
  1734. """
  1735. field = self._fields[field]
  1736. field.convert_to_cache(value, self)
  1737. @api.model_cr
  1738. def _check_removed_columns(self, log=False):
  1739. # iterate on the database columns to drop the NOT NULL constraints of
  1740. # fields which were required but have been removed (or will be added by
  1741. # another module)
  1742. cr = self._cr
  1743. cols = [name for name, field in self._fields.items()
  1744. if field.store and field.column_type]
  1745. cr.execute("SELECT a.attname, a.attnotnull"
  1746. " FROM pg_class c, pg_attribute a"
  1747. " WHERE c.relname=%s"
  1748. " AND c.oid=a.attrelid"
  1749. " AND a.attisdropped=%s"
  1750. " AND pg_catalog.format_type(a.atttypid, a.atttypmod) NOT IN ('cid', 'tid', 'oid', 'xid')"
  1751. " AND a.attname NOT IN %s", (self._table, False, tuple(cols))),
  1752. for row in cr.dictfetchall():
  1753. if log:
  1754. _logger.debug("column %s is in the table %s but not in the corresponding object %s",
  1755. row['attname'], self._table, self._name)
  1756. if row['attnotnull']:
  1757. tools.drop_not_null(cr, self._table, row['attname'])
  1758. @api.model_cr_context
  1759. def _init_column(self, column_name):
  1760. """ Initialize the value of the given column for existing rows. """
  1761. # get the default value; ideally, we should use default_get(), but it
  1762. # fails due to ir.default not being ready
  1763. field = self._fields[column_name]
  1764. if field.default:
  1765. value = field.default(self)
  1766. value = field.convert_to_cache(value, self, validate=False)
  1767. value = field.convert_to_record(value, self)
  1768. value = field.convert_to_write(value, self)
  1769. value = field.convert_to_column(value, self)
  1770. else:
  1771. value = None
  1772. # Write value if non-NULL, except for booleans for which False means
  1773. # the same as NULL - this saves us an expensive query on large tables.
  1774. necessary = (value is not None) if field.type != 'boolean' else value
  1775. if necessary:
  1776. _logger.debug("Table '%s': setting default value of new column %s to %r",
  1777. self._table, column_name, value)
  1778. query = 'UPDATE "%s" SET "%s"=%s WHERE "%s" IS NULL' % (
  1779. self._table, column_name, field.column_format, column_name)
  1780. self._cr.execute(query, (value,))
  1781. @ormcache()
  1782. def _table_has_rows(self):
  1783. """ Return whether the model's table has rows. This method should only
  1784. be used when updating the database schema (:meth:`~._auto_init`).
  1785. """
  1786. self.env.cr.execute('SELECT 1 FROM "%s" LIMIT 1' % self._table)
  1787. return self.env.cr.rowcount
  1788. @api.model_cr_context
  1789. def _auto_init(self):
  1790. """ Initialize the database schema of ``self``:
  1791. - create the corresponding table,
  1792. - create/update the necessary columns/tables for fields,
  1793. - initialize new columns on existing rows,
  1794. - add the SQL constraints given on the model,
  1795. - add the indexes on indexed fields,
  1796. Also prepare post-init stuff to:
  1797. - add foreign key constraints,
  1798. - reflect models, fields, relations and constraints,
  1799. - mark fields to recompute on existing records.
  1800. Note: you should not override this method. Instead, you can modify
  1801. the model's database schema by overriding method :meth:`~.init`,
  1802. which is called right after this one.
  1803. """
  1804. raise_on_invalid_object_name(self._name)
  1805. # This prevents anything called by this method (in particular default
  1806. # values) from prefetching a field for which the corresponding column
  1807. # has not been added in database yet!
  1808. self = self.with_context(prefetch_fields=False)
  1809. self.pool.post_init(self._reflect)
  1810. cr = self._cr
  1811. parent_store_compute = False
  1812. update_custom_fields = self._context.get('update_custom_fields', False)
  1813. must_create_table = not tools.table_exists(cr, self._table)
  1814. if self._auto:
  1815. if must_create_table:
  1816. tools.create_model_table(cr, self._table, self._description)
  1817. if self._parent_store:
  1818. if not tools.column_exists(cr, self._table, 'parent_left'):
  1819. self._create_parent_columns()
  1820. parent_store_compute = True
  1821. self._check_removed_columns(log=False)
  1822. # update the database schema for fields
  1823. columns = tools.table_columns(cr, self._table)
  1824. def recompute(field):
  1825. _logger.info("Storing computed values of %s", field)
  1826. recs = self.with_context(active_test=False).search([])
  1827. recs._recompute_todo(field)
  1828. for field in self._fields.values():
  1829. if not field.store:
  1830. continue
  1831. if field.manual and not update_custom_fields:
  1832. continue # don't update custom fields
  1833. new = field.update_db(self, columns)
  1834. if new and field.compute:
  1835. self.pool.post_init(recompute, field)
  1836. if self._auto:
  1837. self._add_sql_constraints()
  1838. if must_create_table:
  1839. self._execute_sql()
  1840. if parent_store_compute:
  1841. self._parent_store_compute()
  1842. @api.model_cr
  1843. def init(self):
  1844. """ This method is called after :meth:`~._auto_init`, and may be
  1845. overridden to create or modify a model's database schema.
  1846. """
  1847. pass
  1848. @api.model_cr
  1849. def _create_parent_columns(self):
  1850. tools.create_column(self._cr, self._table, 'parent_left', 'INTEGER')
  1851. tools.create_column(self._cr, self._table, 'parent_right', 'INTEGER')
  1852. if 'parent_left' not in self._fields:
  1853. _logger.error("add a field parent_left on model %s: parent_left = fields.Integer('Left Parent', index=True)", self._name)
  1854. elif not self._fields['parent_left'].index:
  1855. _logger.error('parent_left field on model %s must be indexed! Add index=True to the field definition)', self._name)
  1856. if 'parent_right' not in self._fields:
  1857. _logger.error("add a field parent_right on model %s: parent_right = fields.Integer('Left Parent', index=True)", self._name)
  1858. elif not self._fields['parent_right'].index:
  1859. _logger.error("parent_right field on model %s must be indexed! Add index=True to the field definition)", self._name)
  1860. if self._fields[self._parent_name].ondelete not in ('cascade', 'restrict'):
  1861. _logger.error("The field %s on model %s must be set as ondelete='cascade' or 'restrict'", self._parent_name, self._name)
  1862. @api.model_cr
  1863. def _add_sql_constraints(self):
  1864. """
  1865. Modify this model's database table constraints so they match the one in
  1866. _sql_constraints.
  1867. """
  1868. cr = self._cr
  1869. foreign_key_re = re.compile(r'\s*foreign\s+key\b.*', re.I)
  1870. def cons_text(txt):
  1871. return txt.lower().replace(', ',',').replace(' (','(')
  1872. def process(key, definition):
  1873. conname = '%s_%s' % (self._table, key)
  1874. has_definition = tools.constraint_definition(cr, conname)
  1875. if not has_definition:
  1876. # constraint does not exists
  1877. tools.add_constraint(cr, self._table, conname, definition)
  1878. elif cons_text(definition) != cons_text(has_definition):
  1879. # constraint exists but its definition may have changed
  1880. tools.drop_constraint(cr, self._table, conname)
  1881. tools.add_constraint(cr, self._table, conname, definition)
  1882. for (key, definition, _) in self._sql_constraints:
  1883. if foreign_key_re.match(definition):
  1884. self.pool.post_init(process, key, definition)
  1885. else:
  1886. process(key, definition)
  1887. @api.model_cr
  1888. def _execute_sql(self):
  1889. """ Execute the SQL code from the _sql attribute (if any)."""
  1890. if hasattr(self, "_sql"):
  1891. self._cr.execute(self._sql)
  1892. #
  1893. # Update objects that uses this one to update their _inherits fields
  1894. #
  1895. @api.model
  1896. def _add_inherited_fields(self):
  1897. """ Determine inherited fields. """
  1898. # determine candidate inherited fields
  1899. fields = {}
  1900. for parent_model, parent_field in self._inherits.items():
  1901. parent = self.env[parent_model]
  1902. for name, field in parent._fields.items():
  1903. # inherited fields are implemented as related fields, with the
  1904. # following specific properties:
  1905. # - reading inherited fields should not bypass access rights
  1906. # - copy inherited fields iff their original field is copied
  1907. fields[name] = field.new(
  1908. inherited=True,
  1909. related=(parent_field, name),
  1910. related_sudo=False,
  1911. copy=field.copy,
  1912. )
  1913. # add inherited fields that are not redefined locally
  1914. for name, field in fields.items():
  1915. if name not in self._fields:
  1916. self._add_field(name, field)
  1917. @api.model
  1918. def _inherits_check(self):
  1919. for table, field_name in self._inherits.items():
  1920. field = self._fields.get(field_name)
  1921. if not field:
  1922. _logger.info('Missing many2one field definition for _inherits reference "%s" in "%s", using default one.', field_name, self._name)
  1923. from .fields import Many2one
  1924. field = Many2one(table, string="Automatically created field to link to parent %s" % table, required=True, ondelete="cascade")
  1925. self._add_field(field_name, field)
  1926. elif not field.required or field.ondelete.lower() not in ("cascade", "restrict"):
  1927. _logger.warning('Field definition for _inherits reference "%s" in "%s" must be marked as "required" with ondelete="cascade" or "restrict", forcing it to required + cascade.', field_name, self._name)
  1928. field.required = True
  1929. field.ondelete = "cascade"
  1930. # reflect fields with delegate=True in dictionary self._inherits
  1931. for field in self._fields.values():
  1932. if field.type == 'many2one' and not field.related and field.delegate:
  1933. if not field.required:
  1934. _logger.warning("Field %s with delegate=True must be required.", field)
  1935. field.required = True
  1936. if field.ondelete.lower() not in ('cascade', 'restrict'):
  1937. field.ondelete = 'cascade'
  1938. self._inherits[field.comodel_name] = field.name
  1939. @api.model
  1940. def _prepare_setup(self):
  1941. """ Prepare the setup of the model. """
  1942. cls = type(self)
  1943. cls._setup_done = False
  1944. # a model's base structure depends on its mro (without registry classes)
  1945. cls._model_cache_key = tuple(c for c in cls.mro() if getattr(c, 'pool', None) is None)
  1946. @api.model
  1947. def _setup_base(self):
  1948. """ Determine the inherited and custom fields of the model. """
  1949. cls = type(self)
  1950. if cls._setup_done:
  1951. return
  1952. # 1. determine the proper fields of the model: the fields defined on the
  1953. # class and magic fields, not the inherited or custom ones
  1954. cls0 = cls.pool.model_cache.get(cls._model_cache_key)
  1955. if cls0 and cls0._model_cache_key == cls._model_cache_key:
  1956. # cls0 is either a model class from another registry, or cls itself.
  1957. # The point is that it has the same base classes. We retrieve stuff
  1958. # from cls0 to optimize the setup of cls. cls0 is guaranteed to be
  1959. # properly set up: registries are loaded under a global lock,
  1960. # therefore two registries are never set up at the same time.
  1961. # remove fields that are not proper to cls
  1962. for name in OrderedSet(cls._fields) - cls0._proper_fields:
  1963. delattr(cls, name)
  1964. cls._fields.pop(name, None)
  1965. # collect proper fields on cls0, and add them on cls
  1966. for name in cls0._proper_fields:
  1967. field = cls0._fields[name]
  1968. # regular fields are shared, while related fields are setup from scratch
  1969. if not field.related:
  1970. self._add_field(name, field)
  1971. else:
  1972. self._add_field(name, field.new(**field.args))
  1973. cls._proper_fields = OrderedSet(cls._fields)
  1974. else:
  1975. # retrieve fields from parent classes, and duplicate them on cls to
  1976. # avoid clashes with inheritance between different models
  1977. for name in cls._fields:
  1978. delattr(cls, name)
  1979. cls._fields = OrderedDict()
  1980. for name, field in sorted(getmembers(cls, Field.__instancecheck__), key=lambda f: f[1]._sequence):
  1981. # do not retrieve magic, custom and inherited fields
  1982. if not any(field.args.get(k) for k in ('automatic', 'manual', 'inherited')):
  1983. self._add_field(name, field.new())
  1984. self._add_magic_fields()
  1985. cls._proper_fields = OrderedSet(cls._fields)
  1986. cls.pool.model_cache[cls._model_cache_key] = cls
  1987. # 2. add manual fields
  1988. if self.pool._init_modules:
  1989. self.env['ir.model.fields']._add_manual_fields(self)
  1990. # 3. make sure that parent models determine their own fields, then add
  1991. # inherited fields to cls
  1992. self._inherits_check()
  1993. for parent in self._inherits:
  1994. self.env[parent]._setup_base()
  1995. self._add_inherited_fields()
  1996. # 4. initialize more field metadata
  1997. cls._field_computed = {} # fields computed with the same method
  1998. cls._field_inverses = Collector() # inverse fields for related fields
  1999. cls._field_triggers = Collector() # list of (field, path) to invalidate
  2000. cls._setup_done = True
  2001. @api.model
  2002. def _setup_fields(self):
  2003. """ Setup the fields, except for recomputation triggers. """
  2004. cls = type(self)
  2005. # set up fields
  2006. bad_fields = []
  2007. for name, field in cls._fields.items():
  2008. try:
  2009. field.setup_full(self)
  2010. except Exception:
  2011. if not self.pool.loaded and field.manual:
  2012. # Something goes wrong when setup a manual field.
  2013. # This can happen with related fields using another manual many2one field
  2014. # that hasn't been loaded because the comodel does not exist yet.
  2015. # This can also be a manual function field depending on not loaded fields yet.
  2016. bad_fields.append(name)
  2017. continue
  2018. raise
  2019. for name in bad_fields:
  2020. del cls._fields[name]
  2021. delattr(cls, name)
  2022. # map each field to the fields computed with the same method
  2023. groups = defaultdict(list)
  2024. for field in cls._fields.values():
  2025. if field.compute:
  2026. cls._field_computed[field] = group = groups[field.compute]
  2027. group.append(field)
  2028. for fields in groups.values():
  2029. compute_sudo = fields[0].compute_sudo
  2030. if not all(field.compute_sudo == compute_sudo for field in fields):
  2031. _logger.warning("%s: inconsistent 'compute_sudo' for computed fields: %s",
  2032. self._name, ", ".join(field.name for field in fields))
  2033. @api.model
  2034. def _setup_complete(self):
  2035. """ Setup recomputation triggers, and complete the model setup. """
  2036. cls = type(self)
  2037. if isinstance(self, Model):
  2038. # set up field triggers (on database-persisted models only)
  2039. for field in cls._fields.values():
  2040. # dependencies of custom fields may not exist; ignore that case
  2041. exceptions = (Exception,) if field.manual else ()
  2042. with tools.ignore(*exceptions):
  2043. field.setup_triggers(self)
  2044. # register constraints and onchange methods
  2045. cls._init_constraints_onchanges()
  2046. # validate rec_name
  2047. if cls._rec_name:
  2048. assert cls._rec_name in cls._fields, \
  2049. "Invalid rec_name %s for model %s" % (cls._rec_name, cls._name)
  2050. elif 'name' in cls._fields:
  2051. cls._rec_name = 'name'
  2052. elif 'x_name' in cls._fields:
  2053. cls._rec_name = 'x_name'
  2054. # make sure parent_order is set when necessary
  2055. if cls._parent_store and not cls._parent_order:
  2056. cls._parent_order = cls._order
  2057. @api.model
  2058. def fields_get(self, allfields=None, attributes=None):
  2059. """ fields_get([fields][, attributes])
  2060. Return the definition of each field.
  2061. The returned value is a dictionary (indiced by field name) of
  2062. dictionaries. The _inherits'd fields are included. The string, help,
  2063. and selection (if present) attributes are translated.
  2064. :param allfields: list of fields to document, all if empty or not provided
  2065. :param attributes: list of description attributes to return for each field, all if empty or not provided
  2066. """
  2067. has_access = functools.partial(self.check_access_rights, raise_exception=False)
  2068. readonly = not (has_access('write') or has_access('create'))
  2069. res = {}
  2070. for fname, field in self._fields.items():
  2071. if allfields and fname not in allfields:
  2072. continue
  2073. if field.groups and not self.user_has_groups(field.groups):
  2074. continue
  2075. description = field.get_description(self.env)
  2076. if readonly:
  2077. description['readonly'] = True
  2078. description['states'] = {}
  2079. if attributes:
  2080. description = {key: val
  2081. for key, val in description.items()
  2082. if key in attributes}
  2083. res[fname] = description
  2084. return res
  2085. @api.model
  2086. def get_empty_list_help(self, help):
  2087. """ Generic method giving the help message displayed when having
  2088. no result to display in a list or kanban view. By default it returns
  2089. the help given in parameter that is generally the help message
  2090. defined in the action.
  2091. """
  2092. return help
  2093. @api.model
  2094. def check_field_access_rights(self, operation, fields):
  2095. """
  2096. Check the user access rights on the given fields. This raises Access
  2097. Denied if the user does not have the rights. Otherwise it returns the
  2098. fields (as is if the fields is not falsy, or the readable/writable
  2099. fields if fields is falsy).
  2100. """
  2101. if self._uid == SUPERUSER_ID:
  2102. return fields or list(self._fields)
  2103. def valid(fname):
  2104. """ determine whether user has access to field ``fname`` """
  2105. field = self._fields.get(fname)
  2106. if field and field.groups:
  2107. return self.user_has_groups(field.groups)
  2108. else:
  2109. return True
  2110. if not fields:
  2111. fields = [name for name in self._fields if valid(name)]
  2112. else:
  2113. invalid_fields = {name for name in fields if not valid(name)}
  2114. if invalid_fields:
  2115. _logger.info('Access Denied by ACLs for operation: %s, uid: %s, model: %s, fields: %s',
  2116. operation, self._uid, self._name, ', '.join(invalid_fields))
  2117. raise AccessError(_('The requested operation cannot be completed due to security restrictions. '
  2118. 'Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \
  2119. (self._description, operation))
  2120. return fields
  2121. @api.multi
  2122. def read(self, fields=None, load='_classic_read'):
  2123. """ read([fields])
  2124. Reads the requested fields for the records in ``self``, low-level/RPC
  2125. method. In Python code, prefer :meth:`~.browse`.
  2126. :param fields: list of field names to return (default is all fields)
  2127. :return: a list of dictionaries mapping field names to their values,
  2128. with one dictionary per record
  2129. :raise AccessError: if user has no read rights on some of the given
  2130. records
  2131. """
  2132. # check access rights
  2133. self.check_access_rights('read')
  2134. fields = self.check_field_access_rights('read', fields)
  2135. # split fields into stored and computed fields
  2136. stored, inherited, computed = [], [], []
  2137. for name in fields:
  2138. field = self._fields.get(name)
  2139. if field:
  2140. if field.store:
  2141. stored.append(name)
  2142. elif field.base_field.store:
  2143. inherited.append(name)
  2144. else:
  2145. computed.append(name)
  2146. else:
  2147. _logger.warning("%s.read() with unknown field '%s'", self._name, name)
  2148. # fetch stored fields from the database to the cache; this should feed
  2149. # the prefetching of secondary records
  2150. self._read_from_database(stored, inherited)
  2151. # retrieve results from records; this takes values from the cache and
  2152. # computes remaining fields
  2153. result = []
  2154. name_fields = [(name, self._fields[name]) for name in (stored + inherited + computed)]
  2155. use_name_get = (load == '_classic_read')
  2156. for record in self:
  2157. try:
  2158. values = {'id': record.id}
  2159. for name, field in name_fields:
  2160. values[name] = field.convert_to_read(record[name], record, use_name_get)
  2161. result.append(values)
  2162. except MissingError:
  2163. pass
  2164. return result
  2165. @api.multi
  2166. def _prefetch_field(self, field):
  2167. """ Read from the database in order to fetch ``field`` (:class:`Field`
  2168. instance) for ``self`` in cache.
  2169. """
  2170. # fetch the records of this model without field_name in their cache
  2171. records = self._in_cache_without(field)
  2172. # determine which fields can be prefetched
  2173. fs = {field}
  2174. if self._context.get('prefetch_fields', True) and field.prefetch:
  2175. fs.update(
  2176. f
  2177. for f in self._fields.values()
  2178. # select fields that can be prefetched
  2179. if f.prefetch
  2180. # discard fields with groups that the user may not access
  2181. if not (f.groups and not self.user_has_groups(f.groups))
  2182. # discard fields that must be recomputed
  2183. if not (f.compute and self.env.field_todo(f))
  2184. )
  2185. # special case: discard records to recompute for field
  2186. records -= self.env.field_todo(field)
  2187. # in onchange mode, discard computed fields and fields in cache
  2188. if self.env.in_onchange:
  2189. for f in list(fs):
  2190. if f.compute or self.env.cache.contains(self, f):
  2191. fs.discard(f)
  2192. else:
  2193. records &= self._in_cache_without(f)
  2194. # fetch records with read()
  2195. assert self in records and field in fs
  2196. records = records.with_prefetch(self._prefetch)
  2197. result = []
  2198. try:
  2199. result = records.read([f.name for f in fs], load='_classic_write')
  2200. except AccessError:
  2201. # not all records may be accessible, try with only current record
  2202. result = self.read([f.name for f in fs], load='_classic_write')
  2203. # check the cache, and update it if necessary
  2204. if not self.env.cache.contains_value(self, field):
  2205. for values in result:
  2206. record = self.browse(values.pop('id'), self._prefetch)
  2207. record._cache.update(record._convert_to_cache(values, validate=False))
  2208. if not self.env.cache.contains(self, field):
  2209. exc = AccessError("No value found for %s.%s" % (self, field.name))
  2210. self.env.cache.set_failed(self, field, exc)
  2211. @api.multi
  2212. def _read_from_database(self, field_names, inherited_field_names=[]):
  2213. """ Read the given fields of the records in ``self`` from the database,
  2214. and store them in cache. Access errors are also stored in cache.
  2215. :param field_names: list of column names of model ``self``; all those
  2216. fields are guaranteed to be read
  2217. :param inherited_field_names: list of column names from parent
  2218. models; some of those fields may not be read
  2219. """
  2220. if not self:
  2221. return
  2222. env = self.env
  2223. cr, user, context = env.args
  2224. # make a query object for selecting ids, and apply security rules to it
  2225. param_ids = object()
  2226. query = Query(['"%s"' % self._table], ['"%s".id IN %%s' % self._table], [param_ids])
  2227. self._apply_ir_rules(query, 'read')
  2228. # determine the fields that are stored as columns in tables; ignore 'id'
  2229. fields_pre = [
  2230. field
  2231. for field in (self._fields[name] for name in field_names + inherited_field_names)
  2232. if field.name != 'id'
  2233. if field.base_field.store and field.base_field.column_type
  2234. if not (field.inherited and callable(field.base_field.translate))
  2235. ]
  2236. # the query may involve several tables: we need fully-qualified names
  2237. def qualify(field):
  2238. col = field.name
  2239. res = self._inherits_join_calc(self._table, field.name, query)
  2240. if field.type == 'binary' and (context.get('bin_size') or context.get('bin_size_' + col)):
  2241. # PG 9.2 introduces conflicting pg_size_pretty(numeric) -> need ::cast
  2242. res = 'pg_size_pretty(length(%s)::bigint)' % res
  2243. return '%s as "%s"' % (res, col)
  2244. qual_names = [qualify(name) for name in [self._fields['id']] + fields_pre]
  2245. # determine the actual query to execute
  2246. from_clause, where_clause, params = query.get_sql()
  2247. query_str = "SELECT %s FROM %s WHERE %s" % (",".join(qual_names), from_clause, where_clause)
  2248. result = []
  2249. param_pos = params.index(param_ids)
  2250. for sub_ids in cr.split_for_in_conditions(self.ids):
  2251. params[param_pos] = tuple(sub_ids)
  2252. cr.execute(query_str, params)
  2253. result.extend(cr.dictfetchall())
  2254. ids = [vals['id'] for vals in result]
  2255. fetched = self.browse(ids)
  2256. if ids:
  2257. # translate the fields if necessary
  2258. if context.get('lang'):
  2259. for field in fields_pre:
  2260. if not field.inherited and callable(field.translate):
  2261. name = field.name
  2262. translate = field.get_trans_func(fetched)
  2263. for vals in result:
  2264. vals[name] = translate(vals['id'], vals[name])
  2265. # store result in cache
  2266. for vals in result:
  2267. record = self.browse(vals.pop('id'), self._prefetch)
  2268. record._cache.update(record._convert_to_cache(vals, validate=False))
  2269. # determine the fields that must be processed now;
  2270. # for the sake of simplicity, we ignore inherited fields
  2271. for name in field_names:
  2272. field = self._fields[name]
  2273. if not field.column_type:
  2274. field.read(fetched)
  2275. # Warn about deprecated fields now that fields_pre and fields_post are computed
  2276. for name in field_names:
  2277. field = self._fields[name]
  2278. if field.deprecated:
  2279. _logger.warning('Field %s is deprecated: %s', field, field.deprecated)
  2280. # store failed values in cache for the records that could not be read
  2281. missing = self - fetched
  2282. if missing:
  2283. extras = fetched - self
  2284. if extras:
  2285. raise AccessError(
  2286. _("Database fetch misses ids ({}) and has extra ids ({}), may be caused by a type incoherence in a previous request").format(
  2287. missing._ids, extras._ids,
  2288. ))
  2289. # mark non-existing records in missing
  2290. forbidden = missing.exists()
  2291. if forbidden:
  2292. _logger.info(
  2293. _('The requested operation cannot be completed due to record rules: Document type: %s, Operation: %s, Records: %s, User: %s') % \
  2294. (self._name, 'read', ','.join([str(r.id) for r in self][:6]), self._uid))
  2295. # store an access error exception in existing records
  2296. exc = AccessError(
  2297. _('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \
  2298. (self._name, 'read')
  2299. )
  2300. self.env.cache.set_failed(forbidden, self._fields.values(), exc)
  2301. @api.multi
  2302. def get_metadata(self):
  2303. """
  2304. Returns some metadata about the given records.
  2305. :return: list of ownership dictionaries for each requested record
  2306. :rtype: list of dictionaries with the following keys:
  2307. * id: object id
  2308. * create_uid: user who created the record
  2309. * create_date: date when the record was created
  2310. * write_uid: last user who changed the record
  2311. * write_date: date of the last change to the record
  2312. * xmlid: XML ID to use to refer to this record (if there is one), in format ``module.name``
  2313. * noupdate: A boolean telling if the record will be updated or not
  2314. """
  2315. fields = ['id']
  2316. if self._log_access:
  2317. fields += LOG_ACCESS_COLUMNS
  2318. quoted_table = '"%s"' % self._table
  2319. fields_str = ",".join('%s.%s' % (quoted_table, field) for field in fields)
  2320. query = '''SELECT %s, __imd.noupdate, __imd.module, __imd.name
  2321. FROM %s LEFT JOIN ir_model_data __imd
  2322. ON (__imd.model = %%s and __imd.res_id = %s.id)
  2323. WHERE %s.id IN %%s''' % (fields_str, quoted_table, quoted_table, quoted_table)
  2324. self._cr.execute(query, (self._name, tuple(self.ids)))
  2325. res = self._cr.dictfetchall()
  2326. uids = set(r[k] for r in res for k in ['write_uid', 'create_uid'] if r.get(k))
  2327. names = dict(self.env['res.users'].browse(uids).name_get())
  2328. for r in res:
  2329. for key in r:
  2330. value = r[key] = r[key] or False
  2331. if key in ('write_uid', 'create_uid') and value in names:
  2332. r[key] = (value, names[value])
  2333. r['xmlid'] = ("%(module)s.%(name)s" % r) if r['name'] else False
  2334. del r['name'], r['module']
  2335. return res
  2336. @api.multi
  2337. def _check_concurrency(self):
  2338. if not (self._log_access and self._context.get(self.CONCURRENCY_CHECK_FIELD)):
  2339. return
  2340. check_clause = "(id = %s AND %s < COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp)"
  2341. for sub_ids in self._cr.split_for_in_conditions(self.ids):
  2342. nclauses = 0
  2343. params = []
  2344. for id in sub_ids:
  2345. id_ref = "%s,%s" % (self._name, id)
  2346. update_date = self._context[self.CONCURRENCY_CHECK_FIELD].pop(id_ref, None)
  2347. if update_date:
  2348. nclauses += 1
  2349. params.extend([id, update_date])
  2350. if not nclauses:
  2351. continue
  2352. query = "SELECT id FROM %s WHERE %s" % (self._table, " OR ".join([check_clause] * nclauses))
  2353. self._cr.execute(query, tuple(params))
  2354. res = self._cr.fetchone()
  2355. if res:
  2356. # mention the first one only to keep the error message readable
  2357. raise ValidationError(_('A document was modified since you last viewed it (%s:%d)') % (self._description, res[0]))
  2358. @api.multi
  2359. def _check_record_rules_result_count(self, result_ids, operation):
  2360. """ Verify the returned rows after applying record rules matches the
  2361. length of ``self``, and raise an appropriate exception if it does not.
  2362. """
  2363. ids, result_ids = set(self.ids), set(result_ids)
  2364. missing_ids = ids - result_ids
  2365. if missing_ids:
  2366. # Attempt to distinguish record rule restriction vs deleted records,
  2367. # to provide a more specific error message
  2368. self._cr.execute('SELECT id FROM %s WHERE id IN %%s' % self._table, (tuple(missing_ids),))
  2369. forbidden_ids = [x[0] for x in self._cr.fetchall()]
  2370. if forbidden_ids:
  2371. # the missing ids are (at least partially) hidden by access rules
  2372. if self._uid == SUPERUSER_ID:
  2373. return
  2374. _logger.info('Access Denied by record rules for operation: %s on record ids: %r, uid: %s, model: %s', operation, forbidden_ids, self._uid, self._name)
  2375. raise AccessError(_('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \
  2376. (self._description, operation))
  2377. else:
  2378. # If we get here, the missing_ids are not in the database
  2379. if operation in ('read','unlink'):
  2380. # No need to warn about deleting an already deleted record.
  2381. # And no error when reading a record that was deleted, to prevent spurious
  2382. # errors for non-transactional search/read sequences coming from clients
  2383. return
  2384. _logger.info('Failed operation on deleted record(s): %s, uid: %s, model: %s', operation, self._uid, self._name)
  2385. raise MissingError(_('Missing document(s)') + ':' + _('One of the documents you are trying to access has been deleted, please try again after refreshing.'))
  2386. @api.model
  2387. def check_access_rights(self, operation, raise_exception=True):
  2388. """ Verifies that the operation given by ``operation`` is allowed for
  2389. the current user according to the access rights.
  2390. """
  2391. return self.env['ir.model.access'].check(self._name, operation, raise_exception)
  2392. @api.multi
  2393. def check_access_rule(self, operation):
  2394. """ Verifies that the operation given by ``operation`` is allowed for
  2395. the current user according to ir.rules.
  2396. :param operation: one of ``write``, ``unlink``
  2397. :raise UserError: * if current ir.rules do not permit this operation.
  2398. :return: None if the operation is allowed
  2399. """
  2400. if self._uid == SUPERUSER_ID:
  2401. return
  2402. if self.is_transient():
  2403. # Only one single implicit access rule for transient models: owner only!
  2404. # This is ok to hardcode because we assert that TransientModels always
  2405. # have log_access enabled so that the create_uid column is always there.
  2406. # And even with _inherits, these fields are always present in the local
  2407. # table too, so no need for JOINs.
  2408. query = "SELECT DISTINCT create_uid FROM %s WHERE id IN %%s" % self._table
  2409. self._cr.execute(query, (tuple(self.ids),))
  2410. uids = [x[0] for x in self._cr.fetchall()]
  2411. if len(uids) != 1 or uids[0] != self._uid:
  2412. raise AccessError(_('For this kind of document, you may only access records you created yourself.\n\n(Document type: %s)') % (self._description,))
  2413. else:
  2414. where_clause, where_params, tables = self.env['ir.rule'].domain_get(self._name, operation)
  2415. if where_clause:
  2416. query = "SELECT %s.id FROM %s WHERE %s.id IN %%s AND " % (self._table, ",".join(tables), self._table)
  2417. query = query + " AND ".join(where_clause)
  2418. for sub_ids in self._cr.split_for_in_conditions(self.ids):
  2419. self._cr.execute(query, [sub_ids] + where_params)
  2420. returned_ids = [x[0] for x in self._cr.fetchall()]
  2421. self.browse(sub_ids)._check_record_rules_result_count(returned_ids, operation)
  2422. @api.multi
  2423. def unlink(self):
  2424. """ unlink()
  2425. Deletes the records of the current set
  2426. :raise AccessError: * if user has no unlink rights on the requested object
  2427. * if user tries to bypass access rules for unlink on the requested object
  2428. :raise UserError: if the record is default property for other records
  2429. """
  2430. if not self:
  2431. return True
  2432. # for recomputing fields
  2433. self.modified(self._fields)
  2434. self._check_concurrency()
  2435. self.check_access_rights('unlink')
  2436. # Check if the records are used as default properties.
  2437. refs = ['%s,%s' % (self._name, i) for i in self.ids]
  2438. if self.env['ir.property'].search([('res_id', '=', False), ('value_reference', 'in', refs)]):
  2439. raise UserError(_('Unable to delete this document because it is used as a default property'))
  2440. # Delete the records' properties.
  2441. with self.env.norecompute():
  2442. self.env['ir.property'].search([('res_id', 'in', refs)]).unlink()
  2443. self.check_access_rule('unlink')
  2444. cr = self._cr
  2445. Data = self.env['ir.model.data'].sudo().with_context({})
  2446. Defaults = self.env['ir.default'].sudo()
  2447. Attachment = self.env['ir.attachment']
  2448. for sub_ids in cr.split_for_in_conditions(self.ids):
  2449. query = "DELETE FROM %s WHERE id IN %%s" % self._table
  2450. cr.execute(query, (sub_ids,))
  2451. # Removing the ir_model_data reference if the record being deleted
  2452. # is a record created by xml/csv file, as these are not connected
  2453. # with real database foreign keys, and would be dangling references.
  2454. #
  2455. # Note: the following steps are performed as superuser to avoid
  2456. # access rights restrictions, and with no context to avoid possible
  2457. # side-effects during admin calls.
  2458. data = Data.search([('model', '=', self._name), ('res_id', 'in', sub_ids)])
  2459. if data:
  2460. data.unlink()
  2461. # For the same reason, remove the defaults having some of the
  2462. # records as value
  2463. Defaults.discard_records(self.browse(sub_ids))
  2464. # For the same reason, remove the relevant records in ir_attachment
  2465. # (the search is performed with sql as the search method of
  2466. # ir_attachment is overridden to hide attachments of deleted
  2467. # records)
  2468. query = 'SELECT id FROM ir_attachment WHERE res_model=%s AND res_id IN %s'
  2469. cr.execute(query, (self._name, sub_ids))
  2470. attachments = Attachment.browse([row[0] for row in cr.fetchall()])
  2471. if attachments:
  2472. attachments.unlink()
  2473. # invalidate the *whole* cache, since the orm does not handle all
  2474. # changes made in the database, like cascading delete!
  2475. self.invalidate_cache()
  2476. # recompute new-style fields
  2477. if self.env.recompute and self._context.get('recompute', True):
  2478. self.recompute()
  2479. # auditing: deletions are infrequent and leave no trace in the database
  2480. _unlink.info('User #%s deleted %s records with IDs: %r', self._uid, self._name, self.ids)
  2481. return True
  2482. #
  2483. # TODO: Validate
  2484. #
  2485. @api.multi
  2486. def write(self, vals):
  2487. """ write(vals)
  2488. Updates all records in the current set with the provided values.
  2489. :param dict vals: fields to update and the value to set on them e.g::
  2490. {'foo': 1, 'bar': "Qux"}
  2491. will set the field ``foo`` to ``1`` and the field ``bar`` to
  2492. ``"Qux"`` if those are valid (otherwise it will trigger an error).
  2493. :raise AccessError: * if user has no write rights on the requested object
  2494. * if user tries to bypass access rules for write on the requested object
  2495. :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
  2496. :raise UserError: if a loop would be created in a hierarchy of objects a result of the operation (such as setting an object as its own parent)
  2497. * For numeric fields (:class:`~odoo.fields.Integer`,
  2498. :class:`~odoo.fields.Float`) the value should be of the
  2499. corresponding type
  2500. * For :class:`~odoo.fields.Boolean`, the value should be a
  2501. :class:`python:bool`
  2502. * For :class:`~odoo.fields.Selection`, the value should match the
  2503. selection values (generally :class:`python:str`, sometimes
  2504. :class:`python:int`)
  2505. * For :class:`~odoo.fields.Many2one`, the value should be the
  2506. database identifier of the record to set
  2507. * Other non-relational fields use a string for value
  2508. .. danger::
  2509. for historical and compatibility reasons,
  2510. :class:`~odoo.fields.Date` and
  2511. :class:`~odoo.fields.Datetime` fields use strings as values
  2512. (written and read) rather than :class:`~python:datetime.date` or
  2513. :class:`~python:datetime.datetime`. These date strings are
  2514. UTC-only and formatted according to
  2515. :const:`odoo.tools.misc.DEFAULT_SERVER_DATE_FORMAT` and
  2516. :const:`odoo.tools.misc.DEFAULT_SERVER_DATETIME_FORMAT`
  2517. * .. _openerp/models/relationals/format:
  2518. :class:`~odoo.fields.One2many` and
  2519. :class:`~odoo.fields.Many2many` use a special "commands" format to
  2520. manipulate the set of records stored in/associated with the field.
  2521. This format is a list of triplets executed sequentially, where each
  2522. triplet is a command to execute on the set of records. Not all
  2523. commands apply in all situations. Possible commands are:
  2524. ``(0, _, values)``
  2525. adds a new record created from the provided ``value`` dict.
  2526. ``(1, id, values)``
  2527. updates an existing record of id ``id`` with the values in
  2528. ``values``. Can not be used in :meth:`~.create`.
  2529. ``(2, id, _)``
  2530. removes the record of id ``id`` from the set, then deletes it
  2531. (from the database). Can not be used in :meth:`~.create`.
  2532. ``(3, id, _)``
  2533. removes the record of id ``id`` from the set, but does not
  2534. delete it. Can not be used on
  2535. :class:`~odoo.fields.One2many`. Can not be used in
  2536. :meth:`~.create`.
  2537. ``(4, id, _)``
  2538. adds an existing record of id ``id`` to the set. Can not be
  2539. used on :class:`~odoo.fields.One2many`.
  2540. ``(5, _, _)``
  2541. removes all records from the set, equivalent to using the
  2542. command ``3`` on every record explicitly. Can not be used on
  2543. :class:`~odoo.fields.One2many`. Can not be used in
  2544. :meth:`~.create`.
  2545. ``(6, _, ids)``
  2546. replaces all existing records in the set by the ``ids`` list,
  2547. equivalent to using the command ``5`` followed by a command
  2548. ``4`` for each ``id`` in ``ids``.
  2549. .. note:: Values marked as ``_`` in the list above are ignored and
  2550. can be anything, generally ``0`` or ``False``.
  2551. """
  2552. if not self:
  2553. return True
  2554. self._check_concurrency()
  2555. self.check_access_rights('write')
  2556. # No user-driven update of these columns
  2557. pop_fields = ['parent_left', 'parent_right']
  2558. if self._log_access:
  2559. pop_fields.extend(MAGIC_COLUMNS)
  2560. for field in pop_fields:
  2561. vals.pop(field, None)
  2562. # split up fields into old-style and pure new-style ones
  2563. old_vals, new_vals, unknown = {}, {}, []
  2564. for key, val in vals.items():
  2565. field = self._fields.get(key)
  2566. if field:
  2567. if field.store or field.inherited:
  2568. old_vals[key] = val
  2569. if field.inverse and not field.inherited:
  2570. new_vals[key] = val
  2571. else:
  2572. unknown.append(key)
  2573. if unknown:
  2574. _logger.warning("%s.write() with unknown fields: %s", self._name, ', '.join(sorted(unknown)))
  2575. protected_fields = [self._fields[n] for n in new_vals]
  2576. with self.env.protecting(protected_fields, self):
  2577. # write old-style fields with (low-level) method _write
  2578. if old_vals:
  2579. self._write(old_vals)
  2580. if new_vals:
  2581. self.modified(set(new_vals) - set(old_vals))
  2582. # put the values of fields into cache, and inverse them
  2583. for key in new_vals:
  2584. field = self._fields[key]
  2585. # If a field is not stored, its inverse method will probably
  2586. # write on its dependencies, which will invalidate the field
  2587. # on all records. We therefore inverse the field one record
  2588. # at a time.
  2589. batches = [self] if field.store else list(self)
  2590. for records in batches:
  2591. for record in records:
  2592. record._cache.update(
  2593. record._convert_to_cache(new_vals, update=True)
  2594. )
  2595. field.determine_inverse(records)
  2596. self.modified(set(new_vals) - set(old_vals))
  2597. # check Python constraints for inversed fields
  2598. self._validate_fields(set(new_vals) - set(old_vals))
  2599. # recompute new-style fields
  2600. if self.env.recompute and self._context.get('recompute', True):
  2601. self.recompute()
  2602. return True
  2603. @api.multi
  2604. def _write(self, vals):
  2605. # low-level implementation of write()
  2606. if not self:
  2607. return True
  2608. self.check_field_access_rights('write', list(vals))
  2609. cr = self._cr
  2610. # for recomputing new-style fields
  2611. extra_fields = ['write_date', 'write_uid'] if self._log_access else []
  2612. self.modified(list(vals) + extra_fields)
  2613. # for updating parent_left, parent_right
  2614. parents_changed = []
  2615. if self._parent_store and (self._parent_name in vals) and \
  2616. not self._context.get('defer_parent_store_computation'):
  2617. # The parent_left/right computation may take up to 5 seconds. No
  2618. # need to recompute the values if the parent is the same.
  2619. #
  2620. # Note: to respect parent_order, nodes must be processed in
  2621. # order, so ``parents_changed`` must be ordered properly.
  2622. parent_val = vals[self._parent_name]
  2623. if parent_val:
  2624. query = "SELECT id FROM %s WHERE id IN %%s AND (%s != %%s OR %s IS NULL) ORDER BY %s" % \
  2625. (self._table, self._parent_name, self._parent_name, self._parent_order)
  2626. cr.execute(query, (tuple(self.ids), parent_val))
  2627. else:
  2628. query = "SELECT id FROM %s WHERE id IN %%s AND (%s IS NOT NULL) ORDER BY %s" % \
  2629. (self._table, self._parent_name, self._parent_order)
  2630. cr.execute(query, (tuple(self.ids),))
  2631. parents_changed = [x[0] for x in cr.fetchall()]
  2632. updates = [] # list of (column, expr) or (column, pattern, value)
  2633. upd_todo = [] # list of column names to set explicitly
  2634. updend = [] # list of possibly inherited field names
  2635. direct = [] # list of direcly updated columns
  2636. has_trans = self.env.lang and self.env.lang != 'en_US'
  2637. single_lang = len(self.env['res.lang'].get_installed()) <= 1
  2638. for name, val in vals.items():
  2639. field = self._fields[name]
  2640. if field and field.deprecated:
  2641. _logger.warning('Field %s.%s is deprecated: %s', self._name, name, field.deprecated)
  2642. if field.store:
  2643. if hasattr(field, 'selection') and val:
  2644. self._check_selection_field_value(name, val)
  2645. if field.column_type:
  2646. if single_lang or not (has_trans and field.translate is True):
  2647. # val is not a translation: update the table
  2648. val = field.convert_to_column(val, self, vals)
  2649. updates.append((name, field.column_format, val))
  2650. direct.append(name)
  2651. else:
  2652. upd_todo.append(name)
  2653. else:
  2654. updend.append(name)
  2655. if self._log_access:
  2656. updates.append(('write_uid', '%s', self._uid))
  2657. updates.append(('write_date', "(now() at time zone 'UTC')"))
  2658. direct.append('write_uid')
  2659. direct.append('write_date')
  2660. if updates:
  2661. self.check_access_rule('write')
  2662. query = 'UPDATE "%s" SET %s WHERE id IN %%s' % (
  2663. self._table, ','.join('"%s"=%s' % (u[0], u[1]) for u in updates),
  2664. )
  2665. params = tuple(u[2] for u in updates if len(u) > 2)
  2666. for sub_ids in cr.split_for_in_conditions(set(self.ids)):
  2667. cr.execute(query, params + (sub_ids,))
  2668. if cr.rowcount != len(sub_ids):
  2669. raise MissingError(_('One of the records you are trying to modify has already been deleted (Document type: %s).') % self._description)
  2670. # TODO: optimize
  2671. for name in direct:
  2672. field = self._fields[name]
  2673. if callable(field.translate):
  2674. # The source value of a field has been modified,
  2675. # synchronize translated terms when possible.
  2676. self.env['ir.translation']._sync_terms_translations(self._fields[name], self)
  2677. elif has_trans and field.translate:
  2678. # The translated value of a field has been modified.
  2679. src_trans = self.read([name])[0][name]
  2680. if not src_trans:
  2681. # Insert value to DB
  2682. src_trans = vals[name]
  2683. self.with_context(lang=None).write({name: src_trans})
  2684. val = field.convert_to_column(vals[name], self, vals)
  2685. tname = "%s,%s" % (self._name, name)
  2686. self.env['ir.translation']._set_ids(
  2687. tname, 'model', self.env.lang, self.ids, val, src_trans)
  2688. # invalidate and mark new-style fields to recompute; do this before
  2689. # setting other fields, because it can require the value of computed
  2690. # fields, e.g., a one2many checking constraints on records
  2691. self.modified(direct)
  2692. # defaults in context must be removed when call a one2many or many2many
  2693. rel_context = {key: val
  2694. for key, val in self._context.items()
  2695. if not key.startswith('default_')}
  2696. # call the 'write' method of fields which are not columns
  2697. for name in upd_todo:
  2698. field = self._fields[name]
  2699. field.write(self.with_context(rel_context), vals[name])
  2700. # for recomputing new-style fields
  2701. self.modified(upd_todo)
  2702. # write inherited fields on the corresponding parent records
  2703. unknown_fields = set(updend)
  2704. for parent_model, parent_field in self._inherits.items():
  2705. parent_ids = []
  2706. for sub_ids in cr.split_for_in_conditions(self.ids):
  2707. query = "SELECT DISTINCT %s FROM %s WHERE id IN %%s" % (parent_field, self._table)
  2708. cr.execute(query, (sub_ids,))
  2709. parent_ids.extend([row[0] for row in cr.fetchall()])
  2710. parent_vals = {}
  2711. for name in updend:
  2712. field = self._fields[name]
  2713. if field.inherited and field.related[0] == parent_field:
  2714. parent_vals[name] = vals[name]
  2715. unknown_fields.discard(name)
  2716. if parent_vals:
  2717. self.env[parent_model].browse(parent_ids).write(parent_vals)
  2718. if unknown_fields:
  2719. _logger.warning('No such field(s) in model %s: %s.', self._name, ', '.join(unknown_fields))
  2720. # check Python constraints
  2721. self._validate_fields(vals)
  2722. # TODO: use _order to set dest at the right position and not first node of parent
  2723. # We can't defer parent_store computation because the stored function
  2724. # fields that are computer may refer (directly or indirectly) to
  2725. # parent_left/right (via a child_of domain)
  2726. if parents_changed:
  2727. if self.pool._init:
  2728. self.pool._init_parent[self._name] = True
  2729. else:
  2730. parent_val = vals[self._parent_name]
  2731. if parent_val:
  2732. clause, params = '%s=%%s' % self._parent_name, (parent_val,)
  2733. else:
  2734. clause, params = '%s IS NULL' % self._parent_name, ()
  2735. for id in parents_changed:
  2736. # determine old parent_left, parent_right of current record
  2737. cr.execute('SELECT parent_left, parent_right FROM %s WHERE id=%%s' % self._table, (id,))
  2738. pleft0, pright0 = cr.fetchone()
  2739. width = pright0 - pleft0 + 1
  2740. # determine new parent_left of current record; it comes
  2741. # right after the parent_right of its closest left sibling
  2742. # (this CANNOT be fetched outside the loop, as it needs to
  2743. # be refreshed after each update, in case several nodes are
  2744. # sequentially inserted one next to the other)
  2745. pleft1 = None
  2746. cr.execute('SELECT id, parent_right FROM %s WHERE %s ORDER BY %s' % \
  2747. (self._table, clause, self._parent_order), params)
  2748. for (sibling_id, sibling_parent_right) in cr.fetchall():
  2749. if sibling_id == id:
  2750. break
  2751. pleft1 = (sibling_parent_right or 0) + 1
  2752. if not pleft1:
  2753. # the current record is the first node of the parent
  2754. if not parent_val:
  2755. pleft1 = 0 # the first node starts at 0
  2756. else:
  2757. cr.execute('SELECT parent_left FROM %s WHERE id=%%s' % self._table, (parent_val,))
  2758. pleft1 = cr.fetchone()[0] + 1
  2759. if pleft0 < pleft1 <= pright0:
  2760. raise UserError(_('Recursivity Detected.'))
  2761. # make some room for parent_left and parent_right at the new position
  2762. cr.execute('UPDATE %s SET parent_left=parent_left+%%s WHERE %%s<=parent_left' % self._table, (width, pleft1))
  2763. cr.execute('UPDATE %s SET parent_right=parent_right+%%s WHERE %%s<=parent_right' % self._table, (width, pleft1))
  2764. # slide the subtree of the current record to its new position
  2765. if pleft0 < pleft1:
  2766. cr.execute('''UPDATE %s SET parent_left=parent_left+%%s, parent_right=parent_right+%%s
  2767. WHERE %%s<=parent_left AND parent_left<%%s''' % self._table,
  2768. (pleft1 - pleft0, pleft1 - pleft0, pleft0, pright0))
  2769. else:
  2770. cr.execute('''UPDATE %s SET parent_left=parent_left-%%s, parent_right=parent_right-%%s
  2771. WHERE %%s<=parent_left AND parent_left<%%s''' % self._table,
  2772. (pleft0 - pleft1 + width, pleft0 - pleft1 + width, pleft0 + width, pright0 + width))
  2773. self.invalidate_cache(['parent_left', 'parent_right'])
  2774. # recompute new-style fields
  2775. if self.env.recompute and self._context.get('recompute', True):
  2776. self.recompute()
  2777. return True
  2778. #
  2779. # TODO: Should set perm to user.xxx
  2780. #
  2781. @api.model
  2782. @api.returns('self', lambda value: value.id)
  2783. def create(self, vals):
  2784. """ create(vals) -> record
  2785. Creates a new record for the model.
  2786. The new record is initialized using the values from ``vals`` and
  2787. if necessary those from :meth:`~.default_get`.
  2788. :param dict vals:
  2789. values for the model's fields, as a dictionary::
  2790. {'field_name': field_value, ...}
  2791. see :meth:`~.write` for details
  2792. :return: new record created
  2793. :raise AccessError: * if user has no create rights on the requested object
  2794. * if user tries to bypass access rules for create on the requested object
  2795. :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
  2796. :raise UserError: if a loop would be created in a hierarchy of objects a result of the operation (such as setting an object as its own parent)
  2797. """
  2798. self.check_access_rights('create')
  2799. # add missing defaults, and drop fields that may not be set by user
  2800. vals = self._add_missing_default_values(vals)
  2801. pop_fields = ['parent_left', 'parent_right']
  2802. if self._log_access:
  2803. pop_fields.extend(MAGIC_COLUMNS)
  2804. for field in pop_fields:
  2805. vals.pop(field, None)
  2806. # split up fields into old-style and pure new-style ones
  2807. old_vals, new_vals, unknown = {}, {}, []
  2808. for key, val in vals.items():
  2809. field = self._fields.get(key)
  2810. if field:
  2811. if field.store or field.inherited:
  2812. old_vals[key] = val
  2813. if field.inverse and not field.inherited:
  2814. new_vals[key] = val
  2815. else:
  2816. unknown.append(key)
  2817. if unknown:
  2818. _logger.warning("%s.create() includes unknown fields: %s", self._name, ', '.join(sorted(unknown)))
  2819. # create record with old-style fields
  2820. record = self.browse(self._create(old_vals))
  2821. protected_fields = [self._fields[n] for n in new_vals]
  2822. with self.env.protecting(protected_fields, record):
  2823. # put the values of pure new-style fields into cache, and inverse them
  2824. record.modified(set(new_vals) - set(old_vals))
  2825. record._cache.update(record._convert_to_cache(new_vals))
  2826. for key in new_vals:
  2827. self._fields[key].determine_inverse(record)
  2828. record.modified(set(new_vals) - set(old_vals))
  2829. # check Python constraints for inversed fields
  2830. record._validate_fields(set(new_vals) - set(old_vals))
  2831. # recompute new-style fields
  2832. if self.env.recompute and self._context.get('recompute', True):
  2833. self.recompute()
  2834. return record
  2835. @api.model
  2836. def _create(self, vals):
  2837. # data of parent records to create or update, by model
  2838. tocreate = {
  2839. parent_model: {'id': vals.pop(parent_field, None)}
  2840. for parent_model, parent_field in self._inherits.items()
  2841. }
  2842. # list of column assignments defined as tuples like:
  2843. # (column_name, format_string, column_value)
  2844. # (column_name, sql_formula)
  2845. # Those tuples will be used by the string formatting for the INSERT
  2846. # statement below.
  2847. updates = [
  2848. ('id', "nextval('%s')" % self._sequence),
  2849. ]
  2850. upd_todo = []
  2851. unknown_fields = []
  2852. protected_fields = []
  2853. for name, val in list(vals.items()):
  2854. field = self._fields.get(name)
  2855. if not field:
  2856. unknown_fields.append(name)
  2857. del vals[name]
  2858. elif field.inherited:
  2859. tocreate[field.related_field.model_name][name] = val
  2860. del vals[name]
  2861. elif not field.store:
  2862. del vals[name]
  2863. elif field.inverse:
  2864. protected_fields.append(field)
  2865. if unknown_fields:
  2866. _logger.warning('No such field(s) in model %s: %s.', self._name, ', '.join(unknown_fields))
  2867. # create or update parent records
  2868. for parent_model, parent_vals in tocreate.items():
  2869. parent_id = parent_vals.pop('id')
  2870. if not parent_id:
  2871. parent_id = self.env[parent_model].create(parent_vals).id
  2872. else:
  2873. self.env[parent_model].browse(parent_id).write(parent_vals)
  2874. vals[self._inherits[parent_model]] = parent_id
  2875. # set boolean fields to False by default (to make search more powerful)
  2876. for name, field in self._fields.items():
  2877. if field.type == 'boolean' and field.store and name not in vals:
  2878. vals[name] = False
  2879. # determine SQL values
  2880. self = self.browse()
  2881. for name, val in vals.items():
  2882. field = self._fields[name]
  2883. if field.store and field.column_type:
  2884. column_val = field.convert_to_column(val, self, vals)
  2885. updates.append((name, field.column_format, column_val))
  2886. else:
  2887. upd_todo.append(name)
  2888. if hasattr(field, 'selection') and val:
  2889. self._check_selection_field_value(name, val)
  2890. if self._log_access:
  2891. updates.append(('create_uid', '%s', self._uid))
  2892. updates.append(('write_uid', '%s', self._uid))
  2893. updates.append(('create_date', "(now() at time zone 'UTC')"))
  2894. updates.append(('write_date', "(now() at time zone 'UTC')"))
  2895. # insert a row for this record
  2896. cr = self._cr
  2897. query = """INSERT INTO "%s" (%s) VALUES(%s) RETURNING id""" % (
  2898. self._table,
  2899. ', '.join('"%s"' % u[0] for u in updates),
  2900. ', '.join(u[1] for u in updates),
  2901. )
  2902. cr.execute(query, tuple(u[2] for u in updates if len(u) > 2))
  2903. # from now on, self is the new record
  2904. id_new, = cr.fetchone()
  2905. self = self.browse(id_new)
  2906. if self._parent_store and not self._context.get('defer_parent_store_computation'):
  2907. if self.pool._init:
  2908. self.pool._init_parent[self._name] = True
  2909. else:
  2910. parent_val = vals.get(self._parent_name)
  2911. if parent_val:
  2912. # determine parent_left: it comes right after the
  2913. # parent_right of its closest left sibling
  2914. pleft = None
  2915. cr.execute("SELECT parent_right FROM %s WHERE %s=%%s ORDER BY %s" % \
  2916. (self._table, self._parent_name, self._parent_order),
  2917. (parent_val,))
  2918. for (pright,) in cr.fetchall():
  2919. if not pright:
  2920. break
  2921. pleft = pright + 1
  2922. if not pleft:
  2923. # this is the leftmost child of its parent
  2924. cr.execute("SELECT parent_left FROM %s WHERE id=%%s" % self._table, (parent_val,))
  2925. pleft = cr.fetchone()[0] + 1
  2926. else:
  2927. # determine parent_left: it comes after all top-level parent_right
  2928. cr.execute("SELECT MAX(parent_right) FROM %s" % self._table)
  2929. pleft = (cr.fetchone()[0] or 0) + 1
  2930. # make some room for the new node, and insert it in the MPTT
  2931. cr.execute("UPDATE %s SET parent_left=parent_left+2 WHERE parent_left>=%%s" % self._table,
  2932. (pleft,))
  2933. cr.execute("UPDATE %s SET parent_right=parent_right+2 WHERE parent_right>=%%s" % self._table,
  2934. (pleft,))
  2935. cr.execute("UPDATE %s SET parent_left=%%s, parent_right=%%s WHERE id=%%s" % self._table,
  2936. (pleft, pleft + 1, id_new))
  2937. self.invalidate_cache(['parent_left', 'parent_right'])
  2938. with self.env.protecting(protected_fields, self):
  2939. # invalidate and mark new-style fields to recompute; do this before
  2940. # setting other fields, because it can require the value of computed
  2941. # fields, e.g., a one2many checking constraints on records
  2942. self.modified(self._fields)
  2943. # defaults in context must be removed when call a one2many or many2many
  2944. rel_context = {key: val
  2945. for key, val in self._context.items()
  2946. if not key.startswith('default_')}
  2947. # call the 'write' method of fields which are not columns
  2948. for name in sorted(upd_todo, key=lambda name: self._fields[name]._sequence):
  2949. field = self._fields[name]
  2950. field.write(self.with_context(rel_context), vals[name], create=True)
  2951. # for recomputing new-style fields
  2952. self.modified(upd_todo)
  2953. # check Python constraints
  2954. self._validate_fields(vals)
  2955. if self.env.recompute and self._context.get('recompute', True):
  2956. # recompute new-style fields
  2957. self.recompute()
  2958. self.check_access_rule('create')
  2959. if self.env.lang and self.env.lang != 'en_US':
  2960. # add translations for self.env.lang
  2961. for name, val in vals.items():
  2962. field = self._fields[name]
  2963. if field.store and field.column_type and field.translate is True:
  2964. tname = "%s,%s" % (self._name, name)
  2965. self.env['ir.translation']._set_ids(tname, 'model', self.env.lang, self.ids, val, val)
  2966. return id_new
  2967. # TODO: ameliorer avec NULL
  2968. @api.model
  2969. def _where_calc(self, domain, active_test=True):
  2970. """Computes the WHERE clause needed to implement an OpenERP domain.
  2971. :param domain: the domain to compute
  2972. :type domain: list
  2973. :param active_test: whether the default filtering of records with ``active``
  2974. field set to ``False`` should be applied.
  2975. :return: the query expressing the given domain as provided in domain
  2976. :rtype: osv.query.Query
  2977. """
  2978. # if the object has a field named 'active', filter out all inactive
  2979. # records unless they were explicitely asked for
  2980. if 'active' in self._fields and active_test and self._context.get('active_test', True):
  2981. # the item[0] trick below works for domain items and '&'/'|'/'!'
  2982. # operators too
  2983. if not any(item[0] == 'active' for item in domain):
  2984. domain = [('active', '=', 1)] + domain
  2985. if domain:
  2986. e = expression.expression(domain, self)
  2987. tables = e.get_tables()
  2988. where_clause, where_params = e.to_sql()
  2989. where_clause = [where_clause] if where_clause else []
  2990. else:
  2991. where_clause, where_params, tables = [], [], ['"%s"' % self._table]
  2992. return Query(tables, where_clause, where_params)
  2993. def _check_qorder(self, word):
  2994. if not regex_order.match(word):
  2995. raise UserError(_('Invalid "order" specified. A valid "order" specification is a comma-separated list of valid field names (optionally followed by asc/desc for the direction)'))
  2996. return True
  2997. @api.model
  2998. def _apply_ir_rules(self, query, mode='read'):
  2999. """Add what's missing in ``query`` to implement all appropriate ir.rules
  3000. (using the ``model_name``'s rules or the current model's rules if ``model_name`` is None)
  3001. :param query: the current query object
  3002. """
  3003. if self._uid == SUPERUSER_ID:
  3004. return
  3005. def apply_rule(clauses, params, tables, parent_model=None):
  3006. """ :param parent_model: name of the parent model, if the added
  3007. clause comes from a parent model
  3008. """
  3009. if clauses:
  3010. if parent_model:
  3011. # as inherited rules are being applied, we need to add the
  3012. # missing JOIN to reach the parent table (if not JOINed yet)
  3013. parent_table = '"%s"' % self.env[parent_model]._table
  3014. parent_alias = '"%s"' % self._inherits_join_add(self, parent_model, query)
  3015. # inherited rules are applied on the external table, replace
  3016. # parent_table by parent_alias
  3017. clauses = [clause.replace(parent_table, parent_alias) for clause in clauses]
  3018. # replace parent_table by parent_alias, and introduce
  3019. # parent_alias if needed
  3020. tables = [
  3021. (parent_table + ' as ' + parent_alias) if table == parent_table \
  3022. else table.replace(parent_table, parent_alias)
  3023. for table in tables
  3024. ]
  3025. query.where_clause += clauses
  3026. query.where_clause_params += params
  3027. for table in tables:
  3028. if table not in query.tables:
  3029. query.tables.append(table)
  3030. # apply main rules on the object
  3031. Rule = self.env['ir.rule']
  3032. where_clause, where_params, tables = Rule.domain_get(self._name, mode)
  3033. apply_rule(where_clause, where_params, tables)
  3034. # apply ir.rules from the parents (through _inherits)
  3035. for parent_model in self._inherits:
  3036. where_clause, where_params, tables = Rule.domain_get(parent_model, mode)
  3037. apply_rule(where_clause, where_params, tables, parent_model)
  3038. @api.model
  3039. def _generate_translated_field(self, table_alias, field, query):
  3040. """
  3041. Add possibly missing JOIN with translations table to ``query`` and
  3042. generate the expression for the translated field.
  3043. :return: the qualified field name (or expression) to use for ``field``
  3044. """
  3045. if self.env.lang:
  3046. # Sub-select to return at most one translation per record.
  3047. # Even if it shoud probably not be the case,
  3048. # this is possible to have multiple translations for a same record in the same language.
  3049. # The parenthesis surrounding the select are important, as this is a sub-select.
  3050. # The quotes surrounding `ir_translation` are important as well.
  3051. unique_translation_subselect = """
  3052. (SELECT DISTINCT ON (res_id) res_id, value
  3053. FROM "ir_translation"
  3054. WHERE name=%s AND lang=%s AND value!=%s
  3055. ORDER BY res_id, id DESC)
  3056. """
  3057. alias, alias_statement = query.add_join(
  3058. (table_alias, unique_translation_subselect, 'id', 'res_id', field),
  3059. implicit=False,
  3060. outer=True,
  3061. extra_params=["%s,%s" % (self._name, field), self.env.lang, ""],
  3062. )
  3063. return 'COALESCE("%s"."%s", "%s"."%s")' % (alias, 'value', table_alias, field)
  3064. else:
  3065. return '"%s"."%s"' % (table_alias, field)
  3066. @api.model
  3067. def _generate_m2o_order_by(self, alias, order_field, query, reverse_direction, seen):
  3068. """
  3069. Add possibly missing JOIN to ``query`` and generate the ORDER BY clause for m2o fields,
  3070. either native m2o fields or function/related fields that are stored, including
  3071. intermediate JOINs for inheritance if required.
  3072. :return: the qualified field name to use in an ORDER BY clause to sort by ``order_field``
  3073. """
  3074. field = self._fields[order_field]
  3075. if field.inherited:
  3076. # also add missing joins for reaching the table containing the m2o field
  3077. qualified_field = self._inherits_join_calc(alias, order_field, query)
  3078. alias, order_field = qualified_field.replace('"', '').split('.', 1)
  3079. field = field.base_field
  3080. assert field.type == 'many2one', 'Invalid field passed to _generate_m2o_order_by()'
  3081. if not field.store:
  3082. _logger.debug("Many2one function/related fields must be stored "
  3083. "to be used as ordering fields! Ignoring sorting for %s.%s",
  3084. self._name, order_field)
  3085. return []
  3086. # figure out the applicable order_by for the m2o
  3087. dest_model = self.env[field.comodel_name]
  3088. m2o_order = dest_model._order
  3089. if not regex_order.match(m2o_order):
  3090. # _order is complex, can't use it here, so we default to _rec_name
  3091. m2o_order = dest_model._rec_name
  3092. # Join the dest m2o table if it's not joined yet. We use [LEFT] OUTER join here
  3093. # as we don't want to exclude results that have NULL values for the m2o
  3094. join = (alias, dest_model._table, order_field, 'id', order_field)
  3095. dest_alias, _ = query.add_join(join, implicit=False, outer=True)
  3096. return dest_model._generate_order_by_inner(dest_alias, m2o_order, query,
  3097. reverse_direction, seen)
  3098. @api.model
  3099. def _generate_order_by_inner(self, alias, order_spec, query, reverse_direction=False, seen=None):
  3100. if seen is None:
  3101. seen = set()
  3102. self._check_qorder(order_spec)
  3103. order_by_elements = []
  3104. for order_part in order_spec.split(','):
  3105. order_split = order_part.strip().split(' ')
  3106. order_field = order_split[0].strip()
  3107. order_direction = order_split[1].strip().upper() if len(order_split) == 2 else ''
  3108. if reverse_direction:
  3109. order_direction = 'ASC' if order_direction == 'DESC' else 'DESC'
  3110. do_reverse = order_direction == 'DESC'
  3111. field = self._fields.get(order_field)
  3112. if not field:
  3113. raise ValueError(_("Sorting field %s not found on model %s") % (order_field, self._name))
  3114. if order_field == 'id':
  3115. order_by_elements.append('"%s"."%s" %s' % (alias, order_field, order_direction))
  3116. else:
  3117. if field.inherited:
  3118. field = field.base_field
  3119. if field.store and field.type == 'many2one':
  3120. key = (field.model_name, field.comodel_name, order_field)
  3121. if key not in seen:
  3122. seen.add(key)
  3123. order_by_elements += self._generate_m2o_order_by(alias, order_field, query, do_reverse, seen)
  3124. elif field.store and field.column_type:
  3125. qualifield_name = self._inherits_join_calc(alias, order_field, query, implicit=False, outer=True)
  3126. if field.type == 'boolean':
  3127. qualifield_name = "COALESCE(%s, false)" % qualifield_name
  3128. order_by_elements.append("%s %s" % (qualifield_name, order_direction))
  3129. else:
  3130. continue # ignore non-readable or "non-joinable" fields
  3131. return order_by_elements
  3132. @api.model
  3133. def _generate_order_by(self, order_spec, query):
  3134. """
  3135. Attempt to construct an appropriate ORDER BY clause based on order_spec, which must be
  3136. a comma-separated list of valid field names, optionally followed by an ASC or DESC direction.
  3137. :raise ValueError in case order_spec is malformed
  3138. """
  3139. order_by_clause = ''
  3140. order_spec = order_spec or self._order
  3141. if order_spec:
  3142. order_by_elements = self._generate_order_by_inner(self._table, order_spec, query)
  3143. if order_by_elements:
  3144. order_by_clause = ",".join(order_by_elements)
  3145. return order_by_clause and (' ORDER BY %s ' % order_by_clause) or ''
  3146. @api.model
  3147. def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None):
  3148. """
  3149. Private implementation of search() method, allowing specifying the uid to use for the access right check.
  3150. This is useful for example when filling in the selection list for a drop-down and avoiding access rights errors,
  3151. by specifying ``access_rights_uid=1`` to bypass access rights check, but not ir.rules!
  3152. This is ok at the security level because this method is private and not callable through XML-RPC.
  3153. :param access_rights_uid: optional user ID to use when checking access rights
  3154. (not for ir.rules, this is only for ir.model.access)
  3155. :return: a list of record ids or an integer (if count is True)
  3156. """
  3157. self.sudo(access_rights_uid or self._uid).check_access_rights('read')
  3158. # For transient models, restrict access to the current user, except for the super-user
  3159. if self.is_transient() and self._log_access and self._uid != SUPERUSER_ID:
  3160. args = expression.AND(([('create_uid', '=', self._uid)], args or []))
  3161. if expression.is_false(self, args):
  3162. # optimization: no need to query, as no record satisfies the domain
  3163. return 0 if count else []
  3164. query = self._where_calc(args)
  3165. self._apply_ir_rules(query, 'read')
  3166. order_by = self._generate_order_by(order, query)
  3167. from_clause, where_clause, where_clause_params = query.get_sql()
  3168. where_str = where_clause and (" WHERE %s" % where_clause) or ''
  3169. if count:
  3170. # Ignore order, limit and offset when just counting, they don't make sense and could
  3171. # hurt performance
  3172. query_str = 'SELECT count(1) FROM ' + from_clause + where_str
  3173. self._cr.execute(query_str, where_clause_params)
  3174. res = self._cr.fetchone()
  3175. return res[0]
  3176. limit_str = limit and ' limit %d' % limit or ''
  3177. offset_str = offset and ' offset %d' % offset or ''
  3178. query_str = 'SELECT "%s".id FROM ' % self._table + from_clause + where_str + order_by + limit_str + offset_str
  3179. self._cr.execute(query_str, where_clause_params)
  3180. res = self._cr.fetchall()
  3181. # TDE note: with auto_join, we could have several lines about the same result
  3182. # i.e. a lead with several unread messages; we uniquify the result using
  3183. # a fast way to do it while preserving order (http://www.peterbe.com/plog/uniqifiers-benchmark)
  3184. def _uniquify_list(seq):
  3185. seen = set()
  3186. return [x for x in seq if x not in seen and not seen.add(x)]
  3187. return _uniquify_list([x[0] for x in res])
  3188. @api.multi
  3189. @api.returns(None, lambda value: value[0])
  3190. def copy_data(self, default=None):
  3191. """
  3192. Copy given record's data with all its fields values
  3193. :param default: field values to override in the original values of the copied record
  3194. :return: list with a dictionary containing all the field values
  3195. """
  3196. # In the old API, this method took a single id and return a dict. When
  3197. # invoked with the new API, it returned a list of dicts.
  3198. self.ensure_one()
  3199. # avoid recursion through already copied records in case of circular relationship
  3200. if '__copy_data_seen' not in self._context:
  3201. self = self.with_context(__copy_data_seen=defaultdict(set))
  3202. seen_map = self._context['__copy_data_seen']
  3203. if self.id in seen_map[self._name]:
  3204. return
  3205. seen_map[self._name].add(self.id)
  3206. default = dict(default or [])
  3207. if 'state' not in default and 'state' in self._fields:
  3208. field = self._fields['state']
  3209. if field.default:
  3210. value = field.default(self)
  3211. value = field.convert_to_cache(value, self)
  3212. value = field.convert_to_record(value, self)
  3213. value = field.convert_to_write(value, self)
  3214. default['state'] = value
  3215. # build a black list of fields that should not be copied
  3216. blacklist = set(MAGIC_COLUMNS + ['parent_left', 'parent_right'])
  3217. whitelist = set(name for name, field in self._fields.items() if not field.inherited)
  3218. def blacklist_given_fields(model):
  3219. # blacklist the fields that are given by inheritance
  3220. for parent_model, parent_field in model._inherits.items():
  3221. blacklist.add(parent_field)
  3222. if parent_field in default:
  3223. # all the fields of 'parent_model' are given by the record:
  3224. # default[parent_field], except the ones redefined in self
  3225. blacklist.update(set(self.env[parent_model]._fields) - whitelist)
  3226. else:
  3227. blacklist_given_fields(self.env[parent_model])
  3228. # blacklist deprecated fields
  3229. for name, field in model._fields.items():
  3230. if field.deprecated:
  3231. blacklist.add(name)
  3232. blacklist_given_fields(self)
  3233. fields_to_copy = {name: field
  3234. for name, field in self._fields.items()
  3235. if field.copy and name not in default and name not in blacklist}
  3236. for name, field in fields_to_copy.items():
  3237. if field.type == 'one2many':
  3238. # duplicate following the order of the ids because we'll rely on
  3239. # it later for copying translations in copy_translation()!
  3240. lines = [rec.copy_data()[0] for rec in self[name].sorted(key='id')]
  3241. # the lines are duplicated using the wrong (old) parent, but then
  3242. # are reassigned to the correct one thanks to the (0, 0, ...)
  3243. default[name] = [(0, 0, line) for line in lines if line]
  3244. elif field.type == 'many2many':
  3245. default[name] = [(6, 0, self[name].ids)]
  3246. else:
  3247. default[name] = field.convert_to_write(self[name], self)
  3248. return [default]
  3249. @api.multi
  3250. def copy_translations(old, new):
  3251. # avoid recursion through already copied records in case of circular relationship
  3252. if '__copy_translations_seen' not in old._context:
  3253. old = old.with_context(__copy_translations_seen=defaultdict(set))
  3254. seen_map = old._context['__copy_translations_seen']
  3255. if old.id in seen_map[old._name]:
  3256. return
  3257. seen_map[old._name].add(old.id)
  3258. def get_trans(field, old, new):
  3259. """ Return the 'name' of the translations to search for, together
  3260. with the record ids corresponding to ``old`` and ``new``.
  3261. """
  3262. if field.inherited:
  3263. pname = field.related[0]
  3264. return get_trans(field.related_field, old[pname], new[pname])
  3265. return "%s,%s" % (field.model_name, field.name), old.id, new.id
  3266. # removing the lang to compare untranslated values
  3267. old_wo_lang, new_wo_lang = (old + new).with_context(lang=None)
  3268. Translation = old.env['ir.translation']
  3269. for name, field in old._fields.items():
  3270. if not field.copy:
  3271. continue
  3272. if field.type == 'one2many':
  3273. # we must recursively copy the translations for o2m; here we
  3274. # rely on the order of the ids to match the translations as
  3275. # foreseen in copy_data()
  3276. old_lines = old[name].sorted(key='id')
  3277. new_lines = new[name].sorted(key='id')
  3278. for (old_line, new_line) in pycompat.izip(old_lines, new_lines):
  3279. old_line.copy_translations(new_line)
  3280. elif field.translate:
  3281. # for translatable fields we copy their translations
  3282. trans_name, source_id, target_id = get_trans(field, old, new)
  3283. domain = [('name', '=', trans_name), ('res_id', '=', source_id)]
  3284. new_val = new_wo_lang[name]
  3285. if old.env.lang and callable(field.translate):
  3286. # the new value *without lang* must be the old value without lang
  3287. new_wo_lang[name] = old_wo_lang[name]
  3288. for vals in Translation.search_read(domain):
  3289. del vals['id']
  3290. del vals['source'] # remove source to avoid triggering _set_src
  3291. del vals['module'] # duplicated vals is not linked to any module
  3292. vals['res_id'] = target_id
  3293. if vals['lang'] == old.env.lang and field.translate is True:
  3294. # force a source if the new_val was not changed by copy override
  3295. if new_val == old[name]:
  3296. vals['source'] = old_wo_lang[name]
  3297. # the value should be the new value (given by copy())
  3298. vals['value'] = new_val
  3299. Translation.create(vals)
  3300. @api.multi
  3301. @api.returns('self', lambda value: value.id)
  3302. def copy(self, default=None):
  3303. """ copy(default=None)
  3304. Duplicate record ``self`` updating it with default values
  3305. :param dict default: dictionary of field values to override in the
  3306. original values of the copied record, e.g: ``{'field_name': overridden_value, ...}``
  3307. :returns: new record
  3308. """
  3309. self.ensure_one()
  3310. vals = self.copy_data(default)[0]
  3311. # To avoid to create a translation in the lang of the user, copy_translation will do it
  3312. new = self.with_context(lang=None).create(vals)
  3313. self.copy_translations(new)
  3314. return new
  3315. @api.multi
  3316. @api.returns('self')
  3317. def exists(self):
  3318. """ exists() -> records
  3319. Returns the subset of records in ``self`` that exist, and marks deleted
  3320. records as such in cache. It can be used as a test on records::
  3321. if record.exists():
  3322. ...
  3323. By convention, new records are returned as existing.
  3324. """
  3325. ids, new_ids = [], []
  3326. for i in self._ids:
  3327. (ids if isinstance(i, pycompat.integer_types) else new_ids).append(i)
  3328. if not ids:
  3329. return self
  3330. query = """SELECT id FROM "%s" WHERE id IN %%s""" % self._table
  3331. self._cr.execute(query, [tuple(ids)])
  3332. ids = [r[0] for r in self._cr.fetchall()]
  3333. existing = self.browse(ids + new_ids)
  3334. if len(existing) < len(self):
  3335. # mark missing records in cache with a failed value
  3336. exc = MissingError(_("Record does not exist or has been deleted."))
  3337. self.env.cache.set_failed(self - existing, self._fields.values(), exc)
  3338. return existing
  3339. @api.multi
  3340. def _check_recursion(self, parent=None):
  3341. """
  3342. Verifies that there is no loop in a hierarchical structure of records,
  3343. by following the parent relationship using the **parent** field until a
  3344. loop is detected or until a top-level record is found.
  3345. :param parent: optional parent field name (default: ``self._parent_name``)
  3346. :return: **True** if no loop was found, **False** otherwise.
  3347. """
  3348. if not parent:
  3349. parent = self._parent_name
  3350. # must ignore 'active' flag, ir.rules, etc. => direct SQL query
  3351. cr = self._cr
  3352. query = 'SELECT "%s" FROM "%s" WHERE id = %%s' % (parent, self._table)
  3353. for id in self.ids:
  3354. current_id = id
  3355. while current_id:
  3356. cr.execute(query, (current_id,))
  3357. result = cr.fetchone()
  3358. current_id = result[0] if result else None
  3359. if current_id == id:
  3360. return False
  3361. return True
  3362. @api.multi
  3363. def _check_m2m_recursion(self, field_name):
  3364. """
  3365. Verifies that there is no loop in a directed graph of records, by
  3366. following a many2many relationship with the given field name.
  3367. :param field_name: field to check
  3368. :return: **True** if no loop was found, **False** otherwise.
  3369. """
  3370. field = self._fields.get(field_name)
  3371. if not (field and field.type == 'many2many' and
  3372. field.comodel_name == self._name and field.store):
  3373. # field must be a many2many on itself
  3374. raise ValueError('invalid field_name: %r' % (field_name,))
  3375. cr = self._cr
  3376. query = 'SELECT "%s", "%s" FROM "%s" WHERE "%s" IN %%s AND "%s" IS NOT NULL' % \
  3377. (field.column1, field.column2, field.relation, field.column1, field.column2)
  3378. succs = defaultdict(set) # transitive closure of successors
  3379. preds = defaultdict(set) # transitive closure of predecessors
  3380. todo, done = set(self.ids), set()
  3381. while todo:
  3382. # retrieve the respective successors of the nodes in 'todo'
  3383. cr.execute(query, [tuple(todo)])
  3384. done.update(todo)
  3385. todo.clear()
  3386. for id1, id2 in cr.fetchall():
  3387. # connect id1 and its predecessors to id2 and its successors
  3388. for x, y in itertools.product([id1] + list(preds[id1]),
  3389. [id2] + list(succs[id2])):
  3390. if x == y:
  3391. return False # we found a cycle here!
  3392. succs[x].add(y)
  3393. preds[y].add(x)
  3394. if id2 not in done:
  3395. todo.add(id2)
  3396. return True
  3397. @api.multi
  3398. def _get_external_ids(self):
  3399. """Retrieve the External ID(s) of any database record.
  3400. **Synopsis**: ``_get_xml_ids() -> { 'id': ['module.xml_id'] }``
  3401. :return: map of ids to the list of their fully qualified External IDs
  3402. in the form ``module.key``, or an empty list when there's no External
  3403. ID for a record, e.g.::
  3404. { 'id': ['module.ext_id', 'module.ext_id_bis'],
  3405. 'id2': [] }
  3406. """
  3407. result = {record.id: [] for record in self}
  3408. domain = [('model', '=', self._name), ('res_id', 'in', self.ids)]
  3409. for data in self.env['ir.model.data'].sudo().search_read(domain, ['module', 'name', 'res_id']):
  3410. result[data['res_id']].append('%(module)s.%(name)s' % data)
  3411. return result
  3412. @api.multi
  3413. def get_external_id(self):
  3414. """Retrieve the External ID of any database record, if there
  3415. is one. This method works as a possible implementation
  3416. for a function field, to be able to add it to any
  3417. model object easily, referencing it as ``Model.get_external_id``.
  3418. When multiple External IDs exist for a record, only one
  3419. of them is returned (randomly).
  3420. :return: map of ids to their fully qualified XML ID,
  3421. defaulting to an empty string when there's none
  3422. (to be usable as a function field),
  3423. e.g.::
  3424. { 'id': 'module.ext_id',
  3425. 'id2': '' }
  3426. """
  3427. results = self._get_external_ids()
  3428. return {key: val[0] if val else ''
  3429. for key, val in results.items()}
  3430. # backwards compatibility
  3431. get_xml_id = get_external_id
  3432. _get_xml_ids = _get_external_ids
  3433. # Transience
  3434. @classmethod
  3435. def is_transient(cls):
  3436. """ Return whether the model is transient.
  3437. See :class:`TransientModel`.
  3438. """
  3439. return cls._transient
  3440. @api.model_cr
  3441. def _transient_clean_rows_older_than(self, seconds):
  3442. assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
  3443. # Never delete rows used in last 5 minutes
  3444. seconds = max(seconds, 300)
  3445. query = ("SELECT id FROM " + self._table + " WHERE"
  3446. " COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp"
  3447. " < ((now() at time zone 'UTC') - interval %s)")
  3448. self._cr.execute(query, ("%s seconds" % seconds,))
  3449. ids = [x[0] for x in self._cr.fetchall()]
  3450. self.sudo().browse(ids).unlink()
  3451. @api.model_cr
  3452. def _transient_clean_old_rows(self, max_count):
  3453. # Check how many rows we have in the table
  3454. self._cr.execute("SELECT count(*) AS row_count FROM " + self._table)
  3455. res = self._cr.fetchall()
  3456. if res[0][0] <= max_count:
  3457. return # max not reached, nothing to do
  3458. self._transient_clean_rows_older_than(300)
  3459. @api.model
  3460. def _transient_vacuum(self, force=False):
  3461. """Clean the transient records.
  3462. This unlinks old records from the transient model tables whenever the
  3463. "_transient_max_count" or "_max_age" conditions (if any) are reached.
  3464. Actual cleaning will happen only once every "_transient_check_time" calls.
  3465. This means this method can be called frequently called (e.g. whenever
  3466. a new record is created).
  3467. Example with both max_hours and max_count active:
  3468. Suppose max_hours = 0.2 (e.g. 12 minutes), max_count = 20, there are 55 rows in the
  3469. table, 10 created/changed in the last 5 minutes, an additional 12 created/changed between
  3470. 5 and 10 minutes ago, the rest created/changed more then 12 minutes ago.
  3471. - age based vacuum will leave the 22 rows created/changed in the last 12 minutes
  3472. - count based vacuum will wipe out another 12 rows. Not just 2, otherwise each addition
  3473. would immediately cause the maximum to be reached again.
  3474. - the 10 rows that have been created/changed the last 5 minutes will NOT be deleted
  3475. """
  3476. assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
  3477. _transient_check_time = 20 # arbitrary limit on vacuum executions
  3478. cls = type(self)
  3479. cls._transient_check_count += 1
  3480. if not force and (cls._transient_check_count < _transient_check_time):
  3481. return True # no vacuum cleaning this time
  3482. cls._transient_check_count = 0
  3483. # Age-based expiration
  3484. if self._transient_max_hours:
  3485. self._transient_clean_rows_older_than(self._transient_max_hours * 60 * 60)
  3486. # Count-based expiration
  3487. if self._transient_max_count:
  3488. self._transient_clean_old_rows(self._transient_max_count)
  3489. return True
  3490. @api.model
  3491. def resolve_2many_commands(self, field_name, commands, fields=None):
  3492. """ Serializes one2many and many2many commands into record dictionaries
  3493. (as if all the records came from the database via a read()). This
  3494. method is aimed at onchange methods on one2many and many2many fields.
  3495. Because commands might be creation commands, not all record dicts
  3496. will contain an ``id`` field. Commands matching an existing record
  3497. will have an ``id``.
  3498. :param field_name: name of the one2many or many2many field matching the commands
  3499. :type field_name: str
  3500. :param commands: one2many or many2many commands to execute on ``field_name``
  3501. :type commands: list((int|False, int|False, dict|False))
  3502. :param fields: list of fields to read from the database, when applicable
  3503. :type fields: list(str)
  3504. :returns: records in a shape similar to that returned by ``read()``
  3505. (except records may be missing the ``id`` field if they don't exist in db)
  3506. :rtype: list(dict)
  3507. """
  3508. result = [] # result (list of dict)
  3509. record_ids = [] # ids of records to read
  3510. updates = defaultdict(dict) # {id: vals} of updates on records
  3511. for command in commands or []:
  3512. if not isinstance(command, (list, tuple)):
  3513. record_ids.append(command)
  3514. elif command[0] == 0:
  3515. result.append(command[2])
  3516. elif command[0] == 1:
  3517. record_ids.append(command[1])
  3518. updates[command[1]].update(command[2])
  3519. elif command[0] in (2, 3):
  3520. record_ids = [id for id in record_ids if id != command[1]]
  3521. elif command[0] == 4:
  3522. record_ids.append(command[1])
  3523. elif command[0] == 5:
  3524. result, record_ids = [], []
  3525. elif command[0] == 6:
  3526. result, record_ids = [], list(command[2])
  3527. # read the records and apply the updates
  3528. field = self._fields[field_name]
  3529. records = self.env[field.comodel_name].browse(record_ids)
  3530. for data in records.read(fields):
  3531. data.update(updates.get(data['id'], {}))
  3532. result.append(data)
  3533. return result
  3534. # for backward compatibility
  3535. resolve_o2m_commands_to_record_dicts = resolve_2many_commands
  3536. @api.model
  3537. def search_read(self, domain=None, fields=None, offset=0, limit=None, order=None):
  3538. """
  3539. Performs a ``search()`` followed by a ``read()``.
  3540. :param domain: Search domain, see ``args`` parameter in ``search()``. Defaults to an empty domain that will match all records.
  3541. :param fields: List of fields to read, see ``fields`` parameter in ``read()``. Defaults to all fields.
  3542. :param offset: Number of records to skip, see ``offset`` parameter in ``search()``. Defaults to 0.
  3543. :param limit: Maximum number of records to return, see ``limit`` parameter in ``search()``. Defaults to no limit.
  3544. :param order: Columns to sort result, see ``order`` parameter in ``search()``. Defaults to no sort.
  3545. :return: List of dictionaries containing the asked fields.
  3546. :rtype: List of dictionaries.
  3547. """
  3548. records = self.search(domain or [], offset=offset, limit=limit, order=order)
  3549. if not records:
  3550. return []
  3551. if fields and fields == ['id']:
  3552. # shortcut read if we only want the ids
  3553. return [{'id': record.id} for record in records]
  3554. # read() ignores active_test, but it would forward it to any downstream search call
  3555. # (e.g. for x2m or function fields), and this is not the desired behavior, the flag
  3556. # was presumably only meant for the main search().
  3557. # TODO: Move this to read() directly?
  3558. if 'active_test' in self._context:
  3559. context = dict(self._context)
  3560. del context['active_test']
  3561. records = records.with_context(context)
  3562. result = records.read(fields)
  3563. if len(result) <= 1:
  3564. return result
  3565. # reorder read
  3566. index = {vals['id']: vals for vals in result}
  3567. return [index[record.id] for record in records if record.id in index]
  3568. @api.multi
  3569. def toggle_active(self):
  3570. """ Inverse the value of the field ``active`` on the records in ``self``. """
  3571. for record in self:
  3572. record.active = not record.active
  3573. @api.model_cr
  3574. def _register_hook(self):
  3575. """ stuff to do right after the registry is built """
  3576. pass
  3577. @classmethod
  3578. def _patch_method(cls, name, method):
  3579. """ Monkey-patch a method for all instances of this model. This replaces
  3580. the method called ``name`` by ``method`` in the given class.
  3581. The original method is then accessible via ``method.origin``, and it
  3582. can be restored with :meth:`~._revert_method`.
  3583. Example::
  3584. @api.multi
  3585. def do_write(self, values):
  3586. # do stuff, and call the original method
  3587. return do_write.origin(self, values)
  3588. # patch method write of model
  3589. model._patch_method('write', do_write)
  3590. # this will call do_write
  3591. records = model.search([...])
  3592. records.write(...)
  3593. # restore the original method
  3594. model._revert_method('write')
  3595. """
  3596. origin = getattr(cls, name)
  3597. method.origin = origin
  3598. # propagate decorators from origin to method, and apply api decorator
  3599. wrapped = api.guess(api.propagate(origin, method))
  3600. wrapped.origin = origin
  3601. setattr(cls, name, wrapped)
  3602. @classmethod
  3603. def _revert_method(cls, name):
  3604. """ Revert the original method called ``name`` in the given class.
  3605. See :meth:`~._patch_method`.
  3606. """
  3607. method = getattr(cls, name)
  3608. setattr(cls, name, method.origin)
  3609. #
  3610. # Instance creation
  3611. #
  3612. # An instance represents an ordered collection of records in a given
  3613. # execution environment. The instance object refers to the environment, and
  3614. # the records themselves are represented by their cache dictionary. The 'id'
  3615. # of each record is found in its corresponding cache dictionary.
  3616. #
  3617. # This design has the following advantages:
  3618. # - cache access is direct and thus fast;
  3619. # - one can consider records without an 'id' (see new records);
  3620. # - the global cache is only an index to "resolve" a record 'id'.
  3621. #
  3622. @classmethod
  3623. def _browse(cls, ids, env, prefetch=None):
  3624. """ Create a recordset instance.
  3625. :param ids: a tuple of record ids
  3626. :param env: an environment
  3627. :param prefetch: an optional prefetch object
  3628. """
  3629. records = object.__new__(cls)
  3630. records.env = env
  3631. records._ids = ids
  3632. if prefetch is None:
  3633. prefetch = defaultdict(set) # {model_name: set(ids)}
  3634. records._prefetch = prefetch
  3635. prefetch[cls._name].update(ids)
  3636. return records
  3637. def browse(self, arg=None, prefetch=None):
  3638. """ browse([ids]) -> records
  3639. Returns a recordset for the ids provided as parameter in the current
  3640. environment.
  3641. Can take no ids, a single id or a sequence of ids.
  3642. """
  3643. ids = _normalize_ids(arg)
  3644. #assert all(isinstance(id, IdType) for id in ids), "Browsing invalid ids: %s" % ids
  3645. return self._browse(ids, self.env, prefetch)
  3646. #
  3647. # Internal properties, for manipulating the instance's implementation
  3648. #
  3649. @property
  3650. def ids(self):
  3651. """ List of actual record ids in this recordset (ignores placeholder
  3652. ids for records to create)
  3653. """
  3654. return [it for it in self._ids if it]
  3655. # backward-compatibility with former browse records
  3656. _cr = property(lambda self: self.env.cr)
  3657. _uid = property(lambda self: self.env.uid)
  3658. _context = property(lambda self: self.env.context)
  3659. #
  3660. # Conversion methods
  3661. #
  3662. def ensure_one(self):
  3663. """ Verifies that the current recorset holds a single record. Raises
  3664. an exception otherwise.
  3665. """
  3666. if len(self) == 1:
  3667. return self
  3668. raise ValueError("Expected singleton: %s" % self)
  3669. def with_env(self, env):
  3670. """ Returns a new version of this recordset attached to the provided
  3671. environment
  3672. .. warning::
  3673. The new environment will not benefit from the current
  3674. environment's data cache, so later data access may incur extra
  3675. delays while re-fetching from the database.
  3676. The returned recordset has the same prefetch object as ``self``.
  3677. :type env: :class:`~odoo.api.Environment`
  3678. """
  3679. return self._browse(self._ids, env, self._prefetch)
  3680. def sudo(self, user=SUPERUSER_ID):
  3681. """ sudo([user=SUPERUSER])
  3682. Returns a new version of this recordset attached to the provided
  3683. user.
  3684. By default this returns a ``SUPERUSER`` recordset, where access
  3685. control and record rules are bypassed.
  3686. .. note::
  3687. Using ``sudo`` could cause data access to cross the
  3688. boundaries of record rules, possibly mixing records that
  3689. are meant to be isolated (e.g. records from different
  3690. companies in multi-company environments).
  3691. It may lead to un-intuitive results in methods which select one
  3692. record among many - for example getting the default company, or
  3693. selecting a Bill of Materials.
  3694. .. note::
  3695. Because the record rules and access control will have to be
  3696. re-evaluated, the new recordset will not benefit from the current
  3697. environment's data cache, so later data access may incur extra
  3698. delays while re-fetching from the database.
  3699. The returned recordset has the same prefetch object as ``self``.
  3700. """
  3701. return self.with_env(self.env(user=user))
  3702. def with_context(self, *args, **kwargs):
  3703. """ with_context([context][, **overrides]) -> records
  3704. Returns a new version of this recordset attached to an extended
  3705. context.
  3706. The extended context is either the provided ``context`` in which
  3707. ``overrides`` are merged or the *current* context in which
  3708. ``overrides`` are merged e.g.::
  3709. # current context is {'key1': True}
  3710. r2 = records.with_context({}, key2=True)
  3711. # -> r2._context is {'key2': True}
  3712. r2 = records.with_context(key2=True)
  3713. # -> r2._context is {'key1': True, 'key2': True}
  3714. .. note:
  3715. The returned recordset has the same prefetch object as ``self``.
  3716. """
  3717. context = dict(args[0] if args else self._context, **kwargs)
  3718. return self.with_env(self.env(context=context))
  3719. def with_prefetch(self, prefetch=None):
  3720. """ with_prefetch([prefetch]) -> records
  3721. Return a new version of this recordset that uses the given prefetch
  3722. object, or a new prefetch object if not given.
  3723. """
  3724. return self._browse(self._ids, self.env, prefetch)
  3725. def _convert_to_cache(self, values, update=False, validate=True):
  3726. """ Convert the ``values`` dictionary into cached values.
  3727. :param update: whether the conversion is made for updating ``self``;
  3728. this is necessary for interpreting the commands of *2many fields
  3729. :param validate: whether values must be checked
  3730. """
  3731. fields = self._fields
  3732. target = self if update else self.browse([], self._prefetch)
  3733. return {
  3734. name: fields[name].convert_to_cache(value, target, validate=validate)
  3735. for name, value in values.items()
  3736. if name in fields
  3737. }
  3738. def _convert_to_record(self, values):
  3739. """ Convert the ``values`` dictionary from the cache format to the
  3740. record format.
  3741. """
  3742. return {
  3743. name: self._fields[name].convert_to_record(value, self)
  3744. for name, value in values.items()
  3745. }
  3746. def _convert_to_write(self, values):
  3747. """ Convert the ``values`` dictionary into the format of :meth:`write`. """
  3748. fields = self._fields
  3749. result = {}
  3750. for name, value in values.items():
  3751. if name in fields:
  3752. field = fields[name]
  3753. value = field.convert_to_cache(value, self, validate=False)
  3754. value = field.convert_to_record(value, self)
  3755. value = field.convert_to_write(value, self)
  3756. if not isinstance(value, NewId):
  3757. result[name] = value
  3758. return result
  3759. #
  3760. # Record traversal and update
  3761. #
  3762. def _mapped_func(self, func):
  3763. """ Apply function ``func`` on all records in ``self``, and return the
  3764. result as a list or a recordset (if ``func`` returns recordsets).
  3765. """
  3766. if self:
  3767. vals = [func(rec) for rec in self]
  3768. if isinstance(vals[0], BaseModel):
  3769. return vals[0].union(*vals) # union of all recordsets
  3770. return vals
  3771. else:
  3772. vals = func(self)
  3773. return vals if isinstance(vals, BaseModel) else []
  3774. def mapped(self, func):
  3775. """ Apply ``func`` on all records in ``self``, and return the result as a
  3776. list or a recordset (if ``func`` return recordsets). In the latter
  3777. case, the order of the returned recordset is arbitrary.
  3778. :param func: a function or a dot-separated sequence of field names
  3779. (string); any falsy value simply returns the recordset ``self``
  3780. """
  3781. if not func:
  3782. return self # support for an empty path of fields
  3783. if isinstance(func, pycompat.string_types):
  3784. recs = self
  3785. for name in func.split('.'):
  3786. recs = recs._mapped_func(operator.itemgetter(name))
  3787. return recs
  3788. else:
  3789. return self._mapped_func(func)
  3790. def _mapped_cache(self, name_seq):
  3791. """ Same as `~.mapped`, but ``name_seq`` is a dot-separated sequence of
  3792. field names, and only cached values are used.
  3793. """
  3794. recs = self
  3795. for name in name_seq.split('.'):
  3796. field = recs._fields[name]
  3797. null = field.convert_to_cache(False, self, validate=False)
  3798. if recs:
  3799. recs = recs.mapped(lambda rec: field.convert_to_record(rec._cache.get_value(name, null), rec))
  3800. else:
  3801. recs = field.convert_to_record(null, recs)
  3802. return recs
  3803. def filtered(self, func):
  3804. """ Select the records in ``self`` such that ``func(rec)`` is true, and
  3805. return them as a recordset.
  3806. :param func: a function or a dot-separated sequence of field names
  3807. """
  3808. if isinstance(func, pycompat.string_types):
  3809. name = func
  3810. func = lambda rec: any(rec.mapped(name))
  3811. return self.browse([rec.id for rec in self if func(rec)])
  3812. def sorted(self, key=None, reverse=False):
  3813. """ Return the recordset ``self`` ordered by ``key``.
  3814. :param key: either a function of one argument that returns a
  3815. comparison key for each record, or a field name, or ``None``, in
  3816. which case records are ordered according the default model's order
  3817. :param reverse: if ``True``, return the result in reverse order
  3818. """
  3819. if key is None:
  3820. recs = self.search([('id', 'in', self.ids)])
  3821. return self.browse(reversed(recs._ids)) if reverse else recs
  3822. if isinstance(key, pycompat.string_types):
  3823. key = itemgetter(key)
  3824. return self.browse(item.id for item in sorted(self, key=key, reverse=reverse))
  3825. @api.multi
  3826. def update(self, values):
  3827. """ Update the records in ``self`` with ``values``. """
  3828. for record in self:
  3829. for name, value in values.items():
  3830. record[name] = value
  3831. #
  3832. # New records - represent records that do not exist in the database yet;
  3833. # they are used to perform onchanges.
  3834. #
  3835. @api.model
  3836. def new(self, values={}, ref=None):
  3837. """ new([values]) -> record
  3838. Return a new record instance attached to the current environment and
  3839. initialized with the provided ``value``. The record is *not* created
  3840. in database, it only exists in memory.
  3841. One can pass a reference value to identify the record among other new
  3842. records. The reference is encapsulated in the ``id`` of the record.
  3843. """
  3844. record = self.browse([NewId(ref)])
  3845. record._cache.update(record._convert_to_cache(values, update=True))
  3846. if record.env.in_onchange:
  3847. # The cache update does not set inverse fields, so do it manually.
  3848. # This is useful for computing a function field on secondary
  3849. # records, if that field depends on the main record.
  3850. for name in values:
  3851. field = self._fields.get(name)
  3852. if field:
  3853. for invf in self._field_inverses[field]:
  3854. invf._update(record[name], record)
  3855. return record
  3856. #
  3857. # Dirty flags, to mark record fields modified (in draft mode)
  3858. #
  3859. def _is_dirty(self):
  3860. """ Return whether any record in ``self`` is dirty. """
  3861. dirty = self.env.dirty
  3862. return any(record in dirty for record in self)
  3863. def _get_dirty(self):
  3864. """ Return the list of field names for which ``self`` is dirty. """
  3865. dirty = self.env.dirty
  3866. return list(dirty.get(self, ()))
  3867. def _set_dirty(self, field_name):
  3868. """ Mark the records in ``self`` as dirty for the given ``field_name``. """
  3869. dirty = self.env.dirty
  3870. for record in self:
  3871. dirty[record].add(field_name)
  3872. #
  3873. # "Dunder" methods
  3874. #
  3875. def __bool__(self):
  3876. """ Test whether ``self`` is nonempty. """
  3877. return bool(getattr(self, '_ids', True))
  3878. __nonzero__ = __bool__
  3879. def __len__(self):
  3880. """ Return the size of ``self``. """
  3881. return len(self._ids)
  3882. def __iter__(self):
  3883. """ Return an iterator over ``self``. """
  3884. for id in self._ids:
  3885. yield self._browse((id,), self.env, self._prefetch)
  3886. def __contains__(self, item):
  3887. """ Test whether ``item`` (record or field name) is an element of ``self``.
  3888. In the first case, the test is fully equivalent to::
  3889. any(item == record for record in self)
  3890. """
  3891. if isinstance(item, BaseModel) and self._name == item._name:
  3892. return len(item) == 1 and item.id in self._ids
  3893. elif isinstance(item, pycompat.string_types):
  3894. return item in self._fields
  3895. else:
  3896. raise TypeError("Mixing apples and oranges: %s in %s" % (item, self))
  3897. def __add__(self, other):
  3898. """ Return the concatenation of two recordsets. """
  3899. return self.concat(other)
  3900. def concat(self, *args):
  3901. """ Return the concatenation of ``self`` with all the arguments (in
  3902. linear time complexity).
  3903. """
  3904. ids = list(self._ids)
  3905. for arg in args:
  3906. if not (isinstance(arg, BaseModel) and arg._name == self._name):
  3907. raise TypeError("Mixing apples and oranges: %s.concat(%s)" % (self, arg))
  3908. ids.extend(arg._ids)
  3909. return self.browse(ids)
  3910. def __sub__(self, other):
  3911. """ Return the recordset of all the records in ``self`` that are not in
  3912. ``other``. Note that recordset order is preserved.
  3913. """
  3914. if not isinstance(other, BaseModel) or self._name != other._name:
  3915. raise TypeError("Mixing apples and oranges: %s - %s" % (self, other))
  3916. other_ids = set(other._ids)
  3917. return self.browse([id for id in self._ids if id not in other_ids])
  3918. def __and__(self, other):
  3919. """ Return the intersection of two recordsets.
  3920. Note that first occurrence order is preserved.
  3921. """
  3922. if not isinstance(other, BaseModel) or self._name != other._name:
  3923. raise TypeError("Mixing apples and oranges: %s & %s" % (self, other))
  3924. other_ids = set(other._ids)
  3925. return self.browse(OrderedSet(id for id in self._ids if id in other_ids))
  3926. def __or__(self, other):
  3927. """ Return the union of two recordsets.
  3928. Note that first occurrence order is preserved.
  3929. """
  3930. return self.union(other)
  3931. def union(self, *args):
  3932. """ Return the union of ``self`` with all the arguments (in linear time
  3933. complexity, with first occurrence order preserved).
  3934. """
  3935. ids = list(self._ids)
  3936. for arg in args:
  3937. if not (isinstance(arg, BaseModel) and arg._name == self._name):
  3938. raise TypeError("Mixing apples and oranges: %s.union(%s)" % (self, arg))
  3939. ids.extend(arg._ids)
  3940. return self.browse(OrderedSet(ids))
  3941. def __eq__(self, other):
  3942. """ Test whether two recordsets are equivalent (up to reordering). """
  3943. if not isinstance(other, BaseModel):
  3944. if other:
  3945. filename, lineno = frame_codeinfo(currentframe(), 1)
  3946. _logger.warning("Comparing apples and oranges: %r == %r (%s:%s)",
  3947. self, other, filename, lineno)
  3948. return False
  3949. return self._name == other._name and set(self._ids) == set(other._ids)
  3950. def __ne__(self, other):
  3951. return not self == other
  3952. def __lt__(self, other):
  3953. if not isinstance(other, BaseModel) or self._name != other._name:
  3954. raise TypeError("Mixing apples and oranges: %s < %s" % (self, other))
  3955. return set(self._ids) < set(other._ids)
  3956. def __le__(self, other):
  3957. if not isinstance(other, BaseModel) or self._name != other._name:
  3958. raise TypeError("Mixing apples and oranges: %s <= %s" % (self, other))
  3959. return set(self._ids) <= set(other._ids)
  3960. def __gt__(self, other):
  3961. if not isinstance(other, BaseModel) or self._name != other._name:
  3962. raise TypeError("Mixing apples and oranges: %s > %s" % (self, other))
  3963. return set(self._ids) > set(other._ids)
  3964. def __ge__(self, other):
  3965. if not isinstance(other, BaseModel) or self._name != other._name:
  3966. raise TypeError("Mixing apples and oranges: %s >= %s" % (self, other))
  3967. return set(self._ids) >= set(other._ids)
  3968. def __int__(self):
  3969. return self.id
  3970. def __str__(self):
  3971. return "%s%s" % (self._name, getattr(self, '_ids', ""))
  3972. def __repr__(self):
  3973. return str(self)
  3974. def __hash__(self):
  3975. if hasattr(self, '_ids'):
  3976. return hash((self._name, frozenset(self._ids)))
  3977. else:
  3978. return hash(self._name)
  3979. def __getitem__(self, key):
  3980. """ If ``key`` is an integer or a slice, return the corresponding record
  3981. selection as an instance (attached to ``self.env``).
  3982. Otherwise read the field ``key`` of the first record in ``self``.
  3983. Examples::
  3984. inst = model.search(dom) # inst is a recordset
  3985. r4 = inst[3] # fourth record in inst
  3986. rs = inst[10:20] # subset of inst
  3987. nm = rs['name'] # name of first record in inst
  3988. """
  3989. if isinstance(key, pycompat.string_types):
  3990. # important: one must call the field's getter
  3991. return self._fields[key].__get__(self, type(self))
  3992. elif isinstance(key, slice):
  3993. return self._browse(self._ids[key], self.env)
  3994. else:
  3995. return self._browse((self._ids[key],), self.env)
  3996. def __setitem__(self, key, value):
  3997. """ Assign the field ``key`` to ``value`` in record ``self``. """
  3998. # important: one must call the field's setter
  3999. return self._fields[key].__set__(self, value)
  4000. #
  4001. # Cache and recomputation management
  4002. #
  4003. @lazy_property
  4004. def _cache(self):
  4005. """ Return the cache of ``self``, mapping field names to values. """
  4006. return RecordCache(self)
  4007. @api.model
  4008. def _in_cache_without(self, field, limit=PREFETCH_MAX):
  4009. """ Return records to prefetch that have no value in cache for ``field``
  4010. (:class:`Field` instance), including ``self``.
  4011. Return at most ``limit`` records.
  4012. """
  4013. ids0 = self._prefetch[self._name]
  4014. ids1 = set(self.env.cache.get_records(self, field)._ids)
  4015. recs = self.browse([it for it in ids0 if it and it not in ids1])
  4016. if limit and len(recs) > limit:
  4017. recs = self + (recs - self)[:(limit - len(self))]
  4018. return recs
  4019. @api.model
  4020. def refresh(self):
  4021. """ Clear the records cache.
  4022. .. deprecated:: 8.0
  4023. The record cache is automatically invalidated.
  4024. """
  4025. self.invalidate_cache()
  4026. @api.model
  4027. def invalidate_cache(self, fnames=None, ids=None):
  4028. """ Invalidate the record caches after some records have been modified.
  4029. If both ``fnames`` and ``ids`` are ``None``, the whole cache is cleared.
  4030. :param fnames: the list of modified fields, or ``None`` for all fields
  4031. :param ids: the list of modified record ids, or ``None`` for all
  4032. """
  4033. if fnames is None:
  4034. if ids is None:
  4035. return self.env.cache.invalidate()
  4036. fields = list(self._fields.values())
  4037. else:
  4038. fields = [self._fields[n] for n in fnames]
  4039. # invalidate fields and inverse fields, too
  4040. spec = [(f, ids) for f in fields] + \
  4041. [(invf, None) for f in fields for invf in self._field_inverses[f]]
  4042. self.env.cache.invalidate(spec)
  4043. @api.multi
  4044. def modified(self, fnames):
  4045. """ Notify that fields have been modified on ``self``. This invalidates
  4046. the cache, and prepares the recomputation of stored function fields
  4047. (new-style fields only).
  4048. :param fnames: iterable of field names that have been modified on
  4049. records ``self``
  4050. """
  4051. # group triggers by (model, path) to minimize the calls to search()
  4052. invalids = []
  4053. triggers = defaultdict(set)
  4054. for fname in fnames:
  4055. mfield = self._fields[fname]
  4056. # invalidate mfield on self, and its inverses fields
  4057. invalids.append((mfield, self._ids))
  4058. for field in self._field_inverses[mfield]:
  4059. invalids.append((field, None))
  4060. # group triggers by model and path to reduce the number of search()
  4061. for field, path in self._field_triggers[mfield]:
  4062. triggers[(field.model_name, path)].add(field)
  4063. # process triggers, mark fields to be invalidated/recomputed
  4064. for model_path, fields in triggers.items():
  4065. model_name, path = model_path
  4066. stored = {field for field in fields if field.compute and field.store}
  4067. # process stored fields
  4068. if path and stored:
  4069. # determine records of model_name linked by path to self
  4070. if path == 'id':
  4071. target0 = self
  4072. else:
  4073. env = self.env(user=SUPERUSER_ID, context={'active_test': False})
  4074. target0 = env[model_name].search([(path, 'in', self.ids)])
  4075. target0 = target0.with_env(self.env)
  4076. # prepare recomputation for each field on linked records
  4077. for field in stored:
  4078. # discard records to not recompute for field
  4079. target = target0 - self.env.protected(field)
  4080. if not target:
  4081. continue
  4082. invalids.append((field, target._ids))
  4083. # mark field to be recomputed on target
  4084. if field.compute_sudo:
  4085. target = target.sudo()
  4086. target._recompute_todo(field)
  4087. # process non-stored fields
  4088. for field in (fields - stored):
  4089. invalids.append((field, None))
  4090. self.env.cache.invalidate(invalids)
  4091. def _recompute_check(self, field):
  4092. """ If ``field`` must be recomputed on some record in ``self``, return the
  4093. corresponding records that must be recomputed.
  4094. """
  4095. return self.env.check_todo(field, self)
  4096. def _recompute_todo(self, field):
  4097. """ Mark ``field`` to be recomputed. """
  4098. self.env.add_todo(field, self)
  4099. def _recompute_done(self, field):
  4100. """ Mark ``field`` as recomputed. """
  4101. self.env.remove_todo(field, self)
  4102. @api.model
  4103. def recompute(self):
  4104. """ Recompute stored function fields. The fields and records to
  4105. recompute have been determined by method :meth:`modified`.
  4106. """
  4107. while self.env.has_todo():
  4108. field, recs = self.env.get_todo()
  4109. # determine the fields to recompute
  4110. fs = self.env[field.model_name]._field_computed[field]
  4111. ns = [f.name for f in fs if f.store]
  4112. # evaluate fields, and group record ids by update
  4113. updates = defaultdict(set)
  4114. for rec in recs:
  4115. try:
  4116. vals = {n: rec[n] for n in ns}
  4117. except MissingError:
  4118. continue
  4119. vals = rec._convert_to_write(vals)
  4120. updates[frozendict(vals)].add(rec.id)
  4121. # update records in batch when possible
  4122. with recs.env.norecompute():
  4123. for vals, ids in updates.items():
  4124. target = recs.browse(ids)
  4125. try:
  4126. target._write(dict(vals))
  4127. except MissingError:
  4128. # retry without missing records
  4129. target.exists()._write(dict(vals))
  4130. # mark computed fields as done
  4131. for f in fs:
  4132. recs._recompute_done(f)
  4133. #
  4134. # Generic onchange method
  4135. #
  4136. def _has_onchange(self, field, other_fields):
  4137. """ Return whether ``field`` should trigger an onchange event in the
  4138. presence of ``other_fields``.
  4139. """
  4140. # test whether self has an onchange method for field, or field is a
  4141. # dependency of any field in other_fields
  4142. return field.name in self._onchange_methods or \
  4143. any(dep in other_fields for dep, _ in self._field_triggers[field])
  4144. @api.model
  4145. def _onchange_spec(self, view_info=None):
  4146. """ Return the onchange spec from a view description; if not given, the
  4147. result of ``self.fields_view_get()`` is used.
  4148. """
  4149. result = {}
  4150. # for traversing the XML arch and populating result
  4151. def process(node, info, prefix):
  4152. if node.tag == 'field':
  4153. name = node.attrib['name']
  4154. names = "%s.%s" % (prefix, name) if prefix else name
  4155. if not result.get(names):
  4156. result[names] = node.attrib.get('on_change')
  4157. # traverse the subviews included in relational fields
  4158. for subinfo in info['fields'][name].get('views', {}).values():
  4159. process(etree.fromstring(subinfo['arch']), subinfo, names)
  4160. else:
  4161. for child in node:
  4162. process(child, info, prefix)
  4163. if view_info is None:
  4164. view_info = self.fields_view_get()
  4165. process(etree.fromstring(view_info['arch']), view_info, '')
  4166. return result
  4167. def _onchange_eval(self, field_name, onchange, result):
  4168. """ Apply onchange method(s) for field ``field_name`` with spec ``onchange``
  4169. on record ``self``. Value assignments are applied on ``self``, while
  4170. domain and warning messages are put in dictionary ``result``.
  4171. """
  4172. onchange = onchange.strip()
  4173. def process(res):
  4174. if not res:
  4175. return
  4176. if res.get('value'):
  4177. res['value'].pop('id', None)
  4178. self.update({key: val for key, val in res['value'].items() if key in self._fields})
  4179. if res.get('domain'):
  4180. result.setdefault('domain', {}).update(res['domain'])
  4181. if res.get('warning'):
  4182. if result.get('warning'):
  4183. # Concatenate multiple warnings
  4184. warning = result['warning']
  4185. warning['message'] = '\n\n'.join(s for s in [
  4186. warning.get('title'),
  4187. warning.get('message'),
  4188. res['warning'].get('title'),
  4189. res['warning'].get('message'),
  4190. ] if s)
  4191. warning['title'] = _('Warnings')
  4192. else:
  4193. result['warning'] = res['warning']
  4194. # onchange V8
  4195. if onchange in ("1", "true"):
  4196. for method in self._onchange_methods.get(field_name, ()):
  4197. method_res = method(self)
  4198. process(method_res)
  4199. return
  4200. # onchange V7
  4201. match = onchange_v7.match(onchange)
  4202. if match:
  4203. method, params = match.groups()
  4204. class RawRecord(object):
  4205. def __init__(self, record):
  4206. self._record = record
  4207. def __getitem__(self, name):
  4208. record = self._record
  4209. field = record._fields[name]
  4210. return field.convert_to_write(record[name], record)
  4211. def __getattr__(self, name):
  4212. return self[name]
  4213. # evaluate params -> tuple
  4214. global_vars = {'context': self._context, 'uid': self._uid}
  4215. if self._context.get('field_parent'):
  4216. record = self[self._context['field_parent']]
  4217. global_vars['parent'] = RawRecord(record)
  4218. field_vars = RawRecord(self)
  4219. params = safe_eval("[%s]" % params, global_vars, field_vars, nocopy=True)
  4220. # invoke onchange method
  4221. method_res = getattr(self._origin, method)(*params)
  4222. process(method_res)
  4223. @api.multi
  4224. def onchange(self, values, field_name, field_onchange):
  4225. """ Perform an onchange on the given field.
  4226. :param values: dictionary mapping field names to values, giving the
  4227. current state of modification
  4228. :param field_name: name of the modified field, or list of field
  4229. names (in view order), or False
  4230. :param field_onchange: dictionary mapping field names to their
  4231. on_change attribute
  4232. """
  4233. env = self.env
  4234. if isinstance(field_name, list):
  4235. names = field_name
  4236. elif field_name:
  4237. names = [field_name]
  4238. else:
  4239. names = []
  4240. if not all(name in self._fields for name in names):
  4241. return {}
  4242. # filter out keys in field_onchange that do not refer to actual fields
  4243. dotnames = []
  4244. for dotname in field_onchange:
  4245. try:
  4246. model = self.browse()
  4247. for name in dotname.split('.'):
  4248. model = model[name]
  4249. dotnames.append(dotname)
  4250. except Exception:
  4251. pass
  4252. # create a new record with values, and attach ``self`` to it
  4253. with env.do_in_onchange():
  4254. record = self.new(values)
  4255. values = {name: record[name] for name in record._cache}
  4256. # attach ``self`` with a different context (for cache consistency)
  4257. record._origin = self.with_context(__onchange=True)
  4258. # load fields on secondary records, to avoid false changes
  4259. with env.do_in_onchange():
  4260. for dotname in dotnames:
  4261. record.mapped(dotname)
  4262. # determine which field(s) should be triggered an onchange
  4263. todo = list(names) or list(values)
  4264. done = set()
  4265. # dummy assignment: trigger invalidations on the record
  4266. with env.do_in_onchange():
  4267. for name in todo:
  4268. if name == 'id':
  4269. continue
  4270. value = record[name]
  4271. field = self._fields[name]
  4272. if field.type == 'many2one' and field.delegate and not value:
  4273. # do not nullify all fields of parent record for new records
  4274. continue
  4275. record[name] = value
  4276. result = {}
  4277. dirty = set()
  4278. # process names in order (or the keys of values if no name given)
  4279. while todo:
  4280. name = todo.pop(0)
  4281. if name in done:
  4282. continue
  4283. done.add(name)
  4284. with env.do_in_onchange():
  4285. # apply field-specific onchange methods
  4286. if field_onchange.get(name):
  4287. record._onchange_eval(name, field_onchange[name], result)
  4288. # force re-evaluation of function fields on secondary records
  4289. for dotname in dotnames:
  4290. record.mapped(dotname)
  4291. # determine which fields have been modified
  4292. for name, oldval in values.items():
  4293. field = self._fields[name]
  4294. newval = record[name]
  4295. if newval != oldval or (
  4296. field.type in ('one2many', 'many2many') and newval._is_dirty()
  4297. ):
  4298. todo.append(name)
  4299. dirty.add(name)
  4300. # determine subfields for field.convert_to_onchange() below
  4301. Tree = lambda: defaultdict(Tree)
  4302. subnames = Tree()
  4303. for dotname in dotnames:
  4304. subtree = subnames
  4305. for name in dotname.split('.'):
  4306. subtree = subtree[name]
  4307. # collect values from dirty fields
  4308. result['value'] = {
  4309. name: self._fields[name].convert_to_onchange(record[name], record, subnames[name])
  4310. for name in dirty
  4311. }
  4312. return result
  4313. collections.Set.register(BaseModel)
  4314. # not exactly true as BaseModel doesn't have __reversed__, index or count
  4315. collections.Sequence.register(BaseModel)
  4316. class RecordCache(MutableMapping):
  4317. """ A mapping from field names to values, to read and update the cache of a record. """
  4318. def __init__(self, record):
  4319. assert len(record) == 1, "Unexpected RecordCache(%s)" % record
  4320. self._record = record
  4321. def __contains__(self, name):
  4322. """ Return whether `record` has a cached value for field ``name``. """
  4323. field = self._record._fields[name]
  4324. return self._record.env.cache.contains(self._record, field)
  4325. def __getitem__(self, name):
  4326. """ Return the cached value of field ``name`` for `record`. """
  4327. field = self._record._fields[name]
  4328. return self._record.env.cache.get(self._record, field)
  4329. def __setitem__(self, name, value):
  4330. """ Assign the cached value of field ``name`` for ``record``. """
  4331. field = self._record._fields[name]
  4332. self._record.env.cache.set(self._record, field, value)
  4333. def __delitem__(self, name):
  4334. """ Remove the cached value of field ``name`` for ``record``. """
  4335. field = self._record._fields[name]
  4336. self._record.env.cache.remove(self._record, field)
  4337. def __iter__(self):
  4338. """ Iterate over the field names with a cached value. """
  4339. for field in self._record.env.cache.get_fields(self._record):
  4340. yield field.name
  4341. def __len__(self):
  4342. """ Return the number of fields with a cached value. """
  4343. return sum(1 for name in self)
  4344. def has_value(self, name):
  4345. """ Return whether `record` has a cached, regular value for field ``name``. """
  4346. field = self._record._fields[name]
  4347. return self._record.env.cache.contains_value(self._record, field)
  4348. def get_value(self, name, default=None):
  4349. """ Return the cached, regular value of field ``name`` for `record`, or ``default``. """
  4350. field = self._record._fields[name]
  4351. return self._record.env.cache.get_value(self._record, field, default)
  4352. def set_special(self, name, getter):
  4353. """ Use the given getter to get the cached value of field ``name``. """
  4354. field = self._record._fields[name]
  4355. self._record.env.cache.set_special(self._record, field, getter)
  4356. def set_failed(self, names, exception):
  4357. """ Mark the given fields with the given exception. """
  4358. fields = [self._record._fields[name] for name in names]
  4359. self._record.env.cache.set_failed(self._record, fields, exception)
  4360. AbstractModel = BaseModel
  4361. class Model(AbstractModel):
  4362. """ Main super-class for regular database-persisted Odoo models.
  4363. Odoo models are created by inheriting from this class::
  4364. class user(Model):
  4365. ...
  4366. The system will later instantiate the class once per database (on
  4367. which the class' module is installed).
  4368. """
  4369. _auto = True # automatically create database backend
  4370. _register = False # not visible in ORM registry, meant to be python-inherited only
  4371. _abstract = False # not abstract
  4372. _transient = False # not transient
  4373. class TransientModel(Model):
  4374. """ Model super-class for transient records, meant to be temporarily
  4375. persisted, and regularly vacuum-cleaned.
  4376. A TransientModel has a simplified access rights management, all users can
  4377. create new records, and may only access the records they created. The super-
  4378. user has unrestricted access to all TransientModel records.
  4379. """
  4380. _auto = True # automatically create database backend
  4381. _register = False # not visible in ORM registry, meant to be python-inherited only
  4382. _abstract = False # not abstract
  4383. _transient = True # transient
  4384. def itemgetter_tuple(items):
  4385. """ Fixes itemgetter inconsistency (useful in some cases) of not returning
  4386. a tuple if len(items) == 1: always returns an n-tuple where n = len(items)
  4387. """
  4388. if len(items) == 0:
  4389. return lambda a: ()
  4390. if len(items) == 1:
  4391. return lambda gettable: (gettable[items[0]],)
  4392. return operator.itemgetter(*items)
  4393. def convert_pgerror_not_null(model, fields, info, e):
  4394. if e.diag.table_name != model._table:
  4395. return {'message': tools.ustr(e)}
  4396. field_name = e.diag.column_name
  4397. field = fields[field_name]
  4398. message = _(u"Missing required value for the field '%s' (%s)") % (field['string'], field_name)
  4399. return {
  4400. 'message': message,
  4401. 'field': field_name,
  4402. }
  4403. def convert_pgerror_unique(model, fields, info, e):
  4404. # new cursor since we're probably in an error handler in a blown
  4405. # transaction which may not have been rollbacked/cleaned yet
  4406. with closing(model.env.registry.cursor()) as cr:
  4407. cr.execute("""
  4408. SELECT
  4409. conname AS "constraint name",
  4410. t.relname AS "table name",
  4411. ARRAY(
  4412. SELECT attname FROM pg_attribute
  4413. WHERE attrelid = conrelid
  4414. AND attnum = ANY(conkey)
  4415. ) as "columns"
  4416. FROM pg_constraint
  4417. JOIN pg_class t ON t.oid = conrelid
  4418. WHERE conname = %s
  4419. """, [e.diag.constraint_name])
  4420. constraint, table, ufields = cr.fetchone() or (None, None, None)
  4421. # if the unique constraint is on an expression or on an other table
  4422. if not ufields or model._table != table:
  4423. return {'message': tools.ustr(e)}
  4424. # TODO: add stuff from e.diag.message_hint? provides details about the constraint & duplication values but may be localized...
  4425. if len(ufields) == 1:
  4426. field_name = ufields[0]
  4427. field = fields[field_name]
  4428. message = _(u"The value for the field '%s' already exists (this is probably '%s' in the current model).") % (field_name, field['string'])
  4429. return {
  4430. 'message': message,
  4431. 'field': field_name,
  4432. }
  4433. field_strings = [fields[fname]['string'] for fname in ufields]
  4434. message = _(u"The values for the fields '%s' already exist (they are probably '%s' in the current model).") % (', '.join(ufields), ', '.join(field_strings))
  4435. return {
  4436. 'message': message,
  4437. # no field, unclear which one we should pick and they could be in any order
  4438. }
  4439. PGERROR_TO_OE = defaultdict(
  4440. # shape of mapped converters
  4441. lambda: (lambda model, fvg, info, pgerror: {'message': tools.ustr(pgerror)}), {
  4442. '23502': convert_pgerror_not_null,
  4443. '23505': convert_pgerror_unique,
  4444. })
  4445. def _normalize_ids(arg, atoms=set(IdType)):
  4446. """ Normalizes the ids argument for ``browse`` (v7 and v8) to a tuple.
  4447. Various implementations were tested on the corpus of all browse() calls
  4448. performed during a full crawler run (after having installed all website_*
  4449. modules) and this one was the most efficient overall.
  4450. A possible bit of correctness was sacrificed by not doing any test on
  4451. Iterable and just assuming that any non-atomic type was an iterable of
  4452. some kind.
  4453. :rtype: tuple
  4454. """
  4455. # much of the corpus is falsy objects (empty list, tuple or set, None)
  4456. if not arg:
  4457. return ()
  4458. # `type in set` is significantly faster (because more restrictive) than
  4459. # isinstance(arg, set) or issubclass(type, set); and for new-style classes
  4460. # obj.__class__ is equivalent to but faster than type(obj). Not relevant
  4461. # (and looks much worse) in most cases, but over millions of calls it
  4462. # does have a very minor effect.
  4463. if arg.__class__ in atoms:
  4464. return arg,
  4465. return tuple(arg)
  4466. # keep those imports here to avoid dependency cycle errors
  4467. from .osv import expression
  4468. from .fields import Field