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