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