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