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)
57 from lxml import etree
62 import openerp.netsvc as netsvc
63 import openerp.tools as tools
64 from openerp.tools.config import config
65 from openerp.tools.misc import CountingStream
66 from openerp.tools.safe_eval import safe_eval as eval
67 from openerp.tools.translate import _
68 from openerp import SUPERUSER_ID
69 from query import Query
70 from openerp import SUPERUSER_ID
72 _logger = logging.getLogger(__name__)
73 _schema = logging.getLogger(__name__ + '.schema')
75 # List of etree._Element subclasses that we choose to ignore when parsing XML.
76 from openerp.tools import SKIPPED_ELEMENT_TYPES
78 regex_order = re.compile('^(([a-z0-9_]+|"[a-z0-9_]+")( *desc| *asc)?( *, *|))+$', re.I)
79 regex_object_name = re.compile(r'^[a-z0-9_.]+$')
81 def transfer_field_to_modifiers(field, modifiers):
84 for attr in ('invisible', 'readonly', 'required'):
85 state_exceptions[attr] = []
86 default_values[attr] = bool(field.get(attr))
87 for state, modifs in (field.get("states",{})).items():
89 if default_values[modif[0]] != modif[1]:
90 state_exceptions[modif[0]].append(state)
92 for attr, default_value in default_values.items():
93 if state_exceptions[attr]:
94 modifiers[attr] = [("state", "not in" if default_value else "in", state_exceptions[attr])]
96 modifiers[attr] = default_value
99 # Don't deal with groups, it is done by check_group().
100 # Need the context to evaluate the invisible attribute on tree views.
101 # For non-tree views, the context shouldn't be given.
102 def transfer_node_to_modifiers(node, modifiers, context=None, in_tree_view=False):
103 if node.get('attrs'):
104 modifiers.update(eval(node.get('attrs')))
106 if node.get('states'):
107 if 'invisible' in modifiers and isinstance(modifiers['invisible'], list):
108 # TODO combine with AND or OR, use implicit AND for now.
109 modifiers['invisible'].append(('state', 'not in', node.get('states').split(',')))
111 modifiers['invisible'] = [('state', 'not in', node.get('states').split(','))]
113 for a in ('invisible', 'readonly', 'required'):
115 v = bool(eval(node.get(a), {'context': context or {}}))
116 if in_tree_view and a == 'invisible':
117 # Invisible in a tree view has a specific meaning, make it a
118 # new key in the modifiers attribute.
119 modifiers['tree_invisible'] = v
120 elif v or (a not in modifiers or not isinstance(modifiers[a], list)):
121 # Don't set the attribute to False if a dynamic value was
122 # provided (i.e. a domain from attrs or states).
126 def simplify_modifiers(modifiers):
127 for a in ('invisible', 'readonly', 'required'):
128 if a in modifiers and not modifiers[a]:
132 def transfer_modifiers_to_node(modifiers, node):
134 simplify_modifiers(modifiers)
135 node.set('modifiers', simplejson.dumps(modifiers))
137 def setup_modifiers(node, field=None, context=None, in_tree_view=False):
138 """ Processes node attributes and field descriptors to generate
139 the ``modifiers`` node attribute and set it on the provided node.
141 Alters its first argument in-place.
143 :param node: ``field`` node from an OpenERP view
144 :type node: lxml.etree._Element
145 :param dict field: field descriptor corresponding to the provided node
146 :param dict context: execution context used to evaluate node attributes
147 :param bool in_tree_view: triggers the ``tree_invisible`` code
148 path (separate from ``invisible``): in
149 tree view there are two levels of
150 invisibility, cell content (a column is
151 present but the cell itself is not
152 displayed) with ``invisible`` and column
153 invisibility (the whole column is
154 hidden) with ``tree_invisible``.
158 if field is not None:
159 transfer_field_to_modifiers(field, modifiers)
160 transfer_node_to_modifiers(
161 node, modifiers, context=context, in_tree_view=in_tree_view)
162 transfer_modifiers_to_node(modifiers, node)
164 def test_modifiers(what, expected):
166 if isinstance(what, basestring):
167 node = etree.fromstring(what)
168 transfer_node_to_modifiers(node, modifiers)
169 simplify_modifiers(modifiers)
170 json = simplejson.dumps(modifiers)
171 assert json == expected, "%s != %s" % (json, expected)
172 elif isinstance(what, dict):
173 transfer_field_to_modifiers(what, modifiers)
174 simplify_modifiers(modifiers)
175 json = simplejson.dumps(modifiers)
176 assert json == expected, "%s != %s" % (json, expected)
181 # openerp.osv.orm.modifiers_tests()
182 def modifiers_tests():
183 test_modifiers('<field name="a"/>', '{}')
184 test_modifiers('<field name="a" invisible="1"/>', '{"invisible": true}')
185 test_modifiers('<field name="a" readonly="1"/>', '{"readonly": true}')
186 test_modifiers('<field name="a" required="1"/>', '{"required": true}')
187 test_modifiers('<field name="a" invisible="0"/>', '{}')
188 test_modifiers('<field name="a" readonly="0"/>', '{}')
189 test_modifiers('<field name="a" required="0"/>', '{}')
190 test_modifiers('<field name="a" invisible="1" required="1"/>', '{"invisible": true, "required": true}') # TODO order is not guaranteed
191 test_modifiers('<field name="a" invisible="1" required="0"/>', '{"invisible": true}')
192 test_modifiers('<field name="a" invisible="0" required="1"/>', '{"required": true}')
193 test_modifiers("""<field name="a" attrs="{'invisible': [('b', '=', 'c')]}"/>""", '{"invisible": [["b", "=", "c"]]}')
195 # The dictionary is supposed to be the result of fields_get().
196 test_modifiers({}, '{}')
197 test_modifiers({"invisible": True}, '{"invisible": true}')
198 test_modifiers({"invisible": False}, '{}')
201 def check_object_name(name):
202 """ Check if the given name is a valid openerp object name.
204 The _name attribute in osv and osv_memory object is subject to
205 some restrictions. This function returns True or False whether
206 the given name is allowed or not.
208 TODO: this is an approximation. The goal in this approximation
209 is to disallow uppercase characters (in some places, we quote
210 table/column names and in other not, which leads to this kind
213 psycopg2.ProgrammingError: relation "xxx" does not exist).
215 The same restriction should apply to both osv and osv_memory
216 objects for consistency.
219 if regex_object_name.match(name) is None:
223 def raise_on_invalid_object_name(name):
224 if not check_object_name(name):
225 msg = "The _name attribute %s is not valid." % name
227 raise except_orm('ValueError', msg)
229 POSTGRES_CONFDELTYPES = {
237 def intersect(la, lb):
238 return filter(lambda x: x in lb, la)
240 def fix_import_export_id_paths(fieldname):
242 Fixes the id fields in import and exports, and splits field paths
245 :param str fieldname: name of the field to import/export
246 :return: split field name
249 fixed_db_id = re.sub(r'([^/])\.id', r'\1/.id', fieldname)
250 fixed_external_id = re.sub(r'([^/]):id', r'\1/id', fixed_db_id)
251 return fixed_external_id.split('/')
253 class except_orm(Exception):
254 def __init__(self, name, value):
257 self.args = (name, value)
259 class BrowseRecordError(Exception):
262 class browse_null(object):
263 """ Readonly python database object browser
269 def __getitem__(self, name):
272 def __getattr__(self, name):
273 return None # XXX: return self ?
281 def __nonzero__(self):
284 def __unicode__(self):
289 # TODO: execute an object method on browse_record_list
291 class browse_record_list(list):
292 """ Collection of browse objects
294 Such an instance will be returned when doing a ``browse([ids..])``
295 and will be iterable, yielding browse() objects
298 def __init__(self, lst, context=None):
301 super(browse_record_list, self).__init__(lst)
302 self.context = context
305 class browse_record(object):
306 """ An object that behaves like a row of an object's table.
307 It has attributes after the columns of the corresponding object.
311 uobj = pool.get('res.users')
312 user_rec = uobj.browse(cr, uid, 104)
316 def __init__(self, cr, uid, id, table, cache, context=None,
317 list_class=browse_record_list, fields_process=None):
319 :param table: the browsed object (inherited from orm)
320 :param dict cache: a dictionary of model->field->data to be shared
321 across browse objects, thus reducing the SQL
322 read()s. It can speed up things a lot, but also be
323 disastrous if not discarded after write()/unlink()
325 :param dict context: dictionary with an optional context
327 if fields_process is None:
331 self._list_class = list_class
335 self._table = table # deprecated, use _model!
337 self._table_name = self._table._name
338 self.__logger = logging.getLogger('openerp.osv.orm.browse_record.' + self._table_name)
339 self._context = context
340 self._fields_process = fields_process
342 cache.setdefault(table._name, {})
343 self._data = cache[table._name]
345 # if not (id and isinstance(id, (int, long,))):
346 # raise BrowseRecordError(_('Wrong ID for the browse record, got %r, expected an integer.') % (id,))
347 # if not table.exists(cr, uid, id, context):
348 # raise BrowseRecordError(_('Object %s does not exists') % (self,))
350 if id not in self._data:
351 self._data[id] = {'id': id}
355 def __getitem__(self, name):
359 if name not in self._data[self._id]:
360 # build the list of fields we will fetch
362 # fetch the definition of the field which was asked for
363 if name in self._table._columns:
364 col = self._table._columns[name]
365 elif name in self._table._inherit_fields:
366 col = self._table._inherit_fields[name][2]
367 elif hasattr(self._table, str(name)):
368 attr = getattr(self._table, name)
369 if isinstance(attr, (types.MethodType, types.LambdaType, types.FunctionType)):
370 def function_proxy(*args, **kwargs):
371 if 'context' not in kwargs and self._context:
372 kwargs.update(context=self._context)
373 return attr(self._cr, self._uid, [self._id], *args, **kwargs)
374 return function_proxy
378 error_msg = "Field '%s' does not exist in object '%s'" % (name, self)
379 self.__logger.warning(error_msg)
380 raise KeyError(error_msg)
382 # if the field is a classic one or a many2one, we'll fetch all classic and many2one fields
384 # gen the list of "local" (ie not inherited) fields which are classic or many2one
385 fields_to_fetch = filter(lambda x: x[1]._classic_write, self._table._columns.items())
386 # gen the list of inherited fields
387 inherits = map(lambda x: (x[0], x[1][2]), self._table._inherit_fields.items())
388 # complete the field list with the inherited fields which are classic or many2one
389 fields_to_fetch += filter(lambda x: x[1]._classic_write, inherits)
390 # otherwise we fetch only that field
392 fields_to_fetch = [(name, col)]
393 ids = filter(lambda id: name not in self._data[id], self._data.keys())
395 field_names = map(lambda x: x[0], fields_to_fetch)
396 field_values = self._table.read(self._cr, self._uid, ids, field_names, context=self._context, load="_classic_write")
398 # TODO: improve this, very slow for reports
399 if self._fields_process:
400 lang = self._context.get('lang', 'en_US') or 'en_US'
401 lang_obj_ids = self.pool.get('res.lang').search(self._cr, self._uid, [('code', '=', lang)])
403 raise Exception(_('Language with code "%s" is not defined in your system !\nDefine it through the Administration menu.') % (lang,))
404 lang_obj = self.pool.get('res.lang').browse(self._cr, self._uid, lang_obj_ids[0])
406 for field_name, field_column in fields_to_fetch:
407 if field_column._type in self._fields_process:
408 for result_line in field_values:
409 result_line[field_name] = self._fields_process[field_column._type](result_line[field_name])
410 if result_line[field_name]:
411 result_line[field_name].set_value(self._cr, self._uid, result_line[field_name], self, field_column, lang_obj)
414 # Where did those ids come from? Perhaps old entries in ir_model_dat?
415 _logger.warning("No field_values found for ids %s in %s", ids, self)
416 raise KeyError('Field %s not found in %s'%(name, self))
417 # create browse records for 'remote' objects
418 for result_line in field_values:
420 for field_name, field_column in fields_to_fetch:
421 if field_column._type == 'many2one':
422 if result_line[field_name]:
423 obj = self._table.pool.get(field_column._obj)
424 if isinstance(result_line[field_name], (list, tuple)):
425 value = result_line[field_name][0]
427 value = result_line[field_name]
429 # FIXME: this happen when a _inherits object
430 # overwrite a field of it parent. Need
431 # testing to be sure we got the right
432 # object and not the parent one.
433 if not isinstance(value, browse_record):
435 # In some cases the target model is not available yet, so we must ignore it,
436 # which is safe in most cases, this value will just be loaded later when needed.
437 # This situation can be caused by custom fields that connect objects with m2o without
438 # respecting module dependencies, causing relationships to be connected to soon when
439 # the target is not loaded yet.
441 new_data[field_name] = browse_record(self._cr,
442 self._uid, value, obj, self._cache,
443 context=self._context,
444 list_class=self._list_class,
445 fields_process=self._fields_process)
447 new_data[field_name] = value
449 new_data[field_name] = browse_null()
451 new_data[field_name] = browse_null()
452 elif field_column._type in ('one2many', 'many2many') and len(result_line[field_name]):
453 new_data[field_name] = self._list_class([browse_record(self._cr, self._uid, id, self._table.pool.get(field_column._obj), self._cache, context=self._context, list_class=self._list_class, fields_process=self._fields_process) for id in result_line[field_name]], self._context)
454 elif field_column._type in ('reference'):
455 if result_line[field_name]:
456 if isinstance(result_line[field_name], browse_record):
457 new_data[field_name] = result_line[field_name]
459 ref_obj, ref_id = result_line[field_name].split(',')
460 ref_id = long(ref_id)
462 obj = self._table.pool.get(ref_obj)
463 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)
465 new_data[field_name] = browse_null()
467 new_data[field_name] = browse_null()
469 new_data[field_name] = result_line[field_name]
470 self._data[result_line['id']].update(new_data)
472 if not name in self._data[self._id]:
473 # How did this happen? Could be a missing model due to custom fields used too soon, see above.
474 self.__logger.error("Fields to fetch: %s, Field values: %s", field_names, field_values)
475 self.__logger.error("Cached: %s, Table: %s", self._data[self._id], self._table)
476 raise KeyError(_('Unknown attribute %s in %s ') % (name, self))
477 return self._data[self._id][name]
479 def __getattr__(self, name):
483 raise AttributeError(e)
485 def __contains__(self, name):
486 return (name in self._table._columns) or (name in self._table._inherit_fields) or hasattr(self._table, name)
489 raise NotImplementedError("Iteration is not allowed on %s" % self)
491 def __hasattr__(self, name):
498 return "browse_record(%s, %d)" % (self._table_name, self._id)
500 def __eq__(self, other):
501 if not isinstance(other, browse_record):
503 return (self._table_name, self._id) == (other._table_name, other._id)
505 def __ne__(self, other):
506 if not isinstance(other, browse_record):
508 return (self._table_name, self._id) != (other._table_name, other._id)
510 # we need to define __unicode__ even though we've already defined __str__
511 # because we have overridden __getattr__
512 def __unicode__(self):
513 return unicode(str(self))
516 return hash((self._table_name, self._id))
521 """Force refreshing this browse_record's data and all the data of the
522 records that belong to the same cache, by emptying the cache completely,
523 preserving only the record identifiers (for prefetching optimizations).
525 for model, model_cache in self._cache.iteritems():
526 # only preserve the ids of the records that were in the cache
527 cached_ids = dict([(i, {'id': i}) for i in model_cache.keys()])
528 self._cache[model].clear()
529 self._cache[model].update(cached_ids)
531 def pg_varchar(size=0):
532 """ Returns the VARCHAR declaration for the provided size:
534 * If no size (or an empty or negative size is provided) return an
536 * Otherwise return a VARCHAR(n)
538 :type int size: varchar size, optional
542 if not isinstance(size, int):
543 raise TypeError("VARCHAR parameter should be an int, got %s"
546 return 'VARCHAR(%d)' % size
549 FIELDS_TO_PGTYPES = {
550 fields.boolean: 'bool',
551 fields.integer: 'int4',
555 fields.datetime: 'timestamp',
556 fields.binary: 'bytea',
557 fields.many2one: 'int4',
558 fields.serialized: 'text',
561 def get_pg_type(f, type_override=None):
563 :param fields._column f: field to get a Postgres type for
564 :param type type_override: use the provided type for dispatching instead of the field's own type
565 :returns: (postgres_identification_type, postgres_type_specification)
568 field_type = type_override or type(f)
570 if field_type in FIELDS_TO_PGTYPES:
571 pg_type = (FIELDS_TO_PGTYPES[field_type], FIELDS_TO_PGTYPES[field_type])
572 elif issubclass(field_type, fields.float):
574 pg_type = ('numeric', 'NUMERIC')
576 pg_type = ('float8', 'DOUBLE PRECISION')
577 elif issubclass(field_type, (fields.char, fields.reference)):
578 pg_type = ('varchar', pg_varchar(f.size))
579 elif issubclass(field_type, fields.selection):
580 if (isinstance(f.selection, list) and isinstance(f.selection[0][0], int))\
581 or getattr(f, 'size', None) == -1:
582 pg_type = ('int4', 'INTEGER')
584 pg_type = ('varchar', pg_varchar(getattr(f, 'size', None)))
585 elif issubclass(field_type, fields.function):
586 if f._type == 'selection':
587 pg_type = ('varchar', pg_varchar())
589 pg_type = get_pg_type(f, getattr(fields, f._type))
591 _logger.warning('%s type not supported!', field_type)
597 class MetaModel(type):
598 """ Metaclass for the Model.
600 This class is used as the metaclass for the Model class to discover
601 the models defined in a module (i.e. without instanciating them).
602 If the automatic discovery is not needed, it is possible to set the
603 model's _register attribute to False.
607 module_to_models = {}
609 def __init__(self, name, bases, attrs):
610 if not self._register:
611 self._register = True
612 super(MetaModel, self).__init__(name, bases, attrs)
615 # The (OpenERP) module name can be in the `openerp.addons` namespace
616 # or not. For instance module `sale` can be imported as
617 # `openerp.addons.sale` (the good way) or `sale` (for backward
619 module_parts = self.__module__.split('.')
620 if len(module_parts) > 2 and module_parts[0] == 'openerp' and \
621 module_parts[1] == 'addons':
622 module_name = self.__module__.split('.')[2]
624 module_name = self.__module__.split('.')[0]
625 if not hasattr(self, '_module'):
626 self._module = module_name
628 # Remember which models to instanciate for this module.
629 self.module_to_models.setdefault(self._module, []).append(self)
632 # Definition of log access columns, automatically added to models if
633 # self._log_access is True
634 LOG_ACCESS_COLUMNS = {
635 'create_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
636 'create_date': 'TIMESTAMP',
637 'write_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
638 'write_date': 'TIMESTAMP'
640 # special columns automatically created by the ORM
641 MAGIC_COLUMNS = ['id'] + LOG_ACCESS_COLUMNS.keys()
643 class BaseModel(object):
644 """ Base class for OpenERP models.
646 OpenERP models are created by inheriting from this class' subclasses:
648 * Model: for regular database-persisted models
649 * TransientModel: for temporary data, stored in the database but automatically
650 vaccuumed every so often
651 * AbstractModel: for abstract super classes meant to be shared by multiple
652 _inheriting classes (usually Models or TransientModels)
654 The system will later instantiate the class once per database (on
655 which the class' module is installed).
657 To create a class that should not be instantiated, the _register class attribute
660 __metaclass__ = MetaModel
661 _auto = True # create database backend
662 _register = False # Set to false if the model shouldn't be automatically discovered.
668 _parent_name = 'parent_id'
669 _parent_store = False
670 _parent_order = False
677 # dict of {field:method}, with method returning the (name_get of records, {id: fold})
678 # to include in the _read_group, if grouped on this field
682 _transient = False # True in a TransientModel
683 _transient_max_count = None
684 _transient_max_hours = None
685 _transient_check_time = 20
688 # { 'parent_model': 'm2o_field', ... }
691 # Mapping from inherits'd field name to triple (m, r, f, n) where m is the
692 # model from which it is inherits'd, r is the (local) field towards m, f
693 # is the _column object itself, and n is the original (i.e. top-most)
696 # { 'field_name': ('parent_model', 'm2o_field_to_reach_parent',
697 # field_column_obj, origina_parent_model), ... }
700 # Mapping field name/column_info object
701 # This is similar to _inherit_fields but:
702 # 1. includes self fields,
703 # 2. uses column_info instead of a triple.
709 _sql_constraints = []
710 _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']
712 CONCURRENCY_CHECK_FIELD = '__last_update'
714 def log(self, cr, uid, id, message, secondary=False, context=None):
715 return _logger.warning("log() is deprecated. Please use OpenChatter notification system instead of the res.log mechanism.")
717 def view_init(self, cr, uid, fields_list, context=None):
718 """Override this method to do specific things when a view on the object is opened."""
721 def _field_create(self, cr, context=None):
722 """ Create entries in ir_model_fields for all the model's fields.
724 If necessary, also create an entry in ir_model, and if called from the
725 modules loading scheme (by receiving 'module' in the context), also
726 create entries in ir_model_data (for the model and the fields).
728 - create an entry in ir_model (if there is not already one),
729 - create an entry in ir_model_data (if there is not already one, and if
730 'module' is in the context),
731 - update ir_model_fields with the fields found in _columns
732 (TODO there is some redundancy as _columns is updated from
733 ir_model_fields in __init__).
738 cr.execute("SELECT id FROM ir_model WHERE model=%s", (self._name,))
740 cr.execute('SELECT nextval(%s)', ('ir_model_id_seq',))
741 model_id = cr.fetchone()[0]
742 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'))
744 model_id = cr.fetchone()[0]
745 if 'module' in context:
746 name_id = 'model_'+self._name.replace('.', '_')
747 cr.execute('select * from ir_model_data where name=%s and module=%s', (name_id, context['module']))
749 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)", \
750 (name_id, context['module'], 'ir.model', model_id)
755 cr.execute("SELECT * FROM ir_model_fields WHERE model=%s", (self._name,))
757 for rec in cr.dictfetchall():
758 cols[rec['name']] = rec
760 ir_model_fields_obj = self.pool.get('ir.model.fields')
762 # sparse field should be created at the end, as it depends on its serialized field already existing
763 model_fields = sorted(self._columns.items(), key=lambda x: 1 if x[1]._type == 'sparse' else 0)
764 for (k, f) in model_fields:
766 'model_id': model_id,
769 'field_description': f.string,
771 'relation': f._obj or '',
772 'view_load': (f.view_load and 1) or 0,
773 'select_level': tools.ustr(f.select or 0),
774 'readonly': (f.readonly and 1) or 0,
775 'required': (f.required and 1) or 0,
776 'selectable': (f.selectable and 1) or 0,
777 'translate': (f.translate and 1) or 0,
778 'relation_field': f._fields_id if isinstance(f, fields.one2many) else '',
779 'serialization_field_id': None,
781 if getattr(f, 'serialization_field', None):
782 # resolve link to serialization_field if specified by name
783 serialization_field_id = ir_model_fields_obj.search(cr, SUPERUSER_ID, [('model','=',vals['model']), ('name', '=', f.serialization_field)])
784 if not serialization_field_id:
785 raise except_orm(_('Error'), _("Serialization field `%s` not found for sparse field `%s`!") % (f.serialization_field, k))
786 vals['serialization_field_id'] = serialization_field_id[0]
788 # When its a custom field,it does not contain f.select
789 if context.get('field_state', 'base') == 'manual':
790 if context.get('field_name', '') == k:
791 vals['select_level'] = context.get('select', '0')
792 #setting value to let the problem NOT occur next time
794 vals['select_level'] = cols[k]['select_level']
797 cr.execute('select nextval(%s)', ('ir_model_fields_id_seq',))
798 id = cr.fetchone()[0]
800 cr.execute("""INSERT INTO ir_model_fields (
801 id, model_id, model, name, field_description, ttype,
802 relation,view_load,state,select_level,relation_field, translate, serialization_field_id
804 %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s
806 id, vals['model_id'], vals['model'], vals['name'], vals['field_description'], vals['ttype'],
807 vals['relation'], bool(vals['view_load']), 'base',
808 vals['select_level'], vals['relation_field'], bool(vals['translate']), vals['serialization_field_id']
810 if 'module' in context:
811 name1 = 'field_' + self._table + '_' + k
812 cr.execute("select name from ir_model_data where name=%s", (name1,))
814 name1 = name1 + "_" + str(id)
815 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)", \
816 (name1, context['module'], 'ir.model.fields', id)
819 for key, val in vals.items():
820 if cols[k][key] != vals[key]:
821 cr.execute('update ir_model_fields set field_description=%s where model=%s and name=%s', (vals['field_description'], vals['model'], vals['name']))
823 cr.execute("""UPDATE ir_model_fields SET
824 model_id=%s, field_description=%s, ttype=%s, relation=%s,
825 view_load=%s, select_level=%s, readonly=%s ,required=%s, selectable=%s, relation_field=%s, translate=%s, serialization_field_id=%s
827 model=%s AND name=%s""", (
828 vals['model_id'], vals['field_description'], vals['ttype'],
829 vals['relation'], bool(vals['view_load']),
830 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']
836 # Goal: try to apply inheritance at the instanciation level and
837 # put objects in the pool var
840 def create_instance(cls, pool, cr):
841 """ Instanciate a given model.
843 This class method instanciates the class of some model (i.e. a class
844 deriving from osv or osv_memory). The class might be the class passed
845 in argument or, if it inherits from another class, a class constructed
846 by combining the two classes.
848 The ``attributes`` argument specifies which parent class attributes
851 TODO: the creation of the combined class is repeated at each call of
852 this method. This is probably unnecessary.
855 attributes = ['_columns', '_defaults', '_inherits', '_constraints',
858 parent_names = getattr(cls, '_inherit', None)
860 if isinstance(parent_names, (str, unicode)):
861 name = cls._name or parent_names
862 parent_names = [parent_names]
865 # for res.parnter.address compatiblity, should be remove in v7
866 if 'res.partner.address' in parent_names:
867 parent_names.pop(parent_names.index('res.partner.address'))
868 parent_names.append('res.partner')
870 raise TypeError('_name is mandatory in case of multiple inheritance')
872 for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]):
873 parent_model = pool.get(parent_name)
875 raise TypeError('The model "%s" specifies an unexisting parent class "%s"\n'
876 'You may need to add a dependency on the parent class\' module.' % (name, parent_name))
877 if not getattr(cls, '_original_module', None) and name == parent_model._name:
878 cls._original_module = parent_model._original_module
879 parent_class = parent_model.__class__
882 new = copy.copy(getattr(parent_model, s, {}))
884 # Don't _inherit custom fields.
888 # Duplicate float fields because they have a .digits
889 # cache (which must be per-registry, not server-wide).
891 if new[c]._type == 'float':
892 new[c] = copy.copy(new[c])
893 if hasattr(new, 'update'):
894 new.update(cls.__dict__.get(s, {}))
895 elif s=='_constraints':
896 for c in cls.__dict__.get(s, []):
898 for c2 in range(len(new)):
899 #For _constraints, we should check field and methods as well
900 if new[c2][2]==c[2] and (new[c2][0] == c[0] \
901 or getattr(new[c2][0],'__name__', True) == \
902 getattr(c[0],'__name__', False)):
903 # If new class defines a constraint with
904 # same function name, we let it override
913 new.extend(cls.__dict__.get(s, []))
915 cls = type(name, (cls, parent_class), dict(nattr, _register=False))
916 if not getattr(cls, '_original_module', None):
917 cls._original_module = cls._module
918 obj = object.__new__(cls)
919 obj.__init__(pool, cr)
923 """Register this model.
925 This doesn't create an instance but simply register the model
926 as being part of the module where it is defined.
931 # Set the module name (e.g. base, sale, accounting, ...) on the class.
932 module = cls.__module__.split('.')[0]
933 if not hasattr(cls, '_module'):
936 # Record this class in the list of models to instantiate for this module,
937 # managed by the metaclass.
938 module_model_list = MetaModel.module_to_models.setdefault(cls._module, [])
939 if cls not in module_model_list:
940 module_model_list.append(cls)
942 # Since we don't return an instance here, the __init__
943 # method won't be called.
946 def __init__(self, pool, cr):
947 """ Initialize a model and make it part of the given registry.
949 - copy the stored fields' functions in the osv_pool,
950 - update the _columns with the fields found in ir_model_fields,
951 - ensure there is a many2one for each _inherits'd parent,
952 - update the children's _columns,
953 - give a chance to each field to initialize itself.
956 pool.add(self._name, self)
959 if not self._name and not hasattr(self, '_inherit'):
960 name = type(self).__name__.split('.')[0]
961 msg = "The class %s has to have a _name attribute" % name
964 raise except_orm('ValueError', msg)
966 if not self._description:
967 self._description = self._name
969 self._table = self._name.replace('.', '_')
971 if not hasattr(self, '_log_access'):
972 # If _log_access is not specified, it is the same value as _auto.
973 self._log_access = getattr(self, "_auto", True)
975 self._columns = self._columns.copy()
976 for store_field in self._columns:
977 f = self._columns[store_field]
978 if hasattr(f, 'digits_change'):
980 def not_this_field(stored_func):
981 x, y, z, e, f, l = stored_func
982 return x != self._name or y != store_field
983 self.pool._store_function[self._name] = filter(not_this_field, self.pool._store_function.get(self._name, []))
984 if not isinstance(f, fields.function):
990 sm = {self._name: (lambda self, cr, uid, ids, c={}: ids, None, 10, None)}
991 for object, aa in sm.items():
993 (fnct, fields2, order, length) = aa
995 (fnct, fields2, order) = aa
998 raise except_orm('Error',
999 ('Invalid function definition %s in object %s !\nYou must use the definition: store={object:(fnct, fields, priority, time length)}.' % (store_field, self._name)))
1000 self.pool._store_function.setdefault(object, [])
1001 self.pool._store_function[object].append((self._name, store_field, fnct, tuple(fields2) if fields2 else None, order, length))
1002 self.pool._store_function[object].sort(lambda x, y: cmp(x[4], y[4]))
1004 for (key, _, msg) in self._sql_constraints:
1005 self.pool._sql_error[self._table+'_'+key] = msg
1007 # Load manual fields
1009 cr.execute("SELECT id FROM ir_model_fields WHERE name=%s AND model=%s", ('state', 'ir.model.fields'))
1011 cr.execute('SELECT * FROM ir_model_fields WHERE model=%s AND state=%s', (self._name, 'manual'))
1012 for field in cr.dictfetchall():
1013 if field['name'] in self._columns:
1016 'string': field['field_description'],
1017 'required': bool(field['required']),
1018 'readonly': bool(field['readonly']),
1019 'domain': eval(field['domain']) if field['domain'] else None,
1020 'size': field['size'],
1021 'ondelete': field['on_delete'],
1022 'translate': (field['translate']),
1024 #'select': int(field['select_level'])
1027 if field['serialization_field_id']:
1028 cr.execute('SELECT name FROM ir_model_fields WHERE id=%s', (field['serialization_field_id'],))
1029 attrs.update({'serialization_field': cr.fetchone()[0], 'type': field['ttype']})
1030 if field['ttype'] in ['many2one', 'one2many', 'many2many']:
1031 attrs.update({'relation': field['relation']})
1032 self._columns[field['name']] = fields.sparse(**attrs)
1033 elif field['ttype'] == 'selection':
1034 self._columns[field['name']] = fields.selection(eval(field['selection']), **attrs)
1035 elif field['ttype'] == 'reference':
1036 self._columns[field['name']] = fields.reference(selection=eval(field['selection']), **attrs)
1037 elif field['ttype'] == 'many2one':
1038 self._columns[field['name']] = fields.many2one(field['relation'], **attrs)
1039 elif field['ttype'] == 'one2many':
1040 self._columns[field['name']] = fields.one2many(field['relation'], field['relation_field'], **attrs)
1041 elif field['ttype'] == 'many2many':
1042 _rel1 = field['relation'].replace('.', '_')
1043 _rel2 = field['model'].replace('.', '_')
1044 _rel_name = 'x_%s_%s_%s_rel' % (_rel1, _rel2, field['name'])
1045 self._columns[field['name']] = fields.many2many(field['relation'], _rel_name, 'id1', 'id2', **attrs)
1047 self._columns[field['name']] = getattr(fields, field['ttype'])(**attrs)
1048 self._inherits_check()
1049 self._inherits_reload()
1050 if not self._sequence:
1051 self._sequence = self._table + '_id_seq'
1052 for k in self._defaults:
1053 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,)
1054 for f in self._columns:
1055 self._columns[f].restart()
1058 if self.is_transient():
1059 self._transient_check_count = 0
1060 self._transient_max_count = config.get('osv_memory_count_limit')
1061 self._transient_max_hours = config.get('osv_memory_age_limit')
1062 assert self._log_access, "TransientModels must have log_access turned on, "\
1063 "in order to implement their access rights policy"
1066 if self._rec_name is not None:
1067 assert self._rec_name in self._columns.keys() + ['id'], "Invalid rec_name %s for model %s" % (self._rec_name, self._name)
1069 self._rec_name = 'name'
1072 def __export_row(self, cr, uid, row, fields, context=None):
1076 def check_type(field_type):
1077 if field_type == 'float':
1079 elif field_type == 'integer':
1081 elif field_type == 'boolean':
1085 def selection_field(in_field):
1086 col_obj = self.pool.get(in_field.keys()[0])
1087 if f[i] in col_obj._columns.keys():
1088 return col_obj._columns[f[i]]
1089 elif f[i] in col_obj._inherits.keys():
1090 selection_field(col_obj._inherits)
1094 def _get_xml_id(self, cr, uid, r):
1095 model_data = self.pool.get('ir.model.data')
1096 data_ids = model_data.search(cr, uid, [('model', '=', r._table_name), ('res_id', '=', r['id'])])
1098 d = model_data.read(cr, uid, data_ids, ['name', 'module'])[0]
1100 r = '%s.%s' % (d['module'], d['name'])
1106 n = self._table+'_'+str(r['id']) + (postfix and ('_'+str(postfix)) or '' )
1107 if not model_data.search(cr, uid, [('name', '=', n)]):
1110 model_data.create(cr, uid, {
1112 'model': self._name,
1114 'module': '__export__',
1120 data = map(lambda x: '', range(len(fields)))
1122 for fpos in range(len(fields)):
1132 r = _get_xml_id(self, cr, uid, r)
1135 # To display external name of selection field when its exported
1136 if f[i] in self._columns.keys():
1137 cols = self._columns[f[i]]
1138 elif f[i] in self._inherit_fields.keys():
1139 cols = selection_field(self._inherits)
1140 if cols and cols._type == 'selection':
1141 sel_list = cols.selection
1142 if r and type(sel_list) == type([]):
1143 r = [x[1] for x in sel_list if r==x[0]]
1144 r = r and r[0] or False
1146 if f[i] in self._columns:
1147 r = check_type(self._columns[f[i]]._type)
1148 elif f[i] in self._inherit_fields:
1149 r = check_type(self._inherit_fields[f[i]][2]._type)
1150 data[fpos] = r or False
1152 if isinstance(r, (browse_record_list, list)):
1154 fields2 = map(lambda x: (x[:i+1]==f[:i+1] and x[i+1:]) \
1157 if [x for x in fields2 if x]:
1159 done.append(fields2)
1160 if cols and cols._type=='many2many' and len(fields[fpos])>(i+1) and (fields[fpos][i+1]=='id'):
1161 data[fpos] = ','.join([_get_xml_id(self, cr, uid, x) for x in r])
1165 lines2 = row2._model.__export_row(cr, uid, row2, fields2,
1168 for fpos2 in range(len(fields)):
1169 if lines2 and lines2[0][fpos2]:
1170 data[fpos2] = lines2[0][fpos2]
1174 name_relation = self.pool.get(rr._table_name)._rec_name
1175 if isinstance(rr[name_relation], browse_record):
1176 rr = rr[name_relation]
1177 rr_name = self.pool.get(rr._table_name).name_get(cr, uid, [rr.id], context=context)
1178 rr_name = rr_name and rr_name[0] and rr_name[0][1] or ''
1179 dt += tools.ustr(rr_name or '') + ','
1180 data[fpos] = dt[:-1]
1189 if isinstance(r, browse_record):
1190 r = self.pool.get(r._table_name).name_get(cr, uid, [r.id], context=context)
1191 r = r and r[0] and r[0][1] or ''
1192 data[fpos] = tools.ustr(r or '')
1193 return [data] + lines
1195 def export_data(self, cr, uid, ids, fields_to_export, context=None):
1197 Export fields for selected objects
1199 :param cr: database cursor
1200 :param uid: current user id
1201 :param ids: list of ids
1202 :param fields_to_export: list of fields
1203 :param context: context arguments, like lang, time zone
1204 :rtype: dictionary with a *datas* matrix
1206 This method is used when exporting data via client menu
1211 cols = self._columns.copy()
1212 for f in self._inherit_fields:
1213 cols.update({f: self._inherit_fields[f][2]})
1214 fields_to_export = map(fix_import_export_id_paths, fields_to_export)
1216 for row in self.browse(cr, uid, ids, context):
1217 datas += self.__export_row(cr, uid, row, fields_to_export, context)
1218 return {'datas': datas}
1220 def import_data(self, cr, uid, fields, datas, mode='init', current_module='', noupdate=False, context=None, filename=None):
1221 """Import given data in given module
1223 This method is used when importing data via client menu.
1225 Example of fields to import for a sale.order::
1228 partner_id, (=name_search)
1229 order_line/.id, (=database_id)
1231 order_line/product_id/id, (=xml id)
1232 order_line/price_unit,
1233 order_line/product_uom_qty,
1234 order_line/product_uom/id (=xml_id)
1236 This method returns a 4-tuple with the following structure::
1238 (return_code, errored_resource, error_message, unused)
1240 * The first item is a return code, it is ``-1`` in case of
1241 import error, or the last imported row number in case of success
1242 * The second item contains the record data dict that failed to import
1243 in case of error, otherwise it's 0
1244 * The third item contains an error message string in case of error,
1246 * The last item is currently unused, with no specific semantics
1248 :param fields: list of fields to import
1249 :param datas: data to import
1250 :param mode: 'init' or 'update' for record creation
1251 :param current_module: module name
1252 :param noupdate: flag for record creation
1253 :param filename: optional file to store partial import state for recovery
1254 :returns: 4-tuple in the form (return_code, errored_resource, error_message, unused)
1255 :rtype: (int, dict or 0, str or 0, str or 0)
1259 fields = map(fix_import_export_id_paths, fields)
1260 ir_model_data_obj = self.pool.get('ir.model.data')
1262 # mode: id (XML id) or .id (database id) or False for name_get
1263 def _get_id(model_name, id, current_module=False, mode='id'):
1266 obj_model = self.pool.get(model_name)
1267 ids = obj_model.search(cr, uid, [('id', '=', int(id))])
1269 raise Exception(_("Database ID doesn't exist: %s : %s") %(model_name, id))
1272 module, xml_id = id.rsplit('.', 1)
1274 module, xml_id = current_module, id
1275 record_id = ir_model_data_obj._get_id(cr, uid, module, xml_id)
1276 ir_model_data = ir_model_data_obj.read(cr, uid, [record_id], ['res_id'])
1277 if not ir_model_data:
1278 raise ValueError('No references to %s.%s' % (module, xml_id))
1279 id = ir_model_data[0]['res_id']
1281 obj_model = self.pool.get(model_name)
1282 ids = obj_model.name_search(cr, uid, id, operator='=', context=context)
1284 raise ValueError('No record found for %s' % (id,))
1289 # datas: a list of records, each record is defined by a list of values
1290 # prefix: a list of prefix fields ['line_ids']
1291 # position: the line to process, skip is False if it's the first line of the current record
1293 # (res, position, warning, res_id) with
1294 # res: the record for the next line to process (including it's one2many)
1295 # position: the new position for the next line
1296 # res_id: the ID of the record if it's a modification
1297 def process_liness(self, datas, prefix, current_module, model_name, fields_def, position=0, skip=0):
1298 line = datas[position]
1306 for i, field in enumerate(fields):
1309 raise Exception(_('Please check that all your lines have %d columns.'
1310 'Stopped around line %d having %d columns.') % \
1311 (len(fields), position+2, len(line)))
1315 if field[:len(prefix)] <> prefix:
1316 if line[i] and skip:
1319 field_name = field[len(prefix)]
1321 #set the mode for m2o, o2m, m2m : xml_id/id/name
1322 if len(field) == len(prefix)+1:
1325 mode = field[len(prefix)+1]
1327 # TODO: improve this by using csv.csv_reader
1328 def many_ids(line, relation, current_module, mode):
1330 for db_id in line.split(config.get('csv_internal_sep')):
1331 res.append(_get_id(relation, db_id, current_module, mode))
1334 # ID of the record using a XML ID
1335 if field_name == 'id':
1337 data_res_id = _get_id(model_name, line[i], current_module)
1343 # ID of the record using a database ID
1344 elif field_name == '.id':
1345 data_res_id = _get_id(model_name, line[i], current_module, '.id')
1348 field_type = fields_def[field_name]['type']
1349 # recursive call for getting children and returning [(0,0,{})] or [(1,ID,{})]
1350 if field_type == 'one2many':
1351 if field_name in done:
1353 done[field_name] = True
1354 relation = fields_def[field_name]['relation']
1355 relation_obj = self.pool.get(relation)
1356 newfd = relation_obj.fields_get( cr, uid, context=context )
1362 while pos < len(datas):
1363 res2 = process_liness(self, datas, prefix + [field_name], current_module, relation_obj._name, newfd, pos, first)
1366 (newrow, pos, w2, data_res_id2, xml_id2) = res2
1367 nbrmax = max(nbrmax, pos)
1371 if (not newrow) or not reduce(lambda x, y: x or y, newrow.values(), 0):
1374 res.append( (data_res_id2 and 1 or 0, data_res_id2 or 0, newrow) )
1376 elif field_type == 'many2one':
1377 relation = fields_def[field_name]['relation']
1378 res = _get_id(relation, line[i], current_module, mode)
1380 elif field_type == 'many2many':
1381 relation = fields_def[field_name]['relation']
1382 res = many_ids(line[i], relation, current_module, mode)
1384 elif field_type == 'integer':
1385 res = line[i] and int(line[i]) or 0
1386 elif field_type == 'boolean':
1387 res = line[i].lower() not in ('0', 'false', 'off')
1388 elif field_type == 'float':
1389 res = line[i] and float(line[i]) or 0.0
1390 elif field_type == 'selection':
1391 for key, val in fields_def[field_name]['selection']:
1392 if tools.ustr(line[i]) in [tools.ustr(key), tools.ustr(val)]:
1395 if line[i] and not res:
1397 _("key '%s' not found in selection field '%s'"),
1398 tools.ustr(line[i]), tools.ustr(field_name))
1399 warning.append(_("Key/value '%s' not found in selection field '%s'") % (
1400 tools.ustr(line[i]), tools.ustr(field_name)))
1405 row[field_name] = res or False
1407 return row, nbrmax, warning, data_res_id, xml_id
1409 fields_def = self.fields_get(cr, uid, context=context)
1412 if config.get('import_partial') and filename:
1413 with open(config.get('import_partial'), 'rb') as partial_import_file:
1414 data = pickle.load(partial_import_file)
1415 position = data.get(filename, 0)
1417 while position<len(datas):
1418 (res, position, warning, res_id, xml_id) = \
1419 process_liness(self, datas, [], current_module, self._name, fields_def, position=position)
1422 return -1, res, 'Line ' + str(position) +' : ' + '!\n'.join(warning), ''
1425 ir_model_data_obj._update(cr, uid, self._name,
1426 current_module, res, mode=mode, xml_id=xml_id,
1427 noupdate=noupdate, res_id=res_id, context=context)
1428 except Exception, e:
1429 return -1, res, 'Line ' + str(position) + ' : ' + tools.ustr(e), ''
1431 if config.get('import_partial') and filename and (not (position%100)):
1432 with open(config.get('import_partial'), 'rb') as partial_import:
1433 data = pickle.load(partial_import)
1434 data[filename] = position
1435 with open(config.get('import_partial'), 'wb') as partial_import:
1436 pickle.dump(data, partial_import)
1437 if context.get('defer_parent_store_computation'):
1438 self._parent_store_compute(cr)
1441 if context.get('defer_parent_store_computation'):
1442 self._parent_store_compute(cr)
1443 return position, 0, 0, 0
1445 def load(self, cr, uid, fields, data, context=None):
1448 :param cr: cursor for the request
1449 :param int uid: ID of the user attempting the data import
1450 :param fields: list of fields to import, at the same index as the corresponding data
1451 :type fields: list(str)
1452 :param data: row-major matrix of data to import
1453 :type data: list(list(str))
1454 :param dict context:
1457 cr.execute('SAVEPOINT model_load')
1460 fields = map(fix_import_export_id_paths, fields)
1461 ModelData = self.pool['ir.model.data']
1468 for id, xid, record, info in self._convert_records(cr, uid,
1469 self._extract_records(cr, uid, fields, data,
1470 context=context, log=messages.append),
1471 context=context, log=messages.append):
1472 cr.execute('SAVEPOINT model_load_save')
1474 ids.append(ModelData._update(cr, uid, self._name,
1475 current_module, record, mode=mode, xml_id=xid,
1476 noupdate=noupdate, res_id=id, context=context))
1477 cr.execute('RELEASE SAVEPOINT model_load_save')
1478 except psycopg2.Error, e:
1479 # Failed to write, log to messages, rollback savepoint (to
1480 # avoid broken transaction) and keep going
1481 cr.execute('ROLLBACK TO SAVEPOINT model_load_save')
1482 messages.append(dict(info, type="error", message=str(e)))
1483 if any(message['type'] == 'error' for message in messages):
1484 cr.execute('ROLLBACK TO SAVEPOINT model_load')
1485 return False, messages
1486 return ids, messages
1487 def _extract_records(self, cr, uid, fields_, data,
1488 context=None, log=lambda a: None):
1489 """ Generates record dicts from the data iterable.
1491 The result is a generator of dicts mapping field names to raw
1492 (unconverted, unvalidated) values.
1494 For relational fields, if sub-fields were provided the value will be
1495 a list of sub-records
1497 The following sub-fields may be set on the record (by key):
1498 * None is the name_get for the record (to use with name_create/name_search)
1499 * "id" is the External ID for the record
1500 * ".id" is the Database ID for the record
1502 :param ImportLogger logger:
1504 columns = dict((k, v.column) for k, v in self._all_columns.iteritems())
1505 # Fake columns to avoid special cases in extractor
1506 columns[None] = fields.char('rec_name')
1507 columns['id'] = fields.char('External ID')
1508 columns['.id'] = fields.integer('Database ID')
1510 # m2o fields can't be on multiple lines so exclude them from the
1511 # is_relational field rows filter, but special-case it later on to
1512 # be handled with relational fields (as it can have subfields)
1513 is_relational = lambda field: columns[field]._type in ('one2many', 'many2many', 'many2one')
1514 get_o2m_values = itemgetter_tuple(
1515 [index for index, field in enumerate(fields_)
1516 if columns[field[0]]._type == 'one2many'])
1517 get_nono2m_values = itemgetter_tuple(
1518 [index for index, field in enumerate(fields_)
1519 if columns[field[0]]._type != 'one2many'])
1520 # Checks if the provided row has any non-empty non-relational field
1521 def only_o2m_values(row, f=get_nono2m_values, g=get_o2m_values):
1522 return any(g(row)) and not any(f(row))
1524 rows = CountingStream(data)
1526 row = next(rows, None)
1527 if row is None: return
1528 record_row_index = rows.index
1530 # copy non-relational fields to record dict
1531 record = dict((field[0], value)
1532 for field, value in itertools.izip(fields_, row)
1533 if not is_relational(field[0]))
1535 # Get all following rows which have relational values attached to
1536 # the current record (no non-relational values)
1537 # WARNING: replaces existing ``rows``
1538 record_span, _rows = span(only_o2m_values, rows)
1539 # stitch record row back on for relational fields
1540 record_span = itertools.chain([row], record_span)
1541 for relfield in set(
1542 field[0] for field in fields_
1543 if is_relational(field[0])):
1544 column = columns[relfield]
1545 # FIXME: how to not use _obj without relying on fields_get?
1546 Model = self.pool[column._obj]
1548 # copy stream to reuse for next relational field
1549 fieldrows, record_span = itertools.tee(record_span)
1550 # get only cells for this sub-field, should be strictly
1551 # non-empty, field path [None] is for name_get column
1552 indices, subfields = zip(*((index, field[1:] or [None])
1553 for index, field in enumerate(fields_)
1554 if field[0] == relfield))
1556 # return all rows which have at least one value for the
1557 # subfields of relfield
1558 relfield_data = filter(any, map(itemgetter_tuple(indices), fieldrows))
1559 record[relfield] = [subrecord
1560 for subrecord, _subinfo in Model._extract_records(
1561 cr, uid, subfields, relfield_data,
1562 context=context, log=log)]
1563 # Ensure full consumption of the span (and therefore advancement of
1564 # ``rows``) even if there are no relational fields. Needs two as
1565 # the code above stiched the row back on (so first call may only
1566 # get the stiched row without advancing the underlying operator row
1568 next(record_span, None)
1569 next(record_span, None)
1571 # old rows consumption (by iterating the span) should be done here,
1572 # at this point the old ``rows`` is 1 past `span` (either on the
1573 # next record row or past ``StopIteration``, so wrap new ``rows``
1574 # (``_rows``) in a counting stream indexed 1-before the old
1576 rows = CountingStream(_rows, rows.index - 1)
1577 yield record, {'rows': {'from': record_row_index,'to': rows.index}}
1578 def _convert_records(self, cr, uid, records,
1579 context=None, log=lambda a: None):
1580 """ Converts records from the source iterable (recursive dicts of
1581 strings) into forms which can be written to the database (via
1582 self.create or (ir.model.data)._update)
1584 :param ImportLogger parent_logger:
1585 :returns: a list of triplets of (id, xid, record)
1586 :rtype: list((int|None, str|None, dict))
1588 Converter = self.pool['ir.fields.converter']
1589 columns = dict((k, v.column) for k, v in self._all_columns.iteritems())
1591 (k, Converter.to_field(cr, uid, self, column, context=context))
1592 for k, column in columns.iteritems())
1594 stream = CountingStream(records)
1595 for record, extras in stream:
1599 # name_get/name_create
1600 if None in record: pass
1607 dbid = int(record['.id'])
1609 # in case of overridden id column
1610 dbid = record['.id']
1611 if not self.search(cr, uid, [('id', '=', dbid)], context=context):
1614 record=stream.index,
1616 message=_(u"Unknown database identifier '%s'") % dbid))
1619 for field, strvalue in record.iteritems():
1620 if field in (None, 'id', '.id'): continue
1622 message_base = dict(extras, record=stream.index, field=field)
1623 with warnings.catch_warnings(record=True) as w:
1625 converted[field] = converters[field](strvalue)
1628 log(dict(message_base, type='warning',
1629 message=unicode(warning.message) % message_base))
1630 except ValueError, e:
1631 log(dict(message_base,
1633 message=unicode(e) % message_base
1636 yield dbid, xid, converted, dict(extras, record=stream.index)
1638 def get_invalid_fields(self, cr, uid):
1639 return list(self._invalids)
1641 def _validate(self, cr, uid, ids, context=None):
1642 context = context or {}
1643 lng = context.get('lang', False) or 'en_US'
1644 trans = self.pool.get('ir.translation')
1646 for constraint in self._constraints:
1647 fun, msg, fields = constraint
1648 if not fun(self, cr, uid, ids):
1649 # Check presence of __call__ directly instead of using
1650 # callable() because it will be deprecated as of Python 3.0
1651 if hasattr(msg, '__call__'):
1652 tmp_msg = msg(self, cr, uid, ids, context=context)
1653 if isinstance(tmp_msg, tuple):
1654 tmp_msg, params = tmp_msg
1655 translated_msg = tmp_msg % params
1657 translated_msg = tmp_msg
1659 translated_msg = trans._get_source(cr, uid, self._name, 'constraint', lng, msg) or msg
1661 _("Error occurred while validating the field(s) %s: %s") % (','.join(fields), translated_msg)
1663 self._invalids.update(fields)
1666 raise except_orm('ValidateError', '\n'.join(error_msgs))
1668 self._invalids.clear()
1670 def default_get(self, cr, uid, fields_list, context=None):
1672 Returns default values for the fields in fields_list.
1674 :param fields_list: list of fields to get the default values for (example ['field1', 'field2',])
1675 :type fields_list: list
1676 :param context: optional context dictionary - it may contains keys for specifying certain options
1677 like ``context_lang`` (language) or ``context_tz`` (timezone) to alter the results of the call.
1678 It may contain keys in the form ``default_XXX`` (where XXX is a field name), to set
1679 or override a default value for a field.
1680 A special ``bin_size`` boolean flag may also be passed in the context to request the
1681 value of all fields.binary columns to be returned as the size of the binary instead of its
1682 contents. This can also be selectively overriden by passing a field-specific flag
1683 in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field.
1684 Note: The ``bin_size_XXX`` form is new in OpenERP v6.0.
1685 :return: dictionary of the default values (set on the object model class, through user preferences, or in the context)
1687 # trigger view init hook
1688 self.view_init(cr, uid, fields_list, context)
1694 # get the default values for the inherited fields
1695 for t in self._inherits.keys():
1696 defaults.update(self.pool.get(t).default_get(cr, uid, fields_list,
1699 # get the default values defined in the object
1700 for f in fields_list:
1701 if f in self._defaults:
1702 if callable(self._defaults[f]):
1703 defaults[f] = self._defaults[f](self, cr, uid, context)
1705 defaults[f] = self._defaults[f]
1707 fld_def = ((f in self._columns) and self._columns[f]) \
1708 or ((f in self._inherit_fields) and self._inherit_fields[f][2]) \
1711 if isinstance(fld_def, fields.property):
1712 property_obj = self.pool.get('ir.property')
1713 prop_value = property_obj.get(cr, uid, f, self._name, context=context)
1715 if isinstance(prop_value, (browse_record, browse_null)):
1716 defaults[f] = prop_value.id
1718 defaults[f] = prop_value
1720 if f not in defaults:
1723 # get the default values set by the user and override the default
1724 # values defined in the object
1725 ir_values_obj = self.pool.get('ir.values')
1726 res = ir_values_obj.get(cr, uid, 'default', False, [self._name])
1727 for id, field, field_value in res:
1728 if field in fields_list:
1729 fld_def = (field in self._columns) and self._columns[field] or self._inherit_fields[field][2]
1730 if fld_def._type == 'many2one':
1731 obj = self.pool.get(fld_def._obj)
1732 if not obj.search(cr, uid, [('id', '=', field_value or False)]):
1734 if fld_def._type == 'many2many':
1735 obj = self.pool.get(fld_def._obj)
1737 for i in range(len(field_value)):
1738 if not obj.search(cr, uid, [('id', '=',
1741 field_value2.append(field_value[i])
1742 field_value = field_value2
1743 if fld_def._type == 'one2many':
1744 obj = self.pool.get(fld_def._obj)
1746 for i in range(len(field_value)):
1747 field_value2.append({})
1748 for field2 in field_value[i]:
1749 if field2 in obj._columns.keys() and obj._columns[field2]._type == 'many2one':
1750 obj2 = self.pool.get(obj._columns[field2]._obj)
1751 if not obj2.search(cr, uid,
1752 [('id', '=', field_value[i][field2])]):
1754 elif field2 in obj._inherit_fields.keys() and obj._inherit_fields[field2][2]._type == 'many2one':
1755 obj2 = self.pool.get(obj._inherit_fields[field2][2]._obj)
1756 if not obj2.search(cr, uid,
1757 [('id', '=', field_value[i][field2])]):
1759 # TODO add test for many2many and one2many
1760 field_value2[i][field2] = field_value[i][field2]
1761 field_value = field_value2
1762 defaults[field] = field_value
1764 # get the default values from the context
1765 for key in context or {}:
1766 if key.startswith('default_') and (key[8:] in fields_list):
1767 defaults[key[8:]] = context[key]
1770 def fields_get_keys(self, cr, user, context=None):
1771 res = self._columns.keys()
1772 # TODO I believe this loop can be replace by
1773 # res.extend(self._inherit_fields.key())
1774 for parent in self._inherits:
1775 res.extend(self.pool.get(parent).fields_get_keys(cr, user, context))
1778 def _rec_name_fallback(self, cr, uid, context=None):
1779 rec_name = self._rec_name
1780 if rec_name not in self._columns:
1781 rec_name = self._columns.keys()[0] if len(self._columns.keys()) > 0 else "id"
1785 # Overload this method if you need a window title which depends on the context
1787 def view_header_get(self, cr, user, view_id=None, view_type='form', context=None):
1790 def user_has_groups(self, cr, uid, groups, context=None):
1791 """Return true if the user is at least member of one of the groups
1792 in groups_str. Typically used to resolve ``groups`` attribute
1793 in view and model definitions.
1795 :param str groups: comma-separated list of fully-qualified group
1796 external IDs, e.g.: ``base.group_user,base.group_system``
1797 :return: True if the current user is a member of one of the
1800 return any([self.pool.get('res.users').has_group(cr, uid, group_ext_id)
1801 for group_ext_id in groups.split(',')])
1803 def __view_look_dom(self, cr, user, node, view_id, in_tree_view, model_fields, context=None):
1804 """Return the description of the fields in the node.
1806 In a normal call to this method, node is a complete view architecture
1807 but it is actually possible to give some sub-node (this is used so
1808 that the method can call itself recursively).
1810 Originally, the field descriptions are drawn from the node itself.
1811 But there is now some code calling fields_get() in order to merge some
1812 of those information in the architecture.
1824 if isinstance(s, unicode):
1825 return s.encode('utf8')
1828 def check_group(node):
1829 """Apply group restrictions, may be set at view level or model level::
1830 * at view level this means the element should be made invisible to
1831 people who are not members
1832 * at model level (exclusively for fields, obviously), this means
1833 the field should be completely removed from the view, as it is
1834 completely unavailable for non-members
1836 :return: True if field should be included in the result of fields_view_get
1838 if node.tag == 'field' and node.get('name') in self._all_columns:
1839 column = self._all_columns[node.get('name')].column
1840 if column.groups and not self.user_has_groups(cr, user,
1841 groups=column.groups,
1843 node.getparent().remove(node)
1844 fields.pop(node.get('name'), None)
1845 # no point processing view-level ``groups`` anymore, return
1847 if node.get('groups'):
1848 can_see = self.user_has_groups(cr, user,
1849 groups=node.get('groups'),
1852 node.set('invisible', '1')
1853 modifiers['invisible'] = True
1854 if 'attrs' in node.attrib:
1855 del(node.attrib['attrs']) #avoid making field visible later
1856 del(node.attrib['groups'])
1859 if node.tag in ('field', 'node', 'arrow'):
1860 if node.get('object'):
1865 if f.tag in ('field'):
1866 xml += etree.tostring(f, encoding="utf-8")
1868 new_xml = etree.fromstring(encode(xml))
1869 ctx = context.copy()
1870 ctx['base_model_name'] = self._name
1871 xarch, xfields = self.pool.get(node.get('object')).__view_look_dom_arch(cr, user, new_xml, view_id, ctx)
1876 attrs = {'views': views}
1878 if node.get('name'):
1881 if node.get('name') in self._columns:
1882 column = self._columns[node.get('name')]
1884 column = self._inherit_fields[node.get('name')][2]
1889 relation = self.pool.get(column._obj)
1894 if f.tag in ('form', 'tree', 'graph', 'kanban'):
1896 ctx = context.copy()
1897 ctx['base_model_name'] = self._name
1898 xarch, xfields = relation.__view_look_dom_arch(cr, user, f, view_id, ctx)
1899 views[str(f.tag)] = {
1903 attrs = {'views': views}
1904 if node.get('widget') and node.get('widget') == 'selection':
1905 # Prepare the cached selection list for the client. This needs to be
1906 # done even when the field is invisible to the current user, because
1907 # other events could need to change its value to any of the selectable ones
1908 # (such as on_change events, refreshes, etc.)
1910 # If domain and context are strings, we keep them for client-side, otherwise
1911 # we evaluate them server-side to consider them when generating the list of
1913 # TODO: find a way to remove this hack, by allow dynamic domains
1915 if column._domain and not isinstance(column._domain, basestring):
1916 dom = column._domain
1917 dom += eval(node.get('domain', '[]'), {'uid': user, 'time': time})
1918 search_context = dict(context)
1919 if column._context and not isinstance(column._context, basestring):
1920 search_context.update(column._context)
1921 attrs['selection'] = relation._name_search(cr, user, '', dom, context=search_context, limit=None, name_get_uid=1)
1922 if (node.get('required') and not int(node.get('required'))) or not column.required:
1923 attrs['selection'].append((False, ''))
1924 fields[node.get('name')] = attrs
1926 field = model_fields.get(node.get('name'))
1928 transfer_field_to_modifiers(field, modifiers)
1931 elif node.tag in ('form', 'tree'):
1932 result = self.view_header_get(cr, user, False, node.tag, context)
1934 node.set('string', result)
1935 in_tree_view = node.tag == 'tree'
1937 elif node.tag == 'calendar':
1938 for additional_field in ('date_start', 'date_delay', 'date_stop', 'color'):
1939 if node.get(additional_field):
1940 fields[node.get(additional_field)] = {}
1942 if not check_group(node):
1943 # node must be removed, no need to proceed further with its children
1946 # The view architeture overrides the python model.
1947 # Get the attrs before they are (possibly) deleted by check_group below
1948 transfer_node_to_modifiers(node, modifiers, context, in_tree_view)
1950 # TODO remove attrs couterpart in modifiers when invisible is true ?
1953 if 'lang' in context:
1954 if node.text and node.text.strip():
1955 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.text.strip())
1957 node.text = node.text.replace(node.text.strip(), trans)
1958 if node.tail and node.tail.strip():
1959 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.tail.strip())
1961 node.tail = node.tail.replace(node.tail.strip(), trans)
1963 if node.get('string') and not result:
1964 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('string'))
1965 if trans == node.get('string') and ('base_model_name' in context):
1966 # If translation is same as source, perhaps we'd have more luck with the alternative model name
1967 # (in case we are in a mixed situation, such as an inherited view where parent_view.model != model
1968 trans = self.pool.get('ir.translation')._get_source(cr, user, context['base_model_name'], 'view', context['lang'], node.get('string'))
1970 node.set('string', trans)
1972 for attr_name in ('confirm', 'sum', 'help', 'placeholder'):
1973 attr_value = node.get(attr_name)
1975 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], attr_value)
1977 node.set(attr_name, trans)
1980 if children or (node.tag == 'field' and f.tag in ('filter','separator')):
1981 fields.update(self.__view_look_dom(cr, user, f, view_id, in_tree_view, model_fields, context))
1983 transfer_modifiers_to_node(modifiers, node)
1986 def _disable_workflow_buttons(self, cr, user, node):
1987 """ Set the buttons in node to readonly if the user can't activate them. """
1989 # admin user can always activate workflow buttons
1992 # TODO handle the case of more than one workflow for a model or multiple
1993 # transitions with different groups and same signal
1994 usersobj = self.pool.get('res.users')
1995 buttons = (n for n in node.getiterator('button') if n.get('type') != 'object')
1996 for button in buttons:
1997 user_groups = usersobj.read(cr, user, [user], ['groups_id'])[0]['groups_id']
1998 cr.execute("""SELECT DISTINCT t.group_id
2000 INNER JOIN wkf_activity a ON a.wkf_id = wkf.id
2001 INNER JOIN wkf_transition t ON (t.act_to = a.id)
2004 AND t.group_id is NOT NULL
2005 """, (self._name, button.get('name')))
2006 group_ids = [x[0] for x in cr.fetchall() if x[0]]
2007 can_click = not group_ids or bool(set(user_groups).intersection(group_ids))
2008 button.set('readonly', str(int(not can_click)))
2011 def __view_look_dom_arch(self, cr, user, node, view_id, context=None):
2012 """ Return an architecture and a description of all the fields.
2014 The field description combines the result of fields_get() and
2017 :param node: the architecture as as an etree
2018 :return: a tuple (arch, fields) where arch is the given node as a
2019 string and fields is the description of all the fields.
2023 if node.tag == 'diagram':
2024 if node.getchildren()[0].tag == 'node':
2025 node_model = self.pool.get(node.getchildren()[0].get('object'))
2026 node_fields = node_model.fields_get(cr, user, None, context)
2027 fields.update(node_fields)
2028 if not node.get("create") and not node_model.check_access_rights(cr, user, 'create', raise_exception=False):
2029 node.set("create", 'false')
2030 if node.getchildren()[1].tag == 'arrow':
2031 arrow_fields = self.pool.get(node.getchildren()[1].get('object')).fields_get(cr, user, None, context)
2032 fields.update(arrow_fields)
2034 fields = self.fields_get(cr, user, None, context)
2035 fields_def = self.__view_look_dom(cr, user, node, view_id, False, fields, context=context)
2036 node = self._disable_workflow_buttons(cr, user, node)
2037 if node.tag in ('kanban', 'tree', 'form', 'gantt'):
2038 for action, operation in (('create', 'create'), ('delete', 'unlink'), ('edit', 'write')):
2039 if not node.get(action) and not self.check_access_rights(cr, user, operation, raise_exception=False):
2040 node.set(action, 'false')
2041 arch = etree.tostring(node, encoding="utf-8").replace('\t', '')
2042 for k in fields.keys():
2043 if k not in fields_def:
2045 for field in fields_def:
2047 # sometime, the view may contain the (invisible) field 'id' needed for a domain (when 2 objects have cross references)
2048 fields['id'] = {'readonly': True, 'type': 'integer', 'string': 'ID'}
2049 elif field in fields:
2050 fields[field].update(fields_def[field])
2052 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))
2053 res = cr.fetchall()[:]
2055 res.insert(0, ("Can't find field '%s' in the following view parts composing the view of object model '%s':" % (field, model), None))
2056 msg = "\n * ".join([r[0] for r in res])
2057 msg += "\n\nEither you wrongly customized this view, or some modules bringing those views are not compatible with your current data model"
2059 raise except_orm('View error', msg)
2062 def _get_default_form_view(self, cr, user, context=None):
2063 """ Generates a default single-line form view using all fields
2064 of the current model except the m2m and o2m ones.
2066 :param cr: database cursor
2067 :param int user: user id
2068 :param dict context: connection context
2069 :returns: a form view as an lxml document
2070 :rtype: etree._Element
2072 view = etree.Element('form', string=self._description)
2073 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
2074 for field, descriptor in self.fields_get(cr, user, context=context).iteritems():
2075 if descriptor['type'] in ('one2many', 'many2many'):
2077 etree.SubElement(view, 'field', name=field)
2078 if descriptor['type'] == 'text':
2079 etree.SubElement(view, 'newline')
2082 def _get_default_search_view(self, cr, user, context=None):
2083 """ Generates a single-field search view, based on _rec_name.
2085 :param cr: database cursor
2086 :param int user: user id
2087 :param dict context: connection context
2088 :returns: a tree view as an lxml document
2089 :rtype: etree._Element
2091 view = etree.Element('search', string=self._description)
2092 etree.SubElement(view, 'field', name=self._rec_name_fallback(cr, user, context))
2095 def _get_default_tree_view(self, cr, user, context=None):
2096 """ Generates a single-field tree view, based on _rec_name.
2098 :param cr: database cursor
2099 :param int user: user id
2100 :param dict context: connection context
2101 :returns: a tree view as an lxml document
2102 :rtype: etree._Element
2104 view = etree.Element('tree', string=self._description)
2105 etree.SubElement(view, 'field', name=self._rec_name_fallback(cr, user, context))
2108 def _get_default_calendar_view(self, cr, user, context=None):
2109 """ Generates a default calendar view by trying to infer
2110 calendar fields from a number of pre-set attribute names
2112 :param cr: database cursor
2113 :param int user: user id
2114 :param dict context: connection context
2115 :returns: a calendar view
2116 :rtype: etree._Element
2118 def set_first_of(seq, in_, to):
2119 """Sets the first value of ``seq`` also found in ``in_`` to
2120 the ``to`` attribute of the view being closed over.
2122 Returns whether it's found a suitable value (and set it on
2123 the attribute) or not
2131 view = etree.Element('calendar', string=self._description)
2132 etree.SubElement(view, 'field', self._rec_name_fallback(cr, user, context))
2134 if (self._date_name not in self._columns):
2136 for dt in ['date', 'date_start', 'x_date', 'x_date_start']:
2137 if dt in self._columns:
2138 self._date_name = dt
2143 raise except_orm(_('Invalid Object Architecture!'), _("Insufficient fields for Calendar View!"))
2144 view.set('date_start', self._date_name)
2146 set_first_of(["user_id", "partner_id", "x_user_id", "x_partner_id"],
2147 self._columns, 'color')
2149 if not set_first_of(["date_stop", "date_end", "x_date_stop", "x_date_end"],
2150 self._columns, 'date_stop'):
2151 if not set_first_of(["date_delay", "planned_hours", "x_date_delay", "x_planned_hours"],
2152 self._columns, 'date_delay'):
2154 _('Invalid Object Architecture!'),
2155 _("Insufficient fields to generate a Calendar View for %s, missing a date_stop or a date_delay" % (self._name)))
2160 # if view_id, view_type is not required
2162 def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
2164 Get the detailed composition of the requested view like fields, model, view architecture
2166 :param cr: database cursor
2167 :param user: current user id
2168 :param view_id: id of the view or None
2169 :param view_type: type of the view to return if view_id is None ('form', tree', ...)
2170 :param context: context arguments, like lang, time zone
2171 :param toolbar: true to include contextual actions
2172 :param submenu: deprecated
2173 :return: dictionary describing the composition of the requested view (including inherited views and extensions)
2174 :raise AttributeError:
2175 * if the inherited view has unknown position to work with other than 'before', 'after', 'inside', 'replace'
2176 * if some tag other than 'position' is found in parent view
2177 :raise Invalid ArchitectureError: if there is view type other than form, tree, calendar, search etc defined on the structure
2184 if isinstance(s, unicode):
2185 return s.encode('utf8')
2188 def raise_view_error(error_msg, child_view_id):
2189 view, child_view = self.pool.get('ir.ui.view').browse(cr, user, [view_id, child_view_id], context)
2190 error_msg = error_msg % {'parent_xml_id': view.xml_id}
2191 raise AttributeError("View definition error for inherited view '%s' on model '%s': %s"
2192 % (child_view.xml_id, self._name, error_msg))
2194 def locate(source, spec):
2195 """ Locate a node in a source (parent) architecture.
2197 Given a complete source (parent) architecture (i.e. the field
2198 `arch` in a view), and a 'spec' node (a node in an inheriting
2199 view that specifies the location in the source view of what
2200 should be changed), return (if it exists) the node in the
2201 source view matching the specification.
2203 :param source: a parent architecture to modify
2204 :param spec: a modifying node in an inheriting view
2205 :return: a node in the source matching the spec
2208 if spec.tag == 'xpath':
2209 nodes = source.xpath(spec.get('expr'))
2210 return nodes[0] if nodes else None
2211 elif spec.tag == 'field':
2212 # Only compare the field name: a field can be only once in a given view
2213 # at a given level (and for multilevel expressions, we should use xpath
2214 # inheritance spec anyway).
2215 for node in source.getiterator('field'):
2216 if node.get('name') == spec.get('name'):
2220 for node in source.getiterator(spec.tag):
2221 if isinstance(node, SKIPPED_ELEMENT_TYPES):
2223 if all(node.get(attr) == spec.get(attr) \
2224 for attr in spec.attrib
2225 if attr not in ('position','version')):
2226 # Version spec should match parent's root element's version
2227 if spec.get('version') and spec.get('version') != source.get('version'):
2232 def apply_inheritance_specs(source, specs_arch, inherit_id=None):
2233 """ Apply an inheriting view.
2235 Apply to a source architecture all the spec nodes (i.e. nodes
2236 describing where and what changes to apply to some parent
2237 architecture) given by an inheriting view.
2239 :param source: a parent architecture to modify
2240 :param specs_arch: a modifying architecture in an inheriting view
2241 :param inherit_id: the database id of the inheriting view
2242 :return: a modified source where the specs are applied
2245 specs_tree = etree.fromstring(encode(specs_arch))
2246 # Queue of specification nodes (i.e. nodes describing where and
2247 # changes to apply to some parent architecture).
2248 specs = [specs_tree]
2252 if isinstance(spec, SKIPPED_ELEMENT_TYPES):
2254 if spec.tag == 'data':
2255 specs += [ c for c in specs_tree ]
2257 node = locate(source, spec)
2258 if node is not None:
2259 pos = spec.get('position', 'inside')
2260 if pos == 'replace':
2261 if node.getparent() is None:
2262 source = copy.deepcopy(spec[0])
2265 node.addprevious(child)
2266 node.getparent().remove(node)
2267 elif pos == 'attributes':
2268 for child in spec.getiterator('attribute'):
2269 attribute = (child.get('name'), child.text and child.text.encode('utf8') or None)
2271 node.set(attribute[0], attribute[1])
2273 del(node.attrib[attribute[0]])
2275 sib = node.getnext()
2279 elif pos == 'after':
2284 sib.addprevious(child)
2285 elif pos == 'before':
2286 node.addprevious(child)
2288 raise_view_error("Invalid position value: '%s'" % pos, inherit_id)
2291 ' %s="%s"' % (attr, spec.get(attr))
2292 for attr in spec.attrib
2293 if attr != 'position'
2295 tag = "<%s%s>" % (spec.tag, attrs)
2296 if spec.get('version') and spec.get('version') != source.get('version'):
2297 raise_view_error("Mismatching view API version for element '%s': %r vs %r in parent view '%%(parent_xml_id)s'" % \
2298 (tag, spec.get('version'), source.get('version')), inherit_id)
2299 raise_view_error("Element '%s' not found in parent view '%%(parent_xml_id)s'" % tag, inherit_id)
2303 def apply_view_inheritance(cr, user, source, inherit_id):
2304 """ Apply all the (directly and indirectly) inheriting views.
2306 :param source: a parent architecture to modify (with parent
2307 modifications already applied)
2308 :param inherit_id: the database view_id of the parent view
2309 :return: a modified source where all the modifying architecture
2313 sql_inherit = self.pool.get('ir.ui.view').get_inheriting_views_arch(cr, user, inherit_id, self._name)
2314 for (view_arch, view_id) in sql_inherit:
2315 source = apply_inheritance_specs(source, view_arch, view_id)
2316 source = apply_view_inheritance(cr, user, source, view_id)
2319 result = {'type': view_type, 'model': self._name}
2322 parent_view_model = None
2323 view_ref = context.get(view_type + '_view_ref')
2324 # Search for a root (i.e. without any parent) view.
2326 if view_ref and not view_id:
2328 module, view_ref = view_ref.split('.', 1)
2329 cr.execute("SELECT res_id FROM ir_model_data WHERE model='ir.ui.view' AND module=%s AND name=%s", (module, view_ref))
2330 view_ref_res = cr.fetchone()
2332 view_id = view_ref_res[0]
2335 cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model
2337 WHERE id=%s""", (view_id,))
2339 cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model
2341 WHERE model=%s AND type=%s AND inherit_id IS NULL
2342 ORDER BY priority""", (self._name, view_type))
2343 sql_res = cr.dictfetchone()
2348 view_id = sql_res['inherit_id'] or sql_res['id']
2349 parent_view_model = sql_res['model']
2350 if not sql_res['inherit_id']:
2353 # if a view was found
2355 source = etree.fromstring(encode(sql_res['arch']))
2357 arch=apply_view_inheritance(cr, user, source, sql_res['id']),
2358 type=sql_res['type'],
2359 view_id=sql_res['id'],
2360 name=sql_res['name'],
2361 field_parent=sql_res['field_parent'] or False)
2363 # otherwise, build some kind of default view
2365 view = getattr(self, '_get_default_%s_view' % view_type)(
2367 except AttributeError:
2368 # what happens here, graph case?
2369 raise except_orm(_('Invalid Architecture!'), _("There is no view of type '%s' defined for the structure!") % view_type)
2377 if parent_view_model != self._name:
2378 ctx = context.copy()
2379 ctx['base_model_name'] = parent_view_model
2382 xarch, xfields = self.__view_look_dom_arch(cr, user, result['arch'], view_id, context=ctx)
2383 result['arch'] = xarch
2384 result['fields'] = xfields
2389 for key in ('report_sxw_content', 'report_rml_content',
2390 'report_sxw', 'report_rml',
2391 'report_sxw_content_data', 'report_rml_content_data'):
2395 ir_values_obj = self.pool.get('ir.values')
2396 resprint = ir_values_obj.get(cr, user, 'action',
2397 'client_print_multi', [(self._name, False)], False,
2399 resaction = ir_values_obj.get(cr, user, 'action',
2400 'client_action_multi', [(self._name, False)], False,
2403 resrelate = ir_values_obj.get(cr, user, 'action',
2404 'client_action_relate', [(self._name, False)], False,
2406 resaction = [clean(action) for action in resaction
2407 if view_type == 'tree' or not action[2].get('multi')]
2408 resprint = [clean(print_) for print_ in resprint
2409 if view_type == 'tree' or not print_[2].get('multi')]
2410 resrelate = map(lambda x: x[2], resrelate)
2412 for x in itertools.chain(resprint, resaction, resrelate):
2413 x['string'] = x['name']
2415 result['toolbar'] = {
2417 'action': resaction,
2422 _view_look_dom_arch = __view_look_dom_arch
2424 def search_count(self, cr, user, args, context=None):
2427 res = self.search(cr, user, args, context=context, count=True)
2428 if isinstance(res, list):
2432 def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
2434 Search for records based on a search domain.
2436 :param cr: database cursor
2437 :param user: current user id
2438 :param args: list of tuples specifying the search domain [('field_name', 'operator', value), ...]. Pass an empty list to match all records.
2439 :param offset: optional number of results to skip in the returned values (default: 0)
2440 :param limit: optional max number of records to return (default: **None**)
2441 :param order: optional columns to sort by (default: self._order=id )
2442 :param context: optional context arguments, like lang, time zone
2443 :type context: dictionary
2444 :param count: optional (default: **False**), if **True**, returns only the number of records matching the criteria, not their ids
2445 :return: id or list of ids of records matching the criteria
2446 :rtype: integer or list of integers
2447 :raise AccessError: * if user tries to bypass access rules for read on the requested object.
2449 **Expressing a search domain (args)**
2451 Each tuple in the search domain needs to have 3 elements, in the form: **('field_name', 'operator', value)**, where:
2453 * **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.
2454 * **operator** must be a string with a valid comparison operator from this list: ``=, !=, >, >=, <, <=, like, ilike, in, not in, child_of, parent_left, parent_right``
2455 The semantics of most of these operators are obvious.
2456 The ``child_of`` operator will look for records who are children or grand-children of a given record,
2457 according to the semantics of this model (i.e following the relationship field named by
2458 ``self._parent_name``, by default ``parent_id``.
2459 * **value** must be a valid value to compare with the values of **field_name**, depending on its type.
2461 Domain criteria can be combined using 3 logical operators than can be added between tuples: '**&**' (logical AND, default), '**|**' (logical OR), '**!**' (logical NOT).
2462 These are **prefix** operators and the arity of the '**&**' and '**|**' operator is 2, while the arity of the '**!**' is just 1.
2463 Be very careful about this when you combine them the first time.
2465 Here is an example of searching for Partners named *ABC* from Belgium and Germany whose language is not english ::
2467 [('name','=','ABC'),'!',('language.code','=','en_US'),'|',('country_id.code','=','be'),('country_id.code','=','de'))
2469 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::
2471 (name is 'ABC' AND (language is NOT english) AND (country is Belgium OR Germany))
2474 return self._search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count)
2476 def name_get(self, cr, user, ids, context=None):
2477 """Returns the preferred display value (text representation) for the records with the
2478 given ``ids``. By default this will be the value of the ``name`` column, unless
2479 the model implements a custom behavior.
2480 Can sometimes be seen as the inverse function of :meth:`~.name_search`, but it is not
2484 :return: list of pairs ``(id,text_repr)`` for all records with the given ``ids``.
2488 if isinstance(ids, (int, long)):
2491 if self._rec_name in self._all_columns:
2492 rec_name_column = self._all_columns[self._rec_name].column
2493 return [(r['id'], rec_name_column.as_display_name(cr, user, self, r[self._rec_name], context=context))
2494 for r in self.read(cr, user, ids, [self._rec_name],
2495 load='_classic_write', context=context)]
2496 return [(id, "%s,%s" % (self._name, id)) for id in ids]
2498 def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
2499 """Search for records that have a display name matching the given ``name`` pattern if compared
2500 with the given ``operator``, while also matching the optional search domain (``args``).
2501 This is used for example to provide suggestions based on a partial value for a relational
2503 Sometimes be seen as the inverse function of :meth:`~.name_get`, but it is not
2506 This method is equivalent to calling :meth:`~.search` with a search domain based on ``name``
2507 and then :meth:`~.name_get` on the result of the search.
2509 :param list args: optional search domain (see :meth:`~.search` for syntax),
2510 specifying further restrictions
2511 :param str operator: domain operator for matching the ``name`` pattern, such as ``'like'``
2513 :param int limit: optional max number of records to return
2515 :return: list of pairs ``(id,text_repr)`` for all matching records.
2517 return self._name_search(cr, user, name, args, operator, context, limit)
2519 def name_create(self, cr, uid, name, context=None):
2520 """Creates a new record by calling :meth:`~.create` with only one
2521 value provided: the name of the new record (``_rec_name`` field).
2522 The new record will also be initialized with any default values applicable
2523 to this model, or provided through the context. The usual behavior of
2524 :meth:`~.create` applies.
2525 Similarly, this method may raise an exception if the model has multiple
2526 required fields and some do not have default values.
2528 :param name: name of the record to create
2531 :return: the :meth:`~.name_get` pair value for the newly-created record.
2533 rec_id = self.create(cr, uid, {self._rec_name: name}, context);
2534 return self.name_get(cr, uid, [rec_id], context)[0]
2536 # private implementation of name_search, allows passing a dedicated user for the name_get part to
2537 # solve some access rights issues
2538 def _name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100, name_get_uid=None):
2544 # optimize out the default criterion of ``ilike ''`` that matches everything
2545 if not (name == '' and operator == 'ilike'):
2546 args += [(self._rec_name, operator, name)]
2547 access_rights_uid = name_get_uid or user
2548 ids = self._search(cr, user, args, limit=limit, context=context, access_rights_uid=access_rights_uid)
2549 res = self.name_get(cr, access_rights_uid, ids, context)
2552 def read_string(self, cr, uid, id, langs, fields=None, context=None):
2555 self.pool.get('ir.translation').check_access_rights(cr, uid, 'read')
2557 fields = self._columns.keys() + self._inherit_fields.keys()
2558 #FIXME: collect all calls to _get_source into one SQL call.
2560 res[lang] = {'code': lang}
2562 if f in self._columns:
2563 res_trans = self.pool.get('ir.translation')._get_source(cr, uid, self._name+','+f, 'field', lang)
2565 res[lang][f] = res_trans
2567 res[lang][f] = self._columns[f].string
2568 for table in self._inherits:
2569 cols = intersect(self._inherit_fields.keys(), fields)
2570 res2 = self.pool.get(table).read_string(cr, uid, id, langs, cols, context)
2573 res[lang]['code'] = lang
2574 for f in res2[lang]:
2575 res[lang][f] = res2[lang][f]
2578 def write_string(self, cr, uid, id, langs, vals, context=None):
2579 self.pool.get('ir.translation').check_access_rights(cr, uid, 'write')
2580 #FIXME: try to only call the translation in one SQL
2583 if field in self._columns:
2584 src = self._columns[field].string
2585 self.pool.get('ir.translation')._set_ids(cr, uid, self._name+','+field, 'field', lang, [0], vals[field], src)
2586 for table in self._inherits:
2587 cols = intersect(self._inherit_fields.keys(), vals)
2589 self.pool.get(table).write_string(cr, uid, id, langs, vals, context)
2592 def _add_missing_default_values(self, cr, uid, values, context=None):
2593 missing_defaults = []
2594 avoid_tables = [] # avoid overriding inherited values when parent is set
2595 for tables, parent_field in self._inherits.items():
2596 if parent_field in values:
2597 avoid_tables.append(tables)
2598 for field in self._columns.keys():
2599 if not field in values:
2600 missing_defaults.append(field)
2601 for field in self._inherit_fields.keys():
2602 if (field not in values) and (self._inherit_fields[field][0] not in avoid_tables):
2603 missing_defaults.append(field)
2605 if len(missing_defaults):
2606 # override defaults with the provided values, never allow the other way around
2607 defaults = self.default_get(cr, uid, missing_defaults, context)
2609 if ((dv in self._columns and self._columns[dv]._type == 'many2many') \
2610 or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'many2many')) \
2611 and defaults[dv] and isinstance(defaults[dv][0], (int, long)):
2612 defaults[dv] = [(6, 0, defaults[dv])]
2613 if (dv in self._columns and self._columns[dv]._type == 'one2many' \
2614 or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'one2many')) \
2615 and isinstance(defaults[dv], (list, tuple)) and defaults[dv] and isinstance(defaults[dv][0], dict):
2616 defaults[dv] = [(0, 0, x) for x in defaults[dv]]
2617 defaults.update(values)
2621 def clear_caches(self):
2622 """ Clear the caches
2624 This clears the caches associated to methods decorated with
2625 ``tools.ormcache`` or ``tools.ormcache_multi``.
2628 getattr(self, '_ormcache')
2630 except AttributeError:
2634 def _read_group_fill_results(self, cr, uid, domain, groupby, groupby_list, aggregated_fields,
2635 read_group_result, read_group_order=None, context=None):
2636 """Helper method for filling in empty groups for all possible values of
2637 the field being grouped by"""
2639 # self._group_by_full should map groupable fields to a method that returns
2640 # a list of all aggregated values that we want to display for this field,
2641 # in the form of a m2o-like pair (key,label).
2642 # This is useful to implement kanban views for instance, where all columns
2643 # should be displayed even if they don't contain any record.
2645 # Grab the list of all groups that should be displayed, including all present groups
2646 present_group_ids = [x[groupby][0] for x in read_group_result if x[groupby]]
2647 all_groups,folded = self._group_by_full[groupby](self, cr, uid, present_group_ids, domain,
2648 read_group_order=read_group_order,
2649 access_rights_uid=openerp.SUPERUSER_ID,
2652 result_template = dict.fromkeys(aggregated_fields, False)
2653 result_template[groupby + '_count'] = 0
2654 if groupby_list and len(groupby_list) > 1:
2655 result_template['__context'] = {'group_by': groupby_list[1:]}
2657 # Merge the left_side (current results as dicts) with the right_side (all
2658 # possible values as m2o pairs). Both lists are supposed to be using the
2659 # same ordering, and can be merged in one pass.
2662 def append_left(left_side):
2663 grouped_value = left_side[groupby] and left_side[groupby][0]
2664 if not grouped_value in known_values:
2665 result.append(left_side)
2666 known_values[grouped_value] = left_side
2668 count_attr = groupby + '_count'
2669 known_values[grouped_value].update({count_attr: left_side[count_attr]})
2670 def append_right(right_side):
2671 grouped_value = right_side[0]
2672 if not grouped_value in known_values:
2673 line = dict(result_template)
2674 line[groupby] = right_side
2675 line['__domain'] = [(groupby,'=',grouped_value)] + domain
2677 known_values[grouped_value] = line
2678 while read_group_result or all_groups:
2679 left_side = read_group_result[0] if read_group_result else None
2680 right_side = all_groups[0] if all_groups else None
2681 assert left_side is None or left_side[groupby] is False \
2682 or isinstance(left_side[groupby], (tuple,list)), \
2683 'M2O-like pair expected, got %r' % left_side[groupby]
2684 assert right_side is None or isinstance(right_side, (tuple,list)), \
2685 'M2O-like pair expected, got %r' % right_side
2686 if left_side is None:
2687 append_right(all_groups.pop(0))
2688 elif right_side is None:
2689 append_left(read_group_result.pop(0))
2690 elif left_side[groupby] == right_side:
2691 append_left(read_group_result.pop(0))
2692 all_groups.pop(0) # discard right_side
2693 elif not left_side[groupby] or not left_side[groupby][0]:
2694 # left side == "Undefined" entry, not present on right_side
2695 append_left(read_group_result.pop(0))
2697 append_right(all_groups.pop(0))
2701 r['__fold'] = folded.get(r[groupby] and r[groupby][0], False)
2704 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False):
2706 Get the list of records in list view grouped by the given ``groupby`` fields
2708 :param cr: database cursor
2709 :param uid: current user id
2710 :param domain: list specifying search criteria [['field_name', 'operator', 'value'], ...]
2711 :param list fields: list of fields present in the list view specified on the object
2712 :param list groupby: fields by which the records will be grouped
2713 :param int offset: optional number of records to skip
2714 :param int limit: optional max number of records to return
2715 :param dict context: context arguments, like lang, time zone
2716 :param list orderby: optional ``order by`` specification, for
2717 overriding the natural sort ordering of the
2718 groups, see also :py:meth:`~osv.osv.osv.search`
2719 (supported only for many2one fields currently)
2720 :return: list of dictionaries(one dictionary for each record) containing:
2722 * the values of fields grouped by the fields in ``groupby`` argument
2723 * __domain: list of tuples specifying the search criteria
2724 * __context: dictionary with argument like ``groupby``
2725 :rtype: [{'field_name_1': value, ...]
2726 :raise AccessError: * if user has no read rights on the requested object
2727 * if user tries to bypass access rules for read on the requested object
2730 context = context or {}
2731 self.check_access_rights(cr, uid, 'read')
2733 fields = self._columns.keys()
2735 query = self._where_calc(cr, uid, domain, context=context)
2736 self._apply_ir_rules(cr, uid, query, 'read', context=context)
2738 # Take care of adding join(s) if groupby is an '_inherits'ed field
2739 groupby_list = groupby
2740 qualified_groupby_field = groupby
2742 if isinstance(groupby, list):
2743 groupby = groupby[0]
2744 qualified_groupby_field = self._inherits_join_calc(groupby, query)
2747 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?)"
2748 groupby_def = self._columns.get(groupby) or (self._inherit_fields.get(groupby) and self._inherit_fields.get(groupby)[2])
2749 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"
2751 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
2752 fget = self.fields_get(cr, uid, fields)
2754 group_count = group_by = groupby
2756 if fget.get(groupby):
2757 groupby_type = fget[groupby]['type']
2758 if groupby_type in ('date', 'datetime'):
2759 qualified_groupby_field = "to_char(%s,'yyyy-mm')" % qualified_groupby_field
2760 flist = "%s as %s " % (qualified_groupby_field, groupby)
2761 elif groupby_type == 'boolean':
2762 qualified_groupby_field = "coalesce(%s,false)" % qualified_groupby_field
2763 flist = "%s as %s " % (qualified_groupby_field, groupby)
2765 flist = qualified_groupby_field
2767 # Don't allow arbitrary values, as this would be a SQL injection vector!
2768 raise except_orm(_('Invalid group_by'),
2769 _('Invalid group_by specification: "%s".\nA group_by specification must be a list of valid fields.')%(groupby,))
2771 aggregated_fields = [
2773 if f not in ('id', 'sequence')
2774 if fget[f]['type'] in ('integer', 'float')
2775 if (f in self._columns and getattr(self._columns[f], '_classic_write'))]
2776 for f in aggregated_fields:
2777 group_operator = fget[f].get('group_operator', 'sum')
2780 qualified_field = '"%s"."%s"' % (self._table, f)
2781 flist += "%s(%s) AS %s" % (group_operator, qualified_field, f)
2783 gb = groupby and (' GROUP BY ' + qualified_groupby_field) or ''
2785 from_clause, where_clause, where_clause_params = query.get_sql()
2786 where_clause = where_clause and ' WHERE ' + where_clause
2787 limit_str = limit and ' limit %d' % limit or ''
2788 offset_str = offset and ' offset %d' % offset or ''
2789 if len(groupby_list) < 2 and context.get('group_by_no_leaf'):
2791 cr.execute('SELECT min(%s.id) AS id, count(%s.id) AS %s_count' % (self._table, self._table, group_count) + (flist and ',') + flist + ' FROM ' + from_clause + where_clause + gb + limit_str + offset_str, where_clause_params)
2794 for r in cr.dictfetchall():
2795 for fld, val in r.items():
2796 if val == None: r[fld] = False
2797 alldata[r['id']] = r
2800 order = orderby or groupby
2801 data_ids = self.search(cr, uid, [('id', 'in', alldata.keys())], order=order, context=context)
2802 # the IDS of records that have groupby field value = False or '' should be sorted too
2803 data_ids += filter(lambda x:x not in data_ids, alldata.keys())
2804 data = self.read(cr, uid, data_ids, groupby and [groupby] or ['id'], context=context)
2805 # restore order of the search as read() uses the default _order (this is only for groups, so the size of data_read shoud be small):
2806 data.sort(lambda x,y: cmp(data_ids.index(x['id']), data_ids.index(y['id'])))
2810 d['__domain'] = [(groupby, '=', alldata[d['id']][groupby] or False)] + domain
2811 if not isinstance(groupby_list, (str, unicode)):
2812 if groupby or not context.get('group_by_no_leaf', False):
2813 d['__context'] = {'group_by': groupby_list[1:]}
2814 if groupby and groupby in fget:
2815 if d[groupby] and fget[groupby]['type'] in ('date', 'datetime'):
2816 dt = datetime.datetime.strptime(alldata[d['id']][groupby][:7], '%Y-%m')
2817 days = calendar.monthrange(dt.year, dt.month)[1]
2819 d[groupby] = datetime.datetime.strptime(d[groupby][:10], '%Y-%m-%d').strftime('%B %Y')
2820 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),\
2821 (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
2822 del alldata[d['id']][groupby]
2823 d.update(alldata[d['id']])
2826 if groupby and groupby in self._group_by_full:
2827 data = self._read_group_fill_results(cr, uid, domain, groupby, groupby_list,
2828 aggregated_fields, data, read_group_order=order,
2833 def _inherits_join_add(self, current_table, parent_model_name, query):
2835 Add missing table SELECT and JOIN clause to ``query`` for reaching the parent table (no duplicates)
2836 :param current_table: current model object
2837 :param parent_model_name: name of the parent model for which the clauses should be added
2838 :param query: query object on which the JOIN should be added
2840 inherits_field = current_table._inherits[parent_model_name]
2841 parent_model = self.pool.get(parent_model_name)
2842 parent_table_name = parent_model._table
2843 quoted_parent_table_name = '"%s"' % parent_table_name
2844 if quoted_parent_table_name not in query.tables:
2845 query.tables.append(quoted_parent_table_name)
2846 query.where_clause.append('(%s.%s = %s.id)' % (current_table._table, inherits_field, parent_table_name))
2850 def _inherits_join_calc(self, field, query):
2852 Adds missing table select and join clause(s) to ``query`` for reaching
2853 the field coming from an '_inherits' parent table (no duplicates).
2855 :param field: name of inherited field to reach
2856 :param query: query object on which the JOIN should be added
2857 :return: qualified name of field, to be used in SELECT clause
2859 current_table = self
2860 while field in current_table._inherit_fields and not field in current_table._columns:
2861 parent_model_name = current_table._inherit_fields[field][0]
2862 parent_table = self.pool.get(parent_model_name)
2863 self._inherits_join_add(current_table, parent_model_name, query)
2864 current_table = parent_table
2865 return '"%s".%s' % (current_table._table, field)
2867 def _parent_store_compute(self, cr):
2868 if not self._parent_store:
2870 _logger.info('Computing parent left and right for table %s...', self._table)
2871 def browse_rec(root, pos=0):
2873 where = self._parent_name+'='+str(root)
2875 where = self._parent_name+' IS NULL'
2876 if self._parent_order:
2877 where += ' order by '+self._parent_order
2878 cr.execute('SELECT id FROM '+self._table+' WHERE '+where)
2880 for id in cr.fetchall():
2881 pos2 = browse_rec(id[0], pos2)
2882 cr.execute('update '+self._table+' set parent_left=%s, parent_right=%s where id=%s', (pos, pos2, root))
2884 query = 'SELECT id FROM '+self._table+' WHERE '+self._parent_name+' IS NULL'
2885 if self._parent_order:
2886 query += ' order by ' + self._parent_order
2889 for (root,) in cr.fetchall():
2890 pos = browse_rec(root, pos)
2893 def _update_store(self, cr, f, k):
2894 _logger.info("storing computed values of fields.function '%s'", k)
2895 ss = self._columns[k]._symbol_set
2896 update_query = 'UPDATE "%s" SET "%s"=%s WHERE id=%%s' % (self._table, k, ss[0])
2897 cr.execute('select id from '+self._table)
2898 ids_lst = map(lambda x: x[0], cr.fetchall())
2901 ids_lst = ids_lst[40:]
2902 res = f.get(cr, self, iids, k, SUPERUSER_ID, {})
2903 for key, val in res.items():
2906 # if val is a many2one, just write the ID
2907 if type(val) == tuple:
2909 if (val<>False) or (type(val)<>bool):
2910 cr.execute(update_query, (ss[1](val), key))
2912 def _check_selection_field_value(self, cr, uid, field, value, context=None):
2913 """Raise except_orm if value is not among the valid values for the selection field"""
2914 if self._columns[field]._type == 'reference':
2915 val_model, val_id_str = value.split(',', 1)
2918 val_id = long(val_id_str)
2922 raise except_orm(_('ValidateError'),
2923 _('Invalid value for reference field "%s.%s" (last part must be a non-zero integer): "%s"') % (self._table, field, value))
2927 if isinstance(self._columns[field].selection, (tuple, list)):
2928 if val in dict(self._columns[field].selection):
2930 elif val in dict(self._columns[field].selection(self, cr, uid, context=context)):
2932 raise except_orm(_('ValidateError'),
2933 _('The value "%s" for the field "%s.%s" is not in the selection') % (value, self._table, field))
2935 def _check_removed_columns(self, cr, log=False):
2936 # iterate on the database columns to drop the NOT NULL constraints
2937 # of fields which were required but have been removed (or will be added by another module)
2938 columns = [c for c in self._columns if not (isinstance(self._columns[c], fields.function) and not self._columns[c].store)]
2939 columns += MAGIC_COLUMNS
2940 cr.execute("SELECT a.attname, a.attnotnull"
2941 " FROM pg_class c, pg_attribute a"
2942 " WHERE c.relname=%s"
2943 " AND c.oid=a.attrelid"
2944 " AND a.attisdropped=%s"
2945 " AND pg_catalog.format_type(a.atttypid, a.atttypmod) NOT IN ('cid', 'tid', 'oid', 'xid')"
2946 " AND a.attname NOT IN %s", (self._table, False, tuple(columns))),
2948 for column in cr.dictfetchall():
2950 _logger.debug("column %s is in the table %s but not in the corresponding object %s",
2951 column['attname'], self._table, self._name)
2952 if column['attnotnull']:
2953 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, column['attname']))
2954 _schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
2955 self._table, column['attname'])
2957 def _save_constraint(self, cr, constraint_name, type):
2959 Record the creation of a constraint for this model, to make it possible
2960 to delete it later when the module is uninstalled. Type can be either
2961 'f' or 'u' depending on the constraing being a foreign key or not.
2963 assert type in ('f', 'u')
2965 SELECT 1 FROM ir_model_constraint, ir_module_module
2966 WHERE ir_model_constraint.module=ir_module_module.id
2967 AND ir_model_constraint.name=%s
2968 AND ir_module_module.name=%s
2969 """, (constraint_name, self._module))
2972 INSERT INTO ir_model_constraint
2973 (name, date_init, date_update, module, model, type)
2974 VALUES (%s, now() AT TIME ZONE 'UTC', now() AT TIME ZONE 'UTC',
2975 (SELECT id FROM ir_module_module WHERE name=%s),
2976 (SELECT id FROM ir_model WHERE model=%s), %s)""",
2977 (constraint_name, self._module, self._name, type))
2979 def _save_relation_table(self, cr, relation_table):
2981 Record the creation of a many2many for this model, to make it possible
2982 to delete it later when the module is uninstalled.
2985 SELECT 1 FROM ir_model_relation, ir_module_module
2986 WHERE ir_model_relation.module=ir_module_module.id
2987 AND ir_model_relation.name=%s
2988 AND ir_module_module.name=%s
2989 """, (relation_table, self._module))
2991 cr.execute("""INSERT INTO ir_model_relation (name, date_init, date_update, module, model)
2992 VALUES (%s, now() AT TIME ZONE 'UTC', now() AT TIME ZONE 'UTC',
2993 (SELECT id FROM ir_module_module WHERE name=%s),
2994 (SELECT id FROM ir_model WHERE model=%s))""",
2995 (relation_table, self._module, self._name))
2997 # checked version: for direct m2o starting from `self`
2998 def _m2o_add_foreign_key_checked(self, source_field, dest_model, ondelete):
2999 assert self.is_transient() or not dest_model.is_transient(), \
3000 'Many2One relationships from non-transient Model to TransientModel are forbidden'
3001 if self.is_transient() and not dest_model.is_transient():
3002 # TransientModel relationships to regular Models are annoying
3003 # usually because they could block deletion due to the FKs.
3004 # So unless stated otherwise we default them to ondelete=cascade.
3005 ondelete = ondelete or 'cascade'
3006 self._foreign_keys.append((self._table, source_field, dest_model._table, ondelete or 'set null'))
3007 _schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s",
3008 self._table, source_field, dest_model._table, ondelete)
3010 # unchecked version: for custom cases, such as m2m relationships
3011 def _m2o_add_foreign_key_unchecked(self, source_table, source_field, dest_model, ondelete):
3012 self._foreign_keys.append((source_table, source_field, dest_model._table, ondelete or 'set null'))
3013 _schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s",
3014 source_table, source_field, dest_model._table, ondelete)
3016 def _drop_constraint(self, cr, source_table, constraint_name):
3017 cr.execute("ALTER TABLE %s DROP CONSTRAINT %s" % (source_table,constraint_name))
3019 def _m2o_fix_foreign_key(self, cr, source_table, source_field, dest_model, ondelete):
3020 # Find FK constraint(s) currently established for the m2o field,
3021 # and see whether they are stale or not
3022 cr.execute("""SELECT confdeltype as ondelete_rule, conname as constraint_name,
3023 cl2.relname as foreign_table
3024 FROM pg_constraint as con, pg_class as cl1, pg_class as cl2,
3025 pg_attribute as att1, pg_attribute as att2
3026 WHERE con.conrelid = cl1.oid
3027 AND cl1.relname = %s
3028 AND con.confrelid = cl2.oid
3029 AND array_lower(con.conkey, 1) = 1
3030 AND con.conkey[1] = att1.attnum
3031 AND att1.attrelid = cl1.oid
3032 AND att1.attname = %s
3033 AND array_lower(con.confkey, 1) = 1
3034 AND con.confkey[1] = att2.attnum
3035 AND att2.attrelid = cl2.oid
3036 AND att2.attname = %s
3037 AND con.contype = 'f'""", (source_table, source_field, 'id'))
3038 constraints = cr.dictfetchall()
3040 if len(constraints) == 1:
3041 # Is it the right constraint?
3043 if cons['ondelete_rule'] != POSTGRES_CONFDELTYPES.get((ondelete or 'set null').upper(), 'a')\
3044 or cons['foreign_table'] != dest_model._table:
3045 _schema.debug("Table '%s': dropping obsolete FK constraint: '%s'",
3046 source_table, cons['constraint_name'])
3047 self._drop_constraint(cr, source_table, cons['constraint_name'])
3048 self._m2o_add_foreign_key_checked(source_field, dest_model, ondelete)
3049 # else it's all good, nothing to do!
3051 # Multiple FKs found for the same field, drop them all, and re-create
3052 for cons in constraints:
3053 _schema.debug("Table '%s': dropping duplicate FK constraints: '%s'",
3054 source_table, cons['constraint_name'])
3055 self._drop_constraint(cr, source_table, cons['constraint_name'])
3056 self._m2o_add_foreign_key_checked(source_field, dest_model, ondelete)
3060 def _auto_init(self, cr, context=None):
3063 Call _field_create and, unless _auto is False:
3065 - create the corresponding table in database for the model,
3066 - possibly add the parent columns in database,
3067 - possibly add the columns 'create_uid', 'create_date', 'write_uid',
3068 'write_date' in database if _log_access is True (the default),
3069 - report on database columns no more existing in _columns,
3070 - remove no more existing not null constraints,
3071 - alter existing database columns to match _columns,
3072 - create database tables to match _columns,
3073 - add database indices to match _columns,
3074 - save in self._foreign_keys a list a foreign keys to create (see
3078 self._foreign_keys = []
3079 raise_on_invalid_object_name(self._name)
3082 store_compute = False
3084 update_custom_fields = context.get('update_custom_fields', False)
3085 self._field_create(cr, context=context)
3086 create = not self._table_exist(cr)
3087 if getattr(self, '_auto', True):
3090 self._create_table(cr)
3093 if self._parent_store:
3094 if not self._parent_columns_exist(cr):
3095 self._create_parent_columns(cr)
3096 store_compute = True
3098 # Create the create_uid, create_date, write_uid, write_date, columns if desired.
3099 if self._log_access:
3100 self._add_log_columns(cr)
3102 self._check_removed_columns(cr, log=False)
3104 # iterate on the "object columns"
3105 column_data = self._select_column_data(cr)
3107 for k, f in self._columns.iteritems():
3108 if k in MAGIC_COLUMNS:
3110 # Don't update custom (also called manual) fields
3111 if f.manual and not update_custom_fields:
3114 if isinstance(f, fields.one2many):
3115 self._o2m_raise_on_missing_reference(cr, f)
3117 elif isinstance(f, fields.many2many):
3118 self._m2m_raise_or_create_relation(cr, f)
3121 res = column_data.get(k)
3123 # The field is not found as-is in database, try if it
3124 # exists with an old name.
3125 if not res and hasattr(f, 'oldname'):
3126 res = column_data.get(f.oldname)
3128 cr.execute('ALTER TABLE "%s" RENAME "%s" TO "%s"' % (self._table, f.oldname, k))
3130 column_data[k] = res
3131 _schema.debug("Table '%s': renamed column '%s' to '%s'",
3132 self._table, f.oldname, k)
3134 # The field already exists in database. Possibly
3135 # change its type, rename it, drop it or change its
3138 f_pg_type = res['typname']
3139 f_pg_size = res['size']
3140 f_pg_notnull = res['attnotnull']
3141 if isinstance(f, fields.function) and not f.store and\
3142 not getattr(f, 'nodrop', False):
3143 _logger.info('column %s (%s) in table %s removed: converted to a function !\n',
3144 k, f.string, self._table)
3145 cr.execute('ALTER TABLE "%s" DROP COLUMN "%s" CASCADE' % (self._table, k))
3147 _schema.debug("Table '%s': dropped column '%s' with cascade",
3151 f_obj_type = get_pg_type(f) and get_pg_type(f)[0]
3156 ('text', 'char', pg_varchar(f.size), '::%s' % pg_varchar(f.size)),
3157 ('varchar', 'text', 'TEXT', ''),
3158 ('int4', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
3159 ('date', 'datetime', 'TIMESTAMP', '::TIMESTAMP'),
3160 ('timestamp', 'date', 'date', '::date'),
3161 ('numeric', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
3162 ('float8', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
3164 if f_pg_type == 'varchar' and f._type == 'char' and f_pg_size < f.size:
3165 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
3166 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, pg_varchar(f.size)))
3167 cr.execute('UPDATE "%s" SET "%s"=temp_change_size::%s' % (self._table, k, pg_varchar(f.size)))
3168 cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
3170 _schema.debug("Table '%s': column '%s' (type varchar) changed size from %s to %s",
3171 self._table, k, f_pg_size, f.size)
3173 if (f_pg_type==c[0]) and (f._type==c[1]):
3174 if f_pg_type != f_obj_type:
3176 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
3177 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, c[2]))
3178 cr.execute(('UPDATE "%s" SET "%s"=temp_change_size'+c[3]) % (self._table, k))
3179 cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
3181 _schema.debug("Table '%s': column '%s' changed type from %s to %s",
3182 self._table, k, c[0], c[1])
3185 if f_pg_type != f_obj_type:
3189 newname = k + '_moved' + str(i)
3190 cr.execute("SELECT count(1) FROM pg_class c,pg_attribute a " \
3191 "WHERE c.relname=%s " \
3192 "AND a.attname=%s " \
3193 "AND c.oid=a.attrelid ", (self._table, newname))
3194 if not cr.fetchone()[0]:
3198 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
3199 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO "%s"' % (self._table, k, newname))
3200 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
3201 cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,))
3202 _schema.debug("Table '%s': column '%s' has changed type (DB=%s, def=%s), data moved to column %s !",
3203 self._table, k, f_pg_type, f._type, newname)
3205 # if the field is required and hasn't got a NOT NULL constraint
3206 if f.required and f_pg_notnull == 0:
3207 # set the field to the default value if any
3208 if k in self._defaults:
3209 if callable(self._defaults[k]):
3210 default = self._defaults[k](self, cr, SUPERUSER_ID, context)
3212 default = self._defaults[k]
3214 if (default is not None):
3215 ss = self._columns[k]._symbol_set
3216 query = 'UPDATE "%s" SET "%s"=%s WHERE "%s" is NULL' % (self._table, k, ss[0], k)
3217 cr.execute(query, (ss[1](default),))
3218 # add the NOT NULL constraint
3221 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False)
3223 _schema.debug("Table '%s': column '%s': added NOT NULL constraint",
3226 msg = "Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\
3227 "If you want to have it, you should update the records and execute manually:\n"\
3228 "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
3229 _schema.warning(msg, self._table, k, self._table, k)
3231 elif not f.required and f_pg_notnull == 1:
3232 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
3234 _schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
3237 indexname = '%s_%s_index' % (self._table, k)
3238 cr.execute("SELECT indexname FROM pg_indexes WHERE indexname = %s and tablename = %s", (indexname, self._table))
3239 res2 = cr.dictfetchall()
3240 if not res2 and f.select:
3241 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
3243 if f._type == 'text':
3244 # FIXME: for fields.text columns we should try creating GIN indexes instead (seems most suitable for an ERP context)
3245 msg = "Table '%s': Adding (b-tree) index for text column '%s'."\
3246 "This is probably useless (does not work for fulltext search) and prevents INSERTs of long texts"\
3247 " because there is a length limit for indexable btree values!\n"\
3248 "Use a search view instead if you simply want to make the field searchable."
3249 _schema.warning(msg, self._table, k, f._type)
3250 if res2 and not f.select:
3251 cr.execute('DROP INDEX "%s_%s_index"' % (self._table, k))
3253 msg = "Table '%s': dropping index for column '%s' of type '%s' as it is not required anymore"
3254 _schema.debug(msg, self._table, k, f._type)
3256 if isinstance(f, fields.many2one):
3257 dest_model = self.pool.get(f._obj)
3258 if dest_model._table != 'ir_actions':
3259 self._m2o_fix_foreign_key(cr, self._table, k, dest_model, f.ondelete)
3261 # The field doesn't exist in database. Create it if necessary.
3263 if not isinstance(f, fields.function) or f.store:
3264 # add the missing field
3265 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
3266 cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,))
3267 _schema.debug("Table '%s': added column '%s' with definition=%s",
3268 self._table, k, get_pg_type(f)[1])
3271 if not create and k in self._defaults:
3272 if callable(self._defaults[k]):
3273 default = self._defaults[k](self, cr, SUPERUSER_ID, context)
3275 default = self._defaults[k]
3277 ss = self._columns[k]._symbol_set
3278 query = 'UPDATE "%s" SET "%s"=%s' % (self._table, k, ss[0])
3279 cr.execute(query, (ss[1](default),))
3281 _logger.debug("Table '%s': setting default value of new column %s", self._table, k)
3283 # remember the functions to call for the stored fields
3284 if isinstance(f, fields.function):
3286 if f.store is not True: # i.e. if f.store is a dict
3287 order = f.store[f.store.keys()[0]][2]
3288 todo_end.append((order, self._update_store, (f, k)))
3290 # and add constraints if needed
3291 if isinstance(f, fields.many2one):
3292 if not self.pool.get(f._obj):
3293 raise except_orm('Programming Error', ('There is no reference available for %s') % (f._obj,))
3294 dest_model = self.pool.get(f._obj)
3295 ref = dest_model._table
3296 # ir_actions is inherited so foreign key doesn't work on it
3297 if ref != 'ir_actions':
3298 self._m2o_add_foreign_key_checked(k, dest_model, f.ondelete)
3300 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
3304 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False)
3305 _schema.debug("Table '%s': column '%s': added a NOT NULL constraint",
3308 msg = "WARNING: unable to set column %s of table %s not null !\n"\
3309 "Try to re-run: openerp-server --update=module\n"\
3310 "If it doesn't work, update records and execute manually:\n"\
3311 "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
3312 _logger.warning(msg, k, self._table, self._table, k)
3316 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
3317 create = not bool(cr.fetchone())
3319 cr.commit() # start a new transaction
3321 self._add_sql_constraints(cr)
3324 self._execute_sql(cr)
3327 self._parent_store_compute(cr)
3332 def _auto_end(self, cr, context=None):
3333 """ Create the foreign keys recorded by _auto_init. """
3334 for t, k, r, d in self._foreign_keys:
3335 cr.execute('ALTER TABLE "%s" ADD FOREIGN KEY ("%s") REFERENCES "%s" ON DELETE %s' % (t, k, r, d))
3336 self._save_constraint(cr, "%s_%s_fkey" % (t, k), 'f')
3338 del self._foreign_keys
3341 def _table_exist(self, cr):
3342 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
3346 def _create_table(self, cr):
3347 cr.execute('CREATE TABLE "%s" (id SERIAL NOT NULL, PRIMARY KEY(id)) WITHOUT OIDS' % (self._table,))
3348 cr.execute(("COMMENT ON TABLE \"%s\" IS %%s" % self._table), (self._description,))
3349 _schema.debug("Table '%s': created", self._table)
3352 def _parent_columns_exist(self, cr):
3353 cr.execute("""SELECT c.relname
3354 FROM pg_class c, pg_attribute a
3355 WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
3356 """, (self._table, 'parent_left'))
3360 def _create_parent_columns(self, cr):
3361 cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_left" INTEGER' % (self._table,))
3362 cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_right" INTEGER' % (self._table,))
3363 if 'parent_left' not in self._columns:
3364 _logger.error('create a column parent_left on object %s: fields.integer(\'Left Parent\', select=1)',
3366 _schema.debug("Table '%s': added column '%s' with definition=%s",
3367 self._table, 'parent_left', 'INTEGER')
3368 elif not self._columns['parent_left'].select:
3369 _logger.error('parent_left column on object %s must be indexed! Add select=1 to the field definition)',
3371 if 'parent_right' not in self._columns:
3372 _logger.error('create a column parent_right on object %s: fields.integer(\'Right Parent\', select=1)',
3374 _schema.debug("Table '%s': added column '%s' with definition=%s",
3375 self._table, 'parent_right', 'INTEGER')
3376 elif not self._columns['parent_right'].select:
3377 _logger.error('parent_right column on object %s must be indexed! Add select=1 to the field definition)',
3379 if self._columns[self._parent_name].ondelete != 'cascade':
3380 _logger.error("The column %s on object %s must be set as ondelete='cascade'",
3381 self._parent_name, self._name)
3386 def _add_log_columns(self, cr):
3387 for field, field_def in LOG_ACCESS_COLUMNS.iteritems():
3390 FROM pg_class c, pg_attribute a
3391 WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
3392 """, (self._table, field))
3394 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, field, field_def))
3396 _schema.debug("Table '%s': added column '%s' with definition=%s",
3397 self._table, field, field_def)
3400 def _select_column_data(self, cr):
3401 # attlen is the number of bytes necessary to represent the type when
3402 # the type has a fixed size. If the type has a varying size attlen is
3403 # -1 and atttypmod is the size limit + 4, or -1 if there is no limit.
3404 # Thus the query can return a negative size for a unlimited varchar.
3405 cr.execute("SELECT c.relname,a.attname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,t.typname,CASE WHEN a.attlen=-1 THEN a.atttypmod-4 ELSE a.attlen END as size " \
3406 "FROM pg_class c,pg_attribute a,pg_type t " \
3407 "WHERE c.relname=%s " \
3408 "AND c.oid=a.attrelid " \
3409 "AND a.atttypid=t.oid", (self._table,))
3410 return dict(map(lambda x: (x['attname'], x),cr.dictfetchall()))
3413 def _o2m_raise_on_missing_reference(self, cr, f):
3414 # TODO this check should be a method on fields.one2many.
3416 other = self.pool.get(f._obj)
3418 # TODO the condition could use fields_get_keys().
3419 if f._fields_id not in other._columns.keys():
3420 if f._fields_id not in other._inherit_fields.keys():
3421 raise except_orm('Programming Error', ("There is no reference field '%s' found for '%s'") % (f._fields_id, f._obj,))
3423 def _m2m_raise_or_create_relation(self, cr, f):
3424 m2m_tbl, col1, col2 = f._sql_names(self)
3425 self._save_relation_table(cr, m2m_tbl)
3426 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (m2m_tbl,))
3427 if not cr.dictfetchall():
3428 if not self.pool.get(f._obj):
3429 raise except_orm('Programming Error', ('Many2Many destination model does not exist: `%s`') % (f._obj,))
3430 dest_model = self.pool.get(f._obj)
3431 ref = dest_model._table
3432 cr.execute('CREATE TABLE "%s" ("%s" INTEGER NOT NULL, "%s" INTEGER NOT NULL, UNIQUE("%s","%s")) WITH OIDS' % (m2m_tbl, col1, col2, col1, col2))
3433 # create foreign key references with ondelete=cascade, unless the targets are SQL views
3434 cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (ref,))
3435 if not cr.fetchall():
3436 self._m2o_add_foreign_key_unchecked(m2m_tbl, col2, dest_model, 'cascade')
3437 cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (self._table,))
3438 if not cr.fetchall():
3439 self._m2o_add_foreign_key_unchecked(m2m_tbl, col1, self, 'cascade')
3441 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col1, m2m_tbl, col1))
3442 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col2, m2m_tbl, col2))
3443 cr.execute("COMMENT ON TABLE \"%s\" IS 'RELATION BETWEEN %s AND %s'" % (m2m_tbl, self._table, ref))
3445 _schema.debug("Create table '%s': m2m relation between '%s' and '%s'", m2m_tbl, self._table, ref)
3448 def _add_sql_constraints(self, cr):
3451 Modify this model's database table constraints so they match the one in
3455 def unify_cons_text(txt):
3456 return txt.lower().replace(', ',',').replace(' (','(')
3458 for (key, con, _) in self._sql_constraints:
3459 conname = '%s_%s' % (self._table, key)
3461 self._save_constraint(cr, conname, 'u')
3462 cr.execute("SELECT conname, pg_catalog.pg_get_constraintdef(oid, true) as condef FROM pg_constraint where conname=%s", (conname,))
3463 existing_constraints = cr.dictfetchall()
3467 'query': 'ALTER TABLE "%s" DROP CONSTRAINT "%s"' % (self._table, conname, ),
3468 'msg_ok': "Table '%s': dropped constraint '%s'. Reason: its definition changed from '%%s' to '%s'" % (
3469 self._table, conname, con),
3470 'msg_err': "Table '%s': unable to drop \'%s\' constraint !" % (self._table, con),
3475 'query': 'ALTER TABLE "%s" ADD CONSTRAINT "%s" %s' % (self._table, conname, con,),
3476 'msg_ok': "Table '%s': added constraint '%s' with definition=%s" % (self._table, conname, con),
3477 '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" % (
3483 if not existing_constraints:
3484 # constraint does not exists:
3485 sql_actions['add']['execute'] = True
3486 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
3487 elif unify_cons_text(con) not in [unify_cons_text(item['condef']) for item in existing_constraints]:
3488 # constraint exists but its definition has changed:
3489 sql_actions['drop']['execute'] = True
3490 sql_actions['drop']['msg_ok'] = sql_actions['drop']['msg_ok'] % (existing_constraints[0]['condef'].lower(), )
3491 sql_actions['add']['execute'] = True
3492 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
3494 # we need to add the constraint:
3495 sql_actions = [item for item in sql_actions.values()]
3496 sql_actions.sort(key=lambda x: x['order'])
3497 for sql_action in [action for action in sql_actions if action['execute']]:
3499 cr.execute(sql_action['query'])
3501 _schema.debug(sql_action['msg_ok'])
3503 _schema.warning(sql_action['msg_err'])
3507 def _execute_sql(self, cr):
3508 """ Execute the SQL code from the _sql attribute (if any)."""
3509 if hasattr(self, "_sql"):
3510 for line in self._sql.split(';'):
3511 line2 = line.replace('\n', '').strip()
3517 # Update objects that uses this one to update their _inherits fields
3520 def _inherits_reload_src(self):
3521 """ Recompute the _inherit_fields mapping on each _inherits'd child model."""
3522 for obj in self.pool.models.values():
3523 if self._name in obj._inherits:
3524 obj._inherits_reload()
3527 def _inherits_reload(self):
3528 """ Recompute the _inherit_fields mapping.
3530 This will also call itself on each inherits'd child model.
3534 for table in self._inherits:
3535 other = self.pool.get(table)
3536 for col in other._columns.keys():
3537 res[col] = (table, self._inherits[table], other._columns[col], table)
3538 for col in other._inherit_fields.keys():
3539 res[col] = (table, self._inherits[table], other._inherit_fields[col][2], other._inherit_fields[col][3])
3540 self._inherit_fields = res
3541 self._all_columns = self._get_column_infos()
3542 self._inherits_reload_src()
3545 def _get_column_infos(self):
3546 """Returns a dict mapping all fields names (direct fields and
3547 inherited field via _inherits) to a ``column_info`` struct
3548 giving detailed columns """
3550 for k, (parent, m2o, col, original_parent) in self._inherit_fields.iteritems():
3551 result[k] = fields.column_info(k, col, parent, m2o, original_parent)
3552 for k, col in self._columns.iteritems():
3553 result[k] = fields.column_info(k, col)
3557 def _inherits_check(self):
3558 for table, field_name in self._inherits.items():
3559 if field_name not in self._columns:
3560 _logger.info('Missing many2one field definition for _inherits reference "%s" in "%s", using default one.', field_name, self._name)
3561 self._columns[field_name] = fields.many2one(table, string="Automatically created field to link to parent %s" % table,
3562 required=True, ondelete="cascade")
3563 elif not self._columns[field_name].required or self._columns[field_name].ondelete.lower() != "cascade":
3564 _logger.warning('Field definition for _inherits reference "%s" in "%s" must be marked as "required" with ondelete="cascade", forcing it.', field_name, self._name)
3565 self._columns[field_name].required = True
3566 self._columns[field_name].ondelete = "cascade"
3568 #def __getattr__(self, name):
3570 # Proxies attribute accesses to the `inherits` parent so we can call methods defined on the inherited parent
3571 # (though inherits doesn't use Python inheritance).
3572 # Handles translating between local ids and remote ids.
3573 # Known issue: doesn't work correctly when using python's own super(), don't involve inherit-based inheritance
3574 # when you have inherits.
3576 # for model, field in self._inherits.iteritems():
3577 # proxy = self.pool.get(model)
3578 # if hasattr(proxy, name):
3579 # attribute = getattr(proxy, name)
3580 # if not hasattr(attribute, '__call__'):
3584 # return super(orm, self).__getattr__(name)
3586 # def _proxy(cr, uid, ids, *args, **kwargs):
3587 # objects = self.browse(cr, uid, ids, kwargs.get('context', None))
3588 # lst = [obj[field].id for obj in objects if obj[field]]
3589 # return getattr(proxy, name)(cr, uid, lst, *args, **kwargs)
3594 def fields_get(self, cr, user, allfields=None, context=None, write_access=True):
3595 """ Return the definition of each field.
3597 The returned value is a dictionary (indiced by field name) of
3598 dictionaries. The _inherits'd fields are included. The string, help,
3599 and selection (if present) attributes are translated.
3601 :param cr: database cursor
3602 :param user: current user id
3603 :param fields: list of fields
3604 :param context: context arguments, like lang, time zone
3605 :return: dictionary of field dictionaries, each one describing a field of the business object
3606 :raise AccessError: * if user has no create/write rights on the requested object
3612 write_access = self.check_access_rights(cr, user, 'write') or self.check_access_rights(cr, user, 'create')
3616 translation_obj = self.pool.get('ir.translation')
3617 for parent in self._inherits:
3618 res.update(self.pool.get(parent).fields_get(cr, user, allfields, context))
3620 for f, field in self._columns.iteritems():
3621 if (allfields and f not in allfields) or \
3622 (field.groups and not self.user_has_groups(cr, user, groups=field.groups, context=context)):
3625 res[f] = fields.field_to_dict(self, cr, user, field, context=context)
3627 if not write_access:
3628 res[f]['readonly'] = True
3629 res[f]['states'] = {}
3631 if 'string' in res[f]:
3632 res_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'field', context.get('lang', False) or 'en_US')
3634 res[f]['string'] = res_trans
3635 if 'help' in res[f]:
3636 help_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'help', context.get('lang', False) or 'en_US')
3638 res[f]['help'] = help_trans
3639 if 'selection' in res[f]:
3640 if isinstance(field.selection, (tuple, list)):
3641 sel = field.selection
3643 for key, val in sel:
3646 val2 = translation_obj._get_source(cr, user, self._name + ',' + f, 'selection', context.get('lang', False) or 'en_US', val)
3647 sel2.append((key, val2 or val))
3648 res[f]['selection'] = sel2
3652 def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
3653 """ Read records with given ids with the given fields
3655 :param cr: database cursor
3656 :param user: current user id
3657 :param ids: id or list of the ids of the records to read
3658 :param fields: optional list of field names to return (default: all fields would be returned)
3659 :type fields: list (example ['field_name_1', ...])
3660 :param context: optional context dictionary - it may contains keys for specifying certain options
3661 like ``context_lang``, ``context_tz`` to alter the results of the call.
3662 A special ``bin_size`` boolean flag may also be passed in the context to request the
3663 value of all fields.binary columns to be returned as the size of the binary instead of its
3664 contents. This can also be selectively overriden by passing a field-specific flag
3665 in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field.
3666 Note: The ``bin_size_XXX`` form is new in OpenERP v6.0.
3667 :return: list of dictionaries((dictionary per record asked)) with requested field values
3668 :rtype: [{‘name_of_the_field’: value, ...}, ...]
3669 :raise AccessError: * if user has no read rights on the requested object
3670 * if user tries to bypass access rules for read on the requested object
3676 self.check_access_rights(cr, user, 'read')
3678 fields = list(set(self._columns.keys() + self._inherit_fields.keys()))
3679 if isinstance(ids, (int, long)):
3683 select = map(lambda x: isinstance(x, dict) and x['id'] or x, select)
3684 result = self._read_flat(cr, user, select, fields, context, load)
3687 for key, v in r.items():
3691 if isinstance(ids, (int, long, dict)):
3692 return result and result[0] or False
3695 def _read_flat(self, cr, user, ids, fields_to_read, context=None, load='_classic_read'):
3700 if fields_to_read == None:
3701 fields_to_read = self._columns.keys()
3703 # Construct a clause for the security rules.
3704 # 'tables' hold the list of tables necessary for the SELECT including the ir.rule clauses,
3705 # or will at least contain self._table.
3706 rule_clause, rule_params, tables = self.pool.get('ir.rule').domain_get(cr, user, self._name, 'read', context=context)
3708 # all inherited fields + all non inherited fields for which the attribute whose name is in load is True
3709 fields_pre = [f for f in fields_to_read if
3710 f == self.CONCURRENCY_CHECK_FIELD
3711 or (f in self._columns and getattr(self._columns[f], '_classic_write'))
3712 ] + self._inherits.values()
3716 def convert_field(f):
3717 f_qual = '%s."%s"' % (self._table, f) # need fully-qualified references in case len(tables) > 1
3718 if f in ('create_date', 'write_date'):
3719 return "date_trunc('second', %s) as %s" % (f_qual, f)
3720 if f == self.CONCURRENCY_CHECK_FIELD:
3721 if self._log_access:
3722 return "COALESCE(%s.write_date, %s.create_date, (now() at time zone 'UTC'))::timestamp AS %s" % (self._table, self._table, f,)
3723 return "(now() at time zone 'UTC')::timestamp AS %s" % (f,)
3724 if isinstance(self._columns[f], fields.binary) and context.get('bin_size', False):
3725 return 'length(%s) as "%s"' % (f_qual, f)
3728 fields_pre2 = map(convert_field, fields_pre)
3729 order_by = self._parent_order or self._order
3730 select_fields = ','.join(fields_pre2 + [self._table + '.id'])
3731 query = 'SELECT %s FROM %s WHERE %s.id IN %%s' % (select_fields, ','.join(tables), self._table)
3733 query += " AND " + (' OR '.join(rule_clause))
3734 query += " ORDER BY " + order_by
3735 for sub_ids in cr.split_for_in_conditions(ids):
3737 cr.execute(query, [tuple(sub_ids)] + rule_params)
3738 self._check_record_rules_result_count(cr, user, sub_ids, 'read', context=context)
3740 cr.execute(query, (tuple(sub_ids),))
3741 res.extend(cr.dictfetchall())
3743 res = map(lambda x: {'id': x}, ids)
3745 for f in fields_pre:
3746 if f == self.CONCURRENCY_CHECK_FIELD:
3748 if self._columns[f].translate:
3749 ids = [x['id'] for x in res]
3750 #TODO: optimize out of this loop
3751 res_trans = self.pool.get('ir.translation')._get_ids(cr, user, self._name+','+f, 'model', context.get('lang', False) or 'en_US', ids)
3753 r[f] = res_trans.get(r['id'], False) or r[f]
3755 for table in self._inherits:
3756 col = self._inherits[table]
3757 cols = [x for x in intersect(self._inherit_fields.keys(), fields_to_read) if x not in self._columns.keys()]
3760 res2 = self.pool.get(table).read(cr, user, [x[col] for x in res], cols, context, load)
3768 if not record[col]: # if the record is deleted from _inherits table?
3770 record.update(res3[record[col]])
3771 if col not in fields_to_read:
3774 # all fields which need to be post-processed by a simple function (symbol_get)
3775 fields_post = filter(lambda x: x in self._columns and self._columns[x]._symbol_get, fields_to_read)
3778 for f in fields_post:
3779 r[f] = self._columns[f]._symbol_get(r[f])
3780 ids = [x['id'] for x in res]
3782 # all non inherited fields for which the attribute whose name is in load is False
3783 fields_post = filter(lambda x: x in self._columns and not getattr(self._columns[x], load), fields_to_read)
3785 # Compute POST fields
3787 for f in fields_post:
3788 todo.setdefault(self._columns[f]._multi, [])
3789 todo[self._columns[f]._multi].append(f)
3790 for key, val in todo.items():
3792 res2 = self._columns[val[0]].get(cr, self, ids, val, user, context=context, values=res)
3793 assert res2 is not None, \
3794 'The function field "%s" on the "%s" model returned None\n' \
3795 '(a dictionary was expected).' % (val[0], self._name)
3798 if isinstance(res2[record['id']], str): res2[record['id']] = eval(res2[record['id']]) #TOCHECK : why got string instend of dict in python2.6
3799 multi_fields = res2.get(record['id'],{})
3801 record[pos] = multi_fields.get(pos,[])
3804 res2 = self._columns[f].get(cr, self, ids, f, user, context=context, values=res)
3807 record[f] = res2[record['id']]
3811 # Warn about deprecated fields now that fields_pre and fields_post are computed
3812 # Explicitly use list() because we may receive tuples
3813 for f in list(fields_pre) + list(fields_post):
3814 field_column = self._all_columns.get(f) and self._all_columns.get(f).column
3815 if field_column and field_column.deprecated:
3816 _logger.warning('Field %s.%s is deprecated: %s', self._name, f, field_column.deprecated)
3820 for field in vals.copy():
3822 if field in self._columns:
3823 fobj = self._columns[field]
3830 for group in groups:
3831 module = group.split(".")[0]
3832 grp = group.split(".")[1]
3833 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", \
3834 (grp, module, 'res.groups', user))
3835 readonly = cr.fetchall()
3836 if readonly[0][0] >= 1:
3839 elif readonly[0][0] == 0:
3845 if type(vals[field]) == type([]):
3847 elif type(vals[field]) == type(0.0):
3849 elif type(vals[field]) == type(''):
3850 vals[field] = '=No Permission='
3855 # TODO check READ access
3856 def perm_read(self, cr, user, ids, context=None, details=True):
3858 Returns some metadata about the given records.
3860 :param details: if True, \*_uid fields are replaced with the name of the user
3861 :return: list of ownership dictionaries for each requested record
3862 :rtype: list of dictionaries with the following keys:
3865 * create_uid: user who created the record
3866 * create_date: date when the record was created
3867 * write_uid: last user who changed the record
3868 * write_date: date of the last change to the record
3869 * xmlid: XML ID to use to refer to this record (if there is one), in format ``module.name``
3876 uniq = isinstance(ids, (int, long))
3880 if self._log_access:
3881 fields += ['create_uid', 'create_date', 'write_uid', 'write_date']
3882 quoted_table = '"%s"' % self._table
3883 fields_str = ",".join('%s.%s'%(quoted_table, field) for field in fields)
3884 query = '''SELECT %s, __imd.module, __imd.name
3885 FROM %s LEFT JOIN ir_model_data __imd
3886 ON (__imd.model = %%s and __imd.res_id = %s.id)
3887 WHERE %s.id IN %%s''' % (fields_str, quoted_table, quoted_table, quoted_table)
3888 cr.execute(query, (self._name, tuple(ids)))
3889 res = cr.dictfetchall()
3892 r[key] = r[key] or False
3893 if details and key in ('write_uid', 'create_uid') and r[key]:
3895 r[key] = self.pool.get('res.users').name_get(cr, user, [r[key]])[0]
3897 pass # Leave the numeric uid there
3898 r['xmlid'] = ("%(module)s.%(name)s" % r) if r['name'] else False
3899 del r['name'], r['module']
3904 def _check_concurrency(self, cr, ids, context):
3907 if not (context.get(self.CONCURRENCY_CHECK_FIELD) and self._log_access):
3909 check_clause = "(id = %s AND %s < COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp)"
3910 for sub_ids in cr.split_for_in_conditions(ids):
3913 id_ref = "%s,%s" % (self._name, id)
3914 update_date = context[self.CONCURRENCY_CHECK_FIELD].pop(id_ref, None)
3916 ids_to_check.extend([id, update_date])
3917 if not ids_to_check:
3919 cr.execute("SELECT id FROM %s WHERE %s" % (self._table, " OR ".join([check_clause]*(len(ids_to_check)/2))), tuple(ids_to_check))
3922 # mention the first one only to keep the error message readable
3923 raise except_orm('ConcurrencyException', _('A document was modified since you last viewed it (%s:%d)') % (self._description, res[0]))
3925 def _check_record_rules_result_count(self, cr, uid, ids, operation, context=None):
3926 """Verify that number of returned rows after applying record rules matches
3927 the length of `ids`, and raise an appropriate exception if it does not.
3929 if cr.rowcount != len(ids):
3930 # Attempt to distinguish record rule restriction vs deleted records,
3931 # to provide a more specific error message
3932 cr.execute('SELECT id FROM ' + self._table + ' WHERE id IN %s', (tuple(ids),))
3933 if cr.rowcount != len(ids):
3934 if operation == 'unlink':
3935 # no need to warn about deleting an already deleted record!
3937 _logger.warning('Failed operation on deleted record(s): %s, uid: %s, model: %s', operation, uid, self._name)
3938 raise except_orm(_('Missing document(s)'),
3939 _('One of the documents you are trying to access has been deleted, please try again after refreshing.'))
3940 _logger.warning('Access Denied by record rules for operation: %s, uid: %s, model: %s', operation, uid, self._name)
3941 raise except_orm(_('Access Denied'),
3942 _('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \
3943 (self._description, operation))
3945 def check_access_rights(self, cr, uid, operation, raise_exception=True): # no context on purpose.
3946 """Verifies that the operation given by ``operation`` is allowed for the user
3947 according to the access rights."""
3948 return self.pool.get('ir.model.access').check(cr, uid, self._name, operation, raise_exception)
3950 def check_access_rule(self, cr, uid, ids, operation, context=None):
3951 """Verifies that the operation given by ``operation`` is allowed for the user
3952 according to ir.rules.
3954 :param operation: one of ``write``, ``unlink``
3955 :raise except_orm: * if current ir.rules do not permit this operation.
3956 :return: None if the operation is allowed
3958 if uid == SUPERUSER_ID:
3961 if self.is_transient():
3962 # Only one single implicit access rule for transient models: owner only!
3963 # This is ok to hardcode because we assert that TransientModels always
3964 # have log_access enabled so that the create_uid column is always there.
3965 # And even with _inherits, these fields are always present in the local
3966 # table too, so no need for JOINs.
3967 cr.execute("""SELECT distinct create_uid
3969 WHERE id IN %%s""" % self._table, (tuple(ids),))
3970 uids = [x[0] for x in cr.fetchall()]
3971 if len(uids) != 1 or uids[0] != uid:
3972 raise except_orm(_('Access Denied'),
3973 _('For this kind of document, you may only access records you created yourself.\n\n(Document type: %s)') % (self._description,))
3975 where_clause, where_params, tables = self.pool.get('ir.rule').domain_get(cr, uid, self._name, operation, context=context)
3977 where_clause = ' and ' + ' and '.join(where_clause)
3978 for sub_ids in cr.split_for_in_conditions(ids):
3979 cr.execute('SELECT ' + self._table + '.id FROM ' + ','.join(tables) +
3980 ' WHERE ' + self._table + '.id IN %s' + where_clause,
3981 [sub_ids] + where_params)
3982 self._check_record_rules_result_count(cr, uid, sub_ids, operation, context=context)
3984 def _workflow_trigger(self, cr, uid, ids, trigger, context=None):
3985 """Call given workflow trigger as a result of a CRUD operation"""
3986 wf_service = netsvc.LocalService("workflow")
3988 getattr(wf_service, trigger)(uid, self._name, res_id, cr)
3990 def unlink(self, cr, uid, ids, context=None):
3992 Delete records with given ids
3994 :param cr: database cursor
3995 :param uid: current user id
3996 :param ids: id or list of ids
3997 :param context: (optional) context arguments, like lang, time zone
3999 :raise AccessError: * if user has no unlink rights on the requested object
4000 * if user tries to bypass access rules for unlink on the requested object
4001 :raise UserError: if the record is default property for other records
4006 if isinstance(ids, (int, long)):
4009 result_store = self._store_get_values(cr, uid, ids, None, context)
4011 self._check_concurrency(cr, ids, context)
4013 self.check_access_rights(cr, uid, 'unlink')
4015 ir_property = self.pool.get('ir.property')
4017 # Check if the records are used as default properties.
4018 domain = [('res_id', '=', False),
4019 ('value_reference', 'in', ['%s,%s' % (self._name, i) for i in ids]),
4021 if ir_property.search(cr, uid, domain, context=context):
4022 raise except_orm(_('Error'), _('Unable to delete this document because it is used as a default property'))
4024 # Delete the records' properties.
4025 property_ids = ir_property.search(cr, uid, [('res_id', 'in', ['%s,%s' % (self._name, i) for i in ids])], context=context)
4026 ir_property.unlink(cr, uid, property_ids, context=context)
4028 self._workflow_trigger(cr, uid, ids, 'trg_delete', context=context)
4030 self.check_access_rule(cr, uid, ids, 'unlink', context=context)
4031 pool_model_data = self.pool.get('ir.model.data')
4032 ir_values_obj = self.pool.get('ir.values')
4033 for sub_ids in cr.split_for_in_conditions(ids):
4034 cr.execute('delete from ' + self._table + ' ' \
4035 'where id IN %s', (sub_ids,))
4037 # Removing the ir_model_data reference if the record being deleted is a record created by xml/csv file,
4038 # as these are not connected with real database foreign keys, and would be dangling references.
4039 # Note: following steps performed as admin to avoid access rights restrictions, and with no context
4040 # to avoid possible side-effects during admin calls.
4041 # Step 1. Calling unlink of ir_model_data only for the affected IDS
4042 reference_ids = pool_model_data.search(cr, SUPERUSER_ID, [('res_id','in',list(sub_ids)),('model','=',self._name)])
4043 # Step 2. Marching towards the real deletion of referenced records
4045 pool_model_data.unlink(cr, SUPERUSER_ID, reference_ids)
4047 # For the same reason, removing the record relevant to ir_values
4048 ir_value_ids = ir_values_obj.search(cr, uid,
4049 ['|',('value','in',['%s,%s' % (self._name, sid) for sid in sub_ids]),'&',('res_id','in',list(sub_ids)),('model','=',self._name)],
4052 ir_values_obj.unlink(cr, uid, ir_value_ids, context=context)
4054 for order, object, store_ids, fields in result_store:
4055 if object != self._name:
4056 obj = self.pool.get(object)
4057 cr.execute('select id from '+obj._table+' where id IN %s', (tuple(store_ids),))
4058 rids = map(lambda x: x[0], cr.fetchall())
4060 obj._store_set_values(cr, uid, rids, fields, context)
4067 def write(self, cr, user, ids, vals, context=None):
4069 Update records with given ids with the given field values
4071 :param cr: database cursor
4072 :param user: current user id
4074 :param ids: object id or list of object ids to update according to **vals**
4075 :param vals: field values to update, e.g {'field_name': new_field_value, ...}
4076 :type vals: dictionary
4077 :param context: (optional) context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...}
4078 :type context: dictionary
4080 :raise AccessError: * if user has no write rights on the requested object
4081 * if user tries to bypass access rules for write on the requested object
4082 :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
4083 :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)
4085 **Note**: The type of field values to pass in ``vals`` for relationship fields is specific:
4087 + For a many2many field, a list of tuples is expected.
4088 Here is the list of tuple that are accepted, with the corresponding semantics ::
4090 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
4091 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
4092 (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)
4093 (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)
4094 (4, ID) link to existing record with id = ID (adds a relationship)
4095 (5) unlink all (like using (3,ID) for all linked records)
4096 (6, 0, [IDs]) replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)
4099 [(6, 0, [8, 5, 6, 4])] sets the many2many to ids [8, 5, 6, 4]
4101 + For a one2many field, a lits of tuples is expected.
4102 Here is the list of tuple that are accepted, with the corresponding semantics ::
4104 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
4105 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
4106 (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)
4109 [(0, 0, {'field_name':field_value_record1, ...}), (0, 0, {'field_name':field_value_record2, ...})]
4111 + For a many2one field, simply use the ID of target record, which must already exist, or ``False`` to remove the link.
4112 + For a reference field, use a string with the model name, a comma, and the target object id (example: ``'product.product, 5'``)
4116 for field in vals.copy():
4118 if field in self._columns:
4119 fobj = self._columns[field]
4120 elif field in self._inherit_fields:
4121 fobj = self._inherit_fields[field][2]
4128 for group in groups:
4129 module = group.split(".")[0]
4130 grp = group.split(".")[1]
4131 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", \
4132 (grp, module, 'res.groups', user))
4133 readonly = cr.fetchall()
4134 if readonly[0][0] >= 1:
4145 if isinstance(ids, (int, long)):
4148 self._check_concurrency(cr, ids, context)
4149 self.check_access_rights(cr, user, 'write')
4151 result = self._store_get_values(cr, user, ids, vals.keys(), context) or []
4153 # No direct update of parent_left/right
4154 vals.pop('parent_left', None)
4155 vals.pop('parent_right', None)
4157 parents_changed = []
4158 parent_order = self._parent_order or self._order
4159 if self._parent_store and (self._parent_name in vals):
4160 # The parent_left/right computation may take up to
4161 # 5 seconds. No need to recompute the values if the
4162 # parent is the same.
4163 # Note: to respect parent_order, nodes must be processed in
4164 # order, so ``parents_changed`` must be ordered properly.
4165 parent_val = vals[self._parent_name]
4167 query = "SELECT id FROM %s WHERE id IN %%s AND (%s != %%s OR %s IS NULL) ORDER BY %s" % \
4168 (self._table, self._parent_name, self._parent_name, parent_order)
4169 cr.execute(query, (tuple(ids), parent_val))
4171 query = "SELECT id FROM %s WHERE id IN %%s AND (%s IS NOT NULL) ORDER BY %s" % \
4172 (self._table, self._parent_name, parent_order)
4173 cr.execute(query, (tuple(ids),))
4174 parents_changed = map(operator.itemgetter(0), cr.fetchall())
4181 totranslate = context.get('lang', False) and (context['lang'] != 'en_US')
4183 field_column = self._all_columns.get(field) and self._all_columns.get(field).column
4184 if field_column and field_column.deprecated:
4185 _logger.warning('Field %s.%s is deprecated: %s', self._name, field, field_column.deprecated)
4186 if field in self._columns:
4187 if self._columns[field]._classic_write and not (hasattr(self._columns[field], '_fnct_inv')):
4188 if (not totranslate) or not self._columns[field].translate:
4189 upd0.append('"'+field+'"='+self._columns[field]._symbol_set[0])
4190 upd1.append(self._columns[field]._symbol_set[1](vals[field]))
4191 direct.append(field)
4193 upd_todo.append(field)
4195 updend.append(field)
4196 if field in self._columns \
4197 and hasattr(self._columns[field], 'selection') \
4199 self._check_selection_field_value(cr, user, field, vals[field], context=context)
4201 if self._log_access:
4202 upd0.append('write_uid=%s')
4203 upd0.append("write_date=(now() at time zone 'UTC')")
4207 self.check_access_rule(cr, user, ids, 'write', context=context)
4208 for sub_ids in cr.split_for_in_conditions(ids):
4209 cr.execute('update ' + self._table + ' set ' + ','.join(upd0) + ' ' \
4210 'where id IN %s', upd1 + [sub_ids])
4211 if cr.rowcount != len(sub_ids):
4212 raise except_orm(_('AccessError'),
4213 _('One of the records you are trying to modify has already been deleted (Document type: %s).') % self._description)
4218 if self._columns[f].translate:
4219 src_trans = self.pool.get(self._name).read(cr, user, ids, [f])[0][f]
4222 # Inserting value to DB
4223 self.write(cr, user, ids, {f: vals[f]})
4224 self.pool.get('ir.translation')._set_ids(cr, user, self._name+','+f, 'model', context['lang'], ids, vals[f], src_trans)
4227 # call the 'set' method of fields which are not classic_write
4228 upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
4230 # default element in context must be removed when call a one2many or many2many
4231 rel_context = context.copy()
4232 for c in context.items():
4233 if c[0].startswith('default_'):
4234 del rel_context[c[0]]
4236 for field in upd_todo:
4238 result += self._columns[field].set(cr, self, id, field, vals[field], user, context=rel_context) or []
4240 unknown_fields = updend[:]
4241 for table in self._inherits:
4242 col = self._inherits[table]
4244 for sub_ids in cr.split_for_in_conditions(ids):
4245 cr.execute('select distinct "'+col+'" from "'+self._table+'" ' \
4246 'where id IN %s', (sub_ids,))
4247 nids.extend([x[0] for x in cr.fetchall()])
4251 if self._inherit_fields[val][0] == table:
4253 unknown_fields.remove(val)
4255 self.pool.get(table).write(cr, user, nids, v, context)
4259 'No such field(s) in model %s: %s.',
4260 self._name, ', '.join(unknown_fields))
4261 self._validate(cr, user, ids, context)
4263 # TODO: use _order to set dest at the right position and not first node of parent
4264 # We can't defer parent_store computation because the stored function
4265 # fields that are computer may refer (directly or indirectly) to
4266 # parent_left/right (via a child_of domain)
4269 self.pool._init_parent[self._name] = True
4271 order = self._parent_order or self._order
4272 parent_val = vals[self._parent_name]
4274 clause, params = '%s=%%s' % (self._parent_name,), (parent_val,)
4276 clause, params = '%s IS NULL' % (self._parent_name,), ()
4278 for id in parents_changed:
4279 cr.execute('SELECT parent_left, parent_right FROM %s WHERE id=%%s' % (self._table,), (id,))
4280 pleft, pright = cr.fetchone()
4281 distance = pright - pleft + 1
4283 # Positions of current siblings, to locate proper insertion point;
4284 # this can _not_ be fetched outside the loop, as it needs to be refreshed
4285 # after each update, in case several nodes are sequentially inserted one
4286 # next to the other (i.e computed incrementally)
4287 cr.execute('SELECT parent_right, id FROM %s WHERE %s ORDER BY %s' % (self._table, clause, parent_order), params)
4288 parents = cr.fetchall()
4290 # Find Position of the element
4292 for (parent_pright, parent_id) in parents:
4295 position = parent_pright + 1
4297 # It's the first node of the parent
4302 cr.execute('select parent_left from '+self._table+' where id=%s', (parent_val,))
4303 position = cr.fetchone()[0] + 1
4305 if pleft < position <= pright:
4306 raise except_orm(_('UserError'), _('Recursivity Detected.'))
4308 if pleft < position:
4309 cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
4310 cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
4311 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))
4313 cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
4314 cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
4315 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))
4317 result += self._store_get_values(cr, user, ids, vals.keys(), context)
4321 for order, object, ids_to_update, fields_to_recompute in result:
4322 key = (object, tuple(fields_to_recompute))
4323 done.setdefault(key, {})
4324 # avoid to do several times the same computation
4326 for id in ids_to_update:
4327 if id not in done[key]:
4328 done[key][id] = True
4330 self.pool.get(object)._store_set_values(cr, user, todo, fields_to_recompute, context)
4332 self._workflow_trigger(cr, user, ids, 'trg_write', context=context)
4336 # TODO: Should set perm to user.xxx
4338 def create(self, cr, user, vals, context=None):
4340 Create a new record for the model.
4342 The values for the new record are initialized using the ``vals``
4343 argument, and if necessary the result of ``default_get()``.
4345 :param cr: database cursor
4346 :param user: current user id
4348 :param vals: field values for new record, e.g {'field_name': field_value, ...}
4349 :type vals: dictionary
4350 :param context: optional context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...}
4351 :type context: dictionary
4352 :return: id of new record created
4353 :raise AccessError: * if user has no create rights on the requested object
4354 * if user tries to bypass access rules for create on the requested object
4355 :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
4356 :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)
4358 **Note**: The type of field values to pass in ``vals`` for relationship fields is specific.
4359 Please see the description of the :py:meth:`~osv.osv.osv.write` method for details about the possible values and how
4366 if self.is_transient():
4367 self._transient_vacuum(cr, user)
4369 self.check_access_rights(cr, user, 'create')
4371 if self._log_access:
4372 for f in LOG_ACCESS_COLUMNS:
4373 if vals.pop(f, None) is not None:
4375 'Field `%s` is not allowed when creating the model `%s`.',
4377 vals = self._add_missing_default_values(cr, user, vals, context)
4380 for v in self._inherits:
4381 if self._inherits[v] not in vals:
4384 tocreate[v] = {'id': vals[self._inherits[v]]}
4385 (upd0, upd1, upd2) = ('', '', [])
4388 for v in vals.keys():
4389 if v in self._inherit_fields and v not in self._columns:
4390 (table, col, col_detail, original_parent) = self._inherit_fields[v]
4391 tocreate[table][v] = vals[v]
4394 if (v not in self._inherit_fields) and (v not in self._columns):
4396 unknown_fields.append(v)
4399 'No such field(s) in model %s: %s.',
4400 self._name, ', '.join(unknown_fields))
4402 # Try-except added to filter the creation of those records whose filds are readonly.
4403 # Example : any dashboard which has all the fields readonly.(due to Views(database views))
4405 cr.execute("SELECT nextval('"+self._sequence+"')")
4407 raise except_orm(_('UserError'),
4408 _('You cannot perform this operation. New Record Creation is not allowed for this object as this object is for reporting purpose.'))
4410 id_new = cr.fetchone()[0]
4411 for table in tocreate:
4412 if self._inherits[table] in vals:
4413 del vals[self._inherits[table]]
4415 record_id = tocreate[table].pop('id', None)
4417 if record_id is None or not record_id:
4418 record_id = self.pool.get(table).create(cr, user, tocreate[table], context=context)
4420 self.pool.get(table).write(cr, user, [record_id], tocreate[table], context=context)
4422 upd0 += ',' + self._inherits[table]
4424 upd2.append(record_id)
4426 #Start : Set bool fields to be False if they are not touched(to make search more powerful)
4427 bool_fields = [x for x in self._columns.keys() if self._columns[x]._type=='boolean']
4429 for bool_field in bool_fields:
4430 if bool_field not in vals:
4431 vals[bool_field] = False
4433 for field in vals.copy():
4435 if field in self._columns:
4436 fobj = self._columns[field]
4438 fobj = self._inherit_fields[field][2]
4444 for group in groups:
4445 module = group.split(".")[0]
4446 grp = group.split(".")[1]
4447 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" % \
4448 (grp, module, 'res.groups', user))
4449 readonly = cr.fetchall()
4450 if readonly[0][0] >= 1:
4453 elif readonly[0][0] == 0:
4461 if self._columns[field]._classic_write:
4462 upd0 = upd0 + ',"' + field + '"'
4463 upd1 = upd1 + ',' + self._columns[field]._symbol_set[0]
4464 upd2.append(self._columns[field]._symbol_set[1](vals[field]))
4466 if not isinstance(self._columns[field], fields.related):
4467 upd_todo.append(field)
4468 if field in self._columns \
4469 and hasattr(self._columns[field], 'selection') \
4471 self._check_selection_field_value(cr, user, field, vals[field], context=context)
4472 if self._log_access:
4473 upd0 += ',create_uid,create_date'
4474 upd1 += ",%s,(now() at time zone 'UTC')"
4476 cr.execute('insert into "'+self._table+'" (id'+upd0+") values ("+str(id_new)+upd1+')', tuple(upd2))
4477 self.check_access_rule(cr, user, [id_new], 'create', context=context)
4478 upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
4480 if self._parent_store and not context.get('defer_parent_store_computation'):
4482 self.pool._init_parent[self._name] = True
4484 parent = vals.get(self._parent_name, False)
4486 cr.execute('select parent_right from '+self._table+' where '+self._parent_name+'=%s order by '+(self._parent_order or self._order), (parent,))
4488 result_p = cr.fetchall()
4489 for (pleft,) in result_p:
4494 cr.execute('select parent_left from '+self._table+' where id=%s', (parent,))
4495 pleft_old = cr.fetchone()[0]
4498 cr.execute('select max(parent_right) from '+self._table)
4499 pleft = cr.fetchone()[0] or 0
4500 cr.execute('update '+self._table+' set parent_left=parent_left+2 where parent_left>%s', (pleft,))
4501 cr.execute('update '+self._table+' set parent_right=parent_right+2 where parent_right>%s', (pleft,))
4502 cr.execute('update '+self._table+' set parent_left=%s,parent_right=%s where id=%s', (pleft+1, pleft+2, id_new))
4504 # default element in context must be remove when call a one2many or many2many
4505 rel_context = context.copy()
4506 for c in context.items():
4507 if c[0].startswith('default_'):
4508 del rel_context[c[0]]
4511 for field in upd_todo:
4512 result += self._columns[field].set(cr, self, id_new, field, vals[field], user, rel_context) or []
4513 self._validate(cr, user, [id_new], context)
4515 if not context.get('no_store_function', False):
4516 result += self._store_get_values(cr, user, [id_new], vals.keys(), context)
4519 for order, object, ids, fields2 in result:
4520 if not (object, ids, fields2) in done:
4521 self.pool.get(object)._store_set_values(cr, user, ids, fields2, context)
4522 done.append((object, ids, fields2))
4524 if self._log_create and not (context and context.get('no_store_function', False)):
4525 message = self._description + \
4527 self.name_get(cr, user, [id_new], context=context)[0][1] + \
4528 "' " + _("created.")
4529 self.log(cr, user, id_new, message, True, context=context)
4530 self._workflow_trigger(cr, user, [id_new], 'trg_create', context=context)
4533 def browse(self, cr, uid, select, context=None, list_class=None, fields_process=None):
4534 """Fetch records as objects allowing to use dot notation to browse fields and relations
4536 :param cr: database cursor
4537 :param uid: current user id
4538 :param select: id or list of ids.
4539 :param context: context arguments, like lang, time zone
4540 :rtype: object or list of objects requested
4543 self._list_class = list_class or browse_record_list
4545 # need to accepts ints and longs because ids coming from a method
4546 # launched by button in the interface have a type long...
4547 if isinstance(select, (int, long)):
4548 return browse_record(cr, uid, select, self, cache, context=context, list_class=self._list_class, fields_process=fields_process)
4549 elif isinstance(select, list):
4550 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)
4552 return browse_null()
4554 def _store_get_values(self, cr, uid, ids, fields, context):
4555 """Returns an ordered list of fields.functions to call due to
4556 an update operation on ``fields`` of records with ``ids``,
4557 obtained by calling the 'store' functions of these fields,
4558 as setup by their 'store' attribute.
4560 :return: [(priority, model_name, [record_ids,], [function_fields,])]
4562 if fields is None: fields = []
4563 stored_functions = self.pool._store_function.get(self._name, [])
4565 # use indexed names for the details of the stored_functions:
4566 model_name_, func_field_to_compute_, id_mapping_fnct_, trigger_fields_, priority_ = range(5)
4568 # only keep functions that should be triggered for the ``fields``
4570 to_compute = [f for f in stored_functions \
4571 if ((not f[trigger_fields_]) or set(fields).intersection(f[trigger_fields_]))]
4574 for function in to_compute:
4575 # use admin user for accessing objects having rules defined on store fields
4576 target_ids = [id for id in function[id_mapping_fnct_](self, cr, SUPERUSER_ID, ids, context) if id]
4578 # the compound key must consider the priority and model name
4579 key = (function[priority_], function[model_name_])
4580 for target_id in target_ids:
4581 mapping.setdefault(key, {}).setdefault(target_id,set()).add(tuple(function))
4583 # Here mapping looks like:
4584 # { (10, 'model_a') : { target_id1: [ (function_1_tuple, function_2_tuple) ], ... }
4585 # (20, 'model_a') : { target_id2: [ (function_3_tuple, function_4_tuple) ], ... }
4586 # (99, 'model_a') : { target_id1: [ (function_5_tuple, function_6_tuple) ], ... }
4589 # Now we need to generate the batch function calls list
4591 # { (10, 'model_a') : [(10, 'model_a', [record_ids,], [function_fields,])] }
4593 for ((priority,model), id_map) in mapping.iteritems():
4594 functions_ids_maps = {}
4595 # function_ids_maps =
4596 # { (function_1_tuple, function_2_tuple) : [target_id1, target_id2, ..] }
4597 for id, functions in id_map.iteritems():
4598 functions_ids_maps.setdefault(tuple(functions), []).append(id)
4599 for functions, ids in functions_ids_maps.iteritems():
4600 call_map.setdefault((priority,model),[]).append((priority, model, ids,
4601 [f[func_field_to_compute_] for f in functions]))
4602 ordered_keys = call_map.keys()
4606 result = reduce(operator.add, (call_map[k] for k in ordered_keys))
4609 def _store_set_values(self, cr, uid, ids, fields, context):
4610 """Calls the fields.function's "implementation function" for all ``fields``, on records with ``ids`` (taking care of
4611 respecting ``multi`` attributes), and stores the resulting values in the database directly."""
4616 if self._log_access:
4617 cr.execute('select id,write_date from '+self._table+' where id IN %s', (tuple(ids),))
4621 field_dict.setdefault(r[0], [])
4622 res_date = time.strptime((r[1])[:19], '%Y-%m-%d %H:%M:%S')
4623 write_date = datetime.datetime.fromtimestamp(time.mktime(res_date))
4624 for i in self.pool._store_function.get(self._name, []):
4626 up_write_date = write_date + datetime.timedelta(hours=i[5])
4627 if datetime.datetime.now() < up_write_date:
4629 field_dict[r[0]].append(i[1])
4635 if self._columns[f]._multi not in keys:
4636 keys.append(self._columns[f]._multi)
4637 todo.setdefault(self._columns[f]._multi, [])
4638 todo[self._columns[f]._multi].append(f)
4642 # use admin user for accessing objects having rules defined on store fields
4643 result = self._columns[val[0]].get(cr, self, ids, val, SUPERUSER_ID, context=context)
4644 for id, value in result.items():
4646 for f in value.keys():
4647 if f in field_dict[id]:
4654 if self._columns[v]._type == 'many2one':
4656 value[v] = value[v][0]
4659 upd0.append('"'+v+'"='+self._columns[v]._symbol_set[0])
4660 upd1.append(self._columns[v]._symbol_set[1](value[v]))
4663 cr.execute('update "' + self._table + '" set ' + \
4664 ','.join(upd0) + ' where id = %s', upd1)
4668 # use admin user for accessing objects having rules defined on store fields
4669 result = self._columns[f].get(cr, self, ids, f, SUPERUSER_ID, context=context)
4670 for r in result.keys():
4672 if r in field_dict.keys():
4673 if f in field_dict[r]:
4675 for id, value in result.items():
4676 if self._columns[f]._type == 'many2one':
4681 cr.execute('update "' + self._table + '" set ' + \
4682 '"'+f+'"='+self._columns[f]._symbol_set[0] + ' where id = %s', (self._columns[f]._symbol_set[1](value), id))
4688 def perm_write(self, cr, user, ids, fields, context=None):
4689 raise NotImplementedError(_('This method does not exist anymore'))
4691 # TODO: ameliorer avec NULL
4692 def _where_calc(self, cr, user, domain, active_test=True, context=None):
4693 """Computes the WHERE clause needed to implement an OpenERP domain.
4694 :param domain: the domain to compute
4696 :param active_test: whether the default filtering of records with ``active``
4697 field set to ``False`` should be applied.
4698 :return: the query expressing the given domain as provided in domain
4699 :rtype: osv.query.Query
4704 # if the object has a field named 'active', filter out all inactive
4705 # records unless they were explicitely asked for
4706 if 'active' in self._all_columns and (active_test and context.get('active_test', True)):
4708 # the item[0] trick below works for domain items and '&'/'|'/'!'
4710 if not any(item[0] == 'active' for item in domain):
4711 domain.insert(0, ('active', '=', 1))
4713 domain = [('active', '=', 1)]
4716 e = expression.expression(cr, user, domain, self, context)
4717 tables = e.get_tables()
4718 where_clause, where_params = e.to_sql()
4719 where_clause = where_clause and [where_clause] or []
4721 where_clause, where_params, tables = [], [], ['"%s"' % self._table]
4723 return Query(tables, where_clause, where_params)
4725 def _check_qorder(self, word):
4726 if not regex_order.match(word):
4727 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)'))
4730 def _apply_ir_rules(self, cr, uid, query, mode='read', context=None):
4731 """Add what's missing in ``query`` to implement all appropriate ir.rules
4732 (using the ``model_name``'s rules or the current model's rules if ``model_name`` is None)
4734 :param query: the current query object
4736 def apply_rule(added_clause, added_params, added_tables, parent_model=None, child_object=None):
4738 if parent_model and child_object:
4739 # as inherited rules are being applied, we need to add the missing JOIN
4740 # to reach the parent table (if it was not JOINed yet in the query)
4741 child_object._inherits_join_add(child_object, parent_model, query)
4742 query.where_clause += added_clause
4743 query.where_clause_params += added_params
4744 for table in added_tables:
4745 if table not in query.tables:
4746 query.tables.append(table)
4750 # apply main rules on the object
4751 rule_obj = self.pool.get('ir.rule')
4752 apply_rule(*rule_obj.domain_get(cr, uid, self._name, mode, context=context))
4754 # apply ir.rules from the parents (through _inherits)
4755 for inherited_model in self._inherits:
4756 kwargs = dict(parent_model=inherited_model, child_object=self) #workaround for python2.5
4757 apply_rule(*rule_obj.domain_get(cr, uid, inherited_model, mode, context=context), **kwargs)
4759 def _generate_m2o_order_by(self, order_field, query):
4761 Add possibly missing JOIN to ``query`` and generate the ORDER BY clause for m2o fields,
4762 either native m2o fields or function/related fields that are stored, including
4763 intermediate JOINs for inheritance if required.
4765 :return: the qualified field name to use in an ORDER BY clause to sort by ``order_field``
4767 if order_field not in self._columns and order_field in self._inherit_fields:
4768 # also add missing joins for reaching the table containing the m2o field
4769 qualified_field = self._inherits_join_calc(order_field, query)
4770 order_field_column = self._inherit_fields[order_field][2]
4772 qualified_field = '"%s"."%s"' % (self._table, order_field)
4773 order_field_column = self._columns[order_field]
4775 assert order_field_column._type == 'many2one', 'Invalid field passed to _generate_m2o_order_by()'
4776 if not order_field_column._classic_write and not getattr(order_field_column, 'store', False):
4777 _logger.debug("Many2one function/related fields must be stored " \
4778 "to be used as ordering fields! Ignoring sorting for %s.%s",
4779 self._name, order_field)
4782 # figure out the applicable order_by for the m2o
4783 dest_model = self.pool.get(order_field_column._obj)
4784 m2o_order = dest_model._order
4785 if not regex_order.match(m2o_order):
4786 # _order is complex, can't use it here, so we default to _rec_name
4787 m2o_order = dest_model._rec_name
4789 # extract the field names, to be able to qualify them and add desc/asc
4791 for order_part in m2o_order.split(","):
4792 m2o_order_list.append(order_part.strip().split(" ",1)[0].strip())
4793 m2o_order = m2o_order_list
4795 # Join the dest m2o table if it's not joined yet. We use [LEFT] OUTER join here
4796 # as we don't want to exclude results that have NULL values for the m2o
4797 src_table, src_field = qualified_field.replace('"','').split('.', 1)
4798 query.join((src_table, dest_model._table, src_field, 'id'), outer=True)
4799 qualify = lambda field: '"%s"."%s"' % (dest_model._table, field)
4800 return map(qualify, m2o_order) if isinstance(m2o_order, list) else qualify(m2o_order)
4803 def _generate_order_by(self, order_spec, query):
4805 Attempt to consruct an appropriate ORDER BY clause based on order_spec, which must be
4806 a comma-separated list of valid field names, optionally followed by an ASC or DESC direction.
4808 :raise" except_orm in case order_spec is malformed
4810 order_by_clause = self._order
4812 order_by_elements = []
4813 self._check_qorder(order_spec)
4814 for order_part in order_spec.split(','):
4815 order_split = order_part.strip().split(' ')
4816 order_field = order_split[0].strip()
4817 order_direction = order_split[1].strip() if len(order_split) == 2 else ''
4819 if order_field == 'id':
4820 order_by_clause = '"%s"."%s"' % (self._table, order_field)
4821 elif order_field in self._columns:
4822 order_column = self._columns[order_field]
4823 if order_column._classic_read:
4824 inner_clause = '"%s"."%s"' % (self._table, order_field)
4825 elif order_column._type == 'many2one':
4826 inner_clause = self._generate_m2o_order_by(order_field, query)
4828 continue # ignore non-readable or "non-joinable" fields
4829 elif order_field in self._inherit_fields:
4830 parent_obj = self.pool.get(self._inherit_fields[order_field][3])
4831 order_column = parent_obj._columns[order_field]
4832 if order_column._classic_read:
4833 inner_clause = self._inherits_join_calc(order_field, query)
4834 elif order_column._type == 'many2one':
4835 inner_clause = self._generate_m2o_order_by(order_field, query)
4837 continue # ignore non-readable or "non-joinable" fields
4839 if isinstance(inner_clause, list):
4840 for clause in inner_clause:
4841 order_by_elements.append("%s %s" % (clause, order_direction))
4843 order_by_elements.append("%s %s" % (inner_clause, order_direction))
4844 if order_by_elements:
4845 order_by_clause = ",".join(order_by_elements)
4847 return order_by_clause and (' ORDER BY %s ' % order_by_clause) or ''
4849 def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
4851 Private implementation of search() method, allowing specifying the uid to use for the access right check.
4852 This is useful for example when filling in the selection list for a drop-down and avoiding access rights errors,
4853 by specifying ``access_rights_uid=1`` to bypass access rights check, but not ir.rules!
4854 This is ok at the security level because this method is private and not callable through XML-RPC.
4856 :param access_rights_uid: optional user ID to use when checking access rights
4857 (not for ir.rules, this is only for ir.model.access)
4861 self.check_access_rights(cr, access_rights_uid or user, 'read')
4863 # For transient models, restrict acces to the current user, except for the super-user
4864 if self.is_transient() and self._log_access and user != SUPERUSER_ID:
4865 args = expression.AND(([('create_uid', '=', user)], args or []))
4867 query = self._where_calc(cr, user, args, context=context)
4868 self._apply_ir_rules(cr, user, query, 'read', context=context)
4869 order_by = self._generate_order_by(order, query)
4870 from_clause, where_clause, where_clause_params = query.get_sql()
4872 limit_str = limit and ' limit %d' % limit or ''
4873 offset_str = offset and ' offset %d' % offset or ''
4874 where_str = where_clause and (" WHERE %s" % where_clause) or ''
4877 cr.execute('SELECT count("%s".id) FROM ' % self._table + from_clause + where_str + limit_str + offset_str, where_clause_params)
4880 cr.execute('SELECT "%s".id FROM ' % self._table + from_clause + where_str + order_by + limit_str + offset_str, where_clause_params)
4882 return [x[0] for x in res]
4884 # returns the different values ever entered for one field
4885 # this is used, for example, in the client when the user hits enter on
4887 def distinct_field_get(self, cr, uid, field, value, args=None, offset=0, limit=None):
4890 if field in self._inherit_fields:
4891 return self.pool.get(self._inherit_fields[field][0]).distinct_field_get(cr, uid, field, value, args, offset, limit)
4893 return self._columns[field].search(cr, self, args, field, value, offset, limit, uid)
4895 def copy_data(self, cr, uid, id, default=None, context=None):
4897 Copy given record's data with all its fields values
4899 :param cr: database cursor
4900 :param user: current user id
4901 :param id: id of the record to copy
4902 :param default: field values to override in the original values of the copied record
4903 :type default: dictionary
4904 :param context: context arguments, like lang, time zone
4905 :type context: dictionary
4906 :return: dictionary containing all the field values
4912 # avoid recursion through already copied records in case of circular relationship
4913 seen_map = context.setdefault('__copy_data_seen',{})
4914 if id in seen_map.setdefault(self._name,[]):
4916 seen_map[self._name].append(id)
4920 if 'state' not in default:
4921 if 'state' in self._defaults:
4922 if callable(self._defaults['state']):
4923 default['state'] = self._defaults['state'](self, cr, uid, context)
4925 default['state'] = self._defaults['state']
4927 context_wo_lang = context.copy()
4928 if 'lang' in context:
4929 del context_wo_lang['lang']
4930 data = self.read(cr, uid, [id,], context=context_wo_lang)
4934 raise IndexError( _("Record #%d of %s not found, cannot copy!") %( id, self._name))
4936 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
4937 fields = self.fields_get(cr, uid, context=context)
4939 ftype = fields[f]['type']
4941 if self._log_access and f in LOG_ACCESS_COLUMNS:
4945 data[f] = default[f]
4946 elif 'function' in fields[f]:
4948 elif ftype == 'many2one':
4950 data[f] = data[f] and data[f][0]
4953 elif ftype == 'one2many':
4955 rel = self.pool.get(fields[f]['relation'])
4957 # duplicate following the order of the ids
4958 # because we'll rely on it later for copying
4959 # translations in copy_translation()!
4961 for rel_id in data[f]:
4962 # the lines are first duplicated using the wrong (old)
4963 # parent but then are reassigned to the correct one thanks
4964 # to the (0, 0, ...)
4965 d = rel.copy_data(cr, uid, rel_id, context=context)
4967 res.append((0, 0, d))
4969 elif ftype == 'many2many':
4970 data[f] = [(6, 0, data[f])]
4974 # make sure we don't break the current parent_store structure and
4975 # force a clean recompute!
4976 for parent_column in ['parent_left', 'parent_right']:
4977 data.pop(parent_column, None)
4978 # Remove _inherits field's from data recursively, missing parents will
4979 # be created by create() (so that copy() copy everything).
4980 def remove_ids(inherits_dict):
4981 for parent_table in inherits_dict:
4982 del data[inherits_dict[parent_table]]
4983 remove_ids(self.pool.get(parent_table)._inherits)
4984 remove_ids(self._inherits)
4987 def copy_translations(self, cr, uid, old_id, new_id, context=None):
4991 # avoid recursion through already copied records in case of circular relationship
4992 seen_map = context.setdefault('__copy_translations_seen',{})
4993 if old_id in seen_map.setdefault(self._name,[]):
4995 seen_map[self._name].append(old_id)
4997 trans_obj = self.pool.get('ir.translation')
4998 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
4999 fields = self.fields_get(cr, uid, context=context)
5001 translation_records = []
5002 for field_name, field_def in fields.items():
5003 # we must recursively copy the translations for o2o and o2m
5004 if field_def['type'] == 'one2many':
5005 target_obj = self.pool.get(field_def['relation'])
5006 old_record, new_record = self.read(cr, uid, [old_id, new_id], [field_name], context=context)
5007 # here we rely on the order of the ids to match the translations
5008 # as foreseen in copy_data()
5009 old_children = sorted(old_record[field_name])
5010 new_children = sorted(new_record[field_name])
5011 for (old_child, new_child) in zip(old_children, new_children):
5012 target_obj.copy_translations(cr, uid, old_child, new_child, context=context)
5013 # and for translatable fields we keep them for copy
5014 elif field_def.get('translate'):
5016 if field_name in self._columns:
5017 trans_name = self._name + "," + field_name
5018 elif field_name in self._inherit_fields:
5019 trans_name = self._inherit_fields[field_name][0] + "," + field_name
5021 trans_ids = trans_obj.search(cr, uid, [
5022 ('name', '=', trans_name),
5023 ('res_id', '=', old_id)
5025 translation_records.extend(trans_obj.read(cr, uid, trans_ids, context=context))
5027 for record in translation_records:
5029 record['res_id'] = new_id
5030 trans_obj.create(cr, uid, record, context=context)
5033 def copy(self, cr, uid, id, default=None, context=None):
5035 Duplicate record with given id updating it with default values
5037 :param cr: database cursor
5038 :param uid: current user id
5039 :param id: id of the record to copy
5040 :param default: dictionary of field values to override in the original values of the copied record, e.g: ``{'field_name': overriden_value, ...}``
5041 :type default: dictionary
5042 :param context: context arguments, like lang, time zone
5043 :type context: dictionary
5044 :return: id of the newly created record
5049 context = context.copy()
5050 data = self.copy_data(cr, uid, id, default, context)
5051 new_id = self.create(cr, uid, data, context)
5052 self.copy_translations(cr, uid, id, new_id, context)
5055 def exists(self, cr, uid, ids, context=None):
5056 """Checks whether the given id or ids exist in this model,
5057 and return the list of ids that do. This is simple to use for
5058 a truth test on a browse_record::
5063 :param ids: id or list of ids to check for existence
5064 :type ids: int or [int]
5065 :return: the list of ids that currently exist, out of
5068 if type(ids) in (int, long):
5070 query = 'SELECT id FROM "%s"' % (self._table)
5071 cr.execute(query + "WHERE ID IN %s", (tuple(ids),))
5072 return [x[0] for x in cr.fetchall()]
5074 def check_recursion(self, cr, uid, ids, context=None, parent=None):
5075 _logger.warning("You are using deprecated %s.check_recursion(). Please use the '_check_recursion()' instead!" % \
5077 assert parent is None or parent in self._columns or parent in self._inherit_fields,\
5078 "The 'parent' parameter passed to check_recursion() must be None or a valid field name"
5079 return self._check_recursion(cr, uid, ids, context, parent)
5081 def _check_recursion(self, cr, uid, ids, context=None, parent=None):
5083 Verifies that there is no loop in a hierarchical structure of records,
5084 by following the parent relationship using the **parent** field until a loop
5085 is detected or until a top-level record is found.
5087 :param cr: database cursor
5088 :param uid: current user id
5089 :param ids: list of ids of records to check
5090 :param parent: optional parent field name (default: ``self._parent_name = parent_id``)
5091 :return: **True** if the operation can proceed safely, or **False** if an infinite loop is detected.
5095 parent = self._parent_name
5097 query = 'SELECT distinct "%s" FROM "%s" WHERE id IN %%s' % (parent, self._table)
5100 for i in range(0, len(ids), cr.IN_MAX):
5101 sub_ids_parent = ids_parent[i:i+cr.IN_MAX]
5102 cr.execute(query, (tuple(sub_ids_parent),))
5103 ids_parent2.extend(filter(None, map(lambda x: x[0], cr.fetchall())))
5104 ids_parent = ids_parent2
5105 for i in ids_parent:
5110 def _get_external_ids(self, cr, uid, ids, *args, **kwargs):
5111 """Retrieve the External ID(s) of any database record.
5113 **Synopsis**: ``_get_xml_ids(cr, uid, ids) -> { 'id': ['module.xml_id'] }``
5115 :return: map of ids to the list of their fully qualified External IDs
5116 in the form ``module.key``, or an empty list when there's no External
5117 ID for a record, e.g.::
5119 { 'id': ['module.ext_id', 'module.ext_id_bis'],
5122 ir_model_data = self.pool.get('ir.model.data')
5123 data_ids = ir_model_data.search(cr, uid, [('model', '=', self._name), ('res_id', 'in', ids)])
5124 data_results = ir_model_data.read(cr, uid, data_ids, ['module', 'name', 'res_id'])
5127 # can't use dict.fromkeys() as the list would be shared!
5129 for record in data_results:
5130 result[record['res_id']].append('%(module)s.%(name)s' % record)
5133 def get_external_id(self, cr, uid, ids, *args, **kwargs):
5134 """Retrieve the External ID of any database record, if there
5135 is one. This method works as a possible implementation
5136 for a function field, to be able to add it to any
5137 model object easily, referencing it as ``Model.get_external_id``.
5139 When multiple External IDs exist for a record, only one
5140 of them is returned (randomly).
5142 :return: map of ids to their fully qualified XML ID,
5143 defaulting to an empty string when there's none
5144 (to be usable as a function field),
5147 { 'id': 'module.ext_id',
5150 results = self._get_xml_ids(cr, uid, ids)
5151 for k, v in results.iteritems():
5158 # backwards compatibility
5159 get_xml_id = get_external_id
5160 _get_xml_ids = _get_external_ids
5163 def is_transient(self):
5164 """ Return whether the model is transient.
5169 return self._transient
5171 def _transient_clean_rows_older_than(self, cr, seconds):
5172 assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
5173 cr.execute("SELECT id FROM " + self._table + " WHERE"
5174 " COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp <"
5175 " ((now() at time zone 'UTC') - interval %s)", ("%s seconds" % seconds,))
5176 ids = [x[0] for x in cr.fetchall()]
5177 self.unlink(cr, SUPERUSER_ID, ids)
5179 def _transient_clean_old_rows(self, cr, count):
5180 assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
5182 "SELECT id, COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp"
5183 " AS t FROM " + self._table +
5184 " ORDER BY t LIMIT %s", (count,))
5185 ids = [x[0] for x in cr.fetchall()]
5186 self.unlink(cr, SUPERUSER_ID, ids)
5188 def _transient_vacuum(self, cr, uid, force=False):
5189 """Clean the transient records.
5191 This unlinks old records from the transient model tables whenever the
5192 "_transient_max_count" or "_max_age" conditions (if any) are reached.
5193 Actual cleaning will happen only once every "_transient_check_time" calls.
5194 This means this method can be called frequently called (e.g. whenever
5195 a new record is created).
5197 assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
5198 self._transient_check_count += 1
5199 if (not force) and (self._transient_check_count % self._transient_check_time):
5200 self._transient_check_count = 0
5203 # Age-based expiration
5204 if self._transient_max_hours:
5205 self._transient_clean_rows_older_than(cr, self._transient_max_hours * 60 * 60)
5207 # Count-based expiration
5208 if self._transient_max_count:
5209 self._transient_clean_old_rows(cr, self._transient_max_count)
5213 def resolve_2many_commands(self, cr, uid, field_name, commands, fields=None, context=None):
5214 """ Serializes one2many and many2many commands into record dictionaries
5215 (as if all the records came from the database via a read()). This
5216 method is aimed at onchange methods on one2many and many2many fields.
5218 Because commands might be creation commands, not all record dicts
5219 will contain an ``id`` field. Commands matching an existing record
5220 will have an ``id``.
5222 :param field_name: name of the one2many or many2many field matching the commands
5223 :type field_name: str
5224 :param commands: one2many or many2many commands to execute on ``field_name``
5225 :type commands: list((int|False, int|False, dict|False))
5226 :param fields: list of fields to read from the database, when applicable
5227 :type fields: list(str)
5228 :returns: records in a shape similar to that returned by ``read()``
5229 (except records may be missing the ``id`` field if they don't exist in db)
5232 result = [] # result (list of dict)
5233 record_ids = [] # ids of records to read
5234 updates = {} # {id: dict} of updates on particular records
5236 for command in commands:
5237 if not isinstance(command, (list, tuple)):
5238 record_ids.append(command)
5239 elif command[0] == 0:
5240 result.append(command[2])
5241 elif command[0] == 1:
5242 record_ids.append(command[1])
5243 updates.setdefault(command[1], {}).update(command[2])
5244 elif command[0] in (2, 3):
5245 record_ids = [id for id in record_ids if id != command[1]]
5246 elif command[0] == 4:
5247 record_ids.append(command[1])
5248 elif command[0] == 5:
5249 result, record_ids = [], []
5250 elif command[0] == 6:
5251 result, record_ids = [], list(command[2])
5253 # read the records and apply the updates
5254 other_model = self.pool.get(self._all_columns[field_name].column._obj)
5255 for record in other_model.read(cr, uid, record_ids, fields=fields, context=context):
5256 record.update(updates.get(record['id'], {}))
5257 result.append(record)
5261 # for backward compatibility
5262 resolve_o2m_commands_to_record_dicts = resolve_2many_commands
5264 # keep this import here, at top it will cause dependency cycle errors
5267 class Model(BaseModel):
5268 """Main super-class for regular database-persisted OpenERP models.
5270 OpenERP models are created by inheriting from this class::
5275 The system will later instantiate the class once per database (on
5276 which the class' module is installed).
5279 _register = False # not visible in ORM registry, meant to be python-inherited only
5280 _transient = False # True in a TransientModel
5282 class TransientModel(BaseModel):
5283 """Model super-class for transient records, meant to be temporarily
5284 persisted, and regularly vaccuum-cleaned.
5286 A TransientModel has a simplified access rights management,
5287 all users can create new records, and may only access the
5288 records they created. The super-user has unrestricted access
5289 to all TransientModel records.
5292 _register = False # not visible in ORM registry, meant to be python-inherited only
5295 class AbstractModel(BaseModel):
5296 """Abstract Model super-class for creating an abstract class meant to be
5297 inherited by regular models (Models or TransientModels) but not meant to
5298 be usable on its own, or persisted.
5300 Technical note: we don't want to make AbstractModel the super-class of
5301 Model or BaseModel because it would not make sense to put the main
5302 definition of persistence methods such as create() in it, and still we
5303 should be able to override them within an AbstractModel.
5305 _auto = False # don't create any database backend for AbstractModels
5306 _register = False # not visible in ORM registry, meant to be python-inherited only
5308 def span(predicate, iterable):
5309 """ Splits the iterable between the longest prefix of ``iterable`` whose
5310 elements satisfy ``predicate`` and the rest.
5312 If called with a list, equivalent to::
5314 takewhile(predicate, lst), dropwhile(predicate, lst)
5316 :param callable predicate:
5318 :rtype: (iterable, iterable)
5320 it1, it2 = itertools.tee(iterable)
5321 return (itertools.takewhile(predicate, it1),
5322 itertools.dropwhile(predicate, it2))
5323 def itemgetter_tuple(items):
5324 """ Fixes itemgetter inconsistency (useful in some cases) of not returning
5325 a tuple if len(items) == 1: always returns an n-tuple where n = len(items)
5330 return lambda gettable: (gettable[items[0]],)
5331 return operator.itemgetter(*items)
5332 class ImportWarning(Warning):
5333 """ Used to send warnings upwards the stack during the import process
5336 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: