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 import openerp.netsvc as netsvc
58 from lxml import etree
59 from openerp.tools.config import config
60 from openerp.tools.translate import _
63 from query import Query
64 import openerp.tools as tools
65 from openerp.tools.safe_eval import safe_eval as eval
67 # List of etree._Element subclasses that we choose to ignore when parsing XML.
68 from openerp.tools import SKIPPED_ELEMENT_TYPES
70 regex_order = re.compile('^(([a-z0-9_]+|"[a-z0-9_]+")( *desc| *asc)?( *, *|))+$', re.I)
71 regex_object_name = re.compile(r'^[a-z0-9_.]+$')
73 # Mapping between openerp module names and their osv classes.
74 module_class_list = {}
76 # Super-user identifier (aka Administrator aka root)
79 def transfer_field_to_modifiers(field, modifiers):
82 for attr in ('invisible', 'readonly', 'required'):
83 state_exceptions[attr] = []
84 default_values[attr] = bool(field.get(attr))
85 for state, modifs in (field.get("states",{})).items():
87 if default_values[modif[0]] != modif[1]:
88 state_exceptions[modif[0]].append(state)
90 for attr, default_value in default_values.items():
91 if state_exceptions[attr]:
92 modifiers[attr] = [("state", "not in" if default_value else "in", state_exceptions[attr])]
94 modifiers[attr] = default_value
97 # Don't deal with groups, it is done by check_group().
98 # Need the context to evaluate the invisible attribute on tree views.
99 # For non-tree views, the context shouldn't be given.
100 def transfer_node_to_modifiers(node, modifiers, context=None, in_tree_view=False):
101 if node.get('attrs'):
102 modifiers.update(eval(node.get('attrs')))
104 if node.get('states'):
105 if 'invisible' in modifiers and isinstance(modifiers['invisible'], list):
106 # TODO combine with AND or OR, use implicit AND for now.
107 modifiers['invisible'].append(('state', 'not in', node.get('states').split(',')))
109 modifiers['invisible'] = [('state', 'not in', node.get('states').split(','))]
111 for a in ('invisible', 'readonly', 'required'):
113 v = bool(eval(node.get(a), {'context': context or {}}))
114 if in_tree_view and a == 'invisible':
115 # Invisible in a tree view has a specific meaning, make it a
116 # new key in the modifiers attribute.
117 modifiers['tree_invisible'] = v
118 elif v or (a not in modifiers or not isinstance(modifiers[a], list)):
119 # Don't set the attribute to False if a dynamic value was
120 # provided (i.e. a domain from attrs or states).
124 def simplify_modifiers(modifiers):
125 for a in ('invisible', 'readonly', 'required'):
126 if a in modifiers and not modifiers[a]:
130 def transfer_modifiers_to_node(modifiers, node):
132 simplify_modifiers(modifiers)
133 node.set('modifiers', simplejson.dumps(modifiers))
136 def test_modifiers(what, expected):
138 if isinstance(what, basestring):
139 node = etree.fromstring(what)
140 transfer_node_to_modifiers(node, modifiers)
141 simplify_modifiers(modifiers)
142 json = simplejson.dumps(modifiers)
143 assert json == expected, "%s != %s" % (json, expected)
144 elif isinstance(what, dict):
145 transfer_field_to_modifiers(what, modifiers)
146 simplify_modifiers(modifiers)
147 json = simplejson.dumps(modifiers)
148 assert json == expected, "%s != %s" % (json, expected)
153 # openerp.osv.orm.modifiers_tests()
154 def modifiers_tests():
155 test_modifiers('<field name="a"/>', '{}')
156 test_modifiers('<field name="a" invisible="1"/>', '{"invisible": true}')
157 test_modifiers('<field name="a" readonly="1"/>', '{"readonly": true}')
158 test_modifiers('<field name="a" required="1"/>', '{"required": true}')
159 test_modifiers('<field name="a" invisible="0"/>', '{}')
160 test_modifiers('<field name="a" readonly="0"/>', '{}')
161 test_modifiers('<field name="a" required="0"/>', '{}')
162 test_modifiers('<field name="a" invisible="1" required="1"/>', '{"invisible": true, "required": true}') # TODO order is not guaranteed
163 test_modifiers('<field name="a" invisible="1" required="0"/>', '{"invisible": true}')
164 test_modifiers('<field name="a" invisible="0" required="1"/>', '{"required": true}')
165 test_modifiers("""<field name="a" attrs="{'invisible': [('b', '=', 'c')]}"/>""", '{"invisible": [["b", "=", "c"]]}')
167 # The dictionary is supposed to be the result of fields_get().
168 test_modifiers({}, '{}')
169 test_modifiers({"invisible": True}, '{"invisible": true}')
170 test_modifiers({"invisible": False}, '{}')
173 def check_object_name(name):
174 """ Check if the given name is a valid openerp object name.
176 The _name attribute in osv and osv_memory object is subject to
177 some restrictions. This function returns True or False whether
178 the given name is allowed or not.
180 TODO: this is an approximation. The goal in this approximation
181 is to disallow uppercase characters (in some places, we quote
182 table/column names and in other not, which leads to this kind
185 psycopg2.ProgrammingError: relation "xxx" does not exist).
187 The same restriction should apply to both osv and osv_memory
188 objects for consistency.
191 if regex_object_name.match(name) is None:
195 def raise_on_invalid_object_name(name):
196 if not check_object_name(name):
197 msg = "The _name attribute %s is not valid." % name
198 logger = netsvc.Logger()
199 logger.notifyChannel('orm', netsvc.LOG_ERROR, msg)
200 raise except_orm('ValueError', msg)
202 POSTGRES_CONFDELTYPES = {
210 def last_day_of_current_month():
211 today = datetime.date.today()
212 last_day = str(calendar.monthrange(today.year, today.month)[1])
213 return time.strftime('%Y-%m-' + last_day)
215 def intersect(la, lb):
216 return filter(lambda x: x in lb, la)
218 class except_orm(Exception):
219 def __init__(self, name, value):
222 self.args = (name, value)
224 class BrowseRecordError(Exception):
227 class browse_null(object):
228 """ Readonly python database object browser
234 def __getitem__(self, name):
237 def __getattr__(self, name):
238 return None # XXX: return self ?
246 def __nonzero__(self):
249 def __unicode__(self):
254 # TODO: execute an object method on browse_record_list
256 class browse_record_list(list):
257 """ Collection of browse objects
259 Such an instance will be returned when doing a ``browse([ids..])``
260 and will be iterable, yielding browse() objects
263 def __init__(self, lst, context=None):
266 super(browse_record_list, self).__init__(lst)
267 self.context = context
270 class browse_record(object):
271 """ An object that behaves like a row of an object's table.
272 It has attributes after the columns of the corresponding object.
276 uobj = pool.get('res.users')
277 user_rec = uobj.browse(cr, uid, 104)
280 logger = netsvc.Logger()
282 def __init__(self, cr, uid, id, table, cache, context=None, list_class=None, fields_process=None):
284 @param cache a dictionary of model->field->data to be shared accross browse
285 objects, thus reducing the SQL read()s . It can speed up things a lot,
286 but also be disastrous if not discarded after write()/unlink() operations
287 @param table the object (inherited from orm)
288 @param context dictionary with an optional context
290 if fields_process is None:
294 self._list_class = list_class or browse_record_list
299 self._table_name = self._table._name
300 self.__logger = logging.getLogger(
301 'osv.browse_record.' + self._table_name)
302 self._context = context
303 self._fields_process = fields_process
305 cache.setdefault(table._name, {})
306 self._data = cache[table._name]
308 if not (id and isinstance(id, (int, long,))):
309 raise BrowseRecordError(_('Wrong ID for the browse record, got %r, expected an integer.') % (id,))
310 # if not table.exists(cr, uid, id, context):
311 # raise BrowseRecordError(_('Object %s does not exists') % (self,))
313 if id not in self._data:
314 self._data[id] = {'id': id}
318 def __getitem__(self, name):
322 if name not in self._data[self._id]:
323 # build the list of fields we will fetch
325 # fetch the definition of the field which was asked for
326 if name in self._table._columns:
327 col = self._table._columns[name]
328 elif name in self._table._inherit_fields:
329 col = self._table._inherit_fields[name][2]
330 elif hasattr(self._table, str(name)):
331 attr = getattr(self._table, name)
333 if isinstance(attr, (types.MethodType, types.LambdaType, types.FunctionType)):
334 return lambda *args, **argv: attr(self._cr, self._uid, [self._id], *args, **argv)
338 self.logger.notifyChannel("browse_record", netsvc.LOG_WARNING,
339 "Field '%s' does not exist in object '%s': \n%s" % (
340 name, self, ''.join(traceback.format_exc())))
341 raise KeyError("Field '%s' does not exist in object '%s'" % (
344 # if the field is a classic one or a many2one, we'll fetch all classic and many2one fields
346 # gen the list of "local" (ie not inherited) fields which are classic or many2one
347 fields_to_fetch = filter(lambda x: x[1]._classic_write, self._table._columns.items())
348 # gen the list of inherited fields
349 inherits = map(lambda x: (x[0], x[1][2]), self._table._inherit_fields.items())
350 # complete the field list with the inherited fields which are classic or many2one
351 fields_to_fetch += filter(lambda x: x[1]._classic_write, inherits)
352 # otherwise we fetch only that field
354 fields_to_fetch = [(name, col)]
355 ids = filter(lambda id: name not in self._data[id], self._data.keys())
357 field_names = map(lambda x: x[0], fields_to_fetch)
358 field_values = self._table.read(self._cr, self._uid, ids, field_names, context=self._context, load="_classic_write")
360 # TODO: improve this, very slow for reports
361 if self._fields_process:
362 lang = self._context.get('lang', 'en_US') or 'en_US'
363 lang_obj_ids = self.pool.get('res.lang').search(self._cr, self._uid, [('code', '=', lang)])
365 raise Exception(_('Language with code "%s" is not defined in your system !\nDefine it through the Administration menu.') % (lang,))
366 lang_obj = self.pool.get('res.lang').browse(self._cr, self._uid, lang_obj_ids[0])
368 for field_name, field_column in fields_to_fetch:
369 if field_column._type in self._fields_process:
370 for result_line in field_values:
371 result_line[field_name] = self._fields_process[field_column._type](result_line[field_name])
372 if result_line[field_name]:
373 result_line[field_name].set_value(self._cr, self._uid, result_line[field_name], self, field_column, lang_obj)
376 # Where did those ids come from? Perhaps old entries in ir_model_dat?
377 self.__logger.warn("No field_values found for ids %s in %s", ids, self)
378 raise KeyError('Field %s not found in %s'%(name, self))
379 # create browse records for 'remote' objects
380 for result_line in field_values:
382 for field_name, field_column in fields_to_fetch:
383 if field_column._type in ('many2one', 'one2one'):
384 if result_line[field_name]:
385 obj = self._table.pool.get(field_column._obj)
386 if isinstance(result_line[field_name], (list, tuple)):
387 value = result_line[field_name][0]
389 value = result_line[field_name]
391 # FIXME: this happen when a _inherits object
392 # overwrite a field of it parent. Need
393 # testing to be sure we got the right
394 # object and not the parent one.
395 if not isinstance(value, browse_record):
397 # In some cases the target model is not available yet, so we must ignore it,
398 # which is safe in most cases, this value will just be loaded later when needed.
399 # This situation can be caused by custom fields that connect objects with m2o without
400 # respecting module dependencies, causing relationships to be connected to soon when
401 # the target is not loaded yet.
403 new_data[field_name] = browse_record(self._cr,
404 self._uid, value, obj, self._cache,
405 context=self._context,
406 list_class=self._list_class,
407 fields_process=self._fields_process)
409 new_data[field_name] = value
411 new_data[field_name] = browse_null()
413 new_data[field_name] = browse_null()
414 elif field_column._type in ('one2many', 'many2many') and len(result_line[field_name]):
415 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)
416 elif field_column._type in ('reference'):
417 if result_line[field_name]:
418 if isinstance(result_line[field_name], browse_record):
419 new_data[field_name] = result_line[field_name]
421 ref_obj, ref_id = result_line[field_name].split(',')
422 ref_id = long(ref_id)
424 obj = self._table.pool.get(ref_obj)
425 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)
427 new_data[field_name] = browse_null()
429 new_data[field_name] = browse_null()
431 new_data[field_name] = result_line[field_name]
432 self._data[result_line['id']].update(new_data)
434 if not name in self._data[self._id]:
435 # How did this happen? Could be a missing model due to custom fields used too soon, see above.
436 self.logger.notifyChannel("browse_record", netsvc.LOG_ERROR,
437 "Fields to fetch: %s, Field values: %s"%(field_names, field_values))
438 self.logger.notifyChannel("browse_record", netsvc.LOG_ERROR,
439 "Cached: %s, Table: %s"%(self._data[self._id], self._table))
440 raise KeyError(_('Unknown attribute %s in %s ') % (name, self))
441 return self._data[self._id][name]
443 def __getattr__(self, name):
447 raise AttributeError(e)
449 def __contains__(self, name):
450 return (name in self._table._columns) or (name in self._table._inherit_fields) or hasattr(self._table, name)
452 def __hasattr__(self, name):
459 return "browse_record(%s, %d)" % (self._table_name, self._id)
461 def __eq__(self, other):
462 if not isinstance(other, browse_record):
464 return (self._table_name, self._id) == (other._table_name, other._id)
466 def __ne__(self, other):
467 if not isinstance(other, browse_record):
469 return (self._table_name, self._id) != (other._table_name, other._id)
471 # we need to define __unicode__ even though we've already defined __str__
472 # because we have overridden __getattr__
473 def __unicode__(self):
474 return unicode(str(self))
477 return hash((self._table_name, self._id))
485 (type returned by postgres when the column was created, type expression to create the column)
489 fields.boolean: 'bool',
490 fields.integer: 'int4',
491 fields.integer_big: 'int8',
495 fields.datetime: 'timestamp',
496 fields.binary: 'bytea',
497 fields.many2one: 'int4',
499 if type(f) in type_dict:
500 f_type = (type_dict[type(f)], type_dict[type(f)])
501 elif isinstance(f, fields.float):
503 f_type = ('numeric', 'NUMERIC')
505 f_type = ('float8', 'DOUBLE PRECISION')
506 elif isinstance(f, (fields.char, fields.reference)):
507 f_type = ('varchar', 'VARCHAR(%d)' % (f.size,))
508 elif isinstance(f, fields.selection):
509 if isinstance(f.selection, list) and isinstance(f.selection[0][0], (str, unicode)):
510 f_size = reduce(lambda x, y: max(x, len(y[0])), f.selection, f.size or 16)
511 elif isinstance(f.selection, list) and isinstance(f.selection[0][0], int):
514 f_size = getattr(f, 'size', None) or 16
517 f_type = ('int4', 'INTEGER')
519 f_type = ('varchar', 'VARCHAR(%d)' % f_size)
520 elif isinstance(f, fields.function) and eval('fields.'+(f._type), globals()) in type_dict:
521 t = eval('fields.'+(f._type), globals())
522 f_type = (type_dict[t], type_dict[t])
523 elif isinstance(f, fields.function) and f._type == 'float':
525 f_type = ('numeric', 'NUMERIC')
527 f_type = ('float8', 'DOUBLE PRECISION')
528 elif isinstance(f, fields.function) and f._type == 'selection':
529 f_type = ('text', 'text')
530 elif isinstance(f, fields.function) and f._type == 'char':
531 f_type = ('varchar', 'VARCHAR(%d)' % (f.size))
533 logger = netsvc.Logger()
534 logger.notifyChannel("init", netsvc.LOG_WARNING, '%s type not supported!' % (type(f)))
539 class MetaModel(type):
540 """ Metaclass for the Model.
542 This class is used as the metaclass for the Model class to discover
543 the models defined in a module (i.e. without instanciating them).
544 If the automatic discovery is not needed, it is possible to set the
545 model's _register attribute to False.
549 module_to_models = {}
551 def __init__(self, name, bases, attrs):
552 if not self._register:
553 self._register = True
554 super(MetaModel, self).__init__(name, bases, attrs)
557 module_name = self.__module__.split('.')[0]
558 if not hasattr(self, '_module'):
559 self._module = module_name
561 # Remember which models to instanciate for this module.
562 self.module_to_models.setdefault(self._module, []).append(self)
565 class orm_template(object):
566 """ Base class for OpenERP models.
568 OpenERP models are created by inheriting from this class (although
569 not directly; more specifically by inheriting from osv or
570 osv_memory). The constructor is called once, usually directly
571 after the class definition, e.g.:
577 The system will later instanciate the class once per database (on
578 which the class' module is installed).
586 _parent_name = 'parent_id'
587 _parent_store = False
588 _parent_order = False
594 # Mapping from inherits'd field name to triple (m, r, f)
595 # where m is the model from which it is inherits'd,
596 # r is the (local) field towards m,
597 # and f is the _column object itself.
599 # Mapping field name/column_info object
600 # This is similar to _inherit_fields but:
601 # 1. includes self fields,
602 # 2. uses column_info instead of a triple.
608 CONCURRENCY_CHECK_FIELD = '__last_update'
609 def log(self, cr, uid, id, message, secondary=False, context=None):
610 if context and context.get('disable_log'):
612 return self.pool.get('res.log').create(cr, uid,
615 'res_model': self._name,
616 'secondary': secondary,
622 def view_init(self, cr, uid, fields_list, context=None):
623 """Override this method to do specific things when a view on the object is opened."""
626 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False):
627 raise NotImplementedError(_('The read_group method is not implemented on this object !'))
629 def _field_create(self, cr, context=None):
630 """ Create entries in ir_model_fields for all the model's fields.
632 If necessary, also create an entry in ir_model, and if called from the
633 modules loading scheme (by receiving 'module' in the context), also
634 create entries in ir_model_data (for the model and the fields).
636 - create an entry in ir_model (if there is not already one),
637 - create an entry in ir_model_data (if there is not already one, and if
638 'module' is in the context),
639 - update ir_model_fields with the fields found in _columns
640 (TODO there is some redundancy as _columns is updated from
641 ir_model_fields in __init__).
646 cr.execute("SELECT id FROM ir_model WHERE model=%s", (self._name,))
648 cr.execute('SELECT nextval(%s)', ('ir_model_id_seq',))
649 model_id = cr.fetchone()[0]
650 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'))
652 model_id = cr.fetchone()[0]
653 if 'module' in context:
654 name_id = 'model_'+self._name.replace('.', '_')
655 cr.execute('select * from ir_model_data where name=%s and module=%s', (name_id, context['module']))
657 cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, now(), now(), %s, %s, %s)", \
658 (name_id, context['module'], 'ir.model', model_id)
663 cr.execute("SELECT * FROM ir_model_fields WHERE model=%s", (self._name,))
665 for rec in cr.dictfetchall():
666 cols[rec['name']] = rec
668 for (k, f) in self._columns.items():
670 'model_id': model_id,
673 'field_description': f.string.replace("'", " "),
675 'relation': f._obj or '',
676 'view_load': (f.view_load and 1) or 0,
677 'select_level': tools.ustr(f.select or 0),
678 'readonly': (f.readonly and 1) or 0,
679 'required': (f.required and 1) or 0,
680 'selectable': (f.selectable and 1) or 0,
681 'translate': (f.translate and 1) or 0,
682 'relation_field': (f._type=='one2many' and isinstance(f, fields.one2many)) and f._fields_id or '',
684 # When its a custom field,it does not contain f.select
685 if context.get('field_state', 'base') == 'manual':
686 if context.get('field_name', '') == k:
687 vals['select_level'] = context.get('select', '0')
688 #setting value to let the problem NOT occur next time
690 vals['select_level'] = cols[k]['select_level']
693 cr.execute('select nextval(%s)', ('ir_model_fields_id_seq',))
694 id = cr.fetchone()[0]
696 cr.execute("""INSERT INTO ir_model_fields (
697 id, model_id, model, name, field_description, ttype,
698 relation,view_load,state,select_level,relation_field, translate
700 %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s
702 id, vals['model_id'], vals['model'], vals['name'], vals['field_description'], vals['ttype'],
703 vals['relation'], bool(vals['view_load']), 'base',
704 vals['select_level'], vals['relation_field'], bool(vals['translate'])
706 if 'module' in context:
707 name1 = 'field_' + self._table + '_' + k
708 cr.execute("select name from ir_model_data where name=%s", (name1,))
710 name1 = name1 + "_" + str(id)
711 cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, now(), now(), %s, %s, %s)", \
712 (name1, context['module'], 'ir.model.fields', id)
715 for key, val in vals.items():
716 if cols[k][key] != vals[key]:
717 cr.execute('update ir_model_fields set field_description=%s where model=%s and name=%s', (vals['field_description'], vals['model'], vals['name']))
719 cr.execute("""UPDATE ir_model_fields SET
720 model_id=%s, field_description=%s, ttype=%s, relation=%s,
721 view_load=%s, select_level=%s, readonly=%s ,required=%s, selectable=%s, relation_field=%s, translate=%s
723 model=%s AND name=%s""", (
724 vals['model_id'], vals['field_description'], vals['ttype'],
725 vals['relation'], bool(vals['view_load']),
726 vals['select_level'], bool(vals['readonly']), bool(vals['required']), bool(vals['selectable']), vals['relation_field'], bool(vals['translate']), vals['model'], vals['name']
731 def _auto_init(self, cr, context=None):
732 raise_on_invalid_object_name(self._name)
733 self._field_create(cr, context=context)
735 def _auto_end(self, cr, context=None):
739 # Goal: try to apply inheritance at the instanciation level and
740 # put objects in the pool var
743 def makeInstance(cls, pool, cr, attributes):
744 """ Instanciate a given model.
746 This class method instanciates the class of some model (i.e. a class
747 deriving from osv or osv_memory). The class might be the class passed
748 in argument or, if it inherits from another class, a class constructed
749 by combining the two classes.
751 The ``attributes`` argument specifies which parent class attributes
754 TODO: the creation of the combined class is repeated at each call of
755 this method. This is probably unnecessary.
758 parent_names = getattr(cls, '_inherit', None)
760 if isinstance(parent_names, (str, unicode)):
761 name = cls._name or parent_names
762 parent_names = [parent_names]
767 raise TypeError('_name is mandatory in case of multiple inheritance')
769 for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]):
770 parent_class = pool.get(parent_name).__class__
771 if not pool.get(parent_name):
772 raise TypeError('The model "%s" specifies an unexisting parent class "%s"\n'
773 'You may need to add a dependency on the parent class\' module.' % (name, parent_name))
776 new = copy.copy(getattr(pool.get(parent_name), s))
778 # Don't _inherit custom fields.
782 if hasattr(new, 'update'):
783 new.update(cls.__dict__.get(s, {}))
784 elif s=='_constraints':
785 for c in cls.__dict__.get(s, []):
787 for c2 in range(len(new)):
788 #For _constraints, we should check field and methods as well
789 if new[c2][2]==c[2] and (new[c2][0] == c[0] \
790 or getattr(new[c2][0],'__name__', True) == \
791 getattr(c[0],'__name__', False)):
792 # If new class defines a constraint with
793 # same function name, we let it override
801 new.extend(cls.__dict__.get(s, []))
803 cls = type(name, (cls, parent_class), dict(nattr, _register=False))
804 obj = object.__new__(cls)
805 obj.__init__(pool, cr)
809 """ Register this model.
811 This doesn't create an instance but simply register the model
812 as being part of the module where it is defined.
814 TODO make it possible to not even have to call the constructor
819 # Set the module name (e.g. base, sale, accounting, ...) on the class.
820 module = cls.__module__.split('.')[0]
821 if not hasattr(cls, '_module'):
824 # Remember which models to instanciate for this module.
825 module_class_list.setdefault(cls._module, []).append(cls)
827 # Since we don't return an instance here, the __init__
828 # method won't be called.
831 def __init__(self, pool, cr):
832 """ Initialize a model and make it part of the given registry."""
833 pool.add(self._name, self)
836 if not self._name and not hasattr(self, '_inherit'):
837 name = type(self).__name__.split('.')[0]
838 msg = "The class %s has to have a _name attribute" % name
840 logger = netsvc.Logger()
841 logger.notifyChannel('orm', netsvc.LOG_ERROR, msg)
842 raise except_orm('ValueError', msg)
844 if not self._description:
845 self._description = self._name
847 self._table = self._name.replace('.', '_')
849 def browse(self, cr, uid, select, context=None, list_class=None, fields_process=None):
850 """Fetch records as objects allowing to use dot notation to browse fields and relations
852 :param cr: database cursor
853 :param user: current user id
854 :param select: id or list of ids.
855 :param context: context arguments, like lang, time zone
856 :rtype: object or list of objects requested
859 self._list_class = list_class or browse_record_list
861 # need to accepts ints and longs because ids coming from a method
862 # launched by button in the interface have a type long...
863 if isinstance(select, (int, long)):
864 return browse_record(cr, uid, select, self, cache, context=context, list_class=self._list_class, fields_process=fields_process)
865 elif isinstance(select, list):
866 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)
870 def __export_row(self, cr, uid, row, fields, context=None):
874 def check_type(field_type):
875 if field_type == 'float':
877 elif field_type == 'integer':
879 elif field_type == 'boolean':
883 def selection_field(in_field):
884 col_obj = self.pool.get(in_field.keys()[0])
885 if f[i] in col_obj._columns.keys():
886 return col_obj._columns[f[i]]
887 elif f[i] in col_obj._inherits.keys():
888 selection_field(col_obj._inherits)
893 data = map(lambda x: '', range(len(fields)))
895 for fpos in range(len(fields)):
904 model_data = self.pool.get('ir.model.data')
905 data_ids = model_data.search(cr, uid, [('model', '=', r._table_name), ('res_id', '=', r['id'])])
907 d = model_data.read(cr, uid, data_ids, ['name', 'module'])[0]
909 r = '%s.%s' % (d['module'], d['name'])
916 # To display external name of selection field when its exported
918 if f[i] in self._columns.keys():
919 cols = self._columns[f[i]]
920 elif f[i] in self._inherit_fields.keys():
921 cols = selection_field(self._inherits)
922 if cols and cols._type == 'selection':
923 sel_list = cols.selection
924 if r and type(sel_list) == type([]):
925 r = [x[1] for x in sel_list if r==x[0]]
926 r = r and r[0] or False
928 if f[i] in self._columns:
929 r = check_type(self._columns[f[i]]._type)
930 elif f[i] in self._inherit_fields:
931 r = check_type(self._inherit_fields[f[i]][2]._type)
932 data[fpos] = r or False
934 if isinstance(r, (browse_record_list, list)):
936 fields2 = map(lambda x: (x[:i+1]==f[:i+1] and x[i+1:]) \
939 if [x for x in fields2 if x]:
943 lines2 = self.__export_row(cr, uid, row2, fields2,
946 for fpos2 in range(len(fields)):
947 if lines2 and lines2[0][fpos2]:
948 data[fpos2] = lines2[0][fpos2]
952 name_relation = self.pool.get(rr._table_name)._rec_name
953 if isinstance(rr[name_relation], browse_record):
954 rr = rr[name_relation]
955 rr_name = self.pool.get(rr._table_name).name_get(cr, uid, [rr.id], context=context)
956 rr_name = rr_name and rr_name[0] and rr_name[0][1] or ''
957 dt += tools.ustr(rr_name or '') + ','
967 if isinstance(r, browse_record):
968 r = self.pool.get(r._table_name).name_get(cr, uid, [r.id], context=context)
969 r = r and r[0] and r[0][1] or ''
970 data[fpos] = tools.ustr(r or '')
971 return [data] + lines
973 def export_data(self, cr, uid, ids, fields_to_export, context=None):
975 Export fields for selected objects
977 :param cr: database cursor
978 :param uid: current user id
979 :param ids: list of ids
980 :param fields_to_export: list of fields
981 :param context: context arguments, like lang, time zone
982 :rtype: dictionary with a *datas* matrix
984 This method is used when exporting data via client menu
989 cols = self._columns.copy()
990 for f in self._inherit_fields:
991 cols.update({f: self._inherit_fields[f][2]})
993 if x=='.id': return [x]
994 return x.replace(':id','/id').replace('.id','/.id').split('/')
995 fields_to_export = map(fsplit, fields_to_export)
997 for row in self.browse(cr, uid, ids, context):
998 datas += self.__export_row(cr, uid, row, fields_to_export, context)
999 return {'datas': datas}
1001 def import_data(self, cr, uid, fields, datas, mode='init', current_module='', noupdate=False, context=None, filename=None):
1003 Import given data in given module
1005 :param cr: database cursor
1006 :param uid: current user id
1007 :param fields: list of fields
1008 :param data: data to import
1009 :param mode: 'init' or 'update' for record creation
1010 :param current_module: module name
1011 :param noupdate: flag for record creation
1012 :param context: context arguments, like lang, time zone,
1013 :param filename: optional file to store partial import state for recovery
1016 This method is used when importing data via client menu.
1018 Example of fields to import for a sale.order::
1021 partner_id, (=name_search)
1022 order_line/.id, (=database_id)
1024 order_line/product_id/id, (=xml id)
1025 order_line/price_unit,
1026 order_line/product_uom_qty,
1027 order_line/product_uom/id (=xml_id)
1031 def _replace_field(x):
1032 x = re.sub('([a-z0-9A-Z_])\\.id$', '\\1/.id', x)
1033 return x.replace(':id','/id').split('/')
1034 fields = map(_replace_field, fields)
1035 logger = netsvc.Logger()
1036 ir_model_data_obj = self.pool.get('ir.model.data')
1038 # mode: id (XML id) or .id (database id) or False for name_get
1039 def _get_id(model_name, id, current_module=False, mode='id'):
1042 obj_model = self.pool.get(model_name)
1043 ids = obj_model.search(cr, uid, [('id', '=', int(id))])
1045 raise Exception(_("Database ID doesn't exist: %s : %s") %(model_name, id))
1048 module, xml_id = id.rsplit('.', 1)
1050 module, xml_id = current_module, id
1051 record_id = ir_model_data_obj._get_id(cr, uid, module, xml_id)
1052 ir_model_data = ir_model_data_obj.read(cr, uid, [record_id], ['res_id'])
1053 if not ir_model_data:
1054 raise ValueError('No references to %s.%s' % (module, xml_id))
1055 id = ir_model_data[0]['res_id']
1057 obj_model = self.pool.get(model_name)
1058 ids = obj_model.name_search(cr, uid, id, operator='=', context=context)
1060 raise ValueError('No record found for %s' % (id,))
1065 # datas: a list of records, each record is defined by a list of values
1066 # prefix: a list of prefix fields ['line_ids']
1067 # position: the line to process, skip is False if it's the first line of the current record
1069 # (res, position, warning, res_id) with
1070 # res: the record for the next line to process (including it's one2many)
1071 # position: the new position for the next line
1072 # res_id: the ID of the record if it's a modification
1073 def process_liness(self, datas, prefix, current_module, model_name, fields_def, position=0, skip=0):
1074 line = datas[position]
1082 for i in range(len(fields)):
1085 raise Exception(_('Please check that all your lines have %d columns.'
1086 'Stopped around line %d having %d columns.') % \
1087 (len(fields), position+2, len(line)))
1092 if field[:len(prefix)] <> prefix:
1093 if line[i] and skip:
1097 #set the mode for m2o, o2m, m2m : xml_id/id/name
1098 if len(field) == len(prefix)+1:
1101 mode = field[len(prefix)+1]
1103 # TODO: improve this by using csv.csv_reader
1104 def many_ids(line, relation, current_module, mode):
1106 for db_id in line.split(config.get('csv_internal_sep')):
1107 res.append(_get_id(relation, db_id, current_module, mode))
1110 # ID of the record using a XML ID
1111 if field[len(prefix)]=='id':
1113 data_res_id = _get_id(model_name, line[i], current_module, 'id')
1119 # ID of the record using a database ID
1120 elif field[len(prefix)]=='.id':
1121 data_res_id = _get_id(model_name, line[i], current_module, '.id')
1124 # recursive call for getting children and returning [(0,0,{})] or [(1,ID,{})]
1125 if fields_def[field[len(prefix)]]['type']=='one2many':
1126 if field[len(prefix)] in done:
1128 done[field[len(prefix)]] = True
1129 relation = fields_def[field[len(prefix)]]['relation']
1130 relation_obj = self.pool.get(relation)
1131 newfd = relation_obj.fields_get( cr, uid, context=context )
1134 res = many_ids(line[i], relation, current_module, mode)
1137 while pos < len(datas):
1138 res2 = process_liness(self, datas, prefix + [field[len(prefix)]], current_module, relation_obj._name, newfd, pos, first)
1141 (newrow, pos, w2, data_res_id2, xml_id2) = res2
1142 nbrmax = max(nbrmax, pos)
1147 res.append((4, data_res_id2))
1149 if (not newrow) or not reduce(lambda x, y: x or y, newrow.values(), 0):
1152 res.append( (data_res_id2 and 1 or 0, data_res_id2 or 0, newrow) )
1155 elif fields_def[field[len(prefix)]]['type']=='many2one':
1156 relation = fields_def[field[len(prefix)]]['relation']
1157 res = _get_id(relation, line[i], current_module, mode)
1159 elif fields_def[field[len(prefix)]]['type']=='many2many':
1160 relation = fields_def[field[len(prefix)]]['relation']
1161 res = many_ids(line[i], relation, current_module, mode)
1163 elif fields_def[field[len(prefix)]]['type'] == 'integer':
1164 res = line[i] and int(line[i]) or 0
1165 elif fields_def[field[len(prefix)]]['type'] == 'boolean':
1166 res = line[i].lower() not in ('0', 'false', 'off')
1167 elif fields_def[field[len(prefix)]]['type'] == 'float':
1168 res = line[i] and float(line[i]) or 0.0
1169 elif fields_def[field[len(prefix)]]['type'] == 'selection':
1170 for key, val in fields_def[field[len(prefix)]]['selection']:
1171 if tools.ustr(line[i]) in [tools.ustr(key), tools.ustr(val)]:
1174 if line[i] and not res:
1175 logger.notifyChannel("import", netsvc.LOG_WARNING,
1176 _("key '%s' not found in selection field '%s'") % \
1177 (tools.ustr(line[i]), tools.ustr(field[len(prefix)])))
1178 warning += [_("Key/value '%s' not found in selection field '%s'") % (tools.ustr(line[i]), tools.ustr(field[len(prefix)]))]
1183 row[field[len(prefix)]] = res or False
1185 result = (row, nbrmax, warning, data_res_id, xml_id)
1188 fields_def = self.fields_get(cr, uid, context=context)
1190 if config.get('import_partial', False) and filename:
1191 data = pickle.load(file(config.get('import_partial')))
1194 while position<len(datas):
1197 (res, position, warning, res_id, xml_id) = \
1198 process_liness(self, datas, [], current_module, self._name, fields_def, position=position)
1201 return (-1, res, 'Line ' + str(position) +' : ' + '!\n'.join(warning), '')
1204 ir_model_data_obj._update(cr, uid, self._name,
1205 current_module, res, mode=mode, xml_id=xml_id,
1206 noupdate=noupdate, res_id=res_id, context=context)
1207 except Exception, e:
1208 return (-1, res, 'Line ' + str(position) +' : ' + str(e), '')
1210 if config.get('import_partial', False) and filename and (not (position%100)):
1211 data = pickle.load(file(config.get('import_partial')))
1212 data[filename] = position
1213 pickle.dump(data, file(config.get('import_partial'), 'wb'))
1214 if context.get('defer_parent_store_computation'):
1215 self._parent_store_compute(cr)
1218 if context.get('defer_parent_store_computation'):
1219 self._parent_store_compute(cr)
1220 return (position, 0, 0, 0)
1222 def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
1224 Read records with given ids with the given fields
1226 :param cr: database cursor
1227 :param user: current user id
1228 :param ids: id or list of the ids of the records to read
1229 :param fields: optional list of field names to return (default: all fields would be returned)
1230 :type fields: list (example ['field_name_1', ...])
1231 :param context: optional context dictionary - it may contains keys for specifying certain options
1232 like ``context_lang``, ``context_tz`` to alter the results of the call.
1233 A special ``bin_size`` boolean flag may also be passed in the context to request the
1234 value of all fields.binary columns to be returned as the size of the binary instead of its
1235 contents. This can also be selectively overriden by passing a field-specific flag
1236 in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field.
1237 Note: The ``bin_size_XXX`` form is new in OpenERP v6.0.
1238 :return: list of dictionaries((dictionary per record asked)) with requested field values
1239 :rtype: [{‘name_of_the_field’: value, ...}, ...]
1240 :raise AccessError: * if user has no read rights on the requested object
1241 * if user tries to bypass access rules for read on the requested object
1244 raise NotImplementedError(_('The read method is not implemented on this object !'))
1246 def get_invalid_fields(self, cr, uid):
1247 return list(self._invalids)
1249 def _validate(self, cr, uid, ids, context=None):
1250 context = context or {}
1251 lng = context.get('lang', False) or 'en_US'
1252 trans = self.pool.get('ir.translation')
1254 for constraint in self._constraints:
1255 fun, msg, fields = constraint
1256 if not fun(self, cr, uid, ids):
1257 # Check presence of __call__ directly instead of using
1258 # callable() because it will be deprecated as of Python 3.0
1259 if hasattr(msg, '__call__'):
1260 tmp_msg = msg(self, cr, uid, ids, context=context)
1261 if isinstance(tmp_msg, tuple):
1262 tmp_msg, params = tmp_msg
1263 translated_msg = tmp_msg % params
1265 translated_msg = tmp_msg
1267 translated_msg = trans._get_source(cr, uid, self._name, 'constraint', lng, source=msg) or msg
1269 _("Error occurred while validating the field(s) %s: %s") % (','.join(fields), translated_msg)
1271 self._invalids.update(fields)
1274 raise except_orm('ValidateError', '\n'.join(error_msgs))
1276 self._invalids.clear()
1278 def default_get(self, cr, uid, fields_list, context=None):
1280 Returns default values for the fields in fields_list.
1282 :param fields_list: list of fields to get the default values for (example ['field1', 'field2',])
1283 :type fields_list: list
1284 :param context: optional context dictionary - it may contains keys for specifying certain options
1285 like ``context_lang`` (language) or ``context_tz`` (timezone) to alter the results of the call.
1286 It may contain keys in the form ``default_XXX`` (where XXX is a field name), to set
1287 or override a default value for a field.
1288 A special ``bin_size`` boolean flag may also be passed in the context to request the
1289 value of all fields.binary columns to be returned as the size of the binary instead of its
1290 contents. This can also be selectively overriden by passing a field-specific flag
1291 in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field.
1292 Note: The ``bin_size_XXX`` form is new in OpenERP v6.0.
1293 :return: dictionary of the default values (set on the object model class, through user preferences, or in the context)
1295 # trigger view init hook
1296 self.view_init(cr, uid, fields_list, context)
1302 # get the default values for the inherited fields
1303 for t in self._inherits.keys():
1304 defaults.update(self.pool.get(t).default_get(cr, uid, fields_list,
1307 # get the default values defined in the object
1308 for f in fields_list:
1309 if f in self._defaults:
1310 if callable(self._defaults[f]):
1311 defaults[f] = self._defaults[f](self, cr, uid, context)
1313 defaults[f] = self._defaults[f]
1315 fld_def = ((f in self._columns) and self._columns[f]) \
1316 or ((f in self._inherit_fields) and self._inherit_fields[f][2]) \
1319 if isinstance(fld_def, fields.property):
1320 property_obj = self.pool.get('ir.property')
1321 prop_value = property_obj.get(cr, uid, f, self._name, context=context)
1323 if isinstance(prop_value, (browse_record, browse_null)):
1324 defaults[f] = prop_value.id
1326 defaults[f] = prop_value
1328 if f not in defaults:
1331 # get the default values set by the user and override the default
1332 # values defined in the object
1333 ir_values_obj = self.pool.get('ir.values')
1334 res = ir_values_obj.get(cr, uid, 'default', False, [self._name])
1335 for id, field, field_value in res:
1336 if field in fields_list:
1337 fld_def = (field in self._columns) and self._columns[field] or self._inherit_fields[field][2]
1338 if fld_def._type in ('many2one', 'one2one'):
1339 obj = self.pool.get(fld_def._obj)
1340 if not obj.search(cr, uid, [('id', '=', field_value or False)]):
1342 if fld_def._type in ('many2many'):
1343 obj = self.pool.get(fld_def._obj)
1345 for i in range(len(field_value)):
1346 if not obj.search(cr, uid, [('id', '=',
1349 field_value2.append(field_value[i])
1350 field_value = field_value2
1351 if fld_def._type in ('one2many'):
1352 obj = self.pool.get(fld_def._obj)
1354 for i in range(len(field_value)):
1355 field_value2.append({})
1356 for field2 in field_value[i]:
1357 if field2 in obj._columns.keys() and obj._columns[field2]._type in ('many2one', 'one2one'):
1358 obj2 = self.pool.get(obj._columns[field2]._obj)
1359 if not obj2.search(cr, uid,
1360 [('id', '=', field_value[i][field2])]):
1362 elif field2 in obj._inherit_fields.keys() and obj._inherit_fields[field2][2]._type in ('many2one', 'one2one'):
1363 obj2 = self.pool.get(obj._inherit_fields[field2][2]._obj)
1364 if not obj2.search(cr, uid,
1365 [('id', '=', field_value[i][field2])]):
1367 # TODO add test for many2many and one2many
1368 field_value2[i][field2] = field_value[i][field2]
1369 field_value = field_value2
1370 defaults[field] = field_value
1372 # get the default values from the context
1373 for key in context or {}:
1374 if key.startswith('default_') and (key[8:] in fields_list):
1375 defaults[key[8:]] = context[key]
1379 def perm_read(self, cr, user, ids, context=None, details=True):
1380 raise NotImplementedError(_('The perm_read method is not implemented on this object !'))
1382 def unlink(self, cr, uid, ids, context=None):
1383 raise NotImplementedError(_('The unlink method is not implemented on this object !'))
1385 def write(self, cr, user, ids, vals, context=None):
1386 raise NotImplementedError(_('The write method is not implemented on this object !'))
1388 def create(self, cr, user, vals, context=None):
1389 raise NotImplementedError(_('The create method is not implemented on this object !'))
1391 def fields_get_keys(self, cr, user, context=None):
1392 res = self._columns.keys()
1393 # TODO I believe this loop can be replace by
1394 # res.extend(self._inherit_fields.key())
1395 for parent in self._inherits:
1396 res.extend(self.pool.get(parent).fields_get_keys(cr, user, context))
1400 def fields_get(self, cr, user, allfields=None, context=None, write_access=True):
1401 """ Return the definition of each field.
1403 The returned value is a dictionary (indiced by field name) of
1404 dictionaries. The _inherits'd fields are included. The string,
1405 help, and selection (if present) attributes are translated.
1413 translation_obj = self.pool.get('ir.translation')
1414 for parent in self._inherits:
1415 res.update(self.pool.get(parent).fields_get(cr, user, allfields, context))
1417 for f, field in self._columns.iteritems():
1418 if allfields and f not in allfields:
1421 res[f] = fields.field_to_dict(self, cr, user, context, field)
1423 if not write_access:
1424 res[f]['readonly'] = True
1425 res[f]['states'] = {}
1427 if 'string' in res[f]:
1428 res_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'field', context.get('lang', False) or 'en_US')
1430 res[f]['string'] = res_trans
1431 if 'help' in res[f]:
1432 help_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'help', context.get('lang', False) or 'en_US')
1434 res[f]['help'] = help_trans
1435 if 'selection' in res[f]:
1436 if isinstance(field.selection, (tuple, list)):
1437 sel = field.selection
1439 for key, val in sel:
1442 val2 = translation_obj._get_source(cr, user, self._name + ',' + f, 'selection', context.get('lang', False) or 'en_US', val)
1443 sel2.append((key, val2 or val))
1444 res[f]['selection'] = sel2
1450 # Overload this method if you need a window title which depends on the context
1452 def view_header_get(self, cr, user, view_id=None, view_type='form', context=None):
1455 def __view_look_dom(self, cr, user, node, view_id, in_tree_view, model_fields, context=None):
1456 """ Return the description of the fields in the node.
1458 In a normal call to this method, node is a complete view architecture
1459 but it is actually possible to give some sub-node (this is used so
1460 that the method can call itself recursively).
1462 Originally, the field descriptions are drawn from the node itself.
1463 But there is now some code calling fields_get() in order to merge some
1464 of those information in the architecture.
1476 if isinstance(s, unicode):
1477 return s.encode('utf8')
1480 def check_group(node):
1481 """ Set invisible to true if the user is not in the specified groups. """
1482 if node.get('groups'):
1483 groups = node.get('groups').split(',')
1484 access_pool = self.pool.get('ir.model.access')
1485 can_see = any(access_pool.check_groups(cr, user, group) for group in groups)
1487 node.set('invisible', '1')
1488 modifiers['invisible'] = True
1489 if 'attrs' in node.attrib:
1490 del(node.attrib['attrs']) #avoid making field visible later
1491 del(node.attrib['groups'])
1493 if node.tag in ('field', 'node', 'arrow'):
1494 if node.get('object'):
1499 if f.tag in ('field'):
1500 xml += etree.tostring(f, encoding="utf-8")
1502 new_xml = etree.fromstring(encode(xml))
1503 ctx = context.copy()
1504 ctx['base_model_name'] = self._name
1505 xarch, xfields = self.pool.get(node.get('object')).__view_look_dom_arch(cr, user, new_xml, view_id, ctx)
1510 attrs = {'views': views}
1512 if node.get('name'):
1515 if node.get('name') in self._columns:
1516 column = self._columns[node.get('name')]
1518 column = self._inherit_fields[node.get('name')][2]
1523 relation = self.pool.get(column._obj)
1528 if f.tag in ('form', 'tree', 'graph'):
1530 ctx = context.copy()
1531 ctx['base_model_name'] = self._name
1532 xarch, xfields = relation.__view_look_dom_arch(cr, user, f, view_id, ctx)
1533 views[str(f.tag)] = {
1537 attrs = {'views': views}
1538 if node.get('widget') and node.get('widget') == 'selection':
1539 # Prepare the cached selection list for the client. This needs to be
1540 # done even when the field is invisible to the current user, because
1541 # other events could need to change its value to any of the selectable ones
1542 # (such as on_change events, refreshes, etc.)
1544 # If domain and context are strings, we keep them for client-side, otherwise
1545 # we evaluate them server-side to consider them when generating the list of
1547 # TODO: find a way to remove this hack, by allow dynamic domains
1549 if column._domain and not isinstance(column._domain, basestring):
1550 dom = column._domain
1551 dom += eval(node.get('domain', '[]'), {'uid': user, 'time': time})
1552 search_context = dict(context)
1553 if column._context and not isinstance(column._context, basestring):
1554 search_context.update(column._context)
1555 attrs['selection'] = relation._name_search(cr, user, '', dom, context=search_context, limit=None, name_get_uid=1)
1556 if (node.get('required') and not int(node.get('required'))) or not column.required:
1557 attrs['selection'].append((False, ''))
1558 fields[node.get('name')] = attrs
1560 field = model_fields.get(node.get('name'))
1562 transfer_field_to_modifiers(field, modifiers)
1565 elif node.tag in ('form', 'tree'):
1566 result = self.view_header_get(cr, user, False, node.tag, context)
1568 node.set('string', result)
1569 in_tree_view = node.tag == 'tree'
1571 elif node.tag == 'calendar':
1572 for additional_field in ('date_start', 'date_delay', 'date_stop', 'color'):
1573 if node.get(additional_field):
1574 fields[node.get(additional_field)] = {}
1578 # The view architeture overrides the python model.
1579 # Get the attrs before they are (possibly) deleted by check_group below
1580 transfer_node_to_modifiers(node, modifiers, context, in_tree_view)
1582 # TODO remove attrs couterpart in modifiers when invisible is true ?
1585 if 'lang' in context:
1586 if node.get('string') and not result:
1587 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('string'))
1588 if trans == node.get('string') and ('base_model_name' in context):
1589 # If translation is same as source, perhaps we'd have more luck with the alternative model name
1590 # (in case we are in a mixed situation, such as an inherited view where parent_view.model != model
1591 trans = self.pool.get('ir.translation')._get_source(cr, user, context['base_model_name'], 'view', context['lang'], node.get('string'))
1593 node.set('string', trans)
1594 if node.get('confirm'):
1595 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('confirm'))
1597 node.set('confirm', trans)
1599 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('sum'))
1601 node.set('sum', trans)
1602 if node.get('help'):
1603 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('help'))
1605 node.set('help', trans)
1608 if children or (node.tag == 'field' and f.tag in ('filter','separator')):
1609 fields.update(self.__view_look_dom(cr, user, f, view_id, in_tree_view, model_fields, context))
1611 transfer_modifiers_to_node(modifiers, node)
1614 def _disable_workflow_buttons(self, cr, user, node):
1615 """ Set the buttons in node to readonly if the user can't activate them. """
1617 # admin user can always activate workflow buttons
1620 # TODO handle the case of more than one workflow for a model or multiple
1621 # transitions with different groups and same signal
1622 usersobj = self.pool.get('res.users')
1623 buttons = (n for n in node.getiterator('button') if n.get('type') != 'object')
1624 for button in buttons:
1625 user_groups = usersobj.read(cr, user, [user], ['groups_id'])[0]['groups_id']
1626 cr.execute("""SELECT DISTINCT t.group_id
1628 INNER JOIN wkf_activity a ON a.wkf_id = wkf.id
1629 INNER JOIN wkf_transition t ON (t.act_to = a.id)
1632 AND t.group_id is NOT NULL
1633 """, (self._name, button.get('name')))
1634 group_ids = [x[0] for x in cr.fetchall() if x[0]]
1635 can_click = not group_ids or bool(set(user_groups).intersection(group_ids))
1636 button.set('readonly', str(int(not can_click)))
1639 def __view_look_dom_arch(self, cr, user, node, view_id, context=None):
1640 """ Return an architecture and a description of all the fields.
1642 The field description combines the result of fields_get() and
1645 :param node: the architecture as as an etree
1646 :return: a tuple (arch, fields) where arch is the given node as a
1647 string and fields is the description of all the fields.
1651 if node.tag == 'diagram':
1652 if node.getchildren()[0].tag == 'node':
1653 node_fields = self.pool.get(node.getchildren()[0].get('object')).fields_get(cr, user, None, context)
1654 fields.update(node_fields)
1655 if node.getchildren()[1].tag == 'arrow':
1656 arrow_fields = self.pool.get(node.getchildren()[1].get('object')).fields_get(cr, user, None, context)
1657 fields.update(arrow_fields)
1659 fields = self.fields_get(cr, user, None, context)
1660 fields_def = self.__view_look_dom(cr, user, node, view_id, False, fields, context=context)
1661 node = self._disable_workflow_buttons(cr, user, node)
1662 arch = etree.tostring(node, encoding="utf-8").replace('\t', '')
1663 for k in fields.keys():
1664 if k not in fields_def:
1666 for field in fields_def:
1668 # sometime, the view may contain the (invisible) field 'id' needed for a domain (when 2 objects have cross references)
1669 fields['id'] = {'readonly': True, 'type': 'integer', 'string': 'ID'}
1670 elif field in fields:
1671 fields[field].update(fields_def[field])
1673 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))
1674 res = cr.fetchall()[:]
1676 res.insert(0, ("Can't find field '%s' in the following view parts composing the view of object model '%s':" % (field, model), None))
1677 msg = "\n * ".join([r[0] for r in res])
1678 msg += "\n\nEither you wrongly customized this view, or some modules bringing those views are not compatible with your current data model"
1679 netsvc.Logger().notifyChannel('orm', netsvc.LOG_ERROR, msg)
1680 raise except_orm('View error', msg)
1683 def __get_default_calendar_view(self):
1684 """Generate a default calendar view (For internal use only).
1686 # TODO could return an etree instead of a string
1688 arch = ('<?xml version="1.0" encoding="utf-8"?>\n'
1689 '<calendar string="%s"') % (self._description)
1691 if (self._date_name not in self._columns):
1693 for dt in ['date', 'date_start', 'x_date', 'x_date_start']:
1694 if dt in self._columns:
1695 self._date_name = dt
1700 raise except_orm(_('Invalid Object Architecture!'), _("Insufficient fields for Calendar View!"))
1703 arch += ' date_start="%s"' % (self._date_name)
1705 for color in ["user_id", "partner_id", "x_user_id", "x_partner_id"]:
1706 if color in self._columns:
1707 arch += ' color="' + color + '"'
1710 dt_stop_flag = False
1712 for dt_stop in ["date_stop", "date_end", "x_date_stop", "x_date_end"]:
1713 if dt_stop in self._columns:
1714 arch += ' date_stop="' + dt_stop + '"'
1718 if not dt_stop_flag:
1719 for dt_delay in ["date_delay", "planned_hours", "x_date_delay", "x_planned_hours"]:
1720 if dt_delay in self._columns:
1721 arch += ' date_delay="' + dt_delay + '"'
1725 ' <field name="%s"/>\n'
1726 '</calendar>') % (self._rec_name)
1730 def __get_default_search_view(self, cr, uid, context=None):
1731 form_view = self.fields_view_get(cr, uid, False, 'form', context=context)
1732 tree_view = self.fields_view_get(cr, uid, False, 'tree', context=context)
1734 fields_to_search = set()
1735 # TODO it seems _all_columns could be used instead of fields_get (no need for translated fields info)
1736 fields = self.fields_get(cr, uid, context=context)
1737 for field in fields:
1738 if fields[field].get('select'):
1739 fields_to_search.add(field)
1740 for view in (form_view, tree_view):
1741 view_root = etree.fromstring(view['arch'])
1742 # Only care about select=1 in xpath below, because select=2 is covered
1743 # by the custom advanced search in clients
1744 fields_to_search = fields_to_search.union(view_root.xpath("//field[@select=1]/@name"))
1746 tree_view_root = view_root # as provided by loop above
1747 search_view = etree.Element("search", attrib={'string': tree_view_root.get("string", "")})
1748 field_group = etree.Element("group")
1749 search_view.append(field_group)
1751 for field_name in fields_to_search:
1752 field_group.append(etree.Element("field", attrib={'name': field_name}))
1754 #TODO tostring can be removed as fromstring is call directly after...
1755 return etree.tostring(search_view, encoding="utf-8").replace('\t', '')
1758 # if view_id, view_type is not required
1760 def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
1762 Get the detailed composition of the requested view like fields, model, view architecture
1764 :param cr: database cursor
1765 :param user: current user id
1766 :param view_id: id of the view or None
1767 :param view_type: type of the view to return if view_id is None ('form', tree', ...)
1768 :param context: context arguments, like lang, time zone
1769 :param toolbar: true to include contextual actions
1770 :param submenu: example (portal_project module)
1771 :return: dictionary describing the composition of the requested view (including inherited views and extensions)
1772 :raise AttributeError:
1773 * if the inherited view has unknown position to work with other than 'before', 'after', 'inside', 'replace'
1774 * if some tag other than 'position' is found in parent view
1775 :raise Invalid ArchitectureError: if there is view type other than form, tree, calendar, search etc defined on the structure
1782 if isinstance(s, unicode):
1783 return s.encode('utf8')
1786 def raise_view_error(error_msg, child_view_id):
1787 view, child_view = self.pool.get('ir.ui.view').browse(cr, user, [view_id, child_view_id], context)
1788 raise AttributeError("View definition error for inherited view '%s' on model '%s': %s"
1789 % (child_view.xml_id, self._name, error_msg))
1791 def locate(source, spec):
1792 """ Locate a node in a source (parent) architecture.
1794 Given a complete source (parent) architecture (i.e. the field
1795 `arch` in a view), and a 'spec' node (a node in an inheriting
1796 view that specifies the location in the source view of what
1797 should be changed), return (if it exists) the node in the
1798 source view matching the specification.
1800 :param source: a parent architecture to modify
1801 :param spec: a modifying node in an inheriting view
1802 :return: a node in the source matching the spec
1805 if spec.tag == 'xpath':
1806 nodes = source.xpath(spec.get('expr'))
1807 return nodes[0] if nodes else None
1808 elif spec.tag == 'field':
1809 # Only compare the field name: a field can be only once in a given view
1810 # at a given level (and for multilevel expressions, we should use xpath
1811 # inheritance spec anyway).
1812 for node in source.getiterator('field'):
1813 if node.get('name') == spec.get('name'):
1817 for node in source.getiterator(spec.tag):
1819 for attr in spec.attrib:
1820 if attr != 'position' and (not node.get(attr) or node.get(attr) != spec.get(attr)):
1827 def apply_inheritance_specs(source, specs_arch, inherit_id=None):
1828 """ Apply an inheriting view.
1830 Apply to a source architecture all the spec nodes (i.e. nodes
1831 describing where and what changes to apply to some parent
1832 architecture) given by an inheriting view.
1834 :param source: a parent architecture to modify
1835 :param specs_arch: a modifying architecture in an inheriting view
1836 :param inherit_id: the database id of the inheriting view
1837 :return: a modified source where the specs are applied
1840 specs_tree = etree.fromstring(encode(specs_arch))
1841 # Queue of specification nodes (i.e. nodes describing where and
1842 # changes to apply to some parent architecture).
1843 specs = [specs_tree]
1847 if isinstance(spec, SKIPPED_ELEMENT_TYPES):
1849 if spec.tag == 'data':
1850 specs += [ c for c in specs_tree ]
1852 node = locate(source, spec)
1853 if node is not None:
1854 pos = spec.get('position', 'inside')
1855 if pos == 'replace':
1856 if node.getparent() is None:
1857 source = copy.deepcopy(spec[0])
1860 node.addprevious(child)
1861 node.getparent().remove(node)
1862 elif pos == 'attributes':
1863 for child in spec.getiterator('attribute'):
1864 attribute = (child.get('name'), child.text and child.text.encode('utf8') or None)
1866 node.set(attribute[0], attribute[1])
1868 del(node.attrib[attribute[0]])
1870 sib = node.getnext()
1874 elif pos == 'after':
1879 sib.addprevious(child)
1880 elif pos == 'before':
1881 node.addprevious(child)
1883 raise_view_error("Invalid position value: '%s'" % pos, inherit_id)
1886 ' %s="%s"' % (attr, spec.get(attr))
1887 for attr in spec.attrib
1888 if attr != 'position'
1890 tag = "<%s%s>" % (spec.tag, attrs)
1891 raise_view_error("Element '%s' not found in parent view '%%(parent_xml_id)s'" % tag, inherit_id)
1894 def apply_view_inheritance(source, inherit_id):
1895 """ Apply all the (directly and indirectly) inheriting views.
1897 :param source: a parent architecture to modify (with parent
1898 modifications already applied)
1899 :param inherit_id: the database id of the parent view
1900 :return: a modified source where all the modifying architecture
1904 # get all views which inherit from (ie modify) this view
1905 cr.execute('select arch,id from ir_ui_view where inherit_id=%s and model=%s order by priority', (inherit_id, self._name))
1906 sql_inherit = cr.fetchall()
1907 for (inherit, id) in sql_inherit:
1908 source = apply_inheritance_specs(source, inherit, id)
1909 source = apply_view_inheritance(source, id)
1912 result = {'type': view_type, 'model': self._name}
1915 parent_view_model = None
1916 view_ref = context.get(view_type + '_view_ref')
1917 # Search for a root (i.e. without any parent) view.
1919 if view_ref and not view_id:
1921 module, view_ref = view_ref.split('.', 1)
1922 cr.execute("SELECT res_id FROM ir_model_data WHERE model='ir.ui.view' AND module=%s AND name=%s", (module, view_ref))
1923 view_ref_res = cr.fetchone()
1925 view_id = view_ref_res[0]
1928 cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model
1930 WHERE id=%s""", (view_id,))
1932 cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model
1934 WHERE model=%s AND type=%s AND inherit_id IS NULL
1935 ORDER BY priority""", (self._name, view_type))
1936 sql_res = cr.dictfetchone()
1941 view_id = sql_res['inherit_id'] or sql_res['id']
1942 parent_view_model = sql_res['model']
1943 if not sql_res['inherit_id']:
1946 # if a view was found
1948 result['type'] = sql_res['type']
1949 result['view_id'] = sql_res['id']
1951 source = etree.fromstring(encode(sql_res['arch']))
1952 result['arch'] = apply_view_inheritance(source, result['view_id'])
1954 result['name'] = sql_res['name']
1955 result['field_parent'] = sql_res['field_parent'] or False
1958 # otherwise, build some kind of default view
1959 if view_type == 'form':
1960 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
1961 res = self.fields_get(cr, user, context=context)
1962 xml = '<?xml version="1.0" encoding="utf-8"?> ' \
1963 '<form string="%s">' % (self._description,)
1965 if res[x]['type'] not in ('one2many', 'many2many'):
1966 xml += '<field name="%s"/>' % (x,)
1967 if res[x]['type'] == 'text':
1971 elif view_type == 'tree':
1972 _rec_name = self._rec_name
1973 if _rec_name not in self._columns:
1974 _rec_name = self._columns.keys()[0]
1975 xml = '<?xml version="1.0" encoding="utf-8"?>' \
1976 '<tree string="%s"><field name="%s"/></tree>' \
1977 % (self._description, _rec_name)
1979 elif view_type == 'calendar':
1980 xml = self.__get_default_calendar_view()
1982 elif view_type == 'search':
1983 xml = self.__get_default_search_view(cr, user, context)
1986 # what happens here, graph case?
1987 raise except_orm(_('Invalid Architecture!'), _("There is no view of type '%s' defined for the structure!") % view_type)
1988 result['arch'] = etree.fromstring(encode(xml))
1989 result['name'] = 'default'
1990 result['field_parent'] = False
1991 result['view_id'] = 0
1993 if parent_view_model != self._name:
1994 ctx = context.copy()
1995 ctx['base_model_name'] = parent_view_model
1998 xarch, xfields = self.__view_look_dom_arch(cr, user, result['arch'], view_id, context=ctx)
1999 result['arch'] = xarch
2000 result['fields'] = xfields
2003 if context and context.get('active_id', False):
2004 data_menu = self.pool.get('ir.ui.menu').browse(cr, user, context['active_id'], context).action
2006 act_id = data_menu.id
2008 data_action = self.pool.get('ir.actions.act_window').browse(cr, user, [act_id], context)[0]
2009 result['submenu'] = getattr(data_action, 'menus', False)
2013 for key in ('report_sxw_content', 'report_rml_content',
2014 'report_sxw', 'report_rml',
2015 'report_sxw_content_data', 'report_rml_content_data'):
2019 ir_values_obj = self.pool.get('ir.values')
2020 resprint = ir_values_obj.get(cr, user, 'action',
2021 'client_print_multi', [(self._name, False)], False,
2023 resaction = ir_values_obj.get(cr, user, 'action',
2024 'client_action_multi', [(self._name, False)], False,
2027 resrelate = ir_values_obj.get(cr, user, 'action',
2028 'client_action_relate', [(self._name, False)], False,
2030 resprint = map(clean, resprint)
2031 resaction = map(clean, resaction)
2032 resaction = filter(lambda x: not x.get('multi', False), resaction)
2033 resprint = filter(lambda x: not x.get('multi', False), resprint)
2034 resrelate = map(lambda x: x[2], resrelate)
2036 for x in resprint + resaction + resrelate:
2037 x['string'] = x['name']
2039 result['toolbar'] = {
2041 'action': resaction,
2046 _view_look_dom_arch = __view_look_dom_arch
2048 def search_count(self, cr, user, args, context=None):
2051 res = self.search(cr, user, args, context=context, count=True)
2052 if isinstance(res, list):
2056 def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
2058 Search for records based on a search domain.
2060 :param cr: database cursor
2061 :param user: current user id
2062 :param args: list of tuples specifying the search domain [('field_name', 'operator', value), ...]. Pass an empty list to match all records.
2063 :param offset: optional number of results to skip in the returned values (default: 0)
2064 :param limit: optional max number of records to return (default: **None**)
2065 :param order: optional columns to sort by (default: self._order=id )
2066 :param context: optional context arguments, like lang, time zone
2067 :type context: dictionary
2068 :param count: optional (default: **False**), if **True**, returns only the number of records matching the criteria, not their ids
2069 :return: id or list of ids of records matching the criteria
2070 :rtype: integer or list of integers
2071 :raise AccessError: * if user tries to bypass access rules for read on the requested object.
2073 **Expressing a search domain (args)**
2075 Each tuple in the search domain needs to have 3 elements, in the form: **('field_name', 'operator', value)**, where:
2077 * **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.
2078 * **operator** must be a string with a valid comparison operator from this list: ``=, !=, >, >=, <, <=, like, ilike, in, not in, child_of, parent_left, parent_right``
2079 The semantics of most of these operators are obvious.
2080 The ``child_of`` operator will look for records who are children or grand-children of a given record,
2081 according to the semantics of this model (i.e following the relationship field named by
2082 ``self._parent_name``, by default ``parent_id``.
2083 * **value** must be a valid value to compare with the values of **field_name**, depending on its type.
2085 Domain criteria can be combined using 3 logical operators than can be added between tuples: '**&**' (logical AND, default), '**|**' (logical OR), '**!**' (logical NOT).
2086 These are **prefix** operators and the arity of the '**&**' and '**|**' operator is 2, while the arity of the '**!**' is just 1.
2087 Be very careful about this when you combine them the first time.
2089 Here is an example of searching for Partners named *ABC* from Belgium and Germany whose language is not english ::
2091 [('name','=','ABC'),'!',('language.code','=','en_US'),'|',('country_id.code','=','be'),('country_id.code','=','de'))
2093 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::
2095 (name is 'ABC' AND (language is NOT english) AND (country is Belgium OR Germany))
2098 return self._search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count)
2100 def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
2102 Private implementation of search() method, allowing specifying the uid to use for the access right check.
2103 This is useful for example when filling in the selection list for a drop-down and avoiding access rights errors,
2104 by specifying ``access_rights_uid=1`` to bypass access rights check, but not ir.rules!
2106 :param access_rights_uid: optional user ID to use when checking access rights
2107 (not for ir.rules, this is only for ir.model.access)
2109 raise NotImplementedError(_('The search method is not implemented on this object !'))
2111 def name_get(self, cr, user, ids, context=None):
2114 :param cr: database cursor
2115 :param user: current user id
2117 :param ids: list of ids
2118 :param context: context arguments, like lang, time zone
2119 :type context: dictionary
2120 :return: tuples with the text representation of requested objects for to-many relationships
2127 if isinstance(ids, (int, long)):
2129 return [(r['id'], tools.ustr(r[self._rec_name])) for r in self.read(cr, user, ids,
2130 [self._rec_name], context, load='_classic_write')]
2132 def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
2134 Search for records and their display names according to a search domain.
2136 :param cr: database cursor
2137 :param user: current user id
2138 :param name: object name to search
2139 :param args: list of tuples specifying search criteria [('field_name', 'operator', 'value'), ...]
2140 :param operator: operator for search criterion
2141 :param context: context arguments, like lang, time zone
2142 :type context: dictionary
2143 :param limit: optional max number of records to return
2144 :return: list of object names matching the search criteria, used to provide completion for to-many relationships
2146 This method is equivalent of :py:meth:`~osv.osv.osv.search` on **name** + :py:meth:`~osv.osv.osv.name_get` on the result.
2147 See :py:meth:`~osv.osv.osv.search` for an explanation of the possible values for the search domain specified in **args**.
2150 return self._name_search(cr, user, name, args, operator, context, limit)
2152 def name_create(self, cr, uid, name, context=None):
2154 Creates a new record by calling :py:meth:`~osv.osv.osv.create` with only one
2155 value provided: the name of the new record (``_rec_name`` field).
2156 The new record will also be initialized with any default values applicable
2157 to this model, or provided through the context. The usual behavior of
2158 :py:meth:`~osv.osv.osv.create` applies.
2159 Similarly, this method may raise an exception if the model has multiple
2160 required fields and some do not have default values.
2162 :param name: name of the record to create
2164 :return: the :py:meth:`~osv.osv.osv.name_get` value for the newly-created record.
2166 rec_id = self.create(cr, uid, {self._rec_name: name}, context);
2167 return self.name_get(cr, uid, [rec_id], context)[0]
2169 # private implementation of name_search, allows passing a dedicated user for the name_get part to
2170 # solve some access rights issues
2171 def _name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100, name_get_uid=None):
2178 args += [(self._rec_name, operator, name)]
2179 access_rights_uid = name_get_uid or user
2180 ids = self._search(cr, user, args, limit=limit, context=context, access_rights_uid=access_rights_uid)
2181 res = self.name_get(cr, access_rights_uid, ids, context)
2184 def copy(self, cr, uid, id, default=None, context=None):
2185 raise NotImplementedError(_('The copy method is not implemented on this object !'))
2187 def exists(self, cr, uid, id, context=None):
2188 raise NotImplementedError(_('The exists method is not implemented on this object !'))
2190 def read_string(self, cr, uid, id, langs, fields=None, context=None):
2193 self.pool.get('ir.model.access').check(cr, uid, 'ir.translation', 'read', context=context)
2195 fields = self._columns.keys() + self._inherit_fields.keys()
2196 #FIXME: collect all calls to _get_source into one SQL call.
2198 res[lang] = {'code': lang}
2200 if f in self._columns:
2201 res_trans = self.pool.get('ir.translation')._get_source(cr, uid, self._name+','+f, 'field', lang)
2203 res[lang][f] = res_trans
2205 res[lang][f] = self._columns[f].string
2206 for table in self._inherits:
2207 cols = intersect(self._inherit_fields.keys(), fields)
2208 res2 = self.pool.get(table).read_string(cr, uid, id, langs, cols, context)
2211 res[lang]['code'] = lang
2212 for f in res2[lang]:
2213 res[lang][f] = res2[lang][f]
2216 def write_string(self, cr, uid, id, langs, vals, context=None):
2217 self.pool.get('ir.model.access').check(cr, uid, 'ir.translation', 'write', context=context)
2218 #FIXME: try to only call the translation in one SQL
2221 if field in self._columns:
2222 src = self._columns[field].string
2223 self.pool.get('ir.translation')._set_ids(cr, uid, self._name+','+field, 'field', lang, [0], vals[field], src)
2224 for table in self._inherits:
2225 cols = intersect(self._inherit_fields.keys(), vals)
2227 self.pool.get(table).write_string(cr, uid, id, langs, vals, context)
2230 def _check_removed_columns(self, cr, log=False):
2231 raise NotImplementedError()
2233 def _add_missing_default_values(self, cr, uid, values, context=None):
2234 missing_defaults = []
2235 avoid_tables = [] # avoid overriding inherited values when parent is set
2236 for tables, parent_field in self._inherits.items():
2237 if parent_field in values:
2238 avoid_tables.append(tables)
2239 for field in self._columns.keys():
2240 if not field in values:
2241 missing_defaults.append(field)
2242 for field in self._inherit_fields.keys():
2243 if (field not in values) and (self._inherit_fields[field][0] not in avoid_tables):
2244 missing_defaults.append(field)
2246 if len(missing_defaults):
2247 # override defaults with the provided values, never allow the other way around
2248 defaults = self.default_get(cr, uid, missing_defaults, context)
2250 if ((dv in self._columns and self._columns[dv]._type == 'many2many') \
2251 or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'many2many')) \
2252 and defaults[dv] and isinstance(defaults[dv][0], (int, long)):
2253 defaults[dv] = [(6, 0, defaults[dv])]
2254 if (dv in self._columns and self._columns[dv]._type == 'one2many' \
2255 or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'one2many')) \
2256 and isinstance(defaults[dv], (list, tuple)) and defaults[dv] and isinstance(defaults[dv][0], dict):
2257 defaults[dv] = [(0, 0, x) for x in defaults[dv]]
2258 defaults.update(values)
2262 class orm_memory(orm_template):
2264 _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']
2265 _inherit_fields = {}
2271 def createInstance(cls, pool, cr):
2272 return cls.makeInstance(pool, cr, ['_columns', '_defaults'])
2274 def __init__(self, pool, cr):
2275 super(orm_memory, self).__init__(pool, cr)
2279 self._max_count = config.get('osv_memory_count_limit')
2280 self._max_hours = config.get('osv_memory_age_limit')
2281 cr.execute('delete from wkf_instance where res_type=%s', (self._name,))
2283 def _check_access(self, uid, object_id, mode):
2284 if uid != 1 and self.datas[object_id]['internal.create_uid'] != uid:
2285 raise except_orm(_('AccessError'), '%s access is only allowed on your own records for osv_memory objects except for the super-user' % mode.capitalize())
2287 def vaccum(self, cr, uid, force=False):
2288 """Run the vaccuum cleaning system, expiring and removing old records from the
2289 virtual osv_memory tables if the "max count" or "max age" conditions are enabled
2290 and have been reached. This method can be called very often (e.g. everytime a record
2291 is created), but will only actually trigger the cleanup process once out of
2292 "_check_time" times (by default once out of 20 calls)."""
2294 if (not force) and (self.check_id % self._check_time):
2298 # Age-based expiration
2300 max = time.time() - self._max_hours * 60 * 60
2301 for k,v in self.datas.iteritems():
2302 if v['internal.date_access'] < max:
2304 self.unlink(cr, ROOT_USER_ID, tounlink)
2306 # Count-based expiration
2307 if self._max_count and len(self.datas) > self._max_count:
2308 # sort by access time to remove only the first/oldest ones in LRU fashion
2309 records = self.datas.items()
2310 records.sort(key=lambda x:x[1]['internal.date_access'])
2311 self.unlink(cr, ROOT_USER_ID, [x[0] for x in records[:len(self.datas)-self._max_count]])
2315 def read(self, cr, user, ids, fields_to_read=None, context=None, load='_classic_read'):
2318 if not fields_to_read:
2319 fields_to_read = self._columns.keys()
2323 if isinstance(ids, (int, long)):
2327 for f in fields_to_read:
2328 record = self.datas.get(id)
2330 self._check_access(user, id, 'read')
2331 r[f] = record.get(f, False)
2332 if r[f] and isinstance(self._columns[f], fields.binary) and context.get('bin_size', False):
2335 if id in self.datas:
2336 self.datas[id]['internal.date_access'] = time.time()
2337 fields_post = filter(lambda x: x in self._columns and not getattr(self._columns[x], load), fields_to_read)
2338 for f in fields_post:
2339 res2 = self._columns[f].get_memory(cr, self, ids, f, user, context=context, values=result)
2340 for record in result:
2341 record[f] = res2[record['id']]
2342 if isinstance(ids_orig, (int, long)):
2346 def write(self, cr, user, ids, vals, context=None):
2352 if self._columns[field]._classic_write:
2353 vals2[field] = vals[field]
2355 upd_todo.append(field)
2356 for object_id in ids:
2357 self._check_access(user, object_id, mode='write')
2358 self.datas[object_id].update(vals2)
2359 self.datas[object_id]['internal.date_access'] = time.time()
2360 for field in upd_todo:
2361 self._columns[field].set_memory(cr, self, object_id, field, vals[field], user, context)
2362 self._validate(cr, user, [object_id], context)
2363 wf_service = netsvc.LocalService("workflow")
2364 wf_service.trg_write(user, self._name, object_id, cr)
2367 def create(self, cr, user, vals, context=None):
2368 self.vaccum(cr, user)
2370 id_new = self.next_id
2372 vals = self._add_missing_default_values(cr, user, vals, context)
2377 if self._columns[field]._classic_write:
2378 vals2[field] = vals[field]
2380 upd_todo.append(field)
2381 self.datas[id_new] = vals2
2382 self.datas[id_new]['internal.date_access'] = time.time()
2383 self.datas[id_new]['internal.create_uid'] = user
2385 for field in upd_todo:
2386 self._columns[field].set_memory(cr, self, id_new, field, vals[field], user, context)
2387 self._validate(cr, user, [id_new], context)
2388 if self._log_create and not (context and context.get('no_store_function', False)):
2389 message = self._description + \
2391 self.name_get(cr, user, [id_new], context=context)[0][1] + \
2393 self.log(cr, user, id_new, message, True, context=context)
2394 wf_service = netsvc.LocalService("workflow")
2395 wf_service.trg_create(user, self._name, id_new, cr)
2398 def _where_calc(self, cr, user, args, active_test=True, context=None):
2403 # if the object has a field named 'active', filter out all inactive
2404 # records unless they were explicitely asked for
2405 if 'active' in self._columns and (active_test and context.get('active_test', True)):
2407 active_in_args = False
2409 if a[0] == 'active':
2410 active_in_args = True
2411 if not active_in_args:
2412 args.insert(0, ('active', '=', 1))
2414 args = [('active', '=', 1)]
2417 e = expression.expression(args)
2418 e.parse(cr, user, self, context)
2422 def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
2426 # implicit filter on current user except for superuser
2430 args.insert(0, ('internal.create_uid', '=', user))
2432 result = self._where_calc(cr, user, args, context=context)
2434 return self.datas.keys()
2438 #Find the value of dict
2441 for id, data in self.datas.items():
2442 counter = counter + 1
2444 if limit and (counter > int(limit)):
2449 val = eval('data[arg[0]]'+'==' +' arg[2]', locals())
2450 elif arg[1] in ['<', '>', 'in', 'not in', '<=', '>=', '<>']:
2451 val = eval('data[arg[0]]'+arg[1] +' arg[2]', locals())
2452 elif arg[1] in ['ilike']:
2453 val = (str(data[arg[0]]).find(str(arg[2]))!=-1)
2463 def unlink(self, cr, uid, ids, context=None):
2465 self._check_access(uid, id, 'unlink')
2466 self.datas.pop(id, None)
2468 cr.execute('delete from wkf_instance where res_type=%s and res_id IN %s', (self._name, tuple(ids)))
2471 def perm_read(self, cr, user, ids, context=None, details=True):
2473 credentials = self.pool.get('res.users').name_get(cr, user, [user])[0]
2474 create_date = time.strftime('%Y-%m-%d %H:%M:%S')
2476 self._check_access(user, id, 'read')
2478 'create_uid': credentials,
2479 'create_date': create_date,
2481 'write_date': False,
2487 def _check_removed_columns(self, cr, log=False):
2488 # nothing to check in memory...
2491 def exists(self, cr, uid, id, context=None):
2492 return id in self.datas
2494 class orm(orm_template):
2495 _sql_constraints = []
2497 _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']
2498 __logger = logging.getLogger('orm')
2499 __schema = logging.getLogger('orm.schema')
2500 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False):
2502 Get the list of records in list view grouped by the given ``groupby`` fields
2504 :param cr: database cursor
2505 :param uid: current user id
2506 :param domain: list specifying search criteria [['field_name', 'operator', 'value'], ...]
2507 :param list fields: list of fields present in the list view specified on the object
2508 :param list groupby: fields by which the records will be grouped
2509 :param int offset: optional number of records to skip
2510 :param int limit: optional max number of records to return
2511 :param dict context: context arguments, like lang, time zone
2512 :param list orderby: optional ``order by`` specification, for
2513 overriding the natural sort ordering of the
2514 groups, see also :py:meth:`~osv.osv.osv.search`
2515 (supported only for many2one fields currently)
2516 :return: list of dictionaries(one dictionary for each record) containing:
2518 * the values of fields grouped by the fields in ``groupby`` argument
2519 * __domain: list of tuples specifying the search criteria
2520 * __context: dictionary with argument like ``groupby``
2521 :rtype: [{'field_name_1': value, ...]
2522 :raise AccessError: * if user has no read rights on the requested object
2523 * if user tries to bypass access rules for read on the requested object
2526 context = context or {}
2527 self.pool.get('ir.model.access').check(cr, uid, self._name, 'read', context=context)
2529 fields = self._columns.keys()
2531 query = self._where_calc(cr, uid, domain, context=context)
2532 self._apply_ir_rules(cr, uid, query, 'read', context=context)
2534 # Take care of adding join(s) if groupby is an '_inherits'ed field
2535 groupby_list = groupby
2536 qualified_groupby_field = groupby
2538 if isinstance(groupby, list):
2539 groupby = groupby[0]
2540 qualified_groupby_field = self._inherits_join_calc(groupby, query)
2543 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?)"
2544 groupby_def = self._columns.get(groupby) or (self._inherit_fields.get(groupby) and self._inherit_fields.get(groupby)[2])
2545 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"
2547 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
2548 fget = self.fields_get(cr, uid, fields)
2549 float_int_fields = filter(lambda x: fget[x]['type'] in ('float', 'integer'), fields)
2551 group_count = group_by = groupby
2553 if fget.get(groupby):
2554 if fget[groupby]['type'] in ('date', 'datetime'):
2555 flist = "to_char(%s,'yyyy-mm') as %s " % (qualified_groupby_field, groupby)
2556 groupby = "to_char(%s,'yyyy-mm')" % (qualified_groupby_field)
2557 qualified_groupby_field = groupby
2559 flist = qualified_groupby_field
2561 # Don't allow arbitrary values, as this would be a SQL injection vector!
2562 raise except_orm(_('Invalid group_by'),
2563 _('Invalid group_by specification: "%s".\nA group_by specification must be a list of valid fields.')%(groupby,))
2566 fields_pre = [f for f in float_int_fields if
2567 f == self.CONCURRENCY_CHECK_FIELD
2568 or (f in self._columns and getattr(self._columns[f], '_classic_write'))]
2569 for f in fields_pre:
2570 if f not in ['id', 'sequence']:
2571 group_operator = fget[f].get('group_operator', 'sum')
2574 qualified_field = '"%s"."%s"' % (self._table, f)
2575 flist += "%s(%s) AS %s" % (group_operator, qualified_field, f)
2577 gb = groupby and (' GROUP BY ' + qualified_groupby_field) or ''
2579 from_clause, where_clause, where_clause_params = query.get_sql()
2580 where_clause = where_clause and ' WHERE ' + where_clause
2581 limit_str = limit and ' limit %d' % limit or ''
2582 offset_str = offset and ' offset %d' % offset or ''
2583 if len(groupby_list) < 2 and context.get('group_by_no_leaf'):
2585 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)
2588 for r in cr.dictfetchall():
2589 for fld, val in r.items():
2590 if val == None: r[fld] = False
2591 alldata[r['id']] = r
2594 data_ids = self.search(cr, uid, [('id', 'in', alldata.keys())], order=orderby or groupby, context=context)
2595 # the IDS of records that have groupby field value = False or '' should be sorted too
2596 data_ids += filter(lambda x:x not in data_ids, alldata.keys())
2597 data = self.read(cr, uid, data_ids, groupby and [groupby] or ['id'], context=context)
2598 # 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):
2599 data.sort(lambda x,y: cmp(data_ids.index(x['id']), data_ids.index(y['id'])))
2603 d['__domain'] = [(groupby, '=', alldata[d['id']][groupby] or False)] + domain
2604 if not isinstance(groupby_list, (str, unicode)):
2605 if groupby or not context.get('group_by_no_leaf', False):
2606 d['__context'] = {'group_by': groupby_list[1:]}
2607 if groupby and groupby in fget:
2608 if d[groupby] and fget[groupby]['type'] in ('date', 'datetime'):
2609 dt = datetime.datetime.strptime(alldata[d['id']][groupby][:7], '%Y-%m')
2610 days = calendar.monthrange(dt.year, dt.month)[1]
2612 d[groupby] = datetime.datetime.strptime(d[groupby][:10], '%Y-%m-%d').strftime('%B %Y')
2613 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),\
2614 (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
2615 del alldata[d['id']][groupby]
2616 d.update(alldata[d['id']])
2620 def _inherits_join_add(self, parent_model_name, query):
2622 Add missing table SELECT and JOIN clause to ``query`` for reaching the parent table (no duplicates)
2624 :param parent_model_name: name of the parent model for which the clauses should be added
2625 :param query: query object on which the JOIN should be added
2627 inherits_field = self._inherits[parent_model_name]
2628 parent_model = self.pool.get(parent_model_name)
2629 parent_table_name = parent_model._table
2630 quoted_parent_table_name = '"%s"' % parent_table_name
2631 if quoted_parent_table_name not in query.tables:
2632 query.tables.append(quoted_parent_table_name)
2633 query.where_clause.append('("%s".%s = %s.id)' % (self._table, inherits_field, parent_table_name))
2635 def _inherits_join_calc(self, field, query):
2637 Adds missing table select and join clause(s) to ``query`` for reaching
2638 the field coming from an '_inherits' parent table (no duplicates).
2640 :param field: name of inherited field to reach
2641 :param query: query object on which the JOIN should be added
2642 :return: qualified name of field, to be used in SELECT clause
2644 current_table = self
2645 while field in current_table._inherit_fields and not field in current_table._columns:
2646 parent_model_name = current_table._inherit_fields[field][0]
2647 parent_table = self.pool.get(parent_model_name)
2648 self._inherits_join_add(parent_model_name, query)
2649 current_table = parent_table
2650 return '"%s".%s' % (current_table._table, field)
2652 def _parent_store_compute(self, cr):
2653 if not self._parent_store:
2655 logger = netsvc.Logger()
2656 logger.notifyChannel('data', netsvc.LOG_INFO, 'Computing parent left and right for table %s...' % (self._table, ))
2657 def browse_rec(root, pos=0):
2659 where = self._parent_name+'='+str(root)
2661 where = self._parent_name+' IS NULL'
2662 if self._parent_order:
2663 where += ' order by '+self._parent_order
2664 cr.execute('SELECT id FROM '+self._table+' WHERE '+where)
2666 for id in cr.fetchall():
2667 pos2 = browse_rec(id[0], pos2)
2668 cr.execute('update '+self._table+' set parent_left=%s, parent_right=%s where id=%s', (pos, pos2, root))
2670 query = 'SELECT id FROM '+self._table+' WHERE '+self._parent_name+' IS NULL'
2671 if self._parent_order:
2672 query += ' order by ' + self._parent_order
2675 for (root,) in cr.fetchall():
2676 pos = browse_rec(root, pos)
2679 def _update_store(self, cr, f, k):
2680 logger = netsvc.Logger()
2681 logger.notifyChannel('data', netsvc.LOG_INFO, "storing computed values of fields.function '%s'" % (k,))
2682 ss = self._columns[k]._symbol_set
2683 update_query = 'UPDATE "%s" SET "%s"=%s WHERE id=%%s' % (self._table, k, ss[0])
2684 cr.execute('select id from '+self._table)
2685 ids_lst = map(lambda x: x[0], cr.fetchall())
2688 ids_lst = ids_lst[40:]
2689 res = f.get(cr, self, iids, k, ROOT_USER_ID, {})
2690 for key, val in res.items():
2693 # if val is a many2one, just write the ID
2694 if type(val) == tuple:
2696 if (val<>False) or (type(val)<>bool):
2697 cr.execute(update_query, (ss[1](val), key))
2699 def _check_selection_field_value(self, cr, uid, field, value, context=None):
2700 """Raise except_orm if value is not among the valid values for the selection field"""
2701 if self._columns[field]._type == 'reference':
2702 val_model, val_id_str = value.split(',', 1)
2705 val_id = long(val_id_str)
2709 raise except_orm(_('ValidateError'),
2710 _('Invalid value for reference field "%s" (last part must be a non-zero integer): "%s"') % (field, value))
2714 if isinstance(self._columns[field].selection, (tuple, list)):
2715 if val in dict(self._columns[field].selection):
2717 elif val in dict(self._columns[field].selection(self, cr, uid, context=context)):
2719 raise except_orm(_('ValidateError'),
2720 _('The value "%s" for the field "%s" is not in the selection') % (value, field))
2722 def _check_removed_columns(self, cr, log=False):
2723 # iterate on the database columns to drop the NOT NULL constraints
2724 # of fields which were required but have been removed (or will be added by another module)
2725 columns = [c for c in self._columns if not (isinstance(self._columns[c], fields.function) and not self._columns[c].store)]
2726 columns += ('id', 'write_uid', 'write_date', 'create_uid', 'create_date') # openerp access columns
2727 cr.execute("SELECT a.attname, a.attnotnull"
2728 " FROM pg_class c, pg_attribute a"
2729 " WHERE c.relname=%s"
2730 " AND c.oid=a.attrelid"
2731 " AND a.attisdropped=%s"
2732 " AND pg_catalog.format_type(a.atttypid, a.atttypmod) NOT IN ('cid', 'tid', 'oid', 'xid')"
2733 " AND a.attname NOT IN %s", (self._table, False, tuple(columns))),
2735 for column in cr.dictfetchall():
2737 self.__logger.debug("column %s is in the table %s but not in the corresponding object %s",
2738 column['attname'], self._table, self._name)
2739 if column['attnotnull']:
2740 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, column['attname']))
2741 self.__schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
2742 self._table, column['attname'])
2744 def _auto_init(self, cr, context=None):
2747 Call _field_create and, unless _auto is False:
2749 - create the corresponding table in database for the model,
2750 - possibly add the parent columns in database,
2751 - possibly add the columns 'create_uid', 'create_date', 'write_uid',
2752 'write_date' in database if _log_access is True (the default),
2753 - report on database columns no more existing in _columns,
2754 - remove no more existing not null constraints,
2755 - alter existing database columns to match _columns,
2756 - create database tables to match _columns,
2757 - add database indices to match _columns,
2758 - save in self._foreign_keys a list a foreign keys to create (see
2762 self._foreign_keys = []
2763 raise_on_invalid_object_name(self._name)
2766 store_compute = False
2768 update_custom_fields = context.get('update_custom_fields', False)
2769 self._field_create(cr, context=context)
2770 create = not self._table_exist(cr)
2772 if getattr(self, '_auto', True):
2775 self._create_table(cr)
2778 if self._parent_store:
2779 if not self._parent_columns_exist(cr):
2780 self._create_parent_columns(cr)
2781 store_compute = True
2783 # Create the create_uid, create_date, write_uid, write_date, columns if desired.
2784 if self._log_access:
2785 self._add_log_columns(cr)
2787 self._check_removed_columns(cr, log=False)
2789 # iterate on the "object columns"
2790 column_data = self._select_column_data(cr)
2792 for k, f in self._columns.iteritems():
2793 if k in ('id', 'write_uid', 'write_date', 'create_uid', 'create_date'):
2795 # Don't update custom (also called manual) fields
2796 if f.manual and not update_custom_fields:
2799 if isinstance(f, fields.one2many):
2800 self._o2m_raise_on_missing_reference(cr, f)
2802 elif isinstance(f, fields.many2many):
2803 self._m2m_raise_or_create_relation(cr, f)
2806 res = column_data.get(k)
2808 # The field is not found as-is in database, try if it
2809 # exists with an old name.
2810 if not res and hasattr(f, 'oldname'):
2811 res = column_data.get(f.oldname)
2813 cr.execute('ALTER TABLE "%s" RENAME "%s" TO "%s"' % (self._table, f.oldname, k))
2815 column_data[k] = res
2816 self.__schema.debug("Table '%s': renamed column '%s' to '%s'",
2817 self._table, f.oldname, k)
2819 # The field already exists in database. Possibly
2820 # change its type, rename it, drop it or change its
2823 f_pg_type = res['typname']
2824 f_pg_size = res['size']
2825 f_pg_notnull = res['attnotnull']
2826 if isinstance(f, fields.function) and not f.store and\
2827 not getattr(f, 'nodrop', False):
2828 self.__logger.info('column %s (%s) in table %s removed: converted to a function !\n',
2829 k, f.string, self._table)
2830 cr.execute('ALTER TABLE "%s" DROP COLUMN "%s" CASCADE' % (self._table, k))
2832 self.__schema.debug("Table '%s': dropped column '%s' with cascade",
2836 f_obj_type = get_pg_type(f) and get_pg_type(f)[0]
2841 ('text', 'char', 'VARCHAR(%d)' % (f.size or 0,), '::VARCHAR(%d)'%(f.size or 0,)),
2842 ('varchar', 'text', 'TEXT', ''),
2843 ('int4', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
2844 ('date', 'datetime', 'TIMESTAMP', '::TIMESTAMP'),
2845 ('timestamp', 'date', 'date', '::date'),
2846 ('numeric', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
2847 ('float8', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
2849 if f_pg_type == 'varchar' and f._type == 'char' and f_pg_size < f.size:
2850 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
2851 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" VARCHAR(%d)' % (self._table, k, f.size))
2852 cr.execute('UPDATE "%s" SET "%s"=temp_change_size::VARCHAR(%d)' % (self._table, k, f.size))
2853 cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
2855 self.__schema.debug("Table '%s': column '%s' (type varchar) changed size from %s to %s",
2856 self._table, k, f_pg_size, f.size)
2858 if (f_pg_type==c[0]) and (f._type==c[1]):
2859 if f_pg_type != f_obj_type:
2861 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
2862 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, c[2]))
2863 cr.execute(('UPDATE "%s" SET "%s"=temp_change_size'+c[3]) % (self._table, k))
2864 cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
2866 self.__schema.debug("Table '%s': column '%s' changed type from %s to %s",
2867 self._table, k, c[0], c[1])
2870 if f_pg_type != f_obj_type:
2874 newname = k + '_moved' + str(i)
2875 cr.execute("SELECT count(1) FROM pg_class c,pg_attribute a " \
2876 "WHERE c.relname=%s " \
2877 "AND a.attname=%s " \
2878 "AND c.oid=a.attrelid ", (self._table, newname))
2879 if not cr.fetchone()[0]:
2883 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
2884 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO "%s"' % (self._table, k, newname))
2885 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
2886 cr.execute("COMMENT ON COLUMN %s.%s IS '%s'" % (self._table, k, f.string.replace("'", "''")))
2887 self.__schema.debug("Table '%s': column '%s' has changed type (DB=%s, def=%s), data moved to column %s !",
2888 self._table, k, f_pg_type, f._type, newname)
2890 # if the field is required and hasn't got a NOT NULL constraint
2891 if f.required and f_pg_notnull == 0:
2892 # set the field to the default value if any
2893 if k in self._defaults:
2894 if callable(self._defaults[k]):
2895 default = self._defaults[k](self, cr, ROOT_USER_ID, context)
2897 default = self._defaults[k]
2899 if (default is not None):
2900 ss = self._columns[k]._symbol_set
2901 query = 'UPDATE "%s" SET "%s"=%s WHERE "%s" is NULL' % (self._table, k, ss[0], k)
2902 cr.execute(query, (ss[1](default),))
2903 # add the NOT NULL constraint
2906 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False)
2908 self.__schema.debug("Table '%s': column '%s': added NOT NULL constraint",
2911 msg = "Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\
2912 "If you want to have it, you should update the records and execute manually:\n"\
2913 "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
2914 self.__schema.warn(msg, self._table, k, self._table, k)
2916 elif not f.required and f_pg_notnull == 1:
2917 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
2919 self.__schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
2922 indexname = '%s_%s_index' % (self._table, k)
2923 cr.execute("SELECT indexname FROM pg_indexes WHERE indexname = %s and tablename = %s", (indexname, self._table))
2924 res2 = cr.dictfetchall()
2925 if not res2 and f.select:
2926 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
2928 if f._type == 'text':
2929 # FIXME: for fields.text columns we should try creating GIN indexes instead (seems most suitable for an ERP context)
2930 msg = "Table '%s': Adding (b-tree) index for text column '%s'."\
2931 "This is probably useless (does not work for fulltext search) and prevents INSERTs of long texts"\
2932 " because there is a length limit for indexable btree values!\n"\
2933 "Use a search view instead if you simply want to make the field searchable."
2934 self.__schema.warn(msg, self._table, k, f._type)
2935 if res2 and not f.select:
2936 cr.execute('DROP INDEX "%s_%s_index"' % (self._table, k))
2938 msg = "Table '%s': dropping index for column '%s' of type '%s' as it is not required anymore"
2939 self.__schema.debug(msg, self._table, k, f._type)
2941 if isinstance(f, fields.many2one):
2942 ref = self.pool.get(f._obj)._table
2943 if ref != 'ir_actions':
2944 cr.execute('SELECT confdeltype, conname FROM pg_constraint as con, pg_class as cl1, pg_class as cl2, '
2945 'pg_attribute as att1, pg_attribute as att2 '
2946 'WHERE con.conrelid = cl1.oid '
2947 'AND cl1.relname = %s '
2948 'AND con.confrelid = cl2.oid '
2949 'AND cl2.relname = %s '
2950 'AND array_lower(con.conkey, 1) = 1 '
2951 'AND con.conkey[1] = att1.attnum '
2952 'AND att1.attrelid = cl1.oid '
2953 'AND att1.attname = %s '
2954 'AND array_lower(con.confkey, 1) = 1 '
2955 'AND con.confkey[1] = att2.attnum '
2956 'AND att2.attrelid = cl2.oid '
2957 'AND att2.attname = %s '
2958 "AND con.contype = 'f'", (self._table, ref, k, 'id'))
2959 res2 = cr.dictfetchall()
2961 if res2[0]['confdeltype'] != POSTGRES_CONFDELTYPES.get(f.ondelete.upper(), 'a'):
2962 cr.execute('ALTER TABLE "' + self._table + '" DROP CONSTRAINT "' + res2[0]['conname'] + '"')
2963 self._foreign_keys.append((self._table, k, ref, f.ondelete))
2965 self.__schema.debug("Table '%s': column '%s': XXX",
2968 # The field doesn't exist in database. Create it if necessary.
2970 if not isinstance(f, fields.function) or f.store:
2971 # add the missing field
2972 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
2973 cr.execute("COMMENT ON COLUMN %s.%s IS '%s'" % (self._table, k, f.string.replace("'", "''")))
2974 self.__schema.debug("Table '%s': added column '%s' with definition=%s",
2975 self._table, k, get_pg_type(f)[1])
2978 if not create and k in self._defaults:
2979 if callable(self._defaults[k]):
2980 default = self._defaults[k](self, cr, ROOT_USER_ID, context)
2982 default = self._defaults[k]
2984 ss = self._columns[k]._symbol_set
2985 query = 'UPDATE "%s" SET "%s"=%s' % (self._table, k, ss[0])
2986 cr.execute(query, (ss[1](default),))
2988 netsvc.Logger().notifyChannel('data', netsvc.LOG_DEBUG, "Table '%s': setting default value of new column %s" % (self._table, k))
2990 # remember the functions to call for the stored fields
2991 if isinstance(f, fields.function):
2993 if f.store is not True: # i.e. if f.store is a dict
2994 order = f.store[f.store.keys()[0]][2]
2995 todo_end.append((order, self._update_store, (f, k)))
2997 # and add constraints if needed
2998 if isinstance(f, fields.many2one):
2999 if not self.pool.get(f._obj):
3000 raise except_orm('Programming Error', ('There is no reference available for %s') % (f._obj,))
3001 ref = self.pool.get(f._obj)._table
3002 # ir_actions is inherited so foreign key doesn't work on it
3003 if ref != 'ir_actions':
3004 self._foreign_keys.append((self._table, k, ref, f.ondelete))
3005 self.__schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s",
3006 self._table, k, ref, f.ondelete)
3008 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
3012 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False)
3013 self.__schema.debug("Table '%s': column '%s': added a NOT NULL constraint",
3016 msg = "WARNING: unable to set column %s of table %s not null !\n"\
3017 "Try to re-run: openerp-server --update=module\n"\
3018 "If it doesn't work, update records and execute manually:\n"\
3019 "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
3020 self.__logger.warn(msg, k, self._table, self._table, k)
3024 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
3025 create = not bool(cr.fetchone())
3027 cr.commit() # start a new transaction
3029 self._add_sql_constraints(cr)
3032 self._execute_sql(cr)
3035 self._parent_store_compute(cr)
3041 def _auto_end(self, cr, context=None):
3042 """ Create the foreign keys recorded by _auto_init. """
3043 for t, k, r, d in self._foreign_keys:
3044 cr.execute('ALTER TABLE "%s" ADD FOREIGN KEY ("%s") REFERENCES "%s" ON DELETE %s' % (t, k, r, d))
3046 del self._foreign_keys
3049 def _table_exist(self, cr):
3050 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
3054 def _create_table(self, cr):
3055 cr.execute('CREATE TABLE "%s" (id SERIAL NOT NULL, PRIMARY KEY(id)) WITHOUT OIDS' % (self._table,))
3056 cr.execute("COMMENT ON TABLE \"%s\" IS '%s'" % (self._table, self._description.replace("'", "''")))
3057 self.__schema.debug("Table '%s': created", self._table)
3060 def _parent_columns_exist(self, cr):
3061 cr.execute("""SELECT c.relname
3062 FROM pg_class c, pg_attribute a
3063 WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
3064 """, (self._table, 'parent_left'))
3068 def _create_parent_columns(self, cr):
3069 cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_left" INTEGER' % (self._table,))
3070 cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_right" INTEGER' % (self._table,))
3071 if 'parent_left' not in self._columns:
3072 self.__logger.error('create a column parent_left on object %s: fields.integer(\'Left Parent\', select=1)',
3074 self.__schema.debug("Table '%s': added column '%s' with definition=%s",
3075 self._table, 'parent_left', 'INTEGER')
3076 elif not self._columns['parent_left'].select:
3077 self.__logger.error('parent_left column on object %s must be indexed! Add select=1 to the field definition)',
3079 if 'parent_right' not in self._columns:
3080 self.__logger.error('create a column parent_right on object %s: fields.integer(\'Right Parent\', select=1)',
3082 self.__schema.debug("Table '%s': added column '%s' with definition=%s",
3083 self._table, 'parent_right', 'INTEGER')
3084 elif not self._columns['parent_right'].select:
3085 self.__logger.error('parent_right column on object %s must be indexed! Add select=1 to the field definition)',
3087 if self._columns[self._parent_name].ondelete != 'cascade':
3088 self.__logger.error("The column %s on object %s must be set as ondelete='cascade'",
3089 self._parent_name, self._name)
3094 def _add_log_columns(self, cr):
3096 'create_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
3097 'create_date': 'TIMESTAMP',
3098 'write_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
3099 'write_date': 'TIMESTAMP'
3104 FROM pg_class c, pg_attribute a
3105 WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
3106 """, (self._table, k))
3108 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, logs[k]))
3110 self.__schema.debug("Table '%s': added column '%s' with definition=%s",
3111 self._table, k, logs[k])
3114 def _select_column_data(self, cr):
3115 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 " \
3116 "FROM pg_class c,pg_attribute a,pg_type t " \
3117 "WHERE c.relname=%s " \
3118 "AND c.oid=a.attrelid " \
3119 "AND a.atttypid=t.oid", (self._table,))
3120 return dict(map(lambda x: (x['attname'], x),cr.dictfetchall()))
3123 def _o2m_raise_on_missing_reference(self, cr, f):
3124 # TODO this check should be a method on fields.one2many.
3125 other = self.pool.get(f._obj)
3127 # TODO the condition could use fields_get_keys().
3128 if f._fields_id not in other._columns.keys():
3129 if f._fields_id not in other._inherit_fields.keys():
3130 raise except_orm('Programming Error', ("There is no reference field '%s' found for '%s'") % (f._fields_id, f._obj,))
3133 def _m2m_raise_or_create_relation(self, cr, f):
3134 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (f._rel,))
3135 if not cr.dictfetchall():
3136 if not self.pool.get(f._obj):
3137 raise except_orm('Programming Error', ('There is no reference available for %s') % (f._obj,))
3138 ref = self.pool.get(f._obj)._table
3139 cr.execute('CREATE TABLE "%s" ("%s" INTEGER NOT NULL, "%s" INTEGER NOT NULL, UNIQUE("%s","%s")) WITH OIDS' % (f._rel, f._id1, f._id2, f._id1, f._id2))
3140 self._foreign_keys.append((f._rel, f._id1, self._table, 'CASCADE'))
3141 self._foreign_keys.append((f._rel, f._id2, ref, 'CASCADE'))
3142 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (f._rel, f._id1, f._rel, f._id1))
3143 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (f._rel, f._id2, f._rel, f._id2))
3144 cr.execute("COMMENT ON TABLE \"%s\" IS 'RELATION BETWEEN %s AND %s'" % (f._rel, self._table, ref))
3146 self.__schema.debug("Create table '%s': relation between '%s' and '%s'",
3147 f._rel, self._table, ref)
3150 def _add_sql_constraints(self, cr):
3153 Modify this model's database table constraints so they match the one in
3157 for (key, con, _) in self._sql_constraints:
3158 conname = '%s_%s' % (self._table, key)
3160 cr.execute("SELECT conname, pg_catalog.pg_get_constraintdef(oid, true) as condef FROM pg_constraint where conname=%s", (conname,))
3161 existing_constraints = cr.dictfetchall()
3166 'query': 'ALTER TABLE "%s" DROP CONSTRAINT "%s"' % (self._table, conname, ),
3167 'msg_ok': "Table '%s': dropped constraint '%s'. Reason: its definition changed from '%%s' to '%s'" % (
3168 self._table, conname, con),
3169 'msg_err': "Table '%s': unable to drop \'%s\' constraint !" % (self._table, con),
3174 'query': 'ALTER TABLE "%s" ADD CONSTRAINT "%s" %s' % (self._table, conname, con,),
3175 'msg_ok': "Table '%s': added constraint '%s' with definition=%s" % (self._table, conname, con),
3176 '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" % (
3182 if not existing_constraints:
3183 # constraint does not exists:
3184 sql_actions['add']['execute'] = True
3185 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
3186 elif con.lower() not in [item['condef'].lower() for item in existing_constraints]:
3187 # constraint exists but its definition has changed:
3188 sql_actions['drop']['execute'] = True
3189 sql_actions['drop']['msg_ok'] = sql_actions['drop']['msg_ok'] % (existing_constraints[0]['condef'].lower(), )
3190 sql_actions['add']['execute'] = True
3191 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
3193 # we need to add the constraint:
3194 sql_actions = [item for item in sql_actions.values()]
3195 sql_actions.sort(key=lambda x: x['order'])
3196 for sql_action in [action for action in sql_actions if action['execute']]:
3198 cr.execute(sql_action['query'])
3200 self.__schema.debug(sql_action['msg_ok'])
3202 self.__schema.warn(sql_action['msg_err'])
3206 def _execute_sql(self, cr):
3207 """ Execute the SQL code from the _sql attribute (if any)."""
3208 if hasattr(self, "_sql"):
3209 for line in self._sql.split(';'):
3210 line2 = line.replace('\n', '').strip()
3217 def createInstance(cls, pool, cr):
3218 return cls.makeInstance(pool, cr, ['_columns', '_defaults',
3219 '_inherits', '_constraints', '_sql_constraints'])
3221 def __init__(self, pool, cr):
3224 - copy the stored fields' functions in the osv_pool,
3225 - update the _columns with the fields found in ir_model_fields,
3226 - ensure there is a many2one for each _inherits'd parent,
3227 - update the children's _columns,
3228 - give a chance to each field to initialize itself.
3231 super(orm, self).__init__(pool, cr)
3233 if not hasattr(self, '_log_access'):
3234 # if not access is not specify, it is the same value as _auto
3235 self._log_access = getattr(self, "_auto", True)
3237 self._columns = self._columns.copy()
3238 for store_field in self._columns:
3239 f = self._columns[store_field]
3240 if hasattr(f, 'digits_change'):
3242 if not isinstance(f, fields.function):
3246 if self._columns[store_field].store is True:
3247 sm = {self._name: (lambda self, cr, uid, ids, c={}: ids, None, 10, None)}
3249 sm = self._columns[store_field].store
3250 for object, aa in sm.items():
3252 (fnct, fields2, order, length) = aa
3254 (fnct, fields2, order) = aa
3257 raise except_orm('Error',
3258 ('Invalid function definition %s in object %s !\nYou must use the definition: store={object:(fnct, fields, priority, time length)}.' % (store_field, self._name)))
3259 self.pool._store_function.setdefault(object, [])
3261 for x, y, z, e, f, l in self.pool._store_function[object]:
3262 if (x==self._name) and (y==store_field) and (e==fields2):
3266 self.pool._store_function[object].append( (self._name, store_field, fnct, fields2, order, length))
3267 self.pool._store_function[object].sort(lambda x, y: cmp(x[4], y[4]))
3269 for (key, _, msg) in self._sql_constraints:
3270 self.pool._sql_error[self._table+'_'+key] = msg
3272 # Load manual fields
3274 cr.execute("SELECT id FROM ir_model_fields WHERE name=%s AND model=%s", ('state', 'ir.model.fields'))
3276 cr.execute('SELECT * FROM ir_model_fields WHERE model=%s AND state=%s', (self._name, 'manual'))
3277 for field in cr.dictfetchall():
3278 if field['name'] in self._columns:
3281 'string': field['field_description'],
3282 'required': bool(field['required']),
3283 'readonly': bool(field['readonly']),
3284 'domain': eval(field['domain']) if field['domain'] else None,
3285 'size': field['size'],
3286 'ondelete': field['on_delete'],
3287 'translate': (field['translate']),
3289 #'select': int(field['select_level'])
3292 if field['ttype'] == 'selection':
3293 self._columns[field['name']] = fields.selection(eval(field['selection']), **attrs)
3294 elif field['ttype'] == 'reference':
3295 self._columns[field['name']] = fields.reference(selection=eval(field['selection']), **attrs)
3296 elif field['ttype'] == 'many2one':
3297 self._columns[field['name']] = fields.many2one(field['relation'], **attrs)
3298 elif field['ttype'] == 'one2many':
3299 self._columns[field['name']] = fields.one2many(field['relation'], field['relation_field'], **attrs)
3300 elif field['ttype'] == 'many2many':
3301 _rel1 = field['relation'].replace('.', '_')
3302 _rel2 = field['model'].replace('.', '_')
3303 _rel_name = 'x_%s_%s_%s_rel' % (_rel1, _rel2, field['name'])
3304 self._columns[field['name']] = fields.many2many(field['relation'], _rel_name, 'id1', 'id2', **attrs)
3306 self._columns[field['name']] = getattr(fields, field['ttype'])(**attrs)
3307 self._inherits_check()
3308 self._inherits_reload()
3309 if not self._sequence:
3310 self._sequence = self._table + '_id_seq'
3311 for k in self._defaults:
3312 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,)
3313 for f in self._columns:
3314 self._columns[f].restart()
3316 __init__.__doc__ = orm_template.__init__.__doc__ + __init__.__doc__
3319 # Update objects that uses this one to update their _inherits fields
3322 def _inherits_reload_src(self):
3323 """ Recompute the _inherit_fields mapping on each _inherits'd child model."""
3324 for obj in self.pool.models.values():
3325 if self._name in obj._inherits:
3326 obj._inherits_reload()
3329 def _inherits_reload(self):
3330 """ Recompute the _inherit_fields mapping.
3332 This will also call itself on each inherits'd child model.
3336 for table in self._inherits:
3337 other = self.pool.get(table)
3338 for col in other._columns.keys():
3339 res[col] = (table, self._inherits[table], other._columns[col])
3340 for col in other._inherit_fields.keys():
3341 res[col] = (table, self._inherits[table], other._inherit_fields[col][2])
3342 self._inherit_fields = res
3343 self._all_columns = self._get_column_infos()
3344 self._inherits_reload_src()
3347 def _get_column_infos(self):
3348 """Returns a dict mapping all fields names (direct fields and
3349 inherited field via _inherits) to a ``column_info`` struct
3350 giving detailed columns """
3352 for k, (parent, m2o, col) in self._inherit_fields.iteritems():
3353 result[k] = fields.column_info(k, col, parent, m2o)
3354 for k, col in self._columns.iteritems():
3355 result[k] = fields.column_info(k, col)
3359 def _inherits_check(self):
3360 for table, field_name in self._inherits.items():
3361 if field_name not in self._columns:
3362 logging.getLogger('init').info('Missing many2one field definition for _inherits reference "%s" in "%s", using default one.' % (field_name, self._name))
3363 self._columns[field_name] = fields.many2one(table, string="Automatically created field to link to parent %s" % table,
3364 required=True, ondelete="cascade")
3365 elif not self._columns[field_name].required or self._columns[field_name].ondelete.lower() != "cascade":
3366 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))
3367 self._columns[field_name].required = True
3368 self._columns[field_name].ondelete = "cascade"
3370 #def __getattr__(self, name):
3372 # Proxies attribute accesses to the `inherits` parent so we can call methods defined on the inherited parent
3373 # (though inherits doesn't use Python inheritance).
3374 # Handles translating between local ids and remote ids.
3375 # Known issue: doesn't work correctly when using python's own super(), don't involve inherit-based inheritance
3376 # when you have inherits.
3378 # for model, field in self._inherits.iteritems():
3379 # proxy = self.pool.get(model)
3380 # if hasattr(proxy, name):
3381 # attribute = getattr(proxy, name)
3382 # if not hasattr(attribute, '__call__'):
3386 # return super(orm, self).__getattr__(name)
3388 # def _proxy(cr, uid, ids, *args, **kwargs):
3389 # objects = self.browse(cr, uid, ids, kwargs.get('context', None))
3390 # lst = [obj[field].id for obj in objects if obj[field]]
3391 # return getattr(proxy, name)(cr, uid, lst, *args, **kwargs)
3396 def fields_get(self, cr, user, fields=None, context=None):
3398 Get the description of list of fields
3400 :param cr: database cursor
3401 :param user: current user id
3402 :param fields: list of fields
3403 :param context: context arguments, like lang, time zone
3404 :return: dictionary of field dictionaries, each one describing a field of the business object
3405 :raise AccessError: * if user has no create/write rights on the requested object
3408 ira = self.pool.get('ir.model.access')
3409 write_access = ira.check(cr, user, self._name, 'write', raise_exception=False, context=context) or \
3410 ira.check(cr, user, self._name, 'create', raise_exception=False, context=context)
3411 return super(orm, self).fields_get(cr, user, fields, context, write_access)
3413 def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
3416 self.pool.get('ir.model.access').check(cr, user, self._name, 'read', context=context)
3418 fields = list(set(self._columns.keys() + self._inherit_fields.keys()))
3419 if isinstance(ids, (int, long)):
3423 select = map(lambda x: isinstance(x, dict) and x['id'] or x, select)
3424 result = self._read_flat(cr, user, select, fields, context, load)
3427 for key, v in r.items():
3431 if isinstance(ids, (int, long, dict)):
3432 return result and result[0] or False
3435 def _read_flat(self, cr, user, ids, fields_to_read, context=None, load='_classic_read'):
3440 if fields_to_read == None:
3441 fields_to_read = self._columns.keys()
3443 # Construct a clause for the security rules.
3444 # 'tables' hold the list of tables necessary for the SELECT including the ir.rule clauses,
3445 # or will at least contain self._table.
3446 rule_clause, rule_params, tables = self.pool.get('ir.rule').domain_get(cr, user, self._name, 'read', context=context)
3448 # all inherited fields + all non inherited fields for which the attribute whose name is in load is True
3449 fields_pre = [f for f in fields_to_read if
3450 f == self.CONCURRENCY_CHECK_FIELD
3451 or (f in self._columns and getattr(self._columns[f], '_classic_write'))
3452 ] + self._inherits.values()
3456 def convert_field(f):
3457 f_qual = "%s.%s" % (self._table, f) # need fully-qualified references in case len(tables) > 1
3458 if f in ('create_date', 'write_date'):
3459 return "date_trunc('second', %s) as %s" % (f_qual, f)
3460 if f == self.CONCURRENCY_CHECK_FIELD:
3461 if self._log_access:
3462 return "COALESCE(%s.write_date, %s.create_date, now())::timestamp AS %s" % (self._table, self._table, f,)
3463 return "now()::timestamp AS %s" % (f,)
3464 if isinstance(self._columns[f], fields.binary) and context.get('bin_size', False):
3465 return 'length(%s) as "%s"' % (f_qual, f)
3468 fields_pre2 = map(convert_field, fields_pre)
3469 order_by = self._parent_order or self._order
3470 select_fields = ','.join(fields_pre2 + [self._table + '.id'])
3471 query = 'SELECT %s FROM %s WHERE %s.id IN %%s' % (select_fields, ','.join(tables), self._table)
3473 query += " AND " + (' OR '.join(rule_clause))
3474 query += " ORDER BY " + order_by
3475 for sub_ids in cr.split_for_in_conditions(ids):
3477 cr.execute(query, [tuple(sub_ids)] + rule_params)
3478 if cr.rowcount != len(sub_ids):
3479 raise except_orm(_('AccessError'),
3480 _('Operation prohibited by access rules, or performed on an already deleted document (Operation: read, Document type: %s).')
3481 % (self._description,))
3483 cr.execute(query, (tuple(sub_ids),))
3484 res.extend(cr.dictfetchall())
3486 res = map(lambda x: {'id': x}, ids)
3488 for f in fields_pre:
3489 if f == self.CONCURRENCY_CHECK_FIELD:
3491 if self._columns[f].translate:
3492 ids = [x['id'] for x in res]
3493 #TODO: optimize out of this loop
3494 res_trans = self.pool.get('ir.translation')._get_ids(cr, user, self._name+','+f, 'model', context.get('lang', False) or 'en_US', ids)
3496 r[f] = res_trans.get(r['id'], False) or r[f]
3498 for table in self._inherits:
3499 col = self._inherits[table]
3500 cols = [x for x in intersect(self._inherit_fields.keys(), fields_to_read) if x not in self._columns.keys()]
3503 res2 = self.pool.get(table).read(cr, user, [x[col] for x in res], cols, context, load)
3511 if not record[col]: # if the record is deleted from _inherits table?
3513 record.update(res3[record[col]])
3514 if col not in fields_to_read:
3517 # all fields which need to be post-processed by a simple function (symbol_get)
3518 fields_post = filter(lambda x: x in self._columns and self._columns[x]._symbol_get, fields_to_read)
3521 for f in fields_post:
3522 r[f] = self._columns[f]._symbol_get(r[f])
3523 ids = [x['id'] for x in res]
3525 # all non inherited fields for which the attribute whose name is in load is False
3526 fields_post = filter(lambda x: x in self._columns and not getattr(self._columns[x], load), fields_to_read)
3528 # Compute POST fields
3530 for f in fields_post:
3531 todo.setdefault(self._columns[f]._multi, [])
3532 todo[self._columns[f]._multi].append(f)
3533 for key, val in todo.items():
3535 res2 = self._columns[val[0]].get(cr, self, ids, val, user, context=context, values=res)
3536 assert res2 is not None, \
3537 'The function field "%s" on the "%s" model returned None\n' \
3538 '(a dictionary was expected).' % (val[0], self._name)
3541 if isinstance(res2[record['id']], str): res2[record['id']] = eval(res2[record['id']]) #TOCHECK : why got string instend of dict in python2.6
3542 multi_fields = res2.get(record['id'],{})
3544 record[pos] = multi_fields.get(pos,[])
3547 res2 = self._columns[f].get(cr, self, ids, f, user, context=context, values=res)
3550 record[f] = res2[record['id']]
3555 for field in vals.copy():
3557 if field in self._columns:
3558 fobj = self._columns[field]
3565 for group in groups:
3566 module = group.split(".")[0]
3567 grp = group.split(".")[1]
3568 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", \
3569 (grp, module, 'res.groups', user))
3570 readonly = cr.fetchall()
3571 if readonly[0][0] >= 1:
3574 elif readonly[0][0] == 0:
3580 if type(vals[field]) == type([]):
3582 elif type(vals[field]) == type(0.0):
3584 elif type(vals[field]) == type(''):
3585 vals[field] = '=No Permission='
3590 def perm_read(self, cr, user, ids, context=None, details=True):
3592 Returns some metadata about the given records.
3594 :param details: if True, \*_uid fields are replaced with the name of the user
3595 :return: list of ownership dictionaries for each requested record
3596 :rtype: list of dictionaries with the following keys:
3599 * create_uid: user who created the record
3600 * create_date: date when the record was created
3601 * write_uid: last user who changed the record
3602 * write_date: date of the last change to the record
3603 * xmlid: XML ID to use to refer to this record (if there is one), in format ``module.name``
3610 uniq = isinstance(ids, (int, long))
3614 if self._log_access:
3615 fields += ['create_uid', 'create_date', 'write_uid', 'write_date']
3616 quoted_table = '"%s"' % self._table
3617 fields_str = ",".join('%s.%s'%(quoted_table, field) for field in fields)
3618 query = '''SELECT %s, __imd.module, __imd.name
3619 FROM %s LEFT JOIN ir_model_data __imd
3620 ON (__imd.model = %%s and __imd.res_id = %s.id)
3621 WHERE %s.id IN %%s''' % (fields_str, quoted_table, quoted_table, quoted_table)
3622 cr.execute(query, (self._name, tuple(ids)))
3623 res = cr.dictfetchall()
3626 r[key] = r[key] or False
3627 if details and key in ('write_uid', 'create_uid') and r[key]:
3629 r[key] = self.pool.get('res.users').name_get(cr, user, [r[key]])[0]
3631 pass # Leave the numeric uid there
3632 r['xmlid'] = ("%(module)s.%(name)s" % r) if r['name'] else False
3633 del r['name'], r['module']
3638 def _check_concurrency(self, cr, ids, context):
3641 if not (context.get(self.CONCURRENCY_CHECK_FIELD) and self._log_access):
3643 check_clause = "(id = %s AND %s < COALESCE(write_date, create_date, now())::timestamp)"
3644 for sub_ids in cr.split_for_in_conditions(ids):
3647 id_ref = "%s,%s" % (self._name, id)
3648 update_date = context[self.CONCURRENCY_CHECK_FIELD].pop(id_ref, None)
3650 ids_to_check.extend([id, update_date])
3651 if not ids_to_check:
3653 cr.execute("SELECT id FROM %s WHERE %s" % (self._table, " OR ".join([check_clause]*(len(ids_to_check)/2))), tuple(ids_to_check))
3656 # mention the first one only to keep the error message readable
3657 raise except_orm('ConcurrencyException', _('A document was modified since you last viewed it (%s:%d)') % (self._description, res[0]))
3659 def check_access_rule(self, cr, uid, ids, operation, context=None):
3660 """Verifies that the operation given by ``operation`` is allowed for the user
3661 according to ir.rules.
3663 :param operation: one of ``write``, ``unlink``
3664 :raise except_orm: * if current ir.rules do not permit this operation.
3665 :return: None if the operation is allowed
3667 where_clause, where_params, tables = self.pool.get('ir.rule').domain_get(cr, uid, self._name, operation, context=context)
3669 where_clause = ' and ' + ' and '.join(where_clause)
3670 for sub_ids in cr.split_for_in_conditions(ids):
3671 cr.execute('SELECT ' + self._table + '.id FROM ' + ','.join(tables) +
3672 ' WHERE ' + self._table + '.id IN %s' + where_clause,
3673 [sub_ids] + where_params)
3674 if cr.rowcount != len(sub_ids):
3675 raise except_orm(_('AccessError'),
3676 _('Operation prohibited by access rules, or performed on an already deleted document (Operation: %s, Document type: %s).')
3677 % (operation, self._description))
3679 def unlink(self, cr, uid, ids, context=None):
3681 Delete records with given ids
3683 :param cr: database cursor
3684 :param uid: current user id
3685 :param ids: id or list of ids
3686 :param context: (optional) context arguments, like lang, time zone
3688 :raise AccessError: * if user has no unlink rights on the requested object
3689 * if user tries to bypass access rules for unlink on the requested object
3690 :raise UserError: if the record is default property for other records
3695 if isinstance(ids, (int, long)):
3698 result_store = self._store_get_values(cr, uid, ids, None, context)
3700 self._check_concurrency(cr, ids, context)
3702 self.pool.get('ir.model.access').check(cr, uid, self._name, 'unlink', context=context)
3704 properties = self.pool.get('ir.property')
3705 domain = [('res_id', '=', False),
3706 ('value_reference', 'in', ['%s,%s' % (self._name, i) for i in ids]),
3708 if properties.search(cr, uid, domain, context=context):
3709 raise except_orm(_('Error'), _('Unable to delete this document because it is used as a default property'))
3711 wf_service = netsvc.LocalService("workflow")
3713 wf_service.trg_delete(uid, self._name, oid, cr)
3716 self.check_access_rule(cr, uid, ids, 'unlink', context=context)
3717 pool_model_data = self.pool.get('ir.model.data')
3718 ir_values_obj = self.pool.get('ir.values')
3719 for sub_ids in cr.split_for_in_conditions(ids):
3720 cr.execute('delete from ' + self._table + ' ' \
3721 'where id IN %s', (sub_ids,))
3723 # Removing the ir_model_data reference if the record being deleted is a record created by xml/csv file,
3724 # as these are not connected with real database foreign keys, and would be dangling references.
3725 # Note: following steps performed as admin to avoid access rights restrictions, and with no context
3726 # to avoid possible side-effects during admin calls.
3727 # Step 1. Calling unlink of ir_model_data only for the affected IDS
3728 reference_ids = pool_model_data.search(cr, ROOT_USER_ID, [('res_id','in',list(sub_ids)),('model','=',self._name)])
3729 # Step 2. Marching towards the real deletion of referenced records
3731 pool_model_data.unlink(cr, ROOT_USER_ID, reference_ids)
3733 # For the same reason, removing the record relevant to ir_values
3734 ir_value_ids = ir_values_obj.search(cr, uid,
3735 ['|',('value','in',['%s,%s' % (self._name, sid) for sid in sub_ids]),'&',('res_id','in',list(sub_ids)),('model','=',self._name)],
3738 ir_values_obj.unlink(cr, uid, ir_value_ids, context=context)
3740 for order, object, store_ids, fields in result_store:
3741 if object != self._name:
3742 obj = self.pool.get(object)
3743 cr.execute('select id from '+obj._table+' where id IN %s', (tuple(store_ids),))
3744 rids = map(lambda x: x[0], cr.fetchall())
3746 obj._store_set_values(cr, uid, rids, fields, context)
3753 def write(self, cr, user, ids, vals, context=None):
3755 Update records with given ids with the given field values
3757 :param cr: database cursor
3758 :param user: current user id
3760 :param ids: object id or list of object ids to update according to **vals**
3761 :param vals: field values to update, e.g {'field_name': new_field_value, ...}
3762 :type vals: dictionary
3763 :param context: (optional) context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...}
3764 :type context: dictionary
3766 :raise AccessError: * if user has no write rights on the requested object
3767 * if user tries to bypass access rules for write on the requested object
3768 :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
3769 :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)
3771 **Note**: The type of field values to pass in ``vals`` for relationship fields is specific:
3773 + For a many2many field, a list of tuples is expected.
3774 Here is the list of tuple that are accepted, with the corresponding semantics ::
3776 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
3777 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
3778 (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)
3779 (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)
3780 (4, ID) link to existing record with id = ID (adds a relationship)
3781 (5) unlink all (like using (3,ID) for all linked records)
3782 (6, 0, [IDs]) replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)
3785 [(6, 0, [8, 5, 6, 4])] sets the many2many to ids [8, 5, 6, 4]
3787 + For a one2many field, a lits of tuples is expected.
3788 Here is the list of tuple that are accepted, with the corresponding semantics ::
3790 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
3791 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
3792 (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)
3795 [(0, 0, {'field_name':field_value_record1, ...}), (0, 0, {'field_name':field_value_record2, ...})]
3797 + For a many2one field, simply use the ID of target record, which must already exist, or ``False`` to remove the link.
3798 + For a reference field, use a string with the model name, a comma, and the target object id (example: ``'product.product, 5'``)
3802 for field in vals.copy():
3804 if field in self._columns:
3805 fobj = self._columns[field]
3806 elif field in self._inherit_fields:
3807 fobj = self._inherit_fields[field][2]
3814 for group in groups:
3815 module = group.split(".")[0]
3816 grp = group.split(".")[1]
3817 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", \
3818 (grp, module, 'res.groups', user))
3819 readonly = cr.fetchall()
3820 if readonly[0][0] >= 1:
3823 elif readonly[0][0] == 0:
3835 if isinstance(ids, (int, long)):
3838 self._check_concurrency(cr, ids, context)
3839 self.pool.get('ir.model.access').check(cr, user, self._name, 'write', context=context)
3841 result = self._store_get_values(cr, user, ids, vals.keys(), context) or []
3843 # No direct update of parent_left/right
3844 vals.pop('parent_left', None)
3845 vals.pop('parent_right', None)
3847 parents_changed = []
3848 parent_order = self._parent_order or self._order
3849 if self._parent_store and (self._parent_name in vals):
3850 # The parent_left/right computation may take up to
3851 # 5 seconds. No need to recompute the values if the
3852 # parent is the same.
3853 # Note: to respect parent_order, nodes must be processed in
3854 # order, so ``parents_changed`` must be ordered properly.
3855 parent_val = vals[self._parent_name]
3857 query = "SELECT id FROM %s WHERE id IN %%s AND (%s != %%s OR %s IS NULL) ORDER BY %s" % \
3858 (self._table, self._parent_name, self._parent_name, parent_order)
3859 cr.execute(query, (tuple(ids), parent_val))
3861 query = "SELECT id FROM %s WHERE id IN %%s AND (%s IS NOT NULL) ORDER BY %s" % \
3862 (self._table, self._parent_name, parent_order)
3863 cr.execute(query, (tuple(ids),))
3864 parents_changed = map(operator.itemgetter(0), cr.fetchall())
3871 totranslate = context.get('lang', False) and (context['lang'] != 'en_US')
3873 if field in self._columns:
3874 if self._columns[field]._classic_write and not (hasattr(self._columns[field], '_fnct_inv')):
3875 if (not totranslate) or not self._columns[field].translate:
3876 upd0.append('"'+field+'"='+self._columns[field]._symbol_set[0])
3877 upd1.append(self._columns[field]._symbol_set[1](vals[field]))
3878 direct.append(field)
3880 upd_todo.append(field)
3882 updend.append(field)
3883 if field in self._columns \
3884 and hasattr(self._columns[field], 'selection') \
3886 self._check_selection_field_value(cr, user, field, vals[field], context=context)
3888 if self._log_access:
3889 upd0.append('write_uid=%s')
3890 upd0.append('write_date=now()')
3894 self.check_access_rule(cr, user, ids, 'write', context=context)
3895 for sub_ids in cr.split_for_in_conditions(ids):
3896 cr.execute('update ' + self._table + ' set ' + ','.join(upd0) + ' ' \
3897 'where id IN %s', upd1 + [sub_ids])
3898 if cr.rowcount != len(sub_ids):
3899 raise except_orm(_('AccessError'),
3900 _('One of the records you are trying to modify has already been deleted (Document type: %s).') % self._description)
3905 if self._columns[f].translate:
3906 src_trans = self.pool.get(self._name).read(cr, user, ids, [f])[0][f]
3909 # Inserting value to DB
3910 self.write(cr, user, ids, {f: vals[f]})
3911 self.pool.get('ir.translation')._set_ids(cr, user, self._name+','+f, 'model', context['lang'], ids, vals[f], src_trans)
3914 # call the 'set' method of fields which are not classic_write
3915 upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
3917 # default element in context must be removed when call a one2many or many2many
3918 rel_context = context.copy()
3919 for c in context.items():
3920 if c[0].startswith('default_'):
3921 del rel_context[c[0]]
3923 for field in upd_todo:
3925 result += self._columns[field].set(cr, self, id, field, vals[field], user, context=rel_context) or []
3927 for table in self._inherits:
3928 col = self._inherits[table]
3930 for sub_ids in cr.split_for_in_conditions(ids):
3931 cr.execute('select distinct "'+col+'" from "'+self._table+'" ' \
3932 'where id IN %s', (sub_ids,))
3933 nids.extend([x[0] for x in cr.fetchall()])
3937 if self._inherit_fields[val][0] == table:
3940 self.pool.get(table).write(cr, user, nids, v, context)
3942 self._validate(cr, user, ids, context)
3944 # TODO: use _order to set dest at the right position and not first node of parent
3945 # We can't defer parent_store computation because the stored function
3946 # fields that are computer may refer (directly or indirectly) to
3947 # parent_left/right (via a child_of domain)
3950 self.pool._init_parent[self._name] = True
3952 order = self._parent_order or self._order
3953 parent_val = vals[self._parent_name]
3955 clause, params = '%s=%%s' % (self._parent_name,), (parent_val,)
3957 clause, params = '%s IS NULL' % (self._parent_name,), ()
3959 for id in parents_changed:
3960 cr.execute('SELECT parent_left, parent_right FROM %s WHERE id=%%s' % (self._table,), (id,))
3961 pleft, pright = cr.fetchone()
3962 distance = pright - pleft + 1
3964 # Positions of current siblings, to locate proper insertion point;
3965 # this can _not_ be fetched outside the loop, as it needs to be refreshed
3966 # after each update, in case several nodes are sequentially inserted one
3967 # next to the other (i.e computed incrementally)
3968 cr.execute('SELECT parent_right, id FROM %s WHERE %s ORDER BY %s' % (self._table, clause, parent_order), params)
3969 parents = cr.fetchall()
3971 # Find Position of the element
3973 for (parent_pright, parent_id) in parents:
3976 position = parent_pright + 1
3978 # It's the first node of the parent
3983 cr.execute('select parent_left from '+self._table+' where id=%s', (parent_val,))
3984 position = cr.fetchone()[0] + 1
3986 if pleft < position <= pright:
3987 raise except_orm(_('UserError'), _('Recursivity Detected.'))
3989 if pleft < position:
3990 cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
3991 cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
3992 cr.execute('update '+self._table+' set parent_left=parent_left+%s, parent_right=parent_right+%s where parent_left>=%s and parent_left<%s', (position-pleft, position-pleft, pleft, pright))
3994 cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
3995 cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
3996 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))
3998 result += self._store_get_values(cr, user, ids, vals.keys(), context)
4002 for order, object, ids_to_update, fields_to_recompute in result:
4003 key = (object, tuple(fields_to_recompute))
4004 done.setdefault(key, {})
4005 # avoid to do several times the same computation
4007 for id in ids_to_update:
4008 if id not in done[key]:
4009 done[key][id] = True
4011 self.pool.get(object)._store_set_values(cr, user, todo, fields_to_recompute, context)
4013 wf_service = netsvc.LocalService("workflow")
4015 wf_service.trg_write(user, self._name, id, cr)
4019 # TODO: Should set perm to user.xxx
4021 def create(self, cr, user, vals, context=None):
4023 Create a new record for the model.
4025 The values for the new record are initialized using the ``vals``
4026 argument, and if necessary the result of ``default_get()``.
4028 :param cr: database cursor
4029 :param user: current user id
4031 :param vals: field values for new record, e.g {'field_name': field_value, ...}
4032 :type vals: dictionary
4033 :param context: optional context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...}
4034 :type context: dictionary
4035 :return: id of new record created
4036 :raise AccessError: * if user has no create rights on the requested object
4037 * if user tries to bypass access rules for create on the requested object
4038 :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
4039 :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)
4041 **Note**: The type of field values to pass in ``vals`` for relationship fields is specific.
4042 Please see the description of the :py:meth:`~osv.osv.osv.write` method for details about the possible values and how
4048 self.pool.get('ir.model.access').check(cr, user, self._name, 'create', context=context)
4050 vals = self._add_missing_default_values(cr, user, vals, context)
4053 for v in self._inherits:
4054 if self._inherits[v] not in vals:
4057 tocreate[v] = {'id': vals[self._inherits[v]]}
4058 (upd0, upd1, upd2) = ('', '', [])
4060 for v in vals.keys():
4061 if v in self._inherit_fields:
4062 (table, col, col_detail) = self._inherit_fields[v]
4063 tocreate[table][v] = vals[v]
4066 if (v not in self._inherit_fields) and (v not in self._columns):
4069 # Try-except added to filter the creation of those records whose filds are readonly.
4070 # Example : any dashboard which has all the fields readonly.(due to Views(database views))
4072 cr.execute("SELECT nextval('"+self._sequence+"')")
4074 raise except_orm(_('UserError'),
4075 _('You cannot perform this operation. New Record Creation is not allowed for this object as this object is for reporting purpose.'))
4077 id_new = cr.fetchone()[0]
4078 for table in tocreate:
4079 if self._inherits[table] in vals:
4080 del vals[self._inherits[table]]
4082 record_id = tocreate[table].pop('id', None)
4084 if record_id is None or not record_id:
4085 record_id = self.pool.get(table).create(cr, user, tocreate[table], context=context)
4087 self.pool.get(table).write(cr, user, [record_id], tocreate[table], context=context)
4089 upd0 += ',' + self._inherits[table]
4091 upd2.append(record_id)
4093 #Start : Set bool fields to be False if they are not touched(to make search more powerful)
4094 bool_fields = [x for x in self._columns.keys() if self._columns[x]._type=='boolean']
4096 for bool_field in bool_fields:
4097 if bool_field not in vals:
4098 vals[bool_field] = False
4100 for field in vals.copy():
4102 if field in self._columns:
4103 fobj = self._columns[field]
4105 fobj = self._inherit_fields[field][2]
4111 for group in groups:
4112 module = group.split(".")[0]
4113 grp = group.split(".")[1]
4114 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" % \
4115 (grp, module, 'res.groups', user))
4116 readonly = cr.fetchall()
4117 if readonly[0][0] >= 1:
4120 elif readonly[0][0] == 0:
4128 if self._columns[field]._classic_write:
4129 upd0 = upd0 + ',"' + field + '"'
4130 upd1 = upd1 + ',' + self._columns[field]._symbol_set[0]
4131 upd2.append(self._columns[field]._symbol_set[1](vals[field]))
4133 if not isinstance(self._columns[field], fields.related):
4134 upd_todo.append(field)
4135 if field in self._columns \
4136 and hasattr(self._columns[field], 'selection') \
4138 self._check_selection_field_value(cr, user, field, vals[field], context=context)
4139 if self._log_access:
4140 upd0 += ',create_uid,create_date'
4143 cr.execute('insert into "'+self._table+'" (id'+upd0+") values ("+str(id_new)+upd1+')', tuple(upd2))
4144 self.check_access_rule(cr, user, [id_new], 'create', context=context)
4145 upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
4147 if self._parent_store and not context.get('defer_parent_store_computation'):
4149 self.pool._init_parent[self._name] = True
4151 parent = vals.get(self._parent_name, False)
4153 cr.execute('select parent_right from '+self._table+' where '+self._parent_name+'=%s order by '+(self._parent_order or self._order), (parent,))
4155 result_p = cr.fetchall()
4156 for (pleft,) in result_p:
4161 cr.execute('select parent_left from '+self._table+' where id=%s', (parent,))
4162 pleft_old = cr.fetchone()[0]
4165 cr.execute('select max(parent_right) from '+self._table)
4166 pleft = cr.fetchone()[0] or 0
4167 cr.execute('update '+self._table+' set parent_left=parent_left+2 where parent_left>%s', (pleft,))
4168 cr.execute('update '+self._table+' set parent_right=parent_right+2 where parent_right>%s', (pleft,))
4169 cr.execute('update '+self._table+' set parent_left=%s,parent_right=%s where id=%s', (pleft+1, pleft+2, id_new))
4171 # default element in context must be remove when call a one2many or many2many
4172 rel_context = context.copy()
4173 for c in context.items():
4174 if c[0].startswith('default_'):
4175 del rel_context[c[0]]
4178 for field in upd_todo:
4179 result += self._columns[field].set(cr, self, id_new, field, vals[field], user, rel_context) or []
4180 self._validate(cr, user, [id_new], context)
4182 if not context.get('no_store_function', False):
4183 result += self._store_get_values(cr, user, [id_new], vals.keys(), context)
4186 for order, object, ids, fields2 in result:
4187 if not (object, ids, fields2) in done:
4188 self.pool.get(object)._store_set_values(cr, user, ids, fields2, context)
4189 done.append((object, ids, fields2))
4191 if self._log_create and not (context and context.get('no_store_function', False)):
4192 message = self._description + \
4194 self.name_get(cr, user, [id_new], context=context)[0][1] + \
4195 "' " + _("created.")
4196 self.log(cr, user, id_new, message, True, context=context)
4197 wf_service = netsvc.LocalService("workflow")
4198 wf_service.trg_create(user, self._name, id_new, cr)
4201 def _store_get_values(self, cr, uid, ids, fields, context):
4202 """Returns an ordered list of fields.functions to call due to
4203 an update operation on ``fields`` of records with ``ids``,
4204 obtained by calling the 'store' functions of these fields,
4205 as setup by their 'store' attribute.
4207 :return: [(priority, model_name, [record_ids,], [function_fields,])]
4209 # FIXME: rewrite, cleanup, use real variable names
4210 # e.g.: http://pastie.org/1222060
4212 fncts = self.pool._store_function.get(self._name, [])
4213 for fnct in range(len(fncts)):
4218 for f in (fields or []):
4219 if f in fncts[fnct][3]:
4225 result.setdefault(fncts[fnct][0], {})
4227 # use admin user for accessing objects having rules defined on store fields
4228 ids2 = fncts[fnct][2](self, cr, ROOT_USER_ID, ids, context)
4229 for id in filter(None, ids2):
4230 result[fncts[fnct][0]].setdefault(id, [])
4231 result[fncts[fnct][0]][id].append(fnct)
4233 for object in result:
4235 for id, fnct in result[object].items():
4236 k2.setdefault(tuple(fnct), [])
4237 k2[tuple(fnct)].append(id)
4238 for fnct, id in k2.items():
4239 dict.setdefault(fncts[fnct[0]][4], [])
4240 dict[fncts[fnct[0]][4]].append((fncts[fnct[0]][4], object, id, map(lambda x: fncts[x][1], fnct)))
4248 def _store_set_values(self, cr, uid, ids, fields, context):
4249 """Calls the fields.function's "implementation function" for all ``fields``, on records with ``ids`` (taking care of
4250 respecting ``multi`` attributes), and stores the resulting values in the database directly."""
4255 if self._log_access:
4256 cr.execute('select id,write_date from '+self._table+' where id IN %s', (tuple(ids),))
4260 field_dict.setdefault(r[0], [])
4261 res_date = time.strptime((r[1])[:19], '%Y-%m-%d %H:%M:%S')
4262 write_date = datetime.datetime.fromtimestamp(time.mktime(res_date))
4263 for i in self.pool._store_function.get(self._name, []):
4265 up_write_date = write_date + datetime.timedelta(hours=i[5])
4266 if datetime.datetime.now() < up_write_date:
4268 field_dict[r[0]].append(i[1])
4274 if self._columns[f]._multi not in keys:
4275 keys.append(self._columns[f]._multi)
4276 todo.setdefault(self._columns[f]._multi, [])
4277 todo[self._columns[f]._multi].append(f)
4281 # use admin user for accessing objects having rules defined on store fields
4282 result = self._columns[val[0]].get(cr, self, ids, val, ROOT_USER_ID, context=context)
4283 for id, value in result.items():
4285 for f in value.keys():
4286 if f in field_dict[id]:
4293 if self._columns[v]._type in ('many2one', 'one2one'):
4295 value[v] = value[v][0]
4298 upd0.append('"'+v+'"='+self._columns[v]._symbol_set[0])
4299 upd1.append(self._columns[v]._symbol_set[1](value[v]))
4302 cr.execute('update "' + self._table + '" set ' + \
4303 ','.join(upd0) + ' where id = %s', upd1)
4307 # use admin user for accessing objects having rules defined on store fields
4308 result = self._columns[f].get(cr, self, ids, f, ROOT_USER_ID, context=context)
4309 for r in result.keys():
4311 if r in field_dict.keys():
4312 if f in field_dict[r]:
4314 for id, value in result.items():
4315 if self._columns[f]._type in ('many2one', 'one2one'):
4320 cr.execute('update "' + self._table + '" set ' + \
4321 '"'+f+'"='+self._columns[f]._symbol_set[0] + ' where id = %s', (self._columns[f]._symbol_set[1](value), id))
4327 def perm_write(self, cr, user, ids, fields, context=None):
4328 raise NotImplementedError(_('This method does not exist anymore'))
4330 # TODO: ameliorer avec NULL
4331 def _where_calc(self, cr, user, domain, active_test=True, context=None):
4332 """Computes the WHERE clause needed to implement an OpenERP domain.
4333 :param domain: the domain to compute
4335 :param active_test: whether the default filtering of records with ``active``
4336 field set to ``False`` should be applied.
4337 :return: the query expressing the given domain as provided in domain
4338 :rtype: osv.query.Query
4343 # if the object has a field named 'active', filter out all inactive
4344 # records unless they were explicitely asked for
4345 if 'active' in self._columns and (active_test and context.get('active_test', True)):
4347 active_in_args = False
4349 if a[0] == 'active':
4350 active_in_args = True
4351 if not active_in_args:
4352 domain.insert(0, ('active', '=', 1))
4354 domain = [('active', '=', 1)]
4358 e = expression.expression(domain)
4359 e.parse(cr, user, self, context)
4360 tables = e.get_tables()
4361 where_clause, where_params = e.to_sql()
4362 where_clause = where_clause and [where_clause] or []
4364 where_clause, where_params, tables = [], [], ['"%s"' % self._table]
4366 return Query(tables, where_clause, where_params)
4368 def _check_qorder(self, word):
4369 if not regex_order.match(word):
4370 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)'))
4373 def _apply_ir_rules(self, cr, uid, query, mode='read', context=None):
4374 """Add what's missing in ``query`` to implement all appropriate ir.rules
4375 (using the ``model_name``'s rules or the current model's rules if ``model_name`` is None)
4377 :param query: the current query object
4379 def apply_rule(added_clause, added_params, added_tables, parent_model=None, child_object=None):
4381 if parent_model and child_object:
4382 # as inherited rules are being applied, we need to add the missing JOIN
4383 # to reach the parent table (if it was not JOINed yet in the query)
4384 child_object._inherits_join_add(parent_model, query)
4385 query.where_clause += added_clause
4386 query.where_clause_params += added_params
4387 for table in added_tables:
4388 if table not in query.tables:
4389 query.tables.append(table)
4393 # apply main rules on the object
4394 rule_obj = self.pool.get('ir.rule')
4395 apply_rule(*rule_obj.domain_get(cr, uid, self._name, mode, context=context))
4397 # apply ir.rules from the parents (through _inherits)
4398 for inherited_model in self._inherits:
4399 kwargs = dict(parent_model=inherited_model, child_object=self) #workaround for python2.5
4400 apply_rule(*rule_obj.domain_get(cr, uid, inherited_model, mode, context=context), **kwargs)
4402 def _generate_m2o_order_by(self, order_field, query):
4404 Add possibly missing JOIN to ``query`` and generate the ORDER BY clause for m2o fields,
4405 either native m2o fields or function/related fields that are stored, including
4406 intermediate JOINs for inheritance if required.
4408 :return: the qualified field name to use in an ORDER BY clause to sort by ``order_field``
4410 if order_field not in self._columns and order_field in self._inherit_fields:
4411 # also add missing joins for reaching the table containing the m2o field
4412 qualified_field = self._inherits_join_calc(order_field, query)
4413 order_field_column = self._inherit_fields[order_field][2]
4415 qualified_field = '"%s"."%s"' % (self._table, order_field)
4416 order_field_column = self._columns[order_field]
4418 assert order_field_column._type == 'many2one', 'Invalid field passed to _generate_m2o_order_by()'
4419 if not order_field_column._classic_write and not getattr(order_field_column, 'store', False):
4420 logging.getLogger('orm.search').debug("Many2one function/related fields must be stored " \
4421 "to be used as ordering fields! Ignoring sorting for %s.%s",
4422 self._name, order_field)
4425 # figure out the applicable order_by for the m2o
4426 dest_model = self.pool.get(order_field_column._obj)
4427 m2o_order = dest_model._order
4428 if not regex_order.match(m2o_order):
4429 # _order is complex, can't use it here, so we default to _rec_name
4430 m2o_order = dest_model._rec_name
4432 # extract the field names, to be able to qualify them and add desc/asc
4434 for order_part in m2o_order.split(","):
4435 m2o_order_list.append(order_part.strip().split(" ",1)[0].strip())
4436 m2o_order = m2o_order_list
4438 # Join the dest m2o table if it's not joined yet. We use [LEFT] OUTER join here
4439 # as we don't want to exclude results that have NULL values for the m2o
4440 src_table, src_field = qualified_field.replace('"','').split('.', 1)
4441 query.join((src_table, dest_model._table, src_field, 'id'), outer=True)
4442 qualify = lambda field: '"%s"."%s"' % (dest_model._table, field)
4443 return map(qualify, m2o_order) if isinstance(m2o_order, list) else qualify(m2o_order)
4446 def _generate_order_by(self, order_spec, query):
4448 Attempt to consruct an appropriate ORDER BY clause based on order_spec, which must be
4449 a comma-separated list of valid field names, optionally followed by an ASC or DESC direction.
4451 :raise" except_orm in case order_spec is malformed
4453 order_by_clause = self._order
4455 order_by_elements = []
4456 self._check_qorder(order_spec)
4457 for order_part in order_spec.split(','):
4458 order_split = order_part.strip().split(' ')
4459 order_field = order_split[0].strip()
4460 order_direction = order_split[1].strip() if len(order_split) == 2 else ''
4462 if order_field == 'id':
4463 order_by_clause = '"%s"."%s"' % (self._table, order_field)
4464 elif order_field in self._columns:
4465 order_column = self._columns[order_field]
4466 if order_column._classic_read:
4467 inner_clause = '"%s"."%s"' % (self._table, order_field)
4468 elif order_column._type == 'many2one':
4469 inner_clause = self._generate_m2o_order_by(order_field, query)
4471 continue # ignore non-readable or "non-joinable" fields
4472 elif order_field in self._inherit_fields:
4473 parent_obj = self.pool.get(self._inherit_fields[order_field][0])
4474 order_column = parent_obj._columns[order_field]
4475 if order_column._classic_read:
4476 inner_clause = self._inherits_join_calc(order_field, query)
4477 elif order_column._type == 'many2one':
4478 inner_clause = self._generate_m2o_order_by(order_field, query)
4480 continue # ignore non-readable or "non-joinable" fields
4482 if isinstance(inner_clause, list):
4483 for clause in inner_clause:
4484 order_by_elements.append("%s %s" % (clause, order_direction))
4486 order_by_elements.append("%s %s" % (inner_clause, order_direction))
4487 if order_by_elements:
4488 order_by_clause = ",".join(order_by_elements)
4490 return order_by_clause and (' ORDER BY %s ' % order_by_clause) or ''
4492 def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
4494 Private implementation of search() method, allowing specifying the uid to use for the access right check.
4495 This is useful for example when filling in the selection list for a drop-down and avoiding access rights errors,
4496 by specifying ``access_rights_uid=1`` to bypass access rights check, but not ir.rules!
4497 This is ok at the security level because this method is private and not callable through XML-RPC.
4499 :param access_rights_uid: optional user ID to use when checking access rights
4500 (not for ir.rules, this is only for ir.model.access)
4504 self.pool.get('ir.model.access').check(cr, access_rights_uid or user, self._name, 'read', context=context)
4506 query = self._where_calc(cr, user, args, context=context)
4507 self._apply_ir_rules(cr, user, query, 'read', context=context)
4508 order_by = self._generate_order_by(order, query)
4509 from_clause, where_clause, where_clause_params = query.get_sql()
4511 limit_str = limit and ' limit %d' % limit or ''
4512 offset_str = offset and ' offset %d' % offset or ''
4513 where_str = where_clause and (" WHERE %s" % where_clause) or ''
4516 cr.execute('SELECT count("%s".id) FROM ' % self._table + from_clause + where_str + limit_str + offset_str, where_clause_params)
4519 cr.execute('SELECT "%s".id FROM ' % self._table + from_clause + where_str + order_by + limit_str + offset_str, where_clause_params)
4521 return [x[0] for x in res]
4523 # returns the different values ever entered for one field
4524 # this is used, for example, in the client when the user hits enter on
4526 def distinct_field_get(self, cr, uid, field, value, args=None, offset=0, limit=None):
4529 if field in self._inherit_fields:
4530 return self.pool.get(self._inherit_fields[field][0]).distinct_field_get(cr, uid, field, value, args, offset, limit)
4532 return self._columns[field].search(cr, self, args, field, value, offset, limit, uid)
4534 def copy_data(self, cr, uid, id, default=None, context=None):
4536 Copy given record's data with all its fields values
4538 :param cr: database cursor
4539 :param user: current user id
4540 :param id: id of the record to copy
4541 :param default: field values to override in the original values of the copied record
4542 :type default: dictionary
4543 :param context: context arguments, like lang, time zone
4544 :type context: dictionary
4545 :return: dictionary containing all the field values
4551 # avoid recursion through already copied records in case of circular relationship
4552 seen_map = context.setdefault('__copy_data_seen',{})
4553 if id in seen_map.setdefault(self._name,[]):
4555 seen_map[self._name].append(id)
4559 if 'state' not in default:
4560 if 'state' in self._defaults:
4561 if callable(self._defaults['state']):
4562 default['state'] = self._defaults['state'](self, cr, uid, context)
4564 default['state'] = self._defaults['state']
4566 context_wo_lang = context.copy()
4567 if 'lang' in context:
4568 del context_wo_lang['lang']
4569 data = self.read(cr, uid, [id,], context=context_wo_lang)
4573 raise IndexError( _("Record #%d of %s not found, cannot copy!") %( id, self._name))
4575 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
4576 fields = self.fields_get(cr, uid, context=context)
4578 ftype = fields[f]['type']
4580 if self._log_access and f in ('create_date', 'create_uid', 'write_date', 'write_uid'):
4584 data[f] = default[f]
4585 elif 'function' in fields[f]:
4587 elif ftype == 'many2one':
4589 data[f] = data[f] and data[f][0]
4592 elif ftype in ('one2many', 'one2one'):
4594 rel = self.pool.get(fields[f]['relation'])
4596 # duplicate following the order of the ids
4597 # because we'll rely on it later for copying
4598 # translations in copy_translation()!
4600 for rel_id in data[f]:
4601 # the lines are first duplicated using the wrong (old)
4602 # parent but then are reassigned to the correct one thanks
4603 # to the (0, 0, ...)
4604 d = rel.copy_data(cr, uid, rel_id, context=context)
4606 res.append((0, 0, d))
4608 elif ftype == 'many2many':
4609 data[f] = [(6, 0, data[f])]
4613 # make sure we don't break the current parent_store structure and
4614 # force a clean recompute!
4615 for parent_column in ['parent_left', 'parent_right']:
4616 data.pop(parent_column, None)
4618 for v in self._inherits:
4619 del data[self._inherits[v]]
4622 def copy_translations(self, cr, uid, old_id, new_id, context=None):
4626 # avoid recursion through already copied records in case of circular relationship
4627 seen_map = context.setdefault('__copy_translations_seen',{})
4628 if old_id in seen_map.setdefault(self._name,[]):
4630 seen_map[self._name].append(old_id)
4632 trans_obj = self.pool.get('ir.translation')
4633 # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
4634 fields = self.fields_get(cr, uid, context=context)
4636 translation_records = []
4637 for field_name, field_def in fields.items():
4638 # we must recursively copy the translations for o2o and o2m
4639 if field_def['type'] in ('one2one', 'one2many'):
4640 target_obj = self.pool.get(field_def['relation'])
4641 old_record, new_record = self.read(cr, uid, [old_id, new_id], [field_name], context=context)
4642 # here we rely on the order of the ids to match the translations
4643 # as foreseen in copy_data()
4644 old_children = sorted(old_record[field_name])
4645 new_children = sorted(new_record[field_name])
4646 for (old_child, new_child) in zip(old_children, new_children):
4647 target_obj.copy_translations(cr, uid, old_child, new_child, context=context)
4648 # and for translatable fields we keep them for copy
4649 elif field_def.get('translate'):
4651 if field_name in self._columns:
4652 trans_name = self._name + "," + field_name
4653 elif field_name in self._inherit_fields:
4654 trans_name = self._inherit_fields[field_name][0] + "," + field_name
4656 trans_ids = trans_obj.search(cr, uid, [
4657 ('name', '=', trans_name),
4658 ('res_id', '=', old_id)
4660 translation_records.extend(trans_obj.read(cr, uid, trans_ids, context=context))
4662 for record in translation_records:
4664 record['res_id'] = new_id
4665 trans_obj.create(cr, uid, record, context=context)
4668 def copy(self, cr, uid, id, default=None, context=None):
4670 Duplicate record with given id updating it with default values
4672 :param cr: database cursor
4673 :param uid: current user id
4674 :param id: id of the record to copy
4675 :param default: dictionary of field values to override in the original values of the copied record, e.g: ``{'field_name': overriden_value, ...}``
4676 :type default: dictionary
4677 :param context: context arguments, like lang, time zone
4678 :type context: dictionary
4684 context = context.copy()
4685 data = self.copy_data(cr, uid, id, default, context)
4686 new_id = self.create(cr, uid, data, context)
4687 self.copy_translations(cr, uid, id, new_id, context)
4690 def exists(self, cr, uid, ids, context=None):
4691 if type(ids) in (int, long):
4693 query = 'SELECT count(1) FROM "%s"' % (self._table)
4694 cr.execute(query + "WHERE ID IN %s", (tuple(ids),))
4695 return cr.fetchone()[0] == len(ids)
4697 def check_recursion(self, cr, uid, ids, context=None, parent=None):
4698 warnings.warn("You are using deprecated %s.check_recursion(). Please use the '_check_recursion()' instead!" % \
4699 self._name, DeprecationWarning, stacklevel=3)
4700 assert parent is None or parent in self._columns or parent in self._inherit_fields,\
4701 "The 'parent' parameter passed to check_recursion() must be None or a valid field name"
4702 return self._check_recursion(cr, uid, ids, context, parent)
4704 def _check_recursion(self, cr, uid, ids, context=None, parent=None):
4706 Verifies that there is no loop in a hierarchical structure of records,
4707 by following the parent relationship using the **parent** field until a loop
4708 is detected or until a top-level record is found.
4710 :param cr: database cursor
4711 :param uid: current user id
4712 :param ids: list of ids of records to check
4713 :param parent: optional parent field name (default: ``self._parent_name = parent_id``)
4714 :return: **True** if the operation can proceed safely, or **False** if an infinite loop is detected.
4718 parent = self._parent_name
4720 query = 'SELECT distinct "%s" FROM "%s" WHERE id IN %%s' % (parent, self._table)
4723 for i in range(0, len(ids), cr.IN_MAX):
4724 sub_ids_parent = ids_parent[i:i+cr.IN_MAX]
4725 cr.execute(query, (tuple(sub_ids_parent),))
4726 ids_parent2.extend(filter(None, map(lambda x: x[0], cr.fetchall())))
4727 ids_parent = ids_parent2
4728 for i in ids_parent:
4733 def _get_xml_ids(self, cr, uid, ids, *args, **kwargs):
4734 """Find out the XML ID(s) of any database record.
4736 **Synopsis**: ``_get_xml_ids(cr, uid, ids) -> { 'id': ['module.xml_id'] }``
4738 :return: map of ids to the list of their fully qualified XML IDs
4739 (empty list when there's none).
4741 model_data_obj = self.pool.get('ir.model.data')
4742 data_ids = model_data_obj.search(cr, uid, [('model', '=', self._name), ('res_id', 'in', ids)])
4743 data_results = model_data_obj.read(cr, uid, data_ids, ['module', 'name', 'res_id'])
4746 # can't use dict.fromkeys() as the list would be shared!
4748 for record in data_results:
4749 result[record['res_id']].append('%(module)s.%(name)s' % record)
4752 def get_xml_id(self, cr, uid, ids, *args, **kwargs):
4753 """Find out the XML ID of any database record, if there
4754 is one. This method works as a possible implementation
4755 for a function field, to be able to add it to any
4756 model object easily, referencing it as ``osv.osv.get_xml_id``.
4758 When multiple XML IDs exist for a record, only one
4759 of them is returned (randomly).
4761 **Synopsis**: ``get_xml_id(cr, uid, ids) -> { 'id': 'module.xml_id' }``
4763 :return: map of ids to their fully qualified XML ID,
4764 defaulting to an empty string when there's none
4765 (to be usable as a function field).
4767 results = self._get_xml_ids(cr, uid, ids)
4768 for k, v in results.items():
4775 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: