1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
22 #.apidoc title: Object Relational Mapping
23 #.apidoc module-mods: member-order: bysource
26 Object relational mapping to database (postgresql) module
27 * Hierarchical structure
28 * Constraints consistency, validations
29 * Object meta Data depends on its status
30 * Optimised processing by complex query (multiple actions at once)
31 * Default fields value
32 * Permissions optimisation
33 * Persistant object: DB postgresql
35 * Multi-level caching system
36 * 2 different inheritancies
38 - classicals (varchar, integer, boolean, ...)
39 - relations (one2many, many2one, many2many)
57 from lxml import etree
61 import openerp.netsvc as netsvc
62 import openerp.tools as tools
63 from openerp.tools.config import config
64 from openerp.tools.safe_eval import safe_eval as eval
65 from openerp.tools.translate import _
66 from openerp import SUPERUSER_ID
67 from query import Query
69 # List of etree._Element subclasses that we choose to ignore when parsing XML.
70 from openerp.tools import SKIPPED_ELEMENT_TYPES
72 regex_order = re.compile('^(([a-z0-9_]+|"[a-z0-9_]+")( *desc| *asc)?( *, *|))+$', re.I)
73 regex_object_name = re.compile(r'^[a-z0-9_.]+$')
75 def transfer_field_to_modifiers(field, modifiers):
78 for attr in ('invisible', 'readonly', 'required'):
79 state_exceptions[attr] = []
80 default_values[attr] = bool(field.get(attr))
81 for state, modifs in (field.get("states",{})).items():
83 if default_values[modif[0]] != modif[1]:
84 state_exceptions[modif[0]].append(state)
86 for attr, default_value in default_values.items():
87 if state_exceptions[attr]:
88 modifiers[attr] = [("state", "not in" if default_value else "in", state_exceptions[attr])]
90 modifiers[attr] = default_value
93 # Don't deal with groups, it is done by check_group().
94 # Need the context to evaluate the invisible attribute on tree views.
95 # For non-tree views, the context shouldn't be given.
96 def transfer_node_to_modifiers(node, modifiers, context=None, in_tree_view=False):
98 modifiers.update(eval(node.get('attrs')))
100 if node.get('states'):
101 if 'invisible' in modifiers and isinstance(modifiers['invisible'], list):
102 # TODO combine with AND or OR, use implicit AND for now.
103 modifiers['invisible'].append(('state', 'not in', node.get('states').split(',')))
105 modifiers['invisible'] = [('state', 'not in', node.get('states').split(','))]
107 for a in ('invisible', 'readonly', 'required'):
109 v = bool(eval(node.get(a), {'context': context or {}}))
110 if in_tree_view and a == 'invisible':
111 # Invisible in a tree view has a specific meaning, make it a
112 # new key in the modifiers attribute.
113 modifiers['tree_invisible'] = v
114 elif v or (a not in modifiers or not isinstance(modifiers[a], list)):
115 # Don't set the attribute to False if a dynamic value was
116 # provided (i.e. a domain from attrs or states).
120 def simplify_modifiers(modifiers):
121 for a in ('invisible', 'readonly', 'required'):
122 if a in modifiers and not modifiers[a]:
126 def transfer_modifiers_to_node(modifiers, node):
128 simplify_modifiers(modifiers)
129 node.set('modifiers', simplejson.dumps(modifiers))
132 def test_modifiers(what, expected):
134 if isinstance(what, basestring):
135 node = etree.fromstring(what)
136 transfer_node_to_modifiers(node, modifiers)
137 simplify_modifiers(modifiers)
138 json = simplejson.dumps(modifiers)
139 assert json == expected, "%s != %s" % (json, expected)
140 elif isinstance(what, dict):
141 transfer_field_to_modifiers(what, modifiers)
142 simplify_modifiers(modifiers)
143 json = simplejson.dumps(modifiers)
144 assert json == expected, "%s != %s" % (json, expected)
149 # openerp.osv.orm.modifiers_tests()
150 def modifiers_tests():
151 test_modifiers('<field name="a"/>', '{}')
152 test_modifiers('<field name="a" invisible="1"/>', '{"invisible": true}')
153 test_modifiers('<field name="a" readonly="1"/>', '{"readonly": true}')
154 test_modifiers('<field name="a" required="1"/>', '{"required": true}')
155 test_modifiers('<field name="a" invisible="0"/>', '{}')
156 test_modifiers('<field name="a" readonly="0"/>', '{}')
157 test_modifiers('<field name="a" required="0"/>', '{}')
158 test_modifiers('<field name="a" invisible="1" required="1"/>', '{"invisible": true, "required": true}') # TODO order is not guaranteed
159 test_modifiers('<field name="a" invisible="1" required="0"/>', '{"invisible": true}')
160 test_modifiers('<field name="a" invisible="0" required="1"/>', '{"required": true}')
161 test_modifiers("""<field name="a" attrs="{'invisible': [('b', '=', 'c')]}"/>""", '{"invisible": [["b", "=", "c"]]}')
163 # The dictionary is supposed to be the result of fields_get().
164 test_modifiers({}, '{}')
165 test_modifiers({"invisible": True}, '{"invisible": true}')
166 test_modifiers({"invisible": False}, '{}')
169 def check_object_name(name):
170 """ Check if the given name is a valid openerp object name.
172 The _name attribute in osv and osv_memory object is subject to
173 some restrictions. This function returns True or False whether
174 the given name is allowed or not.
176 TODO: this is an approximation. The goal in this approximation
177 is to disallow uppercase characters (in some places, we quote
178 table/column names and in other not, which leads to this kind
181 psycopg2.ProgrammingError: relation "xxx" does not exist).
183 The same restriction should apply to both osv and osv_memory
184 objects for consistency.
187 if regex_object_name.match(name) is None:
191 def raise_on_invalid_object_name(name):
192 if not check_object_name(name):
193 msg = "The _name attribute %s is not valid." % name
194 logger = netsvc.Logger()
195 logger.notifyChannel('orm', netsvc.LOG_ERROR, msg)
196 raise except_orm('ValueError', msg)
198 POSTGRES_CONFDELTYPES = {
206 def last_day_of_current_month():
207 today = datetime.date.today()
208 last_day = str(calendar.monthrange(today.year, today.month)[1])
209 return time.strftime('%Y-%m-' + last_day)
211 def intersect(la, lb):
212 return filter(lambda x: x in lb, la)
214 def fix_import_export_id_paths(fieldname):
216 Fixes the id fields in import and exports, and splits field paths
219 :param str fieldname: name of the field to import/export
220 :return: split field name
223 fixed_db_id = re.sub(r'([^/])\.id', r'\1/.id', fieldname)
224 fixed_external_id = re.sub(r'([^/]):id', r'\1/id', fixed_db_id)
225 return fixed_external_id.split('/')
227 class except_orm(Exception):
228 def __init__(self, name, value):
231 self.args = (name, value)
233 class BrowseRecordError(Exception):
236 class browse_null(object):
237 """ Readonly python database object browser
243 def __getitem__(self, name):
246 def __getattr__(self, name):
247 return None # XXX: return self ?
255 def __nonzero__(self):
258 def __unicode__(self):
263 # TODO: execute an object method on browse_record_list
265 class browse_record_list(list):
266 """ Collection of browse objects
268 Such an instance will be returned when doing a ``browse([ids..])``
269 and will be iterable, yielding browse() objects
272 def __init__(self, lst, context=None):
275 super(browse_record_list, self).__init__(lst)
276 self.context = context
279 class browse_record(object):
280 """ An object that behaves like a row of an object's table.
281 It has attributes after the columns of the corresponding object.
285 uobj = pool.get('res.users')
286 user_rec = uobj.browse(cr, uid, 104)
289 logger = netsvc.Logger()
291 def __init__(self, cr, uid, id, table, cache, context=None, list_class=None, fields_process=None):
293 @param cache a dictionary of model->field->data to be shared accross browse
294 objects, thus reducing the SQL read()s . It can speed up things a lot,
295 but also be disastrous if not discarded after write()/unlink() operations
296 @param table the object (inherited from orm)
297 @param context dictionary with an optional context
299 if fields_process is None:
303 self._list_class = list_class or browse_record_list
307 self._table = table # deprecated, use _model!
309 self._table_name = self._table._name
310 self.__logger = logging.getLogger(
311 'osv.browse_record.' + self._table_name)
312 self._context = context
313 self._fields_process = fields_process
315 cache.setdefault(table._name, {})
316 self._data = cache[table._name]
318 if not (id and isinstance(id, (int, long,))):
319 raise BrowseRecordError(_('Wrong ID for the browse record, got %r, expected an integer.') % (id,))
320 # if not table.exists(cr, uid, id, context):
321 # raise BrowseRecordError(_('Object %s does not exists') % (self,))
323 if id not in self._data:
324 self._data[id] = {'id': id}
328 def __getitem__(self, name):
332 if name not in self._data[self._id]:
333 # build the list of fields we will fetch
335 # fetch the definition of the field which was asked for
336 if name in self._table._columns:
337 col = self._table._columns[name]
338 elif name in self._table._inherit_fields:
339 col = self._table._inherit_fields[name][2]
340 elif hasattr(self._table, str(name)):
341 attr = getattr(self._table, name)
342 if isinstance(attr, (types.MethodType, types.LambdaType, types.FunctionType)):
343 def function_proxy(*args, **kwargs):
344 if 'context' not in kwargs and self._context:
345 kwargs.update(context=self._context)
346 return attr(self._cr, self._uid, [self._id], *args, **kwargs)
347 return function_proxy
351 self.logger.notifyChannel("browse_record", netsvc.LOG_WARNING,
352 "Field '%s' does not exist in object '%s': \n%s" % (
353 name, self, ''.join(traceback.format_exc())))
354 raise KeyError("Field '%s' does not exist in object '%s'" % (
357 # if the field is a classic one or a many2one, we'll fetch all classic and many2one fields
359 # gen the list of "local" (ie not inherited) fields which are classic or many2one
360 fields_to_fetch = filter(lambda x: x[1]._classic_write, self._table._columns.items())
361 # gen the list of inherited fields
362 inherits = map(lambda x: (x[0], x[1][2]), self._table._inherit_fields.items())
363 # complete the field list with the inherited fields which are classic or many2one
364 fields_to_fetch += filter(lambda x: x[1]._classic_write, inherits)
365 # otherwise we fetch only that field
367 fields_to_fetch = [(name, col)]
368 ids = filter(lambda id: name not in self._data[id], self._data.keys())
370 field_names = map(lambda x: x[0], fields_to_fetch)
371 field_values = self._table.read(self._cr, self._uid, ids, field_names, context=self._context, load="_classic_write")
373 # TODO: improve this, very slow for reports
374 if self._fields_process:
375 lang = self._context.get('lang', 'en_US') or 'en_US'
376 lang_obj_ids = self.pool.get('res.lang').search(self._cr, self._uid, [('code', '=', lang)])
378 raise Exception(_('Language with code "%s" is not defined in your system !\nDefine it through the Administration menu.') % (lang,))
379 lang_obj = self.pool.get('res.lang').browse(self._cr, self._uid, lang_obj_ids[0])
381 for field_name, field_column in fields_to_fetch:
382 if field_column._type in self._fields_process:
383 for result_line in field_values:
384 result_line[field_name] = self._fields_process[field_column._type](result_line[field_name])
385 if result_line[field_name]:
386 result_line[field_name].set_value(self._cr, self._uid, result_line[field_name], self, field_column, lang_obj)
389 # Where did those ids come from? Perhaps old entries in ir_model_dat?
390 self.__logger.warn("No field_values found for ids %s in %s", ids, self)
391 raise KeyError('Field %s not found in %s'%(name, self))
392 # create browse records for 'remote' objects
393 for result_line in field_values:
395 for field_name, field_column in fields_to_fetch:
396 if field_column._type in ('many2one', 'one2one'):
397 if result_line[field_name]:
398 obj = self._table.pool.get(field_column._obj)
399 if isinstance(result_line[field_name], (list, tuple)):
400 value = result_line[field_name][0]
402 value = result_line[field_name]
404 # FIXME: this happen when a _inherits object
405 # overwrite a field of it parent. Need
406 # testing to be sure we got the right
407 # object and not the parent one.
408 if not isinstance(value, browse_record):
410 # In some cases the target model is not available yet, so we must ignore it,
411 # which is safe in most cases, this value will just be loaded later when needed.
412 # This situation can be caused by custom fields that connect objects with m2o without
413 # respecting module dependencies, causing relationships to be connected to soon when
414 # the target is not loaded yet.
416 new_data[field_name] = browse_record(self._cr,
417 self._uid, value, obj, self._cache,
418 context=self._context,
419 list_class=self._list_class,
420 fields_process=self._fields_process)
422 new_data[field_name] = value
424 new_data[field_name] = browse_null()
426 new_data[field_name] = browse_null()
427 elif field_column._type in ('one2many', 'many2many') and len(result_line[field_name]):
428 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)
429 elif field_column._type in ('reference'):
430 if result_line[field_name]:
431 if isinstance(result_line[field_name], browse_record):
432 new_data[field_name] = result_line[field_name]
434 ref_obj, ref_id = result_line[field_name].split(',')
435 ref_id = long(ref_id)
437 obj = self._table.pool.get(ref_obj)
438 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)
440 new_data[field_name] = browse_null()
442 new_data[field_name] = browse_null()
444 new_data[field_name] = result_line[field_name]
445 self._data[result_line['id']].update(new_data)
447 if not name in self._data[self._id]:
448 # How did this happen? Could be a missing model due to custom fields used too soon, see above.
449 self.logger.notifyChannel("browse_record", netsvc.LOG_ERROR,
450 "Fields to fetch: %s, Field values: %s"%(field_names, field_values))
451 self.logger.notifyChannel("browse_record", netsvc.LOG_ERROR,
452 "Cached: %s, Table: %s"%(self._data[self._id], self._table))
453 raise KeyError(_('Unknown attribute %s in %s ') % (name, self))
454 return self._data[self._id][name]
456 def __getattr__(self, name):
460 raise AttributeError(e)
462 def __contains__(self, name):
463 return (name in self._table._columns) or (name in self._table._inherit_fields) or hasattr(self._table, name)
466 raise NotImplementedError("Iteration is not allowed on %s" % self)
468 def __hasattr__(self, name):
475 return "browse_record(%s, %d)" % (self._table_name, self._id)
477 def __eq__(self, other):
478 if not isinstance(other, browse_record):
480 return (self._table_name, self._id) == (other._table_name, other._id)
482 def __ne__(self, other):
483 if not isinstance(other, browse_record):
485 return (self._table_name, self._id) != (other._table_name, other._id)
487 # we need to define __unicode__ even though we've already defined __str__
488 # because we have overridden __getattr__
489 def __unicode__(self):
490 return unicode(str(self))
493 return hash((self._table_name, self._id))
498 """Force refreshing this browse_record's data and all the data of the
499 records that belong to the same cache, by emptying the cache completely,
500 preserving only the record identifiers (for prefetching optimizations).
502 for model, model_cache in self._cache.iteritems():
503 # only preserve the ids of the records that were in the cache
504 cached_ids = dict([(i, {'id': i}) for i in model_cache.keys()])
505 self._cache[model].clear()
506 self._cache[model].update(cached_ids)
508 def pg_varchar(size=0):
509 """ Returns the VARCHAR declaration for the provided size:
511 * If no size (or an empty or negative size is provided) return an
513 * Otherwise return a VARCHAR(n)
515 :type int size: varchar size, optional
519 if not isinstance(size, int):
520 raise TypeError("VARCHAR parameter should be an int, got %s"
523 return 'VARCHAR(%d)' % size
526 FIELDS_TO_PGTYPES = {
527 fields.boolean: 'bool',
528 fields.integer: 'int4',
529 fields.integer_big: 'int8',
533 fields.datetime: 'timestamp',
534 fields.binary: 'bytea',
535 fields.many2one: 'int4',
538 def get_pg_type(f, type_override=None):
540 :param fields._column f: field to get a Postgres type for
541 :param type type_override: use the provided type for dispatching instead of the field's own type
542 :returns: (postgres_identification_type, postgres_type_specification)
545 field_type = type_override or type(f)
547 if field_type in FIELDS_TO_PGTYPES:
548 pg_type = (FIELDS_TO_PGTYPES[field_type], FIELDS_TO_PGTYPES[field_type])
549 elif issubclass(field_type, fields.float):
551 pg_type = ('numeric', 'NUMERIC')
553 pg_type = ('float8', 'DOUBLE PRECISION')
554 elif issubclass(field_type, (fields.char, fields.reference)):
555 pg_type = ('varchar', pg_varchar(f.size))
556 elif issubclass(field_type, fields.selection):
557 if (isinstance(f.selection, list) and isinstance(f.selection[0][0], int))\
558 or getattr(f, 'size', None) == -1:
559 pg_type = ('int4', 'INTEGER')
561 pg_type = ('varchar', pg_varchar(getattr(f, 'size', None)))
562 elif issubclass(field_type, fields.function):
563 if f._type == 'selection':
564 pg_type = ('varchar', pg_varchar())
566 pg_type = get_pg_type(f, getattr(fields, f._type))
568 logging.getLogger('orm').warn('%s type not supported!', field_type)
574 class MetaModel(type):
575 """ Metaclass for the Model.
577 This class is used as the metaclass for the Model class to discover
578 the models defined in a module (i.e. without instanciating them).
579 If the automatic discovery is not needed, it is possible to set the
580 model's _register attribute to False.
584 module_to_models = {}
586 def __init__(self, name, bases, attrs):
587 if not self._register:
588 self._register = True
589 super(MetaModel, self).__init__(name, bases, attrs)
592 module_name = self.__module__.split('.')[0]
593 if not hasattr(self, '_module'):
594 self._module = module_name
596 # Remember which models to instanciate for this module.
597 self.module_to_models.setdefault(self._module, []).append(self)
600 # Definition of log access columns, automatically added to models if
601 # self._log_access is True
602 LOG_ACCESS_COLUMNS = {
603 'create_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
604 'create_date': 'TIMESTAMP',
605 'write_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
606 'write_date': 'TIMESTAMP'
608 # special columns automatically created by the ORM
609 MAGIC_COLUMNS = ['id'] + LOG_ACCESS_COLUMNS.keys()
611 class BaseModel(object):
612 """ Base class for OpenERP models.
614 OpenERP models are created by inheriting from this class' subclasses:
616 * Model: for regular database-persisted models
617 * TransientModel: for temporary data, stored in the database but automatically
618 vaccuumed every so often
619 * AbstractModel: for abstract super classes meant to be shared by multiple
620 _inheriting classes (usually Models or TransientModels)
622 The system will later instantiate the class once per database (on
623 which the class' module is installed).
625 To create a class that should not be instantiated, the _register class attribute
628 __metaclass__ = MetaModel
629 _register = False # Set to false if the model shouldn't be automatically discovered.
635 _parent_name = 'parent_id'
636 _parent_store = False
637 _parent_order = False
644 _transient = False # True in a TransientModel
645 _transient_max_count = None
646 _transient_max_hours = None
647 _transient_check_time = 20
650 # { 'parent_model': 'm2o_field', ... }
653 # Mapping from inherits'd field name to triple (m, r, f, n) where m is the
654 # model from which it is inherits'd, r is the (local) field towards m, f
655 # is the _column object itself, and n is the original (i.e. top-most)
658 # { 'field_name': ('parent_model', 'm2o_field_to_reach_parent',
659 # field_column_obj, origina_parent_model), ... }
662 # Mapping field name/column_info object
663 # This is similar to _inherit_fields but:
664 # 1. includes self fields,
665 # 2. uses column_info instead of a triple.
671 _sql_constraints = []
672 _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']
673 __logger = logging.getLogger('orm')
674 __schema = logging.getLogger('orm.schema')
676 CONCURRENCY_CHECK_FIELD = '__last_update'
678 def log(self, cr, uid, id, message, secondary=False, context=None):
679 if context and context.get('disable_log'):
681 return self.pool.get('res.log').create(cr, uid,
684 'res_model': self._name,
685 'secondary': secondary,
691 def view_init(self, cr, uid, fields_list, context=None):
692 """Override this method to do specific things when a view on the object is opened."""
695 def _field_create(self, cr, context=None):
696 """ Create entries in ir_model_fields for all the model's fields.
698 If necessary, also create an entry in ir_model, and if called from the
699 modules loading scheme (by receiving 'module' in the context), also
700 create entries in ir_model_data (for the model and the fields).
702 - create an entry in ir_model (if there is not already one),
703 - create an entry in ir_model_data (if there is not already one, and if
704 'module' is in the context),
705 - update ir_model_fields with the fields found in _columns
706 (TODO there is some redundancy as _columns is updated from
707 ir_model_fields in __init__).
712 cr.execute("SELECT id FROM ir_model WHERE model=%s", (self._name,))
714 cr.execute('SELECT nextval(%s)', ('ir_model_id_seq',))
715 model_id = cr.fetchone()[0]
716 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'))
718 model_id = cr.fetchone()[0]
719 if 'module' in context:
720 name_id = 'model_'+self._name.replace('.', '_')
721 cr.execute('select * from ir_model_data where name=%s and module=%s', (name_id, context['module']))
723 cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, now(), now(), %s, %s, %s)", \
724 (name_id, context['module'], 'ir.model', model_id)
729 cr.execute("SELECT * FROM ir_model_fields WHERE model=%s", (self._name,))
731 for rec in cr.dictfetchall():
732 cols[rec['name']] = rec
734 for (k, f) in self._columns.items():
736 'model_id': model_id,
739 'field_description': f.string.replace("'", " "),
741 'relation': f._obj or '',
742 'view_load': (f.view_load and 1) or 0,
743 'select_level': tools.ustr(f.select or 0),
744 'readonly': (f.readonly and 1) or 0,
745 'required': (f.required and 1) or 0,
746 'selectable': (f.selectable and 1) or 0,
747 'translate': (f.translate and 1) or 0,
748 'relation_field': (f._type=='one2many' and isinstance(f, fields.one2many)) and f._fields_id or '',
750 # When its a custom field,it does not contain f.select
751 if context.get('field_state', 'base') == 'manual':
752 if context.get('field_name', '') == k:
753 vals['select_level'] = context.get('select', '0')
754 #setting value to let the problem NOT occur next time
756 vals['select_level'] = cols[k]['select_level']
759 cr.execute('select nextval(%s)', ('ir_model_fields_id_seq',))
760 id = cr.fetchone()[0]
762 cr.execute("""INSERT INTO ir_model_fields (
763 id, model_id, model, name, field_description, ttype,
764 relation,view_load,state,select_level,relation_field, translate
766 %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s
768 id, vals['model_id'], vals['model'], vals['name'], vals['field_description'], vals['ttype'],
769 vals['relation'], bool(vals['view_load']), 'base',
770 vals['select_level'], vals['relation_field'], bool(vals['translate'])
772 if 'module' in context:
773 name1 = 'field_' + self._table + '_' + k
774 cr.execute("select name from ir_model_data where name=%s", (name1,))
776 name1 = name1 + "_" + str(id)
777 cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, now(), now(), %s, %s, %s)", \
778 (name1, context['module'], 'ir.model.fields', id)
781 for key, val in vals.items():
782 if cols[k][key] != vals[key]:
783 cr.execute('update ir_model_fields set field_description=%s where model=%s and name=%s', (vals['field_description'], vals['model'], vals['name']))
785 cr.execute("""UPDATE ir_model_fields SET
786 model_id=%s, field_description=%s, ttype=%s, relation=%s,
787 view_load=%s, select_level=%s, readonly=%s ,required=%s, selectable=%s, relation_field=%s, translate=%s
789 model=%s AND name=%s""", (
790 vals['model_id'], vals['field_description'], vals['ttype'],
791 vals['relation'], bool(vals['view_load']),
792 vals['select_level'], bool(vals['readonly']), bool(vals['required']), bool(vals['selectable']), vals['relation_field'], bool(vals['translate']), vals['model'], vals['name']
798 # Goal: try to apply inheritance at the instanciation level and
799 # put objects in the pool var
802 def create_instance(cls, pool, cr):
803 """ Instanciate a given model.
805 This class method instanciates the class of some model (i.e. a class
806 deriving from osv or osv_memory). The class might be the class passed
807 in argument or, if it inherits from another class, a class constructed
808 by combining the two classes.
810 The ``attributes`` argument specifies which parent class attributes
813 TODO: the creation of the combined class is repeated at each call of
814 this method. This is probably unnecessary.
817 attributes = ['_columns', '_defaults', '_inherits', '_constraints',
820 parent_names = getattr(cls, '_inherit', None)
822 if isinstance(parent_names, (str, unicode)):
823 name = cls._name or parent_names
824 parent_names = [parent_names]
829 raise TypeError('_name is mandatory in case of multiple inheritance')
831 for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]):
832 parent_model = pool.get(parent_name)
833 if not getattr(cls, '_original_module', None) and name == parent_model._name:
834 cls._original_module = parent_model._original_module
836 raise TypeError('The model "%s" specifies an unexisting parent class "%s"\n'
837 'You may need to add a dependency on the parent class\' module.' % (name, parent_name))
838 parent_class = parent_model.__class__
841 new = copy.copy(getattr(parent_model, s, {}))
843 # Don't _inherit custom fields.
847 if hasattr(new, 'update'):
848 new.update(cls.__dict__.get(s, {}))
849 elif s=='_constraints':
850 for c in cls.__dict__.get(s, []):
852 for c2 in range(len(new)):
853 #For _constraints, we should check field and methods as well
854 if new[c2][2]==c[2] and (new[c2][0] == c[0] \
855 or getattr(new[c2][0],'__name__', True) == \
856 getattr(c[0],'__name__', False)):
857 # If new class defines a constraint with
858 # same function name, we let it override
866 new.extend(cls.__dict__.get(s, []))
868 cls = type(name, (cls, parent_class), dict(nattr, _register=False))
869 if not getattr(cls, '_original_module', None):
870 cls._original_module = cls._module
871 obj = object.__new__(cls)
872 obj.__init__(pool, cr)
876 """Register this model.
878 This doesn't create an instance but simply register the model
879 as being part of the module where it is defined.
884 # Set the module name (e.g. base, sale, accounting, ...) on the class.
885 module = cls.__module__.split('.')[0]
886 if not hasattr(cls, '_module'):
889 # Record this class in the list of models to instantiate for this module,
890 # managed by the metaclass.
891 module_model_list = MetaModel.module_to_models.setdefault(cls._module, [])
892 if cls not in module_model_list:
893 module_model_list.append(cls)
895 # Since we don't return an instance here, the __init__
896 # method won't be called.
899 def __init__(self, pool, cr):
900 """ Initialize a model and make it part of the given registry.
902 - copy the stored fields' functions in the osv_pool,
903 - update the _columns with the fields found in ir_model_fields,
904 - ensure there is a many2one for each _inherits'd parent,
905 - update the children's _columns,
906 - give a chance to each field to initialize itself.
909 pool.add(self._name, self)
912 if not self._name and not hasattr(self, '_inherit'):
913 name = type(self).__name__.split('.')[0]
914 msg = "The class %s has to have a _name attribute" % name
916 logger = netsvc.Logger()
917 logger.notifyChannel('orm', netsvc.LOG_ERROR, msg)
918 raise except_orm('ValueError', msg)
920 if not self._description:
921 self._description = self._name
923 self._table = self._name.replace('.', '_')
925 if not hasattr(self, '_log_access'):
926 # If _log_access is not specified, it is the same value as _auto.
927 self._log_access = getattr(self, "_auto", True)
929 self._columns = self._columns.copy()
930 for store_field in self._columns:
931 f = self._columns[store_field]
932 if hasattr(f, 'digits_change'):
934 def not_this_field(stored_func):
935 x, y, z, e, f, l = stored_func
936 return x != self._name or y != store_field
937 self.pool._store_function[self._name] = filter(not_this_field, self.pool._store_function.get(self._name, []))
938 if not isinstance(f, fields.function):
944 sm = {self._name: (lambda self, cr, uid, ids, c={}: ids, None, 10, None)}
945 for object, aa in sm.items():
947 (fnct, fields2, order, length) = aa
949 (fnct, fields2, order) = aa
952 raise except_orm('Error',
953 ('Invalid function definition %s in object %s !\nYou must use the definition: store={object:(fnct, fields, priority, time length)}.' % (store_field, self._name)))
954 self.pool._store_function.setdefault(object, [])
955 self.pool._store_function[object].append((self._name, store_field, fnct, tuple(fields2) if fields2 else None, order, length))
956 self.pool._store_function[object].sort(lambda x, y: cmp(x[4], y[4]))
958 for (key, _, msg) in self._sql_constraints:
959 self.pool._sql_error[self._table+'_'+key] = msg
963 cr.execute("SELECT id FROM ir_model_fields WHERE name=%s AND model=%s", ('state', 'ir.model.fields'))
965 cr.execute('SELECT * FROM ir_model_fields WHERE model=%s AND state=%s', (self._name, 'manual'))
966 for field in cr.dictfetchall():
967 if field['name'] in self._columns:
970 'string': field['field_description'],
971 'required': bool(field['required']),
972 'readonly': bool(field['readonly']),
973 'domain': eval(field['domain']) if field['domain'] else None,
974 'size': field['size'],
975 'ondelete': field['on_delete'],
976 'translate': (field['translate']),
978 #'select': int(field['select_level'])
981 if field['ttype'] == 'selection':
982 self._columns[field['name']] = fields.selection(eval(field['selection']), **attrs)
983 elif field['ttype'] == 'reference':
984 self._columns[field['name']] = fields.reference(selection=eval(field['selection']), **attrs)
985 elif field['ttype'] == 'many2one':
986 self._columns[field['name']] = fields.many2one(field['relation'], **attrs)
987 elif field['ttype'] == 'one2many':
988 self._columns[field['name']] = fields.one2many(field['relation'], field['relation_field'], **attrs)
989 elif field['ttype'] == 'many2many':
990 _rel1 = field['relation'].replace('.', '_')
991 _rel2 = field['model'].replace('.', '_')
992 _rel_name = 'x_%s_%s_%s_rel' % (_rel1, _rel2, field['name'])
993 self._columns[field['name']] = fields.many2many(field['relation'], _rel_name, 'id1', 'id2', **attrs)
995 self._columns[field['name']] = getattr(fields, field['ttype'])(**attrs)
996 self._inherits_check()
997 self._inherits_reload()
998 if not self._sequence:
999 self._sequence = self._table + '_id_seq'
1000 for k in self._defaults:
1001 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,)
1002 for f in self._columns:
1003 self._columns[f].restart()
1006 if self.is_transient():
1007 self._transient_check_count = 0
1008 self._transient_max_count = config.get('osv_memory_count_limit')
1009 self._transient_max_hours = config.get('osv_memory_age_limit')
1010 assert self._log_access, "TransientModels must have log_access turned on, "\
1011 "in order to implement their access rights policy"
1013 def __export_row(self, cr, uid, row, fields, context=None):
1017 def check_type(field_type):
1018 if field_type == 'float':
1020 elif field_type == 'integer':
1022 elif field_type == 'boolean':
1026 def selection_field(in_field):
1027 col_obj = self.pool.get(in_field.keys()[0])
1028 if f[i] in col_obj._columns.keys():
1029 return col_obj._columns[f[i]]
1030 elif f[i] in col_obj._inherits.keys():
1031 selection_field(col_obj._inherits)
1036 data = map(lambda x: '', range(len(fields)))
1038 for fpos in range(len(fields)):
1047 model_data = self.pool.get('ir.model.data')
1048 data_ids = model_data.search(cr, uid, [('model', '=', r._table_name), ('res_id', '=', r['id'])])
1050 d = model_data.read(cr, uid, data_ids, ['name', 'module'])[0]
1052 r = '%s.%s' % (d['module'], d['name'])
1058 n = self._table+'_'+str(r['id']) + (postfix and ('_'+str(postfix)) or '' )
1059 if not model_data.search(cr, uid, [('name', '=', n)]):
1062 model_data.create(cr, uid, {
1064 'model': self._name,
1066 'module': '__export__',
1071 # To display external name of selection field when its exported
1073 if f[i] in self._columns.keys():
1074 cols = self._columns[f[i]]
1075 elif f[i] in self._inherit_fields.keys():
1076 cols = selection_field(self._inherits)
1077 if cols and cols._type == 'selection':
1078 sel_list = cols.selection
1079 if r and type(sel_list) == type([]):
1080 r = [x[1] for x in sel_list if r==x[0]]
1081 r = r and r[0] or False
1083 if f[i] in self._columns:
1084 r = check_type(self._columns[f[i]]._type)
1085 elif f[i] in self._inherit_fields:
1086 r = check_type(self._inherit_fields[f[i]][2]._type)
1087 data[fpos] = r or False
1089 if isinstance(r, (browse_record_list, list)):
1091 fields2 = map(lambda x: (x[:i+1]==f[:i+1] and x[i+1:]) \
1094 if [x for x in fields2 if x]:
1096 done.append(fields2)
1098 lines2 = self.__export_row(cr, uid, row2, fields2,
1101 for fpos2 in range(len(fields)):
1102 if lines2 and lines2[0][fpos2]:
1103 data[fpos2] = lines2[0][fpos2]
1107 name_relation = self.pool.get(rr._table_name)._rec_name
1108 if isinstance(rr[name_relation], browse_record):
1109 rr = rr[name_relation]
1110 rr_name = self.pool.get(rr._table_name).name_get(cr, uid, [rr.id], context=context)
1111 rr_name = rr_name and rr_name[0] and rr_name[0][1] or ''
1112 dt += tools.ustr(rr_name or '') + ','
1113 data[fpos] = dt[:-1]
1122 if isinstance(r, browse_record):
1123 r = self.pool.get(r._table_name).name_get(cr, uid, [r.id], context=context)
1124 r = r and r[0] and r[0][1] or ''
1125 data[fpos] = tools.ustr(r or '')
1126 return [data] + lines
1128 def export_data(self, cr, uid, ids, fields_to_export, context=None):
1130 Export fields for selected objects
1132 :param cr: database cursor
1133 :param uid: current user id
1134 :param ids: list of ids
1135 :param fields_to_export: list of fields
1136 :param context: context arguments, like lang, time zone
1137 :rtype: dictionary with a *datas* matrix
1139 This method is used when exporting data via client menu
1144 cols = self._columns.copy()
1145 for f in self._inherit_fields:
1146 cols.update({f: self._inherit_fields[f][2]})
1147 fields_to_export = map(fix_import_export_id_paths, fields_to_export)
1149 for row in self.browse(cr, uid, ids, context):
1150 datas += self.__export_row(cr, uid, row, fields_to_export, context)
1151 return {'datas': datas}
1153 def import_data(self, cr, uid, fields, datas, mode='init', current_module='', noupdate=False, context=None, filename=None):
1155 Import given data in given module
1157 This method is used when importing data via client menu.
1159 Example of fields to import for a sale.order::
1162 partner_id, (=name_search)
1163 order_line/.id, (=database_id)
1165 order_line/product_id/id, (=xml id)
1166 order_line/price_unit,
1167 order_line/product_uom_qty,
1168 order_line/product_uom/id (=xml_id)
1170 This method returns a 4-tuple with the following structure:
1172 * The first item is a return code, it returns either ``-1`` in case o
1174 :param cr: database cursor
1175 :param uid: current user id
1176 :param fields: list of fields
1177 :param data: data to import
1178 :param mode: 'init' or 'update' for record creation
1179 :param current_module: module name
1180 :param noupdate: flag for record creation
1181 :param context: context arguments, like lang, time zone,
1182 :param filename: optional file to store partial import state for recovery
1183 :returns: 4-tuple of a return code, an errored resource, an error message and ???
1184 :rtype: (int, dict|0, str|0, ''|0)
1188 fields = map(fix_import_export_id_paths, fields)
1189 logger = netsvc.Logger()
1190 ir_model_data_obj = self.pool.get('ir.model.data')
1192 # mode: id (XML id) or .id (database id) or False for name_get
1193 def _get_id(model_name, id, current_module=False, mode='id'):
1196 obj_model = self.pool.get(model_name)
1197 ids = obj_model.search(cr, uid, [('id', '=', int(id))])
1199 raise Exception(_("Database ID doesn't exist: %s : %s") %(model_name, id))
1202 module, xml_id = id.rsplit('.', 1)
1204 module, xml_id = current_module, id
1205 record_id = ir_model_data_obj._get_id(cr, uid, module, xml_id)
1206 ir_model_data = ir_model_data_obj.read(cr, uid, [record_id], ['res_id'])
1207 if not ir_model_data:
1208 raise ValueError('No references to %s.%s' % (module, xml_id))
1209 id = ir_model_data[0]['res_id']
1211 obj_model = self.pool.get(model_name)
1212 ids = obj_model.name_search(cr, uid, id, operator='=', context=context)
1214 raise ValueError('No record found for %s' % (id,))
1219 # datas: a list of records, each record is defined by a list of values
1220 # prefix: a list of prefix fields ['line_ids']
1221 # position: the line to process, skip is False if it's the first line of the current record
1223 # (res, position, warning, res_id) with
1224 # res: the record for the next line to process (including it's one2many)
1225 # position: the new position for the next line
1226 # res_id: the ID of the record if it's a modification
1227 def process_liness(self, datas, prefix, current_module, model_name, fields_def, position=0, skip=0):
1228 line = datas[position]
1236 for i in range(len(fields)):
1239 raise Exception(_('Please check that all your lines have %d columns.'
1240 'Stopped around line %d having %d columns.') % \
1241 (len(fields), position+2, len(line)))
1246 if field[:len(prefix)] <> prefix:
1247 if line[i] and skip:
1251 #set the mode for m2o, o2m, m2m : xml_id/id/name
1252 if len(field) == len(prefix)+1:
1255 mode = field[len(prefix)+1]
1257 # TODO: improve this by using csv.csv_reader
1258 def many_ids(line, relation, current_module, mode):
1260 for db_id in line.split(config.get('csv_internal_sep')):
1261 res.append(_get_id(relation, db_id, current_module, mode))
1264 # ID of the record using a XML ID
1265 if field[len(prefix)]=='id':
1267 data_res_id = _get_id(model_name, line[i], current_module, 'id')
1273 # ID of the record using a database ID
1274 elif field[len(prefix)]=='.id':
1275 data_res_id = _get_id(model_name, line[i], current_module, '.id')
1278 # recursive call for getting children and returning [(0,0,{})] or [(1,ID,{})]
1279 if fields_def[field[len(prefix)]]['type']=='one2many':
1280 if field[len(prefix)] in done:
1282 done[field[len(prefix)]] = True
1283 relation = fields_def[field[len(prefix)]]['relation']
1284 relation_obj = self.pool.get(relation)
1285 newfd = relation_obj.fields_get( cr, uid, context=context )
1288 res = many_ids(line[i], relation, current_module, mode)
1291 while pos < len(datas):
1292 res2 = process_liness(self, datas, prefix + [field[len(prefix)]], current_module, relation_obj._name, newfd, pos, first)
1295 (newrow, pos, w2, data_res_id2, xml_id2) = res2
1296 nbrmax = max(nbrmax, pos)
1301 res.append((4, data_res_id2))
1303 if (not newrow) or not reduce(lambda x, y: x or y, newrow.values(), 0):
1306 res.append( (data_res_id2 and 1 or 0, data_res_id2 or 0, newrow) )
1309 elif fields_def[field[len(prefix)]]['type']=='many2one':
1310 relation = fields_def[field[len(prefix)]]['relation']
1311 res = _get_id(relation, line[i], current_module, mode)
1313 elif fields_def[field[len(prefix)]]['type']=='many2many':
1314 relation = fields_def[field[len(prefix)]]['relation']
1315 res = many_ids(line[i], relation, current_module, mode)
1317 elif fields_def[field[len(prefix)]]['type'] == 'integer':
1318 res = line[i] and int(line[i]) or 0
1319 elif fields_def[field[len(prefix)]]['type'] == 'boolean':
1320 res = line[i].lower() not in ('0', 'false', 'off')
1321 elif fields_def[field[len(prefix)]]['type'] == 'float':
1322 res = line[i] and float(line[i]) or 0.0
1323 elif fields_def[field[len(prefix)]]['type'] == 'selection':
1324 for key, val in fields_def[field[len(prefix)]]['selection']:
1325 if tools.ustr(line[i]) in [tools.ustr(key), tools.ustr(val)]:
1328 if line[i] and not res:
1329 logger.notifyChannel("import", netsvc.LOG_WARNING,
1330 _("key '%s' not found in selection field '%s'") % \
1331 (tools.ustr(line[i]), tools.ustr(field[len(prefix)])))
1332 warning += [_("Key/value '%s' not found in selection field '%s'") % (tools.ustr(line[i]), tools.ustr(field[len(prefix)]))]
1337 row[field[len(prefix)]] = res or False
1339 result = (row, nbrmax, warning, data_res_id, xml_id)
1342 fields_def = self.fields_get(cr, uid, context=context)
1344 if config.get('import_partial', False) and filename:
1345 data = pickle.load(file(config.get('import_partial')))
1348 while position<len(datas):
1351 (res, position, warning, res_id, xml_id) = \
1352 process_liness(self, datas, [], current_module, self._name, fields_def, position=position)
1355 return (-1, res, 'Line ' + str(position) +' : ' + '!\n'.join(warning), '')
1358 ir_model_data_obj._update(cr, uid, self._name,
1359 current_module, res, mode=mode, xml_id=xml_id,
1360 noupdate=noupdate, res_id=res_id, context=context)
1361 except Exception, e:
1362 return (-1, res, 'Line ' + str(position) + ' : ' + tools.ustr(e), '')
1364 if config.get('import_partial', False) and filename and (not (position%100)):
1365 data = pickle.load(file(config.get('import_partial')))
1366 data[filename] = position
1367 pickle.dump(data, file(config.get('import_partial'), 'wb'))
1368 if context.get('defer_parent_store_computation'):
1369 self._parent_store_compute(cr)
1372 if context.get('defer_parent_store_computation'):
1373 self._parent_store_compute(cr)
1374 return (position, 0, 0, 0)
1376 def get_invalid_fields(self, cr, uid):
1377 return list(self._invalids)
1379 def _validate(self, cr, uid, ids, context=None):
1380 context = context or {}
1381 lng = context.get('lang', False) or 'en_US'
1382 trans = self.pool.get('ir.translation')
1384 for constraint in self._constraints:
1385 fun, msg, fields = constraint
1386 if not fun(self, cr, uid, ids):
1387 # Check presence of __call__ directly instead of using
1388 # callable() because it will be deprecated as of Python 3.0
1389 if hasattr(msg, '__call__'):
1390 tmp_msg = msg(self, cr, uid, ids, context=context)
1391 if isinstance(tmp_msg, tuple):
1392 tmp_msg, params = tmp_msg
1393 translated_msg = tmp_msg % params
1395 translated_msg = tmp_msg
1397 translated_msg = trans._get_source(cr, uid, self._name, 'constraint', lng, msg) or msg
1399 _("Error occurred while validating the field(s) %s: %s") % (','.join(fields), translated_msg)
1401 self._invalids.update(fields)
1404 raise except_orm('ValidateError', '\n'.join(error_msgs))
1406 self._invalids.clear()
1408 def default_get(self, cr, uid, fields_list, context=None):
1410 Returns default values for the fields in fields_list.
1412 :param fields_list: list of fields to get the default values for (example ['field1', 'field2',])
1413 :type fields_list: list
1414 :param context: optional context dictionary - it may contains keys for specifying certain options
1415 like ``context_lang`` (language) or ``context_tz`` (timezone) to alter the results of the call.
1416 It may contain keys in the form ``default_XXX`` (where XXX is a field name), to set
1417 or override a default value for a field.
1418 A special ``bin_size`` boolean flag may also be passed in the context to request the
1419 value of all fields.binary columns to be returned as the size of the binary instead of its
1420 contents. This can also be selectively overriden by passing a field-specific flag
1421 in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field.
1422 Note: The ``bin_size_XXX`` form is new in OpenERP v6.0.
1423 :return: dictionary of the default values (set on the object model class, through user preferences, or in the context)
1425 # trigger view init hook
1426 self.view_init(cr, uid, fields_list, context)
1432 # get the default values for the inherited fields
1433 for t in self._inherits.keys():
1434 defaults.update(self.pool.get(t).default_get(cr, uid, fields_list,
1437 # get the default values defined in the object
1438 for f in fields_list:
1439 if f in self._defaults:
1440 if callable(self._defaults[f]):
1441 defaults[f] = self._defaults[f](self, cr, uid, context)
1443 defaults[f] = self._defaults[f]
1445 fld_def = ((f in self._columns) and self._columns[f]) \
1446 or ((f in self._inherit_fields) and self._inherit_fields[f][2]) \
1449 if isinstance(fld_def, fields.property):
1450 property_obj = self.pool.get('ir.property')
1451 prop_value = property_obj.get(cr, uid, f, self._name, context=context)
1453 if isinstance(prop_value, (browse_record, browse_null)):
1454 defaults[f] = prop_value.id
1456 defaults[f] = prop_value
1458 if f not in defaults:
1461 # get the default values set by the user and override the default
1462 # values defined in the object
1463 ir_values_obj = self.pool.get('ir.values')
1464 res = ir_values_obj.get(cr, uid, 'default', False, [self._name])
1465 for id, field, field_value in res:
1466 if field in fields_list:
1467 fld_def = (field in self._columns) and self._columns[field] or self._inherit_fields[field][2]
1468 if fld_def._type in ('many2one', 'one2one'):
1469 obj = self.pool.get(fld_def._obj)
1470 if not obj.search(cr, uid, [('id', '=', field_value or False)]):
1472 if fld_def._type in ('many2many'):
1473 obj = self.pool.get(fld_def._obj)
1475 for i in range(len(field_value)):
1476 if not obj.search(cr, uid, [('id', '=',
1479 field_value2.append(field_value[i])
1480 field_value = field_value2
1481 if fld_def._type in ('one2many'):
1482 obj = self.pool.get(fld_def._obj)
1484 for i in range(len(field_value)):
1485 field_value2.append({})
1486 for field2 in field_value[i]:
1487 if field2 in obj._columns.keys() and obj._columns[field2]._type in ('many2one', 'one2one'):
1488 obj2 = self.pool.get(obj._columns[field2]._obj)
1489 if not obj2.search(cr, uid,
1490 [('id', '=', field_value[i][field2])]):
1492 elif field2 in obj._inherit_fields.keys() and obj._inherit_fields[field2][2]._type in ('many2one', 'one2one'):
1493 obj2 = self.pool.get(obj._inherit_fields[field2][2]._obj)
1494 if not obj2.search(cr, uid,
1495 [('id', '=', field_value[i][field2])]):
1497 # TODO add test for many2many and one2many
1498 field_value2[i][field2] = field_value[i][field2]
1499 field_value = field_value2
1500 defaults[field] = field_value
1502 # get the default values from the context
1503 for key in context or {}:
1504 if key.startswith('default_') and (key[8:] in fields_list):
1505 defaults[key[8:]] = context[key]
1508 def fields_get_keys(self, cr, user, context=None):
1509 res = self._columns.keys()
1510 # TODO I believe this loop can be replace by
1511 # res.extend(self._inherit_fields.key())
1512 for parent in self._inherits:
1513 res.extend(self.pool.get(parent).fields_get_keys(cr, user, context))
1517 # Overload this method if you need a window title which depends on the context
1519 def view_header_get(self, cr, user, view_id=None, view_type='form', context=None):
1522 def __view_look_dom(self, cr, user, node, view_id, in_tree_view, model_fields, context=None):
1523 """ Return the description of the fields in the node.
1525 In a normal call to this method, node is a complete view architecture
1526 but it is actually possible to give some sub-node (this is used so
1527 that the method can call itself recursively).
1529 Originally, the field descriptions are drawn from the node itself.
1530 But there is now some code calling fields_get() in order to merge some
1531 of those information in the architecture.
1543 if isinstance(s, unicode):
1544 return s.encode('utf8')
1547 def check_group(node):
1548 """ Set invisible to true if the user is not in the specified groups. """
1549 if node.get('groups'):
1550 groups = node.get('groups').split(',')
1551 ir_model_access = self.pool.get('ir.model.access')
1552 can_see = any(ir_model_access.check_groups(cr, user, group) for group in groups)
1554 node.set('invisible', '1')
1555 modifiers['invisible'] = True
1556 if 'attrs' in node.attrib:
1557 del(node.attrib['attrs']) #avoid making field visible later
1558 del(node.attrib['groups'])
1560 if node.tag in ('field', 'node', 'arrow'):
1561 if node.get('object'):
1566 if f.tag in ('field'):
1567 xml += etree.tostring(f, encoding="utf-8")
1569 new_xml = etree.fromstring(encode(xml))
1570 ctx = context.copy()
1571 ctx['base_model_name'] = self._name
1572 xarch, xfields = self.pool.get(node.get('object')).__view_look_dom_arch(cr, user, new_xml, view_id, ctx)
1577 attrs = {'views': views}
1579 if node.get('name'):
1582 if node.get('name') in self._columns:
1583 column = self._columns[node.get('name')]
1585 column = self._inherit_fields[node.get('name')][2]
1590 relation = self.pool.get(column._obj)
1595 if f.tag in ('form', 'tree', 'graph'):
1597 ctx = context.copy()
1598 ctx['base_model_name'] = self._name
1599 xarch, xfields = relation.__view_look_dom_arch(cr, user, f, view_id, ctx)
1600 views[str(f.tag)] = {
1604 attrs = {'views': views}
1605 if node.get('widget') and node.get('widget') == 'selection':
1606 # Prepare the cached selection list for the client. This needs to be
1607 # done even when the field is invisible to the current user, because
1608 # other events could need to change its value to any of the selectable ones
1609 # (such as on_change events, refreshes, etc.)
1611 # If domain and context are strings, we keep them for client-side, otherwise
1612 # we evaluate them server-side to consider them when generating the list of
1614 # TODO: find a way to remove this hack, by allow dynamic domains
1616 if column._domain and not isinstance(column._domain, basestring):
1617 dom = column._domain
1618 dom += eval(node.get('domain', '[]'), {'uid': user, 'time': time})
1619 search_context = dict(context)
1620 if column._context and not isinstance(column._context, basestring):
1621 search_context.update(column._context)
1622 attrs['selection'] = relation._name_search(cr, user, '', dom, context=search_context, limit=None, name_get_uid=1)
1623 if (node.get('required') and not int(node.get('required'))) or not column.required:
1624 attrs['selection'].append((False, ''))
1625 fields[node.get('name')] = attrs
1627 field = model_fields.get(node.get('name'))
1629 transfer_field_to_modifiers(field, modifiers)
1632 elif node.tag in ('form', 'tree'):
1633 result = self.view_header_get(cr, user, False, node.tag, context)
1635 node.set('string', result)
1636 in_tree_view = node.tag == 'tree'
1638 elif node.tag == 'calendar':
1639 for additional_field in ('date_start', 'date_delay', 'date_stop', 'color'):
1640 if node.get(additional_field):
1641 fields[node.get(additional_field)] = {}
1645 # The view architeture overrides the python model.
1646 # Get the attrs before they are (possibly) deleted by check_group below
1647 transfer_node_to_modifiers(node, modifiers, context, in_tree_view)
1649 # TODO remove attrs couterpart in modifiers when invisible is true ?
1652 if 'lang' in context:
1653 if node.get('string') and not result:
1654 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('string'))
1655 if trans == node.get('string') and ('base_model_name' in context):
1656 # If translation is same as source, perhaps we'd have more luck with the alternative model name
1657 # (in case we are in a mixed situation, such as an inherited view where parent_view.model != model
1658 trans = self.pool.get('ir.translation')._get_source(cr, user, context['base_model_name'], 'view', context['lang'], node.get('string'))
1660 node.set('string', trans)
1661 if node.get('confirm'):
1662 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('confirm'))
1664 node.set('confirm', trans)
1666 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('sum'))
1668 node.set('sum', trans)
1669 if node.get('help'):
1670 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('help'))
1672 node.set('help', trans)
1675 if children or (node.tag == 'field' and f.tag in ('filter','separator')):
1676 fields.update(self.__view_look_dom(cr, user, f, view_id, in_tree_view, model_fields, context))
1678 transfer_modifiers_to_node(modifiers, node)
1681 def _disable_workflow_buttons(self, cr, user, node):
1682 """ Set the buttons in node to readonly if the user can't activate them. """
1684 # admin user can always activate workflow buttons
1687 # TODO handle the case of more than one workflow for a model or multiple
1688 # transitions with different groups and same signal
1689 usersobj = self.pool.get('res.users')
1690 buttons = (n for n in node.getiterator('button') if n.get('type') != 'object')
1691 for button in buttons:
1692 user_groups = usersobj.read(cr, user, [user], ['groups_id'])[0]['groups_id']
1693 cr.execute("""SELECT DISTINCT t.group_id
1695 INNER JOIN wkf_activity a ON a.wkf_id = wkf.id
1696 INNER JOIN wkf_transition t ON (t.act_to = a.id)
1699 AND t.group_id is NOT NULL
1700 """, (self._name, button.get('name')))
1701 group_ids = [x[0] for x in cr.fetchall() if x[0]]
1702 can_click = not group_ids or bool(set(user_groups).intersection(group_ids))
1703 button.set('readonly', str(int(not can_click)))
1706 def __view_look_dom_arch(self, cr, user, node, view_id, context=None):
1707 """ Return an architecture and a description of all the fields.
1709 The field description combines the result of fields_get() and
1712 :param node: the architecture as as an etree
1713 :return: a tuple (arch, fields) where arch is the given node as a
1714 string and fields is the description of all the fields.
1718 if node.tag == 'diagram':
1719 if node.getchildren()[0].tag == 'node':
1720 node_fields = self.pool.get(node.getchildren()[0].get('object')).fields_get(cr, user, None, context)
1721 fields.update(node_fields)
1722 if node.getchildren()[1].tag == 'arrow':
1723 arrow_fields = self.pool.get(node.getchildren()[1].get('object')).fields_get(cr, user, None, context)
1724 fields.update(arrow_fields)
1726 fields = self.fields_get(cr, user, None, context)
1727 fields_def = self.__view_look_dom(cr, user, node, view_id, False, fields, context=context)
1728 node = self._disable_workflow_buttons(cr, user, node)
1729 arch = etree.tostring(node, encoding="utf-8").replace('\t', '')
1730 for k in fields.keys():
1731 if k not in fields_def:
1733 for field in fields_def:
1735 # sometime, the view may contain the (invisible) field 'id' needed for a domain (when 2 objects have cross references)
1736 fields['id'] = {'readonly': True, 'type': 'integer', 'string': 'ID'}
1737 elif field in fields:
1738 fields[field].update(fields_def[field])
1740 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))
1741 res = cr.fetchall()[:]
1743 res.insert(0, ("Can't find field '%s' in the following view parts composing the view of object model '%s':" % (field, model), None))
1744 msg = "\n * ".join([r[0] for r in res])
1745 msg += "\n\nEither you wrongly customized this view, or some modules bringing those views are not compatible with your current data model"
1746 netsvc.Logger().notifyChannel('orm', netsvc.LOG_ERROR, msg)
1747 raise except_orm('View error', msg)
1750 def _get_default_form_view(self, cr, user, context=None):
1751 """ Generates a default single-line form view using all fields
1752 of the current model except the m2m and o2m ones.
1754 :param cr: database cursor
1755 :param int user: user id
1756 :param dict context: connection context
1757 :returns: a form view as an lxml document
1758 :rtype: etree._Element
1760 view = etree.Element('form', string=self._description)
1761 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
1762 for field, descriptor in self.fields_get(cr, user, context=context).iteritems():
1763 if descriptor['type'] in ('one2many', 'many2many'):
1765 etree.SubElement(view, 'field', name=field)
1766 if descriptor['type'] == 'text':
1767 etree.SubElement(view, 'newline')
1770 def _get_default_tree_view(self, cr, user, context=None):
1771 """ Generates a single-field tree view, using _rec_name if
1772 it's one of the columns or the first column it finds otherwise
1774 :param cr: database cursor
1775 :param int user: user id
1776 :param dict context: connection context
1777 :returns: a tree view as an lxml document
1778 :rtype: etree._Element
1780 _rec_name = self._rec_name
1781 if _rec_name not in self._columns:
1782 _rec_name = self._columns.keys()[0]
1784 view = etree.Element('tree', string=self._description)
1785 etree.SubElement(view, 'field', name=_rec_name)
1788 def _get_default_calendar_view(self, cr, user, context=None):
1789 """ Generates a default calendar view by trying to infer
1790 calendar fields from a number of pre-set attribute names
1792 :param cr: database cursor
1793 :param int user: user id
1794 :param dict context: connection context
1795 :returns: a calendar view
1796 :rtype: etree._Element
1798 def set_first_of(seq, in_, to):
1799 """Sets the first value of ``seq`` also found in ``in_`` to
1800 the ``to`` attribute of the view being closed over.
1802 Returns whether it's found a suitable value (and set it on
1803 the attribute) or not
1811 view = etree.Element('calendar', string=self._description)
1812 etree.SubElement(view, 'field', name=self._rec_name)
1814 if (self._date_name not in self._columns):
1816 for dt in ['date', 'date_start', 'x_date', 'x_date_start']:
1817 if dt in self._columns:
1818 self._date_name = dt
1823 raise except_orm(_('Invalid Object Architecture!'), _("Insufficient fields for Calendar View!"))
1824 view.set('date_start', self._date_name)
1826 set_first_of(["user_id", "partner_id", "x_user_id", "x_partner_id"],
1827 self._columns, 'color')
1829 if not set_first_of(["date_stop", "date_end", "x_date_stop", "x_date_end"],
1830 self._columns, 'date_stop'):
1831 if not set_first_of(["date_delay", "planned_hours", "x_date_delay", "x_planned_hours"],
1832 self._columns, 'date_delay'):
1834 _('Invalid Object Architecture!'),
1835 _("Insufficient fields to generate a Calendar View for %s, missing a date_stop or a date_delay" % (self._name)))
1839 def _get_default_search_view(self, cr, uid, context=None):
1841 :param cr: database cursor
1842 :param int user: user id
1843 :param dict context: connection context
1844 :returns: an lxml document of the view
1845 :rtype: etree._Element
1847 form_view = self.fields_view_get(cr, uid, False, 'form', context=context)
1848 tree_view = self.fields_view_get(cr, uid, False, 'tree', context=context)
1850 # TODO it seems _all_columns could be used instead of fields_get (no need for translated fields info)
1851 fields = self.fields_get(cr, uid, context=context)
1852 fields_to_search = set(
1853 field for field, descriptor in fields.iteritems()
1854 if descriptor.get('select'))
1856 for view in (form_view, tree_view):
1857 view_root = etree.fromstring(view['arch'])
1858 # Only care about select=1 in xpath below, because select=2 is covered
1859 # by the custom advanced search in clients
1860 fields_to_search.update(view_root.xpath("//field[@select=1]/@name"))
1862 tree_view_root = view_root # as provided by loop above
1863 search_view = etree.Element("search", string=tree_view_root.get("string", ""))
1865 field_group = etree.SubElement(search_view, "group")
1866 for field_name in fields_to_search:
1867 etree.SubElement(field_group, "field", name=field_name)
1872 # if view_id, view_type is not required
1874 def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
1876 Get the detailed composition of the requested view like fields, model, view architecture
1878 :param cr: database cursor
1879 :param user: current user id
1880 :param view_id: id of the view or None
1881 :param view_type: type of the view to return if view_id is None ('form', tree', ...)
1882 :param context: context arguments, like lang, time zone
1883 :param toolbar: true to include contextual actions
1884 :param submenu: deprecated
1885 :return: dictionary describing the composition of the requested view (including inherited views and extensions)
1886 :raise AttributeError:
1887 * if the inherited view has unknown position to work with other than 'before', 'after', 'inside', 'replace'
1888 * if some tag other than 'position' is found in parent view
1889 :raise Invalid ArchitectureError: if there is view type other than form, tree, calendar, search etc defined on the structure
1896 if isinstance(s, unicode):
1897 return s.encode('utf8')
1900 def raise_view_error(error_msg, child_view_id):
1901 view, child_view = self.pool.get('ir.ui.view').browse(cr, user, [view_id, child_view_id], context)
1902 raise AttributeError("View definition error for inherited view '%s' on model '%s': %s"
1903 % (child_view.xml_id, self._name, error_msg))
1905 def locate(source, spec):
1906 """ Locate a node in a source (parent) architecture.
1908 Given a complete source (parent) architecture (i.e. the field
1909 `arch` in a view), and a 'spec' node (a node in an inheriting
1910 view that specifies the location in the source view of what
1911 should be changed), return (if it exists) the node in the
1912 source view matching the specification.
1914 :param source: a parent architecture to modify
1915 :param spec: a modifying node in an inheriting view
1916 :return: a node in the source matching the spec
1919 if spec.tag == 'xpath':
1920 nodes = source.xpath(spec.get('expr'))
1921 return nodes[0] if nodes else None
1922 elif spec.tag == 'field':
1923 # Only compare the field name: a field can be only once in a given view
1924 # at a given level (and for multilevel expressions, we should use xpath
1925 # inheritance spec anyway).
1926 for node in source.getiterator('field'):
1927 if node.get('name') == spec.get('name'):
1931 for node in source.getiterator(spec.tag):
1933 for attr in spec.attrib:
1934 if attr != 'position' and (not node.get(attr) or node.get(attr) != spec.get(attr)):
1941 def apply_inheritance_specs(source, specs_arch, inherit_id=None):
1942 """ Apply an inheriting view.
1944 Apply to a source architecture all the spec nodes (i.e. nodes
1945 describing where and what changes to apply to some parent
1946 architecture) given by an inheriting view.
1948 :param source: a parent architecture to modify
1949 :param specs_arch: a modifying architecture in an inheriting view
1950 :param inherit_id: the database id of the inheriting view
1951 :return: a modified source where the specs are applied
1954 specs_tree = etree.fromstring(encode(specs_arch))
1955 # Queue of specification nodes (i.e. nodes describing where and
1956 # changes to apply to some parent architecture).
1957 specs = [specs_tree]
1961 if isinstance(spec, SKIPPED_ELEMENT_TYPES):
1963 if spec.tag == 'data':
1964 specs += [ c for c in specs_tree ]
1966 node = locate(source, spec)
1967 if node is not None:
1968 pos = spec.get('position', 'inside')
1969 if pos == 'replace':
1970 if node.getparent() is None:
1971 source = copy.deepcopy(spec[0])
1974 node.addprevious(child)
1975 node.getparent().remove(node)
1976 elif pos == 'attributes':
1977 for child in spec.getiterator('attribute'):
1978 attribute = (child.get('name'), child.text and child.text.encode('utf8') or None)
1980 node.set(attribute[0], attribute[1])
1982 del(node.attrib[attribute[0]])
1984 sib = node.getnext()
1988 elif pos == 'after':
1993 sib.addprevious(child)
1994 elif pos == 'before':
1995 node.addprevious(child)
1997 raise_view_error("Invalid position value: '%s'" % pos, inherit_id)
2000 ' %s="%s"' % (attr, spec.get(attr))
2001 for attr in spec.attrib
2002 if attr != 'position'
2004 tag = "<%s%s>" % (spec.tag, attrs)
2005 raise_view_error("Element '%s' not found in parent view '%%(parent_xml_id)s'" % tag, inherit_id)
2008 def apply_view_inheritance(cr, user, source, inherit_id):
2009 """ Apply all the (directly and indirectly) inheriting views.
2011 :param source: a parent architecture to modify (with parent
2012 modifications already applied)
2013 :param inherit_id: the database view_id of the parent view
2014 :return: a modified source where all the modifying architecture
2018 sql_inherit = self.pool.get('ir.ui.view').get_inheriting_views_arch(cr, user, inherit_id, self._name)
2019 for (view_arch, view_id) in sql_inherit:
2020 source = apply_inheritance_specs(source, view_arch, view_id)
2021 source = apply_view_inheritance(cr, user, source, view_id)
2024 result = {'type': view_type, 'model': self._name}
2027 parent_view_model = None
2028 view_ref = context.get(view_type + '_view_ref')
2029 # Search for a root (i.e. without any parent) view.
2031 if view_ref and not view_id:
2033 module, view_ref = view_ref.split('.', 1)
2034 cr.execute("SELECT res_id FROM ir_model_data WHERE model='ir.ui.view' AND module=%s AND name=%s", (module, view_ref))
2035 view_ref_res = cr.fetchone()
2037 view_id = view_ref_res[0]
2040 cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model
2042 WHERE id=%s""", (view_id,))
2044 cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model
2046 WHERE model=%s AND type=%s AND inherit_id IS NULL
2047 ORDER BY priority""", (self._name, view_type))
2048 sql_res = cr.dictfetchone()
2053 view_id = sql_res['inherit_id'] or sql_res['id']
2054 parent_view_model = sql_res['model']
2055 if not sql_res['inherit_id']:
2058 # if a view was found
2060 source = etree.fromstring(encode(sql_res['arch']))
2062 arch=apply_view_inheritance(cr, user, source, sql_res['id']),
2063 type=sql_res['type'],
2064 view_id=sql_res['id'],
2065 name=sql_res['name'],
2066 field_parent=sql_res['field_parent'] or False)
2068 # otherwise, build some kind of default view
2070 view = getattr(self, '_get_default_%s_view' % view_type)(
2072 except AttributeError:
2073 # what happens here, graph case?
2074 raise except_orm(_('Invalid Architecture!'), _("There is no view of type '%s' defined for the structure!") % view_type)
2082 if parent_view_model != self._name:
2083 ctx = context.copy()
2084 ctx['base_model_name'] = parent_view_model
2087 xarch, xfields = self.__view_look_dom_arch(cr, user, result['arch'], view_id, context=ctx)
2088 result['arch'] = xarch
2089 result['fields'] = xfields
2094 for key in ('report_sxw_content', 'report_rml_content',
2095 'report_sxw', 'report_rml',
2096 'report_sxw_content_data', 'report_rml_content_data'):
2100 ir_values_obj = self.pool.get('ir.values')
2101 resprint = ir_values_obj.get(cr, user, 'action',
2102 'client_print_multi', [(self._name, False)], False,
2104 resaction = ir_values_obj.get(cr, user, 'action',
2105 'client_action_multi', [(self._name, False)], False,
2108 resrelate = ir_values_obj.get(cr, user, 'action',
2109 'client_action_relate', [(self._name, False)], False,
2111 resaction = [clean(action) for action in resaction
2112 if view_type == 'tree' or not action[2].get('multi')]
2113 resprint = [clean(print_) for print_ in resprint
2114 if view_type == 'tree' or not print_[2].get('multi')]
2115 resrelate = map(lambda x: x[2], resrelate)
2117 for x in itertools.chain(resprint, resaction, resrelate):
2118 x['string'] = x['name']
2120 result['toolbar'] = {
2122 'action': resaction,
2127 _view_look_dom_arch = __view_look_dom_arch
2129 def search_count(self, cr, user, args, context=None):
2132 res = self.search(cr, user, args, context=context, count=True)
2133 if isinstance(res, list):
2137 def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
2139 Search for records based on a search domain.
2141 :param cr: database cursor
2142 :param user: current user id
2143 :param args: list of tuples specifying the search domain [('field_name', 'operator', value), ...]. Pass an empty list to match all records.
2144 :param offset: optional number of results to skip in the returned values (default: 0)
2145 :param limit: optional max number of records to return (default: **None**)
2146 :param order: optional columns to sort by (default: self._order=id )
2147 :param context: optional context arguments, like lang, time zone
2148 :type context: dictionary
2149 :param count: optional (default: **False**), if **True**, returns only the number of records matching the criteria, not their ids
2150 :return: id or list of ids of records matching the criteria
2151 :rtype: integer or list of integers
2152 :raise AccessError: * if user tries to bypass access rules for read on the requested object.
2154 **Expressing a search domain (args)**
2156 Each tuple in the search domain needs to have 3 elements, in the form: **('field_name', 'operator', value)**, where:
2158 * **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.
2159 * **operator** must be a string with a valid comparison operator from this list: ``=, !=, >, >=, <, <=, like, ilike, in, not in, child_of, parent_left, parent_right``
2160 The semantics of most of these operators are obvious.
2161 The ``child_of`` operator will look for records who are children or grand-children of a given record,
2162 according to the semantics of this model (i.e following the relationship field named by
2163 ``self._parent_name``, by default ``parent_id``.
2164 * **value** must be a valid value to compare with the values of **field_name**, depending on its type.
2166 Domain criteria can be combined using 3 logical operators than can be added between tuples: '**&**' (logical AND, default), '**|**' (logical OR), '**!**' (logical NOT).
2167 These are **prefix** operators and the arity of the '**&**' and '**|**' operator is 2, while the arity of the '**!**' is just 1.
2168 Be very careful about this when you combine them the first time.
2170 Here is an example of searching for Partners named *ABC* from Belgium and Germany whose language is not english ::
2172 [('name','=','ABC'),'!',('language.code','=','en_US'),'|',('country_id.code','=','be'),('country_id.code','=','de'))
2174 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::
2176 (name is 'ABC' AND (language is NOT english) AND (country is Belgium OR Germany))
2179 return self._search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count)
2181 def name_get(self, cr, user, ids, context=None):
2182 """Returns the preferred display value (text representation) for the records with the
2183 given ``ids``. By default this will be the value of the ``name`` column, unless
2184 the model implements a custom behavior.
2185 Can sometimes be seen as the inverse function of :meth:`~.name_search`, but it is not
2189 :return: list of pairs ``(id,text_repr)`` for all records with the given ``ids``.
2193 if isinstance(ids, (int, long)):
2195 return [(r['id'], tools.ustr(r[self._rec_name])) for r in self.read(cr, user, ids,
2196 [self._rec_name], context, load='_classic_write')]
2198 def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
2199 """Search for records that have a display name matching the given ``name`` pattern if compared
2200 with the given ``operator``, while also matching the optional search domain (``args``).
2201 This is used for example to provide suggestions based on a partial value for a relational
2203 Sometimes be seen as the inverse function of :meth:`~.name_get`, but it is not
2206 This method is equivalent to calling :meth:`~.search` with a search domain based on ``name``
2207 and then :meth:`~.name_get` on the result of the search.
2209 :param list args: optional search domain (see :meth:`~.search` for syntax),
2210 specifying further restrictions
2211 :param str operator: domain operator for matching the ``name`` pattern, such as ``'like'``
2213 :param int limit: optional max number of records to return
2215 :return: list of pairs ``(id,text_repr)`` for all matching records.
2217 return self._name_search(cr, user, name, args, operator, context, limit)
2219 def name_create(self, cr, uid, name, context=None):
2220 """Creates a new record by calling :meth:`~.create` with only one
2221 value provided: the name of the new record (``_rec_name`` field).
2222 The new record will also be initialized with any default values applicable
2223 to this model, or provided through the context. The usual behavior of
2224 :meth:`~.create` applies.
2225 Similarly, this method may raise an exception if the model has multiple
2226 required fields and some do not have default values.
2228 :param name: name of the record to create
2231 :return: the :meth:`~.name_get` pair value for the newly-created record.
2233 rec_id = self.create(cr, uid, {self._rec_name: name}, context);
2234 return self.name_get(cr, uid, [rec_id], context)[0]
2236 # private implementation of name_search, allows passing a dedicated user for the name_get part to
2237 # solve some access rights issues
2238 def _name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100, name_get_uid=None):
2245 args += [(self._rec_name, operator, name)]
2246 access_rights_uid = name_get_uid or user
2247 ids = self._search(cr, user, args, limit=limit, context=context, access_rights_uid=access_rights_uid)
2248 res = self.name_get(cr, access_rights_uid, ids, context)
2251 def read_string(self, cr, uid, id, langs, fields=None, context=None):
2254 self.pool.get('ir.translation').check_read(cr, uid)
2256 fields = self._columns.keys() + self._inherit_fields.keys()
2257 #FIXME: collect all calls to _get_source into one SQL call.
2259 res[lang] = {'code': lang}
2261 if f in self._columns:
2262 res_trans = self.pool.get('ir.translation')._get_source(cr, uid, self._name+','+f, 'field', lang)
2264 res[lang][f] = res_trans
2266 res[lang][f] = self._columns[f].string
2267 for table in self._inherits:
2268 cols = intersect(self._inherit_fields.keys(), fields)
2269 res2 = self.pool.get(table).read_string(cr, uid, id, langs, cols, context)
2272 res[lang]['code'] = lang
2273 for f in res2[lang]:
2274 res[lang][f] = res2[lang][f]
2277 def write_string(self, cr, uid, id, langs, vals, context=None):
2278 self.pool.get('ir.translation').check_write(cr, uid)
2279 #FIXME: try to only call the translation in one SQL
2282 if field in self._columns:
2283 src = self._columns[field].string
2284 self.pool.get('ir.translation')._set_ids(cr, uid, self._name+','+field, 'field', lang, [0], vals[field], src)
2285 for table in self._inherits:
2286 cols = intersect(self._inherit_fields.keys(), vals)
2288 self.pool.get(table).write_string(cr, uid, id, langs, vals, context)
2291 def _add_missing_default_values(self, cr, uid, values, context=None):
2292 missing_defaults = []
2293 avoid_tables = [] # avoid overriding inherited values when parent is set
2294 for tables, parent_field in self._inherits.items():
2295 if parent_field in values:
2296 avoid_tables.append(tables)
2297 for field in self._columns.keys():
2298 if not field in values:
2299 missing_defaults.append(field)
2300 for field in self._inherit_fields.keys():
2301 if (field not in values) and (self._inherit_fields[field][0] not in avoid_tables):
2302 missing_defaults.append(field)
2304 if len(missing_defaults):
2305 # override defaults with the provided values, never allow the other way around
2306 defaults = self.default_get(cr, uid, missing_defaults, context)
2308 if ((dv in self._columns and self._columns[dv]._type == 'many2many') \
2309 or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'many2many')) \
2310 and defaults[dv] and isinstance(defaults[dv][0], (int, long)):
2311 defaults[dv] = [(6, 0, defaults[dv])]
2312 if (dv in self._columns and self._columns[dv]._type == 'one2many' \
2313 or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'one2many')) \
2314 and isinstance(defaults[dv], (list, tuple)) and defaults[dv] and isinstance(defaults[dv][0], dict):
2315 defaults[dv] = [(0, 0, x) for x in defaults[dv]]
2316 defaults.update(values)
2320 def clear_caches(self):
2321 """ Clear the caches
2323 This clears the caches associated to methods decorated with
2324 ``tools.ormcache`` or ``tools.ormcache_multi``.
2327 getattr(self, '_ormcache')
2329 except AttributeError:
2332 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False):
2334 Get the list of records in list view grouped by the given ``groupby`` fields
2336 :param cr: database cursor
2337 :param uid: current user id
2338 :param domain: list specifying search criteria [['field_name', 'operator', 'value'], ...]
2339 :param list fields: list of fields present in the list view specified on the object
2340 :param list groupby: fields by which the records will be grouped
2341 :param int offset: optional number of records to skip
2342 :param int limit: optional max number of records to return
2343 :param dict context: context arguments, like lang, time zone
2344 :param list orderby: optional ``order by`` specification, for
2345 overriding the natural sort ordering of the
2346 groups, see also :py:meth:`~osv.osv.osv.search`
2347 (supported only for many2one fields currently)
2348 :return: list of dictionaries(one dictionary for each record) containing:
2350 * the values of fields grouped by the fields in ``groupby`` argument
2351 * __domain: list of tuples specifying the search criteria
2352 * __context: dictionary with argument like ``groupby``
2353 :rtype: [{'field_name_1': value, ...]
2354 :raise AccessError: * if user has no read rights on the requested object
2355 * if user tries to bypass access rules for read on the requested object
2358 context = context or {}
2359 self.check_read(cr, uid)
2361 fields = self._columns.keys()
2363 query = self._where_calc(cr, uid, domain, context=context)
2364 self._apply_ir_rules(cr, uid, query, 'read', context=context)
2366 # Take care of adding join(s) if groupby is an '_inherits'ed field
2367 groupby_list = groupby
2368 qualified_groupby_field = groupby
2370 if isinstance(groupby, list):
2371 groupby = groupby[0]
2372 qualified_groupby_field = self._inherits_join_calc(groupby, query)
2375 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?)"
2376 groupby_def = self._columns.get(groupby) or (self._inherit_fields.get(groupby) and self._inherit_fields.get(groupby)[2])
2377 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"
2379 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
2380 fget = self.fields_get(cr, uid, fields)
2381 float_int_fields = filter(lambda x: fget[x]['type'] in ('float', 'integer'), fields)
2383 group_count = group_by = groupby
2385 if fget.get(groupby):
2386 if fget[groupby]['type'] in ('date', 'datetime'):
2387 flist = "to_char(%s,'yyyy-mm') as %s " % (qualified_groupby_field, groupby)
2388 groupby = "to_char(%s,'yyyy-mm')" % (qualified_groupby_field)
2389 qualified_groupby_field = groupby
2391 flist = qualified_groupby_field
2393 # Don't allow arbitrary values, as this would be a SQL injection vector!
2394 raise except_orm(_('Invalid group_by'),
2395 _('Invalid group_by specification: "%s".\nA group_by specification must be a list of valid fields.')%(groupby,))
2398 fields_pre = [f for f in float_int_fields if
2399 f == self.CONCURRENCY_CHECK_FIELD
2400 or (f in self._columns and getattr(self._columns[f], '_classic_write'))]
2401 for f in fields_pre:
2402 if f not in ['id', 'sequence']:
2403 group_operator = fget[f].get('group_operator', 'sum')
2406 qualified_field = '"%s"."%s"' % (self._table, f)
2407 flist += "%s(%s) AS %s" % (group_operator, qualified_field, f)
2409 gb = groupby and (' GROUP BY ' + qualified_groupby_field) or ''
2411 from_clause, where_clause, where_clause_params = query.get_sql()
2412 where_clause = where_clause and ' WHERE ' + where_clause
2413 limit_str = limit and ' limit %d' % limit or ''
2414 offset_str = offset and ' offset %d' % offset or ''
2415 if len(groupby_list) < 2 and context.get('group_by_no_leaf'):
2417 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)
2420 for r in cr.dictfetchall():
2421 for fld, val in r.items():
2422 if val == None: r[fld] = False
2423 alldata[r['id']] = r
2426 data_ids = self.search(cr, uid, [('id', 'in', alldata.keys())], order=orderby or groupby, context=context)
2427 # the IDS of records that have groupby field value = False or '' should be sorted too
2428 data_ids += filter(lambda x:x not in data_ids, alldata.keys())
2429 data = self.read(cr, uid, data_ids, groupby and [groupby] or ['id'], context=context)
2430 # 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):
2431 data.sort(lambda x,y: cmp(data_ids.index(x['id']), data_ids.index(y['id'])))
2435 d['__domain'] = [(groupby, '=', alldata[d['id']][groupby] or False)] + domain
2436 if not isinstance(groupby_list, (str, unicode)):
2437 if groupby or not context.get('group_by_no_leaf', False):
2438 d['__context'] = {'group_by': groupby_list[1:]}
2439 if groupby and groupby in fget:
2440 if d[groupby] and fget[groupby]['type'] in ('date', 'datetime'):
2441 dt = datetime.datetime.strptime(alldata[d['id']][groupby][:7], '%Y-%m')
2442 days = calendar.monthrange(dt.year, dt.month)[1]
2444 d[groupby] = datetime.datetime.strptime(d[groupby][:10], '%Y-%m-%d').strftime('%B %Y')
2445 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),\
2446 (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
2447 del alldata[d['id']][groupby]
2448 d.update(alldata[d['id']])
2452 def _inherits_join_add(self, current_table, parent_model_name, query):
2454 Add missing table SELECT and JOIN clause to ``query`` for reaching the parent table (no duplicates)
2455 :param current_table: current model object
2456 :param parent_model_name: name of the parent model for which the clauses should be added
2457 :param query: query object on which the JOIN should be added
2459 inherits_field = current_table._inherits[parent_model_name]
2460 parent_model = self.pool.get(parent_model_name)
2461 parent_table_name = parent_model._table
2462 quoted_parent_table_name = '"%s"' % parent_table_name
2463 if quoted_parent_table_name not in query.tables:
2464 query.tables.append(quoted_parent_table_name)
2465 query.where_clause.append('(%s.%s = %s.id)' % (current_table._table, inherits_field, parent_table_name))
2469 def _inherits_join_calc(self, field, query):
2471 Adds missing table select and join clause(s) to ``query`` for reaching
2472 the field coming from an '_inherits' parent table (no duplicates).
2474 :param field: name of inherited field to reach
2475 :param query: query object on which the JOIN should be added
2476 :return: qualified name of field, to be used in SELECT clause
2478 current_table = self
2479 while field in current_table._inherit_fields and not field in current_table._columns:
2480 parent_model_name = current_table._inherit_fields[field][0]
2481 parent_table = self.pool.get(parent_model_name)
2482 self._inherits_join_add(current_table, parent_model_name, query)
2483 current_table = parent_table
2484 return '"%s".%s' % (current_table._table, field)
2486 def _parent_store_compute(self, cr):
2487 if not self._parent_store:
2489 logger = netsvc.Logger()
2490 logger.notifyChannel('data', netsvc.LOG_INFO, 'Computing parent left and right for table %s...' % (self._table, ))
2491 def browse_rec(root, pos=0):
2493 where = self._parent_name+'='+str(root)
2495 where = self._parent_name+' IS NULL'
2496 if self._parent_order:
2497 where += ' order by '+self._parent_order
2498 cr.execute('SELECT id FROM '+self._table+' WHERE '+where)
2500 for id in cr.fetchall():
2501 pos2 = browse_rec(id[0], pos2)
2502 cr.execute('update '+self._table+' set parent_left=%s, parent_right=%s where id=%s', (pos, pos2, root))
2504 query = 'SELECT id FROM '+self._table+' WHERE '+self._parent_name+' IS NULL'
2505 if self._parent_order:
2506 query += ' order by ' + self._parent_order
2509 for (root,) in cr.fetchall():
2510 pos = browse_rec(root, pos)
2513 def _update_store(self, cr, f, k):
2514 logger = netsvc.Logger()
2515 logger.notifyChannel('data', netsvc.LOG_INFO, "storing computed values of fields.function '%s'" % (k,))
2516 ss = self._columns[k]._symbol_set
2517 update_query = 'UPDATE "%s" SET "%s"=%s WHERE id=%%s' % (self._table, k, ss[0])
2518 cr.execute('select id from '+self._table)
2519 ids_lst = map(lambda x: x[0], cr.fetchall())
2522 ids_lst = ids_lst[40:]
2523 res = f.get(cr, self, iids, k, SUPERUSER_ID, {})
2524 for key, val in res.items():
2527 # if val is a many2one, just write the ID
2528 if type(val) == tuple:
2530 if (val<>False) or (type(val)<>bool):
2531 cr.execute(update_query, (ss[1](val), key))
2533 def _check_selection_field_value(self, cr, uid, field, value, context=None):
2534 """Raise except_orm if value is not among the valid values for the selection field"""
2535 if self._columns[field]._type == 'reference':
2536 val_model, val_id_str = value.split(',', 1)
2539 val_id = long(val_id_str)
2543 raise except_orm(_('ValidateError'),
2544 _('Invalid value for reference field "%s.%s" (last part must be a non-zero integer): "%s"') % (self._table, field, value))
2548 if isinstance(self._columns[field].selection, (tuple, list)):
2549 if val in dict(self._columns[field].selection):
2551 elif val in dict(self._columns[field].selection(self, cr, uid, context=context)):
2553 raise except_orm(_('ValidateError'),
2554 _('The value "%s" for the field "%s.%s" is not in the selection') % (value, self._table, field))
2556 def _check_removed_columns(self, cr, log=False):
2557 # iterate on the database columns to drop the NOT NULL constraints
2558 # of fields which were required but have been removed (or will be added by another module)
2559 columns = [c for c in self._columns if not (isinstance(self._columns[c], fields.function) and not self._columns[c].store)]
2560 columns += MAGIC_COLUMNS
2561 cr.execute("SELECT a.attname, a.attnotnull"
2562 " FROM pg_class c, pg_attribute a"
2563 " WHERE c.relname=%s"
2564 " AND c.oid=a.attrelid"
2565 " AND a.attisdropped=%s"
2566 " AND pg_catalog.format_type(a.atttypid, a.atttypmod) NOT IN ('cid', 'tid', 'oid', 'xid')"
2567 " AND a.attname NOT IN %s", (self._table, False, tuple(columns))),
2569 for column in cr.dictfetchall():
2571 self.__logger.debug("column %s is in the table %s but not in the corresponding object %s",
2572 column['attname'], self._table, self._name)
2573 if column['attnotnull']:
2574 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, column['attname']))
2575 self.__schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
2576 self._table, column['attname'])
2578 # checked version: for direct m2o starting from `self`
2579 def _m2o_add_foreign_key_checked(self, source_field, dest_model, ondelete):
2580 assert self.is_transient() or not dest_model.is_transient(), \
2581 'Many2One relationships from non-transient Model to TransientModel are forbidden'
2582 if self.is_transient() and not dest_model.is_transient():
2583 # TransientModel relationships to regular Models are annoying
2584 # usually because they could block deletion due to the FKs.
2585 # So unless stated otherwise we default them to ondelete=cascade.
2586 ondelete = ondelete or 'cascade'
2587 self._foreign_keys.append((self._table, source_field, dest_model._table, ondelete or 'set null'))
2588 self.__schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s",
2589 self._table, source_field, dest_model._table, ondelete)
2591 # unchecked version: for custom cases, such as m2m relationships
2592 def _m2o_add_foreign_key_unchecked(self, source_table, source_field, dest_model, ondelete):
2593 self._foreign_keys.append((source_table, source_field, dest_model._table, ondelete or 'set null'))
2594 self.__schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s",
2595 source_table, source_field, dest_model._table, ondelete)
2597 def _auto_init(self, cr, context=None):
2600 Call _field_create and, unless _auto is False:
2602 - create the corresponding table in database for the model,
2603 - possibly add the parent columns in database,
2604 - possibly add the columns 'create_uid', 'create_date', 'write_uid',
2605 'write_date' in database if _log_access is True (the default),
2606 - report on database columns no more existing in _columns,
2607 - remove no more existing not null constraints,
2608 - alter existing database columns to match _columns,
2609 - create database tables to match _columns,
2610 - add database indices to match _columns,
2611 - save in self._foreign_keys a list a foreign keys to create (see
2615 self._foreign_keys = []
2616 raise_on_invalid_object_name(self._name)
2619 store_compute = False
2621 update_custom_fields = context.get('update_custom_fields', False)
2622 self._field_create(cr, context=context)
2623 create = not self._table_exist(cr)
2625 if getattr(self, '_auto', True):
2628 self._create_table(cr)
2631 if self._parent_store:
2632 if not self._parent_columns_exist(cr):
2633 self._create_parent_columns(cr)
2634 store_compute = True
2636 # Create the create_uid, create_date, write_uid, write_date, columns if desired.
2637 if self._log_access:
2638 self._add_log_columns(cr)
2640 self._check_removed_columns(cr, log=False)
2642 # iterate on the "object columns"
2643 column_data = self._select_column_data(cr)
2645 for k, f in self._columns.iteritems():
2646 if k in MAGIC_COLUMNS:
2648 # Don't update custom (also called manual) fields
2649 if f.manual and not update_custom_fields:
2652 if isinstance(f, fields.one2many):
2653 self._o2m_raise_on_missing_reference(cr, f)
2655 elif isinstance(f, fields.many2many):
2656 self._m2m_raise_or_create_relation(cr, f)
2659 res = column_data.get(k)
2661 # The field is not found as-is in database, try if it
2662 # exists with an old name.
2663 if not res and hasattr(f, 'oldname'):
2664 res = column_data.get(f.oldname)
2666 cr.execute('ALTER TABLE "%s" RENAME "%s" TO "%s"' % (self._table, f.oldname, k))
2668 column_data[k] = res
2669 self.__schema.debug("Table '%s': renamed column '%s' to '%s'",
2670 self._table, f.oldname, k)
2672 # The field already exists in database. Possibly
2673 # change its type, rename it, drop it or change its
2676 f_pg_type = res['typname']
2677 f_pg_size = res['size']
2678 f_pg_notnull = res['attnotnull']
2679 if isinstance(f, fields.function) and not f.store and\
2680 not getattr(f, 'nodrop', False):
2681 self.__logger.info('column %s (%s) in table %s removed: converted to a function !\n',
2682 k, f.string, self._table)
2683 cr.execute('ALTER TABLE "%s" DROP COLUMN "%s" CASCADE' % (self._table, k))
2685 self.__schema.debug("Table '%s': dropped column '%s' with cascade",
2689 f_obj_type = get_pg_type(f) and get_pg_type(f)[0]
2694 ('text', 'char', pg_varchar(f.size), '::%s' % pg_varchar(f.size)),
2695 ('varchar', 'text', 'TEXT', ''),
2696 ('int4', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
2697 ('date', 'datetime', 'TIMESTAMP', '::TIMESTAMP'),
2698 ('timestamp', 'date', 'date', '::date'),
2699 ('numeric', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
2700 ('float8', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
2702 if f_pg_type == 'varchar' and f._type == 'char' and f_pg_size < f.size:
2703 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
2704 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, pg_varchar(f.size)))
2705 cr.execute('UPDATE "%s" SET "%s"=temp_change_size::%s' % (self._table, k, pg_varchar(f.size)))
2706 cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
2708 self.__schema.debug("Table '%s': column '%s' (type varchar) changed size from %s to %s",
2709 self._table, k, f_pg_size, f.size)
2711 if (f_pg_type==c[0]) and (f._type==c[1]):
2712 if f_pg_type != f_obj_type:
2714 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
2715 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, c[2]))
2716 cr.execute(('UPDATE "%s" SET "%s"=temp_change_size'+c[3]) % (self._table, k))
2717 cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
2719 self.__schema.debug("Table '%s': column '%s' changed type from %s to %s",
2720 self._table, k, c[0], c[1])
2723 if f_pg_type != f_obj_type:
2727 newname = k + '_moved' + str(i)
2728 cr.execute("SELECT count(1) FROM pg_class c,pg_attribute a " \
2729 "WHERE c.relname=%s " \
2730 "AND a.attname=%s " \
2731 "AND c.oid=a.attrelid ", (self._table, newname))
2732 if not cr.fetchone()[0]:
2736 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
2737 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO "%s"' % (self._table, k, newname))
2738 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
2739 cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,))
2740 self.__schema.debug("Table '%s': column '%s' has changed type (DB=%s, def=%s), data moved to column %s !",
2741 self._table, k, f_pg_type, f._type, newname)
2743 # if the field is required and hasn't got a NOT NULL constraint
2744 if f.required and f_pg_notnull == 0:
2745 # set the field to the default value if any
2746 if k in self._defaults:
2747 if callable(self._defaults[k]):
2748 default = self._defaults[k](self, cr, SUPERUSER_ID, context)
2750 default = self._defaults[k]
2752 if (default is not None):
2753 ss = self._columns[k]._symbol_set
2754 query = 'UPDATE "%s" SET "%s"=%s WHERE "%s" is NULL' % (self._table, k, ss[0], k)
2755 cr.execute(query, (ss[1](default),))
2756 # add the NOT NULL constraint
2759 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False)
2761 self.__schema.debug("Table '%s': column '%s': added NOT NULL constraint",
2764 msg = "Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\
2765 "If you want to have it, you should update the records and execute manually:\n"\
2766 "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
2767 self.__schema.warn(msg, self._table, k, self._table, k)
2769 elif not f.required and f_pg_notnull == 1:
2770 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
2772 self.__schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
2775 indexname = '%s_%s_index' % (self._table, k)
2776 cr.execute("SELECT indexname FROM pg_indexes WHERE indexname = %s and tablename = %s", (indexname, self._table))
2777 res2 = cr.dictfetchall()
2778 if not res2 and f.select:
2779 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
2781 if f._type == 'text':
2782 # FIXME: for fields.text columns we should try creating GIN indexes instead (seems most suitable for an ERP context)
2783 msg = "Table '%s': Adding (b-tree) index for text column '%s'."\
2784 "This is probably useless (does not work for fulltext search) and prevents INSERTs of long texts"\
2785 " because there is a length limit for indexable btree values!\n"\
2786 "Use a search view instead if you simply want to make the field searchable."
2787 self.__schema.warn(msg, self._table, k, f._type)
2788 if res2 and not f.select:
2789 cr.execute('DROP INDEX "%s_%s_index"' % (self._table, k))
2791 msg = "Table '%s': dropping index for column '%s' of type '%s' as it is not required anymore"
2792 self.__schema.debug(msg, self._table, k, f._type)
2794 if isinstance(f, fields.many2one):
2795 dest_model = self.pool.get(f._obj)
2796 ref = dest_model._table
2797 if ref != 'ir_actions':
2798 cr.execute('SELECT confdeltype, conname FROM pg_constraint as con, pg_class as cl1, pg_class as cl2, '
2799 'pg_attribute as att1, pg_attribute as att2 '
2800 'WHERE con.conrelid = cl1.oid '
2801 'AND cl1.relname = %s '
2802 'AND con.confrelid = cl2.oid '
2803 'AND cl2.relname = %s '
2804 'AND array_lower(con.conkey, 1) = 1 '
2805 'AND con.conkey[1] = att1.attnum '
2806 'AND att1.attrelid = cl1.oid '
2807 'AND att1.attname = %s '
2808 'AND array_lower(con.confkey, 1) = 1 '
2809 'AND con.confkey[1] = att2.attnum '
2810 'AND att2.attrelid = cl2.oid '
2811 'AND att2.attname = %s '
2812 "AND con.contype = 'f'", (self._table, ref, k, 'id'))
2813 res2 = cr.dictfetchall()
2815 if res2[0]['confdeltype'] != POSTGRES_CONFDELTYPES.get((f.ondelete or 'set null').upper(), 'a'):
2816 cr.execute('ALTER TABLE "' + self._table + '" DROP CONSTRAINT "' + res2[0]['conname'] + '"')
2817 self._m2o_add_foreign_key_checked(k, dest_model, f.ondelete)
2819 self.__schema.debug("Table '%s': column '%s': XXX",
2822 # The field doesn't exist in database. Create it if necessary.
2824 if not isinstance(f, fields.function) or f.store:
2825 # add the missing field
2826 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
2827 cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,))
2828 self.__schema.debug("Table '%s': added column '%s' with definition=%s",
2829 self._table, k, get_pg_type(f)[1])
2832 if not create and k in self._defaults:
2833 if callable(self._defaults[k]):
2834 default = self._defaults[k](self, cr, SUPERUSER_ID, context)
2836 default = self._defaults[k]
2838 ss = self._columns[k]._symbol_set
2839 query = 'UPDATE "%s" SET "%s"=%s' % (self._table, k, ss[0])
2840 cr.execute(query, (ss[1](default),))
2842 netsvc.Logger().notifyChannel('data', netsvc.LOG_DEBUG, "Table '%s': setting default value of new column %s" % (self._table, k))
2844 # remember the functions to call for the stored fields
2845 if isinstance(f, fields.function):
2847 if f.store is not True: # i.e. if f.store is a dict
2848 order = f.store[f.store.keys()[0]][2]
2849 todo_end.append((order, self._update_store, (f, k)))
2851 # and add constraints if needed
2852 if isinstance(f, fields.many2one):
2853 if not self.pool.get(f._obj):
2854 raise except_orm('Programming Error', ('There is no reference available for %s') % (f._obj,))
2855 dest_model = self.pool.get(f._obj)
2856 ref = dest_model._table
2857 # ir_actions is inherited so foreign key doesn't work on it
2858 if ref != 'ir_actions':
2859 self._m2o_add_foreign_key_checked(k, dest_model, f.ondelete)
2861 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
2865 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False)
2866 self.__schema.debug("Table '%s': column '%s': added a NOT NULL constraint",
2869 msg = "WARNING: unable to set column %s of table %s not null !\n"\
2870 "Try to re-run: openerp-server --update=module\n"\
2871 "If it doesn't work, update records and execute manually:\n"\
2872 "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
2873 self.__logger.warn(msg, k, self._table, self._table, k)
2877 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
2878 create = not bool(cr.fetchone())
2880 cr.commit() # start a new transaction
2882 self._add_sql_constraints(cr)
2885 self._execute_sql(cr)
2888 self._parent_store_compute(cr)
2894 def _auto_end(self, cr, context=None):
2895 """ Create the foreign keys recorded by _auto_init. """
2896 for t, k, r, d in self._foreign_keys:
2897 cr.execute('ALTER TABLE "%s" ADD FOREIGN KEY ("%s") REFERENCES "%s" ON DELETE %s' % (t, k, r, d))
2899 del self._foreign_keys
2902 def _table_exist(self, cr):
2903 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
2907 def _create_table(self, cr):
2908 cr.execute('CREATE TABLE "%s" (id SERIAL NOT NULL, PRIMARY KEY(id)) WITHOUT OIDS' % (self._table,))
2909 cr.execute(("COMMENT ON TABLE \"%s\" IS %%s" % self._table), (self._description,))
2910 self.__schema.debug("Table '%s': created", self._table)
2913 def _parent_columns_exist(self, cr):
2914 cr.execute("""SELECT c.relname
2915 FROM pg_class c, pg_attribute a
2916 WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
2917 """, (self._table, 'parent_left'))
2921 def _create_parent_columns(self, cr):
2922 cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_left" INTEGER' % (self._table,))
2923 cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_right" INTEGER' % (self._table,))
2924 if 'parent_left' not in self._columns:
2925 self.__logger.error('create a column parent_left on object %s: fields.integer(\'Left Parent\', select=1)',
2927 self.__schema.debug("Table '%s': added column '%s' with definition=%s",
2928 self._table, 'parent_left', 'INTEGER')
2929 elif not self._columns['parent_left'].select:
2930 self.__logger.error('parent_left column on object %s must be indexed! Add select=1 to the field definition)',
2932 if 'parent_right' not in self._columns:
2933 self.__logger.error('create a column parent_right on object %s: fields.integer(\'Right Parent\', select=1)',
2935 self.__schema.debug("Table '%s': added column '%s' with definition=%s",
2936 self._table, 'parent_right', 'INTEGER')
2937 elif not self._columns['parent_right'].select:
2938 self.__logger.error('parent_right column on object %s must be indexed! Add select=1 to the field definition)',
2940 if self._columns[self._parent_name].ondelete != 'cascade':
2941 self.__logger.error("The column %s on object %s must be set as ondelete='cascade'",
2942 self._parent_name, self._name)
2947 def _add_log_columns(self, cr):
2948 for field, field_def in LOG_ACCESS_COLUMNS.iteritems():
2951 FROM pg_class c, pg_attribute a
2952 WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
2953 """, (self._table, field))
2955 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, field, field_def))
2957 self.__schema.debug("Table '%s': added column '%s' with definition=%s",
2958 self._table, field, field_def)
2961 def _select_column_data(self, cr):
2962 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 " \
2963 "FROM pg_class c,pg_attribute a,pg_type t " \
2964 "WHERE c.relname=%s " \
2965 "AND c.oid=a.attrelid " \
2966 "AND a.atttypid=t.oid", (self._table,))
2967 return dict(map(lambda x: (x['attname'], x),cr.dictfetchall()))
2970 def _o2m_raise_on_missing_reference(self, cr, f):
2971 # TODO this check should be a method on fields.one2many.
2972 other = self.pool.get(f._obj)
2974 # TODO the condition could use fields_get_keys().
2975 if f._fields_id not in other._columns.keys():
2976 if f._fields_id not in other._inherit_fields.keys():
2977 raise except_orm('Programming Error', ("There is no reference field '%s' found for '%s'") % (f._fields_id, f._obj,))
2980 def _m2m_raise_or_create_relation(self, cr, f):
2981 m2m_tbl, col1, col2 = f._sql_names(self)
2982 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (m2m_tbl,))
2983 if not cr.dictfetchall():
2984 if not self.pool.get(f._obj):
2985 raise except_orm('Programming Error', ('Many2Many destination model does not exist: `%s`') % (f._obj,))
2986 dest_model = self.pool.get(f._obj)
2987 ref = dest_model._table
2988 cr.execute('CREATE TABLE "%s" ("%s" INTEGER NOT NULL, "%s" INTEGER NOT NULL, UNIQUE("%s","%s")) WITH OIDS' % (m2m_tbl, col1, col2, col1, col2))
2990 # create foreign key references with ondelete=cascade, unless the targets are SQL views
2991 cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (ref,))
2992 if not cr.fetchall():
2993 self._m2o_add_foreign_key_unchecked(m2m_tbl, col2, dest_model, 'cascade')
2994 cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (self._table,))
2995 if not cr.fetchall():
2996 self._m2o_add_foreign_key_unchecked(m2m_tbl, col1, self, 'cascade')
2998 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col1, m2m_tbl, col1))
2999 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col2, m2m_tbl, col2))
3000 cr.execute("COMMENT ON TABLE \"%s\" IS 'RELATION BETWEEN %s AND %s'" % (m2m_tbl, self._table, ref))
3002 self.__schema.debug("Create table '%s': m2m relation between '%s' and '%s'", m2m_tbl, self._table, ref)
3005 def _add_sql_constraints(self, cr):
3008 Modify this model's database table constraints so they match the one in
3012 for (key, con, _) in self._sql_constraints:
3013 conname = '%s_%s' % (self._table, key)
3015 cr.execute("SELECT conname, pg_catalog.pg_get_constraintdef(oid, true) as condef FROM pg_constraint where conname=%s", (conname,))
3016 existing_constraints = cr.dictfetchall()
3021 'query': 'ALTER TABLE "%s" DROP CONSTRAINT "%s"' % (self._table, conname, ),
3022 'msg_ok': "Table '%s': dropped constraint '%s'. Reason: its definition changed from '%%s' to '%s'" % (
3023 self._table, conname, con),
3024 'msg_err': "Table '%s': unable to drop \'%s\' constraint !" % (self._table, con),
3029 'query': 'ALTER TABLE "%s" ADD CONSTRAINT "%s" %s' % (self._table, conname, con,),
3030 'msg_ok': "Table '%s': added constraint '%s' with definition=%s" % (self._table, conname, con),
3031 '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" % (
3037 if not existing_constraints:
3038 # constraint does not exists:
3039 sql_actions['add']['execute'] = True
3040 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
3041 elif con.lower() not in [item['condef'].lower() for item in existing_constraints]:
3042 # constraint exists but its definition has changed:
3043 sql_actions['drop']['execute'] = True
3044 sql_actions['drop']['msg_ok'] = sql_actions['drop']['msg_ok'] % (existing_constraints[0]['condef'].lower(), )
3045 sql_actions['add']['execute'] = True
3046 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
3048 # we need to add the constraint:
3049 sql_actions = [item for item in sql_actions.values()]
3050 sql_actions.sort(key=lambda x: x['order'])
3051 for sql_action in [action for action in sql_actions if action['execute']]:
3053 cr.execute(sql_action['query'])
3055 self.__schema.debug(sql_action['msg_ok'])
3057 self.__schema.warn(sql_action['msg_err'])
3061 def _execute_sql(self, cr):
3062 """ Execute the SQL code from the _sql attribute (if any)."""
3063 if hasattr(self, "_sql"):
3064 for line in self._sql.split(';'):
3065 line2 = line.replace('\n', '').strip()
3071 # Update objects that uses this one to update their _inherits fields
3074 def _inherits_reload_src(self):
3075 """ Recompute the _inherit_fields mapping on each _inherits'd child model."""
3076 for obj in self.pool.models.values():
3077 if self._name in obj._inherits:
3078 obj._inherits_reload()
3081 def _inherits_reload(self):
3082 """ Recompute the _inherit_fields mapping.
3084 This will also call itself on each inherits'd child model.
3088 for table in self._inherits:
3089 other = self.pool.get(table)
3090 for col in other._columns.keys():
3091 res[col] = (table, self._inherits[table], other._columns[col], table)
3092 for col in other._inherit_fields.keys():
3093 res[col] = (table, self._inherits[table], other._inherit_fields[col][2], other._inherit_fields[col][3])
3094 self._inherit_fields = res
3095 self._all_columns = self._get_column_infos()
3096 self._inherits_reload_src()
3099 def _get_column_infos(self):
3100 """Returns a dict mapping all fields names (direct fields and
3101 inherited field via _inherits) to a ``column_info`` struct
3102 giving detailed columns """
3104 for k, (parent, m2o, col, original_parent) in self._inherit_fields.iteritems():
3105 result[k] = fields.column_info(k, col, parent, m2o, original_parent)
3106 for k, col in self._columns.iteritems():
3107 result[k] = fields.column_info(k, col)
3111 def _inherits_check(self):
3112 for table, field_name in self._inherits.items():
3113 if field_name not in self._columns:
3114 logging.getLogger('init').info('Missing many2one field definition for _inherits reference "%s" in "%s", using default one.' % (field_name, self._name))
3115 self._columns[field_name] = fields.many2one(table, string="Automatically created field to link to parent %s" % table,
3116 required=True, ondelete="cascade")
3117 elif not self._columns[field_name].required or self._columns[field_name].ondelete.lower() != "cascade":
3118 logging.getLogger('init').warning('Field definition for _inherits reference "%s" in "%s" must be marked as "required" with ondelete="cascade", forcing it.' % (field_name, self._name))
3119 self._columns[field_name].required = True
3120 self._columns[field_name].ondelete = "cascade"
3122 #def __getattr__(self, name):
3124 # Proxies attribute accesses to the `inherits` parent so we can call methods defined on the inherited parent
3125 # (though inherits doesn't use Python inheritance).
3126 # Handles translating between local ids and remote ids.
3127 # Known issue: doesn't work correctly when using python's own super(), don't involve inherit-based inheritance
3128 # when you have inherits.
3130 # for model, field in self._inherits.iteritems():
3131 # proxy = self.pool.get(model)
3132 # if hasattr(proxy, name):
3133 # attribute = getattr(proxy, name)
3134 # if not hasattr(attribute, '__call__'):
3138 # return super(orm, self).__getattr__(name)
3140 # def _proxy(cr, uid, ids, *args, **kwargs):
3141 # objects = self.browse(cr, uid, ids, kwargs.get('context', None))
3142 # lst = [obj[field].id for obj in objects if obj[field]]
3143 # return getattr(proxy, name)(cr, uid, lst, *args, **kwargs)
3148 def fields_get(self, cr, user, allfields=None, context=None, write_access=True):
3149 """ Return the definition of each field.
3151 The returned value is a dictionary (indiced by field name) of
3152 dictionaries. The _inherits'd fields are included. The string, help,
3153 and selection (if present) attributes are translated.
3155 :param cr: database cursor
3156 :param user: current user id
3157 :param fields: list of fields
3158 :param context: context arguments, like lang, time zone
3159 :return: dictionary of field dictionaries, each one describing a field of the business object
3160 :raise AccessError: * if user has no create/write rights on the requested object
3166 write_access = self.check_write(cr, user, False) or \
3167 self.check_create(cr, user, False)
3171 translation_obj = self.pool.get('ir.translation')
3172 for parent in self._inherits:
3173 res.update(self.pool.get(parent).fields_get(cr, user, allfields, context))
3175 for f, field in self._columns.iteritems():
3176 if allfields and f not in allfields:
3179 res[f] = fields.field_to_dict(self, cr, user, field, context=context)
3181 if not write_access:
3182 res[f]['readonly'] = True
3183 res[f]['states'] = {}
3185 if 'string' in res[f]:
3186 res_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'field', context.get('lang', False) or 'en_US')
3188 res[f]['string'] = res_trans
3189 if 'help' in res[f]:
3190 help_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'help', context.get('lang', False) or 'en_US')
3192 res[f]['help'] = help_trans
3193 if 'selection' in res[f]:
3194 if isinstance(field.selection, (tuple, list)):
3195 sel = field.selection
3197 for key, val in sel:
3200 val2 = translation_obj._get_source(cr, user, self._name + ',' + f, 'selection', context.get('lang', False) or 'en_US', val)
3201 sel2.append((key, val2 or val))
3202 res[f]['selection'] = sel2
3206 def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
3207 """ Read records with given ids with the given fields
3209 :param cr: database cursor
3210 :param user: current user id
3211 :param ids: id or list of the ids of the records to read
3212 :param fields: optional list of field names to return (default: all fields would be returned)
3213 :type fields: list (example ['field_name_1', ...])
3214 :param context: optional context dictionary - it may contains keys for specifying certain options
3215 like ``context_lang``, ``context_tz`` to alter the results of the call.
3216 A special ``bin_size`` boolean flag may also be passed in the context to request the
3217 value of all fields.binary columns to be returned as the size of the binary instead of its
3218 contents. This can also be selectively overriden by passing a field-specific flag
3219 in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field.
3220 Note: The ``bin_size_XXX`` form is new in OpenERP v6.0.
3221 :return: list of dictionaries((dictionary per record asked)) with requested field values
3222 :rtype: [{‘name_of_the_field’: value, ...}, ...]
3223 :raise AccessError: * if user has no read rights on the requested object
3224 * if user tries to bypass access rules for read on the requested object
3230 self.check_read(cr, user)
3232 fields = list(set(self._columns.keys() + self._inherit_fields.keys()))
3233 if isinstance(ids, (int, long)):
3237 select = map(lambda x: isinstance(x, dict) and x['id'] or x, select)
3238 result = self._read_flat(cr, user, select, fields, context, load)
3241 for key, v in r.items():
3245 if isinstance(ids, (int, long, dict)):
3246 return result and result[0] or False
3249 def _read_flat(self, cr, user, ids, fields_to_read, context=None, load='_classic_read'):
3254 if fields_to_read == None:
3255 fields_to_read = self._columns.keys()
3257 # Construct a clause for the security rules.
3258 # 'tables' hold the list of tables necessary for the SELECT including the ir.rule clauses,
3259 # or will at least contain self._table.
3260 rule_clause, rule_params, tables = self.pool.get('ir.rule').domain_get(cr, user, self._name, 'read', context=context)
3262 # all inherited fields + all non inherited fields for which the attribute whose name is in load is True
3263 fields_pre = [f for f in fields_to_read if
3264 f == self.CONCURRENCY_CHECK_FIELD
3265 or (f in self._columns and getattr(self._columns[f], '_classic_write'))
3266 ] + self._inherits.values()
3270 def convert_field(f):
3271 f_qual = '%s."%s"' % (self._table, f) # need fully-qualified references in case len(tables) > 1
3272 if f in ('create_date', 'write_date'):
3273 return "date_trunc('second', %s) as %s" % (f_qual, f)
3274 if f == self.CONCURRENCY_CHECK_FIELD:
3275 if self._log_access:
3276 return "COALESCE(%s.write_date, %s.create_date, now())::timestamp AS %s" % (self._table, self._table, f,)
3277 return "now()::timestamp AS %s" % (f,)
3278 if isinstance(self._columns[f], fields.binary) and context.get('bin_size', False):
3279 return 'length(%s) as "%s"' % (f_qual, f)
3282 fields_pre2 = map(convert_field, fields_pre)
3283 order_by = self._parent_order or self._order
3284 select_fields = ','.join(fields_pre2 + [self._table + '.id'])
3285 query = 'SELECT %s FROM %s WHERE %s.id IN %%s' % (select_fields, ','.join(tables), self._table)
3287 query += " AND " + (' OR '.join(rule_clause))
3288 query += " ORDER BY " + order_by
3289 for sub_ids in cr.split_for_in_conditions(ids):
3291 cr.execute(query, [tuple(sub_ids)] + rule_params)
3292 if cr.rowcount != len(sub_ids):
3293 raise except_orm(_('AccessError'),
3294 _('Operation prohibited by access rules, or performed on an already deleted document (Operation: read, Document type: %s).')
3295 % (self._description,))
3297 cr.execute(query, (tuple(sub_ids),))
3298 res.extend(cr.dictfetchall())
3300 res = map(lambda x: {'id': x}, ids)
3302 for f in fields_pre:
3303 if f == self.CONCURRENCY_CHECK_FIELD:
3305 if self._columns[f].translate:
3306 ids = [x['id'] for x in res]
3307 #TODO: optimize out of this loop
3308 res_trans = self.pool.get('ir.translation')._get_ids(cr, user, self._name+','+f, 'model', context.get('lang', False) or 'en_US', ids)
3310 r[f] = res_trans.get(r['id'], False) or r[f]
3312 for table in self._inherits:
3313 col = self._inherits[table]
3314 cols = [x for x in intersect(self._inherit_fields.keys(), fields_to_read) if x not in self._columns.keys()]
3317 res2 = self.pool.get(table).read(cr, user, [x[col] for x in res], cols, context, load)
3325 if not record[col]: # if the record is deleted from _inherits table?
3327 record.update(res3[record[col]])
3328 if col not in fields_to_read:
3331 # all fields which need to be post-processed by a simple function (symbol_get)
3332 fields_post = filter(lambda x: x in self._columns and self._columns[x]._symbol_get, fields_to_read)
3335 for f in fields_post:
3336 r[f] = self._columns[f]._symbol_get(r[f])
3337 ids = [x['id'] for x in res]
3339 # all non inherited fields for which the attribute whose name is in load is False
3340 fields_post = filter(lambda x: x in self._columns and not getattr(self._columns[x], load), fields_to_read)
3342 # Compute POST fields
3344 for f in fields_post:
3345 todo.setdefault(self._columns[f]._multi, [])
3346 todo[self._columns[f]._multi].append(f)
3347 for key, val in todo.items():
3349 res2 = self._columns[val[0]].get(cr, self, ids, val, user, context=context, values=res)
3350 assert res2 is not None, \
3351 'The function field "%s" on the "%s" model returned None\n' \
3352 '(a dictionary was expected).' % (val[0], self._name)
3355 if isinstance(res2[record['id']], str): res2[record['id']] = eval(res2[record['id']]) #TOCHECK : why got string instend of dict in python2.6
3356 multi_fields = res2.get(record['id'],{})
3358 record[pos] = multi_fields.get(pos,[])
3361 res2 = self._columns[f].get(cr, self, ids, f, user, context=context, values=res)
3364 record[f] = res2[record['id']]
3369 for field in vals.copy():
3371 if field in self._columns:
3372 fobj = self._columns[field]
3379 for group in groups:
3380 module = group.split(".")[0]
3381 grp = group.split(".")[1]
3382 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", \
3383 (grp, module, 'res.groups', user))
3384 readonly = cr.fetchall()
3385 if readonly[0][0] >= 1:
3388 elif readonly[0][0] == 0:
3394 if type(vals[field]) == type([]):
3396 elif type(vals[field]) == type(0.0):
3398 elif type(vals[field]) == type(''):
3399 vals[field] = '=No Permission='
3404 # TODO check READ access
3405 def perm_read(self, cr, user, ids, context=None, details=True):
3407 Returns some metadata about the given records.
3409 :param details: if True, \*_uid fields are replaced with the name of the user
3410 :return: list of ownership dictionaries for each requested record
3411 :rtype: list of dictionaries with the following keys:
3414 * create_uid: user who created the record
3415 * create_date: date when the record was created
3416 * write_uid: last user who changed the record
3417 * write_date: date of the last change to the record
3418 * xmlid: XML ID to use to refer to this record (if there is one), in format ``module.name``
3425 uniq = isinstance(ids, (int, long))
3429 if self._log_access:
3430 fields += ['create_uid', 'create_date', 'write_uid', 'write_date']
3431 quoted_table = '"%s"' % self._table
3432 fields_str = ",".join('%s.%s'%(quoted_table, field) for field in fields)
3433 query = '''SELECT %s, __imd.module, __imd.name
3434 FROM %s LEFT JOIN ir_model_data __imd
3435 ON (__imd.model = %%s and __imd.res_id = %s.id)
3436 WHERE %s.id IN %%s''' % (fields_str, quoted_table, quoted_table, quoted_table)
3437 cr.execute(query, (self._name, tuple(ids)))
3438 res = cr.dictfetchall()
3441 r[key] = r[key] or False
3442 if details and key in ('write_uid', 'create_uid') and r[key]:
3444 r[key] = self.pool.get('res.users').name_get(cr, user, [r[key]])[0]
3446 pass # Leave the numeric uid there
3447 r['xmlid'] = ("%(module)s.%(name)s" % r) if r['name'] else False
3448 del r['name'], r['module']
3453 def _check_concurrency(self, cr, ids, context):
3456 if not (context.get(self.CONCURRENCY_CHECK_FIELD) and self._log_access):
3458 check_clause = "(id = %s AND %s < COALESCE(write_date, create_date, now())::timestamp)"
3459 for sub_ids in cr.split_for_in_conditions(ids):
3462 id_ref = "%s,%s" % (self._name, id)
3463 update_date = context[self.CONCURRENCY_CHECK_FIELD].pop(id_ref, None)
3465 ids_to_check.extend([id, update_date])
3466 if not ids_to_check:
3468 cr.execute("SELECT id FROM %s WHERE %s" % (self._table, " OR ".join([check_clause]*(len(ids_to_check)/2))), tuple(ids_to_check))
3471 # mention the first one only to keep the error message readable
3472 raise except_orm('ConcurrencyException', _('A document was modified since you last viewed it (%s:%d)') % (self._description, res[0]))
3474 def check_access_rights(self, cr, uid, operation, raise_exception=True): # no context on purpose.
3475 """Verifies that the operation given by ``operation`` is allowed for the user
3476 according to the access rights."""
3477 return self.pool.get('ir.model.access').check(cr, uid, self._name, operation, raise_exception)
3479 def check_create(self, cr, uid, raise_exception=True):
3480 return self.check_access_rights(cr, uid, 'create', raise_exception)
3482 def check_read(self, cr, uid, raise_exception=True):
3483 return self.check_access_rights(cr, uid, 'read', raise_exception)
3485 def check_unlink(self, cr, uid, raise_exception=True):
3486 return self.check_access_rights(cr, uid, 'unlink', raise_exception)
3488 def check_write(self, cr, uid, raise_exception=True):
3489 return self.check_access_rights(cr, uid, 'write', raise_exception)
3491 def check_access_rule(self, cr, uid, ids, operation, context=None):
3492 """Verifies that the operation given by ``operation`` is allowed for the user
3493 according to ir.rules.
3495 :param operation: one of ``write``, ``unlink``
3496 :raise except_orm: * if current ir.rules do not permit this operation.
3497 :return: None if the operation is allowed
3499 if uid == SUPERUSER_ID:
3502 if self.is_transient():
3503 # Only one single implicit access rule for transient models: owner only!
3504 # This is ok to hardcode because we assert that TransientModels always
3505 # have log_access enabled and this the create_uid column is always there.
3506 # And even with _inherits, these fields are always present in the local
3507 # table too, so no need for JOINs.
3508 cr.execute("""SELECT distinct create_uid
3510 WHERE id IN %%s""" % self._table, (tuple(ids),))
3511 uids = [x[0] for x in cr.fetchall()]
3512 if len(uids) != 1 or uids[0] != uid:
3513 raise except_orm(_('AccessError'), '%s access is '
3514 'restricted to your own records for transient models '
3515 '(except for the super-user).' % operation.capitalize())
3517 where_clause, where_params, tables = self.pool.get('ir.rule').domain_get(cr, uid, self._name, operation, context=context)
3519 where_clause = ' and ' + ' and '.join(where_clause)
3520 for sub_ids in cr.split_for_in_conditions(ids):
3521 cr.execute('SELECT ' + self._table + '.id FROM ' + ','.join(tables) +
3522 ' WHERE ' + self._table + '.id IN %s' + where_clause,
3523 [sub_ids] + where_params)
3524 if cr.rowcount != len(sub_ids):
3525 raise except_orm(_('AccessError'),
3526 _('Operation prohibited by access rules, or performed on an already deleted document (Operation: %s, Document type: %s).')
3527 % (operation, self._description))
3529 def unlink(self, cr, uid, ids, context=None):
3531 Delete records with given ids
3533 :param cr: database cursor
3534 :param uid: current user id
3535 :param ids: id or list of ids
3536 :param context: (optional) context arguments, like lang, time zone
3538 :raise AccessError: * if user has no unlink rights on the requested object
3539 * if user tries to bypass access rules for unlink on the requested object
3540 :raise UserError: if the record is default property for other records
3545 if isinstance(ids, (int, long)):
3548 result_store = self._store_get_values(cr, uid, ids, None, context)
3550 self._check_concurrency(cr, ids, context)
3552 self.check_unlink(cr, uid)
3554 properties = self.pool.get('ir.property')
3555 domain = [('res_id', '=', False),
3556 ('value_reference', 'in', ['%s,%s' % (self._name, i) for i in ids]),
3558 if properties.search(cr, uid, domain, context=context):
3559 raise except_orm(_('Error'), _('Unable to delete this document because it is used as a default property'))
3561 wf_service = netsvc.LocalService("workflow")
3563 wf_service.trg_delete(uid, self._name, oid, cr)
3566 self.check_access_rule(cr, uid, ids, 'unlink', context=context)
3567 pool_model_data = self.pool.get('ir.model.data')
3568 ir_values_obj = self.pool.get('ir.values')
3569 for sub_ids in cr.split_for_in_conditions(ids):
3570 cr.execute('delete from ' + self._table + ' ' \
3571 'where id IN %s', (sub_ids,))
3573 # Removing the ir_model_data reference if the record being deleted is a record created by xml/csv file,
3574 # as these are not connected with real database foreign keys, and would be dangling references.
3575 # Note: following steps performed as admin to avoid access rights restrictions, and with no context
3576 # to avoid possible side-effects during admin calls.
3577 # Step 1. Calling unlink of ir_model_data only for the affected IDS
3578 reference_ids = pool_model_data.search(cr, SUPERUSER_ID, [('res_id','in',list(sub_ids)),('model','=',self._name)])
3579 # Step 2. Marching towards the real deletion of referenced records
3581 pool_model_data.unlink(cr, SUPERUSER_ID, reference_ids)
3583 # For the same reason, removing the record relevant to ir_values
3584 ir_value_ids = ir_values_obj.search(cr, uid,
3585 ['|',('value','in',['%s,%s' % (self._name, sid) for sid in sub_ids]),'&',('res_id','in',list(sub_ids)),('model','=',self._name)],
3588 ir_values_obj.unlink(cr, uid, ir_value_ids, context=context)
3590 for order, object, store_ids, fields in result_store:
3591 if object != self._name:
3592 obj = self.pool.get(object)
3593 cr.execute('select id from '+obj._table+' where id IN %s', (tuple(store_ids),))
3594 rids = map(lambda x: x[0], cr.fetchall())
3596 obj._store_set_values(cr, uid, rids, fields, context)
3603 def write(self, cr, user, ids, vals, context=None):
3605 Update records with given ids with the given field values
3607 :param cr: database cursor
3608 :param user: current user id
3610 :param ids: object id or list of object ids to update according to **vals**
3611 :param vals: field values to update, e.g {'field_name': new_field_value, ...}
3612 :type vals: dictionary
3613 :param context: (optional) context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...}
3614 :type context: dictionary
3616 :raise AccessError: * if user has no write rights on the requested object
3617 * if user tries to bypass access rules for write on the requested object
3618 :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
3619 :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)
3621 **Note**: The type of field values to pass in ``vals`` for relationship fields is specific:
3623 + For a many2many field, a list of tuples is expected.
3624 Here is the list of tuple that are accepted, with the corresponding semantics ::
3626 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
3627 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
3628 (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)
3629 (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)
3630 (4, ID) link to existing record with id = ID (adds a relationship)
3631 (5) unlink all (like using (3,ID) for all linked records)
3632 (6, 0, [IDs]) replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)
3635 [(6, 0, [8, 5, 6, 4])] sets the many2many to ids [8, 5, 6, 4]
3637 + For a one2many field, a lits of tuples is expected.
3638 Here is the list of tuple that are accepted, with the corresponding semantics ::
3640 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
3641 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
3642 (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)
3645 [(0, 0, {'field_name':field_value_record1, ...}), (0, 0, {'field_name':field_value_record2, ...})]
3647 + For a many2one field, simply use the ID of target record, which must already exist, or ``False`` to remove the link.
3648 + For a reference field, use a string with the model name, a comma, and the target object id (example: ``'product.product, 5'``)
3652 for field in vals.copy():
3654 if field in self._columns:
3655 fobj = self._columns[field]
3656 elif field in self._inherit_fields:
3657 fobj = self._inherit_fields[field][2]
3664 for group in groups:
3665 module = group.split(".")[0]
3666 grp = group.split(".")[1]
3667 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", \
3668 (grp, module, 'res.groups', user))
3669 readonly = cr.fetchall()
3670 if readonly[0][0] >= 1:
3673 elif readonly[0][0] == 0:
3685 if isinstance(ids, (int, long)):
3688 self._check_concurrency(cr, ids, context)
3689 self.check_write(cr, user)
3691 result = self._store_get_values(cr, user, ids, vals.keys(), context) or []
3693 # No direct update of parent_left/right
3694 vals.pop('parent_left', None)
3695 vals.pop('parent_right', None)
3697 parents_changed = []
3698 parent_order = self._parent_order or self._order
3699 if self._parent_store and (self._parent_name in vals):
3700 # The parent_left/right computation may take up to
3701 # 5 seconds. No need to recompute the values if the
3702 # parent is the same.
3703 # Note: to respect parent_order, nodes must be processed in
3704 # order, so ``parents_changed`` must be ordered properly.
3705 parent_val = vals[self._parent_name]
3707 query = "SELECT id FROM %s WHERE id IN %%s AND (%s != %%s OR %s IS NULL) ORDER BY %s" % \
3708 (self._table, self._parent_name, self._parent_name, parent_order)
3709 cr.execute(query, (tuple(ids), parent_val))
3711 query = "SELECT id FROM %s WHERE id IN %%s AND (%s IS NOT NULL) ORDER BY %s" % \
3712 (self._table, self._parent_name, parent_order)
3713 cr.execute(query, (tuple(ids),))
3714 parents_changed = map(operator.itemgetter(0), cr.fetchall())
3721 totranslate = context.get('lang', False) and (context['lang'] != 'en_US')
3723 if field in self._columns:
3724 if self._columns[field]._classic_write and not (hasattr(self._columns[field], '_fnct_inv')):
3725 if (not totranslate) or not self._columns[field].translate:
3726 upd0.append('"'+field+'"='+self._columns[field]._symbol_set[0])
3727 upd1.append(self._columns[field]._symbol_set[1](vals[field]))
3728 direct.append(field)
3730 upd_todo.append(field)
3732 updend.append(field)
3733 if field in self._columns \
3734 and hasattr(self._columns[field], 'selection') \
3736 self._check_selection_field_value(cr, user, field, vals[field], context=context)
3738 if self._log_access:
3739 upd0.append('write_uid=%s')
3740 upd0.append('write_date=now()')
3744 self.check_access_rule(cr, user, ids, 'write', context=context)
3745 for sub_ids in cr.split_for_in_conditions(ids):
3746 cr.execute('update ' + self._table + ' set ' + ','.join(upd0) + ' ' \
3747 'where id IN %s', upd1 + [sub_ids])
3748 if cr.rowcount != len(sub_ids):
3749 raise except_orm(_('AccessError'),
3750 _('One of the records you are trying to modify has already been deleted (Document type: %s).') % self._description)
3755 if self._columns[f].translate:
3756 src_trans = self.pool.get(self._name).read(cr, user, ids, [f])[0][f]
3759 # Inserting value to DB
3760 self.write(cr, user, ids, {f: vals[f]})
3761 self.pool.get('ir.translation')._set_ids(cr, user, self._name+','+f, 'model', context['lang'], ids, vals[f], src_trans)
3764 # call the 'set' method of fields which are not classic_write
3765 upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
3767 # default element in context must be removed when call a one2many or many2many
3768 rel_context = context.copy()
3769 for c in context.items():
3770 if c[0].startswith('default_'):
3771 del rel_context[c[0]]
3773 for field in upd_todo:
3775 result += self._columns[field].set(cr, self, id, field, vals[field], user, context=rel_context) or []
3777 for table in self._inherits:
3778 col = self._inherits[table]
3780 for sub_ids in cr.split_for_in_conditions(ids):
3781 cr.execute('select distinct "'+col+'" from "'+self._table+'" ' \
3782 'where id IN %s', (sub_ids,))
3783 nids.extend([x[0] for x in cr.fetchall()])
3787 if self._inherit_fields[val][0] == table:
3790 self.pool.get(table).write(cr, user, nids, v, context)
3792 self._validate(cr, user, ids, context)
3794 # TODO: use _order to set dest at the right position and not first node of parent
3795 # We can't defer parent_store computation because the stored function
3796 # fields that are computer may refer (directly or indirectly) to
3797 # parent_left/right (via a child_of domain)
3800 self.pool._init_parent[self._name] = True
3802 order = self._parent_order or self._order
3803 parent_val = vals[self._parent_name]
3805 clause, params = '%s=%%s' % (self._parent_name,), (parent_val,)
3807 clause, params = '%s IS NULL' % (self._parent_name,), ()
3809 for id in parents_changed:
3810 cr.execute('SELECT parent_left, parent_right FROM %s WHERE id=%%s' % (self._table,), (id,))
3811 pleft, pright = cr.fetchone()
3812 distance = pright - pleft + 1
3814 # Positions of current siblings, to locate proper insertion point;
3815 # this can _not_ be fetched outside the loop, as it needs to be refreshed
3816 # after each update, in case several nodes are sequentially inserted one
3817 # next to the other (i.e computed incrementally)
3818 cr.execute('SELECT parent_right, id FROM %s WHERE %s ORDER BY %s' % (self._table, clause, parent_order), params)
3819 parents = cr.fetchall()
3821 # Find Position of the element
3823 for (parent_pright, parent_id) in parents:
3826 position = parent_pright + 1
3828 # It's the first node of the parent
3833 cr.execute('select parent_left from '+self._table+' where id=%s', (parent_val,))
3834 position = cr.fetchone()[0] + 1
3836 if pleft < position <= pright:
3837 raise except_orm(_('UserError'), _('Recursivity Detected.'))
3839 if pleft < position:
3840 cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
3841 cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
3842 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))
3844 cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
3845 cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
3846 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))
3848 result += self._store_get_values(cr, user, ids, vals.keys(), context)
3852 for order, object, ids_to_update, fields_to_recompute in result:
3853 key = (object, tuple(fields_to_recompute))
3854 done.setdefault(key, {})
3855 # avoid to do several times the same computation
3857 for id in ids_to_update:
3858 if id not in done[key]:
3859 done[key][id] = True
3861 self.pool.get(object)._store_set_values(cr, user, todo, fields_to_recompute, context)
3863 wf_service = netsvc.LocalService("workflow")
3865 wf_service.trg_write(user, self._name, id, cr)
3869 # TODO: Should set perm to user.xxx
3871 def create(self, cr, user, vals, context=None):
3873 Create a new record for the model.
3875 The values for the new record are initialized using the ``vals``
3876 argument, and if necessary the result of ``default_get()``.
3878 :param cr: database cursor
3879 :param user: current user id
3881 :param vals: field values for new record, e.g {'field_name': field_value, ...}
3882 :type vals: dictionary
3883 :param context: optional context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...}
3884 :type context: dictionary
3885 :return: id of new record created
3886 :raise AccessError: * if user has no create rights on the requested object
3887 * if user tries to bypass access rules for create on the requested object
3888 :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
3889 :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)
3891 **Note**: The type of field values to pass in ``vals`` for relationship fields is specific.
3892 Please see the description of the :py:meth:`~osv.osv.osv.write` method for details about the possible values and how
3899 if self.is_transient():
3900 self._transient_vacuum(cr, user)
3902 self.check_create(cr, user)
3904 vals = self._add_missing_default_values(cr, user, vals, context)
3907 for v in self._inherits:
3908 if self._inherits[v] not in vals:
3911 tocreate[v] = {'id': vals[self._inherits[v]]}
3912 (upd0, upd1, upd2) = ('', '', [])
3914 for v in vals.keys():
3915 if v in self._inherit_fields:
3916 (table, col, col_detail, original_parent) = self._inherit_fields[v]
3917 tocreate[table][v] = vals[v]
3920 if (v not in self._inherit_fields) and (v not in self._columns):
3923 # Try-except added to filter the creation of those records whose filds are readonly.
3924 # Example : any dashboard which has all the fields readonly.(due to Views(database views))
3926 cr.execute("SELECT nextval('"+self._sequence+"')")
3928 raise except_orm(_('UserError'),
3929 _('You cannot perform this operation. New Record Creation is not allowed for this object as this object is for reporting purpose.'))
3931 id_new = cr.fetchone()[0]
3932 for table in tocreate:
3933 if self._inherits[table] in vals:
3934 del vals[self._inherits[table]]
3936 record_id = tocreate[table].pop('id', None)
3938 if record_id is None or not record_id:
3939 record_id = self.pool.get(table).create(cr, user, tocreate[table], context=context)
3941 self.pool.get(table).write(cr, user, [record_id], tocreate[table], context=context)
3943 upd0 += ',' + self._inherits[table]
3945 upd2.append(record_id)
3947 #Start : Set bool fields to be False if they are not touched(to make search more powerful)
3948 bool_fields = [x for x in self._columns.keys() if self._columns[x]._type=='boolean']
3950 for bool_field in bool_fields:
3951 if bool_field not in vals:
3952 vals[bool_field] = False
3954 for field in vals.copy():
3956 if field in self._columns:
3957 fobj = self._columns[field]
3959 fobj = self._inherit_fields[field][2]
3965 for group in groups:
3966 module = group.split(".")[0]
3967 grp = group.split(".")[1]
3968 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" % \
3969 (grp, module, 'res.groups', user))
3970 readonly = cr.fetchall()
3971 if readonly[0][0] >= 1:
3974 elif readonly[0][0] == 0:
3982 if self._columns[field]._classic_write:
3983 upd0 = upd0 + ',"' + field + '"'
3984 upd1 = upd1 + ',' + self._columns[field]._symbol_set[0]
3985 upd2.append(self._columns[field]._symbol_set[1](vals[field]))
3987 if not isinstance(self._columns[field], fields.related):
3988 upd_todo.append(field)
3989 if field in self._columns \
3990 and hasattr(self._columns[field], 'selection') \
3992 self._check_selection_field_value(cr, user, field, vals[field], context=context)
3993 if self._log_access:
3994 upd0 += ',create_uid,create_date'
3997 cr.execute('insert into "'+self._table+'" (id'+upd0+") values ("+str(id_new)+upd1+')', tuple(upd2))
3998 self.check_access_rule(cr, user, [id_new], 'create', context=context)
3999 upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
4001 if self._parent_store and not context.get('defer_parent_store_computation'):
4003 self.pool._init_parent[self._name] = True
4005 parent = vals.get(self._parent_name, False)
4007 cr.execute('select parent_right from '+self._table+' where '+self._parent_name+'=%s order by '+(self._parent_order or self._order), (parent,))
4009 result_p = cr.fetchall()
4010 for (pleft,) in result_p:
4015 cr.execute('select parent_left from '+self._table+' where id=%s', (parent,))
4016 pleft_old = cr.fetchone()[0]
4019 cr.execute('select max(parent_right) from '+self._table)
4020 pleft = cr.fetchone()[0] or 0
4021 cr.execute('update '+self._table+' set parent_left=parent_left+2 where parent_left>%s', (pleft,))
4022 cr.execute('update '+self._table+' set parent_right=parent_right+2 where parent_right>%s', (pleft,))
4023 cr.execute('update '+self._table+' set parent_left=%s,parent_right=%s where id=%s', (pleft+1, pleft+2, id_new))
4025 # default element in context must be remove when call a one2many or many2many
4026 rel_context = context.copy()
4027 for c in context.items():
4028 if c[0].startswith('default_'):
4029 del rel_context[c[0]]
4032 for field in upd_todo:
4033 result += self._columns[field].set(cr, self, id_new, field, vals[field], user, rel_context) or []
4034 self._validate(cr, user, [id_new], context)
4036 if not context.get('no_store_function', False):
4037 result += self._store_get_values(cr, user, [id_new], vals.keys(), context)
4040 for order, object, ids, fields2 in result:
4041 if not (object, ids, fields2) in done:
4042 self.pool.get(object)._store_set_values(cr, user, ids, fields2, context)
4043 done.append((object, ids, fields2))
4045 if self._log_create and not (context and context.get('no_store_function', False)):
4046 message = self._description + \
4048 self.name_get(cr, user, [id_new], context=context)[0][1] + \
4049 "' " + _("created.")
4050 self.log(cr, user, id_new, message, True, context=context)
4051 wf_service = netsvc.LocalService("workflow")
4052 wf_service.trg_create(user, self._name, id_new, cr)
4055 def browse(self, cr, uid, select, context=None, list_class=None, fields_process=None):
4056 """Fetch records as objects allowing to use dot notation to browse fields and relations
4058 :param cr: database cursor
4059 :param user: current user id
4060 :param select: id or list of ids.
4061 :param context: context arguments, like lang, time zone
4062 :rtype: object or list of objects requested
4065 self._list_class = list_class or browse_record_list
4067 # need to accepts ints and longs because ids coming from a method
4068 # launched by button in the interface have a type long...
4069 if isinstance(select, (int, long)):
4070 return browse_record(cr, uid, select, self, cache, context=context, list_class=self._list_class, fields_process=fields_process)
4071 elif isinstance(select, list):
4072 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)
4074 return browse_null()
4076 def _store_get_values(self, cr, uid, ids, fields, context):
4077 """Returns an ordered list of fields.functions to call due to
4078 an update operation on ``fields`` of records with ``ids``,
4079 obtained by calling the 'store' functions of these fields,
4080 as setup by their 'store' attribute.
4082 :return: [(priority, model_name, [record_ids,], [function_fields,])]
4084 if fields is None: fields = []
4085 stored_functions = self.pool._store_function.get(self._name, [])
4087 # use indexed names for the details of the stored_functions:
4088 model_name_, func_field_to_compute_, id_mapping_fnct_, trigger_fields_, priority_ = range(5)
4090 # only keep functions that should be triggered for the ``fields``
4092 to_compute = [f for f in stored_functions \
4093 if ((not f[trigger_fields_]) or set(fields).intersection(f[trigger_fields_]))]
4096 for function in to_compute:
4097 # use admin user for accessing objects having rules defined on store fields
4098 target_ids = [id for id in function[id_mapping_fnct_](self, cr, SUPERUSER_ID, ids, context) if id]
4100 # the compound key must consider the priority and model name
4101 key = (function[priority_], function[model_name_])
4102 for target_id in target_ids:
4103 mapping.setdefault(key, {}).setdefault(target_id,set()).add(tuple(function))
4105 # Here mapping looks like:
4106 # { (10, 'model_a') : { target_id1: [ (function_1_tuple, function_2_tuple) ], ... }
4107 # (20, 'model_a') : { target_id2: [ (function_3_tuple, function_4_tuple) ], ... }
4108 # (99, 'model_a') : { target_id1: [ (function_5_tuple, function_6_tuple) ], ... }
4111 # Now we need to generate the batch function calls list
4113 # { (10, 'model_a') : [(10, 'model_a', [record_ids,], [function_fields,])] }
4115 for ((priority,model), id_map) in mapping.iteritems():
4116 functions_ids_maps = {}
4117 # function_ids_maps =
4118 # { (function_1_tuple, function_2_tuple) : [target_id1, target_id2, ..] }
4119 for id, functions in id_map.iteritems():
4120 functions_ids_maps.setdefault(tuple(functions), []).append(id)
4121 for functions, ids in functions_ids_maps.iteritems():
4122 call_map.setdefault((priority,model),[]).append((priority, model, ids,
4123 [f[func_field_to_compute_] for f in functions]))
4124 ordered_keys = call_map.keys()
4128 result = reduce(operator.add, (call_map[k] for k in ordered_keys))
4131 def _store_set_values(self, cr, uid, ids, fields, context):
4132 """Calls the fields.function's "implementation function" for all ``fields``, on records with ``ids`` (taking care of
4133 respecting ``multi`` attributes), and stores the resulting values in the database directly."""
4138 if self._log_access:
4139 cr.execute('select id,write_date from '+self._table+' where id IN %s', (tuple(ids),))
4143 field_dict.setdefault(r[0], [])
4144 res_date = time.strptime((r[1])[:19], '%Y-%m-%d %H:%M:%S')
4145 write_date = datetime.datetime.fromtimestamp(time.mktime(res_date))
4146 for i in self.pool._store_function.get(self._name, []):
4148 up_write_date = write_date + datetime.timedelta(hours=i[5])
4149 if datetime.datetime.now() < up_write_date:
4151 field_dict[r[0]].append(i[1])
4157 if self._columns[f]._multi not in keys:
4158 keys.append(self._columns[f]._multi)
4159 todo.setdefault(self._columns[f]._multi, [])
4160 todo[self._columns[f]._multi].append(f)
4164 # use admin user for accessing objects having rules defined on store fields
4165 result = self._columns[val[0]].get(cr, self, ids, val, SUPERUSER_ID, context=context)
4166 for id, value in result.items():
4168 for f in value.keys():
4169 if f in field_dict[id]:
4176 if self._columns[v]._type in ('many2one', 'one2one'):
4178 value[v] = value[v][0]
4181 upd0.append('"'+v+'"='+self._columns[v]._symbol_set[0])
4182 upd1.append(self._columns[v]._symbol_set[1](value[v]))
4185 cr.execute('update "' + self._table + '" set ' + \
4186 ','.join(upd0) + ' where id = %s', upd1)
4190 # use admin user for accessing objects having rules defined on store fields
4191 result = self._columns[f].get(cr, self, ids, f, SUPERUSER_ID, context=context)
4192 for r in result.keys():
4194 if r in field_dict.keys():
4195 if f in field_dict[r]:
4197 for id, value in result.items():
4198 if self._columns[f]._type in ('many2one', 'one2one'):
4203 cr.execute('update "' + self._table + '" set ' + \
4204 '"'+f+'"='+self._columns[f]._symbol_set[0] + ' where id = %s', (self._columns[f]._symbol_set[1](value), id))
4210 def perm_write(self, cr, user, ids, fields, context=None):
4211 raise NotImplementedError(_('This method does not exist anymore'))
4213 # TODO: ameliorer avec NULL
4214 def _where_calc(self, cr, user, domain, active_test=True, context=None):
4215 """Computes the WHERE clause needed to implement an OpenERP domain.
4216 :param domain: the domain to compute
4218 :param active_test: whether the default filtering of records with ``active``
4219 field set to ``False`` should be applied.
4220 :return: the query expressing the given domain as provided in domain
4221 :rtype: osv.query.Query
4226 # if the object has a field named 'active', filter out all inactive
4227 # records unless they were explicitely asked for
4228 if 'active' in self._columns and (active_test and context.get('active_test', True)):
4230 active_in_args = False
4232 if a[0] == 'active':
4233 active_in_args = True
4234 if not active_in_args:
4235 domain.insert(0, ('active', '=', 1))
4237 domain = [('active', '=', 1)]
4240 e = expression.expression(cr, user, domain, self, context)
4241 tables = e.get_tables()
4242 where_clause, where_params = e.to_sql()
4243 where_clause = where_clause and [where_clause] or []
4245 where_clause, where_params, tables = [], [], ['"%s"' % self._table]
4247 return Query(tables, where_clause, where_params)
4249 def _check_qorder(self, word):
4250 if not regex_order.match(word):
4251 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)'))
4254 def _apply_ir_rules(self, cr, uid, query, mode='read', context=None):
4255 """Add what's missing in ``query`` to implement all appropriate ir.rules
4256 (using the ``model_name``'s rules or the current model's rules if ``model_name`` is None)
4258 :param query: the current query object
4260 def apply_rule(added_clause, added_params, added_tables, parent_model=None, child_object=None):
4262 if parent_model and child_object:
4263 # as inherited rules are being applied, we need to add the missing JOIN
4264 # to reach the parent table (if it was not JOINed yet in the query)
4265 child_object._inherits_join_add(child_object, parent_model, query)
4266 query.where_clause += added_clause
4267 query.where_clause_params += added_params
4268 for table in added_tables:
4269 if table not in query.tables:
4270 query.tables.append(table)
4274 # apply main rules on the object
4275 rule_obj = self.pool.get('ir.rule')
4276 apply_rule(*rule_obj.domain_get(cr, uid, self._name, mode, context=context))
4278 # apply ir.rules from the parents (through _inherits)
4279 for inherited_model in self._inherits:
4280 kwargs = dict(parent_model=inherited_model, child_object=self) #workaround for python2.5
4281 apply_rule(*rule_obj.domain_get(cr, uid, inherited_model, mode, context=context), **kwargs)
4283 def _generate_m2o_order_by(self, order_field, query):
4285 Add possibly missing JOIN to ``query`` and generate the ORDER BY clause for m2o fields,
4286 either native m2o fields or function/related fields that are stored, including
4287 intermediate JOINs for inheritance if required.
4289 :return: the qualified field name to use in an ORDER BY clause to sort by ``order_field``
4291 if order_field not in self._columns and order_field in self._inherit_fields:
4292 # also add missing joins for reaching the table containing the m2o field
4293 qualified_field = self._inherits_join_calc(order_field, query)
4294 order_field_column = self._inherit_fields[order_field][2]
4296 qualified_field = '"%s"."%s"' % (self._table, order_field)
4297 order_field_column = self._columns[order_field]
4299 assert order_field_column._type == 'many2one', 'Invalid field passed to _generate_m2o_order_by()'
4300 if not order_field_column._classic_write and not getattr(order_field_column, 'store', False):
4301 logging.getLogger('orm.search').debug("Many2one function/related fields must be stored " \
4302 "to be used as ordering fields! Ignoring sorting for %s.%s",
4303 self._name, order_field)
4306 # figure out the applicable order_by for the m2o
4307 dest_model = self.pool.get(order_field_column._obj)
4308 m2o_order = dest_model._order
4309 if not regex_order.match(m2o_order):
4310 # _order is complex, can't use it here, so we default to _rec_name
4311 m2o_order = dest_model._rec_name
4313 # extract the field names, to be able to qualify them and add desc/asc
4315 for order_part in m2o_order.split(","):
4316 m2o_order_list.append(order_part.strip().split(" ",1)[0].strip())
4317 m2o_order = m2o_order_list
4319 # Join the dest m2o table if it's not joined yet. We use [LEFT] OUTER join here
4320 # as we don't want to exclude results that have NULL values for the m2o
4321 src_table, src_field = qualified_field.replace('"','').split('.', 1)
4322 query.join((src_table, dest_model._table, src_field, 'id'), outer=True)
4323 qualify = lambda field: '"%s"."%s"' % (dest_model._table, field)
4324 return map(qualify, m2o_order) if isinstance(m2o_order, list) else qualify(m2o_order)
4327 def _generate_order_by(self, order_spec, query):
4329 Attempt to consruct an appropriate ORDER BY clause based on order_spec, which must be
4330 a comma-separated list of valid field names, optionally followed by an ASC or DESC direction.
4332 :raise" except_orm in case order_spec is malformed
4334 order_by_clause = self._order
4336 order_by_elements = []
4337 self._check_qorder(order_spec)
4338 for order_part in order_spec.split(','):
4339 order_split = order_part.strip().split(' ')
4340 order_field = order_split[0].strip()
4341 order_direction = order_split[1].strip() if len(order_split) == 2 else ''
4343 if order_field == 'id':
4344 order_by_clause = '"%s"."%s"' % (self._table, order_field)
4345 elif order_field in self._columns:
4346 order_column = self._columns[order_field]
4347 if order_column._classic_read:
4348 inner_clause = '"%s"."%s"' % (self._table, order_field)
4349 elif order_column._type == 'many2one':
4350 inner_clause = self._generate_m2o_order_by(order_field, query)
4352 continue # ignore non-readable or "non-joinable" fields
4353 elif order_field in self._inherit_fields:
4354 parent_obj = self.pool.get(self._inherit_fields[order_field][3])
4355 order_column = parent_obj._columns[order_field]
4356 if order_column._classic_read:
4357 inner_clause = self._inherits_join_calc(order_field, query)
4358 elif order_column._type == 'many2one':
4359 inner_clause = self._generate_m2o_order_by(order_field, query)
4361 continue # ignore non-readable or "non-joinable" fields
4363 if isinstance(inner_clause, list):
4364 for clause in inner_clause:
4365 order_by_elements.append("%s %s" % (clause, order_direction))
4367 order_by_elements.append("%s %s" % (inner_clause, order_direction))
4368 if order_by_elements:
4369 order_by_clause = ",".join(order_by_elements)
4371 return order_by_clause and (' ORDER BY %s ' % order_by_clause) or ''
4373 def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
4375 Private implementation of search() method, allowing specifying the uid to use for the access right check.
4376 This is useful for example when filling in the selection list for a drop-down and avoiding access rights errors,
4377 by specifying ``access_rights_uid=1`` to bypass access rights check, but not ir.rules!
4378 This is ok at the security level because this method is private and not callable through XML-RPC.
4380 :param access_rights_uid: optional user ID to use when checking access rights
4381 (not for ir.rules, this is only for ir.model.access)
4385 self.check_read(cr, access_rights_uid or user)
4387 # For transient models, restrict acces to the current user, except for the super-user
4388 if self.is_transient() and self._log_access and user != SUPERUSER_ID:
4389 args = expression.AND(([('create_uid', '=', user)], args or []))
4391 query = self._where_calc(cr, user, args, context=context)
4392 self._apply_ir_rules(cr, user, query, 'read', context=context)
4393 order_by = self._generate_order_by(order, query)
4394 from_clause, where_clause, where_clause_params = query.get_sql()
4396 limit_str = limit and ' limit %d' % limit or ''
4397 offset_str = offset and ' offset %d' % offset or ''
4398 where_str = where_clause and (" WHERE %s" % where_clause) or ''
4401 cr.execute('SELECT count("%s".id) FROM ' % self._table + from_clause + where_str + limit_str + offset_str, where_clause_params)
4404 cr.execute('SELECT "%s".id FROM ' % self._table + from_clause + where_str + order_by + limit_str + offset_str, where_clause_params)
4406 return [x[0] for x in res]
4408 # returns the different values ever entered for one field
4409 # this is used, for example, in the client when the user hits enter on
4411 def distinct_field_get(self, cr, uid, field, value, args=None, offset=0, limit=None):
4414 if field in self._inherit_fields:
4415 return self.pool.get(self._inherit_fields[field][0]).distinct_field_get(cr, uid, field, value, args, offset, limit)
4417 return self._columns[field].search(cr, self, args, field, value, offset, limit, uid)
4419 def copy_data(self, cr, uid, id, default=None, context=None):
4421 Copy given record's data with all its fields values
4423 :param cr: database cursor
4424 :param user: current user id
4425 :param id: id of the record to copy
4426 :param default: field values to override in the original values of the copied record
4427 :type default: dictionary
4428 :param context: context arguments, like lang, time zone
4429 :type context: dictionary
4430 :return: dictionary containing all the field values
4436 # avoid recursion through already copied records in case of circular relationship
4437 seen_map = context.setdefault('__copy_data_seen',{})
4438 if id in seen_map.setdefault(self._name,[]):
4440 seen_map[self._name].append(id)
4444 if 'state' not in default:
4445 if 'state' in self._defaults:
4446 if callable(self._defaults['state']):
4447 default['state'] = self._defaults['state'](self, cr, uid, context)
4449 default['state'] = self._defaults['state']
4451 context_wo_lang = context.copy()
4452 if 'lang' in context:
4453 del context_wo_lang['lang']
4454 data = self.read(cr, uid, [id,], context=context_wo_lang)
4458 raise IndexError( _("Record #%d of %s not found, cannot copy!") %( id, self._name))
4460 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
4461 fields = self.fields_get(cr, uid, context=context)
4463 ftype = fields[f]['type']
4465 if self._log_access and f in LOG_ACCESS_COLUMNS:
4469 data[f] = default[f]
4470 elif 'function' in fields[f]:
4472 elif ftype == 'many2one':
4474 data[f] = data[f] and data[f][0]
4477 elif ftype in ('one2many', 'one2one'):
4479 rel = self.pool.get(fields[f]['relation'])
4481 # duplicate following the order of the ids
4482 # because we'll rely on it later for copying
4483 # translations in copy_translation()!
4485 for rel_id in data[f]:
4486 # the lines are first duplicated using the wrong (old)
4487 # parent but then are reassigned to the correct one thanks
4488 # to the (0, 0, ...)
4489 d = rel.copy_data(cr, uid, rel_id, context=context)
4491 res.append((0, 0, d))
4493 elif ftype == 'many2many':
4494 data[f] = [(6, 0, data[f])]
4498 # make sure we don't break the current parent_store structure and
4499 # force a clean recompute!
4500 for parent_column in ['parent_left', 'parent_right']:
4501 data.pop(parent_column, None)
4502 # Remove _inherits field's from data recursively, missing parents will
4503 # be created by create() (so that copy() copy everything).
4504 def remove_ids(inherits_dict):
4505 for parent_table in inherits_dict:
4506 del data[inherits_dict[parent_table]]
4507 remove_ids(self.pool.get(parent_table)._inherits)
4508 remove_ids(self._inherits)
4511 def copy_translations(self, cr, uid, old_id, new_id, context=None):
4515 # avoid recursion through already copied records in case of circular relationship
4516 seen_map = context.setdefault('__copy_translations_seen',{})
4517 if old_id in seen_map.setdefault(self._name,[]):
4519 seen_map[self._name].append(old_id)
4521 trans_obj = self.pool.get('ir.translation')
4522 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
4523 fields = self.fields_get(cr, uid, context=context)
4525 translation_records = []
4526 for field_name, field_def in fields.items():
4527 # we must recursively copy the translations for o2o and o2m
4528 if field_def['type'] in ('one2one', 'one2many'):
4529 target_obj = self.pool.get(field_def['relation'])
4530 old_record, new_record = self.read(cr, uid, [old_id, new_id], [field_name], context=context)
4531 # here we rely on the order of the ids to match the translations
4532 # as foreseen in copy_data()
4533 old_children = sorted(old_record[field_name])
4534 new_children = sorted(new_record[field_name])
4535 for (old_child, new_child) in zip(old_children, new_children):
4536 target_obj.copy_translations(cr, uid, old_child, new_child, context=context)
4537 # and for translatable fields we keep them for copy
4538 elif field_def.get('translate'):
4540 if field_name in self._columns:
4541 trans_name = self._name + "," + field_name
4542 elif field_name in self._inherit_fields:
4543 trans_name = self._inherit_fields[field_name][0] + "," + field_name
4545 trans_ids = trans_obj.search(cr, uid, [
4546 ('name', '=', trans_name),
4547 ('res_id', '=', old_id)
4549 translation_records.extend(trans_obj.read(cr, uid, trans_ids, context=context))
4551 for record in translation_records:
4553 record['res_id'] = new_id
4554 trans_obj.create(cr, uid, record, context=context)
4557 def copy(self, cr, uid, id, default=None, context=None):
4559 Duplicate record with given id updating it with default values
4561 :param cr: database cursor
4562 :param uid: current user id
4563 :param id: id of the record to copy
4564 :param default: dictionary of field values to override in the original values of the copied record, e.g: ``{'field_name': overriden_value, ...}``
4565 :type default: dictionary
4566 :param context: context arguments, like lang, time zone
4567 :type context: dictionary
4573 context = context.copy()
4574 data = self.copy_data(cr, uid, id, default, context)
4575 new_id = self.create(cr, uid, data, context)
4576 self.copy_translations(cr, uid, id, new_id, context)
4579 def exists(self, cr, uid, ids, context=None):
4580 """Checks whether the given id or ids exist in this model,
4581 and return the list of ids that do. This is simple to use for
4582 a truth test on a browse_record::
4587 :param ids: id or list of ids to check for existence
4588 :type ids: int or [int]
4589 :return: the list of ids that currently exist, out of
4592 if type(ids) in (int, long):
4594 query = 'SELECT id FROM "%s"' % (self._table)
4595 cr.execute(query + "WHERE ID IN %s", (tuple(ids),))
4596 return [x[0] for x in cr.fetchall()]
4598 def check_recursion(self, cr, uid, ids, context=None, parent=None):
4599 warnings.warn("You are using deprecated %s.check_recursion(). Please use the '_check_recursion()' instead!" % \
4600 self._name, DeprecationWarning, stacklevel=3)
4601 assert parent is None or parent in self._columns or parent in self._inherit_fields,\
4602 "The 'parent' parameter passed to check_recursion() must be None or a valid field name"
4603 return self._check_recursion(cr, uid, ids, context, parent)
4605 def _check_recursion(self, cr, uid, ids, context=None, parent=None):
4607 Verifies that there is no loop in a hierarchical structure of records,
4608 by following the parent relationship using the **parent** field until a loop
4609 is detected or until a top-level record is found.
4611 :param cr: database cursor
4612 :param uid: current user id
4613 :param ids: list of ids of records to check
4614 :param parent: optional parent field name (default: ``self._parent_name = parent_id``)
4615 :return: **True** if the operation can proceed safely, or **False** if an infinite loop is detected.
4619 parent = self._parent_name
4621 query = 'SELECT distinct "%s" FROM "%s" WHERE id IN %%s' % (parent, self._table)
4624 for i in range(0, len(ids), cr.IN_MAX):
4625 sub_ids_parent = ids_parent[i:i+cr.IN_MAX]
4626 cr.execute(query, (tuple(sub_ids_parent),))
4627 ids_parent2.extend(filter(None, map(lambda x: x[0], cr.fetchall())))
4628 ids_parent = ids_parent2
4629 for i in ids_parent:
4634 def _get_external_ids(self, cr, uid, ids, *args, **kwargs):
4635 """Retrieve the External ID(s) of any database record.
4637 **Synopsis**: ``_get_xml_ids(cr, uid, ids) -> { 'id': ['module.xml_id'] }``
4639 :return: map of ids to the list of their fully qualified External IDs
4640 in the form ``module.key``, or an empty list when there's no External
4641 ID for a record, e.g.::
4643 { 'id': ['module.ext_id', 'module.ext_id_bis'],
4646 ir_model_data = self.pool.get('ir.model.data')
4647 data_ids = ir_model_data.search(cr, uid, [('model', '=', self._name), ('res_id', 'in', ids)])
4648 data_results = ir_model_data.read(cr, uid, data_ids, ['module', 'name', 'res_id'])
4651 # can't use dict.fromkeys() as the list would be shared!
4653 for record in data_results:
4654 result[record['res_id']].append('%(module)s.%(name)s' % record)
4657 def get_external_id(self, cr, uid, ids, *args, **kwargs):
4658 """Retrieve the External ID of any database record, if there
4659 is one. This method works as a possible implementation
4660 for a function field, to be able to add it to any
4661 model object easily, referencing it as ``Model.get_external_id``.
4663 When multiple External IDs exist for a record, only one
4664 of them is returned (randomly).
4666 :return: map of ids to their fully qualified XML ID,
4667 defaulting to an empty string when there's none
4668 (to be usable as a function field),
4671 { 'id': 'module.ext_id',
4674 results = self._get_xml_ids(cr, uid, ids)
4675 for k, v in results.iteritems():
4682 # backwards compatibility
4683 get_xml_id = get_external_id
4684 _get_xml_ids = _get_external_ids
4687 def is_transient(self):
4688 """ Return whether the model is transient.
4693 return self._transient
4695 def _transient_clean_rows_older_than(self, cr, seconds):
4696 assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
4697 cr.execute("SELECT id FROM " + self._table + " WHERE"
4698 " COALESCE(write_date, create_date, now())::timestamp <"
4699 " (now() - interval %s)", ("%s seconds" % seconds,))
4700 ids = [x[0] for x in cr.fetchall()]
4701 self.unlink(cr, SUPERUSER_ID, ids)
4703 def _transient_clean_old_rows(self, cr, count):
4704 assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
4706 "SELECT id, COALESCE(write_date, create_date, now())::timestamp"
4707 " AS t FROM " + self._table +
4708 " ORDER BY t LIMIT %s", (count,))
4709 ids = [x[0] for x in cr.fetchall()]
4710 self.unlink(cr, SUPERUSER_ID, ids)
4712 def _transient_vacuum(self, cr, uid, force=False):
4713 """Clean the transient records.
4715 This unlinks old records from the transient model tables whenever the
4716 "_transient_max_count" or "_max_age" conditions (if any) are reached.
4717 Actual cleaning will happen only once every "_transient_check_time" calls.
4718 This means this method can be called frequently called (e.g. whenever
4719 a new record is created).
4721 assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
4722 self._transient_check_count += 1
4723 if (not force) and (self._transient_check_count % self._transient_check_time):
4724 self._transient_check_count = 0
4727 # Age-based expiration
4728 if self._transient_max_hours:
4729 self._transient_clean_rows_older_than(cr, self._transient_max_hours * 60 * 60)
4731 # Count-based expiration
4732 if self._transient_max_count:
4733 self._transient_clean_old_rows(cr, self._transient_max_count)
4737 # keep this import here, at top it will cause dependency cycle errors
4740 class Model(BaseModel):
4741 """Main super-class for regular database-persisted OpenERP models.
4743 OpenERP models are created by inheriting from this class::
4748 The system will later instantiate the class once per database (on
4749 which the class' module is installed).
4751 _register = False # not visible in ORM registry, meant to be python-inherited only
4752 _transient = False # True in a TransientModel
4754 class TransientModel(BaseModel):
4755 """Model super-class for transient records, meant to be temporarily
4756 persisted, and regularly vaccuum-cleaned.
4758 A TransientModel has a simplified access rights management,
4759 all users can create new records, and may only access the
4760 records they created. The super-user has unrestricted access
4761 to all TransientModel records.
4763 _register = False # not visible in ORM registry, meant to be python-inherited only
4766 class AbstractModel(BaseModel):
4767 """Abstract Model super-class for creating an abstract class meant to be
4768 inherited by regular models (Models or TransientModels) but not meant to
4769 be usable on its own, or persisted.
4771 Technical note: we don't want to make AbstractModel the super-class of
4772 Model or BaseModel because it would not make sense to put the main
4773 definition of persistence methods such as create() in it, and still we
4774 should be able to override them within an AbstractModel.
4776 _auto = False # don't create any database backend for AbstractModels
4777 _register = False # not visible in ORM registry, meant to be python-inherited only
4780 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: