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