1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
22 #.apidoc title: Object Relational Mapping
23 #.apidoc module-mods: member-order: bysource
26 Object relational mapping to database (postgresql) module
27 * Hierarchical structure
28 * Constraints consistency, validations
29 * Object meta Data depends on its status
30 * Optimised processing by complex query (multiple actions at once)
31 * Default fields value
32 * Permissions optimisation
33 * Persistant object: DB postgresql
35 * Multi-level caching system
36 * 2 different inheritancies
38 - classicals (varchar, integer, boolean, ...)
39 - relations (one2many, many2one, many2many)
60 from lxml import etree
64 import openerp.netsvc as netsvc
65 import openerp.tools as tools
66 from openerp.tools.config import config
67 from openerp.tools.misc import CountingStream
68 from openerp.tools.safe_eval import safe_eval as eval
69 from openerp.tools.translate import _
70 from openerp import SUPERUSER_ID
71 from query import Query
73 _logger = logging.getLogger(__name__)
74 _schema = logging.getLogger(__name__ + '.schema')
76 # List of etree._Element subclasses that we choose to ignore when parsing XML.
77 from openerp.tools import SKIPPED_ELEMENT_TYPES
79 regex_order = re.compile('^( *([a-z0-9_]+|"[a-z0-9_]+")( *desc| *asc)?( *, *|))+$', re.I)
80 regex_object_name = re.compile(r'^[a-z0-9_.]+$')
82 # TODO for trunk, raise the value to 1000
83 AUTOINIT_RECALCULATE_STORED_FIELDS = 40
85 def transfer_field_to_modifiers(field, modifiers):
88 for attr in ('invisible', 'readonly', 'required'):
89 state_exceptions[attr] = []
90 default_values[attr] = bool(field.get(attr))
91 for state, modifs in (field.get("states",{})).items():
93 if default_values[modif[0]] != modif[1]:
94 state_exceptions[modif[0]].append(state)
96 for attr, default_value in default_values.items():
97 if state_exceptions[attr]:
98 modifiers[attr] = [("state", "not in" if default_value else "in", state_exceptions[attr])]
100 modifiers[attr] = default_value
103 # Don't deal with groups, it is done by check_group().
104 # Need the context to evaluate the invisible attribute on tree views.
105 # For non-tree views, the context shouldn't be given.
106 def transfer_node_to_modifiers(node, modifiers, context=None, in_tree_view=False):
107 if node.get('attrs'):
108 modifiers.update(eval(node.get('attrs')))
110 if node.get('states'):
111 if 'invisible' in modifiers and isinstance(modifiers['invisible'], list):
112 # TODO combine with AND or OR, use implicit AND for now.
113 modifiers['invisible'].append(('state', 'not in', node.get('states').split(',')))
115 modifiers['invisible'] = [('state', 'not in', node.get('states').split(','))]
117 for a in ('invisible', 'readonly', 'required'):
119 v = bool(eval(node.get(a), {'context': context or {}}))
120 if in_tree_view and a == 'invisible':
121 # Invisible in a tree view has a specific meaning, make it a
122 # new key in the modifiers attribute.
123 modifiers['tree_invisible'] = v
124 elif v or (a not in modifiers or not isinstance(modifiers[a], list)):
125 # Don't set the attribute to False if a dynamic value was
126 # provided (i.e. a domain from attrs or states).
130 def simplify_modifiers(modifiers):
131 for a in ('invisible', 'readonly', 'required'):
132 if a in modifiers and not modifiers[a]:
136 def transfer_modifiers_to_node(modifiers, node):
138 simplify_modifiers(modifiers)
139 node.set('modifiers', simplejson.dumps(modifiers))
141 def setup_modifiers(node, field=None, context=None, in_tree_view=False):
142 """ Processes node attributes and field descriptors to generate
143 the ``modifiers`` node attribute and set it on the provided node.
145 Alters its first argument in-place.
147 :param node: ``field`` node from an OpenERP view
148 :type node: lxml.etree._Element
149 :param dict field: field descriptor corresponding to the provided node
150 :param dict context: execution context used to evaluate node attributes
151 :param bool in_tree_view: triggers the ``tree_invisible`` code
152 path (separate from ``invisible``): in
153 tree view there are two levels of
154 invisibility, cell content (a column is
155 present but the cell itself is not
156 displayed) with ``invisible`` and column
157 invisibility (the whole column is
158 hidden) with ``tree_invisible``.
162 if field is not None:
163 transfer_field_to_modifiers(field, modifiers)
164 transfer_node_to_modifiers(
165 node, modifiers, context=context, in_tree_view=in_tree_view)
166 transfer_modifiers_to_node(modifiers, node)
168 def test_modifiers(what, expected):
170 if isinstance(what, basestring):
171 node = etree.fromstring(what)
172 transfer_node_to_modifiers(node, modifiers)
173 simplify_modifiers(modifiers)
174 json = simplejson.dumps(modifiers)
175 assert json == expected, "%s != %s" % (json, expected)
176 elif isinstance(what, dict):
177 transfer_field_to_modifiers(what, modifiers)
178 simplify_modifiers(modifiers)
179 json = simplejson.dumps(modifiers)
180 assert json == expected, "%s != %s" % (json, expected)
185 # openerp.osv.orm.modifiers_tests()
186 def modifiers_tests():
187 test_modifiers('<field name="a"/>', '{}')
188 test_modifiers('<field name="a" invisible="1"/>', '{"invisible": true}')
189 test_modifiers('<field name="a" readonly="1"/>', '{"readonly": true}')
190 test_modifiers('<field name="a" required="1"/>', '{"required": true}')
191 test_modifiers('<field name="a" invisible="0"/>', '{}')
192 test_modifiers('<field name="a" readonly="0"/>', '{}')
193 test_modifiers('<field name="a" required="0"/>', '{}')
194 test_modifiers('<field name="a" invisible="1" required="1"/>', '{"invisible": true, "required": true}') # TODO order is not guaranteed
195 test_modifiers('<field name="a" invisible="1" required="0"/>', '{"invisible": true}')
196 test_modifiers('<field name="a" invisible="0" required="1"/>', '{"required": true}')
197 test_modifiers("""<field name="a" attrs="{'invisible': [('b', '=', 'c')]}"/>""", '{"invisible": [["b", "=", "c"]]}')
199 # The dictionary is supposed to be the result of fields_get().
200 test_modifiers({}, '{}')
201 test_modifiers({"invisible": True}, '{"invisible": true}')
202 test_modifiers({"invisible": False}, '{}')
205 def check_object_name(name):
206 """ Check if the given name is a valid openerp object name.
208 The _name attribute in osv and osv_memory object is subject to
209 some restrictions. This function returns True or False whether
210 the given name is allowed or not.
212 TODO: this is an approximation. The goal in this approximation
213 is to disallow uppercase characters (in some places, we quote
214 table/column names and in other not, which leads to this kind
217 psycopg2.ProgrammingError: relation "xxx" does not exist).
219 The same restriction should apply to both osv and osv_memory
220 objects for consistency.
223 if regex_object_name.match(name) is None:
227 def raise_on_invalid_object_name(name):
228 if not check_object_name(name):
229 msg = "The _name attribute %s is not valid." % name
231 raise except_orm('ValueError', msg)
233 POSTGRES_CONFDELTYPES = {
241 def intersect(la, lb):
242 return filter(lambda x: x in lb, la)
244 def fix_import_export_id_paths(fieldname):
246 Fixes the id fields in import and exports, and splits field paths
249 :param str fieldname: name of the field to import/export
250 :return: split field name
253 fixed_db_id = re.sub(r'([^/])\.id', r'\1/.id', fieldname)
254 fixed_external_id = re.sub(r'([^/]):id', r'\1/id', fixed_db_id)
255 return fixed_external_id.split('/')
257 class except_orm(Exception):
258 def __init__(self, name, value):
261 self.args = (name, value)
263 class BrowseRecordError(Exception):
266 class browse_null(object):
267 """ Readonly python database object browser
273 def __getitem__(self, name):
276 def __getattr__(self, name):
277 return None # XXX: return self ?
285 def __nonzero__(self):
288 def __unicode__(self):
293 # TODO: execute an object method on browse_record_list
295 class browse_record_list(list):
296 """ Collection of browse objects
298 Such an instance will be returned when doing a ``browse([ids..])``
299 and will be iterable, yielding browse() objects
302 def __init__(self, lst, context=None):
305 super(browse_record_list, self).__init__(lst)
306 self.context = context
309 class browse_record(object):
310 """ An object that behaves like a row of an object's table.
311 It has attributes after the columns of the corresponding object.
315 uobj = pool.get('res.users')
316 user_rec = uobj.browse(cr, uid, 104)
320 def __init__(self, cr, uid, id, table, cache, context=None,
321 list_class=browse_record_list, fields_process=None):
323 :param table: the browsed object (inherited from orm)
324 :param dict cache: a dictionary of model->field->data to be shared
325 across browse objects, thus reducing the SQL
326 read()s. It can speed up things a lot, but also be
327 disastrous if not discarded after write()/unlink()
329 :param dict context: dictionary with an optional context
331 if fields_process is None:
335 self._list_class = list_class
339 self._table = table # deprecated, use _model!
341 self._table_name = self._table._name
342 self.__logger = logging.getLogger('openerp.osv.orm.browse_record.' + self._table_name)
343 self._context = context
344 self._fields_process = fields_process
346 cache.setdefault(table._name, {})
347 self._data = cache[table._name]
349 # if not (id and isinstance(id, (int, long,))):
350 # raise BrowseRecordError(_('Wrong ID for the browse record, got %r, expected an integer.') % (id,))
351 # if not table.exists(cr, uid, id, context):
352 # raise BrowseRecordError(_('Object %s does not exists') % (self,))
354 if id not in self._data:
355 self._data[id] = {'id': id}
359 def __getitem__(self, name):
363 if name not in self._data[self._id]:
364 # build the list of fields we will fetch
366 # fetch the definition of the field which was asked for
367 if name in self._table._columns:
368 col = self._table._columns[name]
369 elif name in self._table._inherit_fields:
370 col = self._table._inherit_fields[name][2]
371 elif hasattr(self._table, str(name)):
372 attr = getattr(self._table, name)
373 if isinstance(attr, (types.MethodType, types.LambdaType, types.FunctionType)):
374 def function_proxy(*args, **kwargs):
375 if 'context' not in kwargs and self._context:
376 kwargs.update(context=self._context)
377 return attr(self._cr, self._uid, [self._id], *args, **kwargs)
378 return function_proxy
382 error_msg = "Field '%s' does not exist in object '%s'" % (name, self)
383 self.__logger.warning(error_msg)
384 if self.__logger.isEnabledFor(logging.DEBUG):
385 self.__logger.debug(''.join(traceback.format_stack()))
386 raise KeyError(error_msg)
388 # if the field is a classic one or a many2one, we'll fetch all classic and many2one fields
389 if col._prefetch and not col.groups:
390 # gen the list of "local" (ie not inherited) fields which are classic or many2one
391 field_filter = lambda x: x[1]._classic_write and x[1]._prefetch and not x[1].groups
392 fields_to_fetch = filter(field_filter, self._table._columns.items())
393 # gen the list of inherited fields
394 inherits = map(lambda x: (x[0], x[1][2]), self._table._inherit_fields.items())
395 # complete the field list with the inherited fields which are classic or many2one
396 fields_to_fetch += filter(field_filter, inherits)
397 # otherwise we fetch only that field
399 fields_to_fetch = [(name, col)]
401 ids = filter(lambda id: name not in self._data[id], self._data.keys())
403 field_names = map(lambda x: x[0], fields_to_fetch)
405 field_values = self._table.read(self._cr, self._uid, ids, field_names, context=self._context, load="_classic_write")
406 except (openerp.exceptions.AccessError, except_orm):
409 # prefetching attempt failed, perhaps we're violating ACL restrictions involuntarily
410 _logger.info('Prefetching attempt for fields %s on %s failed for ids %s, re-trying just for id %s', field_names, self._model._name, ids, self._id)
412 field_values = self._table.read(self._cr, self._uid, ids, field_names, context=self._context, load="_classic_write")
414 # TODO: improve this, very slow for reports
415 if self._fields_process:
416 lang = self._context.get('lang', 'en_US') or 'en_US'
417 lang_obj_ids = self.pool.get('res.lang').search(self._cr, self._uid, [('code', '=', lang)])
419 raise Exception(_('Language with code "%s" is not defined in your system !\nDefine it through the Administration menu.') % (lang,))
420 lang_obj = self.pool.get('res.lang').browse(self._cr, self._uid, lang_obj_ids[0])
422 for field_name, field_column in fields_to_fetch:
423 if field_column._type in self._fields_process:
424 for result_line in field_values:
425 result_line[field_name] = self._fields_process[field_column._type](result_line[field_name])
426 if result_line[field_name]:
427 result_line[field_name].set_value(self._cr, self._uid, result_line[field_name], self, field_column, lang_obj)
430 # Where did those ids come from? Perhaps old entries in ir_model_dat?
431 _logger.warning("No field_values found for ids %s in %s", ids, self)
432 raise KeyError('Field %s not found in %s'%(name, self))
433 # create browse records for 'remote' objects
434 for result_line in field_values:
436 for field_name, field_column in fields_to_fetch:
437 if field_column._type == 'many2one':
438 if result_line[field_name]:
439 obj = self._table.pool.get(field_column._obj)
440 if isinstance(result_line[field_name], (list, tuple)):
441 value = result_line[field_name][0]
443 value = result_line[field_name]
445 # FIXME: this happen when a _inherits object
446 # overwrite a field of it parent. Need
447 # testing to be sure we got the right
448 # object and not the parent one.
449 if not isinstance(value, browse_record):
451 # In some cases the target model is not available yet, so we must ignore it,
452 # which is safe in most cases, this value will just be loaded later when needed.
453 # This situation can be caused by custom fields that connect objects with m2o without
454 # respecting module dependencies, causing relationships to be connected to soon when
455 # the target is not loaded yet.
457 new_data[field_name] = browse_record(self._cr,
458 self._uid, value, obj, self._cache,
459 context=self._context,
460 list_class=self._list_class,
461 fields_process=self._fields_process)
463 new_data[field_name] = value
465 new_data[field_name] = browse_null()
467 new_data[field_name] = browse_null()
468 elif field_column._type in ('one2many', 'many2many') and len(result_line[field_name]):
469 new_data[field_name] = self._list_class(
470 (browse_record(self._cr, self._uid, id, self._table.pool.get(field_column._obj),
471 self._cache, context=self._context, list_class=self._list_class,
472 fields_process=self._fields_process)
473 for id in result_line[field_name]),
474 context=self._context)
475 elif field_column._type == 'reference':
476 if result_line[field_name]:
477 if isinstance(result_line[field_name], browse_record):
478 new_data[field_name] = result_line[field_name]
480 ref_obj, ref_id = result_line[field_name].split(',')
481 ref_id = long(ref_id)
483 obj = self._table.pool.get(ref_obj)
484 new_data[field_name] = browse_record(self._cr, self._uid, ref_id, obj, self._cache, context=self._context, list_class=self._list_class, fields_process=self._fields_process)
486 new_data[field_name] = browse_null()
488 new_data[field_name] = browse_null()
490 new_data[field_name] = result_line[field_name]
491 self._data[result_line['id']].update(new_data)
493 if not name in self._data[self._id]:
494 # How did this happen? Could be a missing model due to custom fields used too soon, see above.
495 self.__logger.error("Fields to fetch: %s, Field values: %s", field_names, field_values)
496 self.__logger.error("Cached: %s, Table: %s", self._data[self._id], self._table)
497 raise KeyError(_('Unknown attribute %s in %s ') % (name, self))
498 return self._data[self._id][name]
500 def __getattr__(self, name):
504 raise AttributeError(e)
506 def __contains__(self, name):
507 return (name in self._table._columns) or (name in self._table._inherit_fields) or hasattr(self._table, name)
510 raise NotImplementedError("Iteration is not allowed on %s" % self)
512 def __hasattr__(self, name):
519 return "browse_record(%s, %d)" % (self._table_name, self._id)
521 def __eq__(self, other):
522 if not isinstance(other, browse_record):
524 return (self._table_name, self._id) == (other._table_name, other._id)
526 def __ne__(self, other):
527 if not isinstance(other, browse_record):
529 return (self._table_name, self._id) != (other._table_name, other._id)
531 # we need to define __unicode__ even though we've already defined __str__
532 # because we have overridden __getattr__
533 def __unicode__(self):
534 return unicode(str(self))
537 return hash((self._table_name, self._id))
542 """Force refreshing this browse_record's data and all the data of the
543 records that belong to the same cache, by emptying the cache completely,
544 preserving only the record identifiers (for prefetching optimizations).
546 for model, model_cache in self._cache.iteritems():
547 # only preserve the ids of the records that were in the cache
548 cached_ids = dict([(i, {'id': i}) for i in model_cache.keys()])
549 self._cache[model].clear()
550 self._cache[model].update(cached_ids)
552 def pg_varchar(size=0):
553 """ Returns the VARCHAR declaration for the provided size:
555 * If no size (or an empty or negative size is provided) return an
557 * Otherwise return a VARCHAR(n)
559 :type int size: varchar size, optional
563 if not isinstance(size, int):
564 raise TypeError("VARCHAR parameter should be an int, got %s"
567 return 'VARCHAR(%d)' % size
570 FIELDS_TO_PGTYPES = {
571 fields.boolean: 'bool',
572 fields.integer: 'int4',
576 fields.datetime: 'timestamp',
577 fields.binary: 'bytea',
578 fields.many2one: 'int4',
579 fields.serialized: 'text',
582 def get_pg_type(f, type_override=None):
584 :param fields._column f: field to get a Postgres type for
585 :param type type_override: use the provided type for dispatching instead of the field's own type
586 :returns: (postgres_identification_type, postgres_type_specification)
589 field_type = type_override or type(f)
591 if field_type in FIELDS_TO_PGTYPES:
592 pg_type = (FIELDS_TO_PGTYPES[field_type], FIELDS_TO_PGTYPES[field_type])
593 elif issubclass(field_type, fields.float):
595 pg_type = ('numeric', 'NUMERIC')
597 pg_type = ('float8', 'DOUBLE PRECISION')
598 elif issubclass(field_type, (fields.char, fields.reference)):
599 pg_type = ('varchar', pg_varchar(f.size))
600 elif issubclass(field_type, fields.selection):
601 if (isinstance(f.selection, list) and isinstance(f.selection[0][0], int))\
602 or getattr(f, 'size', None) == -1:
603 pg_type = ('int4', 'INTEGER')
605 pg_type = ('varchar', pg_varchar(getattr(f, 'size', None)))
606 elif issubclass(field_type, fields.function):
607 if f._type == 'selection':
608 pg_type = ('varchar', pg_varchar())
610 pg_type = get_pg_type(f, getattr(fields, f._type))
612 _logger.warning('%s type not supported!', field_type)
618 class MetaModel(type):
619 """ Metaclass for the Model.
621 This class is used as the metaclass for the Model class to discover
622 the models defined in a module (i.e. without instanciating them).
623 If the automatic discovery is not needed, it is possible to set the
624 model's _register attribute to False.
628 module_to_models = {}
630 def __init__(self, name, bases, attrs):
631 if not self._register:
632 self._register = True
633 super(MetaModel, self).__init__(name, bases, attrs)
636 # The (OpenERP) module name can be in the `openerp.addons` namespace
637 # or not. For instance module `sale` can be imported as
638 # `openerp.addons.sale` (the good way) or `sale` (for backward
640 module_parts = self.__module__.split('.')
641 if len(module_parts) > 2 and module_parts[0] == 'openerp' and \
642 module_parts[1] == 'addons':
643 module_name = self.__module__.split('.')[2]
645 module_name = self.__module__.split('.')[0]
646 if not hasattr(self, '_module'):
647 self._module = module_name
649 # Remember which models to instanciate for this module.
651 self.module_to_models.setdefault(self._module, []).append(self)
654 # Definition of log access columns, automatically added to models if
655 # self._log_access is True
656 LOG_ACCESS_COLUMNS = {
657 'create_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
658 'create_date': 'TIMESTAMP',
659 'write_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
660 'write_date': 'TIMESTAMP'
662 # special columns automatically created by the ORM
663 MAGIC_COLUMNS = ['id'] + LOG_ACCESS_COLUMNS.keys()
665 class BaseModel(object):
666 """ Base class for OpenERP models.
668 OpenERP models are created by inheriting from this class' subclasses:
670 * Model: for regular database-persisted models
671 * TransientModel: for temporary data, stored in the database but automatically
672 vaccuumed every so often
673 * AbstractModel: for abstract super classes meant to be shared by multiple
674 _inheriting classes (usually Models or TransientModels)
676 The system will later instantiate the class once per database (on
677 which the class' module is installed).
679 To create a class that should not be instantiated, the _register class attribute
682 __metaclass__ = MetaModel
683 _auto = True # create database backend
684 _register = False # Set to false if the model shouldn't be automatically discovered.
691 _parent_name = 'parent_id'
692 _parent_store = False
693 _parent_order = False
700 # dict of {field:method}, with method returning the (name_get of records, {id: fold})
701 # to include in the _read_group, if grouped on this field
705 _transient = False # True in a TransientModel
708 # { 'parent_model': 'm2o_field', ... }
711 # Mapping from inherits'd field name to triple (m, r, f, n) where m is the
712 # model from which it is inherits'd, r is the (local) field towards m, f
713 # is the _column object itself, and n is the original (i.e. top-most)
716 # { 'field_name': ('parent_model', 'm2o_field_to_reach_parent',
717 # field_column_obj, origina_parent_model), ... }
720 # Mapping field name/column_info object
721 # This is similar to _inherit_fields but:
722 # 1. includes self fields,
723 # 2. uses column_info instead of a triple.
729 _sql_constraints = []
730 _protected = ['read', 'write', 'create', 'default_get', 'perm_read', 'unlink', 'fields_get', 'fields_view_get', 'search', 'name_get', 'distinct_field_get', 'name_search', 'copy', 'import_data', 'search_count', 'exists']
732 CONCURRENCY_CHECK_FIELD = '__last_update'
734 def log(self, cr, uid, id, message, secondary=False, context=None):
735 return _logger.warning("log() is deprecated. Please use OpenChatter notification system instead of the res.log mechanism.")
737 def view_init(self, cr, uid, fields_list, context=None):
738 """Override this method to do specific things when a view on the object is opened."""
741 def _field_create(self, cr, context=None):
742 """ Create entries in ir_model_fields for all the model's fields.
744 If necessary, also create an entry in ir_model, and if called from the
745 modules loading scheme (by receiving 'module' in the context), also
746 create entries in ir_model_data (for the model and the fields).
748 - create an entry in ir_model (if there is not already one),
749 - create an entry in ir_model_data (if there is not already one, and if
750 'module' is in the context),
751 - update ir_model_fields with the fields found in _columns
752 (TODO there is some redundancy as _columns is updated from
753 ir_model_fields in __init__).
758 cr.execute("SELECT id FROM ir_model WHERE model=%s", (self._name,))
760 cr.execute('SELECT nextval(%s)', ('ir_model_id_seq',))
761 model_id = cr.fetchone()[0]
762 cr.execute("INSERT INTO ir_model (id,model, name, info,state) VALUES (%s, %s, %s, %s, %s)", (model_id, self._name, self._description, self.__doc__, 'base'))
764 model_id = cr.fetchone()[0]
765 if 'module' in context:
766 name_id = 'model_'+self._name.replace('.', '_')
767 cr.execute('select * from ir_model_data where name=%s and module=%s', (name_id, context['module']))
769 cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, (now() at time zone 'UTC'), (now() at time zone 'UTC'), %s, %s, %s)", \
770 (name_id, context['module'], 'ir.model', model_id)
773 cr.execute("SELECT * FROM ir_model_fields WHERE model=%s", (self._name,))
775 for rec in cr.dictfetchall():
776 cols[rec['name']] = rec
778 ir_model_fields_obj = self.pool.get('ir.model.fields')
780 # sparse field should be created at the end, as it depends on its serialized field already existing
781 model_fields = sorted(self._columns.items(), key=lambda x: 1 if x[1]._type == 'sparse' else 0)
782 for (k, f) in model_fields:
784 'model_id': model_id,
787 'field_description': f.string,
789 'relation': f._obj or '',
790 'view_load': (f.view_load and 1) or 0,
791 'select_level': tools.ustr(f.select or 0),
792 'readonly': (f.readonly and 1) or 0,
793 'required': (f.required and 1) or 0,
794 'selectable': (f.selectable and 1) or 0,
795 'translate': (f.translate and 1) or 0,
796 'relation_field': f._fields_id if isinstance(f, fields.one2many) else '',
797 'serialization_field_id': None,
799 if getattr(f, 'serialization_field', None):
800 # resolve link to serialization_field if specified by name
801 serialization_field_id = ir_model_fields_obj.search(cr, SUPERUSER_ID, [('model','=',vals['model']), ('name', '=', f.serialization_field)])
802 if not serialization_field_id:
803 raise except_orm(_('Error'), _("Serialization field `%s` not found for sparse field `%s`!") % (f.serialization_field, k))
804 vals['serialization_field_id'] = serialization_field_id[0]
806 # When its a custom field,it does not contain f.select
807 if context.get('field_state', 'base') == 'manual':
808 if context.get('field_name', '') == k:
809 vals['select_level'] = context.get('select', '0')
810 #setting value to let the problem NOT occur next time
812 vals['select_level'] = cols[k]['select_level']
815 cr.execute('select nextval(%s)', ('ir_model_fields_id_seq',))
816 id = cr.fetchone()[0]
818 cr.execute("""INSERT INTO ir_model_fields (
819 id, model_id, model, name, field_description, ttype,
820 relation,view_load,state,select_level,relation_field, translate, serialization_field_id
822 %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s
824 id, vals['model_id'], vals['model'], vals['name'], vals['field_description'], vals['ttype'],
825 vals['relation'], bool(vals['view_load']), 'base',
826 vals['select_level'], vals['relation_field'], bool(vals['translate']), vals['serialization_field_id']
828 if 'module' in context:
829 name1 = 'field_' + self._table + '_' + k
830 cr.execute("select name from ir_model_data where name=%s", (name1,))
832 name1 = name1 + "_" + str(id)
833 cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, (now() at time zone 'UTC'), (now() at time zone 'UTC'), %s, %s, %s)", \
834 (name1, context['module'], 'ir.model.fields', id)
837 for key, val in vals.items():
838 if cols[k][key] != vals[key]:
839 cr.execute('update ir_model_fields set field_description=%s where model=%s and name=%s', (vals['field_description'], vals['model'], vals['name']))
840 cr.execute("""UPDATE ir_model_fields SET
841 model_id=%s, field_description=%s, ttype=%s, relation=%s,
842 view_load=%s, select_level=%s, readonly=%s ,required=%s, selectable=%s, relation_field=%s, translate=%s, serialization_field_id=%s
844 model=%s AND name=%s""", (
845 vals['model_id'], vals['field_description'], vals['ttype'],
846 vals['relation'], bool(vals['view_load']),
847 vals['select_level'], bool(vals['readonly']), bool(vals['required']), bool(vals['selectable']), vals['relation_field'], bool(vals['translate']), vals['serialization_field_id'], vals['model'], vals['name']
852 # Goal: try to apply inheritance at the instanciation level and
853 # put objects in the pool var
856 def create_instance(cls, pool, cr):
857 """ Instanciate a given model.
859 This class method instanciates the class of some model (i.e. a class
860 deriving from osv or osv_memory). The class might be the class passed
861 in argument or, if it inherits from another class, a class constructed
862 by combining the two classes.
864 The ``attributes`` argument specifies which parent class attributes
867 TODO: the creation of the combined class is repeated at each call of
868 this method. This is probably unnecessary.
871 attributes = ['_columns', '_defaults', '_inherits', '_constraints',
874 parent_names = getattr(cls, '_inherit', None)
876 if isinstance(parent_names, (str, unicode)):
877 name = cls._name or parent_names
878 parent_names = [parent_names]
882 raise TypeError('_name is mandatory in case of multiple inheritance')
884 for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]):
885 parent_model = pool.get(parent_name)
887 raise TypeError('The model "%s" specifies an unexisting parent class "%s"\n'
888 'You may need to add a dependency on the parent class\' module.' % (name, parent_name))
889 if not getattr(cls, '_original_module', None) and name == parent_model._name:
890 cls._original_module = parent_model._original_module
891 parent_class = parent_model.__class__
894 new = copy.copy(getattr(parent_model, s, {}))
896 # Don't _inherit custom fields.
900 if hasattr(new, 'update'):
901 new.update(cls.__dict__.get(s, {}))
902 elif s=='_constraints':
903 for c in cls.__dict__.get(s, []):
905 for c2 in range(len(new)):
906 #For _constraints, we should check field and methods as well
907 if new[c2][2]==c[2] and (new[c2][0] == c[0] \
908 or getattr(new[c2][0],'__name__', True) == \
909 getattr(c[0],'__name__', False)):
910 # If new class defines a constraint with
911 # same function name, we let it override
920 new.extend(cls.__dict__.get(s, []))
923 # Keep links to non-inherited constraints, e.g. useful when exporting translations
924 nattr['_local_constraints'] = cls.__dict__.get('_constraints', [])
925 nattr['_local_sql_constraints'] = cls.__dict__.get('_sql_constraints', [])
927 cls = type(name, (cls, parent_class), dict(nattr, _register=False))
929 cls._local_constraints = getattr(cls, '_constraints', [])
930 cls._local_sql_constraints = getattr(cls, '_sql_constraints', [])
932 if not getattr(cls, '_original_module', None):
933 cls._original_module = cls._module
934 obj = object.__new__(cls)
936 if hasattr(obj, '_columns'):
937 # float fields are registry-dependent (digit attribute). Duplicate them to avoid issues.
938 for c, f in obj._columns.items():
939 if f._type == 'float':
940 obj._columns[c] = copy.copy(f)
942 obj.__init__(pool, cr)
946 """Register this model.
948 This doesn't create an instance but simply register the model
949 as being part of the module where it is defined.
954 # Set the module name (e.g. base, sale, accounting, ...) on the class.
955 module = cls.__module__.split('.')[0]
956 if not hasattr(cls, '_module'):
959 # Record this class in the list of models to instantiate for this module,
960 # managed by the metaclass.
961 module_model_list = MetaModel.module_to_models.setdefault(cls._module, [])
962 if cls not in module_model_list:
964 module_model_list.append(cls)
966 # Since we don't return an instance here, the __init__
967 # method won't be called.
970 def __init__(self, pool, cr):
971 """ Initialize a model and make it part of the given registry.
973 - copy the stored fields' functions in the osv_pool,
974 - update the _columns with the fields found in ir_model_fields,
975 - ensure there is a many2one for each _inherits'd parent,
976 - update the children's _columns,
977 - give a chance to each field to initialize itself.
980 pool.add(self._name, self)
983 if not self._name and not hasattr(self, '_inherit'):
984 name = type(self).__name__.split('.')[0]
985 msg = "The class %s has to have a _name attribute" % name
988 raise except_orm('ValueError', msg)
990 if not self._description:
991 self._description = self._name
993 self._table = self._name.replace('.', '_')
995 if not hasattr(self, '_log_access'):
996 # If _log_access is not specified, it is the same value as _auto.
997 self._log_access = getattr(self, "_auto", True)
999 self._columns = self._columns.copy()
1000 for store_field in self._columns:
1001 f = self._columns[store_field]
1002 if hasattr(f, 'digits_change'):
1004 def not_this_field(stored_func):
1005 x, y, z, e, f, l = stored_func
1006 return x != self._name or y != store_field
1007 self.pool._store_function[self._name] = filter(not_this_field, self.pool._store_function.get(self._name, []))
1008 if not isinstance(f, fields.function):
1014 sm = {self._name: (lambda self, cr, uid, ids, c={}: ids, None, 10, None)}
1015 for object, aa in sm.items():
1017 (fnct, fields2, order, length) = aa
1019 (fnct, fields2, order) = aa
1022 raise except_orm('Error',
1023 ('Invalid function definition %s in object %s !\nYou must use the definition: store={object:(fnct, fields, priority, time length)}.' % (store_field, self._name)))
1024 self.pool._store_function.setdefault(object, [])
1025 t = (self._name, store_field, fnct, tuple(fields2) if fields2 else None, order, length)
1026 if not t in self.pool._store_function[object]:
1027 self.pool._store_function[object].append((self._name, store_field, fnct, tuple(fields2) if fields2 else None, order, length))
1028 self.pool._store_function[object].sort(lambda x, y: cmp(x[4], y[4]))
1030 for (key, _, msg) in self._sql_constraints:
1031 self.pool._sql_error[self._table+'_'+key] = msg
1033 # Load manual fields
1035 # Check the query is already done for all modules of if we need to
1037 if self.pool.fields_by_model is not None:
1038 manual_fields = self.pool.fields_by_model.get(self._name, [])
1040 cr.execute('SELECT * FROM ir_model_fields WHERE model=%s AND state=%s', (self._name, 'manual'))
1041 manual_fields = cr.dictfetchall()
1042 for field in manual_fields:
1043 if field['name'] in self._columns:
1046 'string': field['field_description'],
1047 'required': bool(field['required']),
1048 'readonly': bool(field['readonly']),
1049 'domain': eval(field['domain']) if field['domain'] else None,
1050 'size': field['size'] or None,
1051 'ondelete': field['on_delete'],
1052 'translate': (field['translate']),
1054 #'select': int(field['select_level'])
1057 if field['serialization_field_id']:
1058 cr.execute('SELECT name FROM ir_model_fields WHERE id=%s', (field['serialization_field_id'],))
1059 attrs.update({'serialization_field': cr.fetchone()[0], 'type': field['ttype']})
1060 if field['ttype'] in ['many2one', 'one2many', 'many2many']:
1061 attrs.update({'relation': field['relation']})
1062 self._columns[field['name']] = fields.sparse(**attrs)
1063 elif field['ttype'] == 'selection':
1064 self._columns[field['name']] = fields.selection(eval(field['selection']), **attrs)
1065 elif field['ttype'] == 'reference':
1066 self._columns[field['name']] = fields.reference(selection=eval(field['selection']), **attrs)
1067 elif field['ttype'] == 'many2one':
1068 self._columns[field['name']] = fields.many2one(field['relation'], **attrs)
1069 elif field['ttype'] == 'one2many':
1070 self._columns[field['name']] = fields.one2many(field['relation'], field['relation_field'], **attrs)
1071 elif field['ttype'] == 'many2many':
1072 _rel1 = field['relation'].replace('.', '_')
1073 _rel2 = field['model'].replace('.', '_')
1074 _rel_name = 'x_%s_%s_%s_rel' % (_rel1, _rel2, field['name'])
1075 self._columns[field['name']] = fields.many2many(field['relation'], _rel_name, 'id1', 'id2', **attrs)
1077 self._columns[field['name']] = getattr(fields, field['ttype'])(**attrs)
1079 self._inherits_check()
1080 self._inherits_reload()
1081 if not self._sequence:
1082 self._sequence = self._table + '_id_seq'
1083 for k in self._defaults:
1084 assert (k in self._columns) or (k in self._inherit_fields), 'Default function defined in %s but field %s does not exist !' % (self._name, k,)
1085 for f in self._columns:
1086 self._columns[f].restart()
1089 if self.is_transient():
1090 self._transient_check_count = 0
1091 self._transient_max_count = config.get('osv_memory_count_limit')
1092 self._transient_max_hours = config.get('osv_memory_age_limit')
1093 assert self._log_access, "TransientModels must have log_access turned on, "\
1094 "in order to implement their access rights policy"
1097 if self._rec_name is not None:
1098 assert self._rec_name in self._all_columns.keys() + ['id'], "Invalid rec_name %s for model %s" % (self._rec_name, self._name)
1100 self._rec_name = 'name'
1103 def __export_row(self, cr, uid, row, fields, context=None):
1107 def check_type(field_type):
1108 if field_type == 'float':
1110 elif field_type == 'integer':
1112 elif field_type == 'boolean':
1116 def selection_field(in_field):
1117 col_obj = self.pool.get(in_field.keys()[0])
1118 if f[i] in col_obj._columns.keys():
1119 return col_obj._columns[f[i]]
1120 elif f[i] in col_obj._inherits.keys():
1121 selection_field(col_obj._inherits)
1125 def _get_xml_id(self, cr, uid, r):
1126 model_data = self.pool.get('ir.model.data')
1127 data_ids = model_data.search(cr, uid, [('model', '=', r._model._name), ('res_id', '=', r['id'])])
1129 d = model_data.read(cr, uid, data_ids, ['name', 'module'])[0]
1131 r = '%s.%s' % (d['module'], d['name'])
1137 n = r._model._table+'_'+str(r['id']) + (postfix and ('_'+str(postfix)) or '' )
1138 if not model_data.search(cr, uid, [('name', '=', n)]):
1141 model_data.create(cr, SUPERUSER_ID, {
1143 'model': r._model._name,
1145 'module': '__export__',
1151 data = map(lambda x: '', range(len(fields)))
1153 for fpos in range(len(fields)):
1163 r = _get_xml_id(self, cr, uid, r)
1166 # To display external name of selection field when its exported
1167 if f[i] in self._columns.keys():
1168 cols = self._columns[f[i]]
1169 elif f[i] in self._inherit_fields.keys():
1170 cols = selection_field(self._inherits)
1171 if cols and cols._type == 'selection':
1172 sel_list = cols.selection
1173 if r and type(sel_list) == type([]):
1174 r = [x[1] for x in sel_list if r==x[0]]
1175 r = r and r[0] or False
1177 if f[i] in self._columns:
1178 r = check_type(self._columns[f[i]]._type)
1179 elif f[i] in self._inherit_fields:
1180 r = check_type(self._inherit_fields[f[i]][2]._type)
1181 data[fpos] = r or False
1183 if isinstance(r, (browse_record_list, list)):
1185 fields2 = map(lambda x: (x[:i+1]==f[:i+1] and x[i+1:]) \
1188 if [x for x in fields2 if x]:
1190 done.append(fields2)
1191 if cols and cols._type=='many2many' and len(fields[fpos])>(i+1) and (fields[fpos][i+1]=='id'):
1192 data[fpos] = ','.join([_get_xml_id(self, cr, uid, x) for x in r])
1196 lines2 = row2._model.__export_row(cr, uid, row2, fields2,
1199 for fpos2 in range(len(fields)):
1200 if lines2 and lines2[0][fpos2]:
1201 data[fpos2] = lines2[0][fpos2]
1205 name_relation = self.pool.get(rr._table_name)._rec_name
1206 if isinstance(rr[name_relation], browse_record):
1207 rr = rr[name_relation]
1208 rr_name = self.pool.get(rr._table_name).name_get(cr, uid, [rr.id], context=context)
1209 rr_name = rr_name and rr_name[0] and rr_name[0][1] or ''
1210 dt += tools.ustr(rr_name or '') + ','
1211 data[fpos] = dt[:-1]
1220 if isinstance(r, browse_record):
1221 r = self.pool.get(r._table_name).name_get(cr, uid, [r.id], context=context)
1222 r = r and r[0] and r[0][1] or ''
1223 data[fpos] = tools.ustr(r or '')
1224 return [data] + lines
1226 def export_data(self, cr, uid, ids, fields_to_export, context=None):
1228 Export fields for selected objects
1230 :param cr: database cursor
1231 :param uid: current user id
1232 :param ids: list of ids
1233 :param fields_to_export: list of fields
1234 :param context: context arguments, like lang, time zone
1235 :rtype: dictionary with a *datas* matrix
1237 This method is used when exporting data via client menu
1242 cols = self._columns.copy()
1243 for f in self._inherit_fields:
1244 cols.update({f: self._inherit_fields[f][2]})
1245 fields_to_export = map(fix_import_export_id_paths, fields_to_export)
1247 for row in self.browse(cr, uid, ids, context):
1248 datas += self.__export_row(cr, uid, row, fields_to_export, context)
1249 return {'datas': datas}
1251 def import_data(self, cr, uid, fields, datas, mode='init', current_module='', noupdate=False, context=None, filename=None):
1254 Use :meth:`~load` instead
1256 Import given data in given module
1258 This method is used when importing data via client menu.
1260 Example of fields to import for a sale.order::
1263 partner_id, (=name_search)
1264 order_line/.id, (=database_id)
1266 order_line/product_id/id, (=xml id)
1267 order_line/price_unit,
1268 order_line/product_uom_qty,
1269 order_line/product_uom/id (=xml_id)
1271 This method returns a 4-tuple with the following structure::
1273 (return_code, errored_resource, error_message, unused)
1275 * The first item is a return code, it is ``-1`` in case of
1276 import error, or the last imported row number in case of success
1277 * The second item contains the record data dict that failed to import
1278 in case of error, otherwise it's 0
1279 * The third item contains an error message string in case of error,
1281 * The last item is currently unused, with no specific semantics
1283 :param fields: list of fields to import
1284 :param datas: data to import
1285 :param mode: 'init' or 'update' for record creation
1286 :param current_module: module name
1287 :param noupdate: flag for record creation
1288 :param filename: optional file to store partial import state for recovery
1289 :returns: 4-tuple in the form (return_code, errored_resource, error_message, unused)
1290 :rtype: (int, dict or 0, str or 0, str or 0)
1292 context = dict(context) if context is not None else {}
1293 context['_import_current_module'] = current_module
1295 fields = map(fix_import_export_id_paths, fields)
1296 ir_model_data_obj = self.pool.get('ir.model.data')
1299 if m['type'] == 'error':
1300 raise Exception(m['message'])
1302 if config.get('import_partial') and filename:
1303 with open(config.get('import_partial'), 'rb') as partial_import_file:
1304 data = pickle.load(partial_import_file)
1305 position = data.get(filename, 0)
1309 for res_id, xml_id, res, info in self._convert_records(cr, uid,
1310 self._extract_records(cr, uid, fields, datas,
1311 context=context, log=log),
1312 context=context, log=log):
1313 ir_model_data_obj._update(cr, uid, self._name,
1314 current_module, res, mode=mode, xml_id=xml_id,
1315 noupdate=noupdate, res_id=res_id, context=context)
1316 position = info.get('rows', {}).get('to', 0) + 1
1317 if config.get('import_partial') and filename and (not (position%100)):
1318 with open(config.get('import_partial'), 'rb') as partial_import:
1319 data = pickle.load(partial_import)
1320 data[filename] = position
1321 with open(config.get('import_partial'), 'wb') as partial_import:
1322 pickle.dump(data, partial_import)
1323 if context.get('defer_parent_store_computation'):
1324 self._parent_store_compute(cr)
1326 except Exception, e:
1328 return -1, {}, 'Line %d : %s' % (position + 1, tools.ustr(e)), ''
1330 if context.get('defer_parent_store_computation'):
1331 self._parent_store_compute(cr)
1332 return position, 0, 0, 0
1334 def load(self, cr, uid, fields, data, context=None):
1336 Attempts to load the data matrix, and returns a list of ids (or
1337 ``False`` if there was an error and no id could be generated) and a
1340 The ids are those of the records created and saved (in database), in
1341 the same order they were extracted from the file. They can be passed
1342 directly to :meth:`~read`
1344 :param fields: list of fields to import, at the same index as the corresponding data
1345 :type fields: list(str)
1346 :param data: row-major matrix of data to import
1347 :type data: list(list(str))
1348 :param dict context:
1349 :returns: {ids: list(int)|False, messages: [Message]}
1351 cr.execute('SAVEPOINT model_load')
1354 fields = map(fix_import_export_id_paths, fields)
1355 ModelData = self.pool['ir.model.data'].clear_caches()
1357 fg = self.fields_get(cr, uid, context=context)
1364 for id, xid, record, info in self._convert_records(cr, uid,
1365 self._extract_records(cr, uid, fields, data,
1366 context=context, log=messages.append),
1367 context=context, log=messages.append):
1369 cr.execute('SAVEPOINT model_load_save')
1370 except psycopg2.InternalError, e:
1371 # broken transaction, exit and hope the source error was
1373 if not any(message['type'] == 'error' for message in messages):
1374 messages.append(dict(info, type='error',message=
1375 u"Unknown database error: '%s'" % e))
1378 ids.append(ModelData._update(cr, uid, self._name,
1379 current_module, record, mode=mode, xml_id=xid,
1380 noupdate=noupdate, res_id=id, context=context))
1381 cr.execute('RELEASE SAVEPOINT model_load_save')
1382 except psycopg2.Warning, e:
1383 messages.append(dict(info, type='warning', message=str(e)))
1384 cr.execute('ROLLBACK TO SAVEPOINT model_load_save')
1385 except psycopg2.Error, e:
1386 messages.append(dict(
1388 **PGERROR_TO_OE[e.pgcode](self, fg, info, e)))
1389 # Failed to write, log to messages, rollback savepoint (to
1390 # avoid broken transaction) and keep going
1391 cr.execute('ROLLBACK TO SAVEPOINT model_load_save')
1392 if any(message['type'] == 'error' for message in messages):
1393 cr.execute('ROLLBACK TO SAVEPOINT model_load')
1395 return {'ids': ids, 'messages': messages}
1396 def _extract_records(self, cr, uid, fields_, data,
1397 context=None, log=lambda a: None):
1398 """ Generates record dicts from the data sequence.
1400 The result is a generator of dicts mapping field names to raw
1401 (unconverted, unvalidated) values.
1403 For relational fields, if sub-fields were provided the value will be
1404 a list of sub-records
1406 The following sub-fields may be set on the record (by key):
1407 * None is the name_get for the record (to use with name_create/name_search)
1408 * "id" is the External ID for the record
1409 * ".id" is the Database ID for the record
1411 columns = dict((k, v.column) for k, v in self._all_columns.iteritems())
1412 # Fake columns to avoid special cases in extractor
1413 columns[None] = fields.char('rec_name')
1414 columns['id'] = fields.char('External ID')
1415 columns['.id'] = fields.integer('Database ID')
1417 # m2o fields can't be on multiple lines so exclude them from the
1418 # is_relational field rows filter, but special-case it later on to
1419 # be handled with relational fields (as it can have subfields)
1420 is_relational = lambda field: columns[field]._type in ('one2many', 'many2many', 'many2one')
1421 get_o2m_values = itemgetter_tuple(
1422 [index for index, field in enumerate(fields_)
1423 if columns[field[0]]._type == 'one2many'])
1424 get_nono2m_values = itemgetter_tuple(
1425 [index for index, field in enumerate(fields_)
1426 if columns[field[0]]._type != 'one2many'])
1427 # Checks if the provided row has any non-empty non-relational field
1428 def only_o2m_values(row, f=get_nono2m_values, g=get_o2m_values):
1429 return any(g(row)) and not any(f(row))
1433 if index >= len(data): return
1436 # copy non-relational fields to record dict
1437 record = dict((field[0], value)
1438 for field, value in itertools.izip(fields_, row)
1439 if not is_relational(field[0]))
1441 # Get all following rows which have relational values attached to
1442 # the current record (no non-relational values)
1443 record_span = itertools.takewhile(
1444 only_o2m_values, itertools.islice(data, index + 1, None))
1445 # stitch record row back on for relational fields
1446 record_span = list(itertools.chain([row], record_span))
1447 for relfield in set(
1448 field[0] for field in fields_
1449 if is_relational(field[0])):
1450 column = columns[relfield]
1451 # FIXME: how to not use _obj without relying on fields_get?
1452 Model = self.pool[column._obj]
1454 # get only cells for this sub-field, should be strictly
1455 # non-empty, field path [None] is for name_get column
1456 indices, subfields = zip(*((index, field[1:] or [None])
1457 for index, field in enumerate(fields_)
1458 if field[0] == relfield))
1460 # return all rows which have at least one value for the
1461 # subfields of relfield
1462 relfield_data = filter(any, map(itemgetter_tuple(indices), record_span))
1463 record[relfield] = [subrecord
1464 for subrecord, _subinfo in Model._extract_records(
1465 cr, uid, subfields, relfield_data,
1466 context=context, log=log)]
1468 yield record, {'rows': {
1470 'to': index + len(record_span) - 1
1472 index += len(record_span)
1473 def _convert_records(self, cr, uid, records,
1474 context=None, log=lambda a: None):
1475 """ Converts records from the source iterable (recursive dicts of
1476 strings) into forms which can be written to the database (via
1477 self.create or (ir.model.data)._update)
1479 :returns: a list of triplets of (id, xid, record)
1480 :rtype: list((int|None, str|None, dict))
1482 if context is None: context = {}
1483 Converter = self.pool['ir.fields.converter']
1484 columns = dict((k, v.column) for k, v in self._all_columns.iteritems())
1485 Translation = self.pool['ir.translation']
1487 (f, (Translation._get_source(cr, uid, self._name + ',' + f, 'field',
1488 context.get('lang'))
1490 for f, column in columns.iteritems())
1492 convert = Converter.for_model(cr, uid, self, context=context)
1494 def _log(base, field, exception):
1495 type = 'warning' if isinstance(exception, Warning) else 'error'
1496 # logs the logical (not human-readable) field name for automated
1497 # processing of response, but injects human readable in message
1498 record = dict(base, type=type, field=field,
1499 message=unicode(exception.args[0]) % base)
1500 if len(exception.args) > 1 and exception.args[1]:
1501 record.update(exception.args[1])
1504 stream = CountingStream(records)
1505 for record, extras in stream:
1508 # name_get/name_create
1509 if None in record: pass
1516 dbid = int(record['.id'])
1518 # in case of overridden id column
1519 dbid = record['.id']
1520 if not self.search(cr, uid, [('id', '=', dbid)], context=context):
1523 record=stream.index,
1525 message=_(u"Unknown database identifier '%s'") % dbid))
1528 converted = convert(record, lambda field, err:\
1529 _log(dict(extras, record=stream.index, field=field_names[field]), field, err))
1531 yield dbid, xid, converted, dict(extras, record=stream.index)
1533 def get_invalid_fields(self, cr, uid):
1534 return list(self._invalids)
1536 def _validate(self, cr, uid, ids, context=None):
1537 context = context or {}
1538 lng = context.get('lang')
1539 trans = self.pool.get('ir.translation')
1541 for constraint in self._constraints:
1542 fun, msg, fields = constraint
1543 # We don't pass around the context here: validation code
1544 # must always yield the same results.
1545 if not fun(self, cr, uid, ids):
1546 # Check presence of __call__ directly instead of using
1547 # callable() because it will be deprecated as of Python 3.0
1548 if hasattr(msg, '__call__'):
1549 tmp_msg = msg(self, cr, uid, ids, context=context)
1550 if isinstance(tmp_msg, tuple):
1551 tmp_msg, params = tmp_msg
1552 translated_msg = tmp_msg % params
1554 translated_msg = tmp_msg
1556 translated_msg = trans._get_source(cr, uid, self._name, 'constraint', lng, msg)
1558 _("Error occurred while validating the field(s) %s: %s") % (', '.join(fields), translated_msg)
1560 self._invalids.update(fields)
1562 raise except_orm('ValidateError', '\n'.join(error_msgs))
1564 self._invalids.clear()
1566 def default_get(self, cr, uid, fields_list, context=None):
1568 Returns default values for the fields in fields_list.
1570 :param fields_list: list of fields to get the default values for (example ['field1', 'field2',])
1571 :type fields_list: list
1572 :param context: optional context dictionary - it may contains keys for specifying certain options
1573 like ``context_lang`` (language) or ``context_tz`` (timezone) to alter the results of the call.
1574 It may contain keys in the form ``default_XXX`` (where XXX is a field name), to set
1575 or override a default value for a field.
1576 A special ``bin_size`` boolean flag may also be passed in the context to request the
1577 value of all fields.binary columns to be returned as the size of the binary instead of its
1578 contents. This can also be selectively overriden by passing a field-specific flag
1579 in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field.
1580 Note: The ``bin_size_XXX`` form is new in OpenERP v6.0.
1581 :return: dictionary of the default values (set on the object model class, through user preferences, or in the context)
1583 # trigger view init hook
1584 self.view_init(cr, uid, fields_list, context)
1590 # get the default values for the inherited fields
1591 for t in self._inherits.keys():
1592 defaults.update(self.pool.get(t).default_get(cr, uid, fields_list,
1595 # get the default values defined in the object
1596 for f in fields_list:
1597 if f in self._defaults:
1598 if callable(self._defaults[f]):
1599 defaults[f] = self._defaults[f](self, cr, uid, context)
1601 defaults[f] = self._defaults[f]
1603 fld_def = ((f in self._columns) and self._columns[f]) \
1604 or ((f in self._inherit_fields) and self._inherit_fields[f][2]) \
1607 if isinstance(fld_def, fields.property):
1608 property_obj = self.pool.get('ir.property')
1609 prop_value = property_obj.get(cr, uid, f, self._name, context=context)
1611 if isinstance(prop_value, (browse_record, browse_null)):
1612 defaults[f] = prop_value.id
1614 defaults[f] = prop_value
1616 if f not in defaults:
1619 # get the default values set by the user and override the default
1620 # values defined in the object
1621 ir_values_obj = self.pool.get('ir.values')
1622 res = ir_values_obj.get(cr, uid, 'default', False, [self._name])
1623 for id, field, field_value in res:
1624 if field in fields_list:
1625 fld_def = (field in self._columns) and self._columns[field] or self._inherit_fields[field][2]
1626 if fld_def._type == 'many2one':
1627 obj = self.pool.get(fld_def._obj)
1628 if not obj.search(cr, uid, [('id', '=', field_value or False)]):
1630 if fld_def._type == 'many2many':
1631 obj = self.pool.get(fld_def._obj)
1633 for i in range(len(field_value or [])):
1634 if not obj.search(cr, uid, [('id', '=',
1637 field_value2.append(field_value[i])
1638 field_value = field_value2
1639 if fld_def._type == 'one2many':
1640 obj = self.pool.get(fld_def._obj)
1642 for i in range(len(field_value or [])):
1643 field_value2.append({})
1644 for field2 in field_value[i]:
1645 if field2 in obj._columns.keys() and obj._columns[field2]._type == 'many2one':
1646 obj2 = self.pool.get(obj._columns[field2]._obj)
1647 if not obj2.search(cr, uid,
1648 [('id', '=', field_value[i][field2])]):
1650 elif field2 in obj._inherit_fields.keys() and obj._inherit_fields[field2][2]._type == 'many2one':
1651 obj2 = self.pool.get(obj._inherit_fields[field2][2]._obj)
1652 if not obj2.search(cr, uid,
1653 [('id', '=', field_value[i][field2])]):
1655 # TODO add test for many2many and one2many
1656 field_value2[i][field2] = field_value[i][field2]
1657 field_value = field_value2
1658 defaults[field] = field_value
1660 # get the default values from the context
1661 for key in context or {}:
1662 if key.startswith('default_') and (key[8:] in fields_list):
1663 defaults[key[8:]] = context[key]
1666 def fields_get_keys(self, cr, user, context=None):
1667 res = self._columns.keys()
1668 # TODO I believe this loop can be replace by
1669 # res.extend(self._inherit_fields.key())
1670 for parent in self._inherits:
1671 res.extend(self.pool.get(parent).fields_get_keys(cr, user, context))
1674 def _rec_name_fallback(self, cr, uid, context=None):
1675 rec_name = self._rec_name
1676 if rec_name not in self._columns:
1677 rec_name = self._columns.keys()[0] if len(self._columns.keys()) > 0 else "id"
1681 # Overload this method if you need a window title which depends on the context
1683 def view_header_get(self, cr, user, view_id=None, view_type='form', context=None):
1686 def user_has_groups(self, cr, uid, groups, context=None):
1687 """Return true if the user is at least member of one of the groups
1688 in groups_str. Typically used to resolve ``groups`` attribute
1689 in view and model definitions.
1691 :param str groups: comma-separated list of fully-qualified group
1692 external IDs, e.g.: ``base.group_user,base.group_system``
1693 :return: True if the current user is a member of one of the
1696 return any([self.pool.get('res.users').has_group(cr, uid, group_ext_id)
1697 for group_ext_id in groups.split(',')])
1699 def __view_look_dom(self, cr, user, node, view_id, in_tree_view, model_fields, context=None):
1700 """Return the description of the fields in the node.
1702 In a normal call to this method, node is a complete view architecture
1703 but it is actually possible to give some sub-node (this is used so
1704 that the method can call itself recursively).
1706 Originally, the field descriptions are drawn from the node itself.
1707 But there is now some code calling fields_get() in order to merge some
1708 of those information in the architecture.
1720 if isinstance(s, unicode):
1721 return s.encode('utf8')
1724 def check_group(node):
1725 """Apply group restrictions, may be set at view level or model level::
1726 * at view level this means the element should be made invisible to
1727 people who are not members
1728 * at model level (exclusively for fields, obviously), this means
1729 the field should be completely removed from the view, as it is
1730 completely unavailable for non-members
1732 :return: True if field should be included in the result of fields_view_get
1734 if node.tag == 'field' and node.get('name') in self._all_columns:
1735 column = self._all_columns[node.get('name')].column
1736 if column.groups and not self.user_has_groups(cr, user,
1737 groups=column.groups,
1739 node.getparent().remove(node)
1740 fields.pop(node.get('name'), None)
1741 # no point processing view-level ``groups`` anymore, return
1743 if node.get('groups'):
1744 can_see = self.user_has_groups(cr, user,
1745 groups=node.get('groups'),
1748 node.set('invisible', '1')
1749 modifiers['invisible'] = True
1750 if 'attrs' in node.attrib:
1751 del(node.attrib['attrs']) #avoid making field visible later
1752 del(node.attrib['groups'])
1755 if node.tag in ('field', 'node', 'arrow'):
1756 if node.get('object'):
1761 if f.tag == 'field':
1762 xml += etree.tostring(f, encoding="utf-8")
1764 new_xml = etree.fromstring(encode(xml))
1765 ctx = context.copy()
1766 ctx['base_model_name'] = self._name
1767 xarch, xfields = self.pool.get(node.get('object')).__view_look_dom_arch(cr, user, new_xml, view_id, ctx)
1772 attrs = {'views': views}
1774 if node.get('name'):
1777 if node.get('name') in self._columns:
1778 column = self._columns[node.get('name')]
1780 column = self._inherit_fields[node.get('name')][2]
1785 relation = self.pool.get(column._obj)
1790 if f.tag in ('form', 'tree', 'graph', 'kanban'):
1792 ctx = context.copy()
1793 ctx['base_model_name'] = self._name
1794 xarch, xfields = relation.__view_look_dom_arch(cr, user, f, view_id, ctx)
1795 views[str(f.tag)] = {
1799 attrs = {'views': views}
1800 if node.get('widget') and node.get('widget') == 'selection':
1801 # Prepare the cached selection list for the client. This needs to be
1802 # done even when the field is invisible to the current user, because
1803 # other events could need to change its value to any of the selectable ones
1804 # (such as on_change events, refreshes, etc.)
1806 # If domain and context are strings, we keep them for client-side, otherwise
1807 # we evaluate them server-side to consider them when generating the list of
1809 # TODO: find a way to remove this hack, by allow dynamic domains
1811 if column._domain and not isinstance(column._domain, basestring):
1812 dom = list(column._domain)
1813 dom += eval(node.get('domain', '[]'), {'uid': user, 'time': time})
1814 search_context = dict(context)
1815 if column._context and not isinstance(column._context, basestring):
1816 search_context.update(column._context)
1817 attrs['selection'] = relation._name_search(cr, user, '', dom, context=search_context, limit=None, name_get_uid=1)
1818 if (node.get('required') and not int(node.get('required'))) or not column.required:
1819 attrs['selection'].append((False, ''))
1820 fields[node.get('name')] = attrs
1822 field = model_fields.get(node.get('name'))
1824 transfer_field_to_modifiers(field, modifiers)
1827 elif node.tag in ('form', 'tree'):
1828 result = self.view_header_get(cr, user, False, node.tag, context)
1830 node.set('string', result)
1831 in_tree_view = node.tag == 'tree'
1833 elif node.tag == 'calendar':
1834 for additional_field in ('date_start', 'date_delay', 'date_stop', 'color'):
1835 if node.get(additional_field):
1836 fields[node.get(additional_field)] = {}
1838 if not check_group(node):
1839 # node must be removed, no need to proceed further with its children
1842 # The view architeture overrides the python model.
1843 # Get the attrs before they are (possibly) deleted by check_group below
1844 transfer_node_to_modifiers(node, modifiers, context, in_tree_view)
1846 # TODO remove attrs couterpart in modifiers when invisible is true ?
1849 if 'lang' in context:
1850 if node.text and node.text.strip():
1851 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.text.strip())
1853 node.text = node.text.replace(node.text.strip(), trans)
1854 if node.tail and node.tail.strip():
1855 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.tail.strip())
1857 node.tail = node.tail.replace(node.tail.strip(), trans)
1859 if node.get('string') and not result:
1860 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('string'))
1861 if trans == node.get('string') and ('base_model_name' in context):
1862 # If translation is same as source, perhaps we'd have more luck with the alternative model name
1863 # (in case we are in a mixed situation, such as an inherited view where parent_view.model != model
1864 trans = self.pool.get('ir.translation')._get_source(cr, user, context['base_model_name'], 'view', context['lang'], node.get('string'))
1866 node.set('string', trans)
1868 for attr_name in ('confirm', 'sum', 'avg', 'help', 'placeholder'):
1869 attr_value = node.get(attr_name)
1871 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], attr_value)
1873 node.set(attr_name, trans)
1876 if children or (node.tag == 'field' and f.tag in ('filter','separator')):
1877 fields.update(self.__view_look_dom(cr, user, f, view_id, in_tree_view, model_fields, context))
1879 transfer_modifiers_to_node(modifiers, node)
1882 def _disable_workflow_buttons(self, cr, user, node):
1883 """ Set the buttons in node to readonly if the user can't activate them. """
1885 # admin user can always activate workflow buttons
1888 # TODO handle the case of more than one workflow for a model or multiple
1889 # transitions with different groups and same signal
1890 usersobj = self.pool.get('res.users')
1891 buttons = (n for n in node.getiterator('button') if n.get('type') != 'object')
1892 for button in buttons:
1893 user_groups = usersobj.read(cr, user, [user], ['groups_id'])[0]['groups_id']
1894 cr.execute("""SELECT DISTINCT t.group_id
1896 INNER JOIN wkf_activity a ON a.wkf_id = wkf.id
1897 INNER JOIN wkf_transition t ON (t.act_to = a.id)
1900 AND t.group_id is NOT NULL
1901 """, (self._name, button.get('name')))
1902 group_ids = [x[0] for x in cr.fetchall() if x[0]]
1903 can_click = not group_ids or bool(set(user_groups).intersection(group_ids))
1904 button.set('readonly', str(int(not can_click)))
1907 def __view_look_dom_arch(self, cr, user, node, view_id, context=None):
1908 """ Return an architecture and a description of all the fields.
1910 The field description combines the result of fields_get() and
1913 :param node: the architecture as as an etree
1914 :return: a tuple (arch, fields) where arch is the given node as a
1915 string and fields is the description of all the fields.
1919 if node.tag == 'diagram':
1920 if node.getchildren()[0].tag == 'node':
1921 node_model = self.pool.get(node.getchildren()[0].get('object'))
1922 node_fields = node_model.fields_get(cr, user, None, context)
1923 fields.update(node_fields)
1924 if not node.get("create") and not node_model.check_access_rights(cr, user, 'create', raise_exception=False):
1925 node.set("create", 'false')
1926 if node.getchildren()[1].tag == 'arrow':
1927 arrow_fields = self.pool.get(node.getchildren()[1].get('object')).fields_get(cr, user, None, context)
1928 fields.update(arrow_fields)
1930 fields = self.fields_get(cr, user, None, context)
1931 fields_def = self.__view_look_dom(cr, user, node, view_id, False, fields, context=context)
1932 node = self._disable_workflow_buttons(cr, user, node)
1933 if node.tag in ('kanban', 'tree', 'form', 'gantt'):
1934 for action, operation in (('create', 'create'), ('delete', 'unlink'), ('edit', 'write')):
1935 if not node.get(action) and not self.check_access_rights(cr, user, operation, raise_exception=False):
1936 node.set(action, 'false')
1937 arch = etree.tostring(node, encoding="utf-8").replace('\t', '')
1938 for k in fields.keys():
1939 if k not in fields_def:
1941 for field in fields_def:
1943 # sometime, the view may contain the (invisible) field 'id' needed for a domain (when 2 objects have cross references)
1944 fields['id'] = {'readonly': True, 'type': 'integer', 'string': 'ID'}
1945 elif field in fields:
1946 fields[field].update(fields_def[field])
1948 cr.execute('select name, model from ir_ui_view where (id=%s or inherit_id=%s) and arch like %s', (view_id, view_id, '%%%s%%' % field))
1949 res = cr.fetchall()[:]
1951 res.insert(0, ("Can't find field '%s' in the following view parts composing the view of object model '%s':" % (field, model), None))
1952 msg = "\n * ".join([r[0] for r in res])
1953 msg += "\n\nEither you wrongly customized this view, or some modules bringing those views are not compatible with your current data model"
1955 raise except_orm('View error', msg)
1958 def _get_default_form_view(self, cr, user, context=None):
1959 """ Generates a default single-line form view using all fields
1960 of the current model except the m2m and o2m ones.
1962 :param cr: database cursor
1963 :param int user: user id
1964 :param dict context: connection context
1965 :returns: a form view as an lxml document
1966 :rtype: etree._Element
1968 view = etree.Element('form', string=self._description)
1969 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
1970 for field, descriptor in self.fields_get(cr, user, context=context).iteritems():
1971 if descriptor['type'] in ('one2many', 'many2many'):
1973 etree.SubElement(view, 'field', name=field)
1974 if descriptor['type'] == 'text':
1975 etree.SubElement(view, 'newline')
1978 def _get_default_search_view(self, cr, user, context=None):
1979 """ Generates a single-field search view, based on _rec_name.
1981 :param cr: database cursor
1982 :param int user: user id
1983 :param dict context: connection context
1984 :returns: a tree view as an lxml document
1985 :rtype: etree._Element
1987 view = etree.Element('search', string=self._description)
1988 etree.SubElement(view, 'field', name=self._rec_name_fallback(cr, user, context))
1991 def _get_default_tree_view(self, cr, user, context=None):
1992 """ Generates a single-field tree view, based on _rec_name.
1994 :param cr: database cursor
1995 :param int user: user id
1996 :param dict context: connection context
1997 :returns: a tree view as an lxml document
1998 :rtype: etree._Element
2000 view = etree.Element('tree', string=self._description)
2001 etree.SubElement(view, 'field', name=self._rec_name_fallback(cr, user, context))
2004 def _get_default_calendar_view(self, cr, user, context=None):
2005 """ Generates a default calendar view by trying to infer
2006 calendar fields from a number of pre-set attribute names
2008 :param cr: database cursor
2009 :param int user: user id
2010 :param dict context: connection context
2011 :returns: a calendar view
2012 :rtype: etree._Element
2014 def set_first_of(seq, in_, to):
2015 """Sets the first value of ``seq`` also found in ``in_`` to
2016 the ``to`` attribute of the view being closed over.
2018 Returns whether it's found a suitable value (and set it on
2019 the attribute) or not
2027 view = etree.Element('calendar', string=self._description)
2028 etree.SubElement(view, 'field', self._rec_name_fallback(cr, user, context))
2030 if self._date_name not in self._columns:
2032 for dt in ['date', 'date_start', 'x_date', 'x_date_start']:
2033 if dt in self._columns:
2034 self._date_name = dt
2039 raise except_orm(_('Invalid Object Architecture!'), _("Insufficient fields for Calendar View!"))
2040 view.set('date_start', self._date_name)
2042 set_first_of(["user_id", "partner_id", "x_user_id", "x_partner_id"],
2043 self._columns, 'color')
2045 if not set_first_of(["date_stop", "date_end", "x_date_stop", "x_date_end"],
2046 self._columns, 'date_stop'):
2047 if not set_first_of(["date_delay", "planned_hours", "x_date_delay", "x_planned_hours"],
2048 self._columns, 'date_delay'):
2050 _('Invalid Object Architecture!'),
2051 _("Insufficient fields to generate a Calendar View for %s, missing a date_stop or a date_delay" % self._name))
2056 # if view_id, view_type is not required
2058 def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
2060 Get the detailed composition of the requested view like fields, model, view architecture
2062 :param cr: database cursor
2063 :param user: current user id
2064 :param view_id: id of the view or None
2065 :param view_type: type of the view to return if view_id is None ('form', tree', ...)
2066 :param context: context arguments, like lang, time zone
2067 :param toolbar: true to include contextual actions
2068 :param submenu: deprecated
2069 :return: dictionary describing the composition of the requested view (including inherited views and extensions)
2070 :raise AttributeError:
2071 * if the inherited view has unknown position to work with other than 'before', 'after', 'inside', 'replace'
2072 * if some tag other than 'position' is found in parent view
2073 :raise Invalid ArchitectureError: if there is view type other than form, tree, calendar, search etc defined on the structure
2080 if isinstance(s, unicode):
2081 return s.encode('utf8')
2084 def raise_view_error(error_msg, child_view_id):
2085 view, child_view = self.pool.get('ir.ui.view').browse(cr, user, [view_id, child_view_id], context)
2086 error_msg = error_msg % {'parent_xml_id': view.xml_id}
2087 raise AttributeError("View definition error for inherited view '%s' on model '%s': %s"
2088 % (child_view.xml_id, self._name, error_msg))
2090 def locate(source, spec):
2091 """ Locate a node in a source (parent) architecture.
2093 Given a complete source (parent) architecture (i.e. the field
2094 `arch` in a view), and a 'spec' node (a node in an inheriting
2095 view that specifies the location in the source view of what
2096 should be changed), return (if it exists) the node in the
2097 source view matching the specification.
2099 :param source: a parent architecture to modify
2100 :param spec: a modifying node in an inheriting view
2101 :return: a node in the source matching the spec
2104 if spec.tag == 'xpath':
2105 nodes = source.xpath(spec.get('expr'))
2106 return nodes[0] if nodes else None
2107 elif spec.tag == 'field':
2108 # Only compare the field name: a field can be only once in a given view
2109 # at a given level (and for multilevel expressions, we should use xpath
2110 # inheritance spec anyway).
2111 for node in source.getiterator('field'):
2112 if node.get('name') == spec.get('name'):
2116 for node in source.getiterator(spec.tag):
2117 if isinstance(node, SKIPPED_ELEMENT_TYPES):
2119 if all(node.get(attr) == spec.get(attr) \
2120 for attr in spec.attrib
2121 if attr not in ('position','version')):
2122 # Version spec should match parent's root element's version
2123 if spec.get('version') and spec.get('version') != source.get('version'):
2128 def apply_inheritance_specs(source, specs_arch, inherit_id=None):
2129 """ Apply an inheriting view.
2131 Apply to a source architecture all the spec nodes (i.e. nodes
2132 describing where and what changes to apply to some parent
2133 architecture) given by an inheriting view.
2135 :param source: a parent architecture to modify
2136 :param specs_arch: a modifying architecture in an inheriting view
2137 :param inherit_id: the database id of the inheriting view
2138 :return: a modified source where the specs are applied
2141 specs_tree = etree.fromstring(encode(specs_arch))
2142 # Queue of specification nodes (i.e. nodes describing where and
2143 # changes to apply to some parent architecture).
2144 specs = [specs_tree]
2148 if isinstance(spec, SKIPPED_ELEMENT_TYPES):
2150 if spec.tag == 'data':
2151 specs += [ c for c in specs_tree ]
2153 node = locate(source, spec)
2154 if node is not None:
2155 pos = spec.get('position', 'inside')
2156 if pos == 'replace':
2157 if node.getparent() is None:
2158 source = copy.deepcopy(spec[0])
2161 node.addprevious(child)
2162 node.getparent().remove(node)
2163 elif pos == 'attributes':
2164 for child in spec.getiterator('attribute'):
2165 attribute = (child.get('name'), child.text or None)
2167 node.set(attribute[0], attribute[1])
2169 del(node.attrib[attribute[0]])
2171 sib = node.getnext()
2175 elif pos == 'after':
2180 sib.addprevious(child)
2181 elif pos == 'before':
2182 node.addprevious(child)
2184 raise_view_error("Invalid position value: '%s'" % pos, inherit_id)
2187 ' %s="%s"' % (attr, spec.get(attr))
2188 for attr in spec.attrib
2189 if attr != 'position'
2191 tag = "<%s%s>" % (spec.tag, attrs)
2192 if spec.get('version') and spec.get('version') != source.get('version'):
2193 raise_view_error("Mismatching view API version for element '%s': %r vs %r in parent view '%%(parent_xml_id)s'" % \
2194 (tag, spec.get('version'), source.get('version')), inherit_id)
2195 raise_view_error("Element '%s' not found in parent view '%%(parent_xml_id)s'" % tag, inherit_id)
2199 def apply_view_inheritance(cr, user, source, inherit_id):
2200 """ Apply all the (directly and indirectly) inheriting views.
2202 :param source: a parent architecture to modify (with parent
2203 modifications already applied)
2204 :param inherit_id: the database view_id of the parent view
2205 :return: a modified source where all the modifying architecture
2209 sql_inherit = self.pool.get('ir.ui.view').get_inheriting_views_arch(cr, user, inherit_id, self._name, context=context)
2210 for (view_arch, view_id) in sql_inherit:
2211 source = apply_inheritance_specs(source, view_arch, view_id)
2212 source = apply_view_inheritance(cr, user, source, view_id)
2215 result = {'type': view_type, 'model': self._name}
2218 parent_view_model = None
2219 view_ref = context.get(view_type + '_view_ref')
2220 # Search for a root (i.e. without any parent) view.
2222 if view_ref and not view_id:
2224 module, view_ref = view_ref.split('.', 1)
2225 cr.execute("SELECT res_id FROM ir_model_data WHERE model='ir.ui.view' AND module=%s AND name=%s", (module, view_ref))
2226 view_ref_res = cr.fetchone()
2228 view_id = view_ref_res[0]
2231 cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model
2233 WHERE id=%s""", (view_id,))
2235 cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model
2237 WHERE model=%s AND type=%s AND inherit_id IS NULL
2238 ORDER BY priority""", (self._name, view_type))
2239 sql_res = cr.dictfetchone()
2244 view_id = sql_res['inherit_id'] or sql_res['id']
2245 parent_view_model = sql_res['model']
2246 if not sql_res['inherit_id']:
2249 # if a view was found
2251 source = etree.fromstring(encode(sql_res['arch']))
2253 arch=apply_view_inheritance(cr, user, source, sql_res['id']),
2254 type=sql_res['type'],
2255 view_id=sql_res['id'],
2256 name=sql_res['name'],
2257 field_parent=sql_res['field_parent'] or False)
2259 # otherwise, build some kind of default view
2261 view = getattr(self, '_get_default_%s_view' % view_type)(
2263 except AttributeError:
2264 # what happens here, graph case?
2265 raise except_orm(_('Invalid Architecture!'), _("There is no view of type '%s' defined for the structure!") % view_type)
2273 if parent_view_model != self._name:
2274 ctx = context.copy()
2275 ctx['base_model_name'] = parent_view_model
2278 xarch, xfields = self.__view_look_dom_arch(cr, user, result['arch'], view_id, context=ctx)
2279 result['arch'] = xarch
2280 result['fields'] = xfields
2285 for key in ('report_sxw_content', 'report_rml_content',
2286 'report_sxw', 'report_rml',
2287 'report_sxw_content_data', 'report_rml_content_data'):
2291 ir_values_obj = self.pool.get('ir.values')
2292 resprint = ir_values_obj.get(cr, user, 'action',
2293 'client_print_multi', [(self._name, False)], False,
2295 resaction = ir_values_obj.get(cr, user, 'action',
2296 'client_action_multi', [(self._name, False)], False,
2299 resrelate = ir_values_obj.get(cr, user, 'action',
2300 'client_action_relate', [(self._name, False)], False,
2302 resaction = [clean(action) for action in resaction
2303 if view_type == 'tree' or not action[2].get('multi')]
2304 resprint = [clean(print_) for print_ in resprint
2305 if view_type == 'tree' or not print_[2].get('multi')]
2306 #When multi="True" set it will display only in More of the list view
2307 resrelate = [clean(action) for action in resrelate
2308 if (action[2].get('multi') and view_type == 'tree') or (not action[2].get('multi') and view_type == 'form')]
2310 for x in itertools.chain(resprint, resaction, resrelate):
2311 x['string'] = x['name']
2313 result['toolbar'] = {
2315 'action': resaction,
2320 _view_look_dom_arch = __view_look_dom_arch
2322 def search_count(self, cr, user, args, context=None):
2325 res = self.search(cr, user, args, context=context, count=True)
2326 if isinstance(res, list):
2330 def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
2332 Search for records based on a search domain.
2334 :param cr: database cursor
2335 :param user: current user id
2336 :param args: list of tuples specifying the search domain [('field_name', 'operator', value), ...]. Pass an empty list to match all records.
2337 :param offset: optional number of results to skip in the returned values (default: 0)
2338 :param limit: optional max number of records to return (default: **None**)
2339 :param order: optional columns to sort by (default: self._order=id )
2340 :param context: optional context arguments, like lang, time zone
2341 :type context: dictionary
2342 :param count: optional (default: **False**), if **True**, returns only the number of records matching the criteria, not their ids
2343 :return: id or list of ids of records matching the criteria
2344 :rtype: integer or list of integers
2345 :raise AccessError: * if user tries to bypass access rules for read on the requested object.
2347 **Expressing a search domain (args)**
2349 Each tuple in the search domain needs to have 3 elements, in the form: **('field_name', 'operator', value)**, where:
2351 * **field_name** must be a valid name of field of the object model, possibly following many-to-one relationships using dot-notation, e.g 'street' or 'partner_id.country' are valid values.
2352 * **operator** must be a string with a valid comparison operator from this list: ``=, !=, >, >=, <, <=, like, ilike, in, not in, child_of, parent_left, parent_right``
2353 The semantics of most of these operators are obvious.
2354 The ``child_of`` operator will look for records who are children or grand-children of a given record,
2355 according to the semantics of this model (i.e following the relationship field named by
2356 ``self._parent_name``, by default ``parent_id``.
2357 * **value** must be a valid value to compare with the values of **field_name**, depending on its type.
2359 Domain criteria can be combined using 3 logical operators than can be added between tuples: '**&**' (logical AND, default), '**|**' (logical OR), '**!**' (logical NOT).
2360 These are **prefix** operators and the arity of the '**&**' and '**|**' operator is 2, while the arity of the '**!**' is just 1.
2361 Be very careful about this when you combine them the first time.
2363 Here is an example of searching for Partners named *ABC* from Belgium and Germany whose language is not english ::
2365 [('name','=','ABC'),'!',('language.code','=','en_US'),'|',('country_id.code','=','be'),('country_id.code','=','de'))
2367 The '&' is omitted as it is the default, and of course we could have used '!=' for the language, but what this domain really represents is::
2369 (name is 'ABC' AND (language is NOT english) AND (country is Belgium OR Germany))
2372 return self._search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count)
2374 def name_get(self, cr, user, ids, context=None):
2375 """Returns the preferred display value (text representation) for the records with the
2376 given ``ids``. By default this will be the value of the ``name`` column, unless
2377 the model implements a custom behavior.
2378 Can sometimes be seen as the inverse function of :meth:`~.name_search`, but it is not
2382 :return: list of pairs ``(id,text_repr)`` for all records with the given ``ids``.
2386 if isinstance(ids, (int, long)):
2389 if self._rec_name in self._all_columns:
2390 rec_name_column = self._all_columns[self._rec_name].column
2391 return [(r['id'], rec_name_column.as_display_name(cr, user, self, r[self._rec_name], context=context))
2392 for r in self.read(cr, user, ids, [self._rec_name],
2393 load='_classic_write', context=context)]
2394 return [(id, "%s,%s" % (self._name, id)) for id in ids]
2396 def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
2397 """Search for records that have a display name matching the given ``name`` pattern if compared
2398 with the given ``operator``, while also matching the optional search domain (``args``).
2399 This is used for example to provide suggestions based on a partial value for a relational
2401 Sometimes be seen as the inverse function of :meth:`~.name_get`, but it is not
2404 This method is equivalent to calling :meth:`~.search` with a search domain based on ``name``
2405 and then :meth:`~.name_get` on the result of the search.
2407 :param list args: optional search domain (see :meth:`~.search` for syntax),
2408 specifying further restrictions
2409 :param str operator: domain operator for matching the ``name`` pattern, such as ``'like'``
2411 :param int limit: optional max number of records to return
2413 :return: list of pairs ``(id,text_repr)`` for all matching records.
2415 return self._name_search(cr, user, name, args, operator, context, limit)
2417 def name_create(self, cr, uid, name, context=None):
2418 """Creates a new record by calling :meth:`~.create` with only one
2419 value provided: the name of the new record (``_rec_name`` field).
2420 The new record will also be initialized with any default values applicable
2421 to this model, or provided through the context. The usual behavior of
2422 :meth:`~.create` applies.
2423 Similarly, this method may raise an exception if the model has multiple
2424 required fields and some do not have default values.
2426 :param name: name of the record to create
2429 :return: the :meth:`~.name_get` pair value for the newly-created record.
2431 rec_id = self.create(cr, uid, {self._rec_name: name}, context)
2432 return self.name_get(cr, uid, [rec_id], context)[0]
2434 # private implementation of name_search, allows passing a dedicated user for the name_get part to
2435 # solve some access rights issues
2436 def _name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100, name_get_uid=None):
2442 # optimize out the default criterion of ``ilike ''`` that matches everything
2443 if not (name == '' and operator == 'ilike'):
2444 args += [(self._rec_name, operator, name)]
2445 access_rights_uid = name_get_uid or user
2446 ids = self._search(cr, user, args, limit=limit, context=context, access_rights_uid=access_rights_uid)
2447 res = self.name_get(cr, access_rights_uid, ids, context)
2450 def read_string(self, cr, uid, id, langs, fields=None, context=None):
2453 self.pool.get('ir.translation').check_access_rights(cr, uid, 'read')
2455 fields = self._columns.keys() + self._inherit_fields.keys()
2456 #FIXME: collect all calls to _get_source into one SQL call.
2458 res[lang] = {'code': lang}
2460 if f in self._columns:
2461 res_trans = self.pool.get('ir.translation')._get_source(cr, uid, self._name+','+f, 'field', lang)
2463 res[lang][f] = res_trans
2465 res[lang][f] = self._columns[f].string
2466 for table in self._inherits:
2467 cols = intersect(self._inherit_fields.keys(), fields)
2468 res2 = self.pool.get(table).read_string(cr, uid, id, langs, cols, context)
2471 res[lang]['code'] = lang
2472 for f in res2[lang]:
2473 res[lang][f] = res2[lang][f]
2476 def write_string(self, cr, uid, id, langs, vals, context=None):
2477 self.pool.get('ir.translation').check_access_rights(cr, uid, 'write')
2478 #FIXME: try to only call the translation in one SQL
2481 if field in self._columns:
2482 src = self._columns[field].string
2483 self.pool.get('ir.translation')._set_ids(cr, uid, self._name+','+field, 'field', lang, [0], vals[field], src)
2484 for table in self._inherits:
2485 cols = intersect(self._inherit_fields.keys(), vals)
2487 self.pool.get(table).write_string(cr, uid, id, langs, vals, context)
2490 def _add_missing_default_values(self, cr, uid, values, context=None):
2491 missing_defaults = []
2492 avoid_tables = [] # avoid overriding inherited values when parent is set
2493 for tables, parent_field in self._inherits.items():
2494 if parent_field in values:
2495 avoid_tables.append(tables)
2496 for field in self._columns.keys():
2497 if not field in values:
2498 missing_defaults.append(field)
2499 for field in self._inherit_fields.keys():
2500 if (field not in values) and (self._inherit_fields[field][0] not in avoid_tables):
2501 missing_defaults.append(field)
2503 if len(missing_defaults):
2504 # override defaults with the provided values, never allow the other way around
2505 defaults = self.default_get(cr, uid, missing_defaults, context)
2507 if ((dv in self._columns and self._columns[dv]._type == 'many2many') \
2508 or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'many2many')) \
2509 and defaults[dv] and isinstance(defaults[dv][0], (int, long)):
2510 defaults[dv] = [(6, 0, defaults[dv])]
2511 if (dv in self._columns and self._columns[dv]._type == 'one2many' \
2512 or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'one2many')) \
2513 and isinstance(defaults[dv], (list, tuple)) and defaults[dv] and isinstance(defaults[dv][0], dict):
2514 defaults[dv] = [(0, 0, x) for x in defaults[dv]]
2515 defaults.update(values)
2519 def clear_caches(self):
2520 """ Clear the caches
2522 This clears the caches associated to methods decorated with
2523 ``tools.ormcache`` or ``tools.ormcache_multi``.
2526 getattr(self, '_ormcache')
2528 self.pool._any_cache_cleared = True
2529 except AttributeError:
2533 def _read_group_fill_results(self, cr, uid, domain, groupby, groupby_list, aggregated_fields,
2534 read_group_result, read_group_order=None, context=None):
2535 """Helper method for filling in empty groups for all possible values of
2536 the field being grouped by"""
2538 # self._group_by_full should map groupable fields to a method that returns
2539 # a list of all aggregated values that we want to display for this field,
2540 # in the form of a m2o-like pair (key,label).
2541 # This is useful to implement kanban views for instance, where all columns
2542 # should be displayed even if they don't contain any record.
2544 # Grab the list of all groups that should be displayed, including all present groups
2545 present_group_ids = [x[groupby][0] for x in read_group_result if x[groupby]]
2546 all_groups,folded = self._group_by_full[groupby](self, cr, uid, present_group_ids, domain,
2547 read_group_order=read_group_order,
2548 access_rights_uid=openerp.SUPERUSER_ID,
2551 result_template = dict.fromkeys(aggregated_fields, False)
2552 result_template[groupby + '_count'] = 0
2553 if groupby_list and len(groupby_list) > 1:
2554 result_template['__context'] = {'group_by': groupby_list[1:]}
2556 # Merge the left_side (current results as dicts) with the right_side (all
2557 # possible values as m2o pairs). Both lists are supposed to be using the
2558 # same ordering, and can be merged in one pass.
2561 def append_left(left_side):
2562 grouped_value = left_side[groupby] and left_side[groupby][0]
2563 if not grouped_value in known_values:
2564 result.append(left_side)
2565 known_values[grouped_value] = left_side
2567 count_attr = groupby + '_count'
2568 known_values[grouped_value].update({count_attr: left_side[count_attr]})
2569 def append_right(right_side):
2570 grouped_value = right_side[0]
2571 if not grouped_value in known_values:
2572 line = dict(result_template)
2573 line[groupby] = right_side
2574 line['__domain'] = [(groupby,'=',grouped_value)] + domain
2576 known_values[grouped_value] = line
2577 while read_group_result or all_groups:
2578 left_side = read_group_result[0] if read_group_result else None
2579 right_side = all_groups[0] if all_groups else None
2580 assert left_side is None or left_side[groupby] is False \
2581 or isinstance(left_side[groupby], (tuple,list)), \
2582 'M2O-like pair expected, got %r' % left_side[groupby]
2583 assert right_side is None or isinstance(right_side, (tuple,list)), \
2584 'M2O-like pair expected, got %r' % right_side
2585 if left_side is None:
2586 append_right(all_groups.pop(0))
2587 elif right_side is None:
2588 append_left(read_group_result.pop(0))
2589 elif left_side[groupby] == right_side:
2590 append_left(read_group_result.pop(0))
2591 all_groups.pop(0) # discard right_side
2592 elif not left_side[groupby] or not left_side[groupby][0]:
2593 # left side == "Undefined" entry, not present on right_side
2594 append_left(read_group_result.pop(0))
2596 append_right(all_groups.pop(0))
2600 r['__fold'] = folded.get(r[groupby] and r[groupby][0], False)
2603 def _read_group_prepare(self, orderby, aggregated_fields, groupby, qualified_groupby_field, query, groupby_type=None):
2605 Prepares the GROUP BY and ORDER BY terms for the read_group method. Adds the missing JOIN clause
2606 to the query if order should be computed against m2o field.
2607 :param orderby: the orderby definition in the form "%(field)s %(order)s"
2608 :param aggregated_fields: list of aggregated fields in the query
2609 :param groupby: the current groupby field name
2610 :param qualified_groupby_field: the fully qualified SQL name for the grouped field
2611 :param osv.Query query: the query under construction
2612 :param groupby_type: the type of the grouped field
2613 :return: (groupby_terms, orderby_terms)
2616 groupby_terms = [qualified_groupby_field] if groupby else []
2618 return groupby_terms, orderby_terms
2620 self._check_qorder(orderby)
2621 for order_part in orderby.split(','):
2622 order_split = order_part.split()
2623 order_field = order_split[0]
2624 if order_field == groupby:
2625 if groupby_type == 'many2one':
2626 order_clause = self._generate_order_by(order_part, query).replace('ORDER BY ', '')
2628 orderby_terms.append(order_clause)
2629 groupby_terms += [order_term.split()[0] for order_term in order_clause.split(',')]
2631 orderby_terms.append(order_part)
2632 elif order_field in aggregated_fields:
2633 orderby_terms.append(order_part)
2635 # Cannot order by a field that will not appear in the results (needs to be grouped or aggregated)
2636 _logger.warn('%s: read_group order by `%s` ignored, cannot sort on empty columns (not grouped/aggregated)',
2637 self._name, order_part)
2638 return groupby_terms, orderby_terms
2640 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False):
2642 Get the list of records in list view grouped by the given ``groupby`` fields
2644 :param cr: database cursor
2645 :param uid: current user id
2646 :param domain: list specifying search criteria [['field_name', 'operator', 'value'], ...]
2647 :param list fields: list of fields present in the list view specified on the object
2648 :param list groupby: fields by which the records will be grouped
2649 :param int offset: optional number of records to skip
2650 :param int limit: optional max number of records to return
2651 :param dict context: context arguments, like lang, time zone
2652 :param list orderby: optional ``order by`` specification, for
2653 overriding the natural sort ordering of the
2654 groups, see also :py:meth:`~osv.osv.osv.search`
2655 (supported only for many2one fields currently)
2656 :return: list of dictionaries(one dictionary for each record) containing:
2658 * the values of fields grouped by the fields in ``groupby`` argument
2659 * __domain: list of tuples specifying the search criteria
2660 * __context: dictionary with argument like ``groupby``
2661 :rtype: [{'field_name_1': value, ...]
2662 :raise AccessError: * if user has no read rights on the requested object
2663 * if user tries to bypass access rules for read on the requested object
2666 context = context or {}
2667 self.check_access_rights(cr, uid, 'read')
2669 fields = self._columns.keys()
2671 query = self._where_calc(cr, uid, domain, context=context)
2672 self._apply_ir_rules(cr, uid, query, 'read', context=context)
2674 # Take care of adding join(s) if groupby is an '_inherits'ed field
2675 groupby_list = groupby
2676 qualified_groupby_field = groupby
2678 if isinstance(groupby, list):
2679 groupby = groupby[0]
2680 qualified_groupby_field = self._inherits_join_calc(groupby, query)
2683 assert not groupby or groupby in fields, "Fields in 'groupby' must appear in the list of fields to read (perhaps it's missing in the list view?)"
2684 groupby_def = self._columns.get(groupby) or (self._inherit_fields.get(groupby) and self._inherit_fields.get(groupby)[2])
2685 assert groupby_def and groupby_def._classic_write, "Fields in 'groupby' must be regular database-persisted fields (no function or related fields), or function fields with store=True"
2687 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
2688 fget = self.fields_get(cr, uid, fields)
2692 if fget.get(groupby):
2693 groupby_type = fget[groupby]['type']
2694 if groupby_type in ('date', 'datetime'):
2695 qualified_groupby_field = "to_char(%s,'yyyy-mm')" % qualified_groupby_field
2696 elif groupby_type == 'boolean':
2697 qualified_groupby_field = "coalesce(%s,false)" % qualified_groupby_field
2698 select_terms.append("%s as %s " % (qualified_groupby_field, groupby))
2700 # Don't allow arbitrary values, as this would be a SQL injection vector!
2701 raise except_orm(_('Invalid group_by'),
2702 _('Invalid group_by specification: "%s".\nA group_by specification must be a list of valid fields.')%(groupby,))
2704 aggregated_fields = [
2706 if f not in ('id', 'sequence', groupby)
2707 if fget[f]['type'] in ('integer', 'float')
2708 if (f in self._all_columns and getattr(self._all_columns[f].column, '_classic_write'))]
2709 for f in aggregated_fields:
2710 group_operator = fget[f].get('group_operator', 'sum')
2711 qualified_field = self._inherits_join_calc(f, query)
2712 select_terms.append("%s(%s) AS %s" % (group_operator, qualified_field, f))
2714 order = orderby or groupby or ''
2715 groupby_terms, orderby_terms = self._read_group_prepare(order, aggregated_fields, groupby, qualified_groupby_field, query, groupby_type)
2717 from_clause, where_clause, where_clause_params = query.get_sql()
2718 if len(groupby_list) < 2 and context.get('group_by_no_leaf'):
2721 count_field = groupby
2723 prefix_terms = lambda prefix, terms: (prefix + " " + ",".join(terms)) if terms else ''
2724 prefix_term = lambda prefix, term: ('%s %s' % (prefix, term)) if term else ''
2727 SELECT min(%(table)s.id) AS id, count(%(table)s.id) AS %(count_field)s_count
2736 'table': self._table,
2737 'count_field': count_field,
2738 'extra_fields': prefix_terms(',', select_terms),
2739 'from': from_clause,
2740 'where': prefix_term('WHERE', where_clause),
2741 'groupby': prefix_terms('GROUP BY', groupby_terms),
2742 'orderby': prefix_terms('ORDER BY', orderby_terms),
2743 'limit': prefix_term('LIMIT', int(limit) if limit else None),
2744 'offset': prefix_term('OFFSET', int(offset) if limit else None),
2746 cr.execute(query, where_clause_params)
2748 fetched_data = cr.dictfetchall()
2751 for r in fetched_data:
2752 for fld, val in r.items():
2753 if val is None: r[fld] = False
2754 alldata[r['id']] = r
2755 data_ids.append(r['id'])
2759 data = self.read(cr, uid, data_ids, [groupby], context=context)
2760 # restore order of the search as read() uses the default _order (this is only for groups, so the footprint of data should be small):
2761 data_dict = dict((d['id'], d[groupby] ) for d in data)
2762 result = [{'id': i, groupby: data_dict[i]} for i in data_ids]
2764 result = [{'id': i} for i in data_ids]
2768 d['__domain'] = [(groupby, '=', alldata[d['id']][groupby] or False)] + domain
2769 if not isinstance(groupby_list, (str, unicode)):
2770 if groupby or not context.get('group_by_no_leaf', False):
2771 d['__context'] = {'group_by': groupby_list[1:]}
2772 if groupby and groupby in fget:
2773 if d[groupby] and fget[groupby]['type'] in ('date', 'datetime'):
2774 dt = datetime.datetime.strptime(alldata[d['id']][groupby][:7], '%Y-%m')
2775 days = calendar.monthrange(dt.year, dt.month)[1]
2777 date_value = datetime.datetime.strptime(d[groupby][:10], '%Y-%m-%d')
2778 d[groupby] = babel.dates.format_date(
2779 date_value, format='MMMM yyyy', locale=context.get('lang', 'en_US'))
2780 d['__domain'] = [(groupby, '>=', alldata[d['id']][groupby] and datetime.datetime.strptime(alldata[d['id']][groupby][:7] + '-01', '%Y-%m-%d').strftime('%Y-%m-%d') or False),\
2781 (groupby, '<=', alldata[d['id']][groupby] and datetime.datetime.strptime(alldata[d['id']][groupby][:7] + '-' + str(days), '%Y-%m-%d').strftime('%Y-%m-%d') or False)] + domain
2782 del alldata[d['id']][groupby]
2783 d.update(alldata[d['id']])
2786 if groupby and groupby in self._group_by_full:
2787 result = self._read_group_fill_results(cr, uid, domain, groupby, groupby_list,
2788 aggregated_fields, result, read_group_order=order,
2793 def _inherits_join_add(self, current_model, parent_model_name, query):
2795 Add missing table SELECT and JOIN clause to ``query`` for reaching the parent table (no duplicates)
2796 :param current_model: current model object
2797 :param parent_model_name: name of the parent model for which the clauses should be added
2798 :param query: query object on which the JOIN should be added
2800 inherits_field = current_model._inherits[parent_model_name]
2801 parent_model = self.pool.get(parent_model_name)
2802 parent_alias, parent_alias_statement = query.add_join((current_model._table, parent_model._table, inherits_field, 'id', inherits_field), implicit=True)
2805 def _inherits_join_calc(self, field, query):
2807 Adds missing table select and join clause(s) to ``query`` for reaching
2808 the field coming from an '_inherits' parent table (no duplicates).
2810 :param field: name of inherited field to reach
2811 :param query: query object on which the JOIN should be added
2812 :return: qualified name of field, to be used in SELECT clause
2814 current_table = self
2815 parent_alias = '"%s"' % current_table._table
2816 while field in current_table._inherit_fields and not field in current_table._columns:
2817 parent_model_name = current_table._inherit_fields[field][0]
2818 parent_table = self.pool.get(parent_model_name)
2819 parent_alias = self._inherits_join_add(current_table, parent_model_name, query)
2820 current_table = parent_table
2821 return '%s."%s"' % (parent_alias, field)
2823 def _parent_store_compute(self, cr):
2824 if not self._parent_store:
2826 _logger.info('Computing parent left and right for table %s...', self._table)
2827 def browse_rec(root, pos=0):
2829 where = self._parent_name+'='+str(root)
2831 where = self._parent_name+' IS NULL'
2832 if self._parent_order:
2833 where += ' order by '+self._parent_order
2834 cr.execute('SELECT id FROM '+self._table+' WHERE '+where)
2836 for id in cr.fetchall():
2837 pos2 = browse_rec(id[0], pos2)
2838 cr.execute('update '+self._table+' set parent_left=%s, parent_right=%s where id=%s', (pos, pos2, root))
2840 query = 'SELECT id FROM '+self._table+' WHERE '+self._parent_name+' IS NULL'
2841 if self._parent_order:
2842 query += ' order by ' + self._parent_order
2845 for (root,) in cr.fetchall():
2846 pos = browse_rec(root, pos)
2849 def _update_store(self, cr, f, k):
2850 _logger.info("storing computed values of fields.function '%s'", k)
2851 ss = self._columns[k]._symbol_set
2852 update_query = 'UPDATE "%s" SET "%s"=%s WHERE id=%%s' % (self._table, k, ss[0])
2853 cr.execute('select id from '+self._table)
2854 ids_lst = map(lambda x: x[0], cr.fetchall())
2856 iids = ids_lst[:AUTOINIT_RECALCULATE_STORED_FIELDS]
2857 ids_lst = ids_lst[AUTOINIT_RECALCULATE_STORED_FIELDS:]
2858 res = f.get(cr, self, iids, k, SUPERUSER_ID, {})
2859 for key, val in res.items():
2862 # if val is a many2one, just write the ID
2863 if type(val) == tuple:
2865 if val is not False:
2866 cr.execute(update_query, (ss[1](val), key))
2868 def _check_selection_field_value(self, cr, uid, field, value, context=None):
2869 """Raise except_orm if value is not among the valid values for the selection field"""
2870 if self._columns[field]._type == 'reference':
2871 val_model, val_id_str = value.split(',', 1)
2874 val_id = long(val_id_str)
2878 raise except_orm(_('ValidateError'),
2879 _('Invalid value for reference field "%s.%s" (last part must be a non-zero integer): "%s"') % (self._table, field, value))
2883 if isinstance(self._columns[field].selection, (tuple, list)):
2884 if val in dict(self._columns[field].selection):
2886 elif val in dict(self._columns[field].selection(self, cr, uid, context=context)):
2888 raise except_orm(_('ValidateError'),
2889 _('The value "%s" for the field "%s.%s" is not in the selection') % (value, self._table, field))
2891 def _check_removed_columns(self, cr, log=False):
2892 # iterate on the database columns to drop the NOT NULL constraints
2893 # of fields which were required but have been removed (or will be added by another module)
2894 columns = [c for c in self._columns if not (isinstance(self._columns[c], fields.function) and not self._columns[c].store)]
2895 columns += MAGIC_COLUMNS
2896 cr.execute("SELECT a.attname, a.attnotnull"
2897 " FROM pg_class c, pg_attribute a"
2898 " WHERE c.relname=%s"
2899 " AND c.oid=a.attrelid"
2900 " AND a.attisdropped=%s"
2901 " AND pg_catalog.format_type(a.atttypid, a.atttypmod) NOT IN ('cid', 'tid', 'oid', 'xid')"
2902 " AND a.attname NOT IN %s", (self._table, False, tuple(columns))),
2904 for column in cr.dictfetchall():
2906 _logger.debug("column %s is in the table %s but not in the corresponding object %s",
2907 column['attname'], self._table, self._name)
2908 if column['attnotnull']:
2909 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, column['attname']))
2910 _schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
2911 self._table, column['attname'])
2913 def _save_constraint(self, cr, constraint_name, type):
2915 Record the creation of a constraint for this model, to make it possible
2916 to delete it later when the module is uninstalled. Type can be either
2917 'f' or 'u' depending on the constraint being a foreign key or not.
2919 if not self._module:
2920 # no need to save constraints for custom models as they're not part
2923 assert type in ('f', 'u')
2925 SELECT 1 FROM ir_model_constraint, ir_module_module
2926 WHERE ir_model_constraint.module=ir_module_module.id
2927 AND ir_model_constraint.name=%s
2928 AND ir_module_module.name=%s
2929 """, (constraint_name, self._module))
2932 INSERT INTO ir_model_constraint
2933 (name, date_init, date_update, module, model, type)
2934 VALUES (%s, now() AT TIME ZONE 'UTC', now() AT TIME ZONE 'UTC',
2935 (SELECT id FROM ir_module_module WHERE name=%s),
2936 (SELECT id FROM ir_model WHERE model=%s), %s)""",
2937 (constraint_name, self._module, self._name, type))
2939 def _save_relation_table(self, cr, relation_table):
2941 Record the creation of a many2many for this model, to make it possible
2942 to delete it later when the module is uninstalled.
2945 SELECT 1 FROM ir_model_relation, ir_module_module
2946 WHERE ir_model_relation.module=ir_module_module.id
2947 AND ir_model_relation.name=%s
2948 AND ir_module_module.name=%s
2949 """, (relation_table, self._module))
2951 cr.execute("""INSERT INTO ir_model_relation (name, date_init, date_update, module, model)
2952 VALUES (%s, now() AT TIME ZONE 'UTC', now() AT TIME ZONE 'UTC',
2953 (SELECT id FROM ir_module_module WHERE name=%s),
2954 (SELECT id FROM ir_model WHERE model=%s))""",
2955 (relation_table, self._module, self._name))
2957 # checked version: for direct m2o starting from `self`
2958 def _m2o_add_foreign_key_checked(self, source_field, dest_model, ondelete):
2959 assert self.is_transient() or not dest_model.is_transient(), \
2960 'Many2One relationships from non-transient Model to TransientModel are forbidden'
2961 if self.is_transient() and not dest_model.is_transient():
2962 # TransientModel relationships to regular Models are annoying
2963 # usually because they could block deletion due to the FKs.
2964 # So unless stated otherwise we default them to ondelete=cascade.
2965 ondelete = ondelete or 'cascade'
2966 fk_def = (self._table, source_field, dest_model._table, ondelete or 'set null')
2967 self._foreign_keys.add(fk_def)
2968 _schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s", *fk_def)
2970 # unchecked version: for custom cases, such as m2m relationships
2971 def _m2o_add_foreign_key_unchecked(self, source_table, source_field, dest_model, ondelete):
2972 fk_def = (source_table, source_field, dest_model._table, ondelete or 'set null')
2973 self._foreign_keys.add(fk_def)
2974 _schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s", *fk_def)
2976 def _drop_constraint(self, cr, source_table, constraint_name):
2977 cr.execute("ALTER TABLE %s DROP CONSTRAINT %s" % (source_table,constraint_name))
2979 def _m2o_fix_foreign_key(self, cr, source_table, source_field, dest_model, ondelete):
2980 # Find FK constraint(s) currently established for the m2o field,
2981 # and see whether they are stale or not
2982 cr.execute("""SELECT confdeltype as ondelete_rule, conname as constraint_name,
2983 cl2.relname as foreign_table
2984 FROM pg_constraint as con, pg_class as cl1, pg_class as cl2,
2985 pg_attribute as att1, pg_attribute as att2
2986 WHERE con.conrelid = cl1.oid
2987 AND cl1.relname = %s
2988 AND con.confrelid = cl2.oid
2989 AND array_lower(con.conkey, 1) = 1
2990 AND con.conkey[1] = att1.attnum
2991 AND att1.attrelid = cl1.oid
2992 AND att1.attname = %s
2993 AND array_lower(con.confkey, 1) = 1
2994 AND con.confkey[1] = att2.attnum
2995 AND att2.attrelid = cl2.oid
2996 AND att2.attname = %s
2997 AND con.contype = 'f'""", (source_table, source_field, 'id'))
2998 constraints = cr.dictfetchall()
3000 if len(constraints) == 1:
3001 # Is it the right constraint?
3003 if cons['ondelete_rule'] != POSTGRES_CONFDELTYPES.get((ondelete or 'set null').upper(), 'a')\
3004 or cons['foreign_table'] != dest_model._table:
3005 # Wrong FK: drop it and recreate
3006 _schema.debug("Table '%s': dropping obsolete FK constraint: '%s'",
3007 source_table, cons['constraint_name'])
3008 self._drop_constraint(cr, source_table, cons['constraint_name'])
3010 # it's all good, nothing to do!
3013 # Multiple FKs found for the same field, drop them all, and re-create
3014 for cons in constraints:
3015 _schema.debug("Table '%s': dropping duplicate FK constraints: '%s'",
3016 source_table, cons['constraint_name'])
3017 self._drop_constraint(cr, source_table, cons['constraint_name'])
3019 # (re-)create the FK
3020 self._m2o_add_foreign_key_checked(source_field, dest_model, ondelete)
3024 def _auto_init(self, cr, context=None):
3027 Call _field_create and, unless _auto is False:
3029 - create the corresponding table in database for the model,
3030 - possibly add the parent columns in database,
3031 - possibly add the columns 'create_uid', 'create_date', 'write_uid',
3032 'write_date' in database if _log_access is True (the default),
3033 - report on database columns no more existing in _columns,
3034 - remove no more existing not null constraints,
3035 - alter existing database columns to match _columns,
3036 - create database tables to match _columns,
3037 - add database indices to match _columns,
3038 - save in self._foreign_keys a list a foreign keys to create (see
3042 self._foreign_keys = set()
3043 raise_on_invalid_object_name(self._name)
3046 store_compute = False
3048 update_custom_fields = context.get('update_custom_fields', False)
3049 self._field_create(cr, context=context)
3050 create = not self._table_exist(cr)
3051 if getattr(self, '_auto', True):
3054 self._create_table(cr)
3057 if self._parent_store:
3058 if not self._parent_columns_exist(cr):
3059 self._create_parent_columns(cr)
3060 store_compute = True
3062 # Create the create_uid, create_date, write_uid, write_date, columns if desired.
3063 if self._log_access:
3064 self._add_log_columns(cr)
3066 self._check_removed_columns(cr, log=False)
3068 # iterate on the "object columns"
3069 column_data = self._select_column_data(cr)
3071 for k, f in self._columns.iteritems():
3072 if k in MAGIC_COLUMNS:
3074 # Don't update custom (also called manual) fields
3075 if f.manual and not update_custom_fields:
3078 if isinstance(f, fields.one2many):
3079 self._o2m_raise_on_missing_reference(cr, f)
3081 elif isinstance(f, fields.many2many):
3082 self._m2m_raise_or_create_relation(cr, f)
3085 res = column_data.get(k)
3087 # The field is not found as-is in database, try if it
3088 # exists with an old name.
3089 if not res and hasattr(f, 'oldname'):
3090 res = column_data.get(f.oldname)
3092 cr.execute('ALTER TABLE "%s" RENAME "%s" TO "%s"' % (self._table, f.oldname, k))
3094 column_data[k] = res
3095 _schema.debug("Table '%s': renamed column '%s' to '%s'",
3096 self._table, f.oldname, k)
3098 # The field already exists in database. Possibly
3099 # change its type, rename it, drop it or change its
3102 f_pg_type = res['typname']
3103 f_pg_size = res['size']
3104 f_pg_notnull = res['attnotnull']
3105 if isinstance(f, fields.function) and not f.store and\
3106 not getattr(f, 'nodrop', False):
3107 _logger.info('column %s (%s) in table %s removed: converted to a function !\n',
3108 k, f.string, self._table)
3109 cr.execute('ALTER TABLE "%s" DROP COLUMN "%s" CASCADE' % (self._table, k))
3111 _schema.debug("Table '%s': dropped column '%s' with cascade",
3115 f_obj_type = get_pg_type(f) and get_pg_type(f)[0]
3120 ('text', 'char', pg_varchar(f.size), '::%s' % pg_varchar(f.size)),
3121 ('varchar', 'text', 'TEXT', ''),
3122 ('int4', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
3123 ('date', 'datetime', 'TIMESTAMP', '::TIMESTAMP'),
3124 ('timestamp', 'date', 'date', '::date'),
3125 ('numeric', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
3126 ('float8', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
3128 if f_pg_type == 'varchar' and f._type == 'char' and f_pg_size and (f.size is None or f_pg_size < f.size):
3129 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
3130 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, pg_varchar(f.size)))
3131 cr.execute('UPDATE "%s" SET "%s"=temp_change_size::%s' % (self._table, k, pg_varchar(f.size)))
3132 cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
3134 _schema.debug("Table '%s': column '%s' (type varchar) changed size from %s to %s",
3135 self._table, k, f_pg_size or 'unlimited', f.size or 'unlimited')
3137 if (f_pg_type==c[0]) and (f._type==c[1]):
3138 if f_pg_type != f_obj_type:
3140 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
3141 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, c[2]))
3142 cr.execute(('UPDATE "%s" SET "%s"=temp_change_size'+c[3]) % (self._table, k))
3143 cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
3145 _schema.debug("Table '%s': column '%s' changed type from %s to %s",
3146 self._table, k, c[0], c[1])
3149 if f_pg_type != f_obj_type:
3153 newname = k + '_moved' + str(i)
3154 cr.execute("SELECT count(1) FROM pg_class c,pg_attribute a " \
3155 "WHERE c.relname=%s " \
3156 "AND a.attname=%s " \
3157 "AND c.oid=a.attrelid ", (self._table, newname))
3158 if not cr.fetchone()[0]:
3162 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
3163 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO "%s"' % (self._table, k, newname))
3164 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
3165 cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,))
3166 _schema.debug("Table '%s': column '%s' has changed type (DB=%s, def=%s), data moved to column %s !",
3167 self._table, k, f_pg_type, f._type, newname)
3169 # if the field is required and hasn't got a NOT NULL constraint
3170 if f.required and f_pg_notnull == 0:
3171 # set the field to the default value if any
3172 if k in self._defaults:
3173 if callable(self._defaults[k]):
3174 default = self._defaults[k](self, cr, SUPERUSER_ID, context)
3176 default = self._defaults[k]
3178 if default is not None:
3179 ss = self._columns[k]._symbol_set
3180 query = 'UPDATE "%s" SET "%s"=%s WHERE "%s" is NULL' % (self._table, k, ss[0], k)
3181 cr.execute(query, (ss[1](default),))
3182 # add the NOT NULL constraint
3185 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False)
3187 _schema.debug("Table '%s': column '%s': added NOT NULL constraint",
3190 msg = "Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\
3191 "If you want to have it, you should update the records and execute manually:\n"\
3192 "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
3193 _schema.warning(msg, self._table, k, self._table, k)
3195 elif not f.required and f_pg_notnull == 1:
3196 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
3198 _schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
3201 indexname = '%s_%s_index' % (self._table, k)
3202 cr.execute("SELECT indexname FROM pg_indexes WHERE indexname = %s and tablename = %s", (indexname, self._table))
3203 res2 = cr.dictfetchall()
3204 if not res2 and f.select:
3205 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
3207 if f._type == 'text':
3208 # FIXME: for fields.text columns we should try creating GIN indexes instead (seems most suitable for an ERP context)
3209 msg = "Table '%s': Adding (b-tree) index for %s column '%s'."\
3210 "This is probably useless (does not work for fulltext search) and prevents INSERTs of long texts"\
3211 " because there is a length limit for indexable btree values!\n"\
3212 "Use a search view instead if you simply want to make the field searchable."
3213 _schema.warning(msg, self._table, f._type, k)
3214 if res2 and not f.select:
3215 cr.execute('DROP INDEX "%s_%s_index"' % (self._table, k))
3217 msg = "Table '%s': dropping index for column '%s' of type '%s' as it is not required anymore"
3218 _schema.debug(msg, self._table, k, f._type)
3220 if isinstance(f, fields.many2one) or (isinstance(f, fields.function) and f._type == 'many2one' and f.store):
3221 dest_model = self.pool.get(f._obj)
3222 if dest_model._table != 'ir_actions':
3223 self._m2o_fix_foreign_key(cr, self._table, k, dest_model, f.ondelete)
3225 # The field doesn't exist in database. Create it if necessary.
3227 if not isinstance(f, fields.function) or f.store:
3228 # add the missing field
3229 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
3230 cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,))
3231 _schema.debug("Table '%s': added column '%s' with definition=%s",
3232 self._table, k, get_pg_type(f)[1])
3235 if not create and k in self._defaults:
3236 if callable(self._defaults[k]):
3237 default = self._defaults[k](self, cr, SUPERUSER_ID, context)
3239 default = self._defaults[k]
3241 ss = self._columns[k]._symbol_set
3242 query = 'UPDATE "%s" SET "%s"=%s' % (self._table, k, ss[0])
3243 cr.execute(query, (ss[1](default),))
3245 _logger.debug("Table '%s': setting default value of new column %s", self._table, k)
3247 # remember the functions to call for the stored fields
3248 if isinstance(f, fields.function):
3250 if f.store is not True: # i.e. if f.store is a dict
3251 order = f.store[f.store.keys()[0]][2]
3252 todo_end.append((order, self._update_store, (f, k)))
3254 # and add constraints if needed
3255 if isinstance(f, fields.many2one) or (isinstance(f, fields.function) and f._type == 'many2one' and f.store):
3256 if not self.pool.get(f._obj):
3257 raise except_orm('Programming Error', 'There is no reference available for %s' % (f._obj,))
3258 dest_model = self.pool.get(f._obj)
3259 ref = dest_model._table
3260 # ir_actions is inherited so foreign key doesn't work on it
3261 if ref != 'ir_actions':
3262 self._m2o_add_foreign_key_checked(k, dest_model, f.ondelete)
3264 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
3268 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False)
3269 _schema.debug("Table '%s': column '%s': added a NOT NULL constraint",
3272 msg = "WARNING: unable to set column %s of table %s not null !\n"\
3273 "Try to re-run: openerp-server --update=module\n"\
3274 "If it doesn't work, update records and execute manually:\n"\
3275 "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
3276 _logger.warning(msg, k, self._table, self._table, k)
3280 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
3281 create = not bool(cr.fetchone())
3283 cr.commit() # start a new transaction
3285 if getattr(self, '_auto', True):
3286 self._add_sql_constraints(cr)
3289 self._execute_sql(cr)
3292 self._parent_store_compute(cr)
3297 def _auto_end(self, cr, context=None):
3298 """ Create the foreign keys recorded by _auto_init. """
3299 for t, k, r, d in self._foreign_keys:
3300 cr.execute('ALTER TABLE "%s" ADD FOREIGN KEY ("%s") REFERENCES "%s" ON DELETE %s' % (t, k, r, d))
3301 self._save_constraint(cr, "%s_%s_fkey" % (t, k), 'f')
3303 del self._foreign_keys
3306 def _table_exist(self, cr):
3307 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
3311 def _create_table(self, cr):
3312 cr.execute('CREATE TABLE "%s" (id SERIAL NOT NULL, PRIMARY KEY(id))' % (self._table,))
3313 cr.execute(("COMMENT ON TABLE \"%s\" IS %%s" % self._table), (self._description,))
3314 _schema.debug("Table '%s': created", self._table)
3317 def _parent_columns_exist(self, cr):
3318 cr.execute("""SELECT c.relname
3319 FROM pg_class c, pg_attribute a
3320 WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
3321 """, (self._table, 'parent_left'))
3325 def _create_parent_columns(self, cr):
3326 cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_left" INTEGER' % (self._table,))
3327 cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_right" INTEGER' % (self._table,))
3328 if 'parent_left' not in self._columns:
3329 _logger.error('create a column parent_left on object %s: fields.integer(\'Left Parent\', select=1)',
3331 _schema.debug("Table '%s': added column '%s' with definition=%s",
3332 self._table, 'parent_left', 'INTEGER')
3333 elif not self._columns['parent_left'].select:
3334 _logger.error('parent_left column on object %s must be indexed! Add select=1 to the field definition)',
3336 if 'parent_right' not in self._columns:
3337 _logger.error('create a column parent_right on object %s: fields.integer(\'Right Parent\', select=1)',
3339 _schema.debug("Table '%s': added column '%s' with definition=%s",
3340 self._table, 'parent_right', 'INTEGER')
3341 elif not self._columns['parent_right'].select:
3342 _logger.error('parent_right column on object %s must be indexed! Add select=1 to the field definition)',
3344 if self._columns[self._parent_name].ondelete not in ('cascade', 'restrict'):
3345 _logger.error("The column %s on object %s must be set as ondelete='cascade' or 'restrict'",
3346 self._parent_name, self._name)
3351 def _add_log_columns(self, cr):
3352 for field, field_def in LOG_ACCESS_COLUMNS.iteritems():
3355 FROM pg_class c, pg_attribute a
3356 WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
3357 """, (self._table, field))
3359 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, field, field_def))
3361 _schema.debug("Table '%s': added column '%s' with definition=%s",
3362 self._table, field, field_def)
3365 def _select_column_data(self, cr):
3366 # attlen is the number of bytes necessary to represent the type when
3367 # the type has a fixed size. If the type has a varying size attlen is
3368 # -1 and atttypmod is the size limit + 4, or -1 if there is no limit.
3369 cr.execute("SELECT c.relname,a.attname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,t.typname,CASE WHEN a.attlen=-1 THEN (CASE WHEN a.atttypmod=-1 THEN 0 ELSE a.atttypmod-4 END) ELSE a.attlen END as size " \
3370 "FROM pg_class c,pg_attribute a,pg_type t " \
3371 "WHERE c.relname=%s " \
3372 "AND c.oid=a.attrelid " \
3373 "AND a.atttypid=t.oid", (self._table,))
3374 return dict(map(lambda x: (x['attname'], x),cr.dictfetchall()))
3377 def _o2m_raise_on_missing_reference(self, cr, f):
3378 # TODO this check should be a method on fields.one2many.
3380 other = self.pool.get(f._obj)
3382 # TODO the condition could use fields_get_keys().
3383 if f._fields_id not in other._columns.keys():
3384 if f._fields_id not in other._inherit_fields.keys():
3385 raise except_orm('Programming Error', "There is no reference field '%s' found for '%s'" % (f._fields_id, f._obj,))
3387 def _m2m_raise_or_create_relation(self, cr, f):
3388 m2m_tbl, col1, col2 = f._sql_names(self)
3389 self._save_relation_table(cr, m2m_tbl)
3390 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (m2m_tbl,))
3391 if not cr.dictfetchall():
3392 if not self.pool.get(f._obj):
3393 raise except_orm('Programming Error', 'Many2Many destination model does not exist: `%s`' % (f._obj,))
3394 dest_model = self.pool.get(f._obj)
3395 ref = dest_model._table
3396 cr.execute('CREATE TABLE "%s" ("%s" INTEGER NOT NULL, "%s" INTEGER NOT NULL, UNIQUE("%s","%s"))' % (m2m_tbl, col1, col2, col1, col2))
3397 # create foreign key references with ondelete=cascade, unless the targets are SQL views
3398 cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (ref,))
3399 if not cr.fetchall():
3400 self._m2o_add_foreign_key_unchecked(m2m_tbl, col2, dest_model, 'cascade')
3401 cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (self._table,))
3402 if not cr.fetchall():
3403 self._m2o_add_foreign_key_unchecked(m2m_tbl, col1, self, 'cascade')
3405 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col1, m2m_tbl, col1))
3406 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col2, m2m_tbl, col2))
3407 cr.execute("COMMENT ON TABLE \"%s\" IS 'RELATION BETWEEN %s AND %s'" % (m2m_tbl, self._table, ref))
3409 _schema.debug("Create table '%s': m2m relation between '%s' and '%s'", m2m_tbl, self._table, ref)
3412 def _add_sql_constraints(self, cr):
3415 Modify this model's database table constraints so they match the one in
3419 def unify_cons_text(txt):
3420 return txt.lower().replace(', ',',').replace(' (','(')
3422 for (key, con, _) in self._sql_constraints:
3423 conname = '%s_%s' % (self._table, key)
3425 self._save_constraint(cr, conname, 'u')
3426 cr.execute("SELECT conname, pg_catalog.pg_get_constraintdef(oid, true) as condef FROM pg_constraint where conname=%s", (conname,))
3427 existing_constraints = cr.dictfetchall()
3431 'query': 'ALTER TABLE "%s" DROP CONSTRAINT "%s"' % (self._table, conname, ),
3432 'msg_ok': "Table '%s': dropped constraint '%s'. Reason: its definition changed from '%%s' to '%s'" % (
3433 self._table, conname, con),
3434 'msg_err': "Table '%s': unable to drop \'%s\' constraint !" % (self._table, con),
3439 'query': 'ALTER TABLE "%s" ADD CONSTRAINT "%s" %s' % (self._table, conname, con,),
3440 'msg_ok': "Table '%s': added constraint '%s' with definition=%s" % (self._table, conname, con),
3441 'msg_err': "Table '%s': unable to add \'%s\' constraint !\n If you want to have it, you should update the records and execute manually:\n%%s" % (
3447 if not existing_constraints:
3448 # constraint does not exists:
3449 sql_actions['add']['execute'] = True
3450 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
3451 elif unify_cons_text(con) not in [unify_cons_text(item['condef']) for item in existing_constraints]:
3452 # constraint exists but its definition has changed:
3453 sql_actions['drop']['execute'] = True
3454 sql_actions['drop']['msg_ok'] = sql_actions['drop']['msg_ok'] % (existing_constraints[0]['condef'].lower(), )
3455 sql_actions['add']['execute'] = True
3456 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
3458 # we need to add the constraint:
3459 sql_actions = [item for item in sql_actions.values()]
3460 sql_actions.sort(key=lambda x: x['order'])
3461 for sql_action in [action for action in sql_actions if action['execute']]:
3463 cr.execute(sql_action['query'])
3465 _schema.debug(sql_action['msg_ok'])
3467 _schema.warning(sql_action['msg_err'])
3471 def _execute_sql(self, cr):
3472 """ Execute the SQL code from the _sql attribute (if any)."""
3473 if hasattr(self, "_sql"):
3474 for line in self._sql.split(';'):
3475 line2 = line.replace('\n', '').strip()
3481 # Update objects that uses this one to update their _inherits fields
3484 def _inherits_reload_src(self):
3485 """ Recompute the _inherit_fields mapping on each _inherits'd child model."""
3486 for obj in self.pool.models.values():
3487 if self._name in obj._inherits:
3488 obj._inherits_reload()
3491 def _inherits_reload(self):
3492 """ Recompute the _inherit_fields mapping.
3494 This will also call itself on each inherits'd child model.
3498 for table in self._inherits:
3499 other = self.pool.get(table)
3500 for col in other._columns.keys():
3501 res[col] = (table, self._inherits[table], other._columns[col], table)
3502 for col in other._inherit_fields.keys():
3503 res[col] = (table, self._inherits[table], other._inherit_fields[col][2], other._inherit_fields[col][3])
3504 self._inherit_fields = res
3505 self._all_columns = self._get_column_infos()
3506 self._inherits_reload_src()
3509 def _get_column_infos(self):
3510 """Returns a dict mapping all fields names (direct fields and
3511 inherited field via _inherits) to a ``column_info`` struct
3512 giving detailed columns """
3514 for k, (parent, m2o, col, original_parent) in self._inherit_fields.iteritems():
3515 result[k] = fields.column_info(k, col, parent, m2o, original_parent)
3516 for k, col in self._columns.iteritems():
3517 result[k] = fields.column_info(k, col)
3521 def _inherits_check(self):
3522 for table, field_name in self._inherits.items():
3523 if field_name not in self._columns:
3524 _logger.info('Missing many2one field definition for _inherits reference "%s" in "%s", using default one.', field_name, self._name)
3525 self._columns[field_name] = fields.many2one(table, string="Automatically created field to link to parent %s" % table,
3526 required=True, ondelete="cascade")
3527 elif not self._columns[field_name].required or self._columns[field_name].ondelete.lower() not in ("cascade", "restrict"):
3528 _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)
3529 self._columns[field_name].required = True
3530 self._columns[field_name].ondelete = "cascade"
3532 #def __getattr__(self, name):
3534 # Proxies attribute accesses to the `inherits` parent so we can call methods defined on the inherited parent
3535 # (though inherits doesn't use Python inheritance).
3536 # Handles translating between local ids and remote ids.
3537 # Known issue: doesn't work correctly when using python's own super(), don't involve inherit-based inheritance
3538 # when you have inherits.
3540 # for model, field in self._inherits.iteritems():
3541 # proxy = self.pool.get(model)
3542 # if hasattr(proxy, name):
3543 # attribute = getattr(proxy, name)
3544 # if not hasattr(attribute, '__call__'):
3548 # return super(orm, self).__getattr__(name)
3550 # def _proxy(cr, uid, ids, *args, **kwargs):
3551 # objects = self.browse(cr, uid, ids, kwargs.get('context', None))
3552 # lst = [obj[field].id for obj in objects if obj[field]]
3553 # return getattr(proxy, name)(cr, uid, lst, *args, **kwargs)
3558 def fields_get(self, cr, user, allfields=None, context=None, write_access=True):
3559 """ Return the definition of each field.
3561 The returned value is a dictionary (indiced by field name) of
3562 dictionaries. The _inherits'd fields are included. The string, help,
3563 and selection (if present) attributes are translated.
3565 :param cr: database cursor
3566 :param user: current user id
3567 :param allfields: list of fields
3568 :param context: context arguments, like lang, time zone
3569 :return: dictionary of field dictionaries, each one describing a field of the business object
3570 :raise AccessError: * if user has no create/write rights on the requested object
3576 write_access = self.check_access_rights(cr, user, 'write', raise_exception=False) \
3577 or self.check_access_rights(cr, user, 'create', raise_exception=False)
3581 translation_obj = self.pool.get('ir.translation')
3582 for parent in self._inherits:
3583 res.update(self.pool.get(parent).fields_get(cr, user, allfields, context))
3585 for f, field in self._columns.iteritems():
3586 if (allfields and f not in allfields) or \
3587 (field.groups and not self.user_has_groups(cr, user, groups=field.groups, context=context)):
3590 res[f] = fields.field_to_dict(self, cr, user, field, context=context)
3592 if not write_access:
3593 res[f]['readonly'] = True
3594 res[f]['states'] = {}
3596 if 'lang' in context:
3597 if 'string' in res[f]:
3598 res_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'field', context['lang'])
3600 res[f]['string'] = res_trans
3601 if 'help' in res[f]:
3602 help_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'help', context['lang'])
3604 res[f]['help'] = help_trans
3605 if 'selection' in res[f]:
3606 if isinstance(field.selection, (tuple, list)):
3607 sel = field.selection
3609 for key, val in sel:
3612 val2 = translation_obj._get_source(cr, user, self._name + ',' + f, 'selection', context['lang'], val)
3613 sel2.append((key, val2 or val))
3614 res[f]['selection'] = sel2
3618 def check_field_access_rights(self, cr, user, operation, fields, context=None):
3620 Check the user access rights on the given fields. This raises Access
3621 Denied if the user does not have the rights. Otherwise it returns the
3622 fields (as is if the fields is not falsy, or the readable/writable
3623 fields if fields is falsy).
3626 """Predicate to test if the user has access to the given field name."""
3627 # Ignore requested field if it doesn't exist. This is ugly but
3628 # it seems to happen at least with 'name_alias' on res.partner.
3629 if field_name not in self._all_columns:
3631 field = self._all_columns[field_name].column
3632 if user != SUPERUSER_ID and field.groups:
3633 return self.user_has_groups(cr, user, groups=field.groups, context=context)
3637 fields = filter(p, self._all_columns.keys())
3639 filtered_fields = filter(lambda a: not p(a), fields)
3641 _logger.warning('Access Denied by ACLs for operation: %s, uid: %s, model: %s, fields: %s', operation, user, self._name, ', '.join(filtered_fields))
3644 _('The requested operation cannot be completed due to security restrictions. '
3645 'Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \
3646 (self._description, operation))
3649 def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
3650 """ Read records with given ids with the given fields
3652 :param cr: database cursor
3653 :param user: current user id
3654 :param ids: id or list of the ids of the records to read
3655 :param fields: optional list of field names to return (default: all fields would be returned)
3656 :type fields: list (example ['field_name_1', ...])
3657 :param context: optional context dictionary - it may contains keys for specifying certain options
3658 like ``context_lang``, ``context_tz`` to alter the results of the call.
3659 A special ``bin_size`` boolean flag may also be passed in the context to request the
3660 value of all fields.binary columns to be returned as the size of the binary instead of its
3661 contents. This can also be selectively overriden by passing a field-specific flag
3662 in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field.
3663 Note: The ``bin_size_XXX`` form is new in OpenERP v6.0.
3664 :return: list of dictionaries((dictionary per record asked)) with requested field values
3665 :rtype: [{‘name_of_the_field’: value, ...}, ...]
3666 :raise AccessError: * if user has no read rights on the requested object
3667 * if user tries to bypass access rules for read on the requested object
3673 self.check_access_rights(cr, user, 'read')
3674 fields = self.check_field_access_rights(cr, user, 'read', fields)
3675 if isinstance(ids, (int, long)):
3679 select = map(lambda x: isinstance(x, dict) and x['id'] or x, select)
3680 result = self._read_flat(cr, user, select, fields, context, load)
3683 for key, v in r.items():
3687 if isinstance(ids, (int, long, dict)):
3688 return result and result[0] or False
3691 def _read_flat(self, cr, user, ids, fields_to_read, context=None, load='_classic_read'):
3696 if fields_to_read is None:
3697 fields_to_read = self._columns.keys()
3699 fields_to_read = list(set(fields_to_read))
3701 # all inherited fields + all non inherited fields for which the attribute whose name is in load is True
3702 fields_pre = [f for f in fields_to_read if
3703 f == self.CONCURRENCY_CHECK_FIELD
3704 or (f in self._columns and getattr(self._columns[f], '_classic_write'))
3705 ] + self._inherits.values()
3709 def convert_field(f):
3710 f_qual = '%s."%s"' % (self._table, f) # need fully-qualified references in case len(tables) > 1
3711 if f in ('create_date', 'write_date'):
3712 return "date_trunc('second', %s) as %s" % (f_qual, f)
3713 if f == self.CONCURRENCY_CHECK_FIELD:
3714 if self._log_access:
3715 return "COALESCE(%s.write_date, %s.create_date, (now() at time zone 'UTC'))::timestamp AS %s" % (self._table, self._table, f,)
3716 return "(now() at time zone 'UTC')::timestamp AS %s" % (f,)
3717 if isinstance(self._columns[f], fields.binary) and context.get('bin_size', False):
3718 return 'length(%s) as "%s"' % (f_qual, f)
3721 # Construct a clause for the security rules.
3722 # 'tables' hold the list of tables necessary for the SELECT including the ir.rule clauses,
3723 # or will at least contain self._table.
3724 rule_clause, rule_params, tables = self.pool.get('ir.rule').domain_get(cr, user, self._name, 'read', context=context)
3726 fields_pre2 = map(convert_field, fields_pre)
3727 order_by = self._parent_order or self._order
3728 select_fields = ','.join(fields_pre2 + ['%s.id' % self._table])
3729 query = 'SELECT %s FROM %s WHERE %s.id IN %%s' % (select_fields, ','.join(tables), self._table)
3731 query += " AND " + (' OR '.join(rule_clause))
3732 query += " ORDER BY " + order_by
3733 for sub_ids in cr.split_for_in_conditions(ids):
3734 cr.execute(query, [tuple(sub_ids)] + rule_params)
3735 results = cr.dictfetchall()
3736 result_ids = [x['id'] for x in results]
3737 self._check_record_rules_result_count(cr, user, sub_ids, result_ids, 'read', context=context)
3740 self.check_access_rule(cr, user, ids, 'read', context=context)
3741 res = map(lambda x: {'id': x}, ids)
3743 if context.get('lang'):
3744 for f in fields_pre:
3745 if f == self.CONCURRENCY_CHECK_FIELD:
3747 if self._columns[f].translate:
3748 ids = [x['id'] for x in res]
3749 #TODO: optimize out of this loop
3750 res_trans = self.pool.get('ir.translation')._get_ids(cr, user, self._name+','+f, 'model', context['lang'], ids)
3752 r[f] = res_trans.get(r['id'], False) or r[f]
3754 for table in self._inherits:
3755 col = self._inherits[table]
3756 cols = [x for x in intersect(self._inherit_fields.keys(), fields_to_read) if x not in self._columns.keys()]
3759 res2 = self.pool.get(table).read(cr, user, [x[col] for x in res], cols, context, load)
3767 if not record[col]: # if the record is deleted from _inherits table?
3769 record.update(res3[record[col]])
3770 if col not in fields_to_read:
3773 # all fields which need to be post-processed by a simple function (symbol_get)
3774 fields_post = filter(lambda x: x in self._columns and self._columns[x]._symbol_get, fields_to_read)
3777 for f in fields_post:
3778 r[f] = self._columns[f]._symbol_get(r[f])
3779 ids = [x['id'] for x in res]
3781 # all non inherited fields for which the attribute whose name is in load is False
3782 fields_post = filter(lambda x: x in self._columns and not getattr(self._columns[x], load), fields_to_read)
3784 # Compute POST fields
3786 for f in fields_post:
3787 todo.setdefault(self._columns[f]._multi, [])
3788 todo[self._columns[f]._multi].append(f)
3789 for key, val in todo.items():
3791 res2 = self._columns[val[0]].get(cr, self, ids, val, user, context=context, values=res)
3792 assert res2 is not None, \
3793 'The function field "%s" on the "%s" model returned None\n' \
3794 '(a dictionary was expected).' % (val[0], self._name)
3797 if isinstance(res2[record['id']], str): res2[record['id']] = eval(res2[record['id']]) #TOCHECK : why got string instend of dict in python2.6
3798 multi_fields = res2.get(record['id'],{})
3800 record[pos] = multi_fields.get(pos,[])
3803 res2 = self._columns[f].get(cr, self, ids, f, user, context=context, values=res)
3806 record[f] = res2[record['id']]
3810 # Warn about deprecated fields now that fields_pre and fields_post are computed
3811 # Explicitly use list() because we may receive tuples
3812 for f in list(fields_pre) + list(fields_post):
3813 field_column = self._all_columns.get(f) and self._all_columns.get(f).column
3814 if field_column and field_column.deprecated:
3815 _logger.warning('Field %s.%s is deprecated: %s', self._name, f, field_column.deprecated)
3819 for field in vals.copy():
3821 if field in self._columns:
3822 fobj = self._columns[field]
3829 for group in groups:
3830 module = group.split(".")[0]
3831 grp = group.split(".")[1]
3832 cr.execute("select count(*) from res_groups_users_rel where gid IN (select res_id from ir_model_data where name=%s and module=%s and model=%s) and uid=%s", \
3833 (grp, module, 'res.groups', user))
3834 readonly = cr.fetchall()
3835 if readonly[0][0] >= 1:
3838 elif readonly[0][0] == 0:
3844 if type(vals[field]) == type([]):
3846 elif type(vals[field]) == type(0.0):
3848 elif type(vals[field]) == type(''):
3849 vals[field] = '=No Permission='
3854 # TODO check READ access
3855 def perm_read(self, cr, user, ids, context=None, details=True):
3857 Returns some metadata about the given records.
3859 :param details: if True, \*_uid fields are replaced with the name of the user
3860 :return: list of ownership dictionaries for each requested record
3861 :rtype: list of dictionaries with the following keys:
3864 * create_uid: user who created the record
3865 * create_date: date when the record was created
3866 * write_uid: last user who changed the record
3867 * write_date: date of the last change to the record
3868 * xmlid: XML ID to use to refer to this record (if there is one), in format ``module.name``
3875 uniq = isinstance(ids, (int, long))
3879 if self._log_access:
3880 fields += ['create_uid', 'create_date', 'write_uid', 'write_date']
3881 quoted_table = '"%s"' % self._table
3882 fields_str = ",".join('%s.%s'%(quoted_table, field) for field in fields)
3883 query = '''SELECT %s, __imd.module, __imd.name
3884 FROM %s LEFT JOIN ir_model_data __imd
3885 ON (__imd.model = %%s and __imd.res_id = %s.id)
3886 WHERE %s.id IN %%s''' % (fields_str, quoted_table, quoted_table, quoted_table)
3887 cr.execute(query, (self._name, tuple(ids)))
3888 res = cr.dictfetchall()
3891 r[key] = r[key] or False
3892 if details and key in ('write_uid', 'create_uid') and r[key]:
3894 r[key] = self.pool.get('res.users').name_get(cr, user, [r[key]])[0]
3896 pass # Leave the numeric uid there
3897 r['xmlid'] = ("%(module)s.%(name)s" % r) if r['name'] else False
3898 del r['name'], r['module']
3903 def _check_concurrency(self, cr, ids, context):
3906 if not (context.get(self.CONCURRENCY_CHECK_FIELD) and self._log_access):
3908 check_clause = "(id = %s AND %s < COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp)"
3909 for sub_ids in cr.split_for_in_conditions(ids):
3912 id_ref = "%s,%s" % (self._name, id)
3913 update_date = context[self.CONCURRENCY_CHECK_FIELD].pop(id_ref, None)
3915 ids_to_check.extend([id, update_date])
3916 if not ids_to_check:
3918 cr.execute("SELECT id FROM %s WHERE %s" % (self._table, " OR ".join([check_clause]*(len(ids_to_check)/2))), tuple(ids_to_check))
3921 # mention the first one only to keep the error message readable
3922 raise except_orm('ConcurrencyException', _('A document was modified since you last viewed it (%s:%d)') % (self._description, res[0]))
3924 def _check_record_rules_result_count(self, cr, uid, ids, result_ids, operation, context=None):
3925 """Verify the returned rows after applying record rules matches
3926 the length of `ids`, and raise an appropriate exception if it does not.
3928 ids, result_ids = set(ids), set(result_ids)
3929 missing_ids = ids - result_ids
3931 # Attempt to distinguish record rule restriction vs deleted records,
3932 # to provide a more specific error message - check if the missinf
3933 cr.execute('SELECT id FROM ' + self._table + ' WHERE id IN %s', (tuple(missing_ids),))
3935 # the missing ids are (at least partially) hidden by access rules
3936 if uid == SUPERUSER_ID:
3938 _logger.warning('Access Denied by record rules for operation: %s, uid: %s, model: %s', operation, uid, self._name)
3939 raise except_orm(_('Access Denied'),
3940 _('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \
3941 (self._description, operation))
3943 # If we get here, the missing_ids are not in the database
3944 if operation in ('read','unlink'):
3945 # No need to warn about deleting an already deleted record.
3946 # And no error when reading a record that was deleted, to prevent spurious
3947 # errors for non-transactional search/read sequences coming from clients
3949 _logger.warning('Failed operation on deleted record(s): %s, uid: %s, model: %s', operation, uid, self._name)
3950 raise except_orm(_('Missing document(s)'),
3951 _('One of the documents you are trying to access has been deleted, please try again after refreshing.'))
3954 def check_access_rights(self, cr, uid, operation, raise_exception=True): # no context on purpose.
3955 """Verifies that the operation given by ``operation`` is allowed for the user
3956 according to the access rights."""
3957 return self.pool.get('ir.model.access').check(cr, uid, self._name, operation, raise_exception)
3959 def check_access_rule(self, cr, uid, ids, operation, context=None):
3960 """Verifies that the operation given by ``operation`` is allowed for the user
3961 according to ir.rules.
3963 :param operation: one of ``write``, ``unlink``
3964 :raise except_orm: * if current ir.rules do not permit this operation.
3965 :return: None if the operation is allowed
3967 if uid == SUPERUSER_ID:
3970 if self.is_transient():
3971 # Only one single implicit access rule for transient models: owner only!
3972 # This is ok to hardcode because we assert that TransientModels always
3973 # have log_access enabled so that the create_uid column is always there.
3974 # And even with _inherits, these fields are always present in the local
3975 # table too, so no need for JOINs.
3976 cr.execute("""SELECT distinct create_uid
3978 WHERE id IN %%s""" % self._table, (tuple(ids),))
3979 uids = [x[0] for x in cr.fetchall()]
3980 if len(uids) != 1 or uids[0] != uid:
3981 raise except_orm(_('Access Denied'),
3982 _('For this kind of document, you may only access records you created yourself.\n\n(Document type: %s)') % (self._description,))
3984 where_clause, where_params, tables = self.pool.get('ir.rule').domain_get(cr, uid, self._name, operation, context=context)
3986 where_clause = ' and ' + ' and '.join(where_clause)
3987 for sub_ids in cr.split_for_in_conditions(ids):
3988 cr.execute('SELECT ' + self._table + '.id FROM ' + ','.join(tables) +
3989 ' WHERE ' + self._table + '.id IN %s' + where_clause,
3990 [sub_ids] + where_params)
3991 returned_ids = [x['id'] for x in cr.dictfetchall()]
3992 self._check_record_rules_result_count(cr, uid, sub_ids, returned_ids, operation, context=context)
3994 def _workflow_trigger(self, cr, uid, ids, trigger, context=None):
3995 """Call given workflow trigger as a result of a CRUD operation"""
3996 wf_service = netsvc.LocalService("workflow")
3998 getattr(wf_service, trigger)(uid, self._name, res_id, cr)
4000 def _workflow_signal(self, cr, uid, ids, signal, context=None):
4001 """Send given workflow signal and return a dict mapping ids to workflow results"""
4002 wf_service = netsvc.LocalService("workflow")
4005 result[res_id] = wf_service.trg_validate(uid, self._name, res_id, signal, cr)
4008 def unlink(self, cr, uid, ids, context=None):
4010 Delete records with given ids
4012 :param cr: database cursor
4013 :param uid: current user id
4014 :param ids: id or list of ids
4015 :param context: (optional) context arguments, like lang, time zone
4017 :raise AccessError: * if user has no unlink rights on the requested object
4018 * if user tries to bypass access rules for unlink on the requested object
4019 :raise UserError: if the record is default property for other records
4024 if isinstance(ids, (int, long)):
4027 result_store = self._store_get_values(cr, uid, ids, self._all_columns.keys(), context)
4029 self._check_concurrency(cr, ids, context)
4031 self.check_access_rights(cr, uid, 'unlink')
4033 ir_property = self.pool.get('ir.property')
4035 # Check if the records are used as default properties.
4036 domain = [('res_id', '=', False),
4037 ('value_reference', 'in', ['%s,%s' % (self._name, i) for i in ids]),
4039 if ir_property.search(cr, uid, domain, context=context):
4040 raise except_orm(_('Error'), _('Unable to delete this document because it is used as a default property'))
4042 # Delete the records' properties.
4043 property_ids = ir_property.search(cr, uid, [('res_id', 'in', ['%s,%s' % (self._name, i) for i in ids])], context=context)
4044 ir_property.unlink(cr, uid, property_ids, context=context)
4046 self._workflow_trigger(cr, uid, ids, 'trg_delete', context=context)
4048 self.check_access_rule(cr, uid, ids, 'unlink', context=context)
4049 pool_model_data = self.pool.get('ir.model.data')
4050 ir_values_obj = self.pool.get('ir.values')
4051 for sub_ids in cr.split_for_in_conditions(ids):
4052 cr.execute('delete from ' + self._table + ' ' \
4053 'where id IN %s', (sub_ids,))
4055 # Removing the ir_model_data reference if the record being deleted is a record created by xml/csv file,
4056 # as these are not connected with real database foreign keys, and would be dangling references.
4057 # Note: following steps performed as admin to avoid access rights restrictions, and with no context
4058 # to avoid possible side-effects during admin calls.
4059 # Step 1. Calling unlink of ir_model_data only for the affected IDS
4060 reference_ids = pool_model_data.search(cr, SUPERUSER_ID, [('res_id','in',list(sub_ids)),('model','=',self._name)])
4061 # Step 2. Marching towards the real deletion of referenced records
4063 pool_model_data.unlink(cr, SUPERUSER_ID, reference_ids)
4065 # For the same reason, removing the record relevant to ir_values
4066 ir_value_ids = ir_values_obj.search(cr, uid,
4067 ['|',('value','in',['%s,%s' % (self._name, sid) for sid in sub_ids]),'&',('res_id','in',list(sub_ids)),('model','=',self._name)],
4070 ir_values_obj.unlink(cr, uid, ir_value_ids, context=context)
4072 for order, object, store_ids, fields in result_store:
4073 if object == self._name:
4074 effective_store_ids = list(set(store_ids) - set(ids))
4076 effective_store_ids = store_ids
4077 if effective_store_ids:
4078 obj = self.pool.get(object)
4079 cr.execute('select id from '+obj._table+' where id IN %s', (tuple(effective_store_ids),))
4080 rids = map(lambda x: x[0], cr.fetchall())
4082 obj._store_set_values(cr, uid, rids, fields, context)
4089 def write(self, cr, user, ids, vals, context=None):
4091 Update records with given ids with the given field values
4093 :param cr: database cursor
4094 :param user: current user id
4096 :param ids: object id or list of object ids to update according to **vals**
4097 :param vals: field values to update, e.g {'field_name': new_field_value, ...}
4098 :type vals: dictionary
4099 :param context: (optional) context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...}
4100 :type context: dictionary
4102 :raise AccessError: * if user has no write rights on the requested object
4103 * if user tries to bypass access rules for write on the requested object
4104 :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
4105 :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)
4107 **Note**: The type of field values to pass in ``vals`` for relationship fields is specific:
4109 + For a many2many field, a list of tuples is expected.
4110 Here is the list of tuple that are accepted, with the corresponding semantics ::
4112 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
4113 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
4114 (2, ID) remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well)
4115 (3, ID) cut the link to the linked record with id = ID (delete the relationship between the two objects but does not delete the target object itself)
4116 (4, ID) link to existing record with id = ID (adds a relationship)
4117 (5) unlink all (like using (3,ID) for all linked records)
4118 (6, 0, [IDs]) replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)
4121 [(6, 0, [8, 5, 6, 4])] sets the many2many to ids [8, 5, 6, 4]
4123 + For a one2many field, a lits of tuples is expected.
4124 Here is the list of tuple that are accepted, with the corresponding semantics ::
4126 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
4127 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
4128 (2, ID) remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well)
4131 [(0, 0, {'field_name':field_value_record1, ...}), (0, 0, {'field_name':field_value_record2, ...})]
4133 + For a many2one field, simply use the ID of target record, which must already exist, or ``False`` to remove the link.
4134 + For a reference field, use a string with the model name, a comma, and the target object id (example: ``'product.product, 5'``)
4138 self.check_field_access_rights(cr, user, 'write', vals.keys())
4139 for field in vals.copy():
4141 if field in self._columns:
4142 fobj = self._columns[field]
4143 elif field in self._inherit_fields:
4144 fobj = self._inherit_fields[field][2]
4151 for group in groups:
4152 module = group.split(".")[0]
4153 grp = group.split(".")[1]
4154 cr.execute("select count(*) from res_groups_users_rel where gid IN (select res_id from ir_model_data where name=%s and module=%s and model=%s) and uid=%s", \
4155 (grp, module, 'res.groups', user))
4156 readonly = cr.fetchall()
4157 if readonly[0][0] >= 1:
4168 if isinstance(ids, (int, long)):
4171 self._check_concurrency(cr, ids, context)
4172 self.check_access_rights(cr, user, 'write')
4174 result = self._store_get_values(cr, user, ids, vals.keys(), context) or []
4176 # No direct update of parent_left/right
4177 vals.pop('parent_left', None)
4178 vals.pop('parent_right', None)
4180 parents_changed = []
4181 parent_order = self._parent_order or self._order
4182 if self._parent_store and (self._parent_name in vals):
4183 # The parent_left/right computation may take up to
4184 # 5 seconds. No need to recompute the values if the
4185 # parent is the same.
4186 # Note: to respect parent_order, nodes must be processed in
4187 # order, so ``parents_changed`` must be ordered properly.
4188 parent_val = vals[self._parent_name]
4190 query = "SELECT id FROM %s WHERE id IN %%s AND (%s != %%s OR %s IS NULL) ORDER BY %s" % \
4191 (self._table, self._parent_name, self._parent_name, parent_order)
4192 cr.execute(query, (tuple(ids), parent_val))
4194 query = "SELECT id FROM %s WHERE id IN %%s AND (%s IS NOT NULL) ORDER BY %s" % \
4195 (self._table, self._parent_name, parent_order)
4196 cr.execute(query, (tuple(ids),))
4197 parents_changed = map(operator.itemgetter(0), cr.fetchall())
4204 totranslate = context.get('lang', False) and (context['lang'] != 'en_US')
4206 field_column = self._all_columns.get(field) and self._all_columns.get(field).column
4207 if field_column and field_column.deprecated:
4208 _logger.warning('Field %s.%s is deprecated: %s', self._name, field, field_column.deprecated)
4209 if field in self._columns:
4210 if self._columns[field]._classic_write and not (hasattr(self._columns[field], '_fnct_inv')):
4211 if (not totranslate) or not self._columns[field].translate:
4212 upd0.append('"'+field+'"='+self._columns[field]._symbol_set[0])
4213 upd1.append(self._columns[field]._symbol_set[1](vals[field]))
4214 direct.append(field)
4216 upd_todo.append(field)
4218 updend.append(field)
4219 if field in self._columns \
4220 and hasattr(self._columns[field], 'selection') \
4222 self._check_selection_field_value(cr, user, field, vals[field], context=context)
4224 if self._log_access:
4225 upd0.append('write_uid=%s')
4226 upd0.append("write_date=(now() at time zone 'UTC')")
4230 self.check_access_rule(cr, user, ids, 'write', context=context)
4231 for sub_ids in cr.split_for_in_conditions(ids):
4232 cr.execute('update ' + self._table + ' set ' + ','.join(upd0) + ' ' \
4233 'where id IN %s', upd1 + [sub_ids])
4234 if cr.rowcount != len(sub_ids):
4235 raise except_orm(_('AccessError'),
4236 _('One of the records you are trying to modify has already been deleted (Document type: %s).') % self._description)
4241 if self._columns[f].translate:
4242 src_trans = self.pool.get(self._name).read(cr, user, ids, [f])[0][f]
4245 # Inserting value to DB
4246 context_wo_lang = dict(context, lang=None)
4247 self.write(cr, user, ids, {f: vals[f]}, context=context_wo_lang)
4248 self.pool.get('ir.translation')._set_ids(cr, user, self._name+','+f, 'model', context['lang'], ids, vals[f], src_trans)
4251 # call the 'set' method of fields which are not classic_write
4252 upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
4254 # default element in context must be removed when call a one2many or many2many
4255 rel_context = context.copy()
4256 for c in context.items():
4257 if c[0].startswith('default_'):
4258 del rel_context[c[0]]
4260 for field in upd_todo:
4262 result += self._columns[field].set(cr, self, id, field, vals[field], user, context=rel_context) or []
4264 unknown_fields = updend[:]
4265 for table in self._inherits:
4266 col = self._inherits[table]
4268 for sub_ids in cr.split_for_in_conditions(ids):
4269 cr.execute('select distinct "'+col+'" from "'+self._table+'" ' \
4270 'where id IN %s', (sub_ids,))
4271 nids.extend([x[0] for x in cr.fetchall()])
4275 if self._inherit_fields[val][0] == table:
4277 unknown_fields.remove(val)
4279 self.pool.get(table).write(cr, user, nids, v, context)
4283 'No such field(s) in model %s: %s.',
4284 self._name, ', '.join(unknown_fields))
4285 self._validate(cr, user, ids, context)
4287 # TODO: use _order to set dest at the right position and not first node of parent
4288 # We can't defer parent_store computation because the stored function
4289 # fields that are computer may refer (directly or indirectly) to
4290 # parent_left/right (via a child_of domain)
4293 self.pool._init_parent[self._name] = True
4295 order = self._parent_order or self._order
4296 parent_val = vals[self._parent_name]
4298 clause, params = '%s=%%s' % (self._parent_name,), (parent_val,)
4300 clause, params = '%s IS NULL' % (self._parent_name,), ()
4302 for id in parents_changed:
4303 cr.execute('SELECT parent_left, parent_right FROM %s WHERE id=%%s' % (self._table,), (id,))
4304 pleft, pright = cr.fetchone()
4305 distance = pright - pleft + 1
4307 # Positions of current siblings, to locate proper insertion point;
4308 # this can _not_ be fetched outside the loop, as it needs to be refreshed
4309 # after each update, in case several nodes are sequentially inserted one
4310 # next to the other (i.e computed incrementally)
4311 cr.execute('SELECT parent_right, id FROM %s WHERE %s ORDER BY %s' % (self._table, clause, parent_order), params)
4312 parents = cr.fetchall()
4314 # Find Position of the element
4316 for (parent_pright, parent_id) in parents:
4319 position = parent_pright + 1
4321 # It's the first node of the parent
4326 cr.execute('select parent_left from '+self._table+' where id=%s', (parent_val,))
4327 position = cr.fetchone()[0] + 1
4329 if pleft < position <= pright:
4330 raise except_orm(_('UserError'), _('Recursivity Detected.'))
4332 if pleft < position:
4333 cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
4334 cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
4335 cr.execute('update '+self._table+' set parent_left=parent_left+%s, parent_right=parent_right+%s where parent_left>=%s and parent_left<%s', (position-pleft, position-pleft, pleft, pright))
4337 cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
4338 cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
4339 cr.execute('update '+self._table+' set parent_left=parent_left-%s, parent_right=parent_right-%s where parent_left>=%s and parent_left<%s', (pleft-position+distance, pleft-position+distance, pleft+distance, pright+distance))
4341 result += self._store_get_values(cr, user, ids, vals.keys(), context)
4345 for order, object, ids_to_update, fields_to_recompute in result:
4346 key = (object, tuple(fields_to_recompute))
4347 done.setdefault(key, {})
4348 # avoid to do several times the same computation
4350 for id in ids_to_update:
4351 if id not in done[key]:
4352 done[key][id] = True
4354 self.pool.get(object)._store_set_values(cr, user, todo, fields_to_recompute, context)
4356 self._workflow_trigger(cr, user, ids, 'trg_write', context=context)
4360 # TODO: Should set perm to user.xxx
4362 def create(self, cr, user, vals, context=None):
4364 Create a new record for the model.
4366 The values for the new record are initialized using the ``vals``
4367 argument, and if necessary the result of ``default_get()``.
4369 :param cr: database cursor
4370 :param user: current user id
4372 :param vals: field values for new record, e.g {'field_name': field_value, ...}
4373 :type vals: dictionary
4374 :param context: optional context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...}
4375 :type context: dictionary
4376 :return: id of new record created
4377 :raise AccessError: * if user has no create rights on the requested object
4378 * if user tries to bypass access rules for create on the requested object
4379 :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
4380 :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)
4382 **Note**: The type of field values to pass in ``vals`` for relationship fields is specific.
4383 Please see the description of the :py:meth:`~osv.osv.osv.write` method for details about the possible values and how
4390 if self.is_transient():
4391 self._transient_vacuum(cr, user)
4393 self.check_access_rights(cr, user, 'create')
4395 if self._log_access:
4396 for f in LOG_ACCESS_COLUMNS:
4397 if vals.pop(f, None) is not None:
4399 'Field `%s` is not allowed when creating the model `%s`.',
4401 vals = self._add_missing_default_values(cr, user, vals, context)
4404 for v in self._inherits:
4405 if self._inherits[v] not in vals:
4408 tocreate[v] = {'id': vals[self._inherits[v]]}
4409 (upd0, upd1, upd2) = ('', '', [])
4412 for v in vals.keys():
4413 if v in self._inherit_fields and v not in self._columns:
4414 (table, col, col_detail, original_parent) = self._inherit_fields[v]
4415 tocreate[table][v] = vals[v]
4418 if (v not in self._inherit_fields) and (v not in self._columns):
4420 unknown_fields.append(v)
4423 'No such field(s) in model %s: %s.',
4424 self._name, ', '.join(unknown_fields))
4426 # Try-except added to filter the creation of those records whose filds are readonly.
4427 # Example : any dashboard which has all the fields readonly.(due to Views(database views))
4429 cr.execute("SELECT nextval('"+self._sequence+"')")
4431 raise except_orm(_('UserError'),
4432 _('You cannot perform this operation. New Record Creation is not allowed for this object as this object is for reporting purpose.'))
4434 id_new = cr.fetchone()[0]
4435 for table in tocreate:
4436 if self._inherits[table] in vals:
4437 del vals[self._inherits[table]]
4439 record_id = tocreate[table].pop('id', None)
4441 # When linking/creating parent records, force context without 'no_store_function' key that
4442 # defers stored functions computing, as these won't be computed in batch at the end of create().
4443 parent_context = dict(context)
4444 parent_context.pop('no_store_function', None)
4446 if record_id is None or not record_id:
4447 record_id = self.pool.get(table).create(cr, user, tocreate[table], context=parent_context)
4449 self.pool.get(table).write(cr, user, [record_id], tocreate[table], context=parent_context)
4451 upd0 += ',' + self._inherits[table]
4453 upd2.append(record_id)
4455 #Start : Set bool fields to be False if they are not touched(to make search more powerful)
4456 bool_fields = [x for x in self._columns.keys() if self._columns[x]._type=='boolean']
4458 for bool_field in bool_fields:
4459 if bool_field not in vals:
4460 vals[bool_field] = False
4462 for field in vals.copy():
4464 if field in self._columns:
4465 fobj = self._columns[field]
4467 fobj = self._inherit_fields[field][2]
4473 for group in groups:
4474 module = group.split(".")[0]
4475 grp = group.split(".")[1]
4476 cr.execute("select count(*) from res_groups_users_rel where gid IN (select res_id from ir_model_data where name='%s' and module='%s' and model='%s') and uid=%s" % \
4477 (grp, module, 'res.groups', user))
4478 readonly = cr.fetchall()
4479 if readonly[0][0] >= 1:
4482 elif readonly[0][0] == 0:
4490 if self._columns[field]._classic_write:
4491 upd0 = upd0 + ',"' + field + '"'
4492 upd1 = upd1 + ',' + self._columns[field]._symbol_set[0]
4493 upd2.append(self._columns[field]._symbol_set[1](vals[field]))
4494 #for the function fields that receive a value, we set them directly in the database
4495 #(they may be required), but we also need to trigger the _fct_inv()
4496 if (hasattr(self._columns[field], '_fnct_inv')) and not isinstance(self._columns[field], fields.related):
4497 #TODO: this way to special case the related fields is really creepy but it shouldn't be changed at
4498 #one week of the release candidate. It seems the only good way to handle correctly this is to add an
4499 #attribute to make a field `really readonly´ and thus totally ignored by the create()... otherwise
4500 #if, for example, the related has a default value (for usability) then the fct_inv is called and it
4501 #may raise some access rights error. Changing this is a too big change for now, and is thus postponed
4502 #after the release but, definitively, the behavior shouldn't be different for related and function
4504 upd_todo.append(field)
4506 #TODO: this `if´ statement should be removed because there is no good reason to special case the fields
4507 #related. See the above TODO comment for further explanations.
4508 if not isinstance(self._columns[field], fields.related):
4509 upd_todo.append(field)
4510 if field in self._columns \
4511 and hasattr(self._columns[field], 'selection') \
4513 self._check_selection_field_value(cr, user, field, vals[field], context=context)
4514 if self._log_access:
4515 upd0 += ',create_uid,create_date,write_uid,write_date'
4516 upd1 += ",%s,(now() at time zone 'UTC'),%s,(now() at time zone 'UTC')"
4517 upd2.extend((user, user))
4518 cr.execute('insert into "'+self._table+'" (id'+upd0+") values ("+str(id_new)+upd1+')', tuple(upd2))
4519 upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
4521 if self._parent_store and not context.get('defer_parent_store_computation'):
4523 self.pool._init_parent[self._name] = True
4525 parent = vals.get(self._parent_name, False)
4527 cr.execute('select parent_right from '+self._table+' where '+self._parent_name+'=%s order by '+(self._parent_order or self._order), (parent,))
4529 result_p = cr.fetchall()
4530 for (pleft,) in result_p:
4535 cr.execute('select parent_left from '+self._table+' where id=%s', (parent,))
4536 pleft_old = cr.fetchone()[0]
4539 cr.execute('select max(parent_right) from '+self._table)
4540 pleft = cr.fetchone()[0] or 0
4541 cr.execute('update '+self._table+' set parent_left=parent_left+2 where parent_left>%s', (pleft,))
4542 cr.execute('update '+self._table+' set parent_right=parent_right+2 where parent_right>%s', (pleft,))
4543 cr.execute('update '+self._table+' set parent_left=%s,parent_right=%s where id=%s', (pleft+1, pleft+2, id_new))
4545 # default element in context must be remove when call a one2many or many2many
4546 rel_context = context.copy()
4547 for c in context.items():
4548 if c[0].startswith('default_'):
4549 del rel_context[c[0]]
4552 for field in upd_todo:
4553 result += self._columns[field].set(cr, self, id_new, field, vals[field], user, rel_context) or []
4554 self._validate(cr, user, [id_new], context)
4556 if not context.get('no_store_function', False):
4557 result += self._store_get_values(cr, user, [id_new],
4558 list(set(vals.keys() + self._inherits.values())),
4562 for order, object, ids, fields2 in result:
4563 if not (object, ids, fields2) in done:
4564 self.pool.get(object)._store_set_values(cr, user, ids, fields2, context)
4565 done.append((object, ids, fields2))
4567 if self._log_create and not (context and context.get('no_store_function', False)):
4568 message = self._description + \
4570 self.name_get(cr, user, [id_new], context=context)[0][1] + \
4571 "' " + _("created.")
4572 self.log(cr, user, id_new, message, True, context=context)
4573 self.check_access_rule(cr, user, [id_new], 'create', context=context)
4574 self._workflow_trigger(cr, user, [id_new], 'trg_create', context=context)
4577 def browse(self, cr, uid, select, context=None, list_class=None, fields_process=None):
4578 """Fetch records as objects allowing to use dot notation to browse fields and relations
4580 :param cr: database cursor
4581 :param uid: current user id
4582 :param select: id or list of ids.
4583 :param context: context arguments, like lang, time zone
4584 :rtype: object or list of objects requested
4587 self._list_class = list_class or browse_record_list
4589 # need to accepts ints and longs because ids coming from a method
4590 # launched by button in the interface have a type long...
4591 if isinstance(select, (int, long)):
4592 return browse_record(cr, uid, select, self, cache, context=context, list_class=self._list_class, fields_process=fields_process)
4593 elif isinstance(select, list):
4594 return self._list_class((browse_record(cr, uid, id, self, cache, context=context, list_class=self._list_class, fields_process=fields_process) for id in select), context=context)
4596 return browse_null()
4598 def _store_get_values(self, cr, uid, ids, fields, context):
4599 """Returns an ordered list of fields.functions to call due to
4600 an update operation on ``fields`` of records with ``ids``,
4601 obtained by calling the 'store' functions of these fields,
4602 as setup by their 'store' attribute.
4604 :return: [(priority, model_name, [record_ids,], [function_fields,])]
4606 if fields is None: fields = []
4607 stored_functions = self.pool._store_function.get(self._name, [])
4609 # use indexed names for the details of the stored_functions:
4610 model_name_, func_field_to_compute_, id_mapping_fnct_, trigger_fields_, priority_ = range(5)
4612 # only keep functions that should be triggered for the ``fields``
4614 to_compute = [f for f in stored_functions \
4615 if ((not f[trigger_fields_]) or set(fields).intersection(f[trigger_fields_]))]
4619 for function in to_compute:
4620 fid = id(function[id_mapping_fnct_])
4621 if not fid in fresults:
4622 # use admin user for accessing objects having rules defined on store fields
4623 fresults[fid] = [id2 for id2 in function[id_mapping_fnct_](self, cr, SUPERUSER_ID, ids, context) if id2]
4624 target_ids = fresults[fid]
4626 # the compound key must consider the priority and model name
4627 key = (function[priority_], function[model_name_])
4628 for target_id in target_ids:
4629 mapping.setdefault(key, {}).setdefault(target_id,set()).add(tuple(function))
4631 # Here mapping looks like:
4632 # { (10, 'model_a') : { target_id1: [ (function_1_tuple, function_2_tuple) ], ... }
4633 # (20, 'model_a') : { target_id2: [ (function_3_tuple, function_4_tuple) ], ... }
4634 # (99, 'model_a') : { target_id1: [ (function_5_tuple, function_6_tuple) ], ... }
4637 # Now we need to generate the batch function calls list
4639 # { (10, 'model_a') : [(10, 'model_a', [record_ids,], [function_fields,])] }
4641 for ((priority,model), id_map) in mapping.iteritems():
4642 functions_ids_maps = {}
4643 # function_ids_maps =
4644 # { (function_1_tuple, function_2_tuple) : [target_id1, target_id2, ..] }
4645 for fid, functions in id_map.iteritems():
4646 functions_ids_maps.setdefault(tuple(functions), []).append(fid)
4647 for functions, ids in functions_ids_maps.iteritems():
4648 call_map.setdefault((priority,model),[]).append((priority, model, ids,
4649 [f[func_field_to_compute_] for f in functions]))
4650 ordered_keys = call_map.keys()
4654 result = reduce(operator.add, (call_map[k] for k in ordered_keys))
4657 def _store_set_values(self, cr, uid, ids, fields, context):
4658 """Calls the fields.function's "implementation function" for all ``fields``, on records with ``ids`` (taking care of
4659 respecting ``multi`` attributes), and stores the resulting values in the database directly."""
4664 if self._log_access:
4665 cr.execute('select id,write_date from '+self._table+' where id IN %s', (tuple(ids),))
4669 field_dict.setdefault(r[0], [])
4670 res_date = time.strptime((r[1])[:19], '%Y-%m-%d %H:%M:%S')
4671 write_date = datetime.datetime.fromtimestamp(time.mktime(res_date))
4672 for i in self.pool._store_function.get(self._name, []):
4674 up_write_date = write_date + datetime.timedelta(hours=i[5])
4675 if datetime.datetime.now() < up_write_date:
4677 field_dict[r[0]].append(i[1])
4683 if self._columns[f]._multi not in keys:
4684 keys.append(self._columns[f]._multi)
4685 todo.setdefault(self._columns[f]._multi, [])
4686 todo[self._columns[f]._multi].append(f)
4690 # use admin user for accessing objects having rules defined on store fields
4691 result = self._columns[val[0]].get(cr, self, ids, val, SUPERUSER_ID, context=context)
4692 for id, value in result.items():
4694 for f in value.keys():
4695 if f in field_dict[id]:
4702 if self._columns[v]._type == 'many2one':
4704 value[v] = value[v][0]
4707 upd0.append('"'+v+'"='+self._columns[v]._symbol_set[0])
4708 upd1.append(self._columns[v]._symbol_set[1](value[v]))
4711 cr.execute('update "' + self._table + '" set ' + \
4712 ','.join(upd0) + ' where id = %s', upd1)
4716 # use admin user for accessing objects having rules defined on store fields
4717 result = self._columns[f].get(cr, self, ids, f, SUPERUSER_ID, context=context)
4718 for r in result.keys():
4720 if r in field_dict.keys():
4721 if f in field_dict[r]:
4723 for id, value in result.items():
4724 if self._columns[f]._type == 'many2one':
4729 cr.execute('update "' + self._table + '" set ' + \
4730 '"'+f+'"='+self._columns[f]._symbol_set[0] + ' where id = %s', (self._columns[f]._symbol_set[1](value), id))
4736 def perm_write(self, cr, user, ids, fields, context=None):
4737 raise NotImplementedError(_('This method does not exist anymore'))
4739 # TODO: ameliorer avec NULL
4740 def _where_calc(self, cr, user, domain, active_test=True, context=None):
4741 """Computes the WHERE clause needed to implement an OpenERP domain.
4742 :param domain: the domain to compute
4744 :param active_test: whether the default filtering of records with ``active``
4745 field set to ``False`` should be applied.
4746 :return: the query expressing the given domain as provided in domain
4747 :rtype: osv.query.Query
4752 # if the object has a field named 'active', filter out all inactive
4753 # records unless they were explicitely asked for
4754 if 'active' in self._all_columns and (active_test and context.get('active_test', True)):
4756 # the item[0] trick below works for domain items and '&'/'|'/'!'
4758 if not any(item[0] == 'active' for item in domain):
4759 domain.insert(0, ('active', '=', 1))
4761 domain = [('active', '=', 1)]
4764 e = expression.expression(cr, user, domain, self, context)
4765 tables = e.get_tables()
4766 where_clause, where_params = e.to_sql()
4767 where_clause = where_clause and [where_clause] or []
4769 where_clause, where_params, tables = [], [], ['"%s"' % self._table]
4771 return Query(tables, where_clause, where_params)
4773 def _check_qorder(self, word):
4774 if not regex_order.match(word):
4775 raise except_orm(_('AccessError'), _('Invalid "order" specified. A valid "order" specification is a comma-separated list of valid field names (optionally followed by asc/desc for the direction)'))
4778 def _apply_ir_rules(self, cr, uid, query, mode='read', context=None):
4779 """Add what's missing in ``query`` to implement all appropriate ir.rules
4780 (using the ``model_name``'s rules or the current model's rules if ``model_name`` is None)
4782 :param query: the current query object
4784 if uid == SUPERUSER_ID:
4787 def apply_rule(added_clause, added_params, added_tables, parent_model=None, child_object=None):
4788 """ :param string parent_model: string of the parent model
4789 :param model child_object: model object, base of the rule application
4792 if parent_model and child_object:
4793 # as inherited rules are being applied, we need to add the missing JOIN
4794 # to reach the parent table (if it was not JOINed yet in the query)
4795 parent_alias = child_object._inherits_join_add(child_object, parent_model, query)
4796 # inherited rules are applied on the external table -> need to get the alias and replace
4797 parent_table = self.pool.get(parent_model)._table
4798 added_clause = [clause.replace('"%s"' % parent_table, '"%s"' % parent_alias) for clause in added_clause]
4799 # change references to parent_table to parent_alias, because we now use the alias to refer to the table
4801 for table in added_tables:
4802 # table is just a table name -> switch to the full alias
4803 if table == '"%s"' % parent_table:
4804 new_tables.append('"%s" as "%s"' % (parent_table, parent_alias))
4805 # table is already a full statement -> replace reference to the table to its alias, is correct with the way aliases are generated
4807 new_tables.append(table.replace('"%s"' % parent_table, '"%s"' % parent_alias))
4808 added_tables = new_tables
4809 query.where_clause += added_clause
4810 query.where_clause_params += added_params
4811 for table in added_tables:
4812 if table not in query.tables:
4813 query.tables.append(table)
4817 # apply main rules on the object
4818 rule_obj = self.pool.get('ir.rule')
4819 rule_where_clause, rule_where_clause_params, rule_tables = rule_obj.domain_get(cr, uid, self._name, mode, context=context)
4820 apply_rule(rule_where_clause, rule_where_clause_params, rule_tables)
4822 # apply ir.rules from the parents (through _inherits)
4823 for inherited_model in self._inherits:
4824 rule_where_clause, rule_where_clause_params, rule_tables = rule_obj.domain_get(cr, uid, inherited_model, mode, context=context)
4825 apply_rule(rule_where_clause, rule_where_clause_params, rule_tables,
4826 parent_model=inherited_model, child_object=self)
4828 def _generate_m2o_order_by(self, order_field, query):
4830 Add possibly missing JOIN to ``query`` and generate the ORDER BY clause for m2o fields,
4831 either native m2o fields or function/related fields that are stored, including
4832 intermediate JOINs for inheritance if required.
4834 :return: the qualified field name to use in an ORDER BY clause to sort by ``order_field``
4836 if order_field not in self._columns and order_field in self._inherit_fields:
4837 # also add missing joins for reaching the table containing the m2o field
4838 qualified_field = self._inherits_join_calc(order_field, query)
4839 order_field_column = self._inherit_fields[order_field][2]
4841 qualified_field = '"%s"."%s"' % (self._table, order_field)
4842 order_field_column = self._columns[order_field]
4844 assert order_field_column._type == 'many2one', 'Invalid field passed to _generate_m2o_order_by()'
4845 if not order_field_column._classic_write and not getattr(order_field_column, 'store', False):
4846 _logger.debug("Many2one function/related fields must be stored " \
4847 "to be used as ordering fields! Ignoring sorting for %s.%s",
4848 self._name, order_field)
4851 # figure out the applicable order_by for the m2o
4852 dest_model = self.pool.get(order_field_column._obj)
4853 m2o_order = dest_model._order
4854 if not regex_order.match(m2o_order):
4855 # _order is complex, can't use it here, so we default to _rec_name
4856 m2o_order = dest_model._rec_name
4858 # extract the field names, to be able to qualify them and add desc/asc
4860 for order_part in m2o_order.split(","):
4861 m2o_order_list.append(order_part.strip().split(" ", 1)[0].strip())
4862 m2o_order = m2o_order_list
4864 # Join the dest m2o table if it's not joined yet. We use [LEFT] OUTER join here
4865 # as we don't want to exclude results that have NULL values for the m2o
4866 src_table, src_field = qualified_field.replace('"', '').split('.', 1)
4867 dst_alias, dst_alias_statement = query.add_join((src_table, dest_model._table, src_field, 'id', src_field), implicit=False, outer=True)
4868 qualify = lambda field: '"%s"."%s"' % (dst_alias, field)
4869 return map(qualify, m2o_order) if isinstance(m2o_order, list) else qualify(m2o_order)
4871 def _generate_order_by(self, order_spec, query):
4873 Attempt to consruct an appropriate ORDER BY clause based on order_spec, which must be
4874 a comma-separated list of valid field names, optionally followed by an ASC or DESC direction.
4876 :raise" except_orm in case order_spec is malformed
4878 order_by_clause = ''
4879 order_spec = order_spec or self._order
4881 order_by_elements = []
4882 self._check_qorder(order_spec)
4883 for order_part in order_spec.split(','):
4884 order_split = order_part.strip().split(' ')
4885 order_field = order_split[0].strip()
4886 order_direction = order_split[1].strip() if len(order_split) == 2 else ''
4888 if order_field == 'id' or (self._log_access and order_field in LOG_ACCESS_COLUMNS.keys()):
4889 order_by_elements.append('"%s"."%s" %s' % (self._table, order_field, order_direction))
4890 elif order_field in self._columns:
4891 order_column = self._columns[order_field]
4892 if order_column._classic_read:
4893 inner_clause = '"%s"."%s"' % (self._table, order_field)
4894 elif order_column._type == 'many2one':
4895 inner_clause = self._generate_m2o_order_by(order_field, query)
4897 continue # ignore non-readable or "non-joinable" fields
4898 elif order_field in self._inherit_fields:
4899 parent_obj = self.pool.get(self._inherit_fields[order_field][3])
4900 order_column = parent_obj._columns[order_field]
4901 if order_column._classic_read:
4902 inner_clause = self._inherits_join_calc(order_field, query)
4903 elif order_column._type == 'many2one':
4904 inner_clause = self._generate_m2o_order_by(order_field, query)
4906 continue # ignore non-readable or "non-joinable" fields
4908 raise ValueError( _("Sorting field %s not found on model %s") %( order_field, self._name))
4910 if isinstance(inner_clause, list):
4911 for clause in inner_clause:
4912 order_by_elements.append("%s %s" % (clause, order_direction))
4914 order_by_elements.append("%s %s" % (inner_clause, order_direction))
4915 if order_by_elements:
4916 order_by_clause = ",".join(order_by_elements)
4918 return order_by_clause and (' ORDER BY %s ' % order_by_clause) or ''
4920 def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
4922 Private implementation of search() method, allowing specifying the uid to use for the access right check.
4923 This is useful for example when filling in the selection list for a drop-down and avoiding access rights errors,
4924 by specifying ``access_rights_uid=1`` to bypass access rights check, but not ir.rules!
4925 This is ok at the security level because this method is private and not callable through XML-RPC.
4927 :param access_rights_uid: optional user ID to use when checking access rights
4928 (not for ir.rules, this is only for ir.model.access)
4932 self.check_access_rights(cr, access_rights_uid or user, 'read')
4934 # For transient models, restrict acces to the current user, except for the super-user
4935 if self.is_transient() and self._log_access and user != SUPERUSER_ID:
4936 args = expression.AND(([('create_uid', '=', user)], args or []))
4938 query = self._where_calc(cr, user, args, context=context)
4939 self._apply_ir_rules(cr, user, query, 'read', context=context)
4940 order_by = self._generate_order_by(order, query)
4941 from_clause, where_clause, where_clause_params = query.get_sql()
4943 limit_str = limit and ' limit %d' % limit or ''
4944 offset_str = offset and ' offset %d' % offset or ''
4945 where_str = where_clause and (" WHERE %s" % where_clause) or ''
4948 cr.execute('SELECT count("%s".id) FROM ' % self._table + from_clause + where_str + limit_str + offset_str, where_clause_params)
4951 cr.execute('SELECT "%s".id FROM ' % self._table + from_clause + where_str + order_by + limit_str + offset_str, where_clause_params)
4954 # TDE note: with auto_join, we could have several lines about the same result
4955 # i.e. a lead with several unread messages; we uniquify the result using
4956 # a fast way to do it while preserving order (http://www.peterbe.com/plog/uniqifiers-benchmark)
4957 def _uniquify_list(seq):
4959 return [x for x in seq if x not in seen and not seen.add(x)]
4961 return _uniquify_list([x[0] for x in res])
4963 # returns the different values ever entered for one field
4964 # this is used, for example, in the client when the user hits enter on
4966 def distinct_field_get(self, cr, uid, field, value, args=None, offset=0, limit=None):
4969 if field in self._inherit_fields:
4970 return self.pool.get(self._inherit_fields[field][0]).distinct_field_get(cr, uid, field, value, args, offset, limit)
4972 return self._columns[field].search(cr, self, args, field, value, offset, limit, uid)
4974 def copy_data(self, cr, uid, id, default=None, context=None):
4976 Copy given record's data with all its fields values
4978 :param cr: database cursor
4979 :param uid: current user id
4980 :param id: id of the record to copy
4981 :param default: field values to override in the original values of the copied record
4982 :type default: dictionary
4983 :param context: context arguments, like lang, time zone
4984 :type context: dictionary
4985 :return: dictionary containing all the field values
4991 # avoid recursion through already copied records in case of circular relationship
4992 seen_map = context.setdefault('__copy_data_seen',{})
4993 if id in seen_map.setdefault(self._name,[]):
4995 seen_map[self._name].append(id)
4999 if 'state' not in default:
5000 if 'state' in self._defaults:
5001 if callable(self._defaults['state']):
5002 default['state'] = self._defaults['state'](self, cr, uid, context)
5004 default['state'] = self._defaults['state']
5006 # build a black list of fields that should not be copied
5007 blacklist = set(MAGIC_COLUMNS + ['parent_left', 'parent_right'])
5008 def blacklist_given_fields(obj):
5009 # blacklist the fields that are given by inheritance
5010 for other, field_to_other in obj._inherits.items():
5011 blacklist.add(field_to_other)
5012 if field_to_other in default:
5013 # all the fields of 'other' are given by the record: default[field_to_other],
5014 # except the ones redefined in self
5015 blacklist.update(set(self.pool.get(other)._all_columns) - set(self._columns))
5017 blacklist_given_fields(self.pool.get(other))
5018 blacklist_given_fields(self)
5021 fields_to_copy = dict((f,fi) for f, fi in self._all_columns.iteritems()
5023 if f not in blacklist
5024 if not isinstance(fi.column, fields.function))
5026 data = self.read(cr, uid, [id], fields_to_copy.keys(), context=context)
5030 raise IndexError( _("Record #%d of %s not found, cannot copy!") %( id, self._name))
5033 for f, colinfo in fields_to_copy.iteritems():
5034 field = colinfo.column
5035 if field._type == 'many2one':
5036 res[f] = data[f] and data[f][0]
5037 elif field._type == 'one2many':
5038 other = self.pool.get(field._obj)
5039 # duplicate following the order of the ids because we'll rely on
5040 # it later for copying translations in copy_translation()!
5041 lines = [other.copy_data(cr, uid, line_id, context=context) for line_id in sorted(data[f])]
5042 # the lines are duplicated using the wrong (old) parent, but then
5043 # are reassigned to the correct one thanks to the (0, 0, ...)
5044 res[f] = [(0, 0, line) for line in lines if line]
5045 elif field._type == 'many2many':
5046 res[f] = [(6, 0, data[f])]
5052 def copy_translations(self, cr, uid, old_id, new_id, context=None):
5056 # avoid recursion through already copied records in case of circular relationship
5057 seen_map = context.setdefault('__copy_translations_seen',{})
5058 if old_id in seen_map.setdefault(self._name,[]):
5060 seen_map[self._name].append(old_id)
5062 trans_obj = self.pool.get('ir.translation')
5063 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
5064 fields = self.fields_get(cr, uid, context=context)
5066 for field_name, field_def in fields.items():
5067 # removing the lang to compare untranslated values
5068 context_wo_lang = dict(context, lang=None)
5069 old_record, new_record = self.browse(cr, uid, [old_id, new_id], context=context_wo_lang)
5070 # we must recursively copy the translations for o2o and o2m
5071 if field_def['type'] == 'one2many':
5072 target_obj = self.pool.get(field_def['relation'])
5073 # here we rely on the order of the ids to match the translations
5074 # as foreseen in copy_data()
5075 old_children = sorted(r.id for r in old_record[field_name])
5076 new_children = sorted(r.id for r in new_record[field_name])
5077 for (old_child, new_child) in zip(old_children, new_children):
5078 target_obj.copy_translations(cr, uid, old_child, new_child, context=context)
5079 # and for translatable fields we keep them for copy
5080 elif field_def.get('translate'):
5081 if field_name in self._columns:
5082 trans_name = self._name + "," + field_name
5085 elif field_name in self._inherit_fields:
5086 trans_name = self._inherit_fields[field_name][0] + "," + field_name
5087 # get the id of the parent record to set the translation
5088 inherit_field_name = self._inherit_fields[field_name][1]
5089 target_id = new_record[inherit_field_name].id
5090 source_id = old_record[inherit_field_name].id
5094 trans_ids = trans_obj.search(cr, uid, [
5095 ('name', '=', trans_name),
5096 ('res_id', '=', source_id)
5098 user_lang = context.get('lang')
5099 for record in trans_obj.read(cr, uid, trans_ids, context=context):
5101 # remove source to avoid triggering _set_src
5102 del record['source']
5103 record.update({'res_id': target_id})
5104 if user_lang and user_lang == record['lang']:
5105 # 'source' to force the call to _set_src
5106 # 'value' needed if value is changed in copy(), want to see the new_value
5107 record['source'] = old_record[field_name]
5108 record['value'] = new_record[field_name]
5109 trans_obj.create(cr, uid, record, context=context)
5112 def copy(self, cr, uid, id, default=None, context=None):
5114 Duplicate record with given id updating it with default values
5116 :param cr: database cursor
5117 :param uid: current user id
5118 :param id: id of the record to copy
5119 :param default: dictionary of field values to override in the original values of the copied record, e.g: ``{'field_name': overriden_value, ...}``
5120 :type default: dictionary
5121 :param context: context arguments, like lang, time zone
5122 :type context: dictionary
5123 :return: id of the newly created record
5128 context = context.copy()
5129 data = self.copy_data(cr, uid, id, default, context)
5130 new_id = self.create(cr, uid, data, context)
5131 self.copy_translations(cr, uid, id, new_id, context)
5134 def exists(self, cr, uid, ids, context=None):
5135 """Checks whether the given id or ids exist in this model,
5136 and return the list of ids that do. This is simple to use for
5137 a truth test on a browse_record::
5142 :param ids: id or list of ids to check for existence
5143 :type ids: int or [int]
5144 :return: the list of ids that currently exist, out of
5147 if type(ids) in (int, long):
5149 query = 'SELECT id FROM "%s"' % self._table
5150 cr.execute(query + "WHERE ID IN %s", (tuple(ids),))
5151 return [x[0] for x in cr.fetchall()]
5153 def check_recursion(self, cr, uid, ids, context=None, parent=None):
5154 _logger.warning("You are using deprecated %s.check_recursion(). Please use the '_check_recursion()' instead!" % \
5156 assert parent is None or parent in self._columns or parent in self._inherit_fields,\
5157 "The 'parent' parameter passed to check_recursion() must be None or a valid field name"
5158 return self._check_recursion(cr, uid, ids, context, parent)
5160 def _check_recursion(self, cr, uid, ids, context=None, parent=None):
5162 Verifies that there is no loop in a hierarchical structure of records,
5163 by following the parent relationship using the **parent** field until a loop
5164 is detected or until a top-level record is found.
5166 :param cr: database cursor
5167 :param uid: current user id
5168 :param ids: list of ids of records to check
5169 :param parent: optional parent field name (default: ``self._parent_name = parent_id``)
5170 :return: **True** if the operation can proceed safely, or **False** if an infinite loop is detected.
5173 parent = self._parent_name
5175 # must ignore 'active' flag, ir.rules, etc. => direct SQL query
5176 query = 'SELECT "%s" FROM "%s" WHERE id = %%s' % (parent, self._table)
5179 while current_id is not None:
5180 cr.execute(query, (current_id,))
5181 result = cr.fetchone()
5182 current_id = result[0] if result else None
5183 if current_id == id:
5187 def _get_external_ids(self, cr, uid, ids, *args, **kwargs):
5188 """Retrieve the External ID(s) of any database record.
5190 **Synopsis**: ``_get_xml_ids(cr, uid, ids) -> { 'id': ['module.xml_id'] }``
5192 :return: map of ids to the list of their fully qualified External IDs
5193 in the form ``module.key``, or an empty list when there's no External
5194 ID for a record, e.g.::
5196 { 'id': ['module.ext_id', 'module.ext_id_bis'],
5199 ir_model_data = self.pool.get('ir.model.data')
5200 data_ids = ir_model_data.search(cr, uid, [('model', '=', self._name), ('res_id', 'in', ids)])
5201 data_results = ir_model_data.read(cr, uid, data_ids, ['module', 'name', 'res_id'])
5204 # can't use dict.fromkeys() as the list would be shared!
5206 for record in data_results:
5207 result[record['res_id']].append('%(module)s.%(name)s' % record)
5210 def get_external_id(self, cr, uid, ids, *args, **kwargs):
5211 """Retrieve the External ID of any database record, if there
5212 is one. This method works as a possible implementation
5213 for a function field, to be able to add it to any
5214 model object easily, referencing it as ``Model.get_external_id``.
5216 When multiple External IDs exist for a record, only one
5217 of them is returned (randomly).
5219 :return: map of ids to their fully qualified XML ID,
5220 defaulting to an empty string when there's none
5221 (to be usable as a function field),
5224 { 'id': 'module.ext_id',
5227 results = self._get_xml_ids(cr, uid, ids)
5228 for k, v in results.iteritems():
5235 # backwards compatibility
5236 get_xml_id = get_external_id
5237 _get_xml_ids = _get_external_ids
5240 def is_transient(self):
5241 """ Return whether the model is transient.
5243 See :class:`TransientModel`.
5246 return self._transient
5248 def _transient_clean_rows_older_than(self, cr, seconds):
5249 assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
5250 # Never delete rows used in last 5 minutes
5251 seconds = max(seconds, 300)
5252 query = ("SELECT id FROM " + self._table + " WHERE"
5253 " COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp"
5254 " < ((now() at time zone 'UTC') - interval %s)")
5255 cr.execute(query, ("%s seconds" % seconds,))
5256 ids = [x[0] for x in cr.fetchall()]
5257 self.unlink(cr, SUPERUSER_ID, ids)
5259 def _transient_clean_old_rows(self, cr, max_count):
5260 # Check how many rows we have in the table
5261 cr.execute("SELECT count(*) AS row_count FROM " + self._table)
5263 if res[0][0] <= max_count:
5264 return # max not reached, nothing to do
5265 self._transient_clean_rows_older_than(cr, 300)
5267 def _transient_vacuum(self, cr, uid, force=False):
5268 """Clean the transient records.
5270 This unlinks old records from the transient model tables whenever the
5271 "_transient_max_count" or "_max_age" conditions (if any) are reached.
5272 Actual cleaning will happen only once every "_transient_check_time" calls.
5273 This means this method can be called frequently called (e.g. whenever
5274 a new record is created).
5275 Example with both max_hours and max_count active:
5276 Suppose max_hours = 0.2 (e.g. 12 minutes), max_count = 20, there are 55 rows in the
5277 table, 10 created/changed in the last 5 minutes, an additional 12 created/changed between
5278 5 and 10 minutes ago, the rest created/changed more then 12 minutes ago.
5279 - age based vacuum will leave the 22 rows created/changed in the last 12 minutes
5280 - count based vacuum will wipe out another 12 rows. Not just 2, otherwise each addition
5281 would immediately cause the maximum to be reached again.
5282 - the 10 rows that have been created/changed the last 5 minutes will NOT be deleted
5284 assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
5285 _transient_check_time = 20 # arbitrary limit on vacuum executions
5286 self._transient_check_count += 1
5287 if not force and (self._transient_check_count < _transient_check_time):
5288 return True # no vacuum cleaning this time
5289 self._transient_check_count = 0
5291 # Age-based expiration
5292 if self._transient_max_hours:
5293 self._transient_clean_rows_older_than(cr, self._transient_max_hours * 60 * 60)
5295 # Count-based expiration
5296 if self._transient_max_count:
5297 self._transient_clean_old_rows(cr, self._transient_max_count)
5301 def resolve_2many_commands(self, cr, uid, field_name, commands, fields=None, context=None):
5302 """ Serializes one2many and many2many commands into record dictionaries
5303 (as if all the records came from the database via a read()). This
5304 method is aimed at onchange methods on one2many and many2many fields.
5306 Because commands might be creation commands, not all record dicts
5307 will contain an ``id`` field. Commands matching an existing record
5308 will have an ``id``.
5310 :param field_name: name of the one2many or many2many field matching the commands
5311 :type field_name: str
5312 :param commands: one2many or many2many commands to execute on ``field_name``
5313 :type commands: list((int|False, int|False, dict|False))
5314 :param fields: list of fields to read from the database, when applicable
5315 :type fields: list(str)
5316 :returns: records in a shape similar to that returned by ``read()``
5317 (except records may be missing the ``id`` field if they don't exist in db)
5320 result = [] # result (list of dict)
5321 record_ids = [] # ids of records to read
5322 updates = {} # {id: dict} of updates on particular records
5324 for command in commands:
5325 if not isinstance(command, (list, tuple)):
5326 record_ids.append(command)
5327 elif command[0] == 0:
5328 result.append(command[2])
5329 elif command[0] == 1:
5330 record_ids.append(command[1])
5331 updates.setdefault(command[1], {}).update(command[2])
5332 elif command[0] in (2, 3):
5333 record_ids = [id for id in record_ids if id != command[1]]
5334 elif command[0] == 4:
5335 record_ids.append(command[1])
5336 elif command[0] == 5:
5337 result, record_ids = [], []
5338 elif command[0] == 6:
5339 result, record_ids = [], list(command[2])
5341 # read the records and apply the updates
5342 other_model = self.pool.get(self._all_columns[field_name].column._obj)
5343 for record in other_model.read(cr, uid, record_ids, fields=fields, context=context):
5344 record.update(updates.get(record['id'], {}))
5345 result.append(record)
5349 # for backward compatibility
5350 resolve_o2m_commands_to_record_dicts = resolve_2many_commands
5352 def _register_hook(self, cr):
5353 """ stuff to do right after the registry is built """
5356 # keep this import here, at top it will cause dependency cycle errors
5359 class Model(BaseModel):
5360 """Main super-class for regular database-persisted OpenERP models.
5362 OpenERP models are created by inheriting from this class::
5367 The system will later instantiate the class once per database (on
5368 which the class' module is installed).
5371 _register = False # not visible in ORM registry, meant to be python-inherited only
5372 _transient = False # True in a TransientModel
5374 class TransientModel(BaseModel):
5375 """Model super-class for transient records, meant to be temporarily
5376 persisted, and regularly vaccuum-cleaned.
5378 A TransientModel has a simplified access rights management,
5379 all users can create new records, and may only access the
5380 records they created. The super-user has unrestricted access
5381 to all TransientModel records.
5384 _register = False # not visible in ORM registry, meant to be python-inherited only
5387 class AbstractModel(BaseModel):
5388 """Abstract Model super-class for creating an abstract class meant to be
5389 inherited by regular models (Models or TransientModels) but not meant to
5390 be usable on its own, or persisted.
5392 Technical note: we don't want to make AbstractModel the super-class of
5393 Model or BaseModel because it would not make sense to put the main
5394 definition of persistence methods such as create() in it, and still we
5395 should be able to override them within an AbstractModel.
5397 _auto = False # don't create any database backend for AbstractModels
5398 _register = False # not visible in ORM registry, meant to be python-inherited only
5401 def itemgetter_tuple(items):
5402 """ Fixes itemgetter inconsistency (useful in some cases) of not returning
5403 a tuple if len(items) == 1: always returns an n-tuple where n = len(items)
5408 return lambda gettable: (gettable[items[0]],)
5409 return operator.itemgetter(*items)
5410 class ImportWarning(Warning):
5411 """ Used to send warnings upwards the stack during the import process
5416 def convert_pgerror_23502(model, fields, info, e):
5417 m = re.match(r'^null value in column "(?P<field>\w+)" violates '
5418 r'not-null constraint\n',
5420 field_name = m.group('field')
5421 if not m or field_name not in fields:
5422 return {'message': unicode(e)}
5423 message = _(u"Missing required value for the field '%s'.") % field_name
5424 field = fields.get(field_name)
5426 message = _(u"%s This might be '%s' in the current model, or a field "
5427 u"of the same name in an o2m.") % (message, field['string'])
5430 'field': field_name,
5432 def convert_pgerror_23505(model, fields, info, e):
5433 m = re.match(r'^duplicate key (?P<field>\w+) violates unique constraint',
5435 field_name = m.group('field')
5436 if not m or field_name not in fields:
5437 return {'message': unicode(e)}
5438 message = _(u"The value for the field '%s' already exists.") % field_name
5439 field = fields.get(field_name)
5441 message = _(u"%s This might be '%s' in the current model, or a field "
5442 u"of the same name in an o2m.") % (message, field['string'])
5445 'field': field_name,
5448 PGERROR_TO_OE = collections.defaultdict(
5449 # shape of mapped converters
5450 lambda: (lambda model, fvg, info, pgerror: {'message': unicode(pgerror)}), {
5451 # not_null_violation
5452 '23502': convert_pgerror_23502,
5453 # unique constraint error
5454 '23505': convert_pgerror_23505,
5456 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: