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)
55 from lxml import etree
59 import openerp.netsvc as netsvc
60 import openerp.tools as tools
61 from openerp.tools.config import config
62 from openerp.tools.safe_eval import safe_eval as eval
63 from openerp.tools.translate import _
64 from openerp import SUPERUSER_ID
65 from query import Query
67 _logger = logging.getLogger(__name__)
68 _schema = logging.getLogger(__name__ + '.schema')
70 # List of etree._Element subclasses that we choose to ignore when parsing XML.
71 from openerp.tools import SKIPPED_ELEMENT_TYPES
73 regex_order = re.compile('^(([a-z0-9_]+|"[a-z0-9_]+")( *desc| *asc)?( *, *|))+$', re.I)
74 regex_object_name = re.compile(r'^[a-z0-9_.]+$')
76 def transfer_field_to_modifiers(field, modifiers):
79 for attr in ('invisible', 'readonly', 'required'):
80 state_exceptions[attr] = []
81 default_values[attr] = bool(field.get(attr))
82 for state, modifs in (field.get("states",{})).items():
84 if default_values[modif[0]] != modif[1]:
85 state_exceptions[modif[0]].append(state)
87 for attr, default_value in default_values.items():
88 if state_exceptions[attr]:
89 modifiers[attr] = [("state", "not in" if default_value else "in", state_exceptions[attr])]
91 modifiers[attr] = default_value
94 # Don't deal with groups, it is done by check_group().
95 # Need the context to evaluate the invisible attribute on tree views.
96 # For non-tree views, the context shouldn't be given.
97 def transfer_node_to_modifiers(node, modifiers, context=None, in_tree_view=False):
99 modifiers.update(eval(node.get('attrs')))
101 if node.get('states'):
102 if 'invisible' in modifiers and isinstance(modifiers['invisible'], list):
103 # TODO combine with AND or OR, use implicit AND for now.
104 modifiers['invisible'].append(('state', 'not in', node.get('states').split(',')))
106 modifiers['invisible'] = [('state', 'not in', node.get('states').split(','))]
108 for a in ('invisible', 'readonly', 'required'):
110 v = bool(eval(node.get(a), {'context': context or {}}))
111 if in_tree_view and a == 'invisible':
112 # Invisible in a tree view has a specific meaning, make it a
113 # new key in the modifiers attribute.
114 modifiers['tree_invisible'] = v
115 elif v or (a not in modifiers or not isinstance(modifiers[a], list)):
116 # Don't set the attribute to False if a dynamic value was
117 # provided (i.e. a domain from attrs or states).
121 def simplify_modifiers(modifiers):
122 for a in ('invisible', 'readonly', 'required'):
123 if a in modifiers and not modifiers[a]:
127 def transfer_modifiers_to_node(modifiers, node):
129 simplify_modifiers(modifiers)
130 node.set('modifiers', simplejson.dumps(modifiers))
132 def setup_modifiers(node, field=None, context=None, in_tree_view=False):
133 """ Processes node attributes and field descriptors to generate
134 the ``modifiers`` node attribute and set it on the provided node.
136 Alters its first argument in-place.
138 :param node: ``field`` node from an OpenERP view
139 :type node: lxml.etree._Element
140 :param dict field: field descriptor corresponding to the provided node
141 :param dict context: execution context used to evaluate node attributes
142 :param bool in_tree_view: triggers the ``tree_invisible`` code
143 path (separate from ``invisible``): in
144 tree view there are two levels of
145 invisibility, cell content (a column is
146 present but the cell itself is not
147 displayed) with ``invisible`` and column
148 invisibility (the whole column is
149 hidden) with ``tree_invisible``.
153 if field is not None:
154 transfer_field_to_modifiers(field, modifiers)
155 transfer_node_to_modifiers(
156 node, modifiers, context=context, in_tree_view=in_tree_view)
157 transfer_modifiers_to_node(modifiers, node)
159 def test_modifiers(what, expected):
161 if isinstance(what, basestring):
162 node = etree.fromstring(what)
163 transfer_node_to_modifiers(node, modifiers)
164 simplify_modifiers(modifiers)
165 json = simplejson.dumps(modifiers)
166 assert json == expected, "%s != %s" % (json, expected)
167 elif isinstance(what, dict):
168 transfer_field_to_modifiers(what, modifiers)
169 simplify_modifiers(modifiers)
170 json = simplejson.dumps(modifiers)
171 assert json == expected, "%s != %s" % (json, expected)
176 # openerp.osv.orm.modifiers_tests()
177 def modifiers_tests():
178 test_modifiers('<field name="a"/>', '{}')
179 test_modifiers('<field name="a" invisible="1"/>', '{"invisible": true}')
180 test_modifiers('<field name="a" readonly="1"/>', '{"readonly": true}')
181 test_modifiers('<field name="a" required="1"/>', '{"required": true}')
182 test_modifiers('<field name="a" invisible="0"/>', '{}')
183 test_modifiers('<field name="a" readonly="0"/>', '{}')
184 test_modifiers('<field name="a" required="0"/>', '{}')
185 test_modifiers('<field name="a" invisible="1" required="1"/>', '{"invisible": true, "required": true}') # TODO order is not guaranteed
186 test_modifiers('<field name="a" invisible="1" required="0"/>', '{"invisible": true}')
187 test_modifiers('<field name="a" invisible="0" required="1"/>', '{"required": true}')
188 test_modifiers("""<field name="a" attrs="{'invisible': [('b', '=', 'c')]}"/>""", '{"invisible": [["b", "=", "c"]]}')
190 # The dictionary is supposed to be the result of fields_get().
191 test_modifiers({}, '{}')
192 test_modifiers({"invisible": True}, '{"invisible": true}')
193 test_modifiers({"invisible": False}, '{}')
196 def check_object_name(name):
197 """ Check if the given name is a valid openerp object name.
199 The _name attribute in osv and osv_memory object is subject to
200 some restrictions. This function returns True or False whether
201 the given name is allowed or not.
203 TODO: this is an approximation. The goal in this approximation
204 is to disallow uppercase characters (in some places, we quote
205 table/column names and in other not, which leads to this kind
208 psycopg2.ProgrammingError: relation "xxx" does not exist).
210 The same restriction should apply to both osv and osv_memory
211 objects for consistency.
214 if regex_object_name.match(name) is None:
218 def raise_on_invalid_object_name(name):
219 if not check_object_name(name):
220 msg = "The _name attribute %s is not valid." % name
222 raise except_orm('ValueError', msg)
224 POSTGRES_CONFDELTYPES = {
232 def intersect(la, lb):
233 return filter(lambda x: x in lb, la)
235 def fix_import_export_id_paths(fieldname):
237 Fixes the id fields in import and exports, and splits field paths
240 :param str fieldname: name of the field to import/export
241 :return: split field name
244 fixed_db_id = re.sub(r'([^/])\.id', r'\1/.id', fieldname)
245 fixed_external_id = re.sub(r'([^/]):id', r'\1/id', fixed_db_id)
246 return fixed_external_id.split('/')
248 class except_orm(Exception):
249 def __init__(self, name, value):
252 self.args = (name, value)
254 class BrowseRecordError(Exception):
257 class browse_null(object):
258 """ Readonly python database object browser
264 def __getitem__(self, name):
267 def __getattr__(self, name):
268 return None # XXX: return self ?
276 def __nonzero__(self):
279 def __unicode__(self):
284 # TODO: execute an object method on browse_record_list
286 class browse_record_list(list):
287 """ Collection of browse objects
289 Such an instance will be returned when doing a ``browse([ids..])``
290 and will be iterable, yielding browse() objects
293 def __init__(self, lst, context=None):
296 super(browse_record_list, self).__init__(lst)
297 self.context = context
300 class browse_record(object):
301 """ An object that behaves like a row of an object's table.
302 It has attributes after the columns of the corresponding object.
306 uobj = pool.get('res.users')
307 user_rec = uobj.browse(cr, uid, 104)
311 def __init__(self, cr, uid, id, table, cache, context=None,
312 list_class=browse_record_list, fields_process=None):
314 :param table: the browsed object (inherited from orm)
315 :param dict cache: a dictionary of model->field->data to be shared
316 across browse objects, thus reducing the SQL
317 read()s. It can speed up things a lot, but also be
318 disastrous if not discarded after write()/unlink()
320 :param dict context: dictionary with an optional context
322 if fields_process is None:
326 self._list_class = list_class
330 self._table = table # deprecated, use _model!
332 self._table_name = self._table._name
333 self.__logger = logging.getLogger('openerp.osv.orm.browse_record.' + self._table_name)
334 self._context = context
335 self._fields_process = fields_process
337 cache.setdefault(table._name, {})
338 self._data = cache[table._name]
340 # if not (id and isinstance(id, (int, long,))):
341 # raise BrowseRecordError(_('Wrong ID for the browse record, got %r, expected an integer.') % (id,))
342 # if not table.exists(cr, uid, id, context):
343 # raise BrowseRecordError(_('Object %s does not exists') % (self,))
345 if id not in self._data:
346 self._data[id] = {'id': id}
350 def __getitem__(self, name):
354 if name not in self._data[self._id]:
355 # build the list of fields we will fetch
357 # fetch the definition of the field which was asked for
358 if name in self._table._columns:
359 col = self._table._columns[name]
360 elif name in self._table._inherit_fields:
361 col = self._table._inherit_fields[name][2]
362 elif hasattr(self._table, str(name)):
363 attr = getattr(self._table, name)
364 if isinstance(attr, (types.MethodType, types.LambdaType, types.FunctionType)):
365 def function_proxy(*args, **kwargs):
366 if 'context' not in kwargs and self._context:
367 kwargs.update(context=self._context)
368 return attr(self._cr, self._uid, [self._id], *args, **kwargs)
369 return function_proxy
373 error_msg = "Field '%s' does not exist in object '%s'" % (name, self)
374 self.__logger.warning(error_msg)
375 raise KeyError(error_msg)
377 # if the field is a classic one or a many2one, we'll fetch all classic and many2one fields
379 # gen the list of "local" (ie not inherited) fields which are classic or many2one
380 fields_to_fetch = filter(lambda x: x[1]._classic_write, self._table._columns.items())
381 # gen the list of inherited fields
382 inherits = map(lambda x: (x[0], x[1][2]), self._table._inherit_fields.items())
383 # complete the field list with the inherited fields which are classic or many2one
384 fields_to_fetch += filter(lambda x: x[1]._classic_write, inherits)
385 # otherwise we fetch only that field
387 fields_to_fetch = [(name, col)]
388 ids = filter(lambda id: name not in self._data[id], self._data.keys())
390 field_names = map(lambda x: x[0], fields_to_fetch)
391 field_values = self._table.read(self._cr, self._uid, ids, field_names, context=self._context, load="_classic_write")
393 # TODO: improve this, very slow for reports
394 if self._fields_process:
395 lang = self._context.get('lang', 'en_US') or 'en_US'
396 lang_obj_ids = self.pool.get('res.lang').search(self._cr, self._uid, [('code', '=', lang)])
398 raise Exception(_('Language with code "%s" is not defined in your system !\nDefine it through the Administration menu.') % (lang,))
399 lang_obj = self.pool.get('res.lang').browse(self._cr, self._uid, lang_obj_ids[0])
401 for field_name, field_column in fields_to_fetch:
402 if field_column._type in self._fields_process:
403 for result_line in field_values:
404 result_line[field_name] = self._fields_process[field_column._type](result_line[field_name])
405 if result_line[field_name]:
406 result_line[field_name].set_value(self._cr, self._uid, result_line[field_name], self, field_column, lang_obj)
409 # Where did those ids come from? Perhaps old entries in ir_model_dat?
410 _logger.warning("No field_values found for ids %s in %s", ids, self)
411 raise KeyError('Field %s not found in %s'%(name, self))
412 # create browse records for 'remote' objects
413 for result_line in field_values:
415 for field_name, field_column in fields_to_fetch:
416 if field_column._type in ('many2one', 'one2one'):
417 if result_line[field_name]:
418 obj = self._table.pool.get(field_column._obj)
419 if isinstance(result_line[field_name], (list, tuple)):
420 value = result_line[field_name][0]
422 value = result_line[field_name]
424 # FIXME: this happen when a _inherits object
425 # overwrite a field of it parent. Need
426 # testing to be sure we got the right
427 # object and not the parent one.
428 if not isinstance(value, browse_record):
430 # In some cases the target model is not available yet, so we must ignore it,
431 # which is safe in most cases, this value will just be loaded later when needed.
432 # This situation can be caused by custom fields that connect objects with m2o without
433 # respecting module dependencies, causing relationships to be connected to soon when
434 # the target is not loaded yet.
436 new_data[field_name] = browse_record(self._cr,
437 self._uid, value, obj, self._cache,
438 context=self._context,
439 list_class=self._list_class,
440 fields_process=self._fields_process)
442 new_data[field_name] = value
444 new_data[field_name] = browse_null()
446 new_data[field_name] = browse_null()
447 elif field_column._type in ('one2many', 'many2many') and len(result_line[field_name]):
448 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)
449 elif field_column._type in ('reference'):
450 if result_line[field_name]:
451 if isinstance(result_line[field_name], browse_record):
452 new_data[field_name] = result_line[field_name]
454 ref_obj, ref_id = result_line[field_name].split(',')
455 ref_id = long(ref_id)
457 obj = self._table.pool.get(ref_obj)
458 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)
460 new_data[field_name] = browse_null()
462 new_data[field_name] = browse_null()
464 new_data[field_name] = result_line[field_name]
465 self._data[result_line['id']].update(new_data)
467 if not name in self._data[self._id]:
468 # How did this happen? Could be a missing model due to custom fields used too soon, see above.
469 self.__logger.error("Fields to fetch: %s, Field values: %s", field_names, field_values)
470 self.__logger.error("Cached: %s, Table: %s", self._data[self._id], self._table)
471 raise KeyError(_('Unknown attribute %s in %s ') % (name, self))
472 return self._data[self._id][name]
474 def __getattr__(self, name):
478 raise AttributeError(e)
480 def __contains__(self, name):
481 return (name in self._table._columns) or (name in self._table._inherit_fields) or hasattr(self._table, name)
484 raise NotImplementedError("Iteration is not allowed on %s" % self)
486 def __hasattr__(self, name):
493 return "browse_record(%s, %d)" % (self._table_name, self._id)
495 def __eq__(self, other):
496 if not isinstance(other, browse_record):
498 return (self._table_name, self._id) == (other._table_name, other._id)
500 def __ne__(self, other):
501 if not isinstance(other, browse_record):
503 return (self._table_name, self._id) != (other._table_name, other._id)
505 # we need to define __unicode__ even though we've already defined __str__
506 # because we have overridden __getattr__
507 def __unicode__(self):
508 return unicode(str(self))
511 return hash((self._table_name, self._id))
516 """Force refreshing this browse_record's data and all the data of the
517 records that belong to the same cache, by emptying the cache completely,
518 preserving only the record identifiers (for prefetching optimizations).
520 for model, model_cache in self._cache.iteritems():
521 # only preserve the ids of the records that were in the cache
522 cached_ids = dict([(i, {'id': i}) for i in model_cache.keys()])
523 self._cache[model].clear()
524 self._cache[model].update(cached_ids)
526 def pg_varchar(size=0):
527 """ Returns the VARCHAR declaration for the provided size:
529 * If no size (or an empty or negative size is provided) return an
531 * Otherwise return a VARCHAR(n)
533 :type int size: varchar size, optional
537 if not isinstance(size, int):
538 raise TypeError("VARCHAR parameter should be an int, got %s"
541 return 'VARCHAR(%d)' % size
544 FIELDS_TO_PGTYPES = {
545 fields.boolean: 'bool',
546 fields.integer: 'int4',
547 fields.integer_big: 'int8',
551 fields.datetime: 'timestamp',
552 fields.binary: 'bytea',
553 fields.many2one: 'int4',
554 fields.serialized: 'text',
557 def get_pg_type(f, type_override=None):
559 :param fields._column f: field to get a Postgres type for
560 :param type type_override: use the provided type for dispatching instead of the field's own type
561 :returns: (postgres_identification_type, postgres_type_specification)
564 field_type = type_override or type(f)
566 if field_type in FIELDS_TO_PGTYPES:
567 pg_type = (FIELDS_TO_PGTYPES[field_type], FIELDS_TO_PGTYPES[field_type])
568 elif issubclass(field_type, fields.float):
570 pg_type = ('numeric', 'NUMERIC')
572 pg_type = ('float8', 'DOUBLE PRECISION')
573 elif issubclass(field_type, (fields.char, fields.reference)):
574 pg_type = ('varchar', pg_varchar(f.size))
575 elif issubclass(field_type, fields.selection):
576 if (isinstance(f.selection, list) and isinstance(f.selection[0][0], int))\
577 or getattr(f, 'size', None) == -1:
578 pg_type = ('int4', 'INTEGER')
580 pg_type = ('varchar', pg_varchar(getattr(f, 'size', None)))
581 elif issubclass(field_type, fields.function):
582 if f._type == 'selection':
583 pg_type = ('varchar', pg_varchar())
585 pg_type = get_pg_type(f, getattr(fields, f._type))
587 _logger.warning('%s type not supported!', field_type)
593 class MetaModel(type):
594 """ Metaclass for the Model.
596 This class is used as the metaclass for the Model class to discover
597 the models defined in a module (i.e. without instanciating them).
598 If the automatic discovery is not needed, it is possible to set the
599 model's _register attribute to False.
603 module_to_models = {}
605 def __init__(self, name, bases, attrs):
606 if not self._register:
607 self._register = True
608 super(MetaModel, self).__init__(name, bases, attrs)
611 # The (OpenERP) module name can be in the `openerp.addons` namespace
612 # or not. For instance module `sale` can be imported as
613 # `openerp.addons.sale` (the good way) or `sale` (for backward
615 module_parts = self.__module__.split('.')
616 if len(module_parts) > 2 and module_parts[0] == 'openerp' and \
617 module_parts[1] == 'addons':
618 module_name = self.__module__.split('.')[2]
620 module_name = self.__module__.split('.')[0]
621 if not hasattr(self, '_module'):
622 self._module = module_name
624 # Remember which models to instanciate for this module.
625 self.module_to_models.setdefault(self._module, []).append(self)
628 # Definition of log access columns, automatically added to models if
629 # self._log_access is True
630 LOG_ACCESS_COLUMNS = {
631 'create_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
632 'create_date': 'TIMESTAMP',
633 'write_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
634 'write_date': 'TIMESTAMP'
636 # special columns automatically created by the ORM
637 MAGIC_COLUMNS = ['id'] + LOG_ACCESS_COLUMNS.keys()
639 class BaseModel(object):
640 """ Base class for OpenERP models.
642 OpenERP models are created by inheriting from this class' subclasses:
644 * Model: for regular database-persisted models
645 * TransientModel: for temporary data, stored in the database but automatically
646 vaccuumed every so often
647 * AbstractModel: for abstract super classes meant to be shared by multiple
648 _inheriting classes (usually Models or TransientModels)
650 The system will later instantiate the class once per database (on
651 which the class' module is installed).
653 To create a class that should not be instantiated, the _register class attribute
656 __metaclass__ = MetaModel
657 _register = False # Set to false if the model shouldn't be automatically discovered.
663 _parent_name = 'parent_id'
664 _parent_store = False
665 _parent_order = False
671 # dict of {field:method}, with method returning the name_get of records
672 # to include in the _read_group, if grouped on this field
676 _transient = False # True in a TransientModel
677 _transient_max_count = None
678 _transient_max_hours = None
679 _transient_check_time = 20
682 # { 'parent_model': 'm2o_field', ... }
685 # Mapping from inherits'd field name to triple (m, r, f, n) where m is the
686 # model from which it is inherits'd, r is the (local) field towards m, f
687 # is the _column object itself, and n is the original (i.e. top-most)
690 # { 'field_name': ('parent_model', 'm2o_field_to_reach_parent',
691 # field_column_obj, origina_parent_model), ... }
694 # Mapping field name/column_info object
695 # This is similar to _inherit_fields but:
696 # 1. includes self fields,
697 # 2. uses column_info instead of a triple.
703 _sql_constraints = []
704 _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']
706 CONCURRENCY_CHECK_FIELD = '__last_update'
708 def log(self, cr, uid, id, message, secondary=False, context=None):
709 if context and context.get('disable_log'):
711 return self.pool.get('res.log').create(cr, uid,
714 'res_model': self._name,
715 'secondary': secondary,
721 def view_init(self, cr, uid, fields_list, context=None):
722 """Override this method to do specific things when a view on the object is opened."""
725 def _field_create(self, cr, context=None):
726 """ Create entries in ir_model_fields for all the model's fields.
728 If necessary, also create an entry in ir_model, and if called from the
729 modules loading scheme (by receiving 'module' in the context), also
730 create entries in ir_model_data (for the model and the fields).
732 - create an entry in ir_model (if there is not already one),
733 - create an entry in ir_model_data (if there is not already one, and if
734 'module' is in the context),
735 - update ir_model_fields with the fields found in _columns
736 (TODO there is some redundancy as _columns is updated from
737 ir_model_fields in __init__).
742 cr.execute("SELECT id FROM ir_model WHERE model=%s", (self._name,))
744 cr.execute('SELECT nextval(%s)', ('ir_model_id_seq',))
745 model_id = cr.fetchone()[0]
746 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'))
748 model_id = cr.fetchone()[0]
749 if 'module' in context:
750 name_id = 'model_'+self._name.replace('.', '_')
751 cr.execute('select * from ir_model_data where name=%s and module=%s', (name_id, context['module']))
753 cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, now(), now(), %s, %s, %s)", \
754 (name_id, context['module'], 'ir.model', model_id)
759 cr.execute("SELECT * FROM ir_model_fields WHERE model=%s", (self._name,))
761 for rec in cr.dictfetchall():
762 cols[rec['name']] = rec
764 ir_model_fields_obj = self.pool.get('ir.model.fields')
766 # sparse field should be created at the end, as it depends on its serialized field already existing
767 model_fields = sorted(self._columns.items(), key=lambda x: 1 if x[1]._type == 'sparse' else 0)
768 for (k, f) in model_fields:
770 'model_id': model_id,
773 'field_description': f.string.replace("'", " "),
775 'relation': f._obj or '',
776 'view_load': (f.view_load and 1) or 0,
777 'select_level': tools.ustr(f.select or 0),
778 'readonly': (f.readonly and 1) or 0,
779 'required': (f.required and 1) or 0,
780 'selectable': (f.selectable and 1) or 0,
781 'translate': (f.translate and 1) or 0,
782 'relation_field': (f._type=='one2many' and isinstance(f, fields.one2many)) and f._fields_id or '',
783 'serialization_field_id': None,
785 if getattr(f, 'serialization_field', None):
786 # resolve link to serialization_field if specified by name
787 serialization_field_id = ir_model_fields_obj.search(cr, 1, [('model','=',vals['model']), ('name', '=', f.serialization_field)])
788 if not serialization_field_id:
789 raise except_orm(_('Error'), _("Serialization field `%s` not found for sparse field `%s`!") % (f.serialization_field, k))
790 vals['serialization_field_id'] = serialization_field_id[0]
792 # When its a custom field,it does not contain f.select
793 if context.get('field_state', 'base') == 'manual':
794 if context.get('field_name', '') == k:
795 vals['select_level'] = context.get('select', '0')
796 #setting value to let the problem NOT occur next time
798 vals['select_level'] = cols[k]['select_level']
801 cr.execute('select nextval(%s)', ('ir_model_fields_id_seq',))
802 id = cr.fetchone()[0]
804 cr.execute("""INSERT INTO ir_model_fields (
805 id, model_id, model, name, field_description, ttype,
806 relation,view_load,state,select_level,relation_field, translate, serialization_field_id
808 %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s
810 id, vals['model_id'], vals['model'], vals['name'], vals['field_description'], vals['ttype'],
811 vals['relation'], bool(vals['view_load']), 'base',
812 vals['select_level'], vals['relation_field'], bool(vals['translate']), vals['serialization_field_id']
814 if 'module' in context:
815 name1 = 'field_' + self._table + '_' + k
816 cr.execute("select name from ir_model_data where name=%s", (name1,))
818 name1 = name1 + "_" + str(id)
819 cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, now(), now(), %s, %s, %s)", \
820 (name1, context['module'], 'ir.model.fields', id)
823 for key, val in vals.items():
824 if cols[k][key] != vals[key]:
825 cr.execute('update ir_model_fields set field_description=%s where model=%s and name=%s', (vals['field_description'], vals['model'], vals['name']))
827 cr.execute("""UPDATE ir_model_fields SET
828 model_id=%s, field_description=%s, ttype=%s, relation=%s,
829 view_load=%s, select_level=%s, readonly=%s ,required=%s, selectable=%s, relation_field=%s, translate=%s, serialization_field_id=%s
831 model=%s AND name=%s""", (
832 vals['model_id'], vals['field_description'], vals['ttype'],
833 vals['relation'], bool(vals['view_load']),
834 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']
840 # Goal: try to apply inheritance at the instanciation level and
841 # put objects in the pool var
844 def create_instance(cls, pool, cr):
845 """ Instanciate a given model.
847 This class method instanciates the class of some model (i.e. a class
848 deriving from osv or osv_memory). The class might be the class passed
849 in argument or, if it inherits from another class, a class constructed
850 by combining the two classes.
852 The ``attributes`` argument specifies which parent class attributes
855 TODO: the creation of the combined class is repeated at each call of
856 this method. This is probably unnecessary.
859 attributes = ['_columns', '_defaults', '_inherits', '_constraints',
862 parent_names = getattr(cls, '_inherit', None)
864 if isinstance(parent_names, (str, unicode)):
865 name = cls._name or parent_names
866 parent_names = [parent_names]
871 raise TypeError('_name is mandatory in case of multiple inheritance')
873 for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]):
874 parent_model = pool.get(parent_name)
875 if not getattr(cls, '_original_module', None) and name == parent_model._name:
876 cls._original_module = parent_model._original_module
878 raise TypeError('The model "%s" specifies an unexisting parent class "%s"\n'
879 'You may need to add a dependency on the parent class\' module.' % (name, parent_name))
880 parent_class = parent_model.__class__
883 new = copy.copy(getattr(parent_model, s, {}))
885 # Don't _inherit custom fields.
889 if hasattr(new, 'update'):
890 new.update(cls.__dict__.get(s, {}))
891 elif s=='_constraints':
892 for c in cls.__dict__.get(s, []):
894 for c2 in range(len(new)):
895 #For _constraints, we should check field and methods as well
896 if new[c2][2]==c[2] and (new[c2][0] == c[0] \
897 or getattr(new[c2][0],'__name__', True) == \
898 getattr(c[0],'__name__', False)):
899 # If new class defines a constraint with
900 # same function name, we let it override
908 new.extend(cls.__dict__.get(s, []))
910 cls = type(name, (cls, parent_class), dict(nattr, _register=False))
911 if not getattr(cls, '_original_module', None):
912 cls._original_module = cls._module
913 obj = object.__new__(cls)
914 obj.__init__(pool, cr)
918 """Register this model.
920 This doesn't create an instance but simply register the model
921 as being part of the module where it is defined.
926 # Set the module name (e.g. base, sale, accounting, ...) on the class.
927 module = cls.__module__.split('.')[0]
928 if not hasattr(cls, '_module'):
931 # Record this class in the list of models to instantiate for this module,
932 # managed by the metaclass.
933 module_model_list = MetaModel.module_to_models.setdefault(cls._module, [])
934 if cls not in module_model_list:
935 module_model_list.append(cls)
937 # Since we don't return an instance here, the __init__
938 # method won't be called.
941 def __init__(self, pool, cr):
942 """ Initialize a model and make it part of the given registry.
944 - copy the stored fields' functions in the osv_pool,
945 - update the _columns with the fields found in ir_model_fields,
946 - ensure there is a many2one for each _inherits'd parent,
947 - update the children's _columns,
948 - give a chance to each field to initialize itself.
951 pool.add(self._name, self)
954 if not self._name and not hasattr(self, '_inherit'):
955 name = type(self).__name__.split('.')[0]
956 msg = "The class %s has to have a _name attribute" % name
959 raise except_orm('ValueError', msg)
961 if not self._description:
962 self._description = self._name
964 self._table = self._name.replace('.', '_')
966 if not hasattr(self, '_log_access'):
967 # If _log_access is not specified, it is the same value as _auto.
968 self._log_access = getattr(self, "_auto", True)
970 self._columns = self._columns.copy()
971 for store_field in self._columns:
972 f = self._columns[store_field]
973 if hasattr(f, 'digits_change'):
975 def not_this_field(stored_func):
976 x, y, z, e, f, l = stored_func
977 return x != self._name or y != store_field
978 self.pool._store_function[self._name] = filter(not_this_field, self.pool._store_function.get(self._name, []))
979 if not isinstance(f, fields.function):
985 sm = {self._name: (lambda self, cr, uid, ids, c={}: ids, None, 10, None)}
986 for object, aa in sm.items():
988 (fnct, fields2, order, length) = aa
990 (fnct, fields2, order) = aa
993 raise except_orm('Error',
994 ('Invalid function definition %s in object %s !\nYou must use the definition: store={object:(fnct, fields, priority, time length)}.' % (store_field, self._name)))
995 self.pool._store_function.setdefault(object, [])
996 self.pool._store_function[object].append((self._name, store_field, fnct, tuple(fields2) if fields2 else None, order, length))
997 self.pool._store_function[object].sort(lambda x, y: cmp(x[4], y[4]))
999 for (key, _, msg) in self._sql_constraints:
1000 self.pool._sql_error[self._table+'_'+key] = msg
1002 # Load manual fields
1004 cr.execute("SELECT id FROM ir_model_fields WHERE name=%s AND model=%s", ('state', 'ir.model.fields'))
1006 cr.execute('SELECT * FROM ir_model_fields WHERE model=%s AND state=%s', (self._name, 'manual'))
1007 for field in cr.dictfetchall():
1008 if field['name'] in self._columns:
1011 'string': field['field_description'],
1012 'required': bool(field['required']),
1013 'readonly': bool(field['readonly']),
1014 'domain': eval(field['domain']) if field['domain'] else None,
1015 'size': field['size'],
1016 'ondelete': field['on_delete'],
1017 'translate': (field['translate']),
1019 #'select': int(field['select_level'])
1022 if field['serialization_field_id']:
1023 cr.execute('SELECT name FROM ir_model_fields WHERE id=%s', (field['serialization_field_id'],))
1024 attrs.update({'serialization_field': cr.fetchone()[0], 'type': field['ttype']})
1025 if field['ttype'] in ['many2one', 'one2many', 'many2many']:
1026 attrs.update({'relation': field['relation']})
1027 self._columns[field['name']] = fields.sparse(**attrs)
1028 elif field['ttype'] == 'selection':
1029 self._columns[field['name']] = fields.selection(eval(field['selection']), **attrs)
1030 elif field['ttype'] == 'reference':
1031 self._columns[field['name']] = fields.reference(selection=eval(field['selection']), **attrs)
1032 elif field['ttype'] == 'many2one':
1033 self._columns[field['name']] = fields.many2one(field['relation'], **attrs)
1034 elif field['ttype'] == 'one2many':
1035 self._columns[field['name']] = fields.one2many(field['relation'], field['relation_field'], **attrs)
1036 elif field['ttype'] == 'many2many':
1037 _rel1 = field['relation'].replace('.', '_')
1038 _rel2 = field['model'].replace('.', '_')
1039 _rel_name = 'x_%s_%s_%s_rel' % (_rel1, _rel2, field['name'])
1040 self._columns[field['name']] = fields.many2many(field['relation'], _rel_name, 'id1', 'id2', **attrs)
1042 self._columns[field['name']] = getattr(fields, field['ttype'])(**attrs)
1043 self._inherits_check()
1044 self._inherits_reload()
1045 if not self._sequence:
1046 self._sequence = self._table + '_id_seq'
1047 for k in self._defaults:
1048 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,)
1049 for f in self._columns:
1050 self._columns[f].restart()
1053 if self.is_transient():
1054 self._transient_check_count = 0
1055 self._transient_max_count = config.get('osv_memory_count_limit')
1056 self._transient_max_hours = config.get('osv_memory_age_limit')
1057 assert self._log_access, "TransientModels must have log_access turned on, "\
1058 "in order to implement their access rights policy"
1060 def __export_row(self, cr, uid, row, fields, context=None):
1064 def check_type(field_type):
1065 if field_type == 'float':
1067 elif field_type == 'integer':
1069 elif field_type == 'boolean':
1073 def selection_field(in_field):
1074 col_obj = self.pool.get(in_field.keys()[0])
1075 if f[i] in col_obj._columns.keys():
1076 return col_obj._columns[f[i]]
1077 elif f[i] in col_obj._inherits.keys():
1078 selection_field(col_obj._inherits)
1082 def _get_xml_id(self, cr, uid, r):
1083 model_data = self.pool.get('ir.model.data')
1084 data_ids = model_data.search(cr, uid, [('model', '=', r._table_name), ('res_id', '=', r['id'])])
1086 d = model_data.read(cr, uid, data_ids, ['name', 'module'])[0]
1088 r = '%s.%s' % (d['module'], d['name'])
1094 n = self._table+'_'+str(r['id']) + (postfix and ('_'+str(postfix)) or '' )
1095 if not model_data.search(cr, uid, [('name', '=', n)]):
1098 model_data.create(cr, uid, {
1100 'model': self._name,
1102 'module': '__export__',
1108 data = map(lambda x: '', range(len(fields)))
1110 for fpos in range(len(fields)):
1120 r = _get_xml_id(self, cr, uid, r)
1123 # To display external name of selection field when its exported
1124 if f[i] in self._columns.keys():
1125 cols = self._columns[f[i]]
1126 elif f[i] in self._inherit_fields.keys():
1127 cols = selection_field(self._inherits)
1128 if cols and cols._type == 'selection':
1129 sel_list = cols.selection
1130 if r and type(sel_list) == type([]):
1131 r = [x[1] for x in sel_list if r==x[0]]
1132 r = r and r[0] or False
1134 if f[i] in self._columns:
1135 r = check_type(self._columns[f[i]]._type)
1136 elif f[i] in self._inherit_fields:
1137 r = check_type(self._inherit_fields[f[i]][2]._type)
1138 data[fpos] = r or False
1140 if isinstance(r, (browse_record_list, list)):
1142 fields2 = map(lambda x: (x[:i+1]==f[:i+1] and x[i+1:]) \
1145 if [x for x in fields2 if x]:
1147 done.append(fields2)
1148 if cols and cols._type=='many2many' and len(fields[fpos])>(i+1) and (fields[fpos][i+1]=='id'):
1149 data[fpos] = ','.join([_get_xml_id(self, cr, uid, x) for x in r])
1153 lines2 = row2._model.__export_row(cr, uid, row2, fields2,
1156 for fpos2 in range(len(fields)):
1157 if lines2 and lines2[0][fpos2]:
1158 data[fpos2] = lines2[0][fpos2]
1162 name_relation = self.pool.get(rr._table_name)._rec_name
1163 if isinstance(rr[name_relation], browse_record):
1164 rr = rr[name_relation]
1165 rr_name = self.pool.get(rr._table_name).name_get(cr, uid, [rr.id], context=context)
1166 rr_name = rr_name and rr_name[0] and rr_name[0][1] or ''
1167 dt += tools.ustr(rr_name or '') + ','
1168 data[fpos] = dt[:-1]
1177 if isinstance(r, browse_record):
1178 r = self.pool.get(r._table_name).name_get(cr, uid, [r.id], context=context)
1179 r = r and r[0] and r[0][1] or ''
1180 data[fpos] = tools.ustr(r or '')
1181 return [data] + lines
1183 def export_data(self, cr, uid, ids, fields_to_export, context=None):
1185 Export fields for selected objects
1187 :param cr: database cursor
1188 :param uid: current user id
1189 :param ids: list of ids
1190 :param fields_to_export: list of fields
1191 :param context: context arguments, like lang, time zone
1192 :rtype: dictionary with a *datas* matrix
1194 This method is used when exporting data via client menu
1199 cols = self._columns.copy()
1200 for f in self._inherit_fields:
1201 cols.update({f: self._inherit_fields[f][2]})
1202 fields_to_export = map(fix_import_export_id_paths, fields_to_export)
1204 for row in self.browse(cr, uid, ids, context):
1205 datas += self.__export_row(cr, uid, row, fields_to_export, context)
1206 return {'datas': datas}
1208 def import_data(self, cr, uid, fields, datas, mode='init', current_module='', noupdate=False, context=None, filename=None):
1209 """Import given data in given module
1211 This method is used when importing data via client menu.
1213 Example of fields to import for a sale.order::
1216 partner_id, (=name_search)
1217 order_line/.id, (=database_id)
1219 order_line/product_id/id, (=xml id)
1220 order_line/price_unit,
1221 order_line/product_uom_qty,
1222 order_line/product_uom/id (=xml_id)
1224 This method returns a 4-tuple with the following structure::
1226 (return_code, errored_resource, error_message, unused)
1228 * The first item is a return code, it is ``-1`` in case of
1229 import error, or the last imported row number in case of success
1230 * The second item contains the record data dict that failed to import
1231 in case of error, otherwise it's 0
1232 * The third item contains an error message string in case of error,
1234 * The last item is currently unused, with no specific semantics
1236 :param fields: list of fields to import
1237 :param data: data to import
1238 :param mode: 'init' or 'update' for record creation
1239 :param current_module: module name
1240 :param noupdate: flag for record creation
1241 :param filename: optional file to store partial import state for recovery
1242 :returns: 4-tuple in the form (return_code, errored_resource, error_message, unused)
1243 :rtype: (int, dict or 0, str or 0, str or 0)
1247 fields = map(fix_import_export_id_paths, fields)
1248 ir_model_data_obj = self.pool.get('ir.model.data')
1250 # mode: id (XML id) or .id (database id) or False for name_get
1251 def _get_id(model_name, id, current_module=False, mode='id'):
1254 obj_model = self.pool.get(model_name)
1255 ids = obj_model.search(cr, uid, [('id', '=', int(id))])
1257 raise Exception(_("Database ID doesn't exist: %s : %s") %(model_name, id))
1260 module, xml_id = id.rsplit('.', 1)
1262 module, xml_id = current_module, id
1263 record_id = ir_model_data_obj._get_id(cr, uid, module, xml_id)
1264 ir_model_data = ir_model_data_obj.read(cr, uid, [record_id], ['res_id'])
1265 if not ir_model_data:
1266 raise ValueError('No references to %s.%s' % (module, xml_id))
1267 id = ir_model_data[0]['res_id']
1269 obj_model = self.pool.get(model_name)
1270 ids = obj_model.name_search(cr, uid, id, operator='=', context=context)
1272 raise ValueError('No record found for %s' % (id,))
1277 # datas: a list of records, each record is defined by a list of values
1278 # prefix: a list of prefix fields ['line_ids']
1279 # position: the line to process, skip is False if it's the first line of the current record
1281 # (res, position, warning, res_id) with
1282 # res: the record for the next line to process (including it's one2many)
1283 # position: the new position for the next line
1284 # res_id: the ID of the record if it's a modification
1285 def process_liness(self, datas, prefix, current_module, model_name, fields_def, position=0, skip=0):
1286 line = datas[position]
1294 for i, field in enumerate(fields):
1297 raise Exception(_('Please check that all your lines have %d columns.'
1298 'Stopped around line %d having %d columns.') % \
1299 (len(fields), position+2, len(line)))
1303 if field[:len(prefix)] <> prefix:
1304 if line[i] and skip:
1307 field_name = field[len(prefix)]
1309 #set the mode for m2o, o2m, m2m : xml_id/id/name
1310 if len(field) == len(prefix)+1:
1313 mode = field[len(prefix)+1]
1315 # TODO: improve this by using csv.csv_reader
1316 def many_ids(line, relation, current_module, mode):
1318 for db_id in line.split(config.get('csv_internal_sep')):
1319 res.append(_get_id(relation, db_id, current_module, mode))
1322 # ID of the record using a XML ID
1323 if field_name == 'id':
1325 data_res_id = _get_id(model_name, line[i], current_module)
1331 # ID of the record using a database ID
1332 elif field_name == '.id':
1333 data_res_id = _get_id(model_name, line[i], current_module, '.id')
1336 field_type = fields_def[field_name]['type']
1337 # recursive call for getting children and returning [(0,0,{})] or [(1,ID,{})]
1338 if field_type == 'one2many':
1339 if field_name in done:
1341 done[field_name] = True
1342 relation = fields_def[field_name]['relation']
1343 relation_obj = self.pool.get(relation)
1344 newfd = relation_obj.fields_get( cr, uid, context=context )
1350 while pos < len(datas):
1351 res2 = process_liness(self, datas, prefix + [field_name], current_module, relation_obj._name, newfd, pos, first)
1354 (newrow, pos, w2, data_res_id2, xml_id2) = res2
1355 nbrmax = max(nbrmax, pos)
1359 if (not newrow) or not reduce(lambda x, y: x or y, newrow.values(), 0):
1362 res.append( (data_res_id2 and 1 or 0, data_res_id2 or 0, newrow) )
1364 elif field_type == 'many2one':
1365 relation = fields_def[field_name]['relation']
1366 res = _get_id(relation, line[i], current_module, mode)
1368 elif field_type == 'many2many':
1369 relation = fields_def[field_name]['relation']
1370 res = many_ids(line[i], relation, current_module, mode)
1372 elif field_type == 'integer':
1373 res = line[i] and int(line[i]) or 0
1374 elif field_type == 'boolean':
1375 res = line[i].lower() not in ('0', 'false', 'off')
1376 elif field_type == 'float':
1377 res = line[i] and float(line[i]) or 0.0
1378 elif field_type == 'selection':
1379 for key, val in fields_def[field_name]['selection']:
1380 if tools.ustr(line[i]) in [tools.ustr(key), tools.ustr(val)]:
1383 if line[i] and not res:
1385 _("key '%s' not found in selection field '%s'"),
1386 tools.ustr(line[i]), tools.ustr(field_name))
1387 warning.append(_("Key/value '%s' not found in selection field '%s'") % (
1388 tools.ustr(line[i]), tools.ustr(field_name)))
1393 row[field_name] = res or False
1395 return row, nbrmax, warning, data_res_id, xml_id
1397 fields_def = self.fields_get(cr, uid, context=context)
1400 if config.get('import_partial') and filename:
1401 with open(config.get('import_partial'), 'rb') as partial_import_file:
1402 data = pickle.load(partial_import_file)
1403 position = data.get(filename, 0)
1405 while position<len(datas):
1406 (res, position, warning, res_id, xml_id) = \
1407 process_liness(self, datas, [], current_module, self._name, fields_def, position=position)
1410 return -1, res, 'Line ' + str(position) +' : ' + '!\n'.join(warning), ''
1413 ir_model_data_obj._update(cr, uid, self._name,
1414 current_module, res, mode=mode, xml_id=xml_id,
1415 noupdate=noupdate, res_id=res_id, context=context)
1416 except Exception, e:
1417 return -1, res, 'Line ' + str(position) + ' : ' + tools.ustr(e), ''
1419 if config.get('import_partial') and filename and (not (position%100)):
1420 with open(config.get('import_partial'), 'rb') as partial_import:
1421 data = pickle.load(partial_import)
1422 data[filename] = position
1423 with open(config.get('import_partial'), 'wb') as partial_import:
1424 pickle.dump(data, partial_import)
1425 if context.get('defer_parent_store_computation'):
1426 self._parent_store_compute(cr)
1429 if context.get('defer_parent_store_computation'):
1430 self._parent_store_compute(cr)
1431 return position, 0, 0, 0
1433 def get_invalid_fields(self, cr, uid):
1434 return list(self._invalids)
1436 def _validate(self, cr, uid, ids, context=None):
1437 context = context or {}
1438 lng = context.get('lang', False) or 'en_US'
1439 trans = self.pool.get('ir.translation')
1441 for constraint in self._constraints:
1442 fun, msg, fields = constraint
1443 if not fun(self, cr, uid, ids):
1444 # Check presence of __call__ directly instead of using
1445 # callable() because it will be deprecated as of Python 3.0
1446 if hasattr(msg, '__call__'):
1447 tmp_msg = msg(self, cr, uid, ids, context=context)
1448 if isinstance(tmp_msg, tuple):
1449 tmp_msg, params = tmp_msg
1450 translated_msg = tmp_msg % params
1452 translated_msg = tmp_msg
1454 translated_msg = trans._get_source(cr, uid, self._name, 'constraint', lng, msg) or msg
1456 _("Error occurred while validating the field(s) %s: %s") % (','.join(fields), translated_msg)
1458 self._invalids.update(fields)
1461 raise except_orm('ValidateError', '\n'.join(error_msgs))
1463 self._invalids.clear()
1465 def default_get(self, cr, uid, fields_list, context=None):
1467 Returns default values for the fields in fields_list.
1469 :param fields_list: list of fields to get the default values for (example ['field1', 'field2',])
1470 :type fields_list: list
1471 :param context: optional context dictionary - it may contains keys for specifying certain options
1472 like ``context_lang`` (language) or ``context_tz`` (timezone) to alter the results of the call.
1473 It may contain keys in the form ``default_XXX`` (where XXX is a field name), to set
1474 or override a default value for a field.
1475 A special ``bin_size`` boolean flag may also be passed in the context to request the
1476 value of all fields.binary columns to be returned as the size of the binary instead of its
1477 contents. This can also be selectively overriden by passing a field-specific flag
1478 in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field.
1479 Note: The ``bin_size_XXX`` form is new in OpenERP v6.0.
1480 :return: dictionary of the default values (set on the object model class, through user preferences, or in the context)
1482 # trigger view init hook
1483 self.view_init(cr, uid, fields_list, context)
1489 # get the default values for the inherited fields
1490 for t in self._inherits.keys():
1491 defaults.update(self.pool.get(t).default_get(cr, uid, fields_list,
1494 # get the default values defined in the object
1495 for f in fields_list:
1496 if f in self._defaults:
1497 if callable(self._defaults[f]):
1498 defaults[f] = self._defaults[f](self, cr, uid, context)
1500 defaults[f] = self._defaults[f]
1502 fld_def = ((f in self._columns) and self._columns[f]) \
1503 or ((f in self._inherit_fields) and self._inherit_fields[f][2]) \
1506 if isinstance(fld_def, fields.property):
1507 property_obj = self.pool.get('ir.property')
1508 prop_value = property_obj.get(cr, uid, f, self._name, context=context)
1510 if isinstance(prop_value, (browse_record, browse_null)):
1511 defaults[f] = prop_value.id
1513 defaults[f] = prop_value
1515 if f not in defaults:
1518 # get the default values set by the user and override the default
1519 # values defined in the object
1520 ir_values_obj = self.pool.get('ir.values')
1521 res = ir_values_obj.get(cr, uid, 'default', False, [self._name])
1522 for id, field, field_value in res:
1523 if field in fields_list:
1524 fld_def = (field in self._columns) and self._columns[field] or self._inherit_fields[field][2]
1525 if fld_def._type in ('many2one', 'one2one'):
1526 obj = self.pool.get(fld_def._obj)
1527 if not obj.search(cr, uid, [('id', '=', field_value or False)]):
1529 if fld_def._type in ('many2many'):
1530 obj = self.pool.get(fld_def._obj)
1532 for i in range(len(field_value)):
1533 if not obj.search(cr, uid, [('id', '=',
1536 field_value2.append(field_value[i])
1537 field_value = field_value2
1538 if fld_def._type in ('one2many'):
1539 obj = self.pool.get(fld_def._obj)
1541 for i in range(len(field_value)):
1542 field_value2.append({})
1543 for field2 in field_value[i]:
1544 if field2 in obj._columns.keys() and obj._columns[field2]._type in ('many2one', 'one2one'):
1545 obj2 = self.pool.get(obj._columns[field2]._obj)
1546 if not obj2.search(cr, uid,
1547 [('id', '=', field_value[i][field2])]):
1549 elif field2 in obj._inherit_fields.keys() and obj._inherit_fields[field2][2]._type in ('many2one', 'one2one'):
1550 obj2 = self.pool.get(obj._inherit_fields[field2][2]._obj)
1551 if not obj2.search(cr, uid,
1552 [('id', '=', field_value[i][field2])]):
1554 # TODO add test for many2many and one2many
1555 field_value2[i][field2] = field_value[i][field2]
1556 field_value = field_value2
1557 defaults[field] = field_value
1559 # get the default values from the context
1560 for key in context or {}:
1561 if key.startswith('default_') and (key[8:] in fields_list):
1562 defaults[key[8:]] = context[key]
1565 def fields_get_keys(self, cr, user, context=None):
1566 res = self._columns.keys()
1567 # TODO I believe this loop can be replace by
1568 # res.extend(self._inherit_fields.key())
1569 for parent in self._inherits:
1570 res.extend(self.pool.get(parent).fields_get_keys(cr, user, context))
1574 # Overload this method if you need a window title which depends on the context
1576 def view_header_get(self, cr, user, view_id=None, view_type='form', context=None):
1579 def __view_look_dom(self, cr, user, node, view_id, in_tree_view, model_fields, context=None):
1580 """ Return the description of the fields in the node.
1582 In a normal call to this method, node is a complete view architecture
1583 but it is actually possible to give some sub-node (this is used so
1584 that the method can call itself recursively).
1586 Originally, the field descriptions are drawn from the node itself.
1587 But there is now some code calling fields_get() in order to merge some
1588 of those information in the architecture.
1600 if isinstance(s, unicode):
1601 return s.encode('utf8')
1604 def check_group(node):
1605 """ Set invisible to true if the user is not in the specified groups. """
1606 if node.get('groups'):
1607 groups = node.get('groups').split(',')
1608 ir_model_access = self.pool.get('ir.model.access')
1609 can_see = any(ir_model_access.check_groups(cr, user, group) for group in groups)
1611 node.set('invisible', '1')
1612 modifiers['invisible'] = True
1613 if 'attrs' in node.attrib:
1614 del(node.attrib['attrs']) #avoid making field visible later
1615 del(node.attrib['groups'])
1617 if node.tag in ('field', 'node', 'arrow'):
1618 if node.get('object'):
1623 if f.tag in ('field'):
1624 xml += etree.tostring(f, encoding="utf-8")
1626 new_xml = etree.fromstring(encode(xml))
1627 ctx = context.copy()
1628 ctx['base_model_name'] = self._name
1629 xarch, xfields = self.pool.get(node.get('object')).__view_look_dom_arch(cr, user, new_xml, view_id, ctx)
1634 attrs = {'views': views}
1636 if node.get('name'):
1639 if node.get('name') in self._columns:
1640 column = self._columns[node.get('name')]
1642 column = self._inherit_fields[node.get('name')][2]
1647 relation = self.pool.get(column._obj)
1652 if f.tag in ('form', 'tree', 'graph'):
1654 ctx = context.copy()
1655 ctx['base_model_name'] = self._name
1656 xarch, xfields = relation.__view_look_dom_arch(cr, user, f, view_id, ctx)
1657 views[str(f.tag)] = {
1661 attrs = {'views': views}
1662 if node.get('widget') and node.get('widget') == 'selection':
1663 # Prepare the cached selection list for the client. This needs to be
1664 # done even when the field is invisible to the current user, because
1665 # other events could need to change its value to any of the selectable ones
1666 # (such as on_change events, refreshes, etc.)
1668 # If domain and context are strings, we keep them for client-side, otherwise
1669 # we evaluate them server-side to consider them when generating the list of
1671 # TODO: find a way to remove this hack, by allow dynamic domains
1673 if column._domain and not isinstance(column._domain, basestring):
1674 dom = column._domain
1675 dom += eval(node.get('domain', '[]'), {'uid': user, 'time': time})
1676 search_context = dict(context)
1677 if column._context and not isinstance(column._context, basestring):
1678 search_context.update(column._context)
1679 attrs['selection'] = relation._name_search(cr, user, '', dom, context=search_context, limit=None, name_get_uid=1)
1680 if (node.get('required') and not int(node.get('required'))) or not column.required:
1681 attrs['selection'].append((False, ''))
1682 fields[node.get('name')] = attrs
1684 field = model_fields.get(node.get('name'))
1686 transfer_field_to_modifiers(field, modifiers)
1689 elif node.tag in ('form', 'tree'):
1690 result = self.view_header_get(cr, user, False, node.tag, context)
1692 node.set('string', result)
1693 in_tree_view = node.tag == 'tree'
1695 elif node.tag == 'calendar':
1696 for additional_field in ('date_start', 'date_delay', 'date_stop', 'color'):
1697 if node.get(additional_field):
1698 fields[node.get(additional_field)] = {}
1702 # The view architeture overrides the python model.
1703 # Get the attrs before they are (possibly) deleted by check_group below
1704 transfer_node_to_modifiers(node, modifiers, context, in_tree_view)
1706 # TODO remove attrs couterpart in modifiers when invisible is true ?
1709 if 'lang' in context:
1710 if node.get('string') and not result:
1711 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('string'))
1712 if trans == node.get('string') and ('base_model_name' in context):
1713 # If translation is same as source, perhaps we'd have more luck with the alternative model name
1714 # (in case we are in a mixed situation, such as an inherited view where parent_view.model != model
1715 trans = self.pool.get('ir.translation')._get_source(cr, user, context['base_model_name'], 'view', context['lang'], node.get('string'))
1717 node.set('string', trans)
1718 if node.get('confirm'):
1719 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('confirm'))
1721 node.set('confirm', trans)
1723 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('sum'))
1725 node.set('sum', trans)
1726 if node.get('help'):
1727 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('help'))
1729 node.set('help', trans)
1732 if children or (node.tag == 'field' and f.tag in ('filter','separator')):
1733 fields.update(self.__view_look_dom(cr, user, f, view_id, in_tree_view, model_fields, context))
1735 transfer_modifiers_to_node(modifiers, node)
1738 def _disable_workflow_buttons(self, cr, user, node):
1739 """ Set the buttons in node to readonly if the user can't activate them. """
1741 # admin user can always activate workflow buttons
1744 # TODO handle the case of more than one workflow for a model or multiple
1745 # transitions with different groups and same signal
1746 usersobj = self.pool.get('res.users')
1747 buttons = (n for n in node.getiterator('button') if n.get('type') != 'object')
1748 for button in buttons:
1749 user_groups = usersobj.read(cr, user, [user], ['groups_id'])[0]['groups_id']
1750 cr.execute("""SELECT DISTINCT t.group_id
1752 INNER JOIN wkf_activity a ON a.wkf_id = wkf.id
1753 INNER JOIN wkf_transition t ON (t.act_to = a.id)
1756 AND t.group_id is NOT NULL
1757 """, (self._name, button.get('name')))
1758 group_ids = [x[0] for x in cr.fetchall() if x[0]]
1759 can_click = not group_ids or bool(set(user_groups).intersection(group_ids))
1760 button.set('readonly', str(int(not can_click)))
1763 def __view_look_dom_arch(self, cr, user, node, view_id, context=None):
1764 """ Return an architecture and a description of all the fields.
1766 The field description combines the result of fields_get() and
1769 :param node: the architecture as as an etree
1770 :return: a tuple (arch, fields) where arch is the given node as a
1771 string and fields is the description of all the fields.
1775 if node.tag == 'diagram':
1776 if node.getchildren()[0].tag == 'node':
1777 node_fields = self.pool.get(node.getchildren()[0].get('object')).fields_get(cr, user, None, context)
1778 fields.update(node_fields)
1779 if node.getchildren()[1].tag == 'arrow':
1780 arrow_fields = self.pool.get(node.getchildren()[1].get('object')).fields_get(cr, user, None, context)
1781 fields.update(arrow_fields)
1783 fields = self.fields_get(cr, user, None, context)
1784 fields_def = self.__view_look_dom(cr, user, node, view_id, False, fields, context=context)
1785 node = self._disable_workflow_buttons(cr, user, node)
1786 arch = etree.tostring(node, encoding="utf-8").replace('\t', '')
1787 for k in fields.keys():
1788 if k not in fields_def:
1790 for field in fields_def:
1792 # sometime, the view may contain the (invisible) field 'id' needed for a domain (when 2 objects have cross references)
1793 fields['id'] = {'readonly': True, 'type': 'integer', 'string': 'ID'}
1794 elif field in fields:
1795 fields[field].update(fields_def[field])
1797 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))
1798 res = cr.fetchall()[:]
1800 res.insert(0, ("Can't find field '%s' in the following view parts composing the view of object model '%s':" % (field, model), None))
1801 msg = "\n * ".join([r[0] for r in res])
1802 msg += "\n\nEither you wrongly customized this view, or some modules bringing those views are not compatible with your current data model"
1804 raise except_orm('View error', msg)
1807 def _get_default_form_view(self, cr, user, context=None):
1808 """ Generates a default single-line form view using all fields
1809 of the current model except the m2m and o2m ones.
1811 :param cr: database cursor
1812 :param int user: user id
1813 :param dict context: connection context
1814 :returns: a form view as an lxml document
1815 :rtype: etree._Element
1817 view = etree.Element('form', string=self._description)
1818 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
1819 for field, descriptor in self.fields_get(cr, user, context=context).iteritems():
1820 if descriptor['type'] in ('one2many', 'many2many'):
1822 etree.SubElement(view, 'field', name=field)
1823 if descriptor['type'] == 'text':
1824 etree.SubElement(view, 'newline')
1827 def _get_default_tree_view(self, cr, user, context=None):
1828 """ Generates a single-field tree view, using _rec_name if
1829 it's one of the columns or the first column it finds otherwise
1831 :param cr: database cursor
1832 :param int user: user id
1833 :param dict context: connection context
1834 :returns: a tree view as an lxml document
1835 :rtype: etree._Element
1837 _rec_name = self._rec_name
1838 if _rec_name not in self._columns:
1839 _rec_name = self._columns.keys()[0] if len(self._columns.keys()) > 0 else "id"
1841 view = etree.Element('tree', string=self._description)
1842 etree.SubElement(view, 'field', name=_rec_name)
1845 def _get_default_calendar_view(self, cr, user, context=None):
1846 """ Generates a default calendar view by trying to infer
1847 calendar fields from a number of pre-set attribute names
1849 :param cr: database cursor
1850 :param int user: user id
1851 :param dict context: connection context
1852 :returns: a calendar view
1853 :rtype: etree._Element
1855 def set_first_of(seq, in_, to):
1856 """Sets the first value of ``seq`` also found in ``in_`` to
1857 the ``to`` attribute of the view being closed over.
1859 Returns whether it's found a suitable value (and set it on
1860 the attribute) or not
1868 view = etree.Element('calendar', string=self._description)
1869 etree.SubElement(view, 'field', name=self._rec_name)
1871 if (self._date_name not in self._columns):
1873 for dt in ['date', 'date_start', 'x_date', 'x_date_start']:
1874 if dt in self._columns:
1875 self._date_name = dt
1880 raise except_orm(_('Invalid Object Architecture!'), _("Insufficient fields for Calendar View!"))
1881 view.set('date_start', self._date_name)
1883 set_first_of(["user_id", "partner_id", "x_user_id", "x_partner_id"],
1884 self._columns, 'color')
1886 if not set_first_of(["date_stop", "date_end", "x_date_stop", "x_date_end"],
1887 self._columns, 'date_stop'):
1888 if not set_first_of(["date_delay", "planned_hours", "x_date_delay", "x_planned_hours"],
1889 self._columns, 'date_delay'):
1891 _('Invalid Object Architecture!'),
1892 _("Insufficient fields to generate a Calendar View for %s, missing a date_stop or a date_delay" % (self._name)))
1896 def _get_default_search_view(self, cr, uid, context=None):
1898 :param cr: database cursor
1899 :param int user: user id
1900 :param dict context: connection context
1901 :returns: an lxml document of the view
1902 :rtype: etree._Element
1904 form_view = self.fields_view_get(cr, uid, False, 'form', context=context)
1905 tree_view = self.fields_view_get(cr, uid, False, 'tree', context=context)
1907 # TODO it seems _all_columns could be used instead of fields_get (no need for translated fields info)
1908 fields = self.fields_get(cr, uid, context=context)
1909 fields_to_search = set(
1910 field for field, descriptor in fields.iteritems()
1911 if descriptor.get('select'))
1913 for view in (form_view, tree_view):
1914 view_root = etree.fromstring(view['arch'])
1915 # Only care about select=1 in xpath below, because select=2 is covered
1916 # by the custom advanced search in clients
1917 fields_to_search.update(view_root.xpath("//field[@select=1]/@name"))
1919 tree_view_root = view_root # as provided by loop above
1920 search_view = etree.Element("search", string=tree_view_root.get("string", ""))
1922 field_group = etree.SubElement(search_view, "group")
1923 for field_name in fields_to_search:
1924 etree.SubElement(field_group, "field", name=field_name)
1929 # if view_id, view_type is not required
1931 def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
1933 Get the detailed composition of the requested view like fields, model, view architecture
1935 :param cr: database cursor
1936 :param user: current user id
1937 :param view_id: id of the view or None
1938 :param view_type: type of the view to return if view_id is None ('form', tree', ...)
1939 :param context: context arguments, like lang, time zone
1940 :param toolbar: true to include contextual actions
1941 :param submenu: deprecated
1942 :return: dictionary describing the composition of the requested view (including inherited views and extensions)
1943 :raise AttributeError:
1944 * if the inherited view has unknown position to work with other than 'before', 'after', 'inside', 'replace'
1945 * if some tag other than 'position' is found in parent view
1946 :raise Invalid ArchitectureError: if there is view type other than form, tree, calendar, search etc defined on the structure
1953 if isinstance(s, unicode):
1954 return s.encode('utf8')
1957 def raise_view_error(error_msg, child_view_id):
1958 view, child_view = self.pool.get('ir.ui.view').browse(cr, user, [view_id, child_view_id], context)
1959 raise AttributeError("View definition error for inherited view '%s' on model '%s': %s"
1960 % (child_view.xml_id, self._name, error_msg))
1962 def locate(source, spec):
1963 """ Locate a node in a source (parent) architecture.
1965 Given a complete source (parent) architecture (i.e. the field
1966 `arch` in a view), and a 'spec' node (a node in an inheriting
1967 view that specifies the location in the source view of what
1968 should be changed), return (if it exists) the node in the
1969 source view matching the specification.
1971 :param source: a parent architecture to modify
1972 :param spec: a modifying node in an inheriting view
1973 :return: a node in the source matching the spec
1976 if spec.tag == 'xpath':
1977 nodes = source.xpath(spec.get('expr'))
1978 return nodes[0] if nodes else None
1979 elif spec.tag == 'field':
1980 # Only compare the field name: a field can be only once in a given view
1981 # at a given level (and for multilevel expressions, we should use xpath
1982 # inheritance spec anyway).
1983 for node in source.getiterator('field'):
1984 if node.get('name') == spec.get('name'):
1988 for node in source.getiterator(spec.tag):
1990 for attr in spec.attrib:
1991 if attr != 'position' and (not node.get(attr) or node.get(attr) != spec.get(attr)):
1998 def apply_inheritance_specs(source, specs_arch, inherit_id=None):
1999 """ Apply an inheriting view.
2001 Apply to a source architecture all the spec nodes (i.e. nodes
2002 describing where and what changes to apply to some parent
2003 architecture) given by an inheriting view.
2005 :param source: a parent architecture to modify
2006 :param specs_arch: a modifying architecture in an inheriting view
2007 :param inherit_id: the database id of the inheriting view
2008 :return: a modified source where the specs are applied
2011 specs_tree = etree.fromstring(encode(specs_arch))
2012 # Queue of specification nodes (i.e. nodes describing where and
2013 # changes to apply to some parent architecture).
2014 specs = [specs_tree]
2018 if isinstance(spec, SKIPPED_ELEMENT_TYPES):
2020 if spec.tag == 'data':
2021 specs += [ c for c in specs_tree ]
2023 node = locate(source, spec)
2024 if node is not None:
2025 pos = spec.get('position', 'inside')
2026 if pos == 'replace':
2027 if node.getparent() is None:
2028 source = copy.deepcopy(spec[0])
2031 node.addprevious(child)
2032 node.getparent().remove(node)
2033 elif pos == 'attributes':
2034 for child in spec.getiterator('attribute'):
2035 attribute = (child.get('name'), child.text and child.text.encode('utf8') or None)
2037 node.set(attribute[0], attribute[1])
2039 del(node.attrib[attribute[0]])
2041 sib = node.getnext()
2045 elif pos == 'after':
2050 sib.addprevious(child)
2051 elif pos == 'before':
2052 node.addprevious(child)
2054 raise_view_error("Invalid position value: '%s'" % pos, inherit_id)
2057 ' %s="%s"' % (attr, spec.get(attr))
2058 for attr in spec.attrib
2059 if attr != 'position'
2061 tag = "<%s%s>" % (spec.tag, attrs)
2062 raise_view_error("Element '%s' not found in parent view '%%(parent_xml_id)s'" % tag, inherit_id)
2065 def apply_view_inheritance(cr, user, source, inherit_id):
2066 """ Apply all the (directly and indirectly) inheriting views.
2068 :param source: a parent architecture to modify (with parent
2069 modifications already applied)
2070 :param inherit_id: the database view_id of the parent view
2071 :return: a modified source where all the modifying architecture
2075 sql_inherit = self.pool.get('ir.ui.view').get_inheriting_views_arch(cr, user, inherit_id, self._name)
2076 for (view_arch, view_id) in sql_inherit:
2077 source = apply_inheritance_specs(source, view_arch, view_id)
2078 source = apply_view_inheritance(cr, user, source, view_id)
2081 result = {'type': view_type, 'model': self._name}
2084 parent_view_model = None
2085 view_ref = context.get(view_type + '_view_ref')
2086 # Search for a root (i.e. without any parent) view.
2088 if view_ref and not view_id:
2090 module, view_ref = view_ref.split('.', 1)
2091 cr.execute("SELECT res_id FROM ir_model_data WHERE model='ir.ui.view' AND module=%s AND name=%s", (module, view_ref))
2092 view_ref_res = cr.fetchone()
2094 view_id = view_ref_res[0]
2097 cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model
2099 WHERE id=%s""", (view_id,))
2101 cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model
2103 WHERE model=%s AND type=%s AND inherit_id IS NULL
2104 ORDER BY priority""", (self._name, view_type))
2105 sql_res = cr.dictfetchone()
2110 view_id = sql_res['inherit_id'] or sql_res['id']
2111 parent_view_model = sql_res['model']
2112 if not sql_res['inherit_id']:
2115 # if a view was found
2117 source = etree.fromstring(encode(sql_res['arch']))
2119 arch=apply_view_inheritance(cr, user, source, sql_res['id']),
2120 type=sql_res['type'],
2121 view_id=sql_res['id'],
2122 name=sql_res['name'],
2123 field_parent=sql_res['field_parent'] or False)
2125 # otherwise, build some kind of default view
2127 view = getattr(self, '_get_default_%s_view' % view_type)(
2129 except AttributeError:
2130 # what happens here, graph case?
2131 raise except_orm(_('Invalid Architecture!'), _("There is no view of type '%s' defined for the structure!") % view_type)
2139 if parent_view_model != self._name:
2140 ctx = context.copy()
2141 ctx['base_model_name'] = parent_view_model
2144 xarch, xfields = self.__view_look_dom_arch(cr, user, result['arch'], view_id, context=ctx)
2145 result['arch'] = xarch
2146 result['fields'] = xfields
2151 for key in ('report_sxw_content', 'report_rml_content',
2152 'report_sxw', 'report_rml',
2153 'report_sxw_content_data', 'report_rml_content_data'):
2157 ir_values_obj = self.pool.get('ir.values')
2158 resprint = ir_values_obj.get(cr, user, 'action',
2159 'client_print_multi', [(self._name, False)], False,
2161 resaction = ir_values_obj.get(cr, user, 'action',
2162 'client_action_multi', [(self._name, False)], False,
2165 resrelate = ir_values_obj.get(cr, user, 'action',
2166 'client_action_relate', [(self._name, False)], False,
2168 resaction = [clean(action) for action in resaction
2169 if view_type == 'tree' or not action[2].get('multi')]
2170 resprint = [clean(print_) for print_ in resprint
2171 if view_type == 'tree' or not print_[2].get('multi')]
2172 resrelate = map(lambda x: x[2], resrelate)
2174 for x in itertools.chain(resprint, resaction, resrelate):
2175 x['string'] = x['name']
2177 result['toolbar'] = {
2179 'action': resaction,
2184 _view_look_dom_arch = __view_look_dom_arch
2186 def search_count(self, cr, user, args, context=None):
2189 res = self.search(cr, user, args, context=context, count=True)
2190 if isinstance(res, list):
2194 def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
2196 Search for records based on a search domain.
2198 :param cr: database cursor
2199 :param user: current user id
2200 :param args: list of tuples specifying the search domain [('field_name', 'operator', value), ...]. Pass an empty list to match all records.
2201 :param offset: optional number of results to skip in the returned values (default: 0)
2202 :param limit: optional max number of records to return (default: **None**)
2203 :param order: optional columns to sort by (default: self._order=id )
2204 :param context: optional context arguments, like lang, time zone
2205 :type context: dictionary
2206 :param count: optional (default: **False**), if **True**, returns only the number of records matching the criteria, not their ids
2207 :return: id or list of ids of records matching the criteria
2208 :rtype: integer or list of integers
2209 :raise AccessError: * if user tries to bypass access rules for read on the requested object.
2211 **Expressing a search domain (args)**
2213 Each tuple in the search domain needs to have 3 elements, in the form: **('field_name', 'operator', value)**, where:
2215 * **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.
2216 * **operator** must be a string with a valid comparison operator from this list: ``=, !=, >, >=, <, <=, like, ilike, in, not in, child_of, parent_left, parent_right``
2217 The semantics of most of these operators are obvious.
2218 The ``child_of`` operator will look for records who are children or grand-children of a given record,
2219 according to the semantics of this model (i.e following the relationship field named by
2220 ``self._parent_name``, by default ``parent_id``.
2221 * **value** must be a valid value to compare with the values of **field_name**, depending on its type.
2223 Domain criteria can be combined using 3 logical operators than can be added between tuples: '**&**' (logical AND, default), '**|**' (logical OR), '**!**' (logical NOT).
2224 These are **prefix** operators and the arity of the '**&**' and '**|**' operator is 2, while the arity of the '**!**' is just 1.
2225 Be very careful about this when you combine them the first time.
2227 Here is an example of searching for Partners named *ABC* from Belgium and Germany whose language is not english ::
2229 [('name','=','ABC'),'!',('language.code','=','en_US'),'|',('country_id.code','=','be'),('country_id.code','=','de'))
2231 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::
2233 (name is 'ABC' AND (language is NOT english) AND (country is Belgium OR Germany))
2236 return self._search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count)
2238 def name_get(self, cr, user, ids, context=None):
2239 """Returns the preferred display value (text representation) for the records with the
2240 given ``ids``. By default this will be the value of the ``name`` column, unless
2241 the model implements a custom behavior.
2242 Can sometimes be seen as the inverse function of :meth:`~.name_search`, but it is not
2246 :return: list of pairs ``(id,text_repr)`` for all records with the given ``ids``.
2250 if isinstance(ids, (int, long)):
2252 return [(r['id'], tools.ustr(r[self._rec_name])) for r in self.read(cr, user, ids,
2253 [self._rec_name], context, load='_classic_write')]
2255 def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
2256 """Search for records that have a display name matching the given ``name`` pattern if compared
2257 with the given ``operator``, while also matching the optional search domain (``args``).
2258 This is used for example to provide suggestions based on a partial value for a relational
2260 Sometimes be seen as the inverse function of :meth:`~.name_get`, but it is not
2263 This method is equivalent to calling :meth:`~.search` with a search domain based on ``name``
2264 and then :meth:`~.name_get` on the result of the search.
2266 :param list args: optional search domain (see :meth:`~.search` for syntax),
2267 specifying further restrictions
2268 :param str operator: domain operator for matching the ``name`` pattern, such as ``'like'``
2270 :param int limit: optional max number of records to return
2272 :return: list of pairs ``(id,text_repr)`` for all matching records.
2274 return self._name_search(cr, user, name, args, operator, context, limit)
2276 def name_create(self, cr, uid, name, context=None):
2277 """Creates a new record by calling :meth:`~.create` with only one
2278 value provided: the name of the new record (``_rec_name`` field).
2279 The new record will also be initialized with any default values applicable
2280 to this model, or provided through the context. The usual behavior of
2281 :meth:`~.create` applies.
2282 Similarly, this method may raise an exception if the model has multiple
2283 required fields and some do not have default values.
2285 :param name: name of the record to create
2288 :return: the :meth:`~.name_get` pair value for the newly-created record.
2290 rec_id = self.create(cr, uid, {self._rec_name: name}, context);
2291 return self.name_get(cr, uid, [rec_id], context)[0]
2293 # private implementation of name_search, allows passing a dedicated user for the name_get part to
2294 # solve some access rights issues
2295 def _name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100, name_get_uid=None):
2301 # optimize out the default criterion of ``ilike ''`` that matches everything
2302 if not (name == '' and operator == 'ilike'):
2303 args += [(self._rec_name, operator, name)]
2304 access_rights_uid = name_get_uid or user
2305 ids = self._search(cr, user, args, limit=limit, context=context, access_rights_uid=access_rights_uid)
2306 res = self.name_get(cr, access_rights_uid, ids, context)
2309 def read_string(self, cr, uid, id, langs, fields=None, context=None):
2312 self.pool.get('ir.translation').check_read(cr, uid)
2314 fields = self._columns.keys() + self._inherit_fields.keys()
2315 #FIXME: collect all calls to _get_source into one SQL call.
2317 res[lang] = {'code': lang}
2319 if f in self._columns:
2320 res_trans = self.pool.get('ir.translation')._get_source(cr, uid, self._name+','+f, 'field', lang)
2322 res[lang][f] = res_trans
2324 res[lang][f] = self._columns[f].string
2325 for table in self._inherits:
2326 cols = intersect(self._inherit_fields.keys(), fields)
2327 res2 = self.pool.get(table).read_string(cr, uid, id, langs, cols, context)
2330 res[lang]['code'] = lang
2331 for f in res2[lang]:
2332 res[lang][f] = res2[lang][f]
2335 def write_string(self, cr, uid, id, langs, vals, context=None):
2336 self.pool.get('ir.translation').check_write(cr, uid)
2337 #FIXME: try to only call the translation in one SQL
2340 if field in self._columns:
2341 src = self._columns[field].string
2342 self.pool.get('ir.translation')._set_ids(cr, uid, self._name+','+field, 'field', lang, [0], vals[field], src)
2343 for table in self._inherits:
2344 cols = intersect(self._inherit_fields.keys(), vals)
2346 self.pool.get(table).write_string(cr, uid, id, langs, vals, context)
2349 def _add_missing_default_values(self, cr, uid, values, context=None):
2350 missing_defaults = []
2351 avoid_tables = [] # avoid overriding inherited values when parent is set
2352 for tables, parent_field in self._inherits.items():
2353 if parent_field in values:
2354 avoid_tables.append(tables)
2355 for field in self._columns.keys():
2356 if not field in values:
2357 missing_defaults.append(field)
2358 for field in self._inherit_fields.keys():
2359 if (field not in values) and (self._inherit_fields[field][0] not in avoid_tables):
2360 missing_defaults.append(field)
2362 if len(missing_defaults):
2363 # override defaults with the provided values, never allow the other way around
2364 defaults = self.default_get(cr, uid, missing_defaults, context)
2366 if ((dv in self._columns and self._columns[dv]._type == 'many2many') \
2367 or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'many2many')) \
2368 and defaults[dv] and isinstance(defaults[dv][0], (int, long)):
2369 defaults[dv] = [(6, 0, defaults[dv])]
2370 if (dv in self._columns and self._columns[dv]._type == 'one2many' \
2371 or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'one2many')) \
2372 and isinstance(defaults[dv], (list, tuple)) and defaults[dv] and isinstance(defaults[dv][0], dict):
2373 defaults[dv] = [(0, 0, x) for x in defaults[dv]]
2374 defaults.update(values)
2378 def clear_caches(self):
2379 """ Clear the caches
2381 This clears the caches associated to methods decorated with
2382 ``tools.ormcache`` or ``tools.ormcache_multi``.
2385 getattr(self, '_ormcache')
2387 except AttributeError:
2391 def _read_group_fill_results(self, cr, uid, domain, groupby, groupby_list, aggregated_fields,
2392 read_group_result, read_group_order=None, context=None):
2393 """Helper method for filling in empty groups for all possible values of
2394 the field being grouped by"""
2396 # self._group_by_full should map groupable fields to a method that returns
2397 # a list of all aggregated values that we want to display for this field,
2398 # in the form of a m2o-like pair (key,label).
2399 # This is useful to implement kanban views for instance, where all columns
2400 # should be displayed even if they don't contain any record.
2402 # Grab the list of all groups that should be displayed, including all present groups
2403 present_group_ids = [x[groupby][0] for x in read_group_result if x[groupby]]
2404 all_groups = self._group_by_full[groupby](self, cr, uid, present_group_ids, domain,
2405 read_group_order=read_group_order,
2406 access_rights_uid=openerp.SUPERUSER_ID,
2409 result_template = dict.fromkeys(aggregated_fields, False)
2410 result_template.update({groupby + '_count':0})
2411 if groupby_list and len(groupby_list) > 1:
2412 result_template.update(__context={'group_by': groupby_list[1:]})
2414 # Merge the left_side (current results as dicts) with the right_side (all
2415 # possible values as m2o pairs). Both lists are supposed to be using the
2416 # same ordering, and can be merged in one pass.
2419 def append_left(left_side):
2420 grouped_value = left_side[groupby] and left_side[groupby][0]
2421 if not grouped_value in known_values:
2422 result.append(left_side)
2423 known_values[grouped_value] = left_side
2425 count_attr = groupby + '_count'
2426 known_values[grouped_value].update({count_attr: left_side[count_attr]})
2427 def append_right(right_side):
2428 grouped_value = right_side[0]
2429 if not grouped_value in known_values:
2430 line = dict(result_template)
2432 groupby: right_side,
2433 '__domain': [(groupby,'=',grouped_value)] + domain,
2436 known_values[grouped_value] = line
2437 while read_group_result or all_groups:
2438 left_side = read_group_result[0] if read_group_result else None
2439 right_side = all_groups[0] if all_groups else None
2440 assert left_side is None or left_side[groupby] is False \
2441 or isinstance(left_side[groupby], (tuple,list)), \
2442 'M2O-like pair expected, got %r' % left_side[groupby]
2443 assert right_side is None or isinstance(right_side, (tuple,list)), \
2444 'M2O-like pair expected, got %r' % right_side
2445 if left_side is None:
2446 append_right(all_groups.pop(0))
2447 elif right_side is None:
2448 append_left(read_group_result.pop(0))
2449 elif left_side[groupby] == right_side:
2450 append_left(read_group_result.pop(0))
2451 all_groups.pop(0) # discard right_side
2452 elif not left_side[groupby] or not left_side[groupby][0]:
2453 # left side == "Undefined" entry, not present on right_side
2454 append_left(read_group_result.pop(0))
2456 append_right(all_groups.pop(0))
2459 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False):
2461 Get the list of records in list view grouped by the given ``groupby`` fields
2463 :param cr: database cursor
2464 :param uid: current user id
2465 :param domain: list specifying search criteria [['field_name', 'operator', 'value'], ...]
2466 :param list fields: list of fields present in the list view specified on the object
2467 :param list groupby: fields by which the records will be grouped
2468 :param int offset: optional number of records to skip
2469 :param int limit: optional max number of records to return
2470 :param dict context: context arguments, like lang, time zone
2471 :param list orderby: optional ``order by`` specification, for
2472 overriding the natural sort ordering of the
2473 groups, see also :py:meth:`~osv.osv.osv.search`
2474 (supported only for many2one fields currently)
2475 :return: list of dictionaries(one dictionary for each record) containing:
2477 * the values of fields grouped by the fields in ``groupby`` argument
2478 * __domain: list of tuples specifying the search criteria
2479 * __context: dictionary with argument like ``groupby``
2480 :rtype: [{'field_name_1': value, ...]
2481 :raise AccessError: * if user has no read rights on the requested object
2482 * if user tries to bypass access rules for read on the requested object
2485 context = context or {}
2486 self.check_read(cr, uid)
2488 fields = self._columns.keys()
2490 query = self._where_calc(cr, uid, domain, context=context)
2491 self._apply_ir_rules(cr, uid, query, 'read', context=context)
2493 # Take care of adding join(s) if groupby is an '_inherits'ed field
2494 groupby_list = groupby
2495 qualified_groupby_field = groupby
2497 if isinstance(groupby, list):
2498 groupby = groupby[0]
2499 qualified_groupby_field = self._inherits_join_calc(groupby, query)
2502 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?)"
2503 groupby_def = self._columns.get(groupby) or (self._inherit_fields.get(groupby) and self._inherit_fields.get(groupby)[2])
2504 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"
2506 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
2507 fget = self.fields_get(cr, uid, fields)
2509 group_count = group_by = groupby
2511 if fget.get(groupby):
2512 groupby_type = fget[groupby]['type']
2513 if groupby_type in ('date', 'datetime'):
2514 qualified_groupby_field = "to_char(%s,'yyyy-mm')" % qualified_groupby_field
2515 flist = "%s as %s " % (qualified_groupby_field, groupby)
2516 elif groupby_type == 'boolean':
2517 qualified_groupby_field = "coalesce(%s,false)" % qualified_groupby_field
2518 flist = "%s as %s " % (qualified_groupby_field, groupby)
2520 flist = qualified_groupby_field
2522 # Don't allow arbitrary values, as this would be a SQL injection vector!
2523 raise except_orm(_('Invalid group_by'),
2524 _('Invalid group_by specification: "%s".\nA group_by specification must be a list of valid fields.')%(groupby,))
2526 aggregated_fields = [
2528 if f not in ('id', 'sequence')
2529 if fget[f]['type'] in ('integer', 'float')
2530 if (f in self._columns and getattr(self._columns[f], '_classic_write'))]
2531 for f in aggregated_fields:
2532 group_operator = fget[f].get('group_operator', 'sum')
2535 qualified_field = '"%s"."%s"' % (self._table, f)
2536 flist += "%s(%s) AS %s" % (group_operator, qualified_field, f)
2538 gb = groupby and (' GROUP BY ' + qualified_groupby_field) or ''
2540 from_clause, where_clause, where_clause_params = query.get_sql()
2541 where_clause = where_clause and ' WHERE ' + where_clause
2542 limit_str = limit and ' limit %d' % limit or ''
2543 offset_str = offset and ' offset %d' % offset or ''
2544 if len(groupby_list) < 2 and context.get('group_by_no_leaf'):
2546 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)
2549 for r in cr.dictfetchall():
2550 for fld, val in r.items():
2551 if val == None: r[fld] = False
2552 alldata[r['id']] = r
2555 order = orderby or groupby
2556 data_ids = self.search(cr, uid, [('id', 'in', alldata.keys())], order=order, context=context)
2557 # the IDS of records that have groupby field value = False or '' should be sorted too
2558 data_ids += filter(lambda x:x not in data_ids, alldata.keys())
2559 data = self.read(cr, uid, data_ids, groupby and [groupby] or ['id'], context=context)
2560 # 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):
2561 data.sort(lambda x,y: cmp(data_ids.index(x['id']), data_ids.index(y['id'])))
2565 d['__domain'] = [(groupby, '=', alldata[d['id']][groupby] or False)] + domain
2566 if not isinstance(groupby_list, (str, unicode)):
2567 if groupby or not context.get('group_by_no_leaf', False):
2568 d['__context'] = {'group_by': groupby_list[1:]}
2569 if groupby and groupby in fget:
2570 if d[groupby] and fget[groupby]['type'] in ('date', 'datetime'):
2571 dt = datetime.datetime.strptime(alldata[d['id']][groupby][:7], '%Y-%m')
2572 days = calendar.monthrange(dt.year, dt.month)[1]
2574 d[groupby] = datetime.datetime.strptime(d[groupby][:10], '%Y-%m-%d').strftime('%B %Y')
2575 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),\
2576 (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
2577 del alldata[d['id']][groupby]
2578 d.update(alldata[d['id']])
2581 if groupby and groupby in self._group_by_full:
2582 data = self._read_group_fill_results(cr, uid, domain, groupby, groupby_list,
2583 aggregated_fields, data, read_group_order=order,
2588 def _inherits_join_add(self, current_table, parent_model_name, query):
2590 Add missing table SELECT and JOIN clause to ``query`` for reaching the parent table (no duplicates)
2591 :param current_table: current model object
2592 :param parent_model_name: name of the parent model for which the clauses should be added
2593 :param query: query object on which the JOIN should be added
2595 inherits_field = current_table._inherits[parent_model_name]
2596 parent_model = self.pool.get(parent_model_name)
2597 parent_table_name = parent_model._table
2598 quoted_parent_table_name = '"%s"' % parent_table_name
2599 if quoted_parent_table_name not in query.tables:
2600 query.tables.append(quoted_parent_table_name)
2601 query.where_clause.append('(%s.%s = %s.id)' % (current_table._table, inherits_field, parent_table_name))
2605 def _inherits_join_calc(self, field, query):
2607 Adds missing table select and join clause(s) to ``query`` for reaching
2608 the field coming from an '_inherits' parent table (no duplicates).
2610 :param field: name of inherited field to reach
2611 :param query: query object on which the JOIN should be added
2612 :return: qualified name of field, to be used in SELECT clause
2614 current_table = self
2615 while field in current_table._inherit_fields and not field in current_table._columns:
2616 parent_model_name = current_table._inherit_fields[field][0]
2617 parent_table = self.pool.get(parent_model_name)
2618 self._inherits_join_add(current_table, parent_model_name, query)
2619 current_table = parent_table
2620 return '"%s".%s' % (current_table._table, field)
2622 def _parent_store_compute(self, cr):
2623 if not self._parent_store:
2625 _logger.info('Computing parent left and right for table %s...', self._table)
2626 def browse_rec(root, pos=0):
2628 where = self._parent_name+'='+str(root)
2630 where = self._parent_name+' IS NULL'
2631 if self._parent_order:
2632 where += ' order by '+self._parent_order
2633 cr.execute('SELECT id FROM '+self._table+' WHERE '+where)
2635 for id in cr.fetchall():
2636 pos2 = browse_rec(id[0], pos2)
2637 cr.execute('update '+self._table+' set parent_left=%s, parent_right=%s where id=%s', (pos, pos2, root))
2639 query = 'SELECT id FROM '+self._table+' WHERE '+self._parent_name+' IS NULL'
2640 if self._parent_order:
2641 query += ' order by ' + self._parent_order
2644 for (root,) in cr.fetchall():
2645 pos = browse_rec(root, pos)
2648 def _update_store(self, cr, f, k):
2649 _logger.info("storing computed values of fields.function '%s'", k)
2650 ss = self._columns[k]._symbol_set
2651 update_query = 'UPDATE "%s" SET "%s"=%s WHERE id=%%s' % (self._table, k, ss[0])
2652 cr.execute('select id from '+self._table)
2653 ids_lst = map(lambda x: x[0], cr.fetchall())
2656 ids_lst = ids_lst[40:]
2657 res = f.get(cr, self, iids, k, SUPERUSER_ID, {})
2658 for key, val in res.items():
2661 # if val is a many2one, just write the ID
2662 if type(val) == tuple:
2664 if (val<>False) or (type(val)<>bool):
2665 cr.execute(update_query, (ss[1](val), key))
2667 def _check_selection_field_value(self, cr, uid, field, value, context=None):
2668 """Raise except_orm if value is not among the valid values for the selection field"""
2669 if self._columns[field]._type == 'reference':
2670 val_model, val_id_str = value.split(',', 1)
2673 val_id = long(val_id_str)
2677 raise except_orm(_('ValidateError'),
2678 _('Invalid value for reference field "%s.%s" (last part must be a non-zero integer): "%s"') % (self._table, field, value))
2682 if isinstance(self._columns[field].selection, (tuple, list)):
2683 if val in dict(self._columns[field].selection):
2685 elif val in dict(self._columns[field].selection(self, cr, uid, context=context)):
2687 raise except_orm(_('ValidateError'),
2688 _('The value "%s" for the field "%s.%s" is not in the selection') % (value, self._table, field))
2690 def _check_removed_columns(self, cr, log=False):
2691 # iterate on the database columns to drop the NOT NULL constraints
2692 # of fields which were required but have been removed (or will be added by another module)
2693 columns = [c for c in self._columns if not (isinstance(self._columns[c], fields.function) and not self._columns[c].store)]
2694 columns += MAGIC_COLUMNS
2695 cr.execute("SELECT a.attname, a.attnotnull"
2696 " FROM pg_class c, pg_attribute a"
2697 " WHERE c.relname=%s"
2698 " AND c.oid=a.attrelid"
2699 " AND a.attisdropped=%s"
2700 " AND pg_catalog.format_type(a.atttypid, a.atttypmod) NOT IN ('cid', 'tid', 'oid', 'xid')"
2701 " AND a.attname NOT IN %s", (self._table, False, tuple(columns))),
2703 for column in cr.dictfetchall():
2705 _logger.debug("column %s is in the table %s but not in the corresponding object %s",
2706 column['attname'], self._table, self._name)
2707 if column['attnotnull']:
2708 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, column['attname']))
2709 _schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
2710 self._table, column['attname'])
2712 # checked version: for direct m2o starting from `self`
2713 def _m2o_add_foreign_key_checked(self, source_field, dest_model, ondelete):
2714 assert self.is_transient() or not dest_model.is_transient(), \
2715 'Many2One relationships from non-transient Model to TransientModel are forbidden'
2716 if self.is_transient() and not dest_model.is_transient():
2717 # TransientModel relationships to regular Models are annoying
2718 # usually because they could block deletion due to the FKs.
2719 # So unless stated otherwise we default them to ondelete=cascade.
2720 ondelete = ondelete or 'cascade'
2721 self._foreign_keys.append((self._table, source_field, dest_model._table, ondelete or 'set null'))
2722 _schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s",
2723 self._table, source_field, dest_model._table, ondelete)
2725 # unchecked version: for custom cases, such as m2m relationships
2726 def _m2o_add_foreign_key_unchecked(self, source_table, source_field, dest_model, ondelete):
2727 self._foreign_keys.append((source_table, source_field, dest_model._table, ondelete or 'set null'))
2728 _schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s",
2729 source_table, source_field, dest_model._table, ondelete)
2731 def _auto_init(self, cr, context=None):
2734 Call _field_create and, unless _auto is False:
2736 - create the corresponding table in database for the model,
2737 - possibly add the parent columns in database,
2738 - possibly add the columns 'create_uid', 'create_date', 'write_uid',
2739 'write_date' in database if _log_access is True (the default),
2740 - report on database columns no more existing in _columns,
2741 - remove no more existing not null constraints,
2742 - alter existing database columns to match _columns,
2743 - create database tables to match _columns,
2744 - add database indices to match _columns,
2745 - save in self._foreign_keys a list a foreign keys to create (see
2749 self._foreign_keys = []
2750 raise_on_invalid_object_name(self._name)
2753 store_compute = False
2755 update_custom_fields = context.get('update_custom_fields', False)
2756 self._field_create(cr, context=context)
2757 create = not self._table_exist(cr)
2759 if getattr(self, '_auto', True):
2762 self._create_table(cr)
2765 if self._parent_store:
2766 if not self._parent_columns_exist(cr):
2767 self._create_parent_columns(cr)
2768 store_compute = True
2770 # Create the create_uid, create_date, write_uid, write_date, columns if desired.
2771 if self._log_access:
2772 self._add_log_columns(cr)
2774 self._check_removed_columns(cr, log=False)
2776 # iterate on the "object columns"
2777 column_data = self._select_column_data(cr)
2779 for k, f in self._columns.iteritems():
2780 if k in MAGIC_COLUMNS:
2782 # Don't update custom (also called manual) fields
2783 if f.manual and not update_custom_fields:
2786 if isinstance(f, fields.one2many):
2787 self._o2m_raise_on_missing_reference(cr, f)
2789 elif isinstance(f, fields.many2many):
2790 self._m2m_raise_or_create_relation(cr, f)
2793 res = column_data.get(k)
2795 # The field is not found as-is in database, try if it
2796 # exists with an old name.
2797 if not res and hasattr(f, 'oldname'):
2798 res = column_data.get(f.oldname)
2800 cr.execute('ALTER TABLE "%s" RENAME "%s" TO "%s"' % (self._table, f.oldname, k))
2802 column_data[k] = res
2803 _schema.debug("Table '%s': renamed column '%s' to '%s'",
2804 self._table, f.oldname, k)
2806 # The field already exists in database. Possibly
2807 # change its type, rename it, drop it or change its
2810 f_pg_type = res['typname']
2811 f_pg_size = res['size']
2812 f_pg_notnull = res['attnotnull']
2813 if isinstance(f, fields.function) and not f.store and\
2814 not getattr(f, 'nodrop', False):
2815 _logger.info('column %s (%s) in table %s removed: converted to a function !\n',
2816 k, f.string, self._table)
2817 cr.execute('ALTER TABLE "%s" DROP COLUMN "%s" CASCADE' % (self._table, k))
2819 _schema.debug("Table '%s': dropped column '%s' with cascade",
2823 f_obj_type = get_pg_type(f) and get_pg_type(f)[0]
2828 ('text', 'char', pg_varchar(f.size), '::%s' % pg_varchar(f.size)),
2829 ('varchar', 'text', 'TEXT', ''),
2830 ('int4', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
2831 ('date', 'datetime', 'TIMESTAMP', '::TIMESTAMP'),
2832 ('timestamp', 'date', 'date', '::date'),
2833 ('numeric', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
2834 ('float8', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
2836 if f_pg_type == 'varchar' and f._type == 'char' and f_pg_size < f.size:
2837 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
2838 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, pg_varchar(f.size)))
2839 cr.execute('UPDATE "%s" SET "%s"=temp_change_size::%s' % (self._table, k, pg_varchar(f.size)))
2840 cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
2842 _schema.debug("Table '%s': column '%s' (type varchar) changed size from %s to %s",
2843 self._table, k, f_pg_size, f.size)
2845 if (f_pg_type==c[0]) and (f._type==c[1]):
2846 if f_pg_type != f_obj_type:
2848 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
2849 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, c[2]))
2850 cr.execute(('UPDATE "%s" SET "%s"=temp_change_size'+c[3]) % (self._table, k))
2851 cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
2853 _schema.debug("Table '%s': column '%s' changed type from %s to %s",
2854 self._table, k, c[0], c[1])
2857 if f_pg_type != f_obj_type:
2861 newname = k + '_moved' + str(i)
2862 cr.execute("SELECT count(1) FROM pg_class c,pg_attribute a " \
2863 "WHERE c.relname=%s " \
2864 "AND a.attname=%s " \
2865 "AND c.oid=a.attrelid ", (self._table, newname))
2866 if not cr.fetchone()[0]:
2870 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
2871 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO "%s"' % (self._table, k, newname))
2872 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
2873 cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,))
2874 _schema.debug("Table '%s': column '%s' has changed type (DB=%s, def=%s), data moved to column %s !",
2875 self._table, k, f_pg_type, f._type, newname)
2877 # if the field is required and hasn't got a NOT NULL constraint
2878 if f.required and f_pg_notnull == 0:
2879 # set the field to the default value if any
2880 if k in self._defaults:
2881 if callable(self._defaults[k]):
2882 default = self._defaults[k](self, cr, SUPERUSER_ID, context)
2884 default = self._defaults[k]
2886 if (default is not None):
2887 ss = self._columns[k]._symbol_set
2888 query = 'UPDATE "%s" SET "%s"=%s WHERE "%s" is NULL' % (self._table, k, ss[0], k)
2889 cr.execute(query, (ss[1](default),))
2890 # add the NOT NULL constraint
2893 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False)
2895 _schema.debug("Table '%s': column '%s': added NOT NULL constraint",
2898 msg = "Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\
2899 "If you want to have it, you should update the records and execute manually:\n"\
2900 "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
2901 _schema.warning(msg, self._table, k, self._table, k)
2903 elif not f.required and f_pg_notnull == 1:
2904 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
2906 _schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
2909 indexname = '%s_%s_index' % (self._table, k)
2910 cr.execute("SELECT indexname FROM pg_indexes WHERE indexname = %s and tablename = %s", (indexname, self._table))
2911 res2 = cr.dictfetchall()
2912 if not res2 and f.select:
2913 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
2915 if f._type == 'text':
2916 # FIXME: for fields.text columns we should try creating GIN indexes instead (seems most suitable for an ERP context)
2917 msg = "Table '%s': Adding (b-tree) index for text column '%s'."\
2918 "This is probably useless (does not work for fulltext search) and prevents INSERTs of long texts"\
2919 " because there is a length limit for indexable btree values!\n"\
2920 "Use a search view instead if you simply want to make the field searchable."
2921 _schema.warning(msg, self._table, k, f._type)
2922 if res2 and not f.select:
2923 cr.execute('DROP INDEX "%s_%s_index"' % (self._table, k))
2925 msg = "Table '%s': dropping index for column '%s' of type '%s' as it is not required anymore"
2926 _schema.debug(msg, self._table, k, f._type)
2928 if isinstance(f, fields.many2one):
2929 dest_model = self.pool.get(f._obj)
2930 ref = dest_model._table
2931 if ref != 'ir_actions':
2932 cr.execute('SELECT confdeltype, conname FROM pg_constraint as con, pg_class as cl1, pg_class as cl2, '
2933 'pg_attribute as att1, pg_attribute as att2 '
2934 'WHERE con.conrelid = cl1.oid '
2935 'AND cl1.relname = %s '
2936 'AND con.confrelid = cl2.oid '
2937 'AND cl2.relname = %s '
2938 'AND array_lower(con.conkey, 1) = 1 '
2939 'AND con.conkey[1] = att1.attnum '
2940 'AND att1.attrelid = cl1.oid '
2941 'AND att1.attname = %s '
2942 'AND array_lower(con.confkey, 1) = 1 '
2943 'AND con.confkey[1] = att2.attnum '
2944 'AND att2.attrelid = cl2.oid '
2945 'AND att2.attname = %s '
2946 "AND con.contype = 'f'", (self._table, ref, k, 'id'))
2947 res2 = cr.dictfetchall()
2949 if res2[0]['confdeltype'] != POSTGRES_CONFDELTYPES.get((f.ondelete or 'set null').upper(), 'a'):
2950 cr.execute('ALTER TABLE "' + self._table + '" DROP CONSTRAINT "' + res2[0]['conname'] + '"')
2951 self._m2o_add_foreign_key_checked(k, dest_model, f.ondelete)
2953 _schema.debug("Table '%s': column '%s': XXX",
2956 # The field doesn't exist in database. Create it if necessary.
2958 if not isinstance(f, fields.function) or f.store:
2959 # add the missing field
2960 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
2961 cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,))
2962 _schema.debug("Table '%s': added column '%s' with definition=%s",
2963 self._table, k, get_pg_type(f)[1])
2966 if not create and k in self._defaults:
2967 if callable(self._defaults[k]):
2968 default = self._defaults[k](self, cr, SUPERUSER_ID, context)
2970 default = self._defaults[k]
2972 ss = self._columns[k]._symbol_set
2973 query = 'UPDATE "%s" SET "%s"=%s' % (self._table, k, ss[0])
2974 cr.execute(query, (ss[1](default),))
2976 _logger.debug("Table '%s': setting default value of new column %s", self._table, k)
2978 # remember the functions to call for the stored fields
2979 if isinstance(f, fields.function):
2981 if f.store is not True: # i.e. if f.store is a dict
2982 order = f.store[f.store.keys()[0]][2]
2983 todo_end.append((order, self._update_store, (f, k)))
2985 # and add constraints if needed
2986 if isinstance(f, fields.many2one):
2987 if not self.pool.get(f._obj):
2988 raise except_orm('Programming Error', ('There is no reference available for %s') % (f._obj,))
2989 dest_model = self.pool.get(f._obj)
2990 ref = dest_model._table
2991 # ir_actions is inherited so foreign key doesn't work on it
2992 if ref != 'ir_actions':
2993 self._m2o_add_foreign_key_checked(k, dest_model, f.ondelete)
2995 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
2999 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False)
3000 _schema.debug("Table '%s': column '%s': added a NOT NULL constraint",
3003 msg = "WARNING: unable to set column %s of table %s not null !\n"\
3004 "Try to re-run: openerp-server --update=module\n"\
3005 "If it doesn't work, update records and execute manually:\n"\
3006 "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
3007 _logger.warning(msg, k, self._table, self._table, k)
3011 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
3012 create = not bool(cr.fetchone())
3014 cr.commit() # start a new transaction
3016 self._add_sql_constraints(cr)
3019 self._execute_sql(cr)
3022 self._parent_store_compute(cr)
3028 def _auto_end(self, cr, context=None):
3029 """ Create the foreign keys recorded by _auto_init. """
3030 for t, k, r, d in self._foreign_keys:
3031 cr.execute('ALTER TABLE "%s" ADD FOREIGN KEY ("%s") REFERENCES "%s" ON DELETE %s' % (t, k, r, d))
3033 del self._foreign_keys
3036 def _table_exist(self, cr):
3037 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
3041 def _create_table(self, cr):
3042 cr.execute('CREATE TABLE "%s" (id SERIAL NOT NULL, PRIMARY KEY(id)) WITHOUT OIDS' % (self._table,))
3043 cr.execute(("COMMENT ON TABLE \"%s\" IS %%s" % self._table), (self._description,))
3044 _schema.debug("Table '%s': created", self._table)
3047 def _parent_columns_exist(self, cr):
3048 cr.execute("""SELECT c.relname
3049 FROM pg_class c, pg_attribute a
3050 WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
3051 """, (self._table, 'parent_left'))
3055 def _create_parent_columns(self, cr):
3056 cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_left" INTEGER' % (self._table,))
3057 cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_right" INTEGER' % (self._table,))
3058 if 'parent_left' not in self._columns:
3059 _logger.error('create a column parent_left on object %s: fields.integer(\'Left Parent\', select=1)',
3061 _schema.debug("Table '%s': added column '%s' with definition=%s",
3062 self._table, 'parent_left', 'INTEGER')
3063 elif not self._columns['parent_left'].select:
3064 _logger.error('parent_left column on object %s must be indexed! Add select=1 to the field definition)',
3066 if 'parent_right' not in self._columns:
3067 _logger.error('create a column parent_right on object %s: fields.integer(\'Right Parent\', select=1)',
3069 _schema.debug("Table '%s': added column '%s' with definition=%s",
3070 self._table, 'parent_right', 'INTEGER')
3071 elif not self._columns['parent_right'].select:
3072 _logger.error('parent_right column on object %s must be indexed! Add select=1 to the field definition)',
3074 if self._columns[self._parent_name].ondelete != 'cascade':
3075 _logger.error("The column %s on object %s must be set as ondelete='cascade'",
3076 self._parent_name, self._name)
3081 def _add_log_columns(self, cr):
3082 for field, field_def in LOG_ACCESS_COLUMNS.iteritems():
3085 FROM pg_class c, pg_attribute a
3086 WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
3087 """, (self._table, field))
3089 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, field, field_def))
3091 _schema.debug("Table '%s': added column '%s' with definition=%s",
3092 self._table, field, field_def)
3095 def _select_column_data(self, cr):
3096 # attlen is the number of bytes necessary to represent the type when
3097 # the type has a fixed size. If the type has a varying size attlen is
3098 # -1 and atttypmod is the size limit + 4, or -1 if there is no limit.
3099 # Thus the query can return a negative size for a unlimited varchar.
3100 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 " \
3101 "FROM pg_class c,pg_attribute a,pg_type t " \
3102 "WHERE c.relname=%s " \
3103 "AND c.oid=a.attrelid " \
3104 "AND a.atttypid=t.oid", (self._table,))
3105 return dict(map(lambda x: (x['attname'], x),cr.dictfetchall()))
3108 def _o2m_raise_on_missing_reference(self, cr, f):
3109 # TODO this check should be a method on fields.one2many.
3110 other = self.pool.get(f._obj)
3112 # TODO the condition could use fields_get_keys().
3113 if f._fields_id not in other._columns.keys():
3114 if f._fields_id not in other._inherit_fields.keys():
3115 raise except_orm('Programming Error', ("There is no reference field '%s' found for '%s'") % (f._fields_id, f._obj,))
3118 def _m2m_raise_or_create_relation(self, cr, f):
3119 m2m_tbl, col1, col2 = f._sql_names(self)
3120 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (m2m_tbl,))
3121 if not cr.dictfetchall():
3122 if not self.pool.get(f._obj):
3123 raise except_orm('Programming Error', ('Many2Many destination model does not exist: `%s`') % (f._obj,))
3124 dest_model = self.pool.get(f._obj)
3125 ref = dest_model._table
3126 cr.execute('CREATE TABLE "%s" ("%s" INTEGER NOT NULL, "%s" INTEGER NOT NULL, UNIQUE("%s","%s")) WITH OIDS' % (m2m_tbl, col1, col2, col1, col2))
3128 # create foreign key references with ondelete=cascade, unless the targets are SQL views
3129 cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (ref,))
3130 if not cr.fetchall():
3131 self._m2o_add_foreign_key_unchecked(m2m_tbl, col2, dest_model, 'cascade')
3132 cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (self._table,))
3133 if not cr.fetchall():
3134 self._m2o_add_foreign_key_unchecked(m2m_tbl, col1, self, 'cascade')
3136 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col1, m2m_tbl, col1))
3137 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col2, m2m_tbl, col2))
3138 cr.execute("COMMENT ON TABLE \"%s\" IS 'RELATION BETWEEN %s AND %s'" % (m2m_tbl, self._table, ref))
3140 _schema.debug("Create table '%s': m2m relation between '%s' and '%s'", m2m_tbl, self._table, ref)
3143 def _add_sql_constraints(self, cr):
3146 Modify this model's database table constraints so they match the one in
3150 for (key, con, _) in self._sql_constraints:
3151 conname = '%s_%s' % (self._table, key)
3153 cr.execute("SELECT conname, pg_catalog.pg_get_constraintdef(oid, true) as condef FROM pg_constraint where conname=%s", (conname,))
3154 existing_constraints = cr.dictfetchall()
3159 'query': 'ALTER TABLE "%s" DROP CONSTRAINT "%s"' % (self._table, conname, ),
3160 'msg_ok': "Table '%s': dropped constraint '%s'. Reason: its definition changed from '%%s' to '%s'" % (
3161 self._table, conname, con),
3162 'msg_err': "Table '%s': unable to drop \'%s\' constraint !" % (self._table, con),
3167 'query': 'ALTER TABLE "%s" ADD CONSTRAINT "%s" %s' % (self._table, conname, con,),
3168 'msg_ok': "Table '%s': added constraint '%s' with definition=%s" % (self._table, conname, con),
3169 '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" % (
3175 if not existing_constraints:
3176 # constraint does not exists:
3177 sql_actions['add']['execute'] = True
3178 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
3179 elif con.lower() not in [item['condef'].lower() for item in existing_constraints]:
3180 # constraint exists but its definition has changed:
3181 sql_actions['drop']['execute'] = True
3182 sql_actions['drop']['msg_ok'] = sql_actions['drop']['msg_ok'] % (existing_constraints[0]['condef'].lower(), )
3183 sql_actions['add']['execute'] = True
3184 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
3186 # we need to add the constraint:
3187 sql_actions = [item for item in sql_actions.values()]
3188 sql_actions.sort(key=lambda x: x['order'])
3189 for sql_action in [action for action in sql_actions if action['execute']]:
3191 cr.execute(sql_action['query'])
3193 _schema.debug(sql_action['msg_ok'])
3195 _schema.warning(sql_action['msg_err'])
3199 def _execute_sql(self, cr):
3200 """ Execute the SQL code from the _sql attribute (if any)."""
3201 if hasattr(self, "_sql"):
3202 for line in self._sql.split(';'):
3203 line2 = line.replace('\n', '').strip()
3209 # Update objects that uses this one to update their _inherits fields
3212 def _inherits_reload_src(self):
3213 """ Recompute the _inherit_fields mapping on each _inherits'd child model."""
3214 for obj in self.pool.models.values():
3215 if self._name in obj._inherits:
3216 obj._inherits_reload()
3219 def _inherits_reload(self):
3220 """ Recompute the _inherit_fields mapping.
3222 This will also call itself on each inherits'd child model.
3226 for table in self._inherits:
3227 other = self.pool.get(table)
3228 for col in other._columns.keys():
3229 res[col] = (table, self._inherits[table], other._columns[col], table)
3230 for col in other._inherit_fields.keys():
3231 res[col] = (table, self._inherits[table], other._inherit_fields[col][2], other._inherit_fields[col][3])
3232 self._inherit_fields = res
3233 self._all_columns = self._get_column_infos()
3234 self._inherits_reload_src()
3237 def _get_column_infos(self):
3238 """Returns a dict mapping all fields names (direct fields and
3239 inherited field via _inherits) to a ``column_info`` struct
3240 giving detailed columns """
3242 for k, (parent, m2o, col, original_parent) in self._inherit_fields.iteritems():
3243 result[k] = fields.column_info(k, col, parent, m2o, original_parent)
3244 for k, col in self._columns.iteritems():
3245 result[k] = fields.column_info(k, col)
3249 def _inherits_check(self):
3250 for table, field_name in self._inherits.items():
3251 if field_name not in self._columns:
3252 _logger.info('Missing many2one field definition for _inherits reference "%s" in "%s", using default one.', field_name, self._name)
3253 self._columns[field_name] = fields.many2one(table, string="Automatically created field to link to parent %s" % table,
3254 required=True, ondelete="cascade")
3255 elif not self._columns[field_name].required or self._columns[field_name].ondelete.lower() != "cascade":
3256 _logger.warning('Field definition for _inherits reference "%s" in "%s" must be marked as "required" with ondelete="cascade", forcing it.', field_name, self._name)
3257 self._columns[field_name].required = True
3258 self._columns[field_name].ondelete = "cascade"
3260 #def __getattr__(self, name):
3262 # Proxies attribute accesses to the `inherits` parent so we can call methods defined on the inherited parent
3263 # (though inherits doesn't use Python inheritance).
3264 # Handles translating between local ids and remote ids.
3265 # Known issue: doesn't work correctly when using python's own super(), don't involve inherit-based inheritance
3266 # when you have inherits.
3268 # for model, field in self._inherits.iteritems():
3269 # proxy = self.pool.get(model)
3270 # if hasattr(proxy, name):
3271 # attribute = getattr(proxy, name)
3272 # if not hasattr(attribute, '__call__'):
3276 # return super(orm, self).__getattr__(name)
3278 # def _proxy(cr, uid, ids, *args, **kwargs):
3279 # objects = self.browse(cr, uid, ids, kwargs.get('context', None))
3280 # lst = [obj[field].id for obj in objects if obj[field]]
3281 # return getattr(proxy, name)(cr, uid, lst, *args, **kwargs)
3286 def fields_get(self, cr, user, allfields=None, context=None, write_access=True):
3287 """ Return the definition of each field.
3289 The returned value is a dictionary (indiced by field name) of
3290 dictionaries. The _inherits'd fields are included. The string, help,
3291 and selection (if present) attributes are translated.
3293 :param cr: database cursor
3294 :param user: current user id
3295 :param fields: list of fields
3296 :param context: context arguments, like lang, time zone
3297 :return: dictionary of field dictionaries, each one describing a field of the business object
3298 :raise AccessError: * if user has no create/write rights on the requested object
3304 write_access = self.check_write(cr, user, False) or \
3305 self.check_create(cr, user, False)
3309 translation_obj = self.pool.get('ir.translation')
3310 for parent in self._inherits:
3311 res.update(self.pool.get(parent).fields_get(cr, user, allfields, context))
3313 for f, field in self._columns.iteritems():
3314 if allfields and f not in allfields:
3317 res[f] = fields.field_to_dict(self, cr, user, field, context=context)
3319 if not write_access:
3320 res[f]['readonly'] = True
3321 res[f]['states'] = {}
3323 if 'string' in res[f]:
3324 res_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'field', context.get('lang', False) or 'en_US')
3326 res[f]['string'] = res_trans
3327 if 'help' in res[f]:
3328 help_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'help', context.get('lang', False) or 'en_US')
3330 res[f]['help'] = help_trans
3331 if 'selection' in res[f]:
3332 if isinstance(field.selection, (tuple, list)):
3333 sel = field.selection
3335 for key, val in sel:
3338 val2 = translation_obj._get_source(cr, user, self._name + ',' + f, 'selection', context.get('lang', False) or 'en_US', val)
3339 sel2.append((key, val2 or val))
3340 res[f]['selection'] = sel2
3344 def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
3345 """ Read records with given ids with the given fields
3347 :param cr: database cursor
3348 :param user: current user id
3349 :param ids: id or list of the ids of the records to read
3350 :param fields: optional list of field names to return (default: all fields would be returned)
3351 :type fields: list (example ['field_name_1', ...])
3352 :param context: optional context dictionary - it may contains keys for specifying certain options
3353 like ``context_lang``, ``context_tz`` to alter the results of the call.
3354 A special ``bin_size`` boolean flag may also be passed in the context to request the
3355 value of all fields.binary columns to be returned as the size of the binary instead of its
3356 contents. This can also be selectively overriden by passing a field-specific flag
3357 in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field.
3358 Note: The ``bin_size_XXX`` form is new in OpenERP v6.0.
3359 :return: list of dictionaries((dictionary per record asked)) with requested field values
3360 :rtype: [{‘name_of_the_field’: value, ...}, ...]
3361 :raise AccessError: * if user has no read rights on the requested object
3362 * if user tries to bypass access rules for read on the requested object
3368 self.check_read(cr, user)
3370 fields = list(set(self._columns.keys() + self._inherit_fields.keys()))
3371 if isinstance(ids, (int, long)):
3375 select = map(lambda x: isinstance(x, dict) and x['id'] or x, select)
3376 result = self._read_flat(cr, user, select, fields, context, load)
3379 for key, v in r.items():
3383 if isinstance(ids, (int, long, dict)):
3384 return result and result[0] or False
3387 def _read_flat(self, cr, user, ids, fields_to_read, context=None, load='_classic_read'):
3392 if fields_to_read == None:
3393 fields_to_read = self._columns.keys()
3395 # Construct a clause for the security rules.
3396 # 'tables' hold the list of tables necessary for the SELECT including the ir.rule clauses,
3397 # or will at least contain self._table.
3398 rule_clause, rule_params, tables = self.pool.get('ir.rule').domain_get(cr, user, self._name, 'read', context=context)
3400 # all inherited fields + all non inherited fields for which the attribute whose name is in load is True
3401 fields_pre = [f for f in fields_to_read if
3402 f == self.CONCURRENCY_CHECK_FIELD
3403 or (f in self._columns and getattr(self._columns[f], '_classic_write'))
3404 ] + self._inherits.values()
3408 def convert_field(f):
3409 f_qual = '%s."%s"' % (self._table, f) # need fully-qualified references in case len(tables) > 1
3410 if f in ('create_date', 'write_date'):
3411 return "date_trunc('second', %s) as %s" % (f_qual, f)
3412 if f == self.CONCURRENCY_CHECK_FIELD:
3413 if self._log_access:
3414 return "COALESCE(%s.write_date, %s.create_date, now())::timestamp AS %s" % (self._table, self._table, f,)
3415 return "now()::timestamp AS %s" % (f,)
3416 if isinstance(self._columns[f], fields.binary) and context.get('bin_size', False):
3417 return 'length(%s) as "%s"' % (f_qual, f)
3420 fields_pre2 = map(convert_field, fields_pre)
3421 order_by = self._parent_order or self._order
3422 select_fields = ','.join(fields_pre2 + [self._table + '.id'])
3423 query = 'SELECT %s FROM %s WHERE %s.id IN %%s' % (select_fields, ','.join(tables), self._table)
3425 query += " AND " + (' OR '.join(rule_clause))
3426 query += " ORDER BY " + order_by
3427 for sub_ids in cr.split_for_in_conditions(ids):
3429 cr.execute(query, [tuple(sub_ids)] + rule_params)
3430 if cr.rowcount != len(sub_ids):
3431 raise except_orm(_('AccessError'),
3432 _('Operation prohibited by access rules, or performed on an already deleted document (Operation: read, Document type: %s).')
3433 % (self._description,))
3435 cr.execute(query, (tuple(sub_ids),))
3436 res.extend(cr.dictfetchall())
3438 res = map(lambda x: {'id': x}, ids)
3440 for f in fields_pre:
3441 if f == self.CONCURRENCY_CHECK_FIELD:
3443 if self._columns[f].translate:
3444 ids = [x['id'] for x in res]
3445 #TODO: optimize out of this loop
3446 res_trans = self.pool.get('ir.translation')._get_ids(cr, user, self._name+','+f, 'model', context.get('lang', False) or 'en_US', ids)
3448 r[f] = res_trans.get(r['id'], False) or r[f]
3450 for table in self._inherits:
3451 col = self._inherits[table]
3452 cols = [x for x in intersect(self._inherit_fields.keys(), fields_to_read) if x not in self._columns.keys()]
3455 res2 = self.pool.get(table).read(cr, user, [x[col] for x in res], cols, context, load)
3463 if not record[col]: # if the record is deleted from _inherits table?
3465 record.update(res3[record[col]])
3466 if col not in fields_to_read:
3469 # all fields which need to be post-processed by a simple function (symbol_get)
3470 fields_post = filter(lambda x: x in self._columns and self._columns[x]._symbol_get, fields_to_read)
3473 for f in fields_post:
3474 r[f] = self._columns[f]._symbol_get(r[f])
3475 ids = [x['id'] for x in res]
3477 # all non inherited fields for which the attribute whose name is in load is False
3478 fields_post = filter(lambda x: x in self._columns and not getattr(self._columns[x], load), fields_to_read)
3480 # Compute POST fields
3482 for f in fields_post:
3483 todo.setdefault(self._columns[f]._multi, [])
3484 todo[self._columns[f]._multi].append(f)
3485 for key, val in todo.items():
3487 res2 = self._columns[val[0]].get(cr, self, ids, val, user, context=context, values=res)
3488 assert res2 is not None, \
3489 'The function field "%s" on the "%s" model returned None\n' \
3490 '(a dictionary was expected).' % (val[0], self._name)
3493 if isinstance(res2[record['id']], str): res2[record['id']] = eval(res2[record['id']]) #TOCHECK : why got string instend of dict in python2.6
3494 multi_fields = res2.get(record['id'],{})
3496 record[pos] = multi_fields.get(pos,[])
3499 res2 = self._columns[f].get(cr, self, ids, f, user, context=context, values=res)
3502 record[f] = res2[record['id']]
3507 for field in vals.copy():
3509 if field in self._columns:
3510 fobj = self._columns[field]
3517 for group in groups:
3518 module = group.split(".")[0]
3519 grp = group.split(".")[1]
3520 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", \
3521 (grp, module, 'res.groups', user))
3522 readonly = cr.fetchall()
3523 if readonly[0][0] >= 1:
3526 elif readonly[0][0] == 0:
3532 if type(vals[field]) == type([]):
3534 elif type(vals[field]) == type(0.0):
3536 elif type(vals[field]) == type(''):
3537 vals[field] = '=No Permission='
3542 # TODO check READ access
3543 def perm_read(self, cr, user, ids, context=None, details=True):
3545 Returns some metadata about the given records.
3547 :param details: if True, \*_uid fields are replaced with the name of the user
3548 :return: list of ownership dictionaries for each requested record
3549 :rtype: list of dictionaries with the following keys:
3552 * create_uid: user who created the record
3553 * create_date: date when the record was created
3554 * write_uid: last user who changed the record
3555 * write_date: date of the last change to the record
3556 * xmlid: XML ID to use to refer to this record (if there is one), in format ``module.name``
3563 uniq = isinstance(ids, (int, long))
3567 if self._log_access:
3568 fields += ['create_uid', 'create_date', 'write_uid', 'write_date']
3569 quoted_table = '"%s"' % self._table
3570 fields_str = ",".join('%s.%s'%(quoted_table, field) for field in fields)
3571 query = '''SELECT %s, __imd.module, __imd.name
3572 FROM %s LEFT JOIN ir_model_data __imd
3573 ON (__imd.model = %%s and __imd.res_id = %s.id)
3574 WHERE %s.id IN %%s''' % (fields_str, quoted_table, quoted_table, quoted_table)
3575 cr.execute(query, (self._name, tuple(ids)))
3576 res = cr.dictfetchall()
3579 r[key] = r[key] or False
3580 if details and key in ('write_uid', 'create_uid') and r[key]:
3582 r[key] = self.pool.get('res.users').name_get(cr, user, [r[key]])[0]
3584 pass # Leave the numeric uid there
3585 r['xmlid'] = ("%(module)s.%(name)s" % r) if r['name'] else False
3586 del r['name'], r['module']
3591 def _check_concurrency(self, cr, ids, context):
3594 if not (context.get(self.CONCURRENCY_CHECK_FIELD) and self._log_access):
3596 check_clause = "(id = %s AND %s < COALESCE(write_date, create_date, now())::timestamp)"
3597 for sub_ids in cr.split_for_in_conditions(ids):
3600 id_ref = "%s,%s" % (self._name, id)
3601 update_date = context[self.CONCURRENCY_CHECK_FIELD].pop(id_ref, None)
3603 ids_to_check.extend([id, update_date])
3604 if not ids_to_check:
3606 cr.execute("SELECT id FROM %s WHERE %s" % (self._table, " OR ".join([check_clause]*(len(ids_to_check)/2))), tuple(ids_to_check))
3609 # mention the first one only to keep the error message readable
3610 raise except_orm('ConcurrencyException', _('A document was modified since you last viewed it (%s:%d)') % (self._description, res[0]))
3612 def check_access_rights(self, cr, uid, operation, raise_exception=True): # no context on purpose.
3613 """Verifies that the operation given by ``operation`` is allowed for the user
3614 according to the access rights."""
3615 return self.pool.get('ir.model.access').check(cr, uid, self._name, operation, raise_exception)
3617 def check_create(self, cr, uid, raise_exception=True):
3618 return self.check_access_rights(cr, uid, 'create', raise_exception)
3620 def check_read(self, cr, uid, raise_exception=True):
3621 return self.check_access_rights(cr, uid, 'read', raise_exception)
3623 def check_unlink(self, cr, uid, raise_exception=True):
3624 return self.check_access_rights(cr, uid, 'unlink', raise_exception)
3626 def check_write(self, cr, uid, raise_exception=True):
3627 return self.check_access_rights(cr, uid, 'write', raise_exception)
3629 def check_access_rule(self, cr, uid, ids, operation, context=None):
3630 """Verifies that the operation given by ``operation`` is allowed for the user
3631 according to ir.rules.
3633 :param operation: one of ``write``, ``unlink``
3634 :raise except_orm: * if current ir.rules do not permit this operation.
3635 :return: None if the operation is allowed
3637 if uid == SUPERUSER_ID:
3640 if self.is_transient():
3641 # Only one single implicit access rule for transient models: owner only!
3642 # This is ok to hardcode because we assert that TransientModels always
3643 # have log_access enabled and this the create_uid column is always there.
3644 # And even with _inherits, these fields are always present in the local
3645 # table too, so no need for JOINs.
3646 cr.execute("""SELECT distinct create_uid
3648 WHERE id IN %%s""" % self._table, (tuple(ids),))
3649 uids = [x[0] for x in cr.fetchall()]
3650 if len(uids) != 1 or uids[0] != uid:
3651 raise except_orm(_('AccessError'), '%s access is '
3652 'restricted to your own records for transient models '
3653 '(except for the super-user).' % operation.capitalize())
3655 where_clause, where_params, tables = self.pool.get('ir.rule').domain_get(cr, uid, self._name, operation, context=context)
3657 where_clause = ' and ' + ' and '.join(where_clause)
3658 for sub_ids in cr.split_for_in_conditions(ids):
3659 cr.execute('SELECT ' + self._table + '.id FROM ' + ','.join(tables) +
3660 ' WHERE ' + self._table + '.id IN %s' + where_clause,
3661 [sub_ids] + where_params)
3662 if cr.rowcount != len(sub_ids):
3663 raise except_orm(_('AccessError'),
3664 _('Operation prohibited by access rules, or performed on an already deleted document (Operation: %s, Document type: %s).')
3665 % (operation, self._description))
3667 def unlink(self, cr, uid, ids, context=None):
3669 Delete records with given ids
3671 :param cr: database cursor
3672 :param uid: current user id
3673 :param ids: id or list of ids
3674 :param context: (optional) context arguments, like lang, time zone
3676 :raise AccessError: * if user has no unlink rights on the requested object
3677 * if user tries to bypass access rules for unlink on the requested object
3678 :raise UserError: if the record is default property for other records
3683 if isinstance(ids, (int, long)):
3686 result_store = self._store_get_values(cr, uid, ids, None, context)
3688 self._check_concurrency(cr, ids, context)
3690 self.check_unlink(cr, uid)
3692 ir_property = self.pool.get('ir.property')
3694 # Check if the records are used as default properties.
3695 domain = [('res_id', '=', False),
3696 ('value_reference', 'in', ['%s,%s' % (self._name, i) for i in ids]),
3698 if ir_property.search(cr, uid, domain, context=context):
3699 raise except_orm(_('Error'), _('Unable to delete this document because it is used as a default property'))
3701 # Delete the records' properties.
3702 property_ids = ir_property.search(cr, uid, [('res_id', 'in', ['%s,%s' % (self._name, i) for i in ids])], context=context)
3703 ir_property.unlink(cr, uid, property_ids, context=context)
3705 wf_service = netsvc.LocalService("workflow")
3707 wf_service.trg_delete(uid, self._name, oid, cr)
3710 self.check_access_rule(cr, uid, ids, 'unlink', context=context)
3711 pool_model_data = self.pool.get('ir.model.data')
3712 ir_values_obj = self.pool.get('ir.values')
3713 for sub_ids in cr.split_for_in_conditions(ids):
3714 cr.execute('delete from ' + self._table + ' ' \
3715 'where id IN %s', (sub_ids,))
3717 # Removing the ir_model_data reference if the record being deleted is a record created by xml/csv file,
3718 # as these are not connected with real database foreign keys, and would be dangling references.
3719 # Note: following steps performed as admin to avoid access rights restrictions, and with no context
3720 # to avoid possible side-effects during admin calls.
3721 # Step 1. Calling unlink of ir_model_data only for the affected IDS
3722 reference_ids = pool_model_data.search(cr, SUPERUSER_ID, [('res_id','in',list(sub_ids)),('model','=',self._name)])
3723 # Step 2. Marching towards the real deletion of referenced records
3725 pool_model_data.unlink(cr, SUPERUSER_ID, reference_ids)
3727 # For the same reason, removing the record relevant to ir_values
3728 ir_value_ids = ir_values_obj.search(cr, uid,
3729 ['|',('value','in',['%s,%s' % (self._name, sid) for sid in sub_ids]),'&',('res_id','in',list(sub_ids)),('model','=',self._name)],
3732 ir_values_obj.unlink(cr, uid, ir_value_ids, context=context)
3734 for order, object, store_ids, fields in result_store:
3735 if object != self._name:
3736 obj = self.pool.get(object)
3737 cr.execute('select id from '+obj._table+' where id IN %s', (tuple(store_ids),))
3738 rids = map(lambda x: x[0], cr.fetchall())
3740 obj._store_set_values(cr, uid, rids, fields, context)
3747 def write(self, cr, user, ids, vals, context=None):
3749 Update records with given ids with the given field values
3751 :param cr: database cursor
3752 :param user: current user id
3754 :param ids: object id or list of object ids to update according to **vals**
3755 :param vals: field values to update, e.g {'field_name': new_field_value, ...}
3756 :type vals: dictionary
3757 :param context: (optional) context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...}
3758 :type context: dictionary
3760 :raise AccessError: * if user has no write rights on the requested object
3761 * if user tries to bypass access rules for write on the requested object
3762 :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
3763 :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)
3765 **Note**: The type of field values to pass in ``vals`` for relationship fields is specific:
3767 + For a many2many field, a list of tuples is expected.
3768 Here is the list of tuple that are accepted, with the corresponding semantics ::
3770 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
3771 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
3772 (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)
3773 (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)
3774 (4, ID) link to existing record with id = ID (adds a relationship)
3775 (5) unlink all (like using (3,ID) for all linked records)
3776 (6, 0, [IDs]) replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)
3779 [(6, 0, [8, 5, 6, 4])] sets the many2many to ids [8, 5, 6, 4]
3781 + For a one2many field, a lits of tuples is expected.
3782 Here is the list of tuple that are accepted, with the corresponding semantics ::
3784 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
3785 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
3786 (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)
3789 [(0, 0, {'field_name':field_value_record1, ...}), (0, 0, {'field_name':field_value_record2, ...})]
3791 + For a many2one field, simply use the ID of target record, which must already exist, or ``False`` to remove the link.
3792 + For a reference field, use a string with the model name, a comma, and the target object id (example: ``'product.product, 5'``)
3796 for field in vals.copy():
3798 if field in self._columns:
3799 fobj = self._columns[field]
3800 elif field in self._inherit_fields:
3801 fobj = self._inherit_fields[field][2]
3808 for group in groups:
3809 module = group.split(".")[0]
3810 grp = group.split(".")[1]
3811 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", \
3812 (grp, module, 'res.groups', user))
3813 readonly = cr.fetchall()
3814 if readonly[0][0] >= 1:
3825 if isinstance(ids, (int, long)):
3828 self._check_concurrency(cr, ids, context)
3829 self.check_write(cr, user)
3831 result = self._store_get_values(cr, user, ids, vals.keys(), context) or []
3833 # No direct update of parent_left/right
3834 vals.pop('parent_left', None)
3835 vals.pop('parent_right', None)
3837 parents_changed = []
3838 parent_order = self._parent_order or self._order
3839 if self._parent_store and (self._parent_name in vals):
3840 # The parent_left/right computation may take up to
3841 # 5 seconds. No need to recompute the values if the
3842 # parent is the same.
3843 # Note: to respect parent_order, nodes must be processed in
3844 # order, so ``parents_changed`` must be ordered properly.
3845 parent_val = vals[self._parent_name]
3847 query = "SELECT id FROM %s WHERE id IN %%s AND (%s != %%s OR %s IS NULL) ORDER BY %s" % \
3848 (self._table, self._parent_name, self._parent_name, parent_order)
3849 cr.execute(query, (tuple(ids), parent_val))
3851 query = "SELECT id FROM %s WHERE id IN %%s AND (%s IS NOT NULL) ORDER BY %s" % \
3852 (self._table, self._parent_name, parent_order)
3853 cr.execute(query, (tuple(ids),))
3854 parents_changed = map(operator.itemgetter(0), cr.fetchall())
3861 totranslate = context.get('lang', False) and (context['lang'] != 'en_US')
3863 if field in self._columns:
3864 if self._columns[field]._classic_write and not (hasattr(self._columns[field], '_fnct_inv')):
3865 if (not totranslate) or not self._columns[field].translate:
3866 upd0.append('"'+field+'"='+self._columns[field]._symbol_set[0])
3867 upd1.append(self._columns[field]._symbol_set[1](vals[field]))
3868 direct.append(field)
3870 upd_todo.append(field)
3872 updend.append(field)
3873 if field in self._columns \
3874 and hasattr(self._columns[field], 'selection') \
3876 self._check_selection_field_value(cr, user, field, vals[field], context=context)
3878 if self._log_access:
3879 upd0.append('write_uid=%s')
3880 upd0.append('write_date=now()')
3884 self.check_access_rule(cr, user, ids, 'write', context=context)
3885 for sub_ids in cr.split_for_in_conditions(ids):
3886 cr.execute('update ' + self._table + ' set ' + ','.join(upd0) + ' ' \
3887 'where id IN %s', upd1 + [sub_ids])
3888 if cr.rowcount != len(sub_ids):
3889 raise except_orm(_('AccessError'),
3890 _('One of the records you are trying to modify has already been deleted (Document type: %s).') % self._description)
3895 if self._columns[f].translate:
3896 src_trans = self.pool.get(self._name).read(cr, user, ids, [f])[0][f]
3899 # Inserting value to DB
3900 self.write(cr, user, ids, {f: vals[f]})
3901 self.pool.get('ir.translation')._set_ids(cr, user, self._name+','+f, 'model', context['lang'], ids, vals[f], src_trans)
3904 # call the 'set' method of fields which are not classic_write
3905 upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
3907 # default element in context must be removed when call a one2many or many2many
3908 rel_context = context.copy()
3909 for c in context.items():
3910 if c[0].startswith('default_'):
3911 del rel_context[c[0]]
3913 for field in upd_todo:
3915 result += self._columns[field].set(cr, self, id, field, vals[field], user, context=rel_context) or []
3917 unknown_fields = updend[:]
3918 for table in self._inherits:
3919 col = self._inherits[table]
3921 for sub_ids in cr.split_for_in_conditions(ids):
3922 cr.execute('select distinct "'+col+'" from "'+self._table+'" ' \
3923 'where id IN %s', (sub_ids,))
3924 nids.extend([x[0] for x in cr.fetchall()])
3928 if self._inherit_fields[val][0] == table:
3930 unknown_fields.remove(val)
3932 self.pool.get(table).write(cr, user, nids, v, context)
3936 'No such field(s) in model %s: %s.',
3937 self._name, ', '.join(unknown_fields))
3938 self._validate(cr, user, ids, context)
3940 # TODO: use _order to set dest at the right position and not first node of parent
3941 # We can't defer parent_store computation because the stored function
3942 # fields that are computer may refer (directly or indirectly) to
3943 # parent_left/right (via a child_of domain)
3946 self.pool._init_parent[self._name] = True
3948 order = self._parent_order or self._order
3949 parent_val = vals[self._parent_name]
3951 clause, params = '%s=%%s' % (self._parent_name,), (parent_val,)
3953 clause, params = '%s IS NULL' % (self._parent_name,), ()
3955 for id in parents_changed:
3956 cr.execute('SELECT parent_left, parent_right FROM %s WHERE id=%%s' % (self._table,), (id,))
3957 pleft, pright = cr.fetchone()
3958 distance = pright - pleft + 1
3960 # Positions of current siblings, to locate proper insertion point;
3961 # this can _not_ be fetched outside the loop, as it needs to be refreshed
3962 # after each update, in case several nodes are sequentially inserted one
3963 # next to the other (i.e computed incrementally)
3964 cr.execute('SELECT parent_right, id FROM %s WHERE %s ORDER BY %s' % (self._table, clause, parent_order), params)
3965 parents = cr.fetchall()
3967 # Find Position of the element
3969 for (parent_pright, parent_id) in parents:
3972 position = parent_pright + 1
3974 # It's the first node of the parent
3979 cr.execute('select parent_left from '+self._table+' where id=%s', (parent_val,))
3980 position = cr.fetchone()[0] + 1
3982 if pleft < position <= pright:
3983 raise except_orm(_('UserError'), _('Recursivity Detected.'))
3985 if pleft < position:
3986 cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
3987 cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
3988 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))
3990 cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
3991 cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
3992 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))
3994 result += self._store_get_values(cr, user, ids, vals.keys(), context)
3998 for order, object, ids_to_update, fields_to_recompute in result:
3999 key = (object, tuple(fields_to_recompute))
4000 done.setdefault(key, {})
4001 # avoid to do several times the same computation
4003 for id in ids_to_update:
4004 if id not in done[key]:
4005 done[key][id] = True
4007 self.pool.get(object)._store_set_values(cr, user, todo, fields_to_recompute, context)
4009 wf_service = netsvc.LocalService("workflow")
4011 wf_service.trg_write(user, self._name, id, cr)
4015 # TODO: Should set perm to user.xxx
4017 def create(self, cr, user, vals, context=None):
4019 Create a new record for the model.
4021 The values for the new record are initialized using the ``vals``
4022 argument, and if necessary the result of ``default_get()``.
4024 :param cr: database cursor
4025 :param user: current user id
4027 :param vals: field values for new record, e.g {'field_name': field_value, ...}
4028 :type vals: dictionary
4029 :param context: optional context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...}
4030 :type context: dictionary
4031 :return: id of new record created
4032 :raise AccessError: * if user has no create rights on the requested object
4033 * if user tries to bypass access rules for create on the requested object
4034 :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
4035 :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)
4037 **Note**: The type of field values to pass in ``vals`` for relationship fields is specific.
4038 Please see the description of the :py:meth:`~osv.osv.osv.write` method for details about the possible values and how
4045 if self.is_transient():
4046 self._transient_vacuum(cr, user)
4048 self.check_create(cr, user)
4050 vals = self._add_missing_default_values(cr, user, vals, context)
4053 for v in self._inherits:
4054 if self._inherits[v] not in vals:
4057 tocreate[v] = {'id': vals[self._inherits[v]]}
4058 (upd0, upd1, upd2) = ('', '', [])
4061 for v in vals.keys():
4062 if v in self._inherit_fields and v not in self._columns:
4063 (table, col, col_detail, original_parent) = self._inherit_fields[v]
4064 tocreate[table][v] = vals[v]
4067 if (v not in self._inherit_fields) and (v not in self._columns):
4069 unknown_fields.append(v)
4072 'No such field(s) in model %s: %s.',
4073 self._name, ', '.join(unknown_fields))
4075 # Try-except added to filter the creation of those records whose filds are readonly.
4076 # Example : any dashboard which has all the fields readonly.(due to Views(database views))
4078 cr.execute("SELECT nextval('"+self._sequence+"')")
4080 raise except_orm(_('UserError'),
4081 _('You cannot perform this operation. New Record Creation is not allowed for this object as this object is for reporting purpose.'))
4083 id_new = cr.fetchone()[0]
4084 for table in tocreate:
4085 if self._inherits[table] in vals:
4086 del vals[self._inherits[table]]
4088 record_id = tocreate[table].pop('id', None)
4090 if record_id is None or not record_id:
4091 record_id = self.pool.get(table).create(cr, user, tocreate[table], context=context)
4093 self.pool.get(table).write(cr, user, [record_id], tocreate[table], context=context)
4095 upd0 += ',' + self._inherits[table]
4097 upd2.append(record_id)
4099 #Start : Set bool fields to be False if they are not touched(to make search more powerful)
4100 bool_fields = [x for x in self._columns.keys() if self._columns[x]._type=='boolean']
4102 for bool_field in bool_fields:
4103 if bool_field not in vals:
4104 vals[bool_field] = False
4106 for field in vals.copy():
4108 if field in self._columns:
4109 fobj = self._columns[field]
4111 fobj = self._inherit_fields[field][2]
4117 for group in groups:
4118 module = group.split(".")[0]
4119 grp = group.split(".")[1]
4120 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" % \
4121 (grp, module, 'res.groups', user))
4122 readonly = cr.fetchall()
4123 if readonly[0][0] >= 1:
4126 elif readonly[0][0] == 0:
4134 if self._columns[field]._classic_write:
4135 upd0 = upd0 + ',"' + field + '"'
4136 upd1 = upd1 + ',' + self._columns[field]._symbol_set[0]
4137 upd2.append(self._columns[field]._symbol_set[1](vals[field]))
4139 if not isinstance(self._columns[field], fields.related):
4140 upd_todo.append(field)
4141 if field in self._columns \
4142 and hasattr(self._columns[field], 'selection') \
4144 self._check_selection_field_value(cr, user, field, vals[field], context=context)
4145 if self._log_access:
4146 upd0 += ',create_uid,create_date'
4149 cr.execute('insert into "'+self._table+'" (id'+upd0+") values ("+str(id_new)+upd1+')', tuple(upd2))
4150 self.check_access_rule(cr, user, [id_new], 'create', context=context)
4151 upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
4153 if self._parent_store and not context.get('defer_parent_store_computation'):
4155 self.pool._init_parent[self._name] = True
4157 parent = vals.get(self._parent_name, False)
4159 cr.execute('select parent_right from '+self._table+' where '+self._parent_name+'=%s order by '+(self._parent_order or self._order), (parent,))
4161 result_p = cr.fetchall()
4162 for (pleft,) in result_p:
4167 cr.execute('select parent_left from '+self._table+' where id=%s', (parent,))
4168 pleft_old = cr.fetchone()[0]
4171 cr.execute('select max(parent_right) from '+self._table)
4172 pleft = cr.fetchone()[0] or 0
4173 cr.execute('update '+self._table+' set parent_left=parent_left+2 where parent_left>%s', (pleft,))
4174 cr.execute('update '+self._table+' set parent_right=parent_right+2 where parent_right>%s', (pleft,))
4175 cr.execute('update '+self._table+' set parent_left=%s,parent_right=%s where id=%s', (pleft+1, pleft+2, id_new))
4177 # default element in context must be remove when call a one2many or many2many
4178 rel_context = context.copy()
4179 for c in context.items():
4180 if c[0].startswith('default_'):
4181 del rel_context[c[0]]
4184 for field in upd_todo:
4185 result += self._columns[field].set(cr, self, id_new, field, vals[field], user, rel_context) or []
4186 self._validate(cr, user, [id_new], context)
4188 if not context.get('no_store_function', False):
4189 result += self._store_get_values(cr, user, [id_new], vals.keys(), context)
4192 for order, object, ids, fields2 in result:
4193 if not (object, ids, fields2) in done:
4194 self.pool.get(object)._store_set_values(cr, user, ids, fields2, context)
4195 done.append((object, ids, fields2))
4197 if self._log_create and not (context and context.get('no_store_function', False)):
4198 message = self._description + \
4200 self.name_get(cr, user, [id_new], context=context)[0][1] + \
4201 "' " + _("created.")
4202 self.log(cr, user, id_new, message, True, context=context)
4203 wf_service = netsvc.LocalService("workflow")
4204 wf_service.trg_create(user, self._name, id_new, cr)
4207 def browse(self, cr, uid, select, context=None, list_class=None, fields_process=None):
4208 """Fetch records as objects allowing to use dot notation to browse fields and relations
4210 :param cr: database cursor
4211 :param uid: current user id
4212 :param select: id or list of ids.
4213 :param context: context arguments, like lang, time zone
4214 :rtype: object or list of objects requested
4217 self._list_class = list_class or browse_record_list
4219 # need to accepts ints and longs because ids coming from a method
4220 # launched by button in the interface have a type long...
4221 if isinstance(select, (int, long)):
4222 return browse_record(cr, uid, select, self, cache, context=context, list_class=self._list_class, fields_process=fields_process)
4223 elif isinstance(select, list):
4224 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)
4226 return browse_null()
4228 def _store_get_values(self, cr, uid, ids, fields, context):
4229 """Returns an ordered list of fields.functions to call due to
4230 an update operation on ``fields`` of records with ``ids``,
4231 obtained by calling the 'store' functions of these fields,
4232 as setup by their 'store' attribute.
4234 :return: [(priority, model_name, [record_ids,], [function_fields,])]
4236 if fields is None: fields = []
4237 stored_functions = self.pool._store_function.get(self._name, [])
4239 # use indexed names for the details of the stored_functions:
4240 model_name_, func_field_to_compute_, id_mapping_fnct_, trigger_fields_, priority_ = range(5)
4242 # only keep functions that should be triggered for the ``fields``
4244 to_compute = [f for f in stored_functions \
4245 if ((not f[trigger_fields_]) or set(fields).intersection(f[trigger_fields_]))]
4248 for function in to_compute:
4249 # use admin user for accessing objects having rules defined on store fields
4250 target_ids = [id for id in function[id_mapping_fnct_](self, cr, SUPERUSER_ID, ids, context) if id]
4252 # the compound key must consider the priority and model name
4253 key = (function[priority_], function[model_name_])
4254 for target_id in target_ids:
4255 mapping.setdefault(key, {}).setdefault(target_id,set()).add(tuple(function))
4257 # Here mapping looks like:
4258 # { (10, 'model_a') : { target_id1: [ (function_1_tuple, function_2_tuple) ], ... }
4259 # (20, 'model_a') : { target_id2: [ (function_3_tuple, function_4_tuple) ], ... }
4260 # (99, 'model_a') : { target_id1: [ (function_5_tuple, function_6_tuple) ], ... }
4263 # Now we need to generate the batch function calls list
4265 # { (10, 'model_a') : [(10, 'model_a', [record_ids,], [function_fields,])] }
4267 for ((priority,model), id_map) in mapping.iteritems():
4268 functions_ids_maps = {}
4269 # function_ids_maps =
4270 # { (function_1_tuple, function_2_tuple) : [target_id1, target_id2, ..] }
4271 for id, functions in id_map.iteritems():
4272 functions_ids_maps.setdefault(tuple(functions), []).append(id)
4273 for functions, ids in functions_ids_maps.iteritems():
4274 call_map.setdefault((priority,model),[]).append((priority, model, ids,
4275 [f[func_field_to_compute_] for f in functions]))
4276 ordered_keys = call_map.keys()
4280 result = reduce(operator.add, (call_map[k] for k in ordered_keys))
4283 def _store_set_values(self, cr, uid, ids, fields, context):
4284 """Calls the fields.function's "implementation function" for all ``fields``, on records with ``ids`` (taking care of
4285 respecting ``multi`` attributes), and stores the resulting values in the database directly."""
4290 if self._log_access:
4291 cr.execute('select id,write_date from '+self._table+' where id IN %s', (tuple(ids),))
4295 field_dict.setdefault(r[0], [])
4296 res_date = time.strptime((r[1])[:19], '%Y-%m-%d %H:%M:%S')
4297 write_date = datetime.datetime.fromtimestamp(time.mktime(res_date))
4298 for i in self.pool._store_function.get(self._name, []):
4300 up_write_date = write_date + datetime.timedelta(hours=i[5])
4301 if datetime.datetime.now() < up_write_date:
4303 field_dict[r[0]].append(i[1])
4309 if self._columns[f]._multi not in keys:
4310 keys.append(self._columns[f]._multi)
4311 todo.setdefault(self._columns[f]._multi, [])
4312 todo[self._columns[f]._multi].append(f)
4316 # use admin user for accessing objects having rules defined on store fields
4317 result = self._columns[val[0]].get(cr, self, ids, val, SUPERUSER_ID, context=context)
4318 for id, value in result.items():
4320 for f in value.keys():
4321 if f in field_dict[id]:
4328 if self._columns[v]._type in ('many2one', 'one2one'):
4330 value[v] = value[v][0]
4333 upd0.append('"'+v+'"='+self._columns[v]._symbol_set[0])
4334 upd1.append(self._columns[v]._symbol_set[1](value[v]))
4337 cr.execute('update "' + self._table + '" set ' + \
4338 ','.join(upd0) + ' where id = %s', upd1)
4342 # use admin user for accessing objects having rules defined on store fields
4343 result = self._columns[f].get(cr, self, ids, f, SUPERUSER_ID, context=context)
4344 for r in result.keys():
4346 if r in field_dict.keys():
4347 if f in field_dict[r]:
4349 for id, value in result.items():
4350 if self._columns[f]._type in ('many2one', 'one2one'):
4355 cr.execute('update "' + self._table + '" set ' + \
4356 '"'+f+'"='+self._columns[f]._symbol_set[0] + ' where id = %s', (self._columns[f]._symbol_set[1](value), id))
4362 def perm_write(self, cr, user, ids, fields, context=None):
4363 raise NotImplementedError(_('This method does not exist anymore'))
4365 # TODO: ameliorer avec NULL
4366 def _where_calc(self, cr, user, domain, active_test=True, context=None):
4367 """Computes the WHERE clause needed to implement an OpenERP domain.
4368 :param domain: the domain to compute
4370 :param active_test: whether the default filtering of records with ``active``
4371 field set to ``False`` should be applied.
4372 :return: the query expressing the given domain as provided in domain
4373 :rtype: osv.query.Query
4378 # if the object has a field named 'active', filter out all inactive
4379 # records unless they were explicitely asked for
4380 if 'active' in self._columns and (active_test and context.get('active_test', True)):
4382 active_in_args = False
4384 if a[0] == 'active':
4385 active_in_args = True
4386 if not active_in_args:
4387 domain.insert(0, ('active', '=', 1))
4389 domain = [('active', '=', 1)]
4392 e = expression.expression(cr, user, domain, self, context)
4393 tables = e.get_tables()
4394 where_clause, where_params = e.to_sql()
4395 where_clause = where_clause and [where_clause] or []
4397 where_clause, where_params, tables = [], [], ['"%s"' % self._table]
4399 return Query(tables, where_clause, where_params)
4401 def _check_qorder(self, word):
4402 if not regex_order.match(word):
4403 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)'))
4406 def _apply_ir_rules(self, cr, uid, query, mode='read', context=None):
4407 """Add what's missing in ``query`` to implement all appropriate ir.rules
4408 (using the ``model_name``'s rules or the current model's rules if ``model_name`` is None)
4410 :param query: the current query object
4412 def apply_rule(added_clause, added_params, added_tables, parent_model=None, child_object=None):
4414 if parent_model and child_object:
4415 # as inherited rules are being applied, we need to add the missing JOIN
4416 # to reach the parent table (if it was not JOINed yet in the query)
4417 child_object._inherits_join_add(child_object, parent_model, query)
4418 query.where_clause += added_clause
4419 query.where_clause_params += added_params
4420 for table in added_tables:
4421 if table not in query.tables:
4422 query.tables.append(table)
4426 # apply main rules on the object
4427 rule_obj = self.pool.get('ir.rule')
4428 apply_rule(*rule_obj.domain_get(cr, uid, self._name, mode, context=context))
4430 # apply ir.rules from the parents (through _inherits)
4431 for inherited_model in self._inherits:
4432 kwargs = dict(parent_model=inherited_model, child_object=self) #workaround for python2.5
4433 apply_rule(*rule_obj.domain_get(cr, uid, inherited_model, mode, context=context), **kwargs)
4435 def _generate_m2o_order_by(self, order_field, query):
4437 Add possibly missing JOIN to ``query`` and generate the ORDER BY clause for m2o fields,
4438 either native m2o fields or function/related fields that are stored, including
4439 intermediate JOINs for inheritance if required.
4441 :return: the qualified field name to use in an ORDER BY clause to sort by ``order_field``
4443 if order_field not in self._columns and order_field in self._inherit_fields:
4444 # also add missing joins for reaching the table containing the m2o field
4445 qualified_field = self._inherits_join_calc(order_field, query)
4446 order_field_column = self._inherit_fields[order_field][2]
4448 qualified_field = '"%s"."%s"' % (self._table, order_field)
4449 order_field_column = self._columns[order_field]
4451 assert order_field_column._type == 'many2one', 'Invalid field passed to _generate_m2o_order_by()'
4452 if not order_field_column._classic_write and not getattr(order_field_column, 'store', False):
4453 _logger.debug("Many2one function/related fields must be stored " \
4454 "to be used as ordering fields! Ignoring sorting for %s.%s",
4455 self._name, order_field)
4458 # figure out the applicable order_by for the m2o
4459 dest_model = self.pool.get(order_field_column._obj)
4460 m2o_order = dest_model._order
4461 if not regex_order.match(m2o_order):
4462 # _order is complex, can't use it here, so we default to _rec_name
4463 m2o_order = dest_model._rec_name
4465 # extract the field names, to be able to qualify them and add desc/asc
4467 for order_part in m2o_order.split(","):
4468 m2o_order_list.append(order_part.strip().split(" ",1)[0].strip())
4469 m2o_order = m2o_order_list
4471 # Join the dest m2o table if it's not joined yet. We use [LEFT] OUTER join here
4472 # as we don't want to exclude results that have NULL values for the m2o
4473 src_table, src_field = qualified_field.replace('"','').split('.', 1)
4474 query.join((src_table, dest_model._table, src_field, 'id'), outer=True)
4475 qualify = lambda field: '"%s"."%s"' % (dest_model._table, field)
4476 return map(qualify, m2o_order) if isinstance(m2o_order, list) else qualify(m2o_order)
4479 def _generate_order_by(self, order_spec, query):
4481 Attempt to consruct an appropriate ORDER BY clause based on order_spec, which must be
4482 a comma-separated list of valid field names, optionally followed by an ASC or DESC direction.
4484 :raise" except_orm in case order_spec is malformed
4486 order_by_clause = self._order
4488 order_by_elements = []
4489 self._check_qorder(order_spec)
4490 for order_part in order_spec.split(','):
4491 order_split = order_part.strip().split(' ')
4492 order_field = order_split[0].strip()
4493 order_direction = order_split[1].strip() if len(order_split) == 2 else ''
4495 if order_field == 'id':
4496 order_by_clause = '"%s"."%s"' % (self._table, order_field)
4497 elif order_field in self._columns:
4498 order_column = self._columns[order_field]
4499 if order_column._classic_read:
4500 inner_clause = '"%s"."%s"' % (self._table, order_field)
4501 elif order_column._type == 'many2one':
4502 inner_clause = self._generate_m2o_order_by(order_field, query)
4504 continue # ignore non-readable or "non-joinable" fields
4505 elif order_field in self._inherit_fields:
4506 parent_obj = self.pool.get(self._inherit_fields[order_field][3])
4507 order_column = parent_obj._columns[order_field]
4508 if order_column._classic_read:
4509 inner_clause = self._inherits_join_calc(order_field, query)
4510 elif order_column._type == 'many2one':
4511 inner_clause = self._generate_m2o_order_by(order_field, query)
4513 continue # ignore non-readable or "non-joinable" fields
4515 if isinstance(inner_clause, list):
4516 for clause in inner_clause:
4517 order_by_elements.append("%s %s" % (clause, order_direction))
4519 order_by_elements.append("%s %s" % (inner_clause, order_direction))
4520 if order_by_elements:
4521 order_by_clause = ",".join(order_by_elements)
4523 return order_by_clause and (' ORDER BY %s ' % order_by_clause) or ''
4525 def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
4527 Private implementation of search() method, allowing specifying the uid to use for the access right check.
4528 This is useful for example when filling in the selection list for a drop-down and avoiding access rights errors,
4529 by specifying ``access_rights_uid=1`` to bypass access rights check, but not ir.rules!
4530 This is ok at the security level because this method is private and not callable through XML-RPC.
4532 :param access_rights_uid: optional user ID to use when checking access rights
4533 (not for ir.rules, this is only for ir.model.access)
4537 self.check_read(cr, access_rights_uid or user)
4539 # For transient models, restrict acces to the current user, except for the super-user
4540 if self.is_transient() and self._log_access and user != SUPERUSER_ID:
4541 args = expression.AND(([('create_uid', '=', user)], args or []))
4543 query = self._where_calc(cr, user, args, context=context)
4544 self._apply_ir_rules(cr, user, query, 'read', context=context)
4545 order_by = self._generate_order_by(order, query)
4546 from_clause, where_clause, where_clause_params = query.get_sql()
4548 limit_str = limit and ' limit %d' % limit or ''
4549 offset_str = offset and ' offset %d' % offset or ''
4550 where_str = where_clause and (" WHERE %s" % where_clause) or ''
4553 cr.execute('SELECT count("%s".id) FROM ' % self._table + from_clause + where_str + limit_str + offset_str, where_clause_params)
4556 cr.execute('SELECT "%s".id FROM ' % self._table + from_clause + where_str + order_by + limit_str + offset_str, where_clause_params)
4558 return [x[0] for x in res]
4560 # returns the different values ever entered for one field
4561 # this is used, for example, in the client when the user hits enter on
4563 def distinct_field_get(self, cr, uid, field, value, args=None, offset=0, limit=None):
4566 if field in self._inherit_fields:
4567 return self.pool.get(self._inherit_fields[field][0]).distinct_field_get(cr, uid, field, value, args, offset, limit)
4569 return self._columns[field].search(cr, self, args, field, value, offset, limit, uid)
4571 def copy_data(self, cr, uid, id, default=None, context=None):
4573 Copy given record's data with all its fields values
4575 :param cr: database cursor
4576 :param user: current user id
4577 :param id: id of the record to copy
4578 :param default: field values to override in the original values of the copied record
4579 :type default: dictionary
4580 :param context: context arguments, like lang, time zone
4581 :type context: dictionary
4582 :return: dictionary containing all the field values
4588 # avoid recursion through already copied records in case of circular relationship
4589 seen_map = context.setdefault('__copy_data_seen',{})
4590 if id in seen_map.setdefault(self._name,[]):
4592 seen_map[self._name].append(id)
4596 if 'state' not in default:
4597 if 'state' in self._defaults:
4598 if callable(self._defaults['state']):
4599 default['state'] = self._defaults['state'](self, cr, uid, context)
4601 default['state'] = self._defaults['state']
4603 context_wo_lang = context.copy()
4604 if 'lang' in context:
4605 del context_wo_lang['lang']
4606 data = self.read(cr, uid, [id,], context=context_wo_lang)
4610 raise IndexError( _("Record #%d of %s not found, cannot copy!") %( id, self._name))
4612 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
4613 fields = self.fields_get(cr, uid, context=context)
4615 ftype = fields[f]['type']
4617 if self._log_access and f in LOG_ACCESS_COLUMNS:
4621 data[f] = default[f]
4622 elif 'function' in fields[f]:
4624 elif ftype == 'many2one':
4626 data[f] = data[f] and data[f][0]
4629 elif ftype in ('one2many', 'one2one'):
4631 rel = self.pool.get(fields[f]['relation'])
4633 # duplicate following the order of the ids
4634 # because we'll rely on it later for copying
4635 # translations in copy_translation()!
4637 for rel_id in data[f]:
4638 # the lines are first duplicated using the wrong (old)
4639 # parent but then are reassigned to the correct one thanks
4640 # to the (0, 0, ...)
4641 d = rel.copy_data(cr, uid, rel_id, context=context)
4643 res.append((0, 0, d))
4645 elif ftype == 'many2many':
4646 data[f] = [(6, 0, data[f])]
4650 # make sure we don't break the current parent_store structure and
4651 # force a clean recompute!
4652 for parent_column in ['parent_left', 'parent_right']:
4653 data.pop(parent_column, None)
4654 # Remove _inherits field's from data recursively, missing parents will
4655 # be created by create() (so that copy() copy everything).
4656 def remove_ids(inherits_dict):
4657 for parent_table in inherits_dict:
4658 del data[inherits_dict[parent_table]]
4659 remove_ids(self.pool.get(parent_table)._inherits)
4660 remove_ids(self._inherits)
4663 def copy_translations(self, cr, uid, old_id, new_id, context=None):
4667 # avoid recursion through already copied records in case of circular relationship
4668 seen_map = context.setdefault('__copy_translations_seen',{})
4669 if old_id in seen_map.setdefault(self._name,[]):
4671 seen_map[self._name].append(old_id)
4673 trans_obj = self.pool.get('ir.translation')
4674 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
4675 fields = self.fields_get(cr, uid, context=context)
4677 translation_records = []
4678 for field_name, field_def in fields.items():
4679 # we must recursively copy the translations for o2o and o2m
4680 if field_def['type'] in ('one2one', 'one2many'):
4681 target_obj = self.pool.get(field_def['relation'])
4682 old_record, new_record = self.read(cr, uid, [old_id, new_id], [field_name], context=context)
4683 # here we rely on the order of the ids to match the translations
4684 # as foreseen in copy_data()
4685 old_children = sorted(old_record[field_name])
4686 new_children = sorted(new_record[field_name])
4687 for (old_child, new_child) in zip(old_children, new_children):
4688 target_obj.copy_translations(cr, uid, old_child, new_child, context=context)
4689 # and for translatable fields we keep them for copy
4690 elif field_def.get('translate'):
4692 if field_name in self._columns:
4693 trans_name = self._name + "," + field_name
4694 elif field_name in self._inherit_fields:
4695 trans_name = self._inherit_fields[field_name][0] + "," + field_name
4697 trans_ids = trans_obj.search(cr, uid, [
4698 ('name', '=', trans_name),
4699 ('res_id', '=', old_id)
4701 translation_records.extend(trans_obj.read(cr, uid, trans_ids, context=context))
4703 for record in translation_records:
4705 record['res_id'] = new_id
4706 trans_obj.create(cr, uid, record, context=context)
4709 def copy(self, cr, uid, id, default=None, context=None):
4711 Duplicate record with given id updating it with default values
4713 :param cr: database cursor
4714 :param uid: current user id
4715 :param id: id of the record to copy
4716 :param default: dictionary of field values to override in the original values of the copied record, e.g: ``{'field_name': overriden_value, ...}``
4717 :type default: dictionary
4718 :param context: context arguments, like lang, time zone
4719 :type context: dictionary
4720 :return: id of the newly created record
4725 context = context.copy()
4726 data = self.copy_data(cr, uid, id, default, context)
4727 new_id = self.create(cr, uid, data, context)
4728 self.copy_translations(cr, uid, id, new_id, context)
4731 def exists(self, cr, uid, ids, context=None):
4732 """Checks whether the given id or ids exist in this model,
4733 and return the list of ids that do. This is simple to use for
4734 a truth test on a browse_record::
4739 :param ids: id or list of ids to check for existence
4740 :type ids: int or [int]
4741 :return: the list of ids that currently exist, out of
4744 if type(ids) in (int, long):
4746 query = 'SELECT id FROM "%s"' % (self._table)
4747 cr.execute(query + "WHERE ID IN %s", (tuple(ids),))
4748 return [x[0] for x in cr.fetchall()]
4750 def check_recursion(self, cr, uid, ids, context=None, parent=None):
4751 _logger.warning("You are using deprecated %s.check_recursion(). Please use the '_check_recursion()' instead!" % \
4753 assert parent is None or parent in self._columns or parent in self._inherit_fields,\
4754 "The 'parent' parameter passed to check_recursion() must be None or a valid field name"
4755 return self._check_recursion(cr, uid, ids, context, parent)
4757 def _check_recursion(self, cr, uid, ids, context=None, parent=None):
4759 Verifies that there is no loop in a hierarchical structure of records,
4760 by following the parent relationship using the **parent** field until a loop
4761 is detected or until a top-level record is found.
4763 :param cr: database cursor
4764 :param uid: current user id
4765 :param ids: list of ids of records to check
4766 :param parent: optional parent field name (default: ``self._parent_name = parent_id``)
4767 :return: **True** if the operation can proceed safely, or **False** if an infinite loop is detected.
4771 parent = self._parent_name
4773 query = 'SELECT distinct "%s" FROM "%s" WHERE id IN %%s' % (parent, self._table)
4776 for i in range(0, len(ids), cr.IN_MAX):
4777 sub_ids_parent = ids_parent[i:i+cr.IN_MAX]
4778 cr.execute(query, (tuple(sub_ids_parent),))
4779 ids_parent2.extend(filter(None, map(lambda x: x[0], cr.fetchall())))
4780 ids_parent = ids_parent2
4781 for i in ids_parent:
4786 def _get_external_ids(self, cr, uid, ids, *args, **kwargs):
4787 """Retrieve the External ID(s) of any database record.
4789 **Synopsis**: ``_get_xml_ids(cr, uid, ids) -> { 'id': ['module.xml_id'] }``
4791 :return: map of ids to the list of their fully qualified External IDs
4792 in the form ``module.key``, or an empty list when there's no External
4793 ID for a record, e.g.::
4795 { 'id': ['module.ext_id', 'module.ext_id_bis'],
4798 ir_model_data = self.pool.get('ir.model.data')
4799 data_ids = ir_model_data.search(cr, uid, [('model', '=', self._name), ('res_id', 'in', ids)])
4800 data_results = ir_model_data.read(cr, uid, data_ids, ['module', 'name', 'res_id'])
4803 # can't use dict.fromkeys() as the list would be shared!
4805 for record in data_results:
4806 result[record['res_id']].append('%(module)s.%(name)s' % record)
4809 def get_external_id(self, cr, uid, ids, *args, **kwargs):
4810 """Retrieve the External ID of any database record, if there
4811 is one. This method works as a possible implementation
4812 for a function field, to be able to add it to any
4813 model object easily, referencing it as ``Model.get_external_id``.
4815 When multiple External IDs exist for a record, only one
4816 of them is returned (randomly).
4818 :return: map of ids to their fully qualified XML ID,
4819 defaulting to an empty string when there's none
4820 (to be usable as a function field),
4823 { 'id': 'module.ext_id',
4826 results = self._get_xml_ids(cr, uid, ids)
4827 for k, v in results.iteritems():
4834 # backwards compatibility
4835 get_xml_id = get_external_id
4836 _get_xml_ids = _get_external_ids
4839 def is_transient(self):
4840 """ Return whether the model is transient.
4845 return self._transient
4847 def _transient_clean_rows_older_than(self, cr, seconds):
4848 assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
4849 cr.execute("SELECT id FROM " + self._table + " WHERE"
4850 " COALESCE(write_date, create_date, now())::timestamp <"
4851 " (now() - interval %s)", ("%s seconds" % seconds,))
4852 ids = [x[0] for x in cr.fetchall()]
4853 self.unlink(cr, SUPERUSER_ID, ids)
4855 def _transient_clean_old_rows(self, cr, count):
4856 assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
4858 "SELECT id, COALESCE(write_date, create_date, now())::timestamp"
4859 " AS t FROM " + self._table +
4860 " ORDER BY t LIMIT %s", (count,))
4861 ids = [x[0] for x in cr.fetchall()]
4862 self.unlink(cr, SUPERUSER_ID, ids)
4864 def _transient_vacuum(self, cr, uid, force=False):
4865 """Clean the transient records.
4867 This unlinks old records from the transient model tables whenever the
4868 "_transient_max_count" or "_max_age" conditions (if any) are reached.
4869 Actual cleaning will happen only once every "_transient_check_time" calls.
4870 This means this method can be called frequently called (e.g. whenever
4871 a new record is created).
4873 assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
4874 self._transient_check_count += 1
4875 if (not force) and (self._transient_check_count % self._transient_check_time):
4876 self._transient_check_count = 0
4879 # Age-based expiration
4880 if self._transient_max_hours:
4881 self._transient_clean_rows_older_than(cr, self._transient_max_hours * 60 * 60)
4883 # Count-based expiration
4884 if self._transient_max_count:
4885 self._transient_clean_old_rows(cr, self._transient_max_count)
4889 def resolve_o2m_commands_to_record_dicts(self, cr, uid, field_name, o2m_commands, fields=None, context=None):
4890 """ Serializes o2m commands into record dictionaries (as if
4891 all the o2m records came from the database via a read()), and
4892 returns an iterable over these dictionaries.
4894 Because o2m commands might be creation commands, not all
4895 record ids will contain an ``id`` field. Commands matching an
4896 existing record (``UPDATE`` and ``LINK_TO``) will have an id.
4898 .. note:: ``CREATE``, ``UPDATE`` and ``LINK_TO`` stand for the
4899 o2m command codes ``0``, ``1`` and ``4``
4902 :param field_name: name of the o2m field matching the commands
4903 :type field_name: str
4904 :param o2m_commands: one2many commands to execute on ``field_name``
4905 :type o2m_commands: list((int|False, int|False, dict|False))
4906 :param fields: list of fields to read from the database, when applicable
4907 :type fields: list(str)
4908 :raises AssertionError: if a command is not ``CREATE``, ``UPDATE`` or ``LINK_TO``
4909 :returns: o2m records in a shape similar to that returned by
4910 ``read()`` (except records may be missing the ``id``
4911 field if they don't exist in db)
4912 :rtype: ``list(dict)``
4914 o2m_model = self._all_columns[field_name].column._obj
4916 # convert single ids and pairs to tripled commands
4918 for o2m_command in o2m_commands:
4919 if not isinstance(o2m_command, (list, tuple)):
4921 commands.append((command, o2m_command, False))
4922 elif len(o2m_command) == 1:
4923 (command,) = o2m_command
4924 commands.append((command, False, False))
4925 elif len(o2m_command) == 2:
4926 command, id = o2m_command
4927 commands.append((command, id, False))
4929 command = o2m_command[0]
4930 commands.append(o2m_command)
4931 assert command in (0, 1, 4), \
4932 "Only CREATE, UPDATE and LINK_TO commands are supported in resolver"
4934 # extract records to read, by id, in a mapping dict
4935 ids_to_read = [id for (command, id, _) in commands if command in (1, 4)]
4936 records_by_id = dict(
4937 (record['id'], record)
4938 for record in self.pool.get(o2m_model).read(
4939 cr, uid, ids_to_read, fields=fields, context=context))
4942 # merge record from db with record provided by command
4943 for command, id, record in commands:
4945 if command in (1, 4): item.update(records_by_id[id])
4946 if command in (0, 1): item.update(record)
4947 record_dicts.append(item)
4950 # keep this import here, at top it will cause dependency cycle errors
4953 class Model(BaseModel):
4954 """Main super-class for regular database-persisted OpenERP models.
4956 OpenERP models are created by inheriting from this class::
4961 The system will later instantiate the class once per database (on
4962 which the class' module is installed).
4964 _register = False # not visible in ORM registry, meant to be python-inherited only
4965 _transient = False # True in a TransientModel
4967 class TransientModel(BaseModel):
4968 """Model super-class for transient records, meant to be temporarily
4969 persisted, and regularly vaccuum-cleaned.
4971 A TransientModel has a simplified access rights management,
4972 all users can create new records, and may only access the
4973 records they created. The super-user has unrestricted access
4974 to all TransientModel records.
4976 _register = False # not visible in ORM registry, meant to be python-inherited only
4979 class AbstractModel(BaseModel):
4980 """Abstract Model super-class for creating an abstract class meant to be
4981 inherited by regular models (Models or TransientModels) but not meant to
4982 be usable on its own, or persisted.
4984 Technical note: we don't want to make AbstractModel the super-class of
4985 Model or BaseModel because it would not make sense to put the main
4986 definition of persistence methods such as create() in it, and still we
4987 should be able to override them within an AbstractModel.
4989 _auto = False # don't create any database backend for AbstractModels
4990 _register = False # not visible in ORM registry, meant to be python-inherited only
4993 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: