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