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