Merge remote-tracking branch 'upstream/7.0' into 7.0-travis
[odoo/odoo.git] / openerp / osv / orm.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #
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.
11 #
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.
16 #
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/>.
19 #
20 ##############################################################################
21
22 #.apidoc title: Object Relational Mapping
23 #.apidoc module-mods: member-order: bysource
24
25 """
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
34      * Datas conversions
35      * Multi-level caching system
36      * 2 different inheritancies
37      * Fields:
38           - classicals (varchar, integer, boolean, ...)
39           - relations (one2many, many2one, many2many)
40           - functions
41
42 """
43
44 import babel.dates
45 import calendar
46 import collections
47 import copy
48 import datetime
49 import itertools
50 import logging
51 import operator
52 import pickle
53 import re
54 import simplejson
55 import time
56 import traceback
57 import types
58
59 import psycopg2
60 from lxml import etree
61
62 import fields
63 import openerp
64 import openerp.netsvc as netsvc
65 import openerp.tools as tools
66 from openerp.tools.config import config
67 from openerp.tools.misc import CountingStream
68 from openerp.tools.safe_eval import safe_eval as eval
69 from openerp.tools.translate import _
70 from openerp import SUPERUSER_ID
71 from query import Query
72
73 _logger = logging.getLogger(__name__)
74 _schema = logging.getLogger(__name__ + '.schema')
75
76 # List of etree._Element subclasses that we choose to ignore when parsing XML.
77 from openerp.tools import SKIPPED_ELEMENT_TYPES
78
79 regex_order = re.compile('^( *([a-z0-9_]+|"[a-z0-9_]+")( *desc| *asc)?( *, *|))+$', re.I)
80 regex_object_name = re.compile(r'^[a-z0-9_.]+$')
81
82 # TODO for trunk, raise the value to 1000
83 AUTOINIT_RECALCULATE_STORED_FIELDS = 40
84
85 def transfer_field_to_modifiers(field, modifiers):
86     default_values = {}
87     state_exceptions = {}
88     for attr in ('invisible', 'readonly', 'required'):
89         state_exceptions[attr] = []
90         default_values[attr] = bool(field.get(attr))
91     for state, modifs in (field.get("states",{})).items():
92         for modif in modifs:
93             if default_values[modif[0]] != modif[1]:
94                 state_exceptions[modif[0]].append(state)
95
96     for attr, default_value in default_values.items():
97         if state_exceptions[attr]:
98             modifiers[attr] = [("state", "not in" if default_value else "in", state_exceptions[attr])]
99         else:
100             modifiers[attr] = default_value
101
102
103 # Don't deal with groups, it is done by check_group().
104 # Need the context to evaluate the invisible attribute on tree views.
105 # For non-tree views, the context shouldn't be given.
106 def transfer_node_to_modifiers(node, modifiers, context=None, in_tree_view=False):
107     if node.get('attrs'):
108         modifiers.update(eval(node.get('attrs')))
109
110     if node.get('states'):
111         if 'invisible' in modifiers and isinstance(modifiers['invisible'], list):
112             # TODO combine with AND or OR, use implicit AND for now.
113             modifiers['invisible'].append(('state', 'not in', node.get('states').split(',')))
114         else:
115             modifiers['invisible'] = [('state', 'not in', node.get('states').split(','))]
116
117     for a in ('invisible', 'readonly', 'required'):
118         if node.get(a):
119             v = bool(eval(node.get(a), {'context': context or {}}))
120             if in_tree_view and a == 'invisible':
121                 # Invisible in a tree view has a specific meaning, make it a
122                 # new key in the modifiers attribute.
123                 modifiers['tree_invisible'] = v
124             elif v or (a not in modifiers or not isinstance(modifiers[a], list)):
125                 # Don't set the attribute to False if a dynamic value was
126                 # provided (i.e. a domain from attrs or states).
127                 modifiers[a] = v
128
129
130 def simplify_modifiers(modifiers):
131     for a in ('invisible', 'readonly', 'required'):
132         if a in modifiers and not modifiers[a]:
133             del modifiers[a]
134
135
136 def transfer_modifiers_to_node(modifiers, node):
137     if modifiers:
138         simplify_modifiers(modifiers)
139         node.set('modifiers', simplejson.dumps(modifiers))
140
141 def setup_modifiers(node, field=None, context=None, in_tree_view=False):
142     """ Processes node attributes and field descriptors to generate
143     the ``modifiers`` node attribute and set it on the provided node.
144
145     Alters its first argument in-place.
146
147     :param node: ``field`` node from an OpenERP view
148     :type node: lxml.etree._Element
149     :param dict field: field descriptor corresponding to the provided node
150     :param dict context: execution context used to evaluate node attributes
151     :param bool in_tree_view: triggers the ``tree_invisible`` code
152                               path (separate from ``invisible``): in
153                               tree view there are two levels of
154                               invisibility, cell content (a column is
155                               present but the cell itself is not
156                               displayed) with ``invisible`` and column
157                               invisibility (the whole column is
158                               hidden) with ``tree_invisible``.
159     :returns: nothing
160     """
161     modifiers = {}
162     if field is not None:
163         transfer_field_to_modifiers(field, modifiers)
164     transfer_node_to_modifiers(
165         node, modifiers, context=context, in_tree_view=in_tree_view)
166     transfer_modifiers_to_node(modifiers, node)
167
168 def test_modifiers(what, expected):
169     modifiers = {}
170     if isinstance(what, basestring):
171         node = etree.fromstring(what)
172         transfer_node_to_modifiers(node, modifiers)
173         simplify_modifiers(modifiers)
174         json = simplejson.dumps(modifiers)
175         assert json == expected, "%s != %s" % (json, expected)
176     elif isinstance(what, dict):
177         transfer_field_to_modifiers(what, modifiers)
178         simplify_modifiers(modifiers)
179         json = simplejson.dumps(modifiers)
180         assert json == expected, "%s != %s" % (json, expected)
181
182
183 # To use this test:
184 # import openerp
185 # openerp.osv.orm.modifiers_tests()
186 def modifiers_tests():
187     test_modifiers('<field name="a"/>', '{}')
188     test_modifiers('<field name="a" invisible="1"/>', '{"invisible": true}')
189     test_modifiers('<field name="a" readonly="1"/>', '{"readonly": true}')
190     test_modifiers('<field name="a" required="1"/>', '{"required": true}')
191     test_modifiers('<field name="a" invisible="0"/>', '{}')
192     test_modifiers('<field name="a" readonly="0"/>', '{}')
193     test_modifiers('<field name="a" required="0"/>', '{}')
194     test_modifiers('<field name="a" invisible="1" required="1"/>', '{"invisible": true, "required": true}') # TODO order is not guaranteed
195     test_modifiers('<field name="a" invisible="1" required="0"/>', '{"invisible": true}')
196     test_modifiers('<field name="a" invisible="0" required="1"/>', '{"required": true}')
197     test_modifiers("""<field name="a" attrs="{'invisible': [('b', '=', 'c')]}"/>""", '{"invisible": [["b", "=", "c"]]}')
198
199     # The dictionary is supposed to be the result of fields_get().
200     test_modifiers({}, '{}')
201     test_modifiers({"invisible": True}, '{"invisible": true}')
202     test_modifiers({"invisible": False}, '{}')
203
204
205 def check_object_name(name):
206     """ Check if the given name is a valid openerp object name.
207
208         The _name attribute in osv and osv_memory object is subject to
209         some restrictions. This function returns True or False whether
210         the given name is allowed or not.
211
212         TODO: this is an approximation. The goal in this approximation
213         is to disallow uppercase characters (in some places, we quote
214         table/column names and in other not, which leads to this kind
215         of errors:
216
217             psycopg2.ProgrammingError: relation "xxx" does not exist).
218
219         The same restriction should apply to both osv and osv_memory
220         objects for consistency.
221
222     """
223     if regex_object_name.match(name) is None:
224         return False
225     return True
226
227 def raise_on_invalid_object_name(name):
228     if not check_object_name(name):
229         msg = "The _name attribute %s is not valid." % name
230         _logger.error(msg)
231         raise except_orm('ValueError', msg)
232
233 POSTGRES_CONFDELTYPES = {
234     'RESTRICT': 'r',
235     'NO ACTION': 'a',
236     'CASCADE': 'c',
237     'SET NULL': 'n',
238     'SET DEFAULT': 'd',
239 }
240
241 def intersect(la, lb):
242     return filter(lambda x: x in lb, la)
243
244 def fix_import_export_id_paths(fieldname):
245     """
246     Fixes the id fields in import and exports, and splits field paths
247     on '/'.
248
249     :param str fieldname: name of the field to import/export
250     :return: split field name
251     :rtype: list of str
252     """
253     fixed_db_id = re.sub(r'([^/])\.id', r'\1/.id', fieldname)
254     fixed_external_id = re.sub(r'([^/]):id', r'\1/id', fixed_db_id)
255     return fixed_external_id.split('/')
256
257 class except_orm(Exception):
258     def __init__(self, name, value):
259         self.name = name
260         self.value = value
261         self.args = (name, value)
262
263 class BrowseRecordError(Exception):
264     pass
265
266 class browse_null(object):
267     """ Readonly python database object browser
268     """
269
270     def __init__(self):
271         self.id = False
272
273     def __getitem__(self, name):
274         return None
275
276     def __getattr__(self, name):
277         return None  # XXX: return self ?
278
279     def __int__(self):
280         return False
281
282     def __str__(self):
283         return ''
284
285     def __nonzero__(self):
286         return False
287
288     def __unicode__(self):
289         return u''
290
291
292 #
293 # TODO: execute an object method on browse_record_list
294 #
295 class browse_record_list(list):
296     """ Collection of browse objects
297
298         Such an instance will be returned when doing a ``browse([ids..])``
299         and will be iterable, yielding browse() objects
300     """
301
302     def __init__(self, lst, context=None):
303         if not context:
304             context = {}
305         super(browse_record_list, self).__init__(lst)
306         self.context = context
307
308
309 class browse_record(object):
310     """ An object that behaves like a row of an object's table.
311         It has attributes after the columns of the corresponding object.
312
313         Examples::
314
315             uobj = pool.get('res.users')
316             user_rec = uobj.browse(cr, uid, 104)
317             name = user_rec.name
318     """
319
320     def __init__(self, cr, uid, id, table, cache, context=None,
321                  list_class=browse_record_list, fields_process=None):
322         """
323         :param table: the browsed object (inherited from orm)
324         :param dict cache: a dictionary of model->field->data to be shared
325                            across browse objects, thus reducing the SQL
326                            read()s. It can speed up things a lot, but also be
327                            disastrous if not discarded after write()/unlink()
328                            operations
329         :param dict context: dictionary with an optional context
330         """
331         if fields_process is None:
332             fields_process = {}
333         if context is None:
334             context = {}
335         self._list_class = list_class
336         self._cr = cr
337         self._uid = uid
338         self._id = id
339         self._table = table # deprecated, use _model!
340         self._model = table
341         self._table_name = self._table._name
342         self.__logger = logging.getLogger('openerp.osv.orm.browse_record.' + self._table_name)
343         self._context = context
344         self._fields_process = fields_process
345
346         cache.setdefault(table._name, {})
347         self._data = cache[table._name]
348
349 #        if not (id and isinstance(id, (int, long,))):
350 #            raise BrowseRecordError(_('Wrong ID for the browse record, got %r, expected an integer.') % (id,))
351 #        if not table.exists(cr, uid, id, context):
352 #            raise BrowseRecordError(_('Object %s does not exists') % (self,))
353
354         if id not in self._data:
355             self._data[id] = {'id': id}
356
357         self._cache = cache
358
359     def __getitem__(self, name):
360         if name == 'id':
361             return self._id
362
363         if name not in self._data[self._id]:
364             # build the list of fields we will fetch
365
366             # fetch the definition of the field which was asked for
367             if name in self._table._columns:
368                 col = self._table._columns[name]
369             elif name in self._table._inherit_fields:
370                 col = self._table._inherit_fields[name][2]
371             elif hasattr(self._table, str(name)):
372                 attr = getattr(self._table, name)
373                 if isinstance(attr, (types.MethodType, types.LambdaType, types.FunctionType)):
374                     def function_proxy(*args, **kwargs):
375                         if 'context' not in kwargs and self._context:
376                             kwargs.update(context=self._context)
377                         return attr(self._cr, self._uid, [self._id], *args, **kwargs)
378                     return function_proxy
379                 else:
380                     return attr
381             else:
382                 error_msg = "Field '%s' does not exist in object '%s'" % (name, self)
383                 self.__logger.warning(error_msg)
384                 if self.__logger.isEnabledFor(logging.DEBUG):
385                     self.__logger.debug(''.join(traceback.format_stack()))
386                 raise KeyError(error_msg)
387
388             # if the field is a classic one or a many2one, we'll fetch all classic and many2one fields
389             if col._prefetch and not col.groups:
390                 # gen the list of "local" (ie not inherited) fields which are classic or many2one
391                 field_filter = lambda x: x[1]._classic_write and x[1]._prefetch and not x[1].groups
392                 fields_to_fetch = filter(field_filter, self._table._columns.items())
393                 # gen the list of inherited fields
394                 inherits = map(lambda x: (x[0], x[1][2]), self._table._inherit_fields.items())
395                 # complete the field list with the inherited fields which are classic or many2one
396                 fields_to_fetch += filter(field_filter, inherits)
397             # otherwise we fetch only that field
398             else:
399                 fields_to_fetch = [(name, col)]
400
401             ids = filter(lambda id: name not in self._data[id], self._data.keys())
402             # read the results
403             field_names = map(lambda x: x[0], fields_to_fetch)
404             try:
405                 field_values = self._table.read(self._cr, self._uid, ids, field_names, context=self._context, load="_classic_write")
406             except (openerp.exceptions.AccessError, except_orm):
407                 if len(ids) == 1:
408                     raise
409                 # prefetching attempt failed, perhaps we're violating ACL restrictions involuntarily
410                 _logger.info('Prefetching attempt for fields %s on %s failed for ids %s, re-trying just for id %s', field_names, self._model._name, ids, self._id)
411                 ids = [self._id]
412                 field_values = self._table.read(self._cr, self._uid, ids, field_names, context=self._context, load="_classic_write")
413
414             # TODO: improve this, very slow for reports
415             if self._fields_process:
416                 lang = self._context.get('lang', 'en_US') or 'en_US'
417                 lang_obj_ids = self.pool.get('res.lang').search(self._cr, self._uid, [('code', '=', lang)])
418                 if not lang_obj_ids:
419                     raise Exception(_('Language with code "%s" is not defined in your system !\nDefine it through the Administration menu.') % (lang,))
420                 lang_obj = self.pool.get('res.lang').browse(self._cr, self._uid, lang_obj_ids[0])
421
422                 for field_name, field_column in fields_to_fetch:
423                     if field_column._type in self._fields_process:
424                         for result_line in field_values:
425                             result_line[field_name] = self._fields_process[field_column._type](result_line[field_name])
426                             if result_line[field_name]:
427                                 result_line[field_name].set_value(self._cr, self._uid, result_line[field_name], self, field_column, lang_obj)
428
429             if not field_values:
430                 # Where did those ids come from? Perhaps old entries in ir_model_dat?
431                 _logger.warning("No field_values found for ids %s in %s", ids, self)
432                 raise KeyError('Field %s not found in %s'%(name, self))
433             # create browse records for 'remote' objects
434             for result_line in field_values:
435                 new_data = {}
436                 for field_name, field_column in fields_to_fetch:
437                     if field_column._type == 'many2one':
438                         if result_line[field_name]:
439                             obj = self._table.pool.get(field_column._obj)
440                             if isinstance(result_line[field_name], (list, tuple)):
441                                 value = result_line[field_name][0]
442                             else:
443                                 value = result_line[field_name]
444                             if value:
445                                 # FIXME: this happen when a _inherits object
446                                 #        overwrite a field of it parent. Need
447                                 #        testing to be sure we got the right
448                                 #        object and not the parent one.
449                                 if not isinstance(value, browse_record):
450                                     if obj is None:
451                                         # In some cases the target model is not available yet, so we must ignore it,
452                                         # which is safe in most cases, this value will just be loaded later when needed.
453                                         # This situation can be caused by custom fields that connect objects with m2o without
454                                         # respecting module dependencies, causing relationships to be connected to soon when
455                                         # the target is not loaded yet.
456                                         continue
457                                     new_data[field_name] = browse_record(self._cr,
458                                         self._uid, value, obj, self._cache,
459                                         context=self._context,
460                                         list_class=self._list_class,
461                                         fields_process=self._fields_process)
462                                 else:
463                                     new_data[field_name] = value
464                             else:
465                                 new_data[field_name] = browse_null()
466                         else:
467                             new_data[field_name] = browse_null()
468                     elif field_column._type in ('one2many', 'many2many') and len(result_line[field_name]):
469                         new_data[field_name] = self._list_class(
470                             (browse_record(self._cr, self._uid, id, self._table.pool.get(field_column._obj),
471                                            self._cache, context=self._context, list_class=self._list_class,
472                                            fields_process=self._fields_process)
473                                for id in result_line[field_name]),
474                             context=self._context)
475                     elif field_column._type == 'reference':
476                         if result_line[field_name]:
477                             if isinstance(result_line[field_name], browse_record):
478                                 new_data[field_name] = result_line[field_name]
479                             else:
480                                 ref_obj, ref_id = result_line[field_name].split(',')
481                                 ref_id = long(ref_id)
482                                 if ref_id:
483                                     obj = self._table.pool.get(ref_obj)
484                                     new_data[field_name] = browse_record(self._cr, self._uid, ref_id, obj, self._cache, context=self._context, list_class=self._list_class, fields_process=self._fields_process)
485                                 else:
486                                     new_data[field_name] = browse_null()
487                         else:
488                             new_data[field_name] = browse_null()
489                     else:
490                         new_data[field_name] = result_line[field_name]
491                 self._data[result_line['id']].update(new_data)
492
493         if not name in self._data[self._id]:
494             # How did this happen? Could be a missing model due to custom fields used too soon, see above.
495             self.__logger.error("Fields to fetch: %s, Field values: %s", field_names, field_values)
496             self.__logger.error("Cached: %s, Table: %s", self._data[self._id], self._table)
497             raise KeyError(_('Unknown attribute %s in %s ') % (name, self))
498         return self._data[self._id][name]
499
500     def __getattr__(self, name):
501         try:
502             return self[name]
503         except KeyError, e:
504             raise AttributeError(e)
505
506     def __contains__(self, name):
507         return (name in self._table._columns) or (name in self._table._inherit_fields) or hasattr(self._table, name)
508
509     def __iter__(self):
510         raise NotImplementedError("Iteration is not allowed on %s" % self)
511
512     def __hasattr__(self, name):
513         return name in self
514
515     def __int__(self):
516         return self._id
517
518     def __str__(self):
519         return "browse_record(%s, %d)" % (self._table_name, self._id)
520
521     def __eq__(self, other):
522         if not isinstance(other, browse_record):
523             return False
524         return (self._table_name, self._id) == (other._table_name, other._id)
525
526     def __ne__(self, other):
527         if not isinstance(other, browse_record):
528             return True
529         return (self._table_name, self._id) != (other._table_name, other._id)
530
531     # we need to define __unicode__ even though we've already defined __str__
532     # because we have overridden __getattr__
533     def __unicode__(self):
534         return unicode(str(self))
535
536     def __hash__(self):
537         return hash((self._table_name, self._id))
538
539     __repr__ = __str__
540
541     def refresh(self):
542         """Force refreshing this browse_record's data and all the data of the
543            records that belong to the same cache, by emptying the cache completely,
544            preserving only the record identifiers (for prefetching optimizations).
545         """
546         for model, model_cache in self._cache.iteritems():
547             # only preserve the ids of the records that were in the cache
548             cached_ids = dict([(i, {'id': i}) for i in model_cache.keys()])
549             self._cache[model].clear()
550             self._cache[model].update(cached_ids)
551
552 def pg_varchar(size=0):
553     """ Returns the VARCHAR declaration for the provided size:
554
555     * If no size (or an empty or negative size is provided) return an
556       'infinite' VARCHAR
557     * Otherwise return a VARCHAR(n)
558
559     :type int size: varchar size, optional
560     :rtype: str
561     """
562     if size:
563         if not isinstance(size, int):
564             raise TypeError("VARCHAR parameter should be an int, got %s"
565                             % type(size))
566         if size > 0:
567             return 'VARCHAR(%d)' % size
568     return 'VARCHAR'
569
570 FIELDS_TO_PGTYPES = {
571     fields.boolean: 'bool',
572     fields.integer: 'int4',
573     fields.text: 'text',
574     fields.html: 'text',
575     fields.date: 'date',
576     fields.datetime: 'timestamp',
577     fields.binary: 'bytea',
578     fields.many2one: 'int4',
579     fields.serialized: 'text',
580 }
581
582 def get_pg_type(f, type_override=None):
583     """
584     :param fields._column f: field to get a Postgres type for
585     :param type type_override: use the provided type for dispatching instead of the field's own type
586     :returns: (postgres_identification_type, postgres_type_specification)
587     :rtype: (str, str)
588     """
589     field_type = type_override or type(f)
590
591     if field_type in FIELDS_TO_PGTYPES:
592         pg_type =  (FIELDS_TO_PGTYPES[field_type], FIELDS_TO_PGTYPES[field_type])
593     elif issubclass(field_type, fields.float):
594         if f.digits:
595             pg_type = ('numeric', 'NUMERIC')
596         else:
597             pg_type = ('float8', 'DOUBLE PRECISION')
598     elif issubclass(field_type, (fields.char, fields.reference)):
599         pg_type = ('varchar', pg_varchar(f.size))
600     elif issubclass(field_type, fields.selection):
601         if (isinstance(f.selection, list) and isinstance(f.selection[0][0], int))\
602                 or getattr(f, 'size', None) == -1:
603             pg_type = ('int4', 'INTEGER')
604         else:
605             pg_type = ('varchar', pg_varchar(getattr(f, 'size', None)))
606     elif issubclass(field_type, fields.function):
607         if f._type == 'selection':
608             pg_type = ('varchar', pg_varchar())
609         else:
610             pg_type = get_pg_type(f, getattr(fields, f._type))
611     else:
612         _logger.warning('%s type not supported!', field_type)
613         pg_type = None
614
615     return pg_type
616
617
618 class MetaModel(type):
619     """ Metaclass for the Model.
620
621     This class is used as the metaclass for the Model class to discover
622     the models defined in a module (i.e. without instanciating them).
623     If the automatic discovery is not needed, it is possible to set the
624     model's _register attribute to False.
625
626     """
627
628     module_to_models = {}
629
630     def __init__(self, name, bases, attrs):
631         if not self._register:
632             self._register = True
633             super(MetaModel, self).__init__(name, bases, attrs)
634             return
635
636         # The (OpenERP) module name can be in the `openerp.addons` namespace
637         # or not. For instance module `sale` can be imported as
638         # `openerp.addons.sale` (the good way) or `sale` (for backward
639         # compatibility).
640         module_parts = self.__module__.split('.')
641         if len(module_parts) > 2 and module_parts[0] == 'openerp' and \
642             module_parts[1] == 'addons':
643             module_name = self.__module__.split('.')[2]
644         else:
645             module_name = self.__module__.split('.')[0]
646         if not hasattr(self, '_module'):
647             self._module = module_name
648
649         # Remember which models to instanciate for this module.
650         if not self._custom:
651             self.module_to_models.setdefault(self._module, []).append(self)
652
653
654 # Definition of log access columns, automatically added to models if
655 # self._log_access is True
656 LOG_ACCESS_COLUMNS = {
657     'create_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
658     'create_date': 'TIMESTAMP',
659     'write_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
660     'write_date': 'TIMESTAMP'
661 }
662 # special columns automatically created by the ORM
663 MAGIC_COLUMNS =  ['id'] + LOG_ACCESS_COLUMNS.keys()
664
665 class BaseModel(object):
666     """ Base class for OpenERP models.
667
668     OpenERP models are created by inheriting from this class' subclasses:
669
670         * Model: for regular database-persisted models
671         * TransientModel: for temporary data, stored in the database but automatically
672                           vaccuumed every so often
673         * AbstractModel: for abstract super classes meant to be shared by multiple
674                         _inheriting classes (usually Models or TransientModels)
675
676     The system will later instantiate the class once per database (on
677     which the class' module is installed).
678
679     To create a class that should not be instantiated, the _register class attribute
680     may be set to False.
681     """
682     __metaclass__ = MetaModel
683     _auto = True # create database backend
684     _register = False # Set to false if the model shouldn't be automatically discovered.
685     _name = None
686     _columns = {}
687     _constraints = []
688     _custom = False
689     _defaults = {}
690     _rec_name = None
691     _parent_name = 'parent_id'
692     _parent_store = False
693     _parent_order = False
694     _date_name = 'date'
695     _order = 'id'
696     _sequence = None
697     _description = None
698     _needaction = False
699
700     # dict of {field:method}, with method returning the (name_get of records, {id: fold})
701     # to include in the _read_group, if grouped on this field
702     _group_by_full = {}
703
704     # Transience
705     _transient = False # True in a TransientModel
706
707     # structure:
708     #  { 'parent_model': 'm2o_field', ... }
709     _inherits = {}
710
711     # Mapping from inherits'd field name to triple (m, r, f, n) where m is the
712     # model from which it is inherits'd, r is the (local) field towards m, f
713     # is the _column object itself, and n is the original (i.e. top-most)
714     # parent model.
715     # Example:
716     #  { 'field_name': ('parent_model', 'm2o_field_to_reach_parent',
717     #                   field_column_obj, origina_parent_model), ... }
718     _inherit_fields = {}
719
720     # Mapping field name/column_info object
721     # This is similar to _inherit_fields but:
722     # 1. includes self fields,
723     # 2. uses column_info instead of a triple.
724     _all_columns = {}
725
726     _table = None
727     _invalids = set()
728     _log_create = False
729     _sql_constraints = []
730     _protected = ['read', 'write', 'create', 'default_get', 'perm_read', 'unlink', 'fields_get', 'fields_view_get', 'search', 'name_get', 'distinct_field_get', 'name_search', 'copy', 'import_data', 'search_count', 'exists']
731
732     CONCURRENCY_CHECK_FIELD = '__last_update'
733
734     def log(self, cr, uid, id, message, secondary=False, context=None):
735         return _logger.warning("log() is deprecated. Please use OpenChatter notification system instead of the res.log mechanism.")
736
737     def view_init(self, cr, uid, fields_list, context=None):
738         """Override this method to do specific things when a view on the object is opened."""
739         pass
740
741     def _field_create(self, cr, context=None):
742         """ Create entries in ir_model_fields for all the model's fields.
743
744         If necessary, also create an entry in ir_model, and if called from the
745         modules loading scheme (by receiving 'module' in the context), also
746         create entries in ir_model_data (for the model and the fields).
747
748         - create an entry in ir_model (if there is not already one),
749         - create an entry in ir_model_data (if there is not already one, and if
750           'module' is in the context),
751         - update ir_model_fields with the fields found in _columns
752           (TODO there is some redundancy as _columns is updated from
753           ir_model_fields in __init__).
754
755         """
756         if context is None:
757             context = {}
758         cr.execute("SELECT id FROM ir_model WHERE model=%s", (self._name,))
759         if not cr.rowcount:
760             cr.execute('SELECT nextval(%s)', ('ir_model_id_seq',))
761             model_id = cr.fetchone()[0]
762             cr.execute("INSERT INTO ir_model (id,model, name, info,state) VALUES (%s, %s, %s, %s, %s)", (model_id, self._name, self._description, self.__doc__, 'base'))
763         else:
764             model_id = cr.fetchone()[0]
765         if 'module' in context:
766             name_id = 'model_'+self._name.replace('.', '_')
767             cr.execute('select * from ir_model_data where name=%s and module=%s', (name_id, context['module']))
768             if not cr.rowcount:
769                 cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, (now() at time zone 'UTC'), (now() at time zone 'UTC'), %s, %s, %s)", \
770                     (name_id, context['module'], 'ir.model', model_id)
771                 )
772
773         cr.execute("SELECT * FROM ir_model_fields WHERE model=%s", (self._name,))
774         cols = {}
775         for rec in cr.dictfetchall():
776             cols[rec['name']] = rec
777
778         ir_model_fields_obj = self.pool.get('ir.model.fields')
779
780         # sparse field should be created at the end, as it depends on its serialized field already existing
781         model_fields = sorted(self._columns.items(), key=lambda x: 1 if x[1]._type == 'sparse' else 0)
782         for (k, f) in model_fields:
783             vals = {
784                 'model_id': model_id,
785                 'model': self._name,
786                 'name': k,
787                 'field_description': f.string,
788                 'ttype': f._type,
789                 'relation': f._obj or '',
790                 'view_load': (f.view_load and 1) or 0,
791                 'select_level': tools.ustr(f.select or 0),
792                 'readonly': (f.readonly and 1) or 0,
793                 'required': (f.required and 1) or 0,
794                 'selectable': (f.selectable and 1) or 0,
795                 'translate': (f.translate and 1) or 0,
796                 'relation_field': f._fields_id if isinstance(f, fields.one2many) else '',
797                 'serialization_field_id': None,
798             }
799             if getattr(f, 'serialization_field', None):
800                 # resolve link to serialization_field if specified by name
801                 serialization_field_id = ir_model_fields_obj.search(cr, SUPERUSER_ID, [('model','=',vals['model']), ('name', '=', f.serialization_field)])
802                 if not serialization_field_id:
803                     raise except_orm(_('Error'), _("Serialization field `%s` not found for sparse field `%s`!") % (f.serialization_field, k))
804                 vals['serialization_field_id'] = serialization_field_id[0]
805
806             # When its a custom field,it does not contain f.select
807             if context.get('field_state', 'base') == 'manual':
808                 if context.get('field_name', '') == k:
809                     vals['select_level'] = context.get('select', '0')
810                 #setting value to let the problem NOT occur next time
811                 elif k in cols:
812                     vals['select_level'] = cols[k]['select_level']
813
814             if k not in cols:
815                 cr.execute('select nextval(%s)', ('ir_model_fields_id_seq',))
816                 id = cr.fetchone()[0]
817                 vals['id'] = id
818                 cr.execute("""INSERT INTO ir_model_fields (
819                     id, model_id, model, name, field_description, ttype,
820                     relation,view_load,state,select_level,relation_field, translate, serialization_field_id
821                 ) VALUES (
822                     %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s
823                 )""", (
824                     id, vals['model_id'], vals['model'], vals['name'], vals['field_description'], vals['ttype'],
825                      vals['relation'], bool(vals['view_load']), 'base',
826                     vals['select_level'], vals['relation_field'], bool(vals['translate']), vals['serialization_field_id']
827                 ))
828                 if 'module' in context:
829                     name1 = 'field_' + self._table + '_' + k
830                     cr.execute("select name from ir_model_data where name=%s", (name1,))
831                     if cr.fetchone():
832                         name1 = name1 + "_" + str(id)
833                     cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, (now() at time zone 'UTC'), (now() at time zone 'UTC'), %s, %s, %s)", \
834                         (name1, context['module'], 'ir.model.fields', id)
835                     )
836             else:
837                 for key, val in vals.items():
838                     if cols[k][key] != vals[key]:
839                         cr.execute('update ir_model_fields set field_description=%s where model=%s and name=%s', (vals['field_description'], vals['model'], vals['name']))
840                         cr.execute("""UPDATE ir_model_fields SET
841                             model_id=%s, field_description=%s, ttype=%s, relation=%s,
842                             view_load=%s, select_level=%s, readonly=%s ,required=%s, selectable=%s, relation_field=%s, translate=%s, serialization_field_id=%s
843                         WHERE
844                             model=%s AND name=%s""", (
845                                 vals['model_id'], vals['field_description'], vals['ttype'],
846                                 vals['relation'], bool(vals['view_load']),
847                                 vals['select_level'], bool(vals['readonly']), bool(vals['required']), bool(vals['selectable']), vals['relation_field'], bool(vals['translate']), vals['serialization_field_id'], vals['model'], vals['name']
848                             ))
849                         break
850
851     #
852     # Goal: try to apply inheritance at the instanciation level and
853     #       put objects in the pool var
854     #
855     @classmethod
856     def create_instance(cls, pool, cr):
857         """ Instanciate a given model.
858
859         This class method instanciates the class of some model (i.e. a class
860         deriving from osv or osv_memory). The class might be the class passed
861         in argument or, if it inherits from another class, a class constructed
862         by combining the two classes.
863
864         The ``attributes`` argument specifies which parent class attributes
865         have to be combined.
866
867         TODO: the creation of the combined class is repeated at each call of
868         this method. This is probably unnecessary.
869
870         """
871         attributes = ['_columns', '_defaults', '_inherits', '_constraints',
872             '_sql_constraints']
873
874         parent_names = getattr(cls, '_inherit', None)
875         if parent_names:
876             if isinstance(parent_names, (str, unicode)):
877                 name = cls._name or parent_names
878                 parent_names = [parent_names]
879             else:
880                 name = cls._name
881             if not name:
882                 raise TypeError('_name is mandatory in case of multiple inheritance')
883
884             for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]):
885                 parent_model = pool.get(parent_name)
886                 if not parent_model:
887                     raise TypeError('The model "%s" specifies an unexisting parent class "%s"\n'
888                         'You may need to add a dependency on the parent class\' module.' % (name, parent_name))
889                 if not getattr(cls, '_original_module', None) and name == parent_model._name:
890                     cls._original_module = parent_model._original_module
891                 parent_class = parent_model.__class__
892                 nattr = {}
893                 for s in attributes:
894                     new = copy.copy(getattr(parent_model, s, {}))
895                     if s == '_columns':
896                         # Don't _inherit custom fields.
897                         for c in new.keys():
898                             if new[c].manual:
899                                 del new[c]
900                     if hasattr(new, 'update'):
901                         new.update(cls.__dict__.get(s, {}))
902                     elif s=='_constraints':
903                         for c in cls.__dict__.get(s, []):
904                             exist = False
905                             for c2 in range(len(new)):
906                                 #For _constraints, we should check field and methods as well
907                                 if new[c2][2]==c[2] and (new[c2][0] == c[0] \
908                                         or getattr(new[c2][0],'__name__', True) == \
909                                             getattr(c[0],'__name__', False)):
910                                     # If new class defines a constraint with
911                                     # same function name, we let it override
912                                     # the old one.
913
914                                     new[c2] = c
915                                     exist = True
916                                     break
917                             if not exist:
918                                 new.append(c)
919                     else:
920                         new.extend(cls.__dict__.get(s, []))
921                     nattr[s] = new
922
923                 # Keep links to non-inherited constraints, e.g. useful when exporting translations
924                 nattr['_local_constraints'] = cls.__dict__.get('_constraints', [])
925                 nattr['_local_sql_constraints'] = cls.__dict__.get('_sql_constraints', [])
926
927                 cls = type(name, (cls, parent_class), dict(nattr, _register=False))
928         else:
929             cls._local_constraints = getattr(cls, '_constraints', [])
930             cls._local_sql_constraints = getattr(cls, '_sql_constraints', [])
931
932         if not getattr(cls, '_original_module', None):
933             cls._original_module = cls._module
934         obj = object.__new__(cls)
935
936         if hasattr(obj, '_columns'):
937             # float fields are registry-dependent (digit attribute). Duplicate them to avoid issues.
938             for c, f in obj._columns.items():
939                 if f._type == 'float':
940                     obj._columns[c] = copy.copy(f)
941
942         obj.__init__(pool, cr)
943         return obj
944
945     def __new__(cls):
946         """Register this model.
947
948         This doesn't create an instance but simply register the model
949         as being part of the module where it is defined.
950
951         """
952
953
954         # Set the module name (e.g. base, sale, accounting, ...) on the class.
955         module = cls.__module__.split('.')[0]
956         if not hasattr(cls, '_module'):
957             cls._module = module
958
959         # Record this class in the list of models to instantiate for this module,
960         # managed by the metaclass.
961         module_model_list = MetaModel.module_to_models.setdefault(cls._module, [])
962         if cls not in module_model_list:
963             if not cls._custom:
964                 module_model_list.append(cls)
965
966         # Since we don't return an instance here, the __init__
967         # method won't be called.
968         return None
969
970     def __init__(self, pool, cr):
971         """ Initialize a model and make it part of the given registry.
972
973         - copy the stored fields' functions in the osv_pool,
974         - update the _columns with the fields found in ir_model_fields,
975         - ensure there is a many2one for each _inherits'd parent,
976         - update the children's _columns,
977         - give a chance to each field to initialize itself.
978
979         """
980         pool.add(self._name, self)
981         self.pool = pool
982
983         if not self._name and not hasattr(self, '_inherit'):
984             name = type(self).__name__.split('.')[0]
985             msg = "The class %s has to have a _name attribute" % name
986
987             _logger.error(msg)
988             raise except_orm('ValueError', msg)
989
990         if not self._description:
991             self._description = self._name
992         if not self._table:
993             self._table = self._name.replace('.', '_')
994
995         if not hasattr(self, '_log_access'):
996             # If _log_access is not specified, it is the same value as _auto.
997             self._log_access = getattr(self, "_auto", True)
998
999         self._columns = self._columns.copy()
1000         for store_field in self._columns:
1001             f = self._columns[store_field]
1002             if hasattr(f, 'digits_change'):
1003                 f.digits_change(cr)
1004             def not_this_field(stored_func):
1005                 x, y, z, e, f, l = stored_func
1006                 return x != self._name or y != store_field
1007             self.pool._store_function[self._name] = filter(not_this_field, self.pool._store_function.get(self._name, []))
1008             if not isinstance(f, fields.function):
1009                 continue
1010             if not f.store:
1011                 continue
1012             sm = f.store
1013             if sm is True:
1014                 sm = {self._name: (lambda self, cr, uid, ids, c={}: ids, None, 10, None)}
1015             for object, aa in sm.items():
1016                 if len(aa) == 4:
1017                     (fnct, fields2, order, length) = aa
1018                 elif len(aa) == 3:
1019                     (fnct, fields2, order) = aa
1020                     length = None
1021                 else:
1022                     raise except_orm('Error',
1023                         ('Invalid function definition %s in object %s !\nYou must use the definition: store={object:(fnct, fields, priority, time length)}.' % (store_field, self._name)))
1024                 self.pool._store_function.setdefault(object, [])
1025                 t = (self._name, store_field, fnct, tuple(fields2) if fields2 else None, order, length)
1026                 if not t in self.pool._store_function[object]:
1027                     self.pool._store_function[object].append((self._name, store_field, fnct, tuple(fields2) if fields2 else None, order, length))
1028                     self.pool._store_function[object].sort(lambda x, y: cmp(x[4], y[4]))
1029
1030         for (key, _, msg) in self._sql_constraints:
1031             self.pool._sql_error[self._table+'_'+key] = msg
1032
1033         # Load manual fields
1034
1035         # Check the query is already done for all modules of if we need to
1036         # do it ourselves.
1037         if self.pool.fields_by_model is not None:
1038             manual_fields = self.pool.fields_by_model.get(self._name, [])
1039         else:
1040             cr.execute('SELECT * FROM ir_model_fields WHERE model=%s AND state=%s', (self._name, 'manual'))
1041             manual_fields = cr.dictfetchall()
1042         for field in manual_fields:
1043             if field['name'] in self._columns:
1044                 continue
1045             attrs = {
1046                 'string': field['field_description'],
1047                 'required': bool(field['required']),
1048                 'readonly': bool(field['readonly']),
1049                 'domain': eval(field['domain']) if field['domain'] else None,
1050                 'size': field['size'] or None,
1051                 'ondelete': field['on_delete'],
1052                 'translate': (field['translate']),
1053                 'manual': True,
1054                 #'select': int(field['select_level'])
1055             }
1056
1057             if field['serialization_field_id']:
1058                 cr.execute('SELECT name FROM ir_model_fields WHERE id=%s', (field['serialization_field_id'],))
1059                 attrs.update({'serialization_field': cr.fetchone()[0], 'type': field['ttype']})
1060                 if field['ttype'] in ['many2one', 'one2many', 'many2many']:
1061                     attrs.update({'relation': field['relation']})
1062                 self._columns[field['name']] = fields.sparse(**attrs)
1063             elif field['ttype'] == 'selection':
1064                 self._columns[field['name']] = fields.selection(eval(field['selection']), **attrs)
1065             elif field['ttype'] == 'reference':
1066                 self._columns[field['name']] = fields.reference(selection=eval(field['selection']), **attrs)
1067             elif field['ttype'] == 'many2one':
1068                 self._columns[field['name']] = fields.many2one(field['relation'], **attrs)
1069             elif field['ttype'] == 'one2many':
1070                 self._columns[field['name']] = fields.one2many(field['relation'], field['relation_field'], **attrs)
1071             elif field['ttype'] == 'many2many':
1072                 _rel1 = field['relation'].replace('.', '_')
1073                 _rel2 = field['model'].replace('.', '_')
1074                 _rel_name = 'x_%s_%s_%s_rel' % (_rel1, _rel2, field['name'])
1075                 self._columns[field['name']] = fields.many2many(field['relation'], _rel_name, 'id1', 'id2', **attrs)
1076             else:
1077                 self._columns[field['name']] = getattr(fields, field['ttype'])(**attrs)
1078
1079         self._inherits_check()
1080         self._inherits_reload()
1081         if not self._sequence:
1082             self._sequence = self._table + '_id_seq'
1083         for k in self._defaults:
1084             assert (k in self._columns) or (k in self._inherit_fields), 'Default function defined in %s but field %s does not exist !' % (self._name, k,)
1085         for f in self._columns:
1086             self._columns[f].restart()
1087
1088         # Transience
1089         if self.is_transient():
1090             self._transient_check_count = 0
1091             self._transient_max_count = config.get('osv_memory_count_limit')
1092             self._transient_max_hours = config.get('osv_memory_age_limit')
1093             assert self._log_access, "TransientModels must have log_access turned on, "\
1094                                      "in order to implement their access rights policy"
1095
1096         # Validate rec_name
1097         if self._rec_name is not None:
1098             assert self._rec_name in self._all_columns.keys() + ['id'], "Invalid rec_name %s for model %s" % (self._rec_name, self._name)
1099         else:
1100             self._rec_name = 'name'
1101
1102
1103     def __export_row(self, cr, uid, row, fields, context=None):
1104         if context is None:
1105             context = {}
1106
1107         def check_type(field_type):
1108             if field_type == 'float':
1109                 return 0.0
1110             elif field_type == 'integer':
1111                 return 0
1112             elif field_type == 'boolean':
1113                 return 'False'
1114             return ''
1115
1116         def selection_field(in_field):
1117             col_obj = self.pool.get(in_field.keys()[0])
1118             if f[i] in col_obj._columns.keys():
1119                 return  col_obj._columns[f[i]]
1120             elif f[i] in col_obj._inherits.keys():
1121                 selection_field(col_obj._inherits)
1122             else:
1123                 return False
1124
1125         def _get_xml_id(self, cr, uid, r):
1126             model_data = self.pool.get('ir.model.data')
1127             data_ids = model_data.search(cr, uid, [('model', '=', r._model._name), ('res_id', '=', r['id'])])
1128             if len(data_ids):
1129                 d = model_data.read(cr, uid, data_ids, ['name', 'module'])[0]
1130                 if d['module']:
1131                     r = '%s.%s' % (d['module'], d['name'])
1132                 else:
1133                     r = d['name']
1134             else:
1135                 postfix = 0
1136                 while True:
1137                     n = r._model._table+'_'+str(r['id']) + (postfix and ('_'+str(postfix)) or '' )
1138                     if not model_data.search(cr, uid, [('name', '=', n)]):
1139                         break
1140                     postfix += 1
1141                 model_data.create(cr, SUPERUSER_ID, {
1142                     'name': n,
1143                     'model': r._model._name,
1144                     'res_id': r['id'],
1145                     'module': '__export__',
1146                 })
1147                 r = '__export__.'+n
1148             return r
1149
1150         lines = []
1151         data = map(lambda x: '', range(len(fields)))
1152         done = []
1153         for fpos in range(len(fields)):
1154             f = fields[fpos]
1155             if f:
1156                 r = row
1157                 i = 0
1158                 while i < len(f):
1159                     cols = False
1160                     if f[i] == '.id':
1161                         r = r['id']
1162                     elif f[i] == 'id':
1163                         r = _get_xml_id(self, cr, uid, r)
1164                     else:
1165                         r = r[f[i]]
1166                         # To display external name of selection field when its exported
1167                         if f[i] in self._columns.keys():
1168                             cols = self._columns[f[i]]
1169                         elif f[i] in self._inherit_fields.keys():
1170                             cols = selection_field(self._inherits)
1171                         if cols and cols._type == 'selection':
1172                             sel_list = cols.selection
1173                             if r and type(sel_list) == type([]):
1174                                 r = [x[1] for x in sel_list if r==x[0]]
1175                                 r = r and r[0] or False
1176                     if not r:
1177                         if f[i] in self._columns:
1178                             r = check_type(self._columns[f[i]]._type)
1179                         elif f[i] in self._inherit_fields:
1180                             r = check_type(self._inherit_fields[f[i]][2]._type)
1181                         data[fpos] = r or False
1182                         break
1183                     if isinstance(r, (browse_record_list, list)):
1184                         first = True
1185                         fields2 = map(lambda x: (x[:i+1]==f[:i+1] and x[i+1:]) \
1186                                 or [], fields)
1187                         if fields2 in done:
1188                             if [x for x in fields2 if x]:
1189                                 break
1190                         done.append(fields2)
1191                         if cols and cols._type=='many2many' and len(fields[fpos])>(i+1) and (fields[fpos][i+1]=='id'):
1192                             data[fpos] = ','.join([_get_xml_id(self, cr, uid, x) for x in r])
1193                             break
1194
1195                         for row2 in r:
1196                             lines2 = row2._model.__export_row(cr, uid, row2, fields2,
1197                                     context)
1198                             if first:
1199                                 for fpos2 in range(len(fields)):
1200                                     if lines2 and lines2[0][fpos2]:
1201                                         data[fpos2] = lines2[0][fpos2]
1202                                 if not data[fpos]:
1203                                     dt = ''
1204                                     for rr in r:
1205                                         name_relation = self.pool.get(rr._table_name)._rec_name
1206                                         if isinstance(rr[name_relation], browse_record):
1207                                             rr = rr[name_relation]
1208                                         rr_name = self.pool.get(rr._table_name).name_get(cr, uid, [rr.id], context=context)
1209                                         rr_name = rr_name and rr_name[0] and rr_name[0][1] or ''
1210                                         dt += tools.ustr(rr_name or '') + ','
1211                                     data[fpos] = dt[:-1]
1212                                     break
1213                                 lines += lines2[1:]
1214                                 first = False
1215                             else:
1216                                 lines += lines2
1217                         break
1218                     i += 1
1219                 if i == len(f):
1220                     if isinstance(r, browse_record):
1221                         r = self.pool.get(r._table_name).name_get(cr, uid, [r.id], context=context)
1222                         r = r and r[0] and r[0][1] or ''
1223                     data[fpos] = tools.ustr(r or '')
1224         return [data] + lines
1225
1226     def export_data(self, cr, uid, ids, fields_to_export, context=None):
1227         """
1228         Export fields for selected objects
1229
1230         :param cr: database cursor
1231         :param uid: current user id
1232         :param ids: list of ids
1233         :param fields_to_export: list of fields
1234         :param context: context arguments, like lang, time zone
1235         :rtype: dictionary with a *datas* matrix
1236
1237         This method is used when exporting data via client menu
1238
1239         """
1240         if context is None:
1241             context = {}
1242         cols = self._columns.copy()
1243         for f in self._inherit_fields:
1244             cols.update({f: self._inherit_fields[f][2]})
1245         fields_to_export = map(fix_import_export_id_paths, fields_to_export)
1246         datas = []
1247         for row in self.browse(cr, uid, ids, context):
1248             datas += self.__export_row(cr, uid, row, fields_to_export, context)
1249         return {'datas': datas}
1250
1251     def import_data(self, cr, uid, fields, datas, mode='init', current_module='', noupdate=False, context=None, filename=None):
1252         """
1253         .. deprecated:: 7.0
1254             Use :meth:`~load` instead
1255
1256         Import given data in given module
1257
1258         This method is used when importing data via client menu.
1259
1260         Example of fields to import for a sale.order::
1261
1262             .id,                         (=database_id)
1263             partner_id,                  (=name_search)
1264             order_line/.id,              (=database_id)
1265             order_line/name,
1266             order_line/product_id/id,    (=xml id)
1267             order_line/price_unit,
1268             order_line/product_uom_qty,
1269             order_line/product_uom/id    (=xml_id)
1270
1271         This method returns a 4-tuple with the following structure::
1272
1273             (return_code, errored_resource, error_message, unused)
1274
1275         * The first item is a return code, it is ``-1`` in case of
1276           import error, or the last imported row number in case of success
1277         * The second item contains the record data dict that failed to import
1278           in case of error, otherwise it's 0
1279         * The third item contains an error message string in case of error,
1280           otherwise it's 0
1281         * The last item is currently unused, with no specific semantics
1282
1283         :param fields: list of fields to import
1284         :param datas: data to import
1285         :param mode: 'init' or 'update' for record creation
1286         :param current_module: module name
1287         :param noupdate: flag for record creation
1288         :param filename: optional file to store partial import state for recovery
1289         :returns: 4-tuple in the form (return_code, errored_resource, error_message, unused)
1290         :rtype: (int, dict or 0, str or 0, str or 0)
1291         """
1292         context = dict(context) if context is not None else {}
1293         context['_import_current_module'] = current_module
1294
1295         fields = map(fix_import_export_id_paths, fields)
1296         ir_model_data_obj = self.pool.get('ir.model.data')
1297
1298         def log(m):
1299             if m['type'] == 'error':
1300                 raise Exception(m['message'])
1301
1302         if config.get('import_partial') and filename:
1303             with open(config.get('import_partial'), 'rb') as partial_import_file:
1304                 data = pickle.load(partial_import_file)
1305                 position = data.get(filename, 0)
1306
1307         position = 0
1308         try:
1309             for res_id, xml_id, res, info in self._convert_records(cr, uid,
1310                             self._extract_records(cr, uid, fields, datas,
1311                                                   context=context, log=log),
1312                             context=context, log=log):
1313                 ir_model_data_obj._update(cr, uid, self._name,
1314                      current_module, res, mode=mode, xml_id=xml_id,
1315                      noupdate=noupdate, res_id=res_id, context=context)
1316                 position = info.get('rows', {}).get('to', 0) + 1
1317                 if config.get('import_partial') and filename and (not (position%100)):
1318                     with open(config.get('import_partial'), 'rb') as partial_import:
1319                         data = pickle.load(partial_import)
1320                     data[filename] = position
1321                     with open(config.get('import_partial'), 'wb') as partial_import:
1322                         pickle.dump(data, partial_import)
1323                     if context.get('defer_parent_store_computation'):
1324                         self._parent_store_compute(cr)
1325                     cr.commit()
1326         except Exception, e:
1327             cr.rollback()
1328             return -1, {}, 'Line %d : %s' % (position + 1, tools.ustr(e)), ''
1329
1330         if context.get('defer_parent_store_computation'):
1331             self._parent_store_compute(cr)
1332         return position, 0, 0, 0
1333
1334     def load(self, cr, uid, fields, data, context=None):
1335         """
1336         Attempts to load the data matrix, and returns a list of ids (or
1337         ``False`` if there was an error and no id could be generated) and a
1338         list of messages.
1339
1340         The ids are those of the records created and saved (in database), in
1341         the same order they were extracted from the file. They can be passed
1342         directly to :meth:`~read`
1343
1344         :param fields: list of fields to import, at the same index as the corresponding data
1345         :type fields: list(str)
1346         :param data: row-major matrix of data to import
1347         :type data: list(list(str))
1348         :param dict context:
1349         :returns: {ids: list(int)|False, messages: [Message]}
1350         """
1351         cr.execute('SAVEPOINT model_load')
1352         messages = []
1353
1354         fields = map(fix_import_export_id_paths, fields)
1355         ModelData = self.pool['ir.model.data'].clear_caches()
1356
1357         fg = self.fields_get(cr, uid, context=context)
1358
1359         mode = 'init'
1360         current_module = ''
1361         noupdate = False
1362
1363         ids = []
1364         for id, xid, record, info in self._convert_records(cr, uid,
1365                 self._extract_records(cr, uid, fields, data,
1366                                       context=context, log=messages.append),
1367                 context=context, log=messages.append):
1368             try:
1369                 cr.execute('SAVEPOINT model_load_save')
1370             except psycopg2.InternalError, e:
1371                 # broken transaction, exit and hope the source error was
1372                 # already logged
1373                 if not any(message['type'] == 'error' for message in messages):
1374                     messages.append(dict(info, type='error',message=
1375                         u"Unknown database error: '%s'" % e))
1376                 break
1377             try:
1378                 ids.append(ModelData._update(cr, uid, self._name,
1379                      current_module, record, mode=mode, xml_id=xid,
1380                      noupdate=noupdate, res_id=id, context=context))
1381                 cr.execute('RELEASE SAVEPOINT model_load_save')
1382             except psycopg2.Warning, e:
1383                 messages.append(dict(info, type='warning', message=str(e)))
1384                 cr.execute('ROLLBACK TO SAVEPOINT model_load_save')
1385             except psycopg2.Error, e:
1386                 messages.append(dict(
1387                     info, type='error',
1388                     **PGERROR_TO_OE[e.pgcode](self, fg, info, e)))
1389                 # Failed to write, log to messages, rollback savepoint (to
1390                 # avoid broken transaction) and keep going
1391                 cr.execute('ROLLBACK TO SAVEPOINT model_load_save')
1392         if any(message['type'] == 'error' for message in messages):
1393             cr.execute('ROLLBACK TO SAVEPOINT model_load')
1394             ids = False
1395         return {'ids': ids, 'messages': messages}
1396     def _extract_records(self, cr, uid, fields_, data,
1397                          context=None, log=lambda a: None):
1398         """ Generates record dicts from the data sequence.
1399
1400         The result is a generator of dicts mapping field names to raw
1401         (unconverted, unvalidated) values.
1402
1403         For relational fields, if sub-fields were provided the value will be
1404         a list of sub-records
1405
1406         The following sub-fields may be set on the record (by key):
1407         * None is the name_get for the record (to use with name_create/name_search)
1408         * "id" is the External ID for the record
1409         * ".id" is the Database ID for the record
1410         """
1411         columns = dict((k, v.column) for k, v in self._all_columns.iteritems())
1412         # Fake columns to avoid special cases in extractor
1413         columns[None] = fields.char('rec_name')
1414         columns['id'] = fields.char('External ID')
1415         columns['.id'] = fields.integer('Database ID')
1416
1417         # m2o fields can't be on multiple lines so exclude them from the
1418         # is_relational field rows filter, but special-case it later on to
1419         # be handled with relational fields (as it can have subfields)
1420         is_relational = lambda field: columns[field]._type in ('one2many', 'many2many', 'many2one')
1421         get_o2m_values = itemgetter_tuple(
1422             [index for index, field in enumerate(fields_)
1423                   if columns[field[0]]._type == 'one2many'])
1424         get_nono2m_values = itemgetter_tuple(
1425             [index for index, field in enumerate(fields_)
1426                   if columns[field[0]]._type != 'one2many'])
1427         # Checks if the provided row has any non-empty non-relational field
1428         def only_o2m_values(row, f=get_nono2m_values, g=get_o2m_values):
1429             return any(g(row)) and not any(f(row))
1430
1431         index = 0
1432         while True:
1433             if index >= len(data): return
1434
1435             row = data[index]
1436             # copy non-relational fields to record dict
1437             record = dict((field[0], value)
1438                 for field, value in itertools.izip(fields_, row)
1439                 if not is_relational(field[0]))
1440
1441             # Get all following rows which have relational values attached to
1442             # the current record (no non-relational values)
1443             record_span = itertools.takewhile(
1444                 only_o2m_values, itertools.islice(data, index + 1, None))
1445             # stitch record row back on for relational fields
1446             record_span = list(itertools.chain([row], record_span))
1447             for relfield in set(
1448                     field[0] for field in fields_
1449                              if is_relational(field[0])):
1450                 column = columns[relfield]
1451                 # FIXME: how to not use _obj without relying on fields_get?
1452                 Model = self.pool[column._obj]
1453
1454                 # get only cells for this sub-field, should be strictly
1455                 # non-empty, field path [None] is for name_get column
1456                 indices, subfields = zip(*((index, field[1:] or [None])
1457                                            for index, field in enumerate(fields_)
1458                                            if field[0] == relfield))
1459
1460                 # return all rows which have at least one value for the
1461                 # subfields of relfield
1462                 relfield_data = filter(any, map(itemgetter_tuple(indices), record_span))
1463                 record[relfield] = [subrecord
1464                     for subrecord, _subinfo in Model._extract_records(
1465                         cr, uid, subfields, relfield_data,
1466                         context=context, log=log)]
1467
1468             yield record, {'rows': {
1469                 'from': index,
1470                 'to': index + len(record_span) - 1
1471             }}
1472             index += len(record_span)
1473     def _convert_records(self, cr, uid, records,
1474                          context=None, log=lambda a: None):
1475         """ Converts records from the source iterable (recursive dicts of
1476         strings) into forms which can be written to the database (via
1477         self.create or (ir.model.data)._update)
1478
1479         :returns: a list of triplets of (id, xid, record)
1480         :rtype: list((int|None, str|None, dict))
1481         """
1482         if context is None: context = {}
1483         Converter = self.pool['ir.fields.converter']
1484         columns = dict((k, v.column) for k, v in self._all_columns.iteritems())
1485         Translation = self.pool['ir.translation']
1486         field_names = dict(
1487             (f, (Translation._get_source(cr, uid, self._name + ',' + f, 'field',
1488                                          context.get('lang'))
1489                  or column.string))
1490             for f, column in columns.iteritems())
1491
1492         convert = Converter.for_model(cr, uid, self, context=context)
1493
1494         def _log(base, field, exception):
1495             type = 'warning' if isinstance(exception, Warning) else 'error'
1496             # logs the logical (not human-readable) field name for automated
1497             # processing of response, but injects human readable in message
1498             record = dict(base, type=type, field=field,
1499                           message=unicode(exception.args[0]) % base)
1500             if len(exception.args) > 1 and exception.args[1]:
1501                 record.update(exception.args[1])
1502             log(record)
1503
1504         stream = CountingStream(records)
1505         for record, extras in stream:
1506             dbid = False
1507             xid = False
1508             # name_get/name_create
1509             if None in record: pass
1510             # xid
1511             if 'id' in record:
1512                 xid = record['id']
1513             # dbid
1514             if '.id' in record:
1515                 try:
1516                     dbid = int(record['.id'])
1517                 except ValueError:
1518                     # in case of overridden id column
1519                     dbid = record['.id']
1520                 if not self.search(cr, uid, [('id', '=', dbid)], context=context):
1521                     log(dict(extras,
1522                         type='error',
1523                         record=stream.index,
1524                         field='.id',
1525                         message=_(u"Unknown database identifier '%s'") % dbid))
1526                     dbid = False
1527
1528             converted = convert(record, lambda field, err:\
1529                 _log(dict(extras, record=stream.index, field=field_names[field]), field, err))
1530
1531             yield dbid, xid, converted, dict(extras, record=stream.index)
1532
1533     def get_invalid_fields(self, cr, uid):
1534         return list(self._invalids)
1535
1536     def _validate(self, cr, uid, ids, context=None):
1537         context = context or {}
1538         lng = context.get('lang')
1539         trans = self.pool.get('ir.translation')
1540         error_msgs = []
1541         for constraint in self._constraints:
1542             fun, msg, fields = constraint
1543             # We don't pass around the context here: validation code
1544             # must always yield the same results.
1545             if not fun(self, cr, uid, ids):
1546                 # Check presence of __call__ directly instead of using
1547                 # callable() because it will be deprecated as of Python 3.0
1548                 if hasattr(msg, '__call__'):
1549                     tmp_msg = msg(self, cr, uid, ids, context=context)
1550                     if isinstance(tmp_msg, tuple):
1551                         tmp_msg, params = tmp_msg
1552                         translated_msg = tmp_msg % params
1553                     else:
1554                         translated_msg = tmp_msg
1555                 else:
1556                     translated_msg = trans._get_source(cr, uid, self._name, 'constraint', lng, msg)
1557                 error_msgs.append(
1558                         _("Error occurred while validating the field(s) %s: %s") % (', '.join(fields), translated_msg)
1559                 )
1560                 self._invalids.update(fields)
1561         if error_msgs:
1562             raise except_orm('ValidateError', '\n'.join(error_msgs))
1563         else:
1564             self._invalids.clear()
1565
1566     def default_get(self, cr, uid, fields_list, context=None):
1567         """
1568         Returns default values for the fields in fields_list.
1569
1570         :param fields_list: list of fields to get the default values for (example ['field1', 'field2',])
1571         :type fields_list: list
1572         :param context: optional context dictionary - it may contains keys for specifying certain options
1573                         like ``context_lang`` (language) or ``context_tz`` (timezone) to alter the results of the call.
1574                         It may contain keys in the form ``default_XXX`` (where XXX is a field name), to set
1575                         or override a default value for a field.
1576                         A special ``bin_size`` boolean flag may also be passed in the context to request the
1577                         value of all fields.binary columns to be returned as the size of the binary instead of its
1578                         contents. This can also be selectively overriden by passing a field-specific flag
1579                         in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field.
1580                         Note: The ``bin_size_XXX`` form is new in OpenERP v6.0.
1581         :return: dictionary of the default values (set on the object model class, through user preferences, or in the context)
1582         """
1583         # trigger view init hook
1584         self.view_init(cr, uid, fields_list, context)
1585
1586         if not context:
1587             context = {}
1588         defaults = {}
1589
1590         # get the default values for the inherited fields
1591         for t in self._inherits.keys():
1592             defaults.update(self.pool.get(t).default_get(cr, uid, fields_list,
1593                 context))
1594
1595         # get the default values defined in the object
1596         for f in fields_list:
1597             if f in self._defaults:
1598                 if callable(self._defaults[f]):
1599                     defaults[f] = self._defaults[f](self, cr, uid, context)
1600                 else:
1601                     defaults[f] = self._defaults[f]
1602
1603             fld_def = ((f in self._columns) and self._columns[f]) \
1604                     or ((f in self._inherit_fields) and self._inherit_fields[f][2]) \
1605                     or False
1606
1607             if isinstance(fld_def, fields.property):
1608                 property_obj = self.pool.get('ir.property')
1609                 prop_value = property_obj.get(cr, uid, f, self._name, context=context)
1610                 if prop_value:
1611                     if isinstance(prop_value, (browse_record, browse_null)):
1612                         defaults[f] = prop_value.id
1613                     else:
1614                         defaults[f] = prop_value
1615                 else:
1616                     if f not in defaults:
1617                         defaults[f] = False
1618
1619         # get the default values set by the user and override the default
1620         # values defined in the object
1621         ir_values_obj = self.pool.get('ir.values')
1622         res = ir_values_obj.get(cr, uid, 'default', False, [self._name])
1623         for id, field, field_value in res:
1624             if field in fields_list:
1625                 fld_def = (field in self._columns) and self._columns[field] or self._inherit_fields[field][2]
1626                 if fld_def._type == 'many2one':
1627                     obj = self.pool.get(fld_def._obj)
1628                     if not obj.search(cr, uid, [('id', '=', field_value or False)]):
1629                         continue
1630                 if fld_def._type == 'many2many':
1631                     obj = self.pool.get(fld_def._obj)
1632                     field_value2 = []
1633                     for i in range(len(field_value or [])):
1634                         if not obj.search(cr, uid, [('id', '=',
1635                             field_value[i])]):
1636                             continue
1637                         field_value2.append(field_value[i])
1638                     field_value = field_value2
1639                 if fld_def._type == 'one2many':
1640                     obj = self.pool.get(fld_def._obj)
1641                     field_value2 = []
1642                     for i in range(len(field_value or [])):
1643                         field_value2.append({})
1644                         for field2 in field_value[i]:
1645                             if field2 in obj._columns.keys() and obj._columns[field2]._type == 'many2one':
1646                                 obj2 = self.pool.get(obj._columns[field2]._obj)
1647                                 if not obj2.search(cr, uid,
1648                                         [('id', '=', field_value[i][field2])]):
1649                                     continue
1650                             elif field2 in obj._inherit_fields.keys() and obj._inherit_fields[field2][2]._type == 'many2one':
1651                                 obj2 = self.pool.get(obj._inherit_fields[field2][2]._obj)
1652                                 if not obj2.search(cr, uid,
1653                                         [('id', '=', field_value[i][field2])]):
1654                                     continue
1655                             # TODO add test for many2many and one2many
1656                             field_value2[i][field2] = field_value[i][field2]
1657                     field_value = field_value2
1658                 defaults[field] = field_value
1659
1660         # get the default values from the context
1661         for key in context or {}:
1662             if key.startswith('default_') and (key[8:] in fields_list):
1663                 defaults[key[8:]] = context[key]
1664         return defaults
1665
1666     def fields_get_keys(self, cr, user, context=None):
1667         res = self._columns.keys()
1668         # TODO I believe this loop can be replace by
1669         # res.extend(self._inherit_fields.key())
1670         for parent in self._inherits:
1671             res.extend(self.pool.get(parent).fields_get_keys(cr, user, context))
1672         return res
1673
1674     def _rec_name_fallback(self, cr, uid, context=None):
1675         rec_name = self._rec_name
1676         if rec_name not in self._columns:
1677             rec_name = self._columns.keys()[0] if len(self._columns.keys()) > 0 else "id"
1678         return rec_name
1679
1680     #
1681     # Overload this method if you need a window title which depends on the context
1682     #
1683     def view_header_get(self, cr, user, view_id=None, view_type='form', context=None):
1684         return False
1685
1686     def user_has_groups(self, cr, uid, groups, context=None):
1687         """Return true if the user is at least member of one of the groups
1688            in groups_str. Typically used to resolve ``groups`` attribute
1689            in view and model definitions.
1690
1691            :param str groups: comma-separated list of fully-qualified group
1692                               external IDs, e.g.: ``base.group_user,base.group_system``
1693            :return: True if the current user is a member of one of the
1694                     given groups
1695         """
1696         return any([self.pool.get('res.users').has_group(cr, uid, group_ext_id)
1697                         for group_ext_id in groups.split(',')])
1698
1699     def __view_look_dom(self, cr, user, node, view_id, in_tree_view, model_fields, context=None):
1700         """Return the description of the fields in the node.
1701
1702         In a normal call to this method, node is a complete view architecture
1703         but it is actually possible to give some sub-node (this is used so
1704         that the method can call itself recursively).
1705
1706         Originally, the field descriptions are drawn from the node itself.
1707         But there is now some code calling fields_get() in order to merge some
1708         of those information in the architecture.
1709
1710         """
1711         if context is None:
1712             context = {}
1713         result = False
1714         fields = {}
1715         children = True
1716
1717         modifiers = {}
1718
1719         def encode(s):
1720             if isinstance(s, unicode):
1721                 return s.encode('utf8')
1722             return s
1723
1724         def check_group(node):
1725             """Apply group restrictions,  may be set at view level or model level::
1726                * at view level this means the element should be made invisible to
1727                  people who are not members
1728                * at model level (exclusively for fields, obviously), this means
1729                  the field should be completely removed from the view, as it is
1730                  completely unavailable for non-members
1731
1732                :return: True if field should be included in the result of fields_view_get
1733             """
1734             if node.tag == 'field' and node.get('name') in self._all_columns:
1735                 column = self._all_columns[node.get('name')].column
1736                 if column.groups and not self.user_has_groups(cr, user,
1737                                                               groups=column.groups,
1738                                                               context=context):
1739                     node.getparent().remove(node)
1740                     fields.pop(node.get('name'), None)
1741                     # no point processing view-level ``groups`` anymore, return
1742                     return False
1743             if node.get('groups'):
1744                 can_see = self.user_has_groups(cr, user,
1745                                                groups=node.get('groups'),
1746                                                context=context)
1747                 if not can_see:
1748                     node.set('invisible', '1')
1749                     modifiers['invisible'] = True
1750                     if 'attrs' in node.attrib:
1751                         del(node.attrib['attrs']) #avoid making field visible later
1752                 del(node.attrib['groups'])
1753             return True
1754
1755         if node.tag in ('field', 'node', 'arrow'):
1756             if node.get('object'):
1757                 attrs = {}
1758                 views = {}
1759                 xml = "<form>"
1760                 for f in node:
1761                     if f.tag == 'field':
1762                         xml += etree.tostring(f, encoding="utf-8")
1763                 xml += "</form>"
1764                 new_xml = etree.fromstring(encode(xml))
1765                 ctx = context.copy()
1766                 ctx['base_model_name'] = self._name
1767                 xarch, xfields = self.pool.get(node.get('object')).__view_look_dom_arch(cr, user, new_xml, view_id, ctx)
1768                 views['form'] = {
1769                     'arch': xarch,
1770                     'fields': xfields
1771                 }
1772                 attrs = {'views': views}
1773                 fields = xfields
1774             if node.get('name'):
1775                 attrs = {}
1776                 try:
1777                     if node.get('name') in self._columns:
1778                         column = self._columns[node.get('name')]
1779                     else:
1780                         column = self._inherit_fields[node.get('name')][2]
1781                 except Exception:
1782                     column = False
1783
1784                 if column:
1785                     relation = self.pool.get(column._obj)
1786
1787                     children = False
1788                     views = {}
1789                     for f in node:
1790                         if f.tag in ('form', 'tree', 'graph', 'kanban'):
1791                             node.remove(f)
1792                             ctx = context.copy()
1793                             ctx['base_model_name'] = self._name
1794                             xarch, xfields = relation.__view_look_dom_arch(cr, user, f, view_id, ctx)
1795                             views[str(f.tag)] = {
1796                                 'arch': xarch,
1797                                 'fields': xfields
1798                             }
1799                     attrs = {'views': views}
1800                     if node.get('widget') and node.get('widget') == 'selection':
1801                         # Prepare the cached selection list for the client. This needs to be
1802                         # done even when the field is invisible to the current user, because
1803                         # other events could need to change its value to any of the selectable ones
1804                         # (such as on_change events, refreshes, etc.)
1805
1806                         # If domain and context are strings, we keep them for client-side, otherwise
1807                         # we evaluate them server-side to consider them when generating the list of
1808                         # possible values
1809                         # TODO: find a way to remove this hack, by allow dynamic domains
1810                         dom = []
1811                         if column._domain and not isinstance(column._domain, basestring):
1812                             dom = list(column._domain)
1813                         dom += eval(node.get('domain', '[]'), {'uid': user, 'time': time})
1814                         search_context = dict(context)
1815                         if column._context and not isinstance(column._context, basestring):
1816                             search_context.update(column._context)
1817                         attrs['selection'] = relation._name_search(cr, user, '', dom, context=search_context, limit=None, name_get_uid=1)
1818                         if (node.get('required') and not int(node.get('required'))) or not column.required:
1819                             attrs['selection'].append((False, ''))
1820                 fields[node.get('name')] = attrs
1821
1822                 field = model_fields.get(node.get('name'))
1823                 if field:
1824                     transfer_field_to_modifiers(field, modifiers)
1825
1826
1827         elif node.tag in ('form', 'tree'):
1828             result = self.view_header_get(cr, user, False, node.tag, context)
1829             if result:
1830                 node.set('string', result)
1831             in_tree_view = node.tag == 'tree'
1832
1833         elif node.tag == 'calendar':
1834             for additional_field in ('date_start', 'date_delay', 'date_stop', 'color'):
1835                 if node.get(additional_field):
1836                     fields[node.get(additional_field)] = {}
1837
1838         if not check_group(node):
1839             # node must be removed, no need to proceed further with its children
1840             return fields
1841
1842         # The view architeture overrides the python model.
1843         # Get the attrs before they are (possibly) deleted by check_group below
1844         transfer_node_to_modifiers(node, modifiers, context, in_tree_view)
1845
1846         # TODO remove attrs couterpart in modifiers when invisible is true ?
1847
1848         # translate view
1849         if 'lang' in context:
1850             if node.text and node.text.strip():
1851                 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.text.strip())
1852                 if trans:
1853                     node.text = node.text.replace(node.text.strip(), trans)
1854             if node.tail and node.tail.strip():
1855                 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.tail.strip())
1856                 if trans:
1857                     node.tail =  node.tail.replace(node.tail.strip(), trans)
1858
1859             if node.get('string') and not result:
1860                 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('string'))
1861                 if trans == node.get('string') and ('base_model_name' in context):
1862                     # If translation is same as source, perhaps we'd have more luck with the alternative model name
1863                     # (in case we are in a mixed situation, such as an inherited view where parent_view.model != model
1864                     trans = self.pool.get('ir.translation')._get_source(cr, user, context['base_model_name'], 'view', context['lang'], node.get('string'))
1865                 if trans:
1866                     node.set('string', trans)
1867
1868             for attr_name in ('confirm', 'sum', 'avg', 'help', 'placeholder'):
1869                 attr_value = node.get(attr_name)
1870                 if attr_value:
1871                     trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], attr_value)
1872                     if trans:
1873                         node.set(attr_name, trans)
1874
1875         for f in node:
1876             if children or (node.tag == 'field' and f.tag in ('filter','separator')):
1877                 fields.update(self.__view_look_dom(cr, user, f, view_id, in_tree_view, model_fields, context))
1878
1879         transfer_modifiers_to_node(modifiers, node)
1880         return fields
1881
1882     def _disable_workflow_buttons(self, cr, user, node):
1883         """ Set the buttons in node to readonly if the user can't activate them. """
1884         if user == 1:
1885             # admin user can always activate workflow buttons
1886             return node
1887
1888         # TODO handle the case of more than one workflow for a model or multiple
1889         # transitions with different groups and same signal
1890         usersobj = self.pool.get('res.users')
1891         buttons = (n for n in node.getiterator('button') if n.get('type') != 'object')
1892         for button in buttons:
1893             user_groups = usersobj.read(cr, user, [user], ['groups_id'])[0]['groups_id']
1894             cr.execute("""SELECT DISTINCT t.group_id
1895                         FROM wkf
1896                   INNER JOIN wkf_activity a ON a.wkf_id = wkf.id
1897                   INNER JOIN wkf_transition t ON (t.act_to = a.id)
1898                        WHERE wkf.osv = %s
1899                          AND t.signal = %s
1900                          AND t.group_id is NOT NULL
1901                    """, (self._name, button.get('name')))
1902             group_ids = [x[0] for x in cr.fetchall() if x[0]]
1903             can_click = not group_ids or bool(set(user_groups).intersection(group_ids))
1904             button.set('readonly', str(int(not can_click)))
1905         return node
1906
1907     def __view_look_dom_arch(self, cr, user, node, view_id, context=None):
1908         """ Return an architecture and a description of all the fields.
1909
1910         The field description combines the result of fields_get() and
1911         __view_look_dom().
1912
1913         :param node: the architecture as as an etree
1914         :return: a tuple (arch, fields) where arch is the given node as a
1915             string and fields is the description of all the fields.
1916
1917         """
1918         fields = {}
1919         if node.tag == 'diagram':
1920             if node.getchildren()[0].tag == 'node':
1921                 node_model = self.pool.get(node.getchildren()[0].get('object'))
1922                 node_fields = node_model.fields_get(cr, user, None, context)
1923                 fields.update(node_fields)
1924                 if not node.get("create") and not node_model.check_access_rights(cr, user, 'create', raise_exception=False):
1925                     node.set("create", 'false')
1926             if node.getchildren()[1].tag == 'arrow':
1927                 arrow_fields = self.pool.get(node.getchildren()[1].get('object')).fields_get(cr, user, None, context)
1928                 fields.update(arrow_fields)
1929         else:
1930             fields = self.fields_get(cr, user, None, context)
1931         fields_def = self.__view_look_dom(cr, user, node, view_id, False, fields, context=context)
1932         node = self._disable_workflow_buttons(cr, user, node)
1933         if node.tag in ('kanban', 'tree', 'form', 'gantt'):
1934             for action, operation in (('create', 'create'), ('delete', 'unlink'), ('edit', 'write')):
1935                 if not node.get(action) and not self.check_access_rights(cr, user, operation, raise_exception=False):
1936                     node.set(action, 'false')
1937         arch = etree.tostring(node, encoding="utf-8").replace('\t', '')
1938         for k in fields.keys():
1939             if k not in fields_def:
1940                 del fields[k]
1941         for field in fields_def:
1942             if field == 'id':
1943                 # sometime, the view may contain the (invisible) field 'id' needed for a domain (when 2 objects have cross references)
1944                 fields['id'] = {'readonly': True, 'type': 'integer', 'string': 'ID'}
1945             elif field in fields:
1946                 fields[field].update(fields_def[field])
1947             else:
1948                 cr.execute('select name, model from ir_ui_view where (id=%s or inherit_id=%s) and arch like %s', (view_id, view_id, '%%%s%%' % field))
1949                 res = cr.fetchall()[:]
1950                 model = res[0][1]
1951                 res.insert(0, ("Can't find field '%s' in the following view parts composing the view of object model '%s':" % (field, model), None))
1952                 msg = "\n * ".join([r[0] for r in res])
1953                 msg += "\n\nEither you wrongly customized this view, or some modules bringing those views are not compatible with your current data model"
1954                 _logger.error(msg)
1955                 raise except_orm('View error', msg)
1956         return arch, fields
1957
1958     def _get_default_form_view(self, cr, user, context=None):
1959         """ Generates a default single-line form view using all fields
1960         of the current model except the m2m and o2m ones.
1961
1962         :param cr: database cursor
1963         :param int user: user id
1964         :param dict context: connection context
1965         :returns: a form view as an lxml document
1966         :rtype: etree._Element
1967         """
1968         view = etree.Element('form', string=self._description)
1969         # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
1970         for field, descriptor in self.fields_get(cr, user, context=context).iteritems():
1971             if descriptor['type'] in ('one2many', 'many2many'):
1972                 continue
1973             etree.SubElement(view, 'field', name=field)
1974             if descriptor['type'] == 'text':
1975                 etree.SubElement(view, 'newline')
1976         return view
1977
1978     def _get_default_search_view(self, cr, user, context=None):
1979         """ Generates a single-field search view, based on _rec_name.
1980
1981         :param cr: database cursor
1982         :param int user: user id
1983         :param dict context: connection context
1984         :returns: a tree view as an lxml document
1985         :rtype: etree._Element
1986         """
1987         view = etree.Element('search', string=self._description)
1988         etree.SubElement(view, 'field', name=self._rec_name_fallback(cr, user, context))
1989         return view
1990
1991     def _get_default_tree_view(self, cr, user, context=None):
1992         """ Generates a single-field tree view, based on _rec_name.
1993
1994         :param cr: database cursor
1995         :param int user: user id
1996         :param dict context: connection context
1997         :returns: a tree view as an lxml document
1998         :rtype: etree._Element
1999         """
2000         view = etree.Element('tree', string=self._description)
2001         etree.SubElement(view, 'field', name=self._rec_name_fallback(cr, user, context))
2002         return view
2003
2004     def _get_default_calendar_view(self, cr, user, context=None):
2005         """ Generates a default calendar view by trying to infer
2006         calendar fields from a number of pre-set attribute names
2007
2008         :param cr: database cursor
2009         :param int user: user id
2010         :param dict context: connection context
2011         :returns: a calendar view
2012         :rtype: etree._Element
2013         """
2014         def set_first_of(seq, in_, to):
2015             """Sets the first value of ``seq`` also found in ``in_`` to
2016             the ``to`` attribute of the view being closed over.
2017
2018             Returns whether it's found a suitable value (and set it on
2019             the attribute) or not
2020             """
2021             for item in seq:
2022                 if item in in_:
2023                     view.set(to, item)
2024                     return True
2025             return False
2026
2027         view = etree.Element('calendar', string=self._description)
2028         etree.SubElement(view, 'field', self._rec_name_fallback(cr, user, context))
2029
2030         if self._date_name not in self._columns:
2031             date_found = False
2032             for dt in ['date', 'date_start', 'x_date', 'x_date_start']:
2033                 if dt in self._columns:
2034                     self._date_name = dt
2035                     date_found = True
2036                     break
2037
2038             if not date_found:
2039                 raise except_orm(_('Invalid Object Architecture!'), _("Insufficient fields for Calendar View!"))
2040         view.set('date_start', self._date_name)
2041
2042         set_first_of(["user_id", "partner_id", "x_user_id", "x_partner_id"],
2043                      self._columns, 'color')
2044
2045         if not set_first_of(["date_stop", "date_end", "x_date_stop", "x_date_end"],
2046                             self._columns, 'date_stop'):
2047             if not set_first_of(["date_delay", "planned_hours", "x_date_delay", "x_planned_hours"],
2048                                 self._columns, 'date_delay'):
2049                 raise except_orm(
2050                     _('Invalid Object Architecture!'),
2051                     _("Insufficient fields to generate a Calendar View for %s, missing a date_stop or a date_delay" % self._name))
2052
2053         return view
2054
2055     #
2056     # if view_id, view_type is not required
2057     #
2058     def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
2059         """
2060         Get the detailed composition of the requested view like fields, model, view architecture
2061
2062         :param cr: database cursor
2063         :param user: current user id
2064         :param view_id: id of the view or None
2065         :param view_type: type of the view to return if view_id is None ('form', tree', ...)
2066         :param context: context arguments, like lang, time zone
2067         :param toolbar: true to include contextual actions
2068         :param submenu: deprecated
2069         :return: dictionary describing the composition of the requested view (including inherited views and extensions)
2070         :raise AttributeError:
2071                             * if the inherited view has unknown position to work with other than 'before', 'after', 'inside', 'replace'
2072                             * if some tag other than 'position' is found in parent view
2073         :raise Invalid ArchitectureError: if there is view type other than form, tree, calendar, search etc defined on the structure
2074
2075         """
2076         if context is None:
2077             context = {}
2078
2079         def encode(s):
2080             if isinstance(s, unicode):
2081                 return s.encode('utf8')
2082             return s
2083
2084         def raise_view_error(error_msg, child_view_id):
2085             view, child_view = self.pool.get('ir.ui.view').browse(cr, user, [view_id, child_view_id], context)
2086             error_msg = error_msg % {'parent_xml_id': view.xml_id}
2087             raise AttributeError("View definition error for inherited view '%s' on model '%s': %s"
2088                                  %  (child_view.xml_id, self._name, error_msg))
2089
2090         def locate(source, spec):
2091             """ Locate a node in a source (parent) architecture.
2092
2093             Given a complete source (parent) architecture (i.e. the field
2094             `arch` in a view), and a 'spec' node (a node in an inheriting
2095             view that specifies the location in the source view of what
2096             should be changed), return (if it exists) the node in the
2097             source view matching the specification.
2098
2099             :param source: a parent architecture to modify
2100             :param spec: a modifying node in an inheriting view
2101             :return: a node in the source matching the spec
2102
2103             """
2104             if spec.tag == 'xpath':
2105                 nodes = source.xpath(spec.get('expr'))
2106                 return nodes[0] if nodes else None
2107             elif spec.tag == 'field':
2108                 # Only compare the field name: a field can be only once in a given view
2109                 # at a given level (and for multilevel expressions, we should use xpath
2110                 # inheritance spec anyway).
2111                 for node in source.getiterator('field'):
2112                     if node.get('name') == spec.get('name'):
2113                         return node
2114                 return None
2115
2116             for node in source.getiterator(spec.tag):
2117                 if isinstance(node, SKIPPED_ELEMENT_TYPES):
2118                     continue
2119                 if all(node.get(attr) == spec.get(attr) \
2120                         for attr in spec.attrib
2121                             if attr not in ('position','version')):
2122                     # Version spec should match parent's root element's version
2123                     if spec.get('version') and spec.get('version') != source.get('version'):
2124                         return None
2125                     return node
2126             return None
2127
2128         def apply_inheritance_specs(source, specs_arch, inherit_id=None):
2129             """ Apply an inheriting view.
2130
2131             Apply to a source architecture all the spec nodes (i.e. nodes
2132             describing where and what changes to apply to some parent
2133             architecture) given by an inheriting view.
2134
2135             :param source: a parent architecture to modify
2136             :param specs_arch: a modifying architecture in an inheriting view
2137             :param inherit_id: the database id of the inheriting view
2138             :return: a modified source where the specs are applied
2139
2140             """
2141             specs_tree = etree.fromstring(encode(specs_arch))
2142             # Queue of specification nodes (i.e. nodes describing where and
2143             # changes to apply to some parent architecture).
2144             specs = [specs_tree]
2145
2146             while len(specs):
2147                 spec = specs.pop(0)
2148                 if isinstance(spec, SKIPPED_ELEMENT_TYPES):
2149                     continue
2150                 if spec.tag == 'data':
2151                     specs += [ c for c in specs_tree ]
2152                     continue
2153                 node = locate(source, spec)
2154                 if node is not None:
2155                     pos = spec.get('position', 'inside')
2156                     if pos == 'replace':
2157                         if node.getparent() is None:
2158                             source = copy.deepcopy(spec[0])
2159                         else:
2160                             for child in spec:
2161                                 node.addprevious(child)
2162                             node.getparent().remove(node)
2163                     elif pos == 'attributes':
2164                         for child in spec.getiterator('attribute'):
2165                             attribute = (child.get('name'), child.text or None)
2166                             if attribute[1]:
2167                                 node.set(attribute[0], attribute[1])
2168                             else:
2169                                 del(node.attrib[attribute[0]])
2170                     else:
2171                         sib = node.getnext()
2172                         for child in spec:
2173                             if pos == 'inside':
2174                                 node.append(child)
2175                             elif pos == 'after':
2176                                 if sib is None:
2177                                     node.addnext(child)
2178                                     node = child
2179                                 else:
2180                                     sib.addprevious(child)
2181                             elif pos == 'before':
2182                                 node.addprevious(child)
2183                             else:
2184                                 raise_view_error("Invalid position value: '%s'" % pos, inherit_id)
2185                 else:
2186                     attrs = ''.join([
2187                         ' %s="%s"' % (attr, spec.get(attr))
2188                         for attr in spec.attrib
2189                         if attr != 'position'
2190                     ])
2191                     tag = "<%s%s>" % (spec.tag, attrs)
2192                     if spec.get('version') and spec.get('version') != source.get('version'):
2193                         raise_view_error("Mismatching view API version for element '%s': %r vs %r in parent view '%%(parent_xml_id)s'" % \
2194                                             (tag, spec.get('version'), source.get('version')), inherit_id)
2195                     raise_view_error("Element '%s' not found in parent view '%%(parent_xml_id)s'" % tag, inherit_id)
2196
2197             return source
2198
2199         def apply_view_inheritance(cr, user, source, inherit_id):
2200             """ Apply all the (directly and indirectly) inheriting views.
2201
2202             :param source: a parent architecture to modify (with parent
2203                 modifications already applied)
2204             :param inherit_id: the database view_id of the parent view
2205             :return: a modified source where all the modifying architecture
2206                 are applied
2207
2208             """
2209             sql_inherit = self.pool.get('ir.ui.view').get_inheriting_views_arch(cr, user, inherit_id, self._name, context=context)
2210             for (view_arch, view_id) in sql_inherit:
2211                 source = apply_inheritance_specs(source, view_arch, view_id)
2212                 source = apply_view_inheritance(cr, user, source, view_id)
2213             return source
2214
2215         result = {'type': view_type, 'model': self._name}
2216
2217         sql_res = False
2218         parent_view_model = None
2219         view_ref = context.get(view_type + '_view_ref')
2220         # Search for a root (i.e. without any parent) view.
2221         while True:
2222             if view_ref and not view_id:
2223                 if '.' in view_ref:
2224                     module, view_ref = view_ref.split('.', 1)
2225                     cr.execute("SELECT res_id FROM ir_model_data WHERE model='ir.ui.view' AND module=%s AND name=%s", (module, view_ref))
2226                     view_ref_res = cr.fetchone()
2227                     if view_ref_res:
2228                         view_id = view_ref_res[0]
2229
2230             if view_id:
2231                 cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model
2232                               FROM ir_ui_view
2233                               WHERE id=%s""", (view_id,))
2234             else:
2235                 cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model
2236                               FROM ir_ui_view
2237                               WHERE model=%s AND type=%s AND inherit_id IS NULL
2238                               ORDER BY priority""", (self._name, view_type))
2239             sql_res = cr.dictfetchone()
2240
2241             if not sql_res:
2242                 break
2243
2244             view_id = sql_res['inherit_id'] or sql_res['id']
2245             parent_view_model = sql_res['model']
2246             if not sql_res['inherit_id']:
2247                 break
2248
2249         # if a view was found
2250         if sql_res:
2251             source = etree.fromstring(encode(sql_res['arch']))
2252             result.update(
2253                 arch=apply_view_inheritance(cr, user, source, sql_res['id']),
2254                 type=sql_res['type'],
2255                 view_id=sql_res['id'],
2256                 name=sql_res['name'],
2257                 field_parent=sql_res['field_parent'] or False)
2258         else:
2259             # otherwise, build some kind of default view
2260             try:
2261                 view = getattr(self, '_get_default_%s_view' % view_type)(
2262                     cr, user, context)
2263             except AttributeError:
2264                 # what happens here, graph case?
2265                 raise except_orm(_('Invalid Architecture!'), _("There is no view of type '%s' defined for the structure!") % view_type)
2266
2267             result.update(
2268                 arch=view,
2269                 name='default',
2270                 field_parent=False,
2271                 view_id=0)
2272
2273         if parent_view_model != self._name:
2274             ctx = context.copy()
2275             ctx['base_model_name'] = parent_view_model
2276         else:
2277             ctx = context
2278         xarch, xfields = self.__view_look_dom_arch(cr, user, result['arch'], view_id, context=ctx)
2279         result['arch'] = xarch
2280         result['fields'] = xfields
2281
2282         if toolbar:
2283             def clean(x):
2284                 x = x[2]
2285                 for key in ('report_sxw_content', 'report_rml_content',
2286                         'report_sxw', 'report_rml',
2287                         'report_sxw_content_data', 'report_rml_content_data'):
2288                     if key in x:
2289                         del x[key]
2290                 return x
2291             ir_values_obj = self.pool.get('ir.values')
2292             resprint = ir_values_obj.get(cr, user, 'action',
2293                     'client_print_multi', [(self._name, False)], False,
2294                     context)
2295             resaction = ir_values_obj.get(cr, user, 'action',
2296                     'client_action_multi', [(self._name, False)], False,
2297                     context)
2298
2299             resrelate = ir_values_obj.get(cr, user, 'action',
2300                     'client_action_relate', [(self._name, False)], False,
2301                     context)
2302             resaction = [clean(action) for action in resaction
2303                          if view_type == 'tree' or not action[2].get('multi')]
2304             resprint = [clean(print_) for print_ in resprint
2305                         if view_type == 'tree' or not print_[2].get('multi')]
2306             #When multi="True" set it will display only in More of the list view 
2307             resrelate = [clean(action) for action in resrelate
2308                          if (action[2].get('multi') and view_type == 'tree') or (not action[2].get('multi') and view_type == 'form')]
2309
2310             for x in itertools.chain(resprint, resaction, resrelate):
2311                 x['string'] = x['name']
2312
2313             result['toolbar'] = {
2314                 'print': resprint,
2315                 'action': resaction,
2316                 'relate': resrelate
2317             }
2318         return result
2319
2320     _view_look_dom_arch = __view_look_dom_arch
2321
2322     def search_count(self, cr, user, args, context=None):
2323         if not context:
2324             context = {}
2325         res = self.search(cr, user, args, context=context, count=True)
2326         if isinstance(res, list):
2327             return len(res)
2328         return res
2329
2330     def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
2331         """
2332         Search for records based on a search domain.
2333
2334         :param cr: database cursor
2335         :param user: current user id
2336         :param args: list of tuples specifying the search domain [('field_name', 'operator', value), ...]. Pass an empty list to match all records.
2337         :param offset: optional number of results to skip in the returned values (default: 0)
2338         :param limit: optional max number of records to return (default: **None**)
2339         :param order: optional columns to sort by (default: self._order=id )
2340         :param context: optional context arguments, like lang, time zone
2341         :type context: dictionary
2342         :param count: optional (default: **False**), if **True**, returns only the number of records matching the criteria, not their ids
2343         :return: id or list of ids of records matching the criteria
2344         :rtype: integer or list of integers
2345         :raise AccessError: * if user tries to bypass access rules for read on the requested object.
2346
2347         **Expressing a search domain (args)**
2348
2349         Each tuple in the search domain needs to have 3 elements, in the form: **('field_name', 'operator', value)**, where:
2350
2351             * **field_name** must be a valid name of field of the object model, possibly following many-to-one relationships using dot-notation, e.g 'street' or 'partner_id.country' are valid values.
2352             * **operator** must be a string with a valid comparison operator from this list: ``=, !=, >, >=, <, <=, like, ilike, in, not in, child_of, parent_left, parent_right``
2353               The semantics of most of these operators are obvious.
2354               The ``child_of`` operator will look for records who are children or grand-children of a given record,
2355               according to the semantics of this model (i.e following the relationship field named by
2356               ``self._parent_name``, by default ``parent_id``.
2357             * **value** must be a valid value to compare with the values of **field_name**, depending on its type.
2358
2359         Domain criteria can be combined using 3 logical operators than can be added between tuples:  '**&**' (logical AND, default), '**|**' (logical OR), '**!**' (logical NOT).
2360         These are **prefix** operators and the arity of the '**&**' and '**|**' operator is 2, while the arity of the '**!**' is just 1.
2361         Be very careful about this when you combine them the first time.
2362
2363         Here is an example of searching for Partners named *ABC* from Belgium and Germany whose language is not english ::
2364
2365             [('name','=','ABC'),'!',('language.code','=','en_US'),'|',('country_id.code','=','be'),('country_id.code','=','de'))
2366
2367         The '&' is omitted as it is the default, and of course we could have used '!=' for the language, but what this domain really represents is::
2368
2369             (name is 'ABC' AND (language is NOT english) AND (country is Belgium OR Germany))
2370
2371         """
2372         return self._search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count)
2373
2374     def name_get(self, cr, user, ids, context=None):
2375         """Returns the preferred display value (text representation) for the records with the
2376            given ``ids``. By default this will be the value of the ``name`` column, unless
2377            the model implements a custom behavior.
2378            Can sometimes be seen as the inverse function of :meth:`~.name_search`, but it is not
2379            guaranteed to be.
2380
2381            :rtype: list(tuple)
2382            :return: list of pairs ``(id,text_repr)`` for all records with the given ``ids``.
2383         """
2384         if not ids:
2385             return []
2386         if isinstance(ids, (int, long)):
2387             ids = [ids]
2388
2389         if self._rec_name in self._all_columns:
2390             rec_name_column = self._all_columns[self._rec_name].column
2391             return [(r['id'], rec_name_column.as_display_name(cr, user, self, r[self._rec_name], context=context))
2392                         for r in self.read(cr, user, ids, [self._rec_name],
2393                                        load='_classic_write', context=context)]
2394         return [(id, "%s,%s" % (self._name, id)) for id in ids]
2395
2396     def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
2397         """Search for records that have a display name matching the given ``name`` pattern if compared
2398            with the given ``operator``, while also matching the optional search domain (``args``).
2399            This is used for example to provide suggestions based on a partial value for a relational
2400            field.
2401            Sometimes be seen as the inverse function of :meth:`~.name_get`, but it is not
2402            guaranteed to be.
2403
2404            This method is equivalent to calling :meth:`~.search` with a search domain based on ``name``
2405            and then :meth:`~.name_get` on the result of the search.
2406
2407            :param list args: optional search domain (see :meth:`~.search` for syntax),
2408                              specifying further restrictions
2409            :param str operator: domain operator for matching the ``name`` pattern, such as ``'like'``
2410                                 or ``'='``.
2411            :param int limit: optional max number of records to return
2412            :rtype: list
2413            :return: list of pairs ``(id,text_repr)`` for all matching records.
2414         """
2415         return self._name_search(cr, user, name, args, operator, context, limit)
2416
2417     def name_create(self, cr, uid, name, context=None):
2418         """Creates a new record by calling :meth:`~.create` with only one
2419            value provided: the name of the new record (``_rec_name`` field).
2420            The new record will also be initialized with any default values applicable
2421            to this model, or provided through the context. The usual behavior of
2422            :meth:`~.create` applies.
2423            Similarly, this method may raise an exception if the model has multiple
2424            required fields and some do not have default values.
2425
2426            :param name: name of the record to create
2427
2428            :rtype: tuple
2429            :return: the :meth:`~.name_get` pair value for the newly-created record.
2430         """
2431         rec_id = self.create(cr, uid, {self._rec_name: name}, context)
2432         return self.name_get(cr, uid, [rec_id], context)[0]
2433
2434     # private implementation of name_search, allows passing a dedicated user for the name_get part to
2435     # solve some access rights issues
2436     def _name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100, name_get_uid=None):
2437         if args is None:
2438             args = []
2439         if context is None:
2440             context = {}
2441         args = args[:]
2442         # optimize out the default criterion of ``ilike ''`` that matches everything
2443         if not (name == '' and operator == 'ilike'):
2444             args += [(self._rec_name, operator, name)]
2445         access_rights_uid = name_get_uid or user
2446         ids = self._search(cr, user, args, limit=limit, context=context, access_rights_uid=access_rights_uid)
2447         res = self.name_get(cr, access_rights_uid, ids, context)
2448         return res
2449
2450     def read_string(self, cr, uid, id, langs, fields=None, context=None):
2451         res = {}
2452         res2 = {}
2453         self.pool.get('ir.translation').check_access_rights(cr, uid, 'read')
2454         if not fields:
2455             fields = self._columns.keys() + self._inherit_fields.keys()
2456         #FIXME: collect all calls to _get_source into one SQL call.
2457         for lang in langs:
2458             res[lang] = {'code': lang}
2459             for f in fields:
2460                 if f in self._columns:
2461                     res_trans = self.pool.get('ir.translation')._get_source(cr, uid, self._name+','+f, 'field', lang)
2462                     if res_trans:
2463                         res[lang][f] = res_trans
2464                     else:
2465                         res[lang][f] = self._columns[f].string
2466         for table in self._inherits:
2467             cols = intersect(self._inherit_fields.keys(), fields)
2468             res2 = self.pool.get(table).read_string(cr, uid, id, langs, cols, context)
2469         for lang in res2:
2470             if lang in res:
2471                 res[lang]['code'] = lang
2472             for f in res2[lang]:
2473                 res[lang][f] = res2[lang][f]
2474         return res
2475
2476     def write_string(self, cr, uid, id, langs, vals, context=None):
2477         self.pool.get('ir.translation').check_access_rights(cr, uid, 'write')
2478         #FIXME: try to only call the translation in one SQL
2479         for lang in langs:
2480             for field in vals:
2481                 if field in self._columns:
2482                     src = self._columns[field].string
2483                     self.pool.get('ir.translation')._set_ids(cr, uid, self._name+','+field, 'field', lang, [0], vals[field], src)
2484         for table in self._inherits:
2485             cols = intersect(self._inherit_fields.keys(), vals)
2486             if cols:
2487                 self.pool.get(table).write_string(cr, uid, id, langs, vals, context)
2488         return True
2489
2490     def _add_missing_default_values(self, cr, uid, values, context=None):
2491         missing_defaults = []
2492         avoid_tables = [] # avoid overriding inherited values when parent is set
2493         for tables, parent_field in self._inherits.items():
2494             if parent_field in values:
2495                 avoid_tables.append(tables)
2496         for field in self._columns.keys():
2497             if not field in values:
2498                 missing_defaults.append(field)
2499         for field in self._inherit_fields.keys():
2500             if (field not in values) and (self._inherit_fields[field][0] not in avoid_tables):
2501                 missing_defaults.append(field)
2502
2503         if len(missing_defaults):
2504             # override defaults with the provided values, never allow the other way around
2505             defaults = self.default_get(cr, uid, missing_defaults, context)
2506             for dv in defaults:
2507                 if ((dv in self._columns and self._columns[dv]._type == 'many2many') \
2508                      or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'many2many')) \
2509                         and defaults[dv] and isinstance(defaults[dv][0], (int, long)):
2510                     defaults[dv] = [(6, 0, defaults[dv])]
2511                 if (dv in self._columns and self._columns[dv]._type == 'one2many' \
2512                     or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'one2many')) \
2513                         and isinstance(defaults[dv], (list, tuple)) and defaults[dv] and isinstance(defaults[dv][0], dict):
2514                     defaults[dv] = [(0, 0, x) for x in defaults[dv]]
2515             defaults.update(values)
2516             values = defaults
2517         return values
2518
2519     def clear_caches(self):
2520         """ Clear the caches
2521
2522         This clears the caches associated to methods decorated with
2523         ``tools.ormcache`` or ``tools.ormcache_multi``.
2524         """
2525         try:
2526             getattr(self, '_ormcache')
2527             self._ormcache = {}
2528             self.pool._any_cache_cleared = True
2529         except AttributeError:
2530             pass
2531
2532
2533     def _read_group_fill_results(self, cr, uid, domain, groupby, groupby_list, aggregated_fields,
2534                                  read_group_result, read_group_order=None, context=None):
2535         """Helper method for filling in empty groups for all possible values of
2536            the field being grouped by"""
2537
2538         # self._group_by_full should map groupable fields to a method that returns
2539         # a list of all aggregated values that we want to display for this field,
2540         # in the form of a m2o-like pair (key,label).
2541         # This is useful to implement kanban views for instance, where all columns
2542         # should be displayed even if they don't contain any record.
2543
2544         # Grab the list of all groups that should be displayed, including all present groups
2545         present_group_ids = [x[groupby][0] for x in read_group_result if x[groupby]]
2546         all_groups,folded = self._group_by_full[groupby](self, cr, uid, present_group_ids, domain,
2547                                                   read_group_order=read_group_order,
2548                                                   access_rights_uid=openerp.SUPERUSER_ID,
2549                                                   context=context)
2550
2551         result_template = dict.fromkeys(aggregated_fields, False)
2552         result_template[groupby + '_count'] = 0
2553         if groupby_list and len(groupby_list) > 1:
2554             result_template['__context'] = {'group_by': groupby_list[1:]}
2555
2556         # Merge the left_side (current results as dicts) with the right_side (all
2557         # possible values as m2o pairs). Both lists are supposed to be using the
2558         # same ordering, and can be merged in one pass.
2559         result = []
2560         known_values = {}
2561         def append_left(left_side):
2562             grouped_value = left_side[groupby] and left_side[groupby][0]
2563             if not grouped_value in known_values:
2564                 result.append(left_side)
2565                 known_values[grouped_value] = left_side
2566             else:
2567                 count_attr = groupby + '_count'
2568                 known_values[grouped_value].update({count_attr: left_side[count_attr]})
2569         def append_right(right_side):
2570             grouped_value = right_side[0]
2571             if not grouped_value in known_values:
2572                 line = dict(result_template)
2573                 line[groupby] = right_side
2574                 line['__domain'] = [(groupby,'=',grouped_value)] + domain
2575                 result.append(line)
2576                 known_values[grouped_value] = line
2577         while read_group_result or all_groups:
2578             left_side = read_group_result[0] if read_group_result else None
2579             right_side = all_groups[0] if all_groups else None
2580             assert left_side is None or left_side[groupby] is False \
2581                  or isinstance(left_side[groupby], (tuple,list)), \
2582                 'M2O-like pair expected, got %r' % left_side[groupby]
2583             assert right_side is None or isinstance(right_side, (tuple,list)), \
2584                 'M2O-like pair expected, got %r' % right_side
2585             if left_side is None:
2586                 append_right(all_groups.pop(0))
2587             elif right_side is None:
2588                 append_left(read_group_result.pop(0))
2589             elif left_side[groupby] == right_side:
2590                 append_left(read_group_result.pop(0))
2591                 all_groups.pop(0) # discard right_side
2592             elif not left_side[groupby] or not left_side[groupby][0]:
2593                 # left side == "Undefined" entry, not present on right_side
2594                 append_left(read_group_result.pop(0))
2595             else:
2596                 append_right(all_groups.pop(0))
2597
2598         if folded:
2599             for r in result:
2600                 r['__fold'] = folded.get(r[groupby] and r[groupby][0], False)
2601         return result
2602
2603     def _read_group_prepare(self, orderby, aggregated_fields, groupby, qualified_groupby_field, query, groupby_type=None):
2604         """
2605         Prepares the GROUP BY and ORDER BY terms for the read_group method. Adds the missing JOIN clause
2606         to the query if order should be computed against m2o field. 
2607         :param orderby: the orderby definition in the form "%(field)s %(order)s"
2608         :param aggregated_fields: list of aggregated fields in the query
2609         :param groupby: the current groupby field name
2610         :param qualified_groupby_field: the fully qualified SQL name for the grouped field
2611         :param osv.Query query: the query under construction
2612         :param groupby_type: the type of the grouped field
2613         :return: (groupby_terms, orderby_terms)
2614         """
2615         orderby_terms = []
2616         groupby_terms = [qualified_groupby_field] if groupby else []
2617         if not orderby:
2618             return groupby_terms, orderby_terms    
2619
2620         self._check_qorder(orderby)
2621         for order_part in orderby.split(','):
2622             order_split = order_part.split()
2623             order_field = order_split[0]
2624             if order_field == groupby:
2625                 if groupby_type == 'many2one':
2626                     order_clause = self._generate_order_by(order_part, query).replace('ORDER BY ', '')
2627                     if order_clause:
2628                         orderby_terms.append(order_clause)
2629                         groupby_terms += [order_term.split()[0] for order_term in order_clause.split(',')]
2630                 else:
2631                     orderby_terms.append(order_part)
2632             elif order_field in aggregated_fields:
2633                 orderby_terms.append(order_part)
2634             else:
2635                 # Cannot order by a field that will not appear in the results (needs to be grouped or aggregated)
2636                 _logger.warn('%s: read_group order by `%s` ignored, cannot sort on empty columns (not grouped/aggregated)',
2637                              self._name, order_part)
2638         return groupby_terms, orderby_terms
2639
2640     def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False):
2641         """
2642         Get the list of records in list view grouped by the given ``groupby`` fields
2643
2644         :param cr: database cursor
2645         :param uid: current user id
2646         :param domain: list specifying search criteria [['field_name', 'operator', 'value'], ...]
2647         :param list fields: list of fields present in the list view specified on the object
2648         :param list groupby: fields by which the records will be grouped
2649         :param int offset: optional number of records to skip
2650         :param int limit: optional max number of records to return
2651         :param dict context: context arguments, like lang, time zone
2652         :param list orderby: optional ``order by`` specification, for
2653                              overriding the natural sort ordering of the
2654                              groups, see also :py:meth:`~osv.osv.osv.search`
2655                              (supported only for many2one fields currently)
2656         :return: list of dictionaries(one dictionary for each record) containing:
2657
2658                     * the values of fields grouped by the fields in ``groupby`` argument
2659                     * __domain: list of tuples specifying the search criteria
2660                     * __context: dictionary with argument like ``groupby``
2661         :rtype: [{'field_name_1': value, ...]
2662         :raise AccessError: * if user has no read rights on the requested object
2663                             * if user tries to bypass access rules for read on the requested object
2664
2665         """
2666         context = context or {}
2667         self.check_access_rights(cr, uid, 'read')
2668         if not fields:
2669             fields = self._columns.keys()
2670
2671         query = self._where_calc(cr, uid, domain, context=context)
2672         self._apply_ir_rules(cr, uid, query, 'read', context=context)
2673
2674         # Take care of adding join(s) if groupby is an '_inherits'ed field
2675         groupby_list = groupby
2676         qualified_groupby_field = groupby
2677         if groupby:
2678             if isinstance(groupby, list):
2679                 groupby = groupby[0]
2680             qualified_groupby_field = self._inherits_join_calc(groupby, query)
2681
2682         if groupby:
2683             assert not groupby or groupby in fields, "Fields in 'groupby' must appear in the list of fields to read (perhaps it's missing in the list view?)"
2684             groupby_def = self._columns.get(groupby) or (self._inherit_fields.get(groupby) and self._inherit_fields.get(groupby)[2])
2685             assert groupby_def and groupby_def._classic_write, "Fields in 'groupby' must be regular database-persisted fields (no function or related fields), or function fields with store=True"
2686
2687         # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
2688         fget = self.fields_get(cr, uid, fields)
2689         select_terms = []
2690         groupby_type = None
2691         if groupby:
2692             if fget.get(groupby):
2693                 groupby_type = fget[groupby]['type']
2694                 if groupby_type in ('date', 'datetime'):
2695                     qualified_groupby_field = "to_char(%s,'yyyy-mm')" % qualified_groupby_field
2696                 elif groupby_type == 'boolean':
2697                     qualified_groupby_field = "coalesce(%s,false)" % qualified_groupby_field
2698                 select_terms.append("%s as %s " % (qualified_groupby_field, groupby))
2699             else:
2700                 # Don't allow arbitrary values, as this would be a SQL injection vector!
2701                 raise except_orm(_('Invalid group_by'),
2702                                  _('Invalid group_by specification: "%s".\nA group_by specification must be a list of valid fields.')%(groupby,))
2703
2704         aggregated_fields = [
2705             f for f in fields
2706             if f not in ('id', 'sequence', groupby)
2707             if fget[f]['type'] in ('integer', 'float')
2708             if (f in self._all_columns and getattr(self._all_columns[f].column, '_classic_write'))]
2709         for f in aggregated_fields:
2710             group_operator = fget[f].get('group_operator', 'sum')
2711             qualified_field = self._inherits_join_calc(f, query)
2712             select_terms.append("%s(%s) AS %s" % (group_operator, qualified_field, f))
2713
2714         order = orderby or groupby or ''
2715         groupby_terms, orderby_terms = self._read_group_prepare(order, aggregated_fields, groupby, qualified_groupby_field, query, groupby_type)
2716
2717         from_clause, where_clause, where_clause_params = query.get_sql()
2718         if len(groupby_list) < 2 and context.get('group_by_no_leaf'):
2719             count_field = '_'
2720         else:
2721             count_field = groupby
2722
2723         prefix_terms = lambda prefix, terms: (prefix + " " + ",".join(terms)) if terms else ''
2724         prefix_term = lambda prefix, term: ('%s %s' % (prefix, term)) if term else ''
2725
2726         query = """
2727             SELECT min(%(table)s.id) AS id, count(%(table)s.id) AS %(count_field)s_count
2728                    %(extra_fields)s
2729             FROM %(from)s
2730             %(where)s
2731             %(groupby)s
2732             %(orderby)s
2733             %(limit)s
2734             %(offset)s
2735         """ % {
2736             'table': self._table,
2737             'count_field': count_field,
2738             'extra_fields': prefix_terms(',', select_terms),
2739             'from': from_clause,
2740             'where': prefix_term('WHERE', where_clause),
2741             'groupby': prefix_terms('GROUP BY', groupby_terms),
2742             'orderby': prefix_terms('ORDER BY', orderby_terms),
2743             'limit': prefix_term('LIMIT', int(limit) if limit else None),
2744             'offset': prefix_term('OFFSET', int(offset) if limit else None),
2745         }
2746         cr.execute(query, where_clause_params)
2747         alldata = {}
2748         fetched_data = cr.dictfetchall()
2749
2750         data_ids = []
2751         for r in fetched_data:
2752             for fld, val in r.items():
2753                 if val is None: r[fld] = False
2754             alldata[r['id']] = r
2755             data_ids.append(r['id'])
2756             del r['id']
2757
2758         if groupby:
2759             data = self.read(cr, uid, data_ids, [groupby], context=context)
2760             # restore order of the search as read() uses the default _order (this is only for groups, so the footprint of data should be small):
2761             data_dict = dict((d['id'], d[groupby] ) for d in data)
2762             result = [{'id': i, groupby: data_dict[i]} for i in data_ids]
2763         else:
2764             result = [{'id': i} for i in data_ids]
2765
2766         for d in result:
2767             if groupby:
2768                 d['__domain'] = [(groupby, '=', alldata[d['id']][groupby] or False)] + domain
2769                 if not isinstance(groupby_list, (str, unicode)):
2770                     if groupby or not context.get('group_by_no_leaf', False):
2771                         d['__context'] = {'group_by': groupby_list[1:]}
2772             if groupby and groupby in fget:
2773                 if d[groupby] and fget[groupby]['type'] in ('date', 'datetime'):
2774                     dt = datetime.datetime.strptime(alldata[d['id']][groupby][:7], '%Y-%m')
2775                     days = calendar.monthrange(dt.year, dt.month)[1]
2776
2777                     date_value = datetime.datetime.strptime(d[groupby][:10], '%Y-%m-%d')
2778                     d[groupby] = babel.dates.format_date(
2779                         date_value, format='MMMM yyyy', locale=context.get('lang', 'en_US'))
2780                     d['__domain'] = [(groupby, '>=', alldata[d['id']][groupby] and datetime.datetime.strptime(alldata[d['id']][groupby][:7] + '-01', '%Y-%m-%d').strftime('%Y-%m-%d') or False),\
2781                                      (groupby, '<=', alldata[d['id']][groupby] and datetime.datetime.strptime(alldata[d['id']][groupby][:7] + '-' + str(days), '%Y-%m-%d').strftime('%Y-%m-%d') or False)] + domain
2782                 del alldata[d['id']][groupby]
2783             d.update(alldata[d['id']])
2784             del d['id']
2785
2786         if groupby and groupby in self._group_by_full:
2787             result = self._read_group_fill_results(cr, uid, domain, groupby, groupby_list,
2788                                                    aggregated_fields, result, read_group_order=order,
2789                                                    context=context)
2790
2791         return result
2792
2793     def _inherits_join_add(self, current_model, parent_model_name, query):
2794         """
2795         Add missing table SELECT and JOIN clause to ``query`` for reaching the parent table (no duplicates)
2796         :param current_model: current model object
2797         :param parent_model_name: name of the parent model for which the clauses should be added
2798         :param query: query object on which the JOIN should be added
2799         """
2800         inherits_field = current_model._inherits[parent_model_name]
2801         parent_model = self.pool.get(parent_model_name)
2802         parent_alias, parent_alias_statement = query.add_join((current_model._table, parent_model._table, inherits_field, 'id', inherits_field), implicit=True)
2803         return parent_alias
2804
2805     def _inherits_join_calc(self, field, query):
2806         """
2807         Adds missing table select and join clause(s) to ``query`` for reaching
2808         the field coming from an '_inherits' parent table (no duplicates).
2809
2810         :param field: name of inherited field to reach
2811         :param query: query object on which the JOIN should be added
2812         :return: qualified name of field, to be used in SELECT clause
2813         """
2814         current_table = self
2815         parent_alias = '"%s"' % current_table._table
2816         while field in current_table._inherit_fields and not field in current_table._columns:
2817             parent_model_name = current_table._inherit_fields[field][0]
2818             parent_table = self.pool.get(parent_model_name)
2819             parent_alias = self._inherits_join_add(current_table, parent_model_name, query)
2820             current_table = parent_table
2821         return '%s."%s"' % (parent_alias, field)
2822
2823     def _parent_store_compute(self, cr):
2824         if not self._parent_store:
2825             return
2826         _logger.info('Computing parent left and right for table %s...', self._table)
2827         def browse_rec(root, pos=0):
2828 # TODO: set order
2829             where = self._parent_name+'='+str(root)
2830             if not root:
2831                 where = self._parent_name+' IS NULL'
2832             if self._parent_order:
2833                 where += ' order by '+self._parent_order
2834             cr.execute('SELECT id FROM '+self._table+' WHERE '+where)
2835             pos2 = pos + 1
2836             for id in cr.fetchall():
2837                 pos2 = browse_rec(id[0], pos2)
2838             cr.execute('update '+self._table+' set parent_left=%s, parent_right=%s where id=%s', (pos, pos2, root))
2839             return pos2 + 1
2840         query = 'SELECT id FROM '+self._table+' WHERE '+self._parent_name+' IS NULL'
2841         if self._parent_order:
2842             query += ' order by ' + self._parent_order
2843         pos = 0
2844         cr.execute(query)
2845         for (root,) in cr.fetchall():
2846             pos = browse_rec(root, pos)
2847         return True
2848
2849     def _update_store(self, cr, f, k):
2850         _logger.info("storing computed values of fields.function '%s'", k)
2851         ss = self._columns[k]._symbol_set
2852         update_query = 'UPDATE "%s" SET "%s"=%s WHERE id=%%s' % (self._table, k, ss[0])
2853         cr.execute('select id from '+self._table)
2854         ids_lst = map(lambda x: x[0], cr.fetchall())
2855         while ids_lst:
2856             iids = ids_lst[:AUTOINIT_RECALCULATE_STORED_FIELDS]
2857             ids_lst = ids_lst[AUTOINIT_RECALCULATE_STORED_FIELDS:]
2858             res = f.get(cr, self, iids, k, SUPERUSER_ID, {})
2859             for key, val in res.items():
2860                 if f._multi:
2861                     val = val[k]
2862                 # if val is a many2one, just write the ID
2863                 if type(val) == tuple:
2864                     val = val[0]
2865                 if val is not False:
2866                     cr.execute(update_query, (ss[1](val), key))
2867
2868     def _check_selection_field_value(self, cr, uid, field, value, context=None):
2869         """Raise except_orm if value is not among the valid values for the selection field"""
2870         if self._columns[field]._type == 'reference':
2871             val_model, val_id_str = value.split(',', 1)
2872             val_id = False
2873             try:
2874                 val_id = long(val_id_str)
2875             except ValueError:
2876                 pass
2877             if not val_id:
2878                 raise except_orm(_('ValidateError'),
2879                                  _('Invalid value for reference field "%s.%s" (last part must be a non-zero integer): "%s"') % (self._table, field, value))
2880             val = val_model
2881         else:
2882             val = value
2883         if isinstance(self._columns[field].selection, (tuple, list)):
2884             if val in dict(self._columns[field].selection):
2885                 return
2886         elif val in dict(self._columns[field].selection(self, cr, uid, context=context)):
2887             return
2888         raise except_orm(_('ValidateError'),
2889                          _('The value "%s" for the field "%s.%s" is not in the selection') % (value, self._table, field))
2890
2891     def _check_removed_columns(self, cr, log=False):
2892         # iterate on the database columns to drop the NOT NULL constraints
2893         # of fields which were required but have been removed (or will be added by another module)
2894         columns = [c for c in self._columns if not (isinstance(self._columns[c], fields.function) and not self._columns[c].store)]
2895         columns += MAGIC_COLUMNS
2896         cr.execute("SELECT a.attname, a.attnotnull"
2897                    "  FROM pg_class c, pg_attribute a"
2898                    " WHERE c.relname=%s"
2899                    "   AND c.oid=a.attrelid"
2900                    "   AND a.attisdropped=%s"
2901                    "   AND pg_catalog.format_type(a.atttypid, a.atttypmod) NOT IN ('cid', 'tid', 'oid', 'xid')"
2902                    "   AND a.attname NOT IN %s", (self._table, False, tuple(columns))),
2903
2904         for column in cr.dictfetchall():
2905             if log:
2906                 _logger.debug("column %s is in the table %s but not in the corresponding object %s",
2907                               column['attname'], self._table, self._name)
2908             if column['attnotnull']:
2909                 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, column['attname']))
2910                 _schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
2911                               self._table, column['attname'])
2912
2913     def _save_constraint(self, cr, constraint_name, type):
2914         """
2915         Record the creation of a constraint for this model, to make it possible
2916         to delete it later when the module is uninstalled. Type can be either
2917         'f' or 'u' depending on the constraint being a foreign key or not.
2918         """
2919         if not self._module:
2920             # no need to save constraints for custom models as they're not part
2921             # of any module
2922             return
2923         assert type in ('f', 'u')
2924         cr.execute("""
2925             SELECT 1 FROM ir_model_constraint, ir_module_module
2926             WHERE ir_model_constraint.module=ir_module_module.id
2927                 AND ir_model_constraint.name=%s
2928                 AND ir_module_module.name=%s
2929             """, (constraint_name, self._module))
2930         if not cr.rowcount:
2931             cr.execute("""
2932                 INSERT INTO ir_model_constraint
2933                     (name, date_init, date_update, module, model, type)
2934                 VALUES (%s, now() AT TIME ZONE 'UTC', now() AT TIME ZONE 'UTC',
2935                     (SELECT id FROM ir_module_module WHERE name=%s),
2936                     (SELECT id FROM ir_model WHERE model=%s), %s)""",
2937                     (constraint_name, self._module, self._name, type))
2938
2939     def _save_relation_table(self, cr, relation_table):
2940         """
2941         Record the creation of a many2many for this model, to make it possible
2942         to delete it later when the module is uninstalled.
2943         """
2944         cr.execute("""
2945             SELECT 1 FROM ir_model_relation, ir_module_module
2946             WHERE ir_model_relation.module=ir_module_module.id
2947                 AND ir_model_relation.name=%s
2948                 AND ir_module_module.name=%s
2949             """, (relation_table, self._module))
2950         if not cr.rowcount:
2951             cr.execute("""INSERT INTO ir_model_relation (name, date_init, date_update, module, model)
2952                                  VALUES (%s, now() AT TIME ZONE 'UTC', now() AT TIME ZONE 'UTC',
2953                     (SELECT id FROM ir_module_module WHERE name=%s),
2954                     (SELECT id FROM ir_model WHERE model=%s))""",
2955                        (relation_table, self._module, self._name))
2956
2957     # checked version: for direct m2o starting from `self`
2958     def _m2o_add_foreign_key_checked(self, source_field, dest_model, ondelete):
2959         assert self.is_transient() or not dest_model.is_transient(), \
2960             'Many2One relationships from non-transient Model to TransientModel are forbidden'
2961         if self.is_transient() and not dest_model.is_transient():
2962             # TransientModel relationships to regular Models are annoying
2963             # usually because they could block deletion due to the FKs.
2964             # So unless stated otherwise we default them to ondelete=cascade.
2965             ondelete = ondelete or 'cascade'
2966         fk_def = (self._table, source_field, dest_model._table, ondelete or 'set null')
2967         self._foreign_keys.add(fk_def)
2968         _schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s", *fk_def)
2969
2970     # unchecked version: for custom cases, such as m2m relationships
2971     def _m2o_add_foreign_key_unchecked(self, source_table, source_field, dest_model, ondelete):
2972         fk_def = (source_table, source_field, dest_model._table, ondelete or 'set null')
2973         self._foreign_keys.add(fk_def)
2974         _schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s", *fk_def)
2975
2976     def _drop_constraint(self, cr, source_table, constraint_name):
2977         cr.execute("ALTER TABLE %s DROP CONSTRAINT %s" % (source_table,constraint_name))
2978
2979     def _m2o_fix_foreign_key(self, cr, source_table, source_field, dest_model, ondelete):
2980         # Find FK constraint(s) currently established for the m2o field,
2981         # and see whether they are stale or not
2982         cr.execute("""SELECT confdeltype as ondelete_rule, conname as constraint_name,
2983                              cl2.relname as foreign_table
2984                       FROM pg_constraint as con, pg_class as cl1, pg_class as cl2,
2985                            pg_attribute as att1, pg_attribute as att2
2986                       WHERE con.conrelid = cl1.oid
2987                         AND cl1.relname = %s
2988                         AND con.confrelid = cl2.oid
2989                         AND array_lower(con.conkey, 1) = 1
2990                         AND con.conkey[1] = att1.attnum
2991                         AND att1.attrelid = cl1.oid
2992                         AND att1.attname = %s
2993                         AND array_lower(con.confkey, 1) = 1
2994                         AND con.confkey[1] = att2.attnum
2995                         AND att2.attrelid = cl2.oid
2996                         AND att2.attname = %s
2997                         AND con.contype = 'f'""", (source_table, source_field, 'id'))
2998         constraints = cr.dictfetchall()
2999         if constraints:
3000             if len(constraints) == 1:
3001                 # Is it the right constraint?
3002                 cons, = constraints
3003                 if cons['ondelete_rule'] != POSTGRES_CONFDELTYPES.get((ondelete or 'set null').upper(), 'a')\
3004                     or cons['foreign_table'] != dest_model._table:
3005                     # Wrong FK: drop it and recreate
3006                     _schema.debug("Table '%s': dropping obsolete FK constraint: '%s'",
3007                                   source_table, cons['constraint_name'])
3008                     self._drop_constraint(cr, source_table, cons['constraint_name'])
3009                 else:
3010                     # it's all good, nothing to do!
3011                     return
3012             else:
3013                 # Multiple FKs found for the same field, drop them all, and re-create
3014                 for cons in constraints:
3015                     _schema.debug("Table '%s': dropping duplicate FK constraints: '%s'",
3016                                   source_table, cons['constraint_name'])
3017                     self._drop_constraint(cr, source_table, cons['constraint_name'])
3018
3019         # (re-)create the FK
3020         self._m2o_add_foreign_key_checked(source_field, dest_model, ondelete)
3021
3022
3023
3024     def _auto_init(self, cr, context=None):
3025         """
3026
3027         Call _field_create and, unless _auto is False:
3028
3029         - create the corresponding table in database for the model,
3030         - possibly add the parent columns in database,
3031         - possibly add the columns 'create_uid', 'create_date', 'write_uid',
3032           'write_date' in database if _log_access is True (the default),
3033         - report on database columns no more existing in _columns,
3034         - remove no more existing not null constraints,
3035         - alter existing database columns to match _columns,
3036         - create database tables to match _columns,
3037         - add database indices to match _columns,
3038         - save in self._foreign_keys a list a foreign keys to create (see
3039           _auto_end).
3040
3041         """
3042         self._foreign_keys = set()
3043         raise_on_invalid_object_name(self._name)
3044         if context is None:
3045             context = {}
3046         store_compute = False
3047         todo_end = []
3048         update_custom_fields = context.get('update_custom_fields', False)
3049         self._field_create(cr, context=context)
3050         create = not self._table_exist(cr)
3051         if getattr(self, '_auto', True):
3052
3053             if create:
3054                 self._create_table(cr)
3055
3056             cr.commit()
3057             if self._parent_store:
3058                 if not self._parent_columns_exist(cr):
3059                     self._create_parent_columns(cr)
3060                     store_compute = True
3061
3062             # Create the create_uid, create_date, write_uid, write_date, columns if desired.
3063             if self._log_access:
3064                 self._add_log_columns(cr)
3065
3066             self._check_removed_columns(cr, log=False)
3067
3068             # iterate on the "object columns"
3069             column_data = self._select_column_data(cr)
3070
3071             for k, f in self._columns.iteritems():
3072                 if k in MAGIC_COLUMNS:
3073                     continue
3074                 # Don't update custom (also called manual) fields
3075                 if f.manual and not update_custom_fields:
3076                     continue
3077
3078                 if isinstance(f, fields.one2many):
3079                     self._o2m_raise_on_missing_reference(cr, f)
3080
3081                 elif isinstance(f, fields.many2many):
3082                     self._m2m_raise_or_create_relation(cr, f)
3083
3084                 else:
3085                     res = column_data.get(k)
3086
3087                     # The field is not found as-is in database, try if it
3088                     # exists with an old name.
3089                     if not res and hasattr(f, 'oldname'):
3090                         res = column_data.get(f.oldname)
3091                         if res:
3092                             cr.execute('ALTER TABLE "%s" RENAME "%s" TO "%s"' % (self._table, f.oldname, k))
3093                             res['attname'] = k
3094                             column_data[k] = res
3095                             _schema.debug("Table '%s': renamed column '%s' to '%s'",
3096                                 self._table, f.oldname, k)
3097
3098                     # The field already exists in database. Possibly
3099                     # change its type, rename it, drop it or change its
3100                     # constraints.
3101                     if res:
3102                         f_pg_type = res['typname']
3103                         f_pg_size = res['size']
3104                         f_pg_notnull = res['attnotnull']
3105                         if isinstance(f, fields.function) and not f.store and\
3106                                 not getattr(f, 'nodrop', False):
3107                             _logger.info('column %s (%s) in table %s removed: converted to a function !\n',
3108                                          k, f.string, self._table)
3109                             cr.execute('ALTER TABLE "%s" DROP COLUMN "%s" CASCADE' % (self._table, k))
3110                             cr.commit()
3111                             _schema.debug("Table '%s': dropped column '%s' with cascade",
3112                                 self._table, k)
3113                             f_obj_type = None
3114                         else:
3115                             f_obj_type = get_pg_type(f) and get_pg_type(f)[0]
3116
3117                         if f_obj_type:
3118                             ok = False
3119                             casts = [
3120                                 ('text', 'char', pg_varchar(f.size), '::%s' % pg_varchar(f.size)),
3121                                 ('varchar', 'text', 'TEXT', ''),
3122                                 ('int4', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
3123                                 ('date', 'datetime', 'TIMESTAMP', '::TIMESTAMP'),
3124                                 ('timestamp', 'date', 'date', '::date'),
3125                                 ('numeric', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
3126                                 ('float8', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
3127                             ]
3128                             if f_pg_type == 'varchar' and f._type == 'char' and f_pg_size and (f.size is None or f_pg_size < f.size):
3129                                 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
3130                                 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, pg_varchar(f.size)))
3131                                 cr.execute('UPDATE "%s" SET "%s"=temp_change_size::%s' % (self._table, k, pg_varchar(f.size)))
3132                                 cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
3133                                 cr.commit()
3134                                 _schema.debug("Table '%s': column '%s' (type varchar) changed size from %s to %s",
3135                                     self._table, k, f_pg_size or 'unlimited', f.size or 'unlimited')
3136                             for c in casts:
3137                                 if (f_pg_type==c[0]) and (f._type==c[1]):
3138                                     if f_pg_type != f_obj_type:
3139                                         ok = True
3140                                         cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
3141                                         cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, c[2]))
3142                                         cr.execute(('UPDATE "%s" SET "%s"=temp_change_size'+c[3]) % (self._table, k))
3143                                         cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
3144                                         cr.commit()
3145                                         _schema.debug("Table '%s': column '%s' changed type from %s to %s",
3146                                             self._table, k, c[0], c[1])
3147                                     break
3148
3149                             if f_pg_type != f_obj_type:
3150                                 if not ok:
3151                                     i = 0
3152                                     while True:
3153                                         newname = k + '_moved' + str(i)
3154                                         cr.execute("SELECT count(1) FROM pg_class c,pg_attribute a " \
3155                                             "WHERE c.relname=%s " \
3156                                             "AND a.attname=%s " \
3157                                             "AND c.oid=a.attrelid ", (self._table, newname))
3158                                         if not cr.fetchone()[0]:
3159                                             break
3160                                         i += 1
3161                                     if f_pg_notnull:
3162                                         cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
3163                                     cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO "%s"' % (self._table, k, newname))
3164                                     cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
3165                                     cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,))
3166                                     _schema.debug("Table '%s': column '%s' has changed type (DB=%s, def=%s), data moved to column %s !",
3167                                         self._table, k, f_pg_type, f._type, newname)
3168
3169                             # if the field is required and hasn't got a NOT NULL constraint
3170                             if f.required and f_pg_notnull == 0:
3171                                 # set the field to the default value if any
3172                                 if k in self._defaults:
3173                                     if callable(self._defaults[k]):
3174                                         default = self._defaults[k](self, cr, SUPERUSER_ID, context)
3175                                     else:
3176                                         default = self._defaults[k]
3177
3178                                     if default is not None:
3179                                         ss = self._columns[k]._symbol_set
3180                                         query = 'UPDATE "%s" SET "%s"=%s WHERE "%s" is NULL' % (self._table, k, ss[0], k)
3181                                         cr.execute(query, (ss[1](default),))
3182                                 # add the NOT NULL constraint
3183                                 cr.commit()
3184                                 try:
3185                                     cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False)
3186                                     cr.commit()
3187                                     _schema.debug("Table '%s': column '%s': added NOT NULL constraint",
3188                                         self._table, k)
3189                                 except Exception:
3190                                     msg = "Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\
3191                                         "If you want to have it, you should update the records and execute manually:\n"\
3192                                         "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
3193                                     _schema.warning(msg, self._table, k, self._table, k)
3194                                 cr.commit()
3195                             elif not f.required and f_pg_notnull == 1:
3196                                 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
3197                                 cr.commit()
3198                                 _schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
3199                                     self._table, k)
3200                             # Verify index
3201                             indexname = '%s_%s_index' % (self._table, k)
3202                             cr.execute("SELECT indexname FROM pg_indexes WHERE indexname = %s and tablename = %s", (indexname, self._table))
3203                             res2 = cr.dictfetchall()
3204                             if not res2 and f.select:
3205                                 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
3206                                 cr.commit()
3207                                 if f._type == 'text':
3208                                     # FIXME: for fields.text columns we should try creating GIN indexes instead (seems most suitable for an ERP context)
3209                                     msg = "Table '%s': Adding (b-tree) index for %s column '%s'."\
3210                                         "This is probably useless (does not work for fulltext search) and prevents INSERTs of long texts"\
3211                                         " because there is a length limit for indexable btree values!\n"\
3212                                         "Use a search view instead if you simply want to make the field searchable."
3213                                     _schema.warning(msg, self._table, f._type, k)
3214                             if res2 and not f.select:
3215                                 cr.execute('DROP INDEX "%s_%s_index"' % (self._table, k))
3216                                 cr.commit()
3217                                 msg = "Table '%s': dropping index for column '%s' of type '%s' as it is not required anymore"
3218                                 _schema.debug(msg, self._table, k, f._type)
3219
3220                             if isinstance(f, fields.many2one) or (isinstance(f, fields.function) and f._type == 'many2one' and f.store):
3221                                 dest_model = self.pool.get(f._obj)
3222                                 if dest_model._table != 'ir_actions':
3223                                     self._m2o_fix_foreign_key(cr, self._table, k, dest_model, f.ondelete)
3224
3225                     # The field doesn't exist in database. Create it if necessary.
3226                     else:
3227                         if not isinstance(f, fields.function) or f.store:
3228                             # add the missing field
3229                             cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
3230                             cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,))
3231                             _schema.debug("Table '%s': added column '%s' with definition=%s",
3232                                 self._table, k, get_pg_type(f)[1])
3233
3234                             # initialize it
3235                             if not create and k in self._defaults:
3236                                 if callable(self._defaults[k]):
3237                                     default = self._defaults[k](self, cr, SUPERUSER_ID, context)
3238                                 else:
3239                                     default = self._defaults[k]
3240
3241                                 ss = self._columns[k]._symbol_set
3242                                 query = 'UPDATE "%s" SET "%s"=%s' % (self._table, k, ss[0])
3243                                 cr.execute(query, (ss[1](default),))
3244                                 cr.commit()
3245                                 _logger.debug("Table '%s': setting default value of new column %s", self._table, k)
3246
3247                             # remember the functions to call for the stored fields
3248                             if isinstance(f, fields.function):
3249                                 order = 10
3250                                 if f.store is not True: # i.e. if f.store is a dict
3251                                     order = f.store[f.store.keys()[0]][2]
3252                                 todo_end.append((order, self._update_store, (f, k)))
3253
3254                             # and add constraints if needed
3255                             if isinstance(f, fields.many2one) or (isinstance(f, fields.function) and f._type == 'many2one' and f.store):
3256                                 if not self.pool.get(f._obj):
3257                                     raise except_orm('Programming Error', 'There is no reference available for %s' % (f._obj,))
3258                                 dest_model = self.pool.get(f._obj)
3259                                 ref = dest_model._table
3260                                 # ir_actions is inherited so foreign key doesn't work on it
3261                                 if ref != 'ir_actions':
3262                                     self._m2o_add_foreign_key_checked(k, dest_model, f.ondelete)
3263                             if f.select:
3264                                 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
3265                             if f.required:
3266                                 try:
3267                                     cr.commit()
3268                                     cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False)
3269                                     _schema.debug("Table '%s': column '%s': added a NOT NULL constraint",
3270                                         self._table, k)
3271                                 except Exception:
3272                                     msg = "WARNING: unable to set column %s of table %s not null !\n"\
3273                                         "Try to re-run: openerp-server --update=module\n"\
3274                                         "If it doesn't work, update records and execute manually:\n"\
3275                                         "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
3276                                     _logger.warning(msg, k, self._table, self._table, k)
3277                             cr.commit()
3278
3279         else:
3280             cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
3281             create = not bool(cr.fetchone())
3282
3283         cr.commit()     # start a new transaction
3284
3285         if getattr(self, '_auto', True):
3286             self._add_sql_constraints(cr)
3287
3288         if create:
3289             self._execute_sql(cr)
3290
3291         if store_compute:
3292             self._parent_store_compute(cr)
3293             cr.commit()
3294
3295         return todo_end
3296
3297     def _auto_end(self, cr, context=None):
3298         """ Create the foreign keys recorded by _auto_init. """
3299         for t, k, r, d in self._foreign_keys:
3300             cr.execute('ALTER TABLE "%s" ADD FOREIGN KEY ("%s") REFERENCES "%s" ON DELETE %s' % (t, k, r, d))
3301             self._save_constraint(cr, "%s_%s_fkey" % (t, k), 'f')
3302         cr.commit()
3303         del self._foreign_keys
3304
3305
3306     def _table_exist(self, cr):
3307         cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
3308         return cr.rowcount
3309
3310
3311     def _create_table(self, cr):
3312         cr.execute('CREATE TABLE "%s" (id SERIAL NOT NULL, PRIMARY KEY(id))' % (self._table,))
3313         cr.execute(("COMMENT ON TABLE \"%s\" IS %%s" % self._table), (self._description,))
3314         _schema.debug("Table '%s': created", self._table)
3315
3316
3317     def _parent_columns_exist(self, cr):
3318         cr.execute("""SELECT c.relname
3319             FROM pg_class c, pg_attribute a
3320             WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
3321             """, (self._table, 'parent_left'))
3322         return cr.rowcount
3323
3324
3325     def _create_parent_columns(self, cr):
3326         cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_left" INTEGER' % (self._table,))
3327         cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_right" INTEGER' % (self._table,))
3328         if 'parent_left' not in self._columns:
3329             _logger.error('create a column parent_left on object %s: fields.integer(\'Left Parent\', select=1)',
3330                           self._table)
3331             _schema.debug("Table '%s': added column '%s' with definition=%s",
3332                 self._table, 'parent_left', 'INTEGER')
3333         elif not self._columns['parent_left'].select:
3334             _logger.error('parent_left column on object %s must be indexed! Add select=1 to the field definition)',
3335                           self._table)
3336         if 'parent_right' not in self._columns:
3337             _logger.error('create a column parent_right on object %s: fields.integer(\'Right Parent\', select=1)',
3338                           self._table)
3339             _schema.debug("Table '%s': added column '%s' with definition=%s",
3340                 self._table, 'parent_right', 'INTEGER')
3341         elif not self._columns['parent_right'].select:
3342             _logger.error('parent_right column on object %s must be indexed! Add select=1 to the field definition)',
3343                           self._table)
3344         if self._columns[self._parent_name].ondelete not in ('cascade', 'restrict'):
3345             _logger.error("The column %s on object %s must be set as ondelete='cascade' or 'restrict'",
3346                           self._parent_name, self._name)
3347
3348         cr.commit()
3349
3350
3351     def _add_log_columns(self, cr):
3352         for field, field_def in LOG_ACCESS_COLUMNS.iteritems():
3353             cr.execute("""
3354                 SELECT c.relname
3355                   FROM pg_class c, pg_attribute a
3356                  WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
3357                 """, (self._table, field))
3358             if not cr.rowcount:
3359                 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, field, field_def))
3360                 cr.commit()
3361                 _schema.debug("Table '%s': added column '%s' with definition=%s",
3362                     self._table, field, field_def)
3363
3364
3365     def _select_column_data(self, cr):
3366         # attlen is the number of bytes necessary to represent the type when
3367         # the type has a fixed size. If the type has a varying size attlen is
3368         # -1 and atttypmod is the size limit + 4, or -1 if there is no limit.
3369         cr.execute("SELECT c.relname,a.attname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,t.typname,CASE WHEN a.attlen=-1 THEN (CASE WHEN a.atttypmod=-1 THEN 0 ELSE a.atttypmod-4 END) ELSE a.attlen END as size " \
3370            "FROM pg_class c,pg_attribute a,pg_type t " \
3371            "WHERE c.relname=%s " \
3372            "AND c.oid=a.attrelid " \
3373            "AND a.atttypid=t.oid", (self._table,))
3374         return dict(map(lambda x: (x['attname'], x),cr.dictfetchall()))
3375
3376
3377     def _o2m_raise_on_missing_reference(self, cr, f):
3378         # TODO this check should be a method on fields.one2many.
3379
3380         other = self.pool.get(f._obj)
3381         if other:
3382             # TODO the condition could use fields_get_keys().
3383             if f._fields_id not in other._columns.keys():
3384                 if f._fields_id not in other._inherit_fields.keys():
3385                     raise except_orm('Programming Error', "There is no reference field '%s' found for '%s'" % (f._fields_id, f._obj,))
3386
3387     def _m2m_raise_or_create_relation(self, cr, f):
3388         m2m_tbl, col1, col2 = f._sql_names(self)
3389         self._save_relation_table(cr, m2m_tbl)
3390         cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (m2m_tbl,))
3391         if not cr.dictfetchall():
3392             if not self.pool.get(f._obj):
3393                 raise except_orm('Programming Error', 'Many2Many destination model does not exist: `%s`' % (f._obj,))
3394             dest_model = self.pool.get(f._obj)
3395             ref = dest_model._table
3396             cr.execute('CREATE TABLE "%s" ("%s" INTEGER NOT NULL, "%s" INTEGER NOT NULL, UNIQUE("%s","%s"))' % (m2m_tbl, col1, col2, col1, col2))
3397             # create foreign key references with ondelete=cascade, unless the targets are SQL views
3398             cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (ref,))
3399             if not cr.fetchall():
3400                 self._m2o_add_foreign_key_unchecked(m2m_tbl, col2, dest_model, 'cascade')
3401             cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (self._table,))
3402             if not cr.fetchall():
3403                 self._m2o_add_foreign_key_unchecked(m2m_tbl, col1, self, 'cascade')
3404
3405             cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col1, m2m_tbl, col1))
3406             cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col2, m2m_tbl, col2))
3407             cr.execute("COMMENT ON TABLE \"%s\" IS 'RELATION BETWEEN %s AND %s'" % (m2m_tbl, self._table, ref))
3408             cr.commit()
3409             _schema.debug("Create table '%s': m2m relation between '%s' and '%s'", m2m_tbl, self._table, ref)
3410
3411
3412     def _add_sql_constraints(self, cr):
3413         """
3414
3415         Modify this model's database table constraints so they match the one in
3416         _sql_constraints.
3417
3418         """
3419         def unify_cons_text(txt):
3420             return txt.lower().replace(', ',',').replace(' (','(')
3421
3422         for (key, con, _) in self._sql_constraints:
3423             conname = '%s_%s' % (self._table, key)
3424
3425             self._save_constraint(cr, conname, 'u')
3426             cr.execute("SELECT conname, pg_catalog.pg_get_constraintdef(oid, true) as condef FROM pg_constraint where conname=%s", (conname,))
3427             existing_constraints = cr.dictfetchall()
3428             sql_actions = {
3429                 'drop': {
3430                     'execute': False,
3431                     'query': 'ALTER TABLE "%s" DROP CONSTRAINT "%s"' % (self._table, conname, ),
3432                     'msg_ok': "Table '%s': dropped constraint '%s'. Reason: its definition changed from '%%s' to '%s'" % (
3433                         self._table, conname, con),
3434                     'msg_err': "Table '%s': unable to drop \'%s\' constraint !" % (self._table, con),
3435                     'order': 1,
3436                 },
3437                 'add': {
3438                     'execute': False,
3439                     'query': 'ALTER TABLE "%s" ADD CONSTRAINT "%s" %s' % (self._table, conname, con,),
3440                     'msg_ok': "Table '%s': added constraint '%s' with definition=%s" % (self._table, conname, con),
3441                     'msg_err': "Table '%s': unable to add \'%s\' constraint !\n If you want to have it, you should update the records and execute manually:\n%%s" % (
3442                         self._table, con),
3443                     'order': 2,
3444                 },
3445             }
3446
3447             if not existing_constraints:
3448                 # constraint does not exists:
3449                 sql_actions['add']['execute'] = True
3450                 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
3451             elif unify_cons_text(con) not in [unify_cons_text(item['condef']) for item in existing_constraints]:
3452                 # constraint exists but its definition has changed:
3453                 sql_actions['drop']['execute'] = True
3454                 sql_actions['drop']['msg_ok'] = sql_actions['drop']['msg_ok'] % (existing_constraints[0]['condef'].lower(), )
3455                 sql_actions['add']['execute'] = True
3456                 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
3457
3458             # we need to add the constraint:
3459             sql_actions = [item for item in sql_actions.values()]
3460             sql_actions.sort(key=lambda x: x['order'])
3461             for sql_action in [action for action in sql_actions if action['execute']]:
3462                 try:
3463                     cr.execute(sql_action['query'])
3464                     cr.commit()
3465                     _schema.debug(sql_action['msg_ok'])
3466                 except:
3467                     _schema.warning(sql_action['msg_err'])
3468                     cr.rollback()
3469
3470
3471     def _execute_sql(self, cr):
3472         """ Execute the SQL code from the _sql attribute (if any)."""
3473         if hasattr(self, "_sql"):
3474             for line in self._sql.split(';'):
3475                 line2 = line.replace('\n', '').strip()
3476                 if line2:
3477                     cr.execute(line2)
3478                     cr.commit()
3479
3480     #
3481     # Update objects that uses this one to update their _inherits fields
3482     #
3483
3484     def _inherits_reload_src(self):
3485         """ Recompute the _inherit_fields mapping on each _inherits'd child model."""
3486         for obj in self.pool.models.values():
3487             if self._name in obj._inherits:
3488                 obj._inherits_reload()
3489
3490
3491     def _inherits_reload(self):
3492         """ Recompute the _inherit_fields mapping.
3493
3494         This will also call itself on each inherits'd child model.
3495
3496         """
3497         res = {}
3498         for table in self._inherits:
3499             other = self.pool.get(table)
3500             for col in other._columns.keys():
3501                 res[col] = (table, self._inherits[table], other._columns[col], table)
3502             for col in other._inherit_fields.keys():
3503                 res[col] = (table, self._inherits[table], other._inherit_fields[col][2], other._inherit_fields[col][3])
3504         self._inherit_fields = res
3505         self._all_columns = self._get_column_infos()
3506         self._inherits_reload_src()
3507
3508
3509     def _get_column_infos(self):
3510         """Returns a dict mapping all fields names (direct fields and
3511            inherited field via _inherits) to a ``column_info`` struct
3512            giving detailed columns """
3513         result = {}
3514         for k, (parent, m2o, col, original_parent) in self._inherit_fields.iteritems():
3515             result[k] = fields.column_info(k, col, parent, m2o, original_parent)
3516         for k, col in self._columns.iteritems():
3517             result[k] = fields.column_info(k, col)
3518         return result
3519
3520
3521     def _inherits_check(self):
3522         for table, field_name in self._inherits.items():
3523             if field_name not in self._columns:
3524                 _logger.info('Missing many2one field definition for _inherits reference "%s" in "%s", using default one.', field_name, self._name)
3525                 self._columns[field_name] = fields.many2one(table, string="Automatically created field to link to parent %s" % table,
3526                                                              required=True, ondelete="cascade")
3527             elif not self._columns[field_name].required or self._columns[field_name].ondelete.lower() not in ("cascade", "restrict"):
3528                 _logger.warning('Field definition for _inherits reference "%s" in "%s" must be marked as "required" with ondelete="cascade" or "restrict", forcing it to required + cascade.', field_name, self._name)
3529                 self._columns[field_name].required = True
3530                 self._columns[field_name].ondelete = "cascade"
3531
3532     #def __getattr__(self, name):
3533     #    """
3534     #    Proxies attribute accesses to the `inherits` parent so we can call methods defined on the inherited parent
3535     #    (though inherits doesn't use Python inheritance).
3536     #    Handles translating between local ids and remote ids.
3537     #    Known issue: doesn't work correctly when using python's own super(), don't involve inherit-based inheritance
3538     #                 when you have inherits.
3539     #    """
3540     #    for model, field in self._inherits.iteritems():
3541     #        proxy = self.pool.get(model)
3542     #        if hasattr(proxy, name):
3543     #            attribute = getattr(proxy, name)
3544     #            if not hasattr(attribute, '__call__'):
3545     #                return attribute
3546     #            break
3547     #    else:
3548     #        return super(orm, self).__getattr__(name)
3549
3550     #    def _proxy(cr, uid, ids, *args, **kwargs):
3551     #        objects = self.browse(cr, uid, ids, kwargs.get('context', None))
3552     #        lst = [obj[field].id for obj in objects if obj[field]]
3553     #        return getattr(proxy, name)(cr, uid, lst, *args, **kwargs)
3554
3555     #    return _proxy
3556
3557
3558     def fields_get(self, cr, user, allfields=None, context=None, write_access=True):
3559         """ Return the definition of each field.
3560
3561         The returned value is a dictionary (indiced by field name) of
3562         dictionaries. The _inherits'd fields are included. The string, help,
3563         and selection (if present) attributes are translated.
3564
3565         :param cr: database cursor
3566         :param user: current user id
3567         :param allfields: list of fields
3568         :param context: context arguments, like lang, time zone
3569         :return: dictionary of field dictionaries, each one describing a field of the business object
3570         :raise AccessError: * if user has no create/write rights on the requested object
3571
3572         """
3573         if context is None:
3574             context = {}
3575
3576         write_access = self.check_access_rights(cr, user, 'write', raise_exception=False) \
3577             or self.check_access_rights(cr, user, 'create', raise_exception=False)
3578
3579         res = {}
3580
3581         translation_obj = self.pool.get('ir.translation')
3582         for parent in self._inherits:
3583             res.update(self.pool.get(parent).fields_get(cr, user, allfields, context))
3584
3585         for f, field in self._columns.iteritems():
3586             if (allfields and f not in allfields) or \
3587                 (field.groups and not self.user_has_groups(cr, user, groups=field.groups, context=context)):
3588                 continue
3589
3590             res[f] = fields.field_to_dict(self, cr, user, field, context=context)
3591
3592             if not write_access:
3593                 res[f]['readonly'] = True
3594                 res[f]['states'] = {}
3595
3596             if 'lang' in context:
3597                 if 'string' in res[f]:
3598                     res_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'field', context['lang'])
3599                     if res_trans:
3600                         res[f]['string'] = res_trans
3601                 if 'help' in res[f]:
3602                     help_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'help', context['lang'])
3603                     if help_trans:
3604                         res[f]['help'] = help_trans
3605                 if 'selection' in res[f]:
3606                     if isinstance(field.selection, (tuple, list)):
3607                         sel = field.selection
3608                         sel2 = []
3609                         for key, val in sel:
3610                             val2 = None
3611                             if val:
3612                                 val2 = translation_obj._get_source(cr, user, self._name + ',' + f, 'selection',  context['lang'], val)
3613                             sel2.append((key, val2 or val))
3614                         res[f]['selection'] = sel2
3615
3616         return res
3617
3618     def check_field_access_rights(self, cr, user, operation, fields, context=None):
3619         """
3620         Check the user access rights on the given fields. This raises Access
3621         Denied if the user does not have the rights. Otherwise it returns the
3622         fields (as is if the fields is not falsy, or the readable/writable
3623         fields if fields is falsy).
3624         """
3625         def p(field_name):
3626             """Predicate to test if the user has access to the given field name."""
3627             # Ignore requested field if it doesn't exist. This is ugly but
3628             # it seems to happen at least with 'name_alias' on res.partner.
3629             if field_name not in self._all_columns:
3630                 return True
3631             field = self._all_columns[field_name].column
3632             if user != SUPERUSER_ID and field.groups:
3633                 return self.user_has_groups(cr, user, groups=field.groups, context=context)
3634             else:
3635                 return True
3636         if not fields:
3637             fields = filter(p, self._all_columns.keys())
3638         else:
3639             filtered_fields = filter(lambda a: not p(a), fields)
3640             if filtered_fields:
3641                 _logger.warning('Access Denied by ACLs for operation: %s, uid: %s, model: %s, fields: %s', operation, user, self._name, ', '.join(filtered_fields))
3642                 raise except_orm(
3643                     _('Access Denied'),
3644                     _('The requested operation cannot be completed due to security restrictions. '
3645                     'Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \
3646                     (self._description, operation))
3647         return fields
3648
3649     def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
3650         """ Read records with given ids with the given fields
3651
3652         :param cr: database cursor
3653         :param user: current user id
3654         :param ids: id or list of the ids of the records to read
3655         :param fields: optional list of field names to return (default: all fields would be returned)
3656         :type fields: list (example ['field_name_1', ...])
3657         :param context: optional context dictionary - it may contains keys for specifying certain options
3658                         like ``context_lang``, ``context_tz`` to alter the results of the call.
3659                         A special ``bin_size`` boolean flag may also be passed in the context to request the
3660                         value of all fields.binary columns to be returned as the size of the binary instead of its
3661                         contents. This can also be selectively overriden by passing a field-specific flag
3662                         in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field.
3663                         Note: The ``bin_size_XXX`` form is new in OpenERP v6.0.
3664         :return: list of dictionaries((dictionary per record asked)) with requested field values
3665         :rtype: [{‘name_of_the_field’: value, ...}, ...]
3666         :raise AccessError: * if user has no read rights on the requested object
3667                             * if user tries to bypass access rules for read on the requested object
3668
3669         """
3670
3671         if not context:
3672             context = {}
3673         self.check_access_rights(cr, user, 'read')
3674         fields = self.check_field_access_rights(cr, user, 'read', fields)
3675         if isinstance(ids, (int, long)):
3676             select = [ids]
3677         else:
3678             select = ids
3679         select = map(lambda x: isinstance(x, dict) and x['id'] or x, select)
3680         result = self._read_flat(cr, user, select, fields, context, load)
3681
3682         for r in result:
3683             for key, v in r.items():
3684                 if v is None:
3685                     r[key] = False
3686
3687         if isinstance(ids, (int, long, dict)):
3688             return result and result[0] or False
3689         return result
3690
3691     def _read_flat(self, cr, user, ids, fields_to_read, context=None, load='_classic_read'):
3692         if not context:
3693             context = {}
3694         if not ids:
3695             return []
3696         if fields_to_read is None:
3697             fields_to_read = self._columns.keys()
3698         else:
3699             fields_to_read = list(set(fields_to_read))
3700
3701         # all inherited fields + all non inherited fields for which the attribute whose name is in load is True
3702         fields_pre = [f for f in fields_to_read if
3703                            f == self.CONCURRENCY_CHECK_FIELD
3704                         or (f in self._columns and getattr(self._columns[f], '_classic_write'))
3705                      ] + self._inherits.values()
3706
3707         res = []
3708         if len(fields_pre):
3709             def convert_field(f):
3710                 f_qual = '%s."%s"' % (self._table, f) # need fully-qualified references in case len(tables) > 1
3711                 if f in ('create_date', 'write_date'):
3712                     return "date_trunc('second', %s) as %s" % (f_qual, f)
3713                 if f == self.CONCURRENCY_CHECK_FIELD:
3714                     if self._log_access:
3715                         return "COALESCE(%s.write_date, %s.create_date, (now() at time zone 'UTC'))::timestamp AS %s" % (self._table, self._table, f,)
3716                     return "(now() at time zone 'UTC')::timestamp AS %s" % (f,)
3717                 if isinstance(self._columns[f], fields.binary) and context.get('bin_size', False):
3718                     return 'length(%s) as "%s"' % (f_qual, f)
3719                 return f_qual
3720
3721             # Construct a clause for the security rules.
3722             # 'tables' hold the list of tables necessary for the SELECT including the ir.rule clauses,
3723             # or will at least contain self._table.
3724             rule_clause, rule_params, tables = self.pool.get('ir.rule').domain_get(cr, user, self._name, 'read', context=context)
3725
3726             fields_pre2 = map(convert_field, fields_pre)
3727             order_by = self._parent_order or self._order
3728             select_fields = ','.join(fields_pre2 + ['%s.id' % self._table])
3729             query = 'SELECT %s FROM %s WHERE %s.id IN %%s' % (select_fields, ','.join(tables), self._table)
3730             if rule_clause:
3731                 query += " AND " + (' OR '.join(rule_clause))
3732             query += " ORDER BY " + order_by
3733             for sub_ids in cr.split_for_in_conditions(ids):
3734                 cr.execute(query, [tuple(sub_ids)] + rule_params)
3735                 results = cr.dictfetchall()
3736                 result_ids = [x['id'] for x in results]
3737                 self._check_record_rules_result_count(cr, user, sub_ids, result_ids, 'read', context=context)
3738                 res.extend(results)
3739         else:
3740             self.check_access_rule(cr, user, ids, 'read', context=context)
3741             res = map(lambda x: {'id': x}, ids)
3742
3743         if context.get('lang'):
3744             for f in fields_pre:
3745                 if f == self.CONCURRENCY_CHECK_FIELD:
3746                     continue
3747                 if self._columns[f].translate:
3748                     ids = [x['id'] for x in res]
3749                     #TODO: optimize out of this loop
3750                     res_trans = self.pool.get('ir.translation')._get_ids(cr, user, self._name+','+f, 'model', context['lang'], ids)
3751                     for r in res:
3752                         r[f] = res_trans.get(r['id'], False) or r[f]
3753
3754         for table in self._inherits:
3755             col = self._inherits[table]
3756             cols = [x for x in intersect(self._inherit_fields.keys(), fields_to_read) if x not in self._columns.keys()]
3757             if not cols:
3758                 continue
3759             res2 = self.pool.get(table).read(cr, user, [x[col] for x in res], cols, context, load)
3760
3761             res3 = {}
3762             for r in res2:
3763                 res3[r['id']] = r
3764                 del r['id']
3765
3766             for record in res:
3767                 if not record[col]: # if the record is deleted from _inherits table?
3768                     continue
3769                 record.update(res3[record[col]])
3770                 if col not in fields_to_read:
3771                     del record[col]
3772
3773         # all fields which need to be post-processed by a simple function (symbol_get)
3774         fields_post = filter(lambda x: x in self._columns and self._columns[x]._symbol_get, fields_to_read)
3775         if fields_post:
3776             for r in res:
3777                 for f in fields_post:
3778                     r[f] = self._columns[f]._symbol_get(r[f])
3779         ids = [x['id'] for x in res]
3780
3781         # all non inherited fields for which the attribute whose name is in load is False
3782         fields_post = filter(lambda x: x in self._columns and not getattr(self._columns[x], load), fields_to_read)
3783
3784         # Compute POST fields
3785         todo = {}
3786         for f in fields_post:
3787             todo.setdefault(self._columns[f]._multi, [])
3788             todo[self._columns[f]._multi].append(f)
3789         for key, val in todo.items():
3790             if key:
3791                 res2 = self._columns[val[0]].get(cr, self, ids, val, user, context=context, values=res)
3792                 assert res2 is not None, \
3793                     'The function field "%s" on the "%s" model returned None\n' \
3794                     '(a dictionary was expected).' % (val[0], self._name)
3795                 for pos in val:
3796                     for record in res:
3797                         if isinstance(res2[record['id']], str): res2[record['id']] = eval(res2[record['id']]) #TOCHECK : why got string instend of dict in python2.6
3798                         multi_fields = res2.get(record['id'],{})
3799                         if multi_fields:
3800                             record[pos] = multi_fields.get(pos,[])
3801             else:
3802                 for f in val:
3803                     res2 = self._columns[f].get(cr, self, ids, f, user, context=context, values=res)
3804                     for record in res:
3805                         if res2:
3806                             record[f] = res2[record['id']]
3807                         else:
3808                             record[f] = []
3809
3810         # Warn about deprecated fields now that fields_pre and fields_post are computed
3811         # Explicitly use list() because we may receive tuples
3812         for f in list(fields_pre) + list(fields_post):
3813             field_column = self._all_columns.get(f) and self._all_columns.get(f).column
3814             if field_column and field_column.deprecated:
3815                 _logger.warning('Field %s.%s is deprecated: %s', self._name, f, field_column.deprecated)
3816
3817         readonly = None
3818         for vals in res:
3819             for field in vals.copy():
3820                 fobj = None
3821                 if field in self._columns:
3822                     fobj = self._columns[field]
3823
3824                 if not fobj:
3825                     continue
3826                 groups = fobj.read
3827                 if groups:
3828                     edit = False
3829                     for group in groups:
3830                         module = group.split(".")[0]
3831                         grp = group.split(".")[1]
3832                         cr.execute("select count(*) from res_groups_users_rel where gid IN (select res_id from ir_model_data where name=%s and module=%s and model=%s) and uid=%s",  \
3833                                    (grp, module, 'res.groups', user))
3834                         readonly = cr.fetchall()
3835                         if readonly[0][0] >= 1:
3836                             edit = True
3837                             break
3838                         elif readonly[0][0] == 0:
3839                             edit = False
3840                         else:
3841                             edit = False
3842
3843                     if not edit:
3844                         if type(vals[field]) == type([]):
3845                             vals[field] = []
3846                         elif type(vals[field]) == type(0.0):
3847                             vals[field] = 0
3848                         elif type(vals[field]) == type(''):
3849                             vals[field] = '=No Permission='
3850                         else:
3851                             vals[field] = False
3852         return res
3853
3854     # TODO check READ access
3855     def perm_read(self, cr, user, ids, context=None, details=True):
3856         """
3857         Returns some metadata about the given records.
3858
3859         :param details: if True, \*_uid fields are replaced with the name of the user
3860         :return: list of ownership dictionaries for each requested record
3861         :rtype: list of dictionaries with the following keys:
3862
3863                     * id: object id
3864                     * create_uid: user who created the record
3865                     * create_date: date when the record was created
3866                     * write_uid: last user who changed the record
3867                     * write_date: date of the last change to the record
3868                     * xmlid: XML ID to use to refer to this record (if there is one), in format ``module.name``
3869         """
3870         if not context:
3871             context = {}
3872         if not ids:
3873             return []
3874         fields = ''
3875         uniq = isinstance(ids, (int, long))
3876         if uniq:
3877             ids = [ids]
3878         fields = ['id']
3879         if self._log_access:
3880             fields += ['create_uid', 'create_date', 'write_uid', 'write_date']
3881         quoted_table = '"%s"' % self._table
3882         fields_str = ",".join('%s.%s'%(quoted_table, field) for field in fields)
3883         query = '''SELECT %s, __imd.module, __imd.name
3884                    FROM %s LEFT JOIN ir_model_data __imd
3885                        ON (__imd.model = %%s and __imd.res_id = %s.id)
3886                    WHERE %s.id IN %%s''' % (fields_str, quoted_table, quoted_table, quoted_table)
3887         cr.execute(query, (self._name, tuple(ids)))
3888         res = cr.dictfetchall()
3889         for r in res:
3890             for key in r:
3891                 r[key] = r[key] or False
3892                 if details and key in ('write_uid', 'create_uid') and r[key]:
3893                     try:
3894                         r[key] = self.pool.get('res.users').name_get(cr, user, [r[key]])[0]
3895                     except Exception:
3896                         pass # Leave the numeric uid there
3897             r['xmlid'] = ("%(module)s.%(name)s" % r) if r['name'] else False
3898             del r['name'], r['module']
3899         if uniq:
3900             return res[ids[0]]
3901         return res
3902
3903     def _check_concurrency(self, cr, ids, context):
3904         if not context:
3905             return
3906         if not (context.get(self.CONCURRENCY_CHECK_FIELD) and self._log_access):
3907             return
3908         check_clause = "(id = %s AND %s < COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp)"
3909         for sub_ids in cr.split_for_in_conditions(ids):
3910             ids_to_check = []
3911             for id in sub_ids:
3912                 id_ref = "%s,%s" % (self._name, id)
3913                 update_date = context[self.CONCURRENCY_CHECK_FIELD].pop(id_ref, None)
3914                 if update_date:
3915                     ids_to_check.extend([id, update_date])
3916             if not ids_to_check:
3917                 continue
3918             cr.execute("SELECT id FROM %s WHERE %s" % (self._table, " OR ".join([check_clause]*(len(ids_to_check)/2))), tuple(ids_to_check))
3919             res = cr.fetchone()
3920             if res:
3921                 # mention the first one only to keep the error message readable
3922                 raise except_orm('ConcurrencyException', _('A document was modified since you last viewed it (%s:%d)') % (self._description, res[0]))
3923
3924     def _check_record_rules_result_count(self, cr, uid, ids, result_ids, operation, context=None):
3925         """Verify the returned rows after applying record rules matches
3926            the length of `ids`, and raise an appropriate exception if it does not.
3927         """
3928         ids, result_ids = set(ids), set(result_ids)
3929         missing_ids = ids - result_ids
3930         if missing_ids:
3931             # Attempt to distinguish record rule restriction vs deleted records,
3932             # to provide a more specific error message - check if the missinf
3933             cr.execute('SELECT id FROM ' + self._table + ' WHERE id IN %s', (tuple(missing_ids),))
3934             if cr.rowcount:
3935                 # the missing ids are (at least partially) hidden by access rules
3936                 if uid == SUPERUSER_ID:
3937                     return
3938                 _logger.warning('Access Denied by record rules for operation: %s, uid: %s, model: %s', operation, uid, self._name)
3939                 raise except_orm(_('Access Denied'),
3940                                  _('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \
3941                                     (self._description, operation))
3942             else:
3943                 # If we get here, the missing_ids are not in the database
3944                 if operation in ('read','unlink'):
3945                     # No need to warn about deleting an already deleted record.
3946                     # And no error when reading a record that was deleted, to prevent spurious
3947                     # errors for non-transactional search/read sequences coming from clients 
3948                     return
3949                 _logger.warning('Failed operation on deleted record(s): %s, uid: %s, model: %s', operation, uid, self._name)
3950                 raise except_orm(_('Missing document(s)'),
3951                                  _('One of the documents you are trying to access has been deleted, please try again after refreshing.'))
3952
3953
3954     def check_access_rights(self, cr, uid, operation, raise_exception=True): # no context on purpose.
3955         """Verifies that the operation given by ``operation`` is allowed for the user
3956            according to the access rights."""
3957         return self.pool.get('ir.model.access').check(cr, uid, self._name, operation, raise_exception)
3958
3959     def check_access_rule(self, cr, uid, ids, operation, context=None):
3960         """Verifies that the operation given by ``operation`` is allowed for the user
3961            according to ir.rules.
3962
3963            :param operation: one of ``write``, ``unlink``
3964            :raise except_orm: * if current ir.rules do not permit this operation.
3965            :return: None if the operation is allowed
3966         """
3967         if uid == SUPERUSER_ID:
3968             return
3969
3970         if self.is_transient():
3971             # Only one single implicit access rule for transient models: owner only!
3972             # This is ok to hardcode because we assert that TransientModels always
3973             # have log_access enabled so that the create_uid column is always there.
3974             # And even with _inherits, these fields are always present in the local
3975             # table too, so no need for JOINs.
3976             cr.execute("""SELECT distinct create_uid
3977                           FROM %s
3978                           WHERE id IN %%s""" % self._table, (tuple(ids),))
3979             uids = [x[0] for x in cr.fetchall()]
3980             if len(uids) != 1 or uids[0] != uid:
3981                 raise except_orm(_('Access Denied'),
3982                                  _('For this kind of document, you may only access records you created yourself.\n\n(Document type: %s)') % (self._description,))
3983         else:
3984             where_clause, where_params, tables = self.pool.get('ir.rule').domain_get(cr, uid, self._name, operation, context=context)
3985             if where_clause:
3986                 where_clause = ' and ' + ' and '.join(where_clause)
3987                 for sub_ids in cr.split_for_in_conditions(ids):
3988                     cr.execute('SELECT ' + self._table + '.id FROM ' + ','.join(tables) +
3989                                ' WHERE ' + self._table + '.id IN %s' + where_clause,
3990                                [sub_ids] + where_params)
3991                     returned_ids = [x['id'] for x in cr.dictfetchall()]
3992                     self._check_record_rules_result_count(cr, uid, sub_ids, returned_ids, operation, context=context)
3993
3994     def _workflow_trigger(self, cr, uid, ids, trigger, context=None):
3995         """Call given workflow trigger as a result of a CRUD operation"""
3996         wf_service = netsvc.LocalService("workflow")
3997         for res_id in ids:
3998             getattr(wf_service, trigger)(uid, self._name, res_id, cr)
3999
4000     def _workflow_signal(self, cr, uid, ids, signal, context=None):
4001         """Send given workflow signal and return a dict mapping ids to workflow results"""
4002         wf_service = netsvc.LocalService("workflow")
4003         result = {}
4004         for res_id in ids:
4005             result[res_id] = wf_service.trg_validate(uid, self._name, res_id, signal, cr)
4006         return result
4007
4008     def unlink(self, cr, uid, ids, context=None):
4009         """
4010         Delete records with given ids
4011
4012         :param cr: database cursor
4013         :param uid: current user id
4014         :param ids: id or list of ids
4015         :param context: (optional) context arguments, like lang, time zone
4016         :return: True
4017         :raise AccessError: * if user has no unlink rights on the requested object
4018                             * if user tries to bypass access rules for unlink on the requested object
4019         :raise UserError: if the record is default property for other records
4020
4021         """
4022         if not ids:
4023             return True
4024         if isinstance(ids, (int, long)):
4025             ids = [ids]
4026
4027         result_store = self._store_get_values(cr, uid, ids, self._all_columns.keys(), context)
4028
4029         self._check_concurrency(cr, ids, context)
4030
4031         self.check_access_rights(cr, uid, 'unlink')
4032
4033         ir_property = self.pool.get('ir.property')
4034
4035         # Check if the records are used as default properties.
4036         domain = [('res_id', '=', False),
4037                   ('value_reference', 'in', ['%s,%s' % (self._name, i) for i in ids]),
4038                  ]
4039         if ir_property.search(cr, uid, domain, context=context):
4040             raise except_orm(_('Error'), _('Unable to delete this document because it is used as a default property'))
4041
4042         # Delete the records' properties.
4043         property_ids = ir_property.search(cr, uid, [('res_id', 'in', ['%s,%s' % (self._name, i) for i in ids])], context=context)
4044         ir_property.unlink(cr, uid, property_ids, context=context)
4045
4046         self._workflow_trigger(cr, uid, ids, 'trg_delete', context=context)
4047
4048         self.check_access_rule(cr, uid, ids, 'unlink', context=context)
4049         pool_model_data = self.pool.get('ir.model.data')
4050         ir_values_obj = self.pool.get('ir.values')
4051         for sub_ids in cr.split_for_in_conditions(ids):
4052             cr.execute('delete from ' + self._table + ' ' \
4053                        'where id IN %s', (sub_ids,))
4054
4055             # Removing the ir_model_data reference if the record being deleted is a record created by xml/csv file,
4056             # as these are not connected with real database foreign keys, and would be dangling references.
4057             # Note: following steps performed as admin to avoid access rights restrictions, and with no context
4058             #       to avoid possible side-effects during admin calls.
4059             # Step 1. Calling unlink of ir_model_data only for the affected IDS
4060             reference_ids = pool_model_data.search(cr, SUPERUSER_ID, [('res_id','in',list(sub_ids)),('model','=',self._name)])
4061             # Step 2. Marching towards the real deletion of referenced records
4062             if reference_ids:
4063                 pool_model_data.unlink(cr, SUPERUSER_ID, reference_ids)
4064
4065             # For the same reason, removing the record relevant to ir_values
4066             ir_value_ids = ir_values_obj.search(cr, uid,
4067                     ['|',('value','in',['%s,%s' % (self._name, sid) for sid in sub_ids]),'&',('res_id','in',list(sub_ids)),('model','=',self._name)],
4068                     context=context)
4069             if ir_value_ids:
4070                 ir_values_obj.unlink(cr, uid, ir_value_ids, context=context)
4071
4072         for order, object, store_ids, fields in result_store:
4073             if object == self._name:
4074                 effective_store_ids = list(set(store_ids) - set(ids))
4075             else:
4076                 effective_store_ids = store_ids
4077             if effective_store_ids:
4078                 obj = self.pool.get(object)
4079                 cr.execute('select id from '+obj._table+' where id IN %s', (tuple(effective_store_ids),))
4080                 rids = map(lambda x: x[0], cr.fetchall())
4081                 if rids:
4082                     obj._store_set_values(cr, uid, rids, fields, context)
4083
4084         return True
4085
4086     #
4087     # TODO: Validate
4088     #
4089     def write(self, cr, user, ids, vals, context=None):
4090         """
4091         Update records with given ids with the given field values
4092
4093         :param cr: database cursor
4094         :param user: current user id
4095         :type user: integer
4096         :param ids: object id or list of object ids to update according to **vals**
4097         :param vals: field values to update, e.g {'field_name': new_field_value, ...}
4098         :type vals: dictionary
4099         :param context: (optional) context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...}
4100         :type context: dictionary
4101         :return: True
4102         :raise AccessError: * if user has no write rights on the requested object
4103                             * if user tries to bypass access rules for write on the requested object
4104         :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
4105         :raise UserError: if a loop would be created in a hierarchy of objects a result of the operation (such as setting an object as its own parent)
4106
4107         **Note**: The type of field values to pass in ``vals`` for relationship fields is specific:
4108
4109             + For a many2many field, a list of tuples is expected.
4110               Here is the list of tuple that are accepted, with the corresponding semantics ::
4111
4112                  (0, 0,  { values })    link to a new record that needs to be created with the given values dictionary
4113                  (1, ID, { values })    update the linked record with id = ID (write *values* on it)
4114                  (2, ID)                remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well)
4115                  (3, ID)                cut the link to the linked record with id = ID (delete the relationship between the two objects but does not delete the target object itself)
4116                  (4, ID)                link to existing record with id = ID (adds a relationship)
4117                  (5)                    unlink all (like using (3,ID) for all linked records)
4118                  (6, 0, [IDs])          replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)
4119
4120                  Example:
4121                     [(6, 0, [8, 5, 6, 4])] sets the many2many to ids [8, 5, 6, 4]
4122
4123             + For a one2many field, a lits of tuples is expected.
4124               Here is the list of tuple that are accepted, with the corresponding semantics ::
4125
4126                  (0, 0,  { values })    link to a new record that needs to be created with the given values dictionary
4127                  (1, ID, { values })    update the linked record with id = ID (write *values* on it)
4128                  (2, ID)                remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well)
4129
4130                  Example:
4131                     [(0, 0, {'field_name':field_value_record1, ...}), (0, 0, {'field_name':field_value_record2, ...})]
4132
4133             + For a many2one field, simply use the ID of target record, which must already exist, or ``False`` to remove the link.
4134             + For a reference field, use a string with the model name, a comma, and the target object id (example: ``'product.product, 5'``)
4135
4136         """
4137         readonly = None
4138         self.check_field_access_rights(cr, user, 'write', vals.keys())
4139         for field in vals.copy():
4140             fobj = None
4141             if field in self._columns:
4142                 fobj = self._columns[field]
4143             elif field in self._inherit_fields:
4144                 fobj = self._inherit_fields[field][2]
4145             if not fobj:
4146                 continue
4147             groups = fobj.write
4148
4149             if groups:
4150                 edit = False
4151                 for group in groups:
4152                     module = group.split(".")[0]
4153                     grp = group.split(".")[1]
4154                     cr.execute("select count(*) from res_groups_users_rel where gid IN (select res_id from ir_model_data where name=%s and module=%s and model=%s) and uid=%s", \
4155                                (grp, module, 'res.groups', user))
4156                     readonly = cr.fetchall()
4157                     if readonly[0][0] >= 1:
4158                         edit = True
4159                         break
4160
4161                 if not edit:
4162                     vals.pop(field)
4163
4164         if not context:
4165             context = {}
4166         if not ids:
4167             return True
4168         if isinstance(ids, (int, long)):
4169             ids = [ids]
4170
4171         self._check_concurrency(cr, ids, context)
4172         self.check_access_rights(cr, user, 'write')
4173
4174         result = self._store_get_values(cr, user, ids, vals.keys(), context) or []
4175
4176         # No direct update of parent_left/right
4177         vals.pop('parent_left', None)
4178         vals.pop('parent_right', None)
4179
4180         parents_changed = []
4181         parent_order = self._parent_order or self._order
4182         if self._parent_store and (self._parent_name in vals):
4183             # The parent_left/right computation may take up to
4184             # 5 seconds. No need to recompute the values if the
4185             # parent is the same.
4186             # Note: to respect parent_order, nodes must be processed in
4187             # order, so ``parents_changed`` must be ordered properly.
4188             parent_val = vals[self._parent_name]
4189             if parent_val:
4190                 query = "SELECT id FROM %s WHERE id IN %%s AND (%s != %%s OR %s IS NULL) ORDER BY %s" % \
4191                                 (self._table, self._parent_name, self._parent_name, parent_order)
4192                 cr.execute(query, (tuple(ids), parent_val))
4193             else:
4194                 query = "SELECT id FROM %s WHERE id IN %%s AND (%s IS NOT NULL) ORDER BY %s" % \
4195                                 (self._table, self._parent_name, parent_order)
4196                 cr.execute(query, (tuple(ids),))
4197             parents_changed = map(operator.itemgetter(0), cr.fetchall())
4198
4199         upd0 = []
4200         upd1 = []
4201         upd_todo = []
4202         updend = []
4203         direct = []
4204         totranslate = context.get('lang', False) and (context['lang'] != 'en_US')
4205         for field in vals:
4206             field_column = self._all_columns.get(field) and self._all_columns.get(field).column
4207             if field_column and field_column.deprecated:
4208                 _logger.warning('Field %s.%s is deprecated: %s', self._name, field, field_column.deprecated)
4209             if field in self._columns:
4210                 if self._columns[field]._classic_write and not (hasattr(self._columns[field], '_fnct_inv')):
4211                     if (not totranslate) or not self._columns[field].translate:
4212                         upd0.append('"'+field+'"='+self._columns[field]._symbol_set[0])
4213                         upd1.append(self._columns[field]._symbol_set[1](vals[field]))
4214                     direct.append(field)
4215                 else:
4216                     upd_todo.append(field)
4217             else:
4218                 updend.append(field)
4219             if field in self._columns \
4220                     and hasattr(self._columns[field], 'selection') \
4221                     and vals[field]:
4222                 self._check_selection_field_value(cr, user, field, vals[field], context=context)
4223
4224         if self._log_access:
4225             upd0.append('write_uid=%s')
4226             upd0.append("write_date=(now() at time zone 'UTC')")
4227             upd1.append(user)
4228
4229         if len(upd0):
4230             self.check_access_rule(cr, user, ids, 'write', context=context)
4231             for sub_ids in cr.split_for_in_conditions(ids):
4232                 cr.execute('update ' + self._table + ' set ' + ','.join(upd0) + ' ' \
4233                            'where id IN %s', upd1 + [sub_ids])
4234                 if cr.rowcount != len(sub_ids):
4235                     raise except_orm(_('AccessError'),
4236                                      _('One of the records you are trying to modify has already been deleted (Document type: %s).') % self._description)
4237
4238             if totranslate:
4239                 # TODO: optimize
4240                 for f in direct:
4241                     if self._columns[f].translate:
4242                         src_trans = self.pool.get(self._name).read(cr, user, ids, [f])[0][f]
4243                         if not src_trans:
4244                             src_trans = vals[f]
4245                             # Inserting value to DB
4246                             context_wo_lang = dict(context, lang=None)
4247                             self.write(cr, user, ids, {f: vals[f]}, context=context_wo_lang)
4248                         self.pool.get('ir.translation')._set_ids(cr, user, self._name+','+f, 'model', context['lang'], ids, vals[f], src_trans)
4249
4250
4251         # call the 'set' method of fields which are not classic_write
4252         upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
4253
4254         # default element in context must be removed when call a one2many or many2many
4255         rel_context = context.copy()
4256         for c in context.items():
4257             if c[0].startswith('default_'):
4258                 del rel_context[c[0]]
4259
4260         for field in upd_todo:
4261             for id in ids:
4262                 result += self._columns[field].set(cr, self, id, field, vals[field], user, context=rel_context) or []
4263
4264         unknown_fields = updend[:]
4265         for table in self._inherits:
4266             col = self._inherits[table]
4267             nids = []
4268             for sub_ids in cr.split_for_in_conditions(ids):
4269                 cr.execute('select distinct "'+col+'" from "'+self._table+'" ' \
4270                            'where id IN %s', (sub_ids,))
4271                 nids.extend([x[0] for x in cr.fetchall()])
4272
4273             v = {}
4274             for val in updend:
4275                 if self._inherit_fields[val][0] == table:
4276                     v[val] = vals[val]
4277                     unknown_fields.remove(val)
4278             if v:
4279                 self.pool.get(table).write(cr, user, nids, v, context)
4280
4281         if unknown_fields:
4282             _logger.warning(
4283                 'No such field(s) in model %s: %s.',
4284                 self._name, ', '.join(unknown_fields))
4285         self._validate(cr, user, ids, context)
4286
4287         # TODO: use _order to set dest at the right position and not first node of parent
4288         # We can't defer parent_store computation because the stored function
4289         # fields that are computer may refer (directly or indirectly) to
4290         # parent_left/right (via a child_of domain)
4291         if parents_changed:
4292             if self.pool._init:
4293                 self.pool._init_parent[self._name] = True
4294             else:
4295                 order = self._parent_order or self._order
4296                 parent_val = vals[self._parent_name]
4297                 if parent_val:
4298                     clause, params = '%s=%%s' % (self._parent_name,), (parent_val,)
4299                 else:
4300                     clause, params = '%s IS NULL' % (self._parent_name,), ()
4301
4302                 for id in parents_changed:
4303                     cr.execute('SELECT parent_left, parent_right FROM %s WHERE id=%%s' % (self._table,), (id,))
4304                     pleft, pright = cr.fetchone()
4305                     distance = pright - pleft + 1
4306
4307                     # Positions of current siblings, to locate proper insertion point;
4308                     # this can _not_ be fetched outside the loop, as it needs to be refreshed
4309                     # after each update, in case several nodes are sequentially inserted one
4310                     # next to the other (i.e computed incrementally)
4311                     cr.execute('SELECT parent_right, id FROM %s WHERE %s ORDER BY %s' % (self._table, clause, parent_order), params)
4312                     parents = cr.fetchall()
4313
4314                     # Find Position of the element
4315                     position = None
4316                     for (parent_pright, parent_id) in parents:
4317                         if parent_id == id:
4318                             break
4319                         position = parent_pright + 1
4320
4321                     # It's the first node of the parent
4322                     if not position:
4323                         if not parent_val:
4324                             position = 1
4325                         else:
4326                             cr.execute('select parent_left from '+self._table+' where id=%s', (parent_val,))
4327                             position = cr.fetchone()[0] + 1
4328
4329                     if pleft < position <= pright:
4330                         raise except_orm(_('UserError'), _('Recursivity Detected.'))
4331
4332                     if pleft < position:
4333                         cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
4334                         cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
4335                         cr.execute('update '+self._table+' set parent_left=parent_left+%s, parent_right=parent_right+%s where parent_left>=%s and parent_left<%s', (position-pleft, position-pleft, pleft, pright))
4336                     else:
4337                         cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
4338                         cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
4339                         cr.execute('update '+self._table+' set parent_left=parent_left-%s, parent_right=parent_right-%s where parent_left>=%s and parent_left<%s', (pleft-position+distance, pleft-position+distance, pleft+distance, pright+distance))
4340
4341         result += self._store_get_values(cr, user, ids, vals.keys(), context)
4342         result.sort()
4343
4344         done = {}
4345         for order, object, ids_to_update, fields_to_recompute in result:
4346             key = (object, tuple(fields_to_recompute))
4347             done.setdefault(key, {})
4348             # avoid to do several times the same computation
4349             todo = []
4350             for id in ids_to_update:
4351                 if id not in done[key]:
4352                     done[key][id] = True
4353                     todo.append(id)
4354             self.pool.get(object)._store_set_values(cr, user, todo, fields_to_recompute, context)
4355
4356         self._workflow_trigger(cr, user, ids, 'trg_write', context=context)
4357         return True
4358
4359     #
4360     # TODO: Should set perm to user.xxx
4361     #
4362     def create(self, cr, user, vals, context=None):
4363         """
4364         Create a new record for the model.
4365
4366         The values for the new record are initialized using the ``vals``
4367         argument, and if necessary the result of ``default_get()``.
4368
4369         :param cr: database cursor
4370         :param user: current user id
4371         :type user: integer
4372         :param vals: field values for new record, e.g {'field_name': field_value, ...}
4373         :type vals: dictionary
4374         :param context: optional context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...}
4375         :type context: dictionary
4376         :return: id of new record created
4377         :raise AccessError: * if user has no create rights on the requested object
4378                             * if user tries to bypass access rules for create on the requested object
4379         :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
4380         :raise UserError: if a loop would be created in a hierarchy of objects a result of the operation (such as setting an object as its own parent)
4381
4382         **Note**: The type of field values to pass in ``vals`` for relationship fields is specific.
4383         Please see the description of the :py:meth:`~osv.osv.osv.write` method for details about the possible values and how
4384         to specify them.
4385
4386         """
4387         if not context:
4388             context = {}
4389
4390         if self.is_transient():
4391             self._transient_vacuum(cr, user)
4392
4393         self.check_access_rights(cr, user, 'create')
4394
4395         if self._log_access:
4396             for f in LOG_ACCESS_COLUMNS:
4397                 if vals.pop(f, None) is not None:
4398                     _logger.warning(
4399                         'Field `%s` is not allowed when creating the model `%s`.',
4400                         f, self._name)
4401         vals = self._add_missing_default_values(cr, user, vals, context)
4402
4403         tocreate = {}
4404         for v in self._inherits:
4405             if self._inherits[v] not in vals:
4406                 tocreate[v] = {}
4407             else:
4408                 tocreate[v] = {'id': vals[self._inherits[v]]}
4409         (upd0, upd1, upd2) = ('', '', [])
4410         upd_todo = []
4411         unknown_fields = []
4412         for v in vals.keys():
4413             if v in self._inherit_fields and v not in self._columns:
4414                 (table, col, col_detail, original_parent) = self._inherit_fields[v]
4415                 tocreate[table][v] = vals[v]
4416                 del vals[v]
4417             else:
4418                 if (v not in self._inherit_fields) and (v not in self._columns):
4419                     del vals[v]
4420                     unknown_fields.append(v)
4421         if unknown_fields:
4422             _logger.warning(
4423                 'No such field(s) in model %s: %s.',
4424                 self._name, ', '.join(unknown_fields))
4425
4426         # Try-except added to filter the creation of those records whose filds are readonly.
4427         # Example : any dashboard which has all the fields readonly.(due to Views(database views))
4428         try:
4429             cr.execute("SELECT nextval('"+self._sequence+"')")
4430         except:
4431             raise except_orm(_('UserError'),
4432                 _('You cannot perform this operation. New Record Creation is not allowed for this object as this object is for reporting purpose.'))
4433
4434         id_new = cr.fetchone()[0]
4435         for table in tocreate:
4436             if self._inherits[table] in vals:
4437                 del vals[self._inherits[table]]
4438
4439             record_id = tocreate[table].pop('id', None)
4440             
4441             # When linking/creating parent records, force context without 'no_store_function' key that
4442             # defers stored functions computing, as these won't be computed in batch at the end of create(). 
4443             parent_context = dict(context)
4444             parent_context.pop('no_store_function', None)
4445             
4446             if record_id is None or not record_id:
4447                 record_id = self.pool.get(table).create(cr, user, tocreate[table], context=parent_context)
4448             else:
4449                 self.pool.get(table).write(cr, user, [record_id], tocreate[table], context=parent_context)
4450
4451             upd0 += ',' + self._inherits[table]
4452             upd1 += ',%s'
4453             upd2.append(record_id)
4454
4455         #Start : Set bool fields to be False if they are not touched(to make search more powerful)
4456         bool_fields = [x for x in self._columns.keys() if self._columns[x]._type=='boolean']
4457
4458         for bool_field in bool_fields:
4459             if bool_field not in vals:
4460                 vals[bool_field] = False
4461         #End
4462         for field in vals.copy():
4463             fobj = None
4464             if field in self._columns:
4465                 fobj = self._columns[field]
4466             else:
4467                 fobj = self._inherit_fields[field][2]
4468             if not fobj:
4469                 continue
4470             groups = fobj.write
4471             if groups:
4472                 edit = False
4473                 for group in groups:
4474                     module = group.split(".")[0]
4475                     grp = group.split(".")[1]
4476                     cr.execute("select count(*) from res_groups_users_rel where gid IN (select res_id from ir_model_data where name='%s' and module='%s' and model='%s') and uid=%s" % \
4477                                (grp, module, 'res.groups', user))
4478                     readonly = cr.fetchall()
4479                     if readonly[0][0] >= 1:
4480                         edit = True
4481                         break
4482                     elif readonly[0][0] == 0:
4483                         edit = False
4484                     else:
4485                         edit = False
4486
4487                 if not edit:
4488                     vals.pop(field)
4489         for field in vals:
4490             if self._columns[field]._classic_write:
4491                 upd0 = upd0 + ',"' + field + '"'
4492                 upd1 = upd1 + ',' + self._columns[field]._symbol_set[0]
4493                 upd2.append(self._columns[field]._symbol_set[1](vals[field]))
4494                 #for the function fields that receive a value, we set them directly in the database 
4495                 #(they may be required), but we also need to trigger the _fct_inv()
4496                 if (hasattr(self._columns[field], '_fnct_inv')) and not isinstance(self._columns[field], fields.related):
4497                     #TODO: this way to special case the related fields is really creepy but it shouldn't be changed at
4498                     #one week of the release candidate. It seems the only good way to handle correctly this is to add an
4499                     #attribute to make a field `really readonly´ and thus totally ignored by the create()... otherwise
4500                     #if, for example, the related has a default value (for usability) then the fct_inv is called and it
4501                     #may raise some access rights error. Changing this is a too big change for now, and is thus postponed
4502                     #after the release but, definitively, the behavior shouldn't be different for related and function
4503                     #fields.
4504                     upd_todo.append(field)
4505             else:
4506                 #TODO: this `if´ statement should be removed because there is no good reason to special case the fields
4507                 #related. See the above TODO comment for further explanations.
4508                 if not isinstance(self._columns[field], fields.related):
4509                     upd_todo.append(field)
4510             if field in self._columns \
4511                     and hasattr(self._columns[field], 'selection') \
4512                     and vals[field]:
4513                 self._check_selection_field_value(cr, user, field, vals[field], context=context)
4514         if self._log_access:
4515             upd0 += ',create_uid,create_date,write_uid,write_date'
4516             upd1 += ",%s,(now() at time zone 'UTC'),%s,(now() at time zone 'UTC')"
4517             upd2.extend((user, user))
4518         cr.execute('insert into "'+self._table+'" (id'+upd0+") values ("+str(id_new)+upd1+')', tuple(upd2))
4519         upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
4520
4521         if self._parent_store and not context.get('defer_parent_store_computation'):
4522             if self.pool._init:
4523                 self.pool._init_parent[self._name] = True
4524             else:
4525                 parent = vals.get(self._parent_name, False)
4526                 if parent:
4527                     cr.execute('select parent_right from '+self._table+' where '+self._parent_name+'=%s order by '+(self._parent_order or self._order), (parent,))
4528                     pleft_old = None
4529                     result_p = cr.fetchall()
4530                     for (pleft,) in result_p:
4531                         if not pleft:
4532                             break
4533                         pleft_old = pleft
4534                     if not pleft_old:
4535                         cr.execute('select parent_left from '+self._table+' where id=%s', (parent,))
4536                         pleft_old = cr.fetchone()[0]
4537                     pleft = pleft_old
4538                 else:
4539                     cr.execute('select max(parent_right) from '+self._table)
4540                     pleft = cr.fetchone()[0] or 0
4541                 cr.execute('update '+self._table+' set parent_left=parent_left+2 where parent_left>%s', (pleft,))
4542                 cr.execute('update '+self._table+' set parent_right=parent_right+2 where parent_right>%s', (pleft,))
4543                 cr.execute('update '+self._table+' set parent_left=%s,parent_right=%s where id=%s', (pleft+1, pleft+2, id_new))
4544
4545         # default element in context must be remove when call a one2many or many2many
4546         rel_context = context.copy()
4547         for c in context.items():
4548             if c[0].startswith('default_'):
4549                 del rel_context[c[0]]
4550
4551         result = []
4552         for field in upd_todo:
4553             result += self._columns[field].set(cr, self, id_new, field, vals[field], user, rel_context) or []
4554         self._validate(cr, user, [id_new], context)
4555
4556         if not context.get('no_store_function', False):
4557             result += self._store_get_values(cr, user, [id_new],
4558                 list(set(vals.keys() + self._inherits.values())),
4559                 context)
4560             result.sort()
4561             done = []
4562             for order, object, ids, fields2 in result:
4563                 if not (object, ids, fields2) in done:
4564                     self.pool.get(object)._store_set_values(cr, user, ids, fields2, context)
4565                     done.append((object, ids, fields2))
4566
4567         if self._log_create and not (context and context.get('no_store_function', False)):
4568             message = self._description + \
4569                 " '" + \
4570                 self.name_get(cr, user, [id_new], context=context)[0][1] + \
4571                 "' " + _("created.")
4572             self.log(cr, user, id_new, message, True, context=context)
4573         self.check_access_rule(cr, user, [id_new], 'create', context=context)
4574         self._workflow_trigger(cr, user, [id_new], 'trg_create', context=context)
4575         return id_new
4576
4577     def browse(self, cr, uid, select, context=None, list_class=None, fields_process=None):
4578         """Fetch records as objects allowing to use dot notation to browse fields and relations
4579
4580         :param cr: database cursor
4581         :param uid: current user id
4582         :param select: id or list of ids.
4583         :param context: context arguments, like lang, time zone
4584         :rtype: object or list of objects requested
4585
4586         """
4587         self._list_class = list_class or browse_record_list
4588         cache = {}
4589         # need to accepts ints and longs because ids coming from a method
4590         # launched by button in the interface have a type long...
4591         if isinstance(select, (int, long)):
4592             return browse_record(cr, uid, select, self, cache, context=context, list_class=self._list_class, fields_process=fields_process)
4593         elif isinstance(select, list):
4594             return self._list_class((browse_record(cr, uid, id, self, cache, context=context, list_class=self._list_class, fields_process=fields_process) for id in select), context=context)
4595         else:
4596             return browse_null()
4597
4598     def _store_get_values(self, cr, uid, ids, fields, context):
4599         """Returns an ordered list of fields.functions to call due to
4600            an update operation on ``fields`` of records with ``ids``,
4601            obtained by calling the 'store' functions of these fields,
4602            as setup by their 'store' attribute.
4603
4604            :return: [(priority, model_name, [record_ids,], [function_fields,])]
4605         """
4606         if fields is None: fields = []
4607         stored_functions = self.pool._store_function.get(self._name, [])
4608
4609         # use indexed names for the details of the stored_functions:
4610         model_name_, func_field_to_compute_, id_mapping_fnct_, trigger_fields_, priority_ = range(5)
4611
4612         # only keep functions that should be triggered for the ``fields``
4613         # being written to.
4614         to_compute = [f for f in stored_functions \
4615                 if ((not f[trigger_fields_]) or set(fields).intersection(f[trigger_fields_]))]
4616
4617         mapping = {}
4618         fresults = {}
4619         for function in to_compute:
4620             fid = id(function[id_mapping_fnct_])
4621             if not fid in fresults:
4622                 # use admin user for accessing objects having rules defined on store fields
4623                 fresults[fid] = [id2 for id2 in function[id_mapping_fnct_](self, cr, SUPERUSER_ID, ids, context) if id2]
4624             target_ids = fresults[fid]
4625
4626             # the compound key must consider the priority and model name
4627             key = (function[priority_], function[model_name_])
4628             for target_id in target_ids:
4629                 mapping.setdefault(key, {}).setdefault(target_id,set()).add(tuple(function))
4630
4631         # Here mapping looks like:
4632         # { (10, 'model_a') : { target_id1: [ (function_1_tuple, function_2_tuple) ], ... }
4633         #   (20, 'model_a') : { target_id2: [ (function_3_tuple, function_4_tuple) ], ... }
4634         #   (99, 'model_a') : { target_id1: [ (function_5_tuple, function_6_tuple) ], ... }
4635         # }
4636
4637         # Now we need to generate the batch function calls list
4638         # call_map =
4639         #   { (10, 'model_a') : [(10, 'model_a', [record_ids,], [function_fields,])] }
4640         call_map = {}
4641         for ((priority,model), id_map) in mapping.iteritems():
4642             functions_ids_maps = {}
4643             # function_ids_maps =
4644             #   { (function_1_tuple, function_2_tuple) : [target_id1, target_id2, ..] }
4645             for fid, functions in id_map.iteritems():
4646                 functions_ids_maps.setdefault(tuple(functions), []).append(fid)
4647             for functions, ids in functions_ids_maps.iteritems():
4648                 call_map.setdefault((priority,model),[]).append((priority, model, ids,
4649                                                                  [f[func_field_to_compute_] for f in functions]))
4650         ordered_keys = call_map.keys()
4651         ordered_keys.sort()
4652         result = []
4653         if ordered_keys:
4654             result = reduce(operator.add, (call_map[k] for k in ordered_keys))
4655         return result
4656
4657     def _store_set_values(self, cr, uid, ids, fields, context):
4658         """Calls the fields.function's "implementation function" for all ``fields``, on records with ``ids`` (taking care of
4659            respecting ``multi`` attributes), and stores the resulting values in the database directly."""
4660         if not ids:
4661             return True
4662         field_flag = False
4663         field_dict = {}
4664         if self._log_access:
4665             cr.execute('select id,write_date from '+self._table+' where id IN %s', (tuple(ids),))
4666             res = cr.fetchall()
4667             for r in res:
4668                 if r[1]:
4669                     field_dict.setdefault(r[0], [])
4670                     res_date = time.strptime((r[1])[:19], '%Y-%m-%d %H:%M:%S')
4671                     write_date = datetime.datetime.fromtimestamp(time.mktime(res_date))
4672                     for i in self.pool._store_function.get(self._name, []):
4673                         if i[5]:
4674                             up_write_date = write_date + datetime.timedelta(hours=i[5])
4675                             if datetime.datetime.now() < up_write_date:
4676                                 if i[1] in fields:
4677                                     field_dict[r[0]].append(i[1])
4678                                     if not field_flag:
4679                                         field_flag = True
4680         todo = {}
4681         keys = []
4682         for f in fields:
4683             if self._columns[f]._multi not in keys:
4684                 keys.append(self._columns[f]._multi)
4685             todo.setdefault(self._columns[f]._multi, [])
4686             todo[self._columns[f]._multi].append(f)
4687         for key in keys:
4688             val = todo[key]
4689             if key:
4690                 # use admin user for accessing objects having rules defined on store fields
4691                 result = self._columns[val[0]].get(cr, self, ids, val, SUPERUSER_ID, context=context)
4692                 for id, value in result.items():
4693                     if field_flag:
4694                         for f in value.keys():
4695                             if f in field_dict[id]:
4696                                 value.pop(f)
4697                     upd0 = []
4698                     upd1 = []
4699                     for v in value:
4700                         if v not in val:
4701                             continue
4702                         if self._columns[v]._type == 'many2one':
4703                             try:
4704                                 value[v] = value[v][0]
4705                             except:
4706                                 pass
4707                         upd0.append('"'+v+'"='+self._columns[v]._symbol_set[0])
4708                         upd1.append(self._columns[v]._symbol_set[1](value[v]))
4709                     upd1.append(id)
4710                     if upd0 and upd1:
4711                         cr.execute('update "' + self._table + '" set ' + \
4712                             ','.join(upd0) + ' where id = %s', upd1)
4713
4714             else:
4715                 for f in val:
4716                     # use admin user for accessing objects having rules defined on store fields
4717                     result = self._columns[f].get(cr, self, ids, f, SUPERUSER_ID, context=context)
4718                     for r in result.keys():
4719                         if field_flag:
4720                             if r in field_dict.keys():
4721                                 if f in field_dict[r]:
4722                                     result.pop(r)
4723                     for id, value in result.items():
4724                         if self._columns[f]._type == 'many2one':
4725                             try:
4726                                 value = value[0]
4727                             except:
4728                                 pass
4729                         cr.execute('update "' + self._table + '" set ' + \
4730                             '"'+f+'"='+self._columns[f]._symbol_set[0] + ' where id = %s', (self._columns[f]._symbol_set[1](value), id))
4731         return True
4732
4733     #
4734     # TODO: Validate
4735     #
4736     def perm_write(self, cr, user, ids, fields, context=None):
4737         raise NotImplementedError(_('This method does not exist anymore'))
4738
4739     # TODO: ameliorer avec NULL
4740     def _where_calc(self, cr, user, domain, active_test=True, context=None):
4741         """Computes the WHERE clause needed to implement an OpenERP domain.
4742         :param domain: the domain to compute
4743         :type domain: list
4744         :param active_test: whether the default filtering of records with ``active``
4745                             field set to ``False`` should be applied.
4746         :return: the query expressing the given domain as provided in domain
4747         :rtype: osv.query.Query
4748         """
4749         if not context:
4750             context = {}
4751         domain = domain[:]
4752         # if the object has a field named 'active', filter out all inactive
4753         # records unless they were explicitely asked for
4754         if 'active' in self._all_columns and (active_test and context.get('active_test', True)):
4755             if domain:
4756                 # the item[0] trick below works for domain items and '&'/'|'/'!'
4757                 # operators too
4758                 if not any(item[0] == 'active' for item in domain):
4759                     domain.insert(0, ('active', '=', 1))
4760             else:
4761                 domain = [('active', '=', 1)]
4762
4763         if domain:
4764             e = expression.expression(cr, user, domain, self, context)
4765             tables = e.get_tables()
4766             where_clause, where_params = e.to_sql()
4767             where_clause = where_clause and [where_clause] or []
4768         else:
4769             where_clause, where_params, tables = [], [], ['"%s"' % self._table]
4770
4771         return Query(tables, where_clause, where_params)
4772
4773     def _check_qorder(self, word):
4774         if not regex_order.match(word):
4775             raise except_orm(_('AccessError'), _('Invalid "order" specified. A valid "order" specification is a comma-separated list of valid field names (optionally followed by asc/desc for the direction)'))
4776         return True
4777
4778     def _apply_ir_rules(self, cr, uid, query, mode='read', context=None):
4779         """Add what's missing in ``query`` to implement all appropriate ir.rules
4780           (using the ``model_name``'s rules or the current model's rules if ``model_name`` is None)
4781
4782            :param query: the current query object
4783         """
4784         if uid == SUPERUSER_ID:
4785             return
4786
4787         def apply_rule(added_clause, added_params, added_tables, parent_model=None, child_object=None):
4788             """ :param string parent_model: string of the parent model
4789                 :param model child_object: model object, base of the rule application
4790             """
4791             if added_clause:
4792                 if parent_model and child_object:
4793                     # as inherited rules are being applied, we need to add the missing JOIN
4794                     # to reach the parent table (if it was not JOINed yet in the query)
4795                     parent_alias = child_object._inherits_join_add(child_object, parent_model, query)
4796                     # inherited rules are applied on the external table -> need to get the alias and replace
4797                     parent_table = self.pool.get(parent_model)._table
4798                     added_clause = [clause.replace('"%s"' % parent_table, '"%s"' % parent_alias) for clause in added_clause]
4799                     # change references to parent_table to parent_alias, because we now use the alias to refer to the table
4800                     new_tables = []
4801                     for table in added_tables:
4802                         # table is just a table name -> switch to the full alias
4803                         if table == '"%s"' % parent_table:
4804                             new_tables.append('"%s" as "%s"' % (parent_table, parent_alias))
4805                         # table is already a full statement -> replace reference to the table to its alias, is correct with the way aliases are generated
4806                         else:
4807                             new_tables.append(table.replace('"%s"' % parent_table, '"%s"' % parent_alias))
4808                     added_tables = new_tables
4809                 query.where_clause += added_clause
4810                 query.where_clause_params += added_params
4811                 for table in added_tables:
4812                     if table not in query.tables:
4813                         query.tables.append(table)
4814                 return True
4815             return False
4816
4817         # apply main rules on the object
4818         rule_obj = self.pool.get('ir.rule')
4819         rule_where_clause, rule_where_clause_params, rule_tables = rule_obj.domain_get(cr, uid, self._name, mode, context=context)
4820         apply_rule(rule_where_clause, rule_where_clause_params, rule_tables)
4821
4822         # apply ir.rules from the parents (through _inherits)
4823         for inherited_model in self._inherits:
4824             rule_where_clause, rule_where_clause_params, rule_tables = rule_obj.domain_get(cr, uid, inherited_model, mode, context=context)
4825             apply_rule(rule_where_clause, rule_where_clause_params, rule_tables,
4826                         parent_model=inherited_model, child_object=self)
4827
4828     def _generate_m2o_order_by(self, order_field, query):
4829         """
4830         Add possibly missing JOIN to ``query`` and generate the ORDER BY clause for m2o fields,
4831         either native m2o fields or function/related fields that are stored, including
4832         intermediate JOINs for inheritance if required.
4833
4834         :return: the qualified field name to use in an ORDER BY clause to sort by ``order_field``
4835         """
4836         if order_field not in self._columns and order_field in self._inherit_fields:
4837             # also add missing joins for reaching the table containing the m2o field
4838             qualified_field = self._inherits_join_calc(order_field, query)
4839             order_field_column = self._inherit_fields[order_field][2]
4840         else:
4841             qualified_field = '"%s"."%s"' % (self._table, order_field)
4842             order_field_column = self._columns[order_field]
4843
4844         assert order_field_column._type == 'many2one', 'Invalid field passed to _generate_m2o_order_by()'
4845         if not order_field_column._classic_write and not getattr(order_field_column, 'store', False):
4846             _logger.debug("Many2one function/related fields must be stored " \
4847                 "to be used as ordering fields! Ignoring sorting for %s.%s",
4848                 self._name, order_field)
4849             return
4850
4851         # figure out the applicable order_by for the m2o
4852         dest_model = self.pool.get(order_field_column._obj)
4853         m2o_order = dest_model._order
4854         if not regex_order.match(m2o_order):
4855             # _order is complex, can't use it here, so we default to _rec_name
4856             m2o_order = dest_model._rec_name
4857         else:
4858             # extract the field names, to be able to qualify them and add desc/asc
4859             m2o_order_list = []
4860             for order_part in m2o_order.split(","):
4861                 m2o_order_list.append(order_part.strip().split(" ", 1)[0].strip())
4862             m2o_order = m2o_order_list
4863
4864         # Join the dest m2o table if it's not joined yet. We use [LEFT] OUTER join here
4865         # as we don't want to exclude results that have NULL values for the m2o
4866         src_table, src_field = qualified_field.replace('"', '').split('.', 1)
4867         dst_alias, dst_alias_statement = query.add_join((src_table, dest_model._table, src_field, 'id', src_field), implicit=False, outer=True)
4868         qualify = lambda field: '"%s"."%s"' % (dst_alias, field)
4869         return map(qualify, m2o_order) if isinstance(m2o_order, list) else qualify(m2o_order)
4870
4871     def _generate_order_by(self, order_spec, query):
4872         """
4873         Attempt to consruct an appropriate ORDER BY clause based on order_spec, which must be
4874         a comma-separated list of valid field names, optionally followed by an ASC or DESC direction.
4875
4876         :raise" except_orm in case order_spec is malformed
4877         """
4878         order_by_clause = ''
4879         order_spec = order_spec or self._order
4880         if order_spec:
4881             order_by_elements = []
4882             self._check_qorder(order_spec)
4883             for order_part in order_spec.split(','):
4884                 order_split = order_part.strip().split(' ')
4885                 order_field = order_split[0].strip()
4886                 order_direction = order_split[1].strip() if len(order_split) == 2 else ''
4887                 inner_clause = None
4888                 if order_field == 'id' or (self._log_access and order_field in LOG_ACCESS_COLUMNS.keys()):
4889                     order_by_elements.append('"%s"."%s" %s' % (self._table, order_field, order_direction))
4890                 elif order_field in self._columns:
4891                     order_column = self._columns[order_field]
4892                     if order_column._classic_read:
4893                         inner_clause = '"%s"."%s"' % (self._table, order_field)
4894                     elif order_column._type == 'many2one':
4895                         inner_clause = self._generate_m2o_order_by(order_field, query)
4896                     else:
4897                         continue  # ignore non-readable or "non-joinable" fields
4898                 elif order_field in self._inherit_fields:
4899                     parent_obj = self.pool.get(self._inherit_fields[order_field][3])
4900                     order_column = parent_obj._columns[order_field]
4901                     if order_column._classic_read:
4902                         inner_clause = self._inherits_join_calc(order_field, query)
4903                     elif order_column._type == 'many2one':
4904                         inner_clause = self._generate_m2o_order_by(order_field, query)
4905                     else:
4906                         continue  # ignore non-readable or "non-joinable" fields
4907                 else:
4908                     raise ValueError( _("Sorting field %s not found on model %s") %( order_field, self._name))
4909                 if inner_clause:
4910                     if isinstance(inner_clause, list):
4911                         for clause in inner_clause:
4912                             order_by_elements.append("%s %s" % (clause, order_direction))
4913                     else:
4914                         order_by_elements.append("%s %s" % (inner_clause, order_direction))
4915             if order_by_elements:
4916                 order_by_clause = ",".join(order_by_elements)
4917
4918         return order_by_clause and (' ORDER BY %s ' % order_by_clause) or ''
4919
4920     def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
4921         """
4922         Private implementation of search() method, allowing specifying the uid to use for the access right check.
4923         This is useful for example when filling in the selection list for a drop-down and avoiding access rights errors,
4924         by specifying ``access_rights_uid=1`` to bypass access rights check, but not ir.rules!
4925         This is ok at the security level because this method is private and not callable through XML-RPC.
4926
4927         :param access_rights_uid: optional user ID to use when checking access rights
4928                                   (not for ir.rules, this is only for ir.model.access)
4929         """
4930         if context is None:
4931             context = {}
4932         self.check_access_rights(cr, access_rights_uid or user, 'read')
4933
4934         # For transient models, restrict acces to the current user, except for the super-user
4935         if self.is_transient() and self._log_access and user != SUPERUSER_ID:
4936             args = expression.AND(([('create_uid', '=', user)], args or []))
4937
4938         query = self._where_calc(cr, user, args, context=context)
4939         self._apply_ir_rules(cr, user, query, 'read', context=context)
4940         order_by = self._generate_order_by(order, query)
4941         from_clause, where_clause, where_clause_params = query.get_sql()
4942
4943         limit_str = limit and ' limit %d' % limit or ''
4944         offset_str = offset and ' offset %d' % offset or ''
4945         where_str = where_clause and (" WHERE %s" % where_clause) or ''
4946
4947         if count:
4948             cr.execute('SELECT count("%s".id) FROM ' % self._table + from_clause + where_str + limit_str + offset_str, where_clause_params)
4949             res = cr.fetchall()
4950             return res[0][0]
4951         cr.execute('SELECT "%s".id FROM ' % self._table + from_clause + where_str + order_by + limit_str + offset_str, where_clause_params)
4952         res = cr.fetchall()
4953
4954         # TDE note: with auto_join, we could have several lines about the same result
4955         # i.e. a lead with several unread messages; we uniquify the result using
4956         # a fast way to do it while preserving order (http://www.peterbe.com/plog/uniqifiers-benchmark)
4957         def _uniquify_list(seq):
4958             seen = set()
4959             return [x for x in seq if x not in seen and not seen.add(x)]
4960
4961         return _uniquify_list([x[0] for x in res])
4962
4963     # returns the different values ever entered for one field
4964     # this is used, for example, in the client when the user hits enter on
4965     # a char field
4966     def distinct_field_get(self, cr, uid, field, value, args=None, offset=0, limit=None):
4967         if not args:
4968             args = []
4969         if field in self._inherit_fields:
4970             return self.pool.get(self._inherit_fields[field][0]).distinct_field_get(cr, uid, field, value, args, offset, limit)
4971         else:
4972             return self._columns[field].search(cr, self, args, field, value, offset, limit, uid)
4973
4974     def copy_data(self, cr, uid, id, default=None, context=None):
4975         """
4976         Copy given record's data with all its fields values
4977
4978         :param cr: database cursor
4979         :param uid: current user id
4980         :param id: id of the record to copy
4981         :param default: field values to override in the original values of the copied record
4982         :type default: dictionary
4983         :param context: context arguments, like lang, time zone
4984         :type context: dictionary
4985         :return: dictionary containing all the field values
4986         """
4987
4988         if context is None:
4989             context = {}
4990
4991         # avoid recursion through already copied records in case of circular relationship
4992         seen_map = context.setdefault('__copy_data_seen',{})
4993         if id in seen_map.setdefault(self._name,[]):
4994             return
4995         seen_map[self._name].append(id)
4996
4997         if default is None:
4998             default = {}
4999         if 'state' not in default:
5000             if 'state' in self._defaults:
5001                 if callable(self._defaults['state']):
5002                     default['state'] = self._defaults['state'](self, cr, uid, context)
5003                 else:
5004                     default['state'] = self._defaults['state']
5005
5006         # build a black list of fields that should not be copied
5007         blacklist = set(MAGIC_COLUMNS + ['parent_left', 'parent_right'])
5008         def blacklist_given_fields(obj):
5009             # blacklist the fields that are given by inheritance
5010             for other, field_to_other in obj._inherits.items():
5011                 blacklist.add(field_to_other)
5012                 if field_to_other in default:
5013                     # all the fields of 'other' are given by the record: default[field_to_other],
5014                     # except the ones redefined in self
5015                     blacklist.update(set(self.pool.get(other)._all_columns) - set(self._columns))
5016                 else:
5017                     blacklist_given_fields(self.pool.get(other))
5018         blacklist_given_fields(self)
5019
5020
5021         fields_to_copy = dict((f,fi) for f, fi in self._all_columns.iteritems()
5022                                      if f not in default
5023                                      if f not in blacklist
5024                                      if not isinstance(fi.column, fields.function))
5025
5026         data = self.read(cr, uid, [id], fields_to_copy.keys(), context=context)
5027         if data:
5028             data = data[0]
5029         else:
5030             raise IndexError( _("Record #%d of %s not found, cannot copy!") %( id, self._name))
5031
5032         res = dict(default)
5033         for f, colinfo in fields_to_copy.iteritems():
5034             field = colinfo.column
5035             if field._type == 'many2one':
5036                 res[f] = data[f] and data[f][0]
5037             elif field._type == 'one2many':
5038                 other = self.pool.get(field._obj)
5039                 # duplicate following the order of the ids because we'll rely on
5040                 # it later for copying translations in copy_translation()!
5041                 lines = [other.copy_data(cr, uid, line_id, context=context) for line_id in sorted(data[f])]
5042                 # the lines are duplicated using the wrong (old) parent, but then
5043                 # are reassigned to the correct one thanks to the (0, 0, ...)
5044                 res[f] = [(0, 0, line) for line in lines if line]
5045             elif field._type == 'many2many':
5046                 res[f] = [(6, 0, data[f])]
5047             else:
5048                 res[f] = data[f]
5049
5050         return res
5051
5052     def copy_translations(self, cr, uid, old_id, new_id, context=None):
5053         if context is None:
5054             context = {}
5055
5056         # avoid recursion through already copied records in case of circular relationship
5057         seen_map = context.setdefault('__copy_translations_seen',{})
5058         if old_id in seen_map.setdefault(self._name,[]):
5059             return
5060         seen_map[self._name].append(old_id)
5061
5062         trans_obj = self.pool.get('ir.translation')
5063         # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
5064         fields = self.fields_get(cr, uid, context=context)
5065
5066         for field_name, field_def in fields.items():
5067             # removing the lang to compare untranslated values
5068             context_wo_lang = dict(context, lang=None)
5069             old_record, new_record = self.browse(cr, uid, [old_id, new_id], context=context_wo_lang)
5070             # we must recursively copy the translations for o2o and o2m
5071             if field_def['type'] == 'one2many':
5072                 target_obj = self.pool.get(field_def['relation'])
5073                 # here we rely on the order of the ids to match the translations
5074                 # as foreseen in copy_data()
5075                 old_children = sorted(r.id for r in old_record[field_name])
5076                 new_children = sorted(r.id for r in new_record[field_name])
5077                 for (old_child, new_child) in zip(old_children, new_children):
5078                     target_obj.copy_translations(cr, uid, old_child, new_child, context=context)
5079             # and for translatable fields we keep them for copy
5080             elif field_def.get('translate'):
5081                 if field_name in self._columns:
5082                     trans_name = self._name + "," + field_name
5083                     target_id = new_id
5084                     source_id = old_id
5085                 elif field_name in self._inherit_fields:
5086                     trans_name = self._inherit_fields[field_name][0] + "," + field_name
5087                     # get the id of the parent record to set the translation
5088                     inherit_field_name = self._inherit_fields[field_name][1]
5089                     target_id = new_record[inherit_field_name].id
5090                     source_id = old_record[inherit_field_name].id
5091                 else:
5092                     continue
5093
5094                 trans_ids = trans_obj.search(cr, uid, [
5095                         ('name', '=', trans_name),
5096                         ('res_id', '=', source_id)
5097                 ])
5098                 user_lang = context.get('lang')
5099                 for record in trans_obj.read(cr, uid, trans_ids, context=context):
5100                     del record['id']
5101                     # remove source to avoid triggering _set_src
5102                     del record['source']
5103                     record.update({'res_id': target_id})
5104                     if user_lang and user_lang == record['lang']:
5105                         # 'source' to force the call to _set_src
5106                         # 'value' needed if value is changed in copy(), want to see the new_value
5107                         record['source'] = old_record[field_name]
5108                         record['value'] = new_record[field_name]
5109                     trans_obj.create(cr, uid, record, context=context)
5110
5111
5112     def copy(self, cr, uid, id, default=None, context=None):
5113         """
5114         Duplicate record with given id updating it with default values
5115
5116         :param cr: database cursor
5117         :param uid: current user id
5118         :param id: id of the record to copy
5119         :param default: dictionary of field values to override in the original values of the copied record, e.g: ``{'field_name': overriden_value, ...}``
5120         :type default: dictionary
5121         :param context: context arguments, like lang, time zone
5122         :type context: dictionary
5123         :return: id of the newly created record
5124
5125         """
5126         if context is None:
5127             context = {}
5128         context = context.copy()
5129         data = self.copy_data(cr, uid, id, default, context)
5130         new_id = self.create(cr, uid, data, context)
5131         self.copy_translations(cr, uid, id, new_id, context)
5132         return new_id
5133
5134     def exists(self, cr, uid, ids, context=None):
5135         """Checks whether the given id or ids exist in this model,
5136            and return the list of ids that do. This is simple to use for
5137            a truth test on a browse_record::
5138
5139                if record.exists():
5140                    pass
5141
5142            :param ids: id or list of ids to check for existence
5143            :type ids: int or [int]
5144            :return: the list of ids that currently exist, out of
5145                     the given `ids`
5146         """
5147         if type(ids) in (int, long):
5148             ids = [ids]
5149         query = 'SELECT id FROM "%s"' % self._table
5150         cr.execute(query + "WHERE ID IN %s", (tuple(ids),))
5151         return [x[0] for x in cr.fetchall()]
5152
5153     def check_recursion(self, cr, uid, ids, context=None, parent=None):
5154         _logger.warning("You are using deprecated %s.check_recursion(). Please use the '_check_recursion()' instead!" % \
5155                         self._name)
5156         assert parent is None or parent in self._columns or parent in self._inherit_fields,\
5157                     "The 'parent' parameter passed to check_recursion() must be None or a valid field name"
5158         return self._check_recursion(cr, uid, ids, context, parent)
5159
5160     def _check_recursion(self, cr, uid, ids, context=None, parent=None):
5161         """
5162         Verifies that there is no loop in a hierarchical structure of records,
5163         by following the parent relationship using the **parent** field until a loop
5164         is detected or until a top-level record is found.
5165
5166         :param cr: database cursor
5167         :param uid: current user id
5168         :param ids: list of ids of records to check
5169         :param parent: optional parent field name (default: ``self._parent_name = parent_id``)
5170         :return: **True** if the operation can proceed safely, or **False** if an infinite loop is detected.
5171         """
5172         if not parent:
5173             parent = self._parent_name
5174
5175         # must ignore 'active' flag, ir.rules, etc. => direct SQL query
5176         query = 'SELECT "%s" FROM "%s" WHERE id = %%s' % (parent, self._table)
5177         for id in ids:
5178             current_id = id
5179             while current_id is not None:
5180                 cr.execute(query, (current_id,))
5181                 result = cr.fetchone()
5182                 current_id = result[0] if result else None
5183                 if current_id == id:
5184                     return False
5185         return True
5186
5187     def _get_external_ids(self, cr, uid, ids, *args, **kwargs):
5188         """Retrieve the External ID(s) of any database record.
5189
5190         **Synopsis**: ``_get_xml_ids(cr, uid, ids) -> { 'id': ['module.xml_id'] }``
5191
5192         :return: map of ids to the list of their fully qualified External IDs
5193                  in the form ``module.key``, or an empty list when there's no External
5194                  ID for a record, e.g.::
5195
5196                      { 'id': ['module.ext_id', 'module.ext_id_bis'],
5197                        'id2': [] }
5198         """
5199         ir_model_data = self.pool.get('ir.model.data')
5200         data_ids = ir_model_data.search(cr, uid, [('model', '=', self._name), ('res_id', 'in', ids)])
5201         data_results = ir_model_data.read(cr, uid, data_ids, ['module', 'name', 'res_id'])
5202         result = {}
5203         for id in ids:
5204             # can't use dict.fromkeys() as the list would be shared!
5205             result[id] = []
5206         for record in data_results:
5207             result[record['res_id']].append('%(module)s.%(name)s' % record)
5208         return result
5209
5210     def get_external_id(self, cr, uid, ids, *args, **kwargs):
5211         """Retrieve the External ID of any database record, if there
5212         is one. This method works as a possible implementation
5213         for a function field, to be able to add it to any
5214         model object easily, referencing it as ``Model.get_external_id``.
5215
5216         When multiple External IDs exist for a record, only one
5217         of them is returned (randomly).
5218
5219         :return: map of ids to their fully qualified XML ID,
5220                  defaulting to an empty string when there's none
5221                  (to be usable as a function field),
5222                  e.g.::
5223
5224                      { 'id': 'module.ext_id',
5225                        'id2': '' }
5226         """
5227         results = self._get_xml_ids(cr, uid, ids)
5228         for k, v in results.iteritems():
5229             if results[k]:
5230                 results[k] = v[0]
5231             else:
5232                 results[k] = ''
5233         return results
5234
5235     # backwards compatibility
5236     get_xml_id = get_external_id
5237     _get_xml_ids = _get_external_ids
5238
5239     # Transience
5240     def is_transient(self):
5241         """ Return whether the model is transient.
5242
5243         See :class:`TransientModel`.
5244
5245         """
5246         return self._transient
5247
5248     def _transient_clean_rows_older_than(self, cr, seconds):
5249         assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
5250         # Never delete rows used in last 5 minutes
5251         seconds = max(seconds, 300)
5252         query = ("SELECT id FROM " + self._table + " WHERE"
5253             " COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp"
5254             " < ((now() at time zone 'UTC') - interval %s)")
5255         cr.execute(query, ("%s seconds" % seconds,))
5256         ids = [x[0] for x in cr.fetchall()]
5257         self.unlink(cr, SUPERUSER_ID, ids)
5258
5259     def _transient_clean_old_rows(self, cr, max_count):
5260         # Check how many rows we have in the table
5261         cr.execute("SELECT count(*) AS row_count FROM " + self._table)
5262         res = cr.fetchall()
5263         if res[0][0] <= max_count:
5264             return  # max not reached, nothing to do
5265         self._transient_clean_rows_older_than(cr, 300)
5266
5267     def _transient_vacuum(self, cr, uid, force=False):
5268         """Clean the transient records.
5269
5270         This unlinks old records from the transient model tables whenever the
5271         "_transient_max_count" or "_max_age" conditions (if any) are reached.
5272         Actual cleaning will happen only once every "_transient_check_time" calls.
5273         This means this method can be called frequently called (e.g. whenever
5274         a new record is created).
5275         Example with both max_hours and max_count active:
5276         Suppose max_hours = 0.2 (e.g. 12 minutes), max_count = 20, there are 55 rows in the
5277         table, 10 created/changed in the last 5 minutes, an additional 12 created/changed between
5278         5 and 10 minutes ago, the rest created/changed more then 12 minutes ago.
5279         - age based vacuum will leave the 22 rows created/changed in the last 12 minutes
5280         - count based vacuum will wipe out another 12 rows. Not just 2, otherwise each addition
5281           would immediately cause the maximum to be reached again.
5282         - the 10 rows that have been created/changed the last 5 minutes will NOT be deleted
5283         """
5284         assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
5285         _transient_check_time = 20          # arbitrary limit on vacuum executions
5286         self._transient_check_count += 1
5287         if not force and (self._transient_check_count < _transient_check_time):
5288             return True  # no vacuum cleaning this time
5289         self._transient_check_count = 0
5290
5291         # Age-based expiration
5292         if self._transient_max_hours:
5293             self._transient_clean_rows_older_than(cr, self._transient_max_hours * 60 * 60)
5294
5295         # Count-based expiration
5296         if self._transient_max_count:
5297             self._transient_clean_old_rows(cr, self._transient_max_count)
5298
5299         return True
5300
5301     def resolve_2many_commands(self, cr, uid, field_name, commands, fields=None, context=None):
5302         """ Serializes one2many and many2many commands into record dictionaries
5303             (as if all the records came from the database via a read()).  This
5304             method is aimed at onchange methods on one2many and many2many fields.
5305
5306             Because commands might be creation commands, not all record dicts
5307             will contain an ``id`` field.  Commands matching an existing record
5308             will have an ``id``.
5309
5310             :param field_name: name of the one2many or many2many field matching the commands
5311             :type field_name: str
5312             :param commands: one2many or many2many commands to execute on ``field_name``
5313             :type commands: list((int|False, int|False, dict|False))
5314             :param fields: list of fields to read from the database, when applicable
5315             :type fields: list(str)
5316             :returns: records in a shape similar to that returned by ``read()``
5317                 (except records may be missing the ``id`` field if they don't exist in db)
5318             :rtype: list(dict)
5319         """
5320         result = []             # result (list of dict)
5321         record_ids = []         # ids of records to read
5322         updates = {}            # {id: dict} of updates on particular records
5323
5324         for command in commands:
5325             if not isinstance(command, (list, tuple)):
5326                 record_ids.append(command)
5327             elif command[0] == 0:
5328                 result.append(command[2])
5329             elif command[0] == 1:
5330                 record_ids.append(command[1])
5331                 updates.setdefault(command[1], {}).update(command[2])
5332             elif command[0] in (2, 3):
5333                 record_ids = [id for id in record_ids if id != command[1]]
5334             elif command[0] == 4:
5335                 record_ids.append(command[1])
5336             elif command[0] == 5:
5337                 result, record_ids = [], []
5338             elif command[0] == 6:
5339                 result, record_ids = [], list(command[2])
5340
5341         # read the records and apply the updates
5342         other_model = self.pool.get(self._all_columns[field_name].column._obj)
5343         for record in other_model.read(cr, uid, record_ids, fields=fields, context=context):
5344             record.update(updates.get(record['id'], {}))
5345             result.append(record)
5346
5347         return result
5348
5349     # for backward compatibility
5350     resolve_o2m_commands_to_record_dicts = resolve_2many_commands
5351
5352     def _register_hook(self, cr):
5353         """ stuff to do right after the registry is built """
5354         pass
5355
5356 # keep this import here, at top it will cause dependency cycle errors
5357 import expression
5358
5359 class Model(BaseModel):
5360     """Main super-class for regular database-persisted OpenERP models.
5361
5362     OpenERP models are created by inheriting from this class::
5363
5364         class user(Model):
5365             ...
5366
5367     The system will later instantiate the class once per database (on
5368     which the class' module is installed).
5369     """
5370     _auto = True
5371     _register = False # not visible in ORM registry, meant to be python-inherited only
5372     _transient = False # True in a TransientModel
5373
5374 class TransientModel(BaseModel):
5375     """Model super-class for transient records, meant to be temporarily
5376        persisted, and regularly vaccuum-cleaned.
5377
5378        A TransientModel has a simplified access rights management,
5379        all users can create new records, and may only access the
5380        records they created. The super-user has unrestricted access
5381        to all TransientModel records.
5382     """
5383     _auto = True
5384     _register = False # not visible in ORM registry, meant to be python-inherited only
5385     _transient = True
5386
5387 class AbstractModel(BaseModel):
5388     """Abstract Model super-class for creating an abstract class meant to be
5389        inherited by regular models (Models or TransientModels) but not meant to
5390        be usable on its own, or persisted.
5391
5392        Technical note: we don't want to make AbstractModel the super-class of
5393        Model or BaseModel because it would not make sense to put the main
5394        definition of persistence methods such as create() in it, and still we
5395        should be able to override them within an AbstractModel.
5396        """
5397     _auto = False # don't create any database backend for AbstractModels
5398     _register = False # not visible in ORM registry, meant to be python-inherited only
5399     _transient = False
5400
5401 def itemgetter_tuple(items):
5402     """ Fixes itemgetter inconsistency (useful in some cases) of not returning
5403     a tuple if len(items) == 1: always returns an n-tuple where n = len(items)
5404     """
5405     if len(items) == 0:
5406         return lambda a: ()
5407     if len(items) == 1:
5408         return lambda gettable: (gettable[items[0]],)
5409     return operator.itemgetter(*items)
5410 class ImportWarning(Warning):
5411     """ Used to send warnings upwards the stack during the import process
5412     """
5413     pass
5414
5415
5416 def convert_pgerror_23502(model, fields, info, e):
5417     m = re.match(r'^null value in column "(?P<field>\w+)" violates '
5418                  r'not-null constraint\n',
5419                  str(e))
5420     field_name = m.group('field')
5421     if not m or field_name not in fields:
5422         return {'message': unicode(e)}
5423     message = _(u"Missing required value for the field '%s'.") % field_name
5424     field = fields.get(field_name)
5425     if field:
5426         message = _(u"%s This might be '%s' in the current model, or a field "
5427                     u"of the same name in an o2m.") % (message, field['string'])
5428     return {
5429         'message': message,
5430         'field': field_name,
5431     }
5432 def convert_pgerror_23505(model, fields, info, e):
5433     m = re.match(r'^duplicate key (?P<field>\w+) violates unique constraint',
5434                  str(e))
5435     field_name = m.group('field')
5436     if not m or field_name not in fields:
5437         return {'message': unicode(e)}
5438     message = _(u"The value for the field '%s' already exists.") % field_name
5439     field = fields.get(field_name)
5440     if field:
5441         message = _(u"%s This might be '%s' in the current model, or a field "
5442                     u"of the same name in an o2m.") % (message, field['string'])
5443     return {
5444         'message': message,
5445         'field': field_name,
5446     }
5447
5448 PGERROR_TO_OE = collections.defaultdict(
5449     # shape of mapped converters
5450     lambda: (lambda model, fvg, info, pgerror: {'message': unicode(pgerror)}), {
5451     # not_null_violation
5452     '23502': convert_pgerror_23502,
5453     # unique constraint error
5454     '23505': convert_pgerror_23505,
5455 })
5456 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: