[MERGE] forward port of branch 8.0 up to ed92589
[odoo/odoo.git] / openerp / models.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
23 """
24     Object Relational Mapping module:
25      * Hierarchical structure
26      * Constraints consistency and validation
27      * Object metadata depends on its status
28      * Optimised processing by complex query (multiple actions at once)
29      * Default field values
30      * Permissions optimisation
31      * Persistant object: DB postgresql
32      * Data conversion
33      * Multi-level caching system
34      * Two different inheritance mechanisms
35      * Rich set of field types:
36           - classical (varchar, integer, boolean, ...)
37           - relational (one2many, many2one, many2many)
38           - functional
39
40 """
41
42 import datetime
43 import functools
44 import itertools
45 import logging
46 import operator
47 import pickle
48 import pytz
49 import re
50 import time
51 from collections import defaultdict, MutableMapping
52 from inspect import getmembers
53
54 import babel.dates
55 import dateutil.relativedelta
56 import psycopg2
57 from lxml import etree
58
59 import openerp
60 from . import SUPERUSER_ID
61 from . import api
62 from . import tools
63 from .api import Environment
64 from .exceptions import except_orm, AccessError, MissingError, ValidationError
65 from .osv import fields
66 from .osv.query import Query
67 from .tools import lazy_property, ormcache
68 from .tools.config import config
69 from .tools.misc import CountingStream, DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT
70 from .tools.safe_eval import safe_eval as eval
71 from .tools.translate import _
72
73 _logger = logging.getLogger(__name__)
74 _schema = logging.getLogger(__name__ + '.schema')
75
76 regex_order = re.compile('^( *([a-z0-9:_]+|"[a-z0-9:_]+")( *desc| *asc)?( *, *|))+$', re.I)
77 regex_object_name = re.compile(r'^[a-z0-9_.]+$')
78 onchange_v7 = re.compile(r"^(\w+)\((.*)\)$")
79
80 AUTOINIT_RECALCULATE_STORED_FIELDS = 1000
81
82
83 def check_object_name(name):
84     """ Check if the given name is a valid openerp object name.
85
86         The _name attribute in osv and osv_memory object is subject to
87         some restrictions. This function returns True or False whether
88         the given name is allowed or not.
89
90         TODO: this is an approximation. The goal in this approximation
91         is to disallow uppercase characters (in some places, we quote
92         table/column names and in other not, which leads to this kind
93         of errors:
94
95             psycopg2.ProgrammingError: relation "xxx" does not exist).
96
97         The same restriction should apply to both osv and osv_memory
98         objects for consistency.
99
100     """
101     if regex_object_name.match(name) is None:
102         return False
103     return True
104
105 def raise_on_invalid_object_name(name):
106     if not check_object_name(name):
107         msg = "The _name attribute %s is not valid." % name
108         _logger.error(msg)
109         raise except_orm('ValueError', msg)
110
111 POSTGRES_CONFDELTYPES = {
112     'RESTRICT': 'r',
113     'NO ACTION': 'a',
114     'CASCADE': 'c',
115     'SET NULL': 'n',
116     'SET DEFAULT': 'd',
117 }
118
119 def intersect(la, lb):
120     return filter(lambda x: x in lb, la)
121
122 def same_name(f, g):
123     """ Test whether functions `f` and `g` are identical or have the same name """
124     return f == g or getattr(f, '__name__', 0) == getattr(g, '__name__', 1)
125
126 def fix_import_export_id_paths(fieldname):
127     """
128     Fixes the id fields in import and exports, and splits field paths
129     on '/'.
130
131     :param str fieldname: name of the field to import/export
132     :return: split field name
133     :rtype: list of str
134     """
135     fixed_db_id = re.sub(r'([^/])\.id', r'\1/.id', fieldname)
136     fixed_external_id = re.sub(r'([^/]):id', r'\1/id', fixed_db_id)
137     return fixed_external_id.split('/')
138
139 def pg_varchar(size=0):
140     """ Returns the VARCHAR declaration for the provided size:
141
142     * If no size (or an empty or negative size is provided) return an
143       'infinite' VARCHAR
144     * Otherwise return a VARCHAR(n)
145
146     :type int size: varchar size, optional
147     :rtype: str
148     """
149     if size:
150         if not isinstance(size, int):
151             raise TypeError("VARCHAR parameter should be an int, got %s"
152                             % type(size))
153         if size > 0:
154             return 'VARCHAR(%d)' % size
155     return 'VARCHAR'
156
157 FIELDS_TO_PGTYPES = {
158     fields.boolean: 'bool',
159     fields.integer: 'int4',
160     fields.text: 'text',
161     fields.html: 'text',
162     fields.date: 'date',
163     fields.datetime: 'timestamp',
164     fields.binary: 'bytea',
165     fields.many2one: 'int4',
166     fields.serialized: 'text',
167 }
168
169 def get_pg_type(f, type_override=None):
170     """
171     :param fields._column f: field to get a Postgres type for
172     :param type type_override: use the provided type for dispatching instead of the field's own type
173     :returns: (postgres_identification_type, postgres_type_specification)
174     :rtype: (str, str)
175     """
176     field_type = type_override or type(f)
177
178     if field_type in FIELDS_TO_PGTYPES:
179         pg_type =  (FIELDS_TO_PGTYPES[field_type], FIELDS_TO_PGTYPES[field_type])
180     elif issubclass(field_type, fields.float):
181         # Explicit support for "falsy" digits (0, False) to indicate a
182         # NUMERIC field with no fixed precision. The values will be saved
183         # in the database with all significant digits.
184         # FLOAT8 type is still the default when there is no precision because
185         # it is faster for most operations (sums, etc.)
186         if f.digits is not None:
187             pg_type = ('numeric', 'NUMERIC')
188         else:
189             pg_type = ('float8', 'DOUBLE PRECISION')
190     elif issubclass(field_type, (fields.char, fields.reference)):
191         pg_type = ('varchar', pg_varchar(f.size))
192     elif issubclass(field_type, fields.selection):
193         if (isinstance(f.selection, list) and isinstance(f.selection[0][0], int))\
194                 or getattr(f, 'size', None) == -1:
195             pg_type = ('int4', 'INTEGER')
196         else:
197             pg_type = ('varchar', pg_varchar(getattr(f, 'size', None)))
198     elif issubclass(field_type, fields.function):
199         if f._type == 'selection':
200             pg_type = ('varchar', pg_varchar())
201         else:
202             pg_type = get_pg_type(f, getattr(fields, f._type))
203     else:
204         _logger.warning('%s type not supported!', field_type)
205         pg_type = None
206
207     return pg_type
208
209
210 class MetaModel(api.Meta):
211     """ Metaclass for the models.
212
213     This class is used as the metaclass for the class :class:`BaseModel` to
214     discover the models defined in a module (without instanciating them).
215     If the automatic discovery is not needed, it is possible to set the model's
216     ``_register`` attribute to False.
217
218     """
219
220     module_to_models = {}
221
222     def __init__(self, name, bases, attrs):
223         if not self._register:
224             self._register = True
225             super(MetaModel, self).__init__(name, bases, attrs)
226             return
227
228         if not hasattr(self, '_module'):
229             # The (OpenERP) module name can be in the `openerp.addons` namespace
230             # or not.  For instance, module `sale` can be imported as
231             # `openerp.addons.sale` (the right way) or `sale` (for backward
232             # compatibility).
233             module_parts = self.__module__.split('.')
234             if len(module_parts) > 2 and module_parts[:2] == ['openerp', 'addons']:
235                 module_name = self.__module__.split('.')[2]
236             else:
237                 module_name = self.__module__.split('.')[0]
238             self._module = module_name
239
240         # Remember which models to instanciate for this module.
241         if not self._custom:
242             self.module_to_models.setdefault(self._module, []).append(self)
243
244         # transform columns into new-style fields (enables field inheritance)
245         for name, column in self._columns.iteritems():
246             if name in self.__dict__:
247                 _logger.warning("In class %s, field %r overriding an existing value", self, name)
248             setattr(self, name, column.to_field())
249
250
251 class NewId(object):
252     """ Pseudo-ids for new records. """
253     def __nonzero__(self):
254         return False
255
256 IdType = (int, long, basestring, NewId)
257
258
259 # maximum number of prefetched records
260 PREFETCH_MAX = 200
261
262 # special columns automatically created by the ORM
263 LOG_ACCESS_COLUMNS = ['create_uid', 'create_date', 'write_uid', 'write_date']
264 MAGIC_COLUMNS = ['id'] + LOG_ACCESS_COLUMNS
265
266 class BaseModel(object):
267     """ Base class for OpenERP models.
268
269     OpenERP models are created by inheriting from this class' subclasses:
270
271     *   :class:`Model` for regular database-persisted models
272
273     *   :class:`TransientModel` for temporary data, stored in the database but
274         automatically vaccuumed every so often
275
276     *   :class:`AbstractModel` for abstract super classes meant to be shared by
277         multiple inheriting model
278
279     The system automatically instantiates every model once per database. Those
280     instances represent the available models on each database, and depend on
281     which modules are installed on that database. The actual class of each
282     instance is built from the Python classes that create and inherit from the
283     corresponding model.
284
285     Every model instance is a "recordset", i.e., an ordered collection of
286     records of the model. Recordsets are returned by methods like
287     :meth:`~.browse`, :meth:`~.search`, or field accesses. Records have no
288     explicit representation: a record is represented as a recordset of one
289     record.
290
291     To create a class that should not be instantiated, the _register class
292     attribute may be set to False.
293     """
294     __metaclass__ = MetaModel
295     _auto = True # create database backend
296     _register = False # Set to false if the model shouldn't be automatically discovered.
297     _name = None
298     _columns = {}
299     _constraints = []
300     _custom = False
301     _defaults = {}
302     _rec_name = None
303     _parent_name = 'parent_id'
304     _parent_store = False
305     _parent_order = False
306     _date_name = 'date'
307     _order = 'id'
308     _sequence = None
309     _description = None
310     _needaction = False
311     _translate = True # set to False to disable translations export for this model
312
313     # dict of {field:method}, with method returning the (name_get of records, {id: fold})
314     # to include in the _read_group, if grouped on this field
315     _group_by_full = {}
316
317     # Transience
318     _transient = False # True in a TransientModel
319
320     # structure:
321     #  { 'parent_model': 'm2o_field', ... }
322     _inherits = {}
323
324     # Mapping from inherits'd field name to triple (m, r, f, n) where m is the
325     # model from which it is inherits'd, r is the (local) field towards m, f
326     # is the _column object itself, and n is the original (i.e. top-most)
327     # parent model.
328     # Example:
329     #  { 'field_name': ('parent_model', 'm2o_field_to_reach_parent',
330     #                   field_column_obj, origina_parent_model), ... }
331     _inherit_fields = {}
332
333     # Mapping field name/column_info object
334     # This is similar to _inherit_fields but:
335     # 1. includes self fields,
336     # 2. uses column_info instead of a triple.
337     _all_columns = {}
338
339     _table = None
340     _log_create = False
341     _sql_constraints = []
342
343     # model dependencies, for models backed up by sql views:
344     # {model_name: field_names, ...}
345     _depends = {}
346
347     CONCURRENCY_CHECK_FIELD = '__last_update'
348
349     def log(self, cr, uid, id, message, secondary=False, context=None):
350         return _logger.warning("log() is deprecated. Please use OpenChatter notification system instead of the res.log mechanism.")
351
352     def view_init(self, cr, uid, fields_list, context=None):
353         """Override this method to do specific things when a view on the object is opened."""
354         pass
355
356     def _field_create(self, cr, context=None):
357         """ Create entries in ir_model_fields for all the model's fields.
358
359         If necessary, also create an entry in ir_model, and if called from the
360         modules loading scheme (by receiving 'module' in the context), also
361         create entries in ir_model_data (for the model and the fields).
362
363         - create an entry in ir_model (if there is not already one),
364         - create an entry in ir_model_data (if there is not already one, and if
365           'module' is in the context),
366         - update ir_model_fields with the fields found in _columns
367           (TODO there is some redundancy as _columns is updated from
368           ir_model_fields in __init__).
369
370         """
371         if context is None:
372             context = {}
373         cr.execute("SELECT id FROM ir_model WHERE model=%s", (self._name,))
374         if not cr.rowcount:
375             cr.execute('SELECT nextval(%s)', ('ir_model_id_seq',))
376             model_id = cr.fetchone()[0]
377             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'))
378         else:
379             model_id = cr.fetchone()[0]
380         if 'module' in context:
381             name_id = 'model_'+self._name.replace('.', '_')
382             cr.execute('select * from ir_model_data where name=%s and module=%s', (name_id, context['module']))
383             if not cr.rowcount:
384                 cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, (now() at time zone 'UTC'), (now() at time zone 'UTC'), %s, %s, %s)", \
385                     (name_id, context['module'], 'ir.model', model_id)
386                 )
387
388         cr.execute("SELECT * FROM ir_model_fields WHERE model=%s", (self._name,))
389         cols = {}
390         for rec in cr.dictfetchall():
391             cols[rec['name']] = rec
392
393         ir_model_fields_obj = self.pool.get('ir.model.fields')
394
395         # sparse field should be created at the end, as it depends on its serialized field already existing
396         model_fields = sorted(self._columns.items(), key=lambda x: 1 if x[1]._type == 'sparse' else 0)
397         for (k, f) in model_fields:
398             vals = {
399                 'model_id': model_id,
400                 'model': self._name,
401                 'name': k,
402                 'field_description': f.string,
403                 'ttype': f._type,
404                 'relation': f._obj or '',
405                 'select_level': tools.ustr(int(f.select)),
406                 'readonly': (f.readonly and 1) or 0,
407                 'required': (f.required and 1) or 0,
408                 'selectable': (f.selectable and 1) or 0,
409                 'translate': (f.translate and 1) or 0,
410                 'relation_field': f._fields_id if isinstance(f, fields.one2many) else '',
411                 'serialization_field_id': None,
412             }
413             if getattr(f, 'serialization_field', None):
414                 # resolve link to serialization_field if specified by name
415                 serialization_field_id = ir_model_fields_obj.search(cr, SUPERUSER_ID, [('model','=',vals['model']), ('name', '=', f.serialization_field)])
416                 if not serialization_field_id:
417                     raise except_orm(_('Error'), _("Serialization field `%s` not found for sparse field `%s`!") % (f.serialization_field, k))
418                 vals['serialization_field_id'] = serialization_field_id[0]
419
420             # When its a custom field,it does not contain f.select
421             if context.get('field_state', 'base') == 'manual':
422                 if context.get('field_name', '') == k:
423                     vals['select_level'] = context.get('select', '0')
424                 #setting value to let the problem NOT occur next time
425                 elif k in cols:
426                     vals['select_level'] = cols[k]['select_level']
427
428             if k not in cols:
429                 cr.execute('select nextval(%s)', ('ir_model_fields_id_seq',))
430                 id = cr.fetchone()[0]
431                 vals['id'] = id
432                 cr.execute("""INSERT INTO ir_model_fields (
433                     id, model_id, model, name, field_description, ttype,
434                     relation,state,select_level,relation_field, translate, serialization_field_id
435                 ) VALUES (
436                     %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s
437                 )""", (
438                     id, vals['model_id'], vals['model'], vals['name'], vals['field_description'], vals['ttype'],
439                      vals['relation'], 'base',
440                     vals['select_level'], vals['relation_field'], bool(vals['translate']), vals['serialization_field_id']
441                 ))
442                 if 'module' in context:
443                     name1 = 'field_' + self._table + '_' + k
444                     cr.execute("select name from ir_model_data where name=%s", (name1,))
445                     if cr.fetchone():
446                         name1 = name1 + "_" + str(id)
447                     cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, (now() at time zone 'UTC'), (now() at time zone 'UTC'), %s, %s, %s)", \
448                         (name1, context['module'], 'ir.model.fields', id)
449                     )
450             else:
451                 for key, val in vals.items():
452                     if cols[k][key] != vals[key]:
453                         cr.execute('update ir_model_fields set field_description=%s where model=%s and name=%s', (vals['field_description'], vals['model'], vals['name']))
454                         cr.execute("""UPDATE ir_model_fields SET
455                             model_id=%s, field_description=%s, ttype=%s, relation=%s,
456                             select_level=%s, readonly=%s ,required=%s, selectable=%s, relation_field=%s, translate=%s, serialization_field_id=%s
457                         WHERE
458                             model=%s AND name=%s""", (
459                                 vals['model_id'], vals['field_description'], vals['ttype'],
460                                 vals['relation'],
461                                 vals['select_level'], bool(vals['readonly']), bool(vals['required']), bool(vals['selectable']), vals['relation_field'], bool(vals['translate']), vals['serialization_field_id'], vals['model'], vals['name']
462                             ))
463                         break
464         self.invalidate_cache(cr, SUPERUSER_ID)
465
466     @classmethod
467     def _add_field(cls, name, field):
468         """ Add the given `field` under the given `name` in the class """
469         # add field as an attribute and in cls._fields (for reflection)
470         if not isinstance(getattr(cls, name, field), Field):
471             _logger.warning("In model %r, field %r overriding existing value", cls._name, name)
472         setattr(cls, name, field)
473         cls._fields[name] = field
474
475         # basic setup of field
476         field.set_class_name(cls, name)
477
478         if field.store:
479             cls._columns[name] = field.to_column()
480         else:
481             # remove potential column that may be overridden by field
482             cls._columns.pop(name, None)
483
484     @classmethod
485     def _pop_field(cls, name):
486         """ Remove the field with the given `name` from the model.
487             This method should only be used for manual fields.
488         """
489         field = cls._fields.pop(name)
490         cls._columns.pop(name, None)
491         cls._all_columns.pop(name, None)
492         if hasattr(cls, name):
493             delattr(cls, name)
494         return field
495
496     @classmethod
497     def _add_magic_fields(cls):
498         """ Introduce magic fields on the current class
499
500         * id is a "normal" field (with a specific getter)
501         * create_uid, create_date, write_uid and write_date have become
502           "normal" fields
503         * $CONCURRENCY_CHECK_FIELD is a computed field with its computing
504           method defined dynamically. Uses ``str(datetime.datetime.utcnow())``
505           to get the same structure as the previous
506           ``(now() at time zone 'UTC')::timestamp``::
507
508               # select (now() at time zone 'UTC')::timestamp;
509                         timezone
510               ----------------------------
511                2013-06-18 08:30:37.292809
512
513               >>> str(datetime.datetime.utcnow())
514               '2013-06-18 08:31:32.821177'
515         """
516         def add(name, field):
517             """ add `field` with the given `name` if it does not exist yet """
518             if name not in cls._columns and name not in cls._fields:
519                 cls._add_field(name, field)
520
521         # cyclic import
522         from . import fields
523
524         # this field 'id' must override any other column or field
525         cls._add_field('id', fields.Id(automatic=True))
526
527         add('display_name', fields.Char(string='Display Name', automatic=True,
528             compute='_compute_display_name'))
529
530         if cls._log_access:
531             add('create_uid', fields.Many2one('res.users', string='Created by', automatic=True))
532             add('create_date', fields.Datetime(string='Created on', automatic=True))
533             add('write_uid', fields.Many2one('res.users', string='Last Updated by', automatic=True))
534             add('write_date', fields.Datetime(string='Last Updated on', automatic=True))
535             last_modified_name = 'compute_concurrency_field_with_access'
536         else:
537             last_modified_name = 'compute_concurrency_field'
538
539         # this field must override any other column or field
540         cls._add_field(cls.CONCURRENCY_CHECK_FIELD, fields.Datetime(
541             string='Last Modified on', compute=last_modified_name, automatic=True))
542
543     @api.one
544     def compute_concurrency_field(self):
545         self[self.CONCURRENCY_CHECK_FIELD] = \
546             datetime.datetime.utcnow().strftime(DEFAULT_SERVER_DATETIME_FORMAT)
547
548     @api.one
549     @api.depends('create_date', 'write_date')
550     def compute_concurrency_field_with_access(self):
551         self[self.CONCURRENCY_CHECK_FIELD] = \
552             self.write_date or self.create_date or \
553             datetime.datetime.utcnow().strftime(DEFAULT_SERVER_DATETIME_FORMAT)
554
555     #
556     # Goal: try to apply inheritance at the instanciation level and
557     #       put objects in the pool var
558     #
559     @classmethod
560     def _build_model(cls, pool, cr):
561         """ Instanciate a given model.
562
563         This class method instanciates the class of some model (i.e. a class
564         deriving from osv or osv_memory). The class might be the class passed
565         in argument or, if it inherits from another class, a class constructed
566         by combining the two classes.
567
568         """
569
570         # IMPORTANT: the registry contains an instance for each model. The class
571         # of each model carries inferred metadata that is shared among the
572         # model's instances for this registry, but not among registries. Hence
573         # we cannot use that "registry class" for combining model classes by
574         # inheritance, since it confuses the metadata inference process.
575
576         # Keep links to non-inherited constraints in cls; this is useful for
577         # instance when exporting translations
578         cls._local_constraints = cls.__dict__.get('_constraints', [])
579         cls._local_sql_constraints = cls.__dict__.get('_sql_constraints', [])
580
581         # determine inherited models
582         parents = getattr(cls, '_inherit', [])
583         parents = [parents] if isinstance(parents, basestring) else (parents or [])
584
585         # determine the model's name
586         name = cls._name or (len(parents) == 1 and parents[0]) or cls.__name__
587
588         # determine the module that introduced the model
589         original_module = pool[name]._original_module if name in parents else cls._module
590
591         # build the class hierarchy for the model
592         for parent in parents:
593             if parent not in pool:
594                 raise TypeError('The model "%s" specifies an unexisting parent class "%s"\n'
595                     'You may need to add a dependency on the parent class\' module.' % (name, parent))
596             parent_model = pool[parent]
597
598             # do no use the class of parent_model, since that class contains
599             # inferred metadata; use its ancestor instead
600             parent_class = type(parent_model).__base__
601
602             # don't inherit custom fields
603             columns = dict((key, val)
604                 for key, val in parent_class._columns.iteritems()
605                 if not val.manual
606             )
607             columns.update(cls._columns)
608
609             inherits = dict(parent_class._inherits)
610             inherits.update(cls._inherits)
611
612             depends = dict(parent_class._depends)
613             for m, fs in cls._depends.iteritems():
614                 depends[m] = depends.get(m, []) + fs
615
616             old_constraints = parent_class._constraints
617             new_constraints = cls._constraints
618             # filter out from old_constraints the ones overridden by a
619             # constraint with the same function name in new_constraints
620             constraints = new_constraints + [oldc
621                 for oldc in old_constraints
622                 if not any(newc[2] == oldc[2] and same_name(newc[0], oldc[0])
623                            for newc in new_constraints)
624             ]
625
626             sql_constraints = cls._sql_constraints + \
627                               parent_class._sql_constraints
628
629             attrs = {
630                 '_name': name,
631                 '_register': False,
632                 '_columns': columns,
633                 '_inherits': inherits,
634                 '_depends': depends,
635                 '_constraints': constraints,
636                 '_sql_constraints': sql_constraints,
637             }
638             cls = type(name, (cls, parent_class), attrs)
639
640         # introduce the "registry class" of the model;
641         # duplicate some attributes so that the ORM can modify them
642         attrs = {
643             '_name': name,
644             '_register': False,
645             '_columns': dict(cls._columns),
646             '_defaults': {},            # filled by Field._determine_default()
647             '_inherits': dict(cls._inherits),
648             '_depends': dict(cls._depends),
649             '_constraints': list(cls._constraints),
650             '_sql_constraints': list(cls._sql_constraints),
651             '_original_module': original_module,
652         }
653         cls = type(cls._name, (cls,), attrs)
654
655         # instantiate the model, and initialize it
656         model = object.__new__(cls)
657         model.__init__(pool, cr)
658         return model
659
660     @classmethod
661     def _init_function_fields(cls, pool, cr):
662         # initialize the list of non-stored function fields for this model
663         pool._pure_function_fields[cls._name] = []
664
665         # process store of low-level function fields
666         for fname, column in cls._columns.iteritems():
667             if hasattr(column, 'digits_change'):
668                 column.digits_change(cr)
669             # filter out existing store about this field
670             pool._store_function[cls._name] = [
671                 stored
672                 for stored in pool._store_function.get(cls._name, [])
673                 if (stored[0], stored[1]) != (cls._name, fname)
674             ]
675             if not isinstance(column, fields.function):
676                 continue
677             if not column.store:
678                 # register it on the pool for invalidation
679                 pool._pure_function_fields[cls._name].append(fname)
680                 continue
681             # process store parameter
682             store = column.store
683             if store is True:
684                 get_ids = lambda self, cr, uid, ids, c={}: ids
685                 store = {cls._name: (get_ids, None, column.priority, None)}
686             for model, spec in store.iteritems():
687                 if len(spec) == 4:
688                     (fnct, fields2, order, length) = spec
689                 elif len(spec) == 3:
690                     (fnct, fields2, order) = spec
691                     length = None
692                 else:
693                     raise except_orm('Error',
694                         ('Invalid function definition %s in object %s !\nYou must use the definition: store={object:(fnct, fields, priority, time length)}.' % (fname, cls._name)))
695                 pool._store_function.setdefault(model, [])
696                 t = (cls._name, fname, fnct, tuple(fields2) if fields2 else None, order, length)
697                 if t not in pool._store_function[model]:
698                     pool._store_function[model].append(t)
699                     pool._store_function[model].sort(key=lambda x: x[4])
700
701     @classmethod
702     def _init_manual_fields(cls, pool, cr):
703         # Check whether the query is already done
704         if pool.fields_by_model is not None:
705             manual_fields = pool.fields_by_model.get(cls._name, [])
706         else:
707             cr.execute('SELECT * FROM ir_model_fields WHERE model=%s AND state=%s', (cls._name, 'manual'))
708             manual_fields = cr.dictfetchall()
709
710         for field in manual_fields:
711             if field['name'] in cls._columns:
712                 continue
713             attrs = {
714                 'string': field['field_description'],
715                 'required': bool(field['required']),
716                 'readonly': bool(field['readonly']),
717                 'domain': eval(field['domain']) if field['domain'] else None,
718                 'size': field['size'] or None,
719                 'ondelete': field['on_delete'],
720                 'translate': (field['translate']),
721                 'manual': True,
722                 '_prefetch': False,
723                 #'select': int(field['select_level'])
724             }
725             if field['serialization_field_id']:
726                 cr.execute('SELECT name FROM ir_model_fields WHERE id=%s', (field['serialization_field_id'],))
727                 attrs.update({'serialization_field': cr.fetchone()[0], 'type': field['ttype']})
728                 if field['ttype'] in ['many2one', 'one2many', 'many2many']:
729                     attrs.update({'relation': field['relation']})
730                 cls._columns[field['name']] = fields.sparse(**attrs)
731             elif field['ttype'] == 'selection':
732                 cls._columns[field['name']] = fields.selection(eval(field['selection']), **attrs)
733             elif field['ttype'] == 'reference':
734                 cls._columns[field['name']] = fields.reference(selection=eval(field['selection']), **attrs)
735             elif field['ttype'] == 'many2one':
736                 cls._columns[field['name']] = fields.many2one(field['relation'], **attrs)
737             elif field['ttype'] == 'one2many':
738                 cls._columns[field['name']] = fields.one2many(field['relation'], field['relation_field'], **attrs)
739             elif field['ttype'] == 'many2many':
740                 _rel1 = field['relation'].replace('.', '_')
741                 _rel2 = field['model'].replace('.', '_')
742                 _rel_name = 'x_%s_%s_%s_rel' % (_rel1, _rel2, field['name'])
743                 cls._columns[field['name']] = fields.many2many(field['relation'], _rel_name, 'id1', 'id2', **attrs)
744             else:
745                 cls._columns[field['name']] = getattr(fields, field['ttype'])(**attrs)
746
747     @classmethod
748     def _init_constraints_onchanges(cls):
749         # store sql constraint error messages
750         for (key, _, msg) in cls._sql_constraints:
751             cls.pool._sql_error[cls._table + '_' + key] = msg
752
753         # collect constraint and onchange methods
754         cls._constraint_methods = []
755         cls._onchange_methods = defaultdict(list)
756         for attr, func in getmembers(cls, callable):
757             if hasattr(func, '_constrains'):
758                 if not all(name in cls._fields for name in func._constrains):
759                     _logger.warning("@constrains%r parameters must be field names", func._constrains)
760                 cls._constraint_methods.append(func)
761             if hasattr(func, '_onchange'):
762                 if not all(name in cls._fields for name in func._onchange):
763                     _logger.warning("@onchange%r parameters must be field names", func._onchange)
764                 for name in func._onchange:
765                     cls._onchange_methods[name].append(func)
766
767     def __new__(cls):
768         # In the past, this method was registering the model class in the server.
769         # This job is now done entirely by the metaclass MetaModel.
770         #
771         # Do not create an instance here.  Model instances are created by method
772         # _build_model().
773         return None
774
775     def __init__(self, pool, cr):
776         """ Initialize a model and make it part of the given registry.
777
778         - copy the stored fields' functions in the registry,
779         - retrieve custom fields and add them in the model,
780         - ensure there is a many2one for each _inherits'd parent,
781         - update the children's _columns,
782         - give a chance to each field to initialize itself.
783
784         """
785         cls = type(self)
786
787         # link the class to the registry, and update the registry
788         cls.pool = pool
789         cls._model = self              # backward compatibility
790         pool.add(cls._name, self)
791
792         # determine description, table, sequence and log_access
793         if not cls._description:
794             cls._description = cls._name
795         if not cls._table:
796             cls._table = cls._name.replace('.', '_')
797         if not cls._sequence:
798             cls._sequence = cls._table + '_id_seq'
799         if not hasattr(cls, '_log_access'):
800             # If _log_access is not specified, it is the same value as _auto.
801             cls._log_access = cls._auto
802
803         # Transience
804         if cls.is_transient():
805             cls._transient_check_count = 0
806             cls._transient_max_count = config.get('osv_memory_count_limit')
807             cls._transient_max_hours = config.get('osv_memory_age_limit')
808             assert cls._log_access, \
809                 "TransientModels must have log_access turned on, " \
810                 "in order to implement their access rights policy"
811
812         # retrieve new-style fields (from above registry class) and duplicate
813         # them (to avoid clashes with inheritance between different models)
814         cls._fields = {}
815         above = cls.__bases__[0]
816         for attr, field in getmembers(above, Field.__instancecheck__):
817             if not field.inherited:
818                 cls._add_field(attr, field.new())
819
820         # introduce magic fields
821         cls._add_magic_fields()
822
823         # register stuff about low-level function fields and custom fields
824         cls._init_function_fields(pool, cr)
825         cls._init_manual_fields(pool, cr)
826
827         # process _inherits
828         cls._inherits_check()
829         cls._inherits_reload()
830
831         # register constraints and onchange methods
832         cls._init_constraints_onchanges()
833
834         # check defaults
835         for k in cls._defaults:
836             assert k in cls._fields, \
837                 "Model %s has a default for non-existing field %s" % (cls._name, k)
838
839         # restart columns
840         for column in cls._columns.itervalues():
841             column.restart()
842
843         # validate rec_name
844         if cls._rec_name:
845             assert cls._rec_name in cls._fields, \
846                 "Invalid rec_name %s for model %s" % (cls._rec_name, cls._name)
847         elif 'name' in cls._fields:
848             cls._rec_name = 'name'
849
850         # prepare ormcache, which must be shared by all instances of the model
851         cls._ormcache = {}
852
853     @api.model
854     @ormcache()
855     def _is_an_ordinary_table(self):
856         self.env.cr.execute("""\
857             SELECT  1
858             FROM    pg_class
859             WHERE   relname = %s
860             AND     relkind = %s""", [self._table, 'r'])
861         return bool(self.env.cr.fetchone())
862
863     def __export_xml_id(self):
864         """ Return a valid xml_id for the record `self`. """
865         if not self._is_an_ordinary_table():
866             raise Exception(
867                 "You can not export the column ID of model %s, because the "
868                 "table %s is not an ordinary table."
869                 % (self._name, self._table))
870         ir_model_data = self.sudo().env['ir.model.data']
871         data = ir_model_data.search([('model', '=', self._name), ('res_id', '=', self.id)])
872         if data:
873             if data[0].module:
874                 return '%s.%s' % (data[0].module, data[0].name)
875             else:
876                 return data[0].name
877         else:
878             postfix = 0
879             name = '%s_%s' % (self._table, self.id)
880             while ir_model_data.search([('module', '=', '__export__'), ('name', '=', name)]):
881                 postfix += 1
882                 name = '%s_%s_%s' % (self._table, self.id, postfix)
883             ir_model_data.create({
884                 'model': self._name,
885                 'res_id': self.id,
886                 'module': '__export__',
887                 'name': name,
888             })
889             return '__export__.' + name
890
891     @api.multi
892     def __export_rows(self, fields):
893         """ Export fields of the records in `self`.
894
895             :param fields: list of lists of fields to traverse
896             :return: list of lists of corresponding values
897         """
898         lines = []
899         for record in self:
900             # main line of record, initially empty
901             current = [''] * len(fields)
902             lines.append(current)
903
904             # list of primary fields followed by secondary field(s)
905             primary_done = []
906
907             # process column by column
908             for i, path in enumerate(fields):
909                 if not path:
910                     continue
911
912                 name = path[0]
913                 if name in primary_done:
914                     continue
915
916                 if name == '.id':
917                     current[i] = str(record.id)
918                 elif name == 'id':
919                     current[i] = record.__export_xml_id()
920                 else:
921                     field = record._fields[name]
922                     value = record[name]
923
924                     # this part could be simpler, but it has to be done this way
925                     # in order to reproduce the former behavior
926                     if not isinstance(value, BaseModel):
927                         current[i] = field.convert_to_export(value, self.env)
928                     else:
929                         primary_done.append(name)
930
931                         # This is a special case, its strange behavior is intended!
932                         if field.type == 'many2many' and len(path) > 1 and path[1] == 'id':
933                             xml_ids = [r.__export_xml_id() for r in value]
934                             current[i] = ','.join(xml_ids) or False
935                             continue
936
937                         # recursively export the fields that follow name
938                         fields2 = [(p[1:] if p and p[0] == name else []) for p in fields]
939                         lines2 = value.__export_rows(fields2)
940                         if lines2:
941                             # merge first line with record's main line
942                             for j, val in enumerate(lines2[0]):
943                                 if val:
944                                     current[j] = val
945                             # check value of current field
946                             if not current[i]:
947                                 # assign xml_ids, and forget about remaining lines
948                                 xml_ids = [item[1] for item in value.name_get()]
949                                 current[i] = ','.join(xml_ids)
950                             else:
951                                 # append the other lines at the end
952                                 lines += lines2[1:]
953                         else:
954                             current[i] = False
955
956         return lines
957
958     @api.multi
959     def export_data(self, fields_to_export, raw_data=False):
960         """ Export fields for selected objects
961
962             :param fields_to_export: list of fields
963             :param raw_data: True to return value in native Python type
964             :rtype: dictionary with a *datas* matrix
965
966             This method is used when exporting data via client menu
967         """
968         fields_to_export = map(fix_import_export_id_paths, fields_to_export)
969         if raw_data:
970             self = self.with_context(export_raw_data=True)
971         return {'datas': self.__export_rows(fields_to_export)}
972
973     def import_data(self, cr, uid, fields, datas, mode='init', current_module='', noupdate=False, context=None, filename=None):
974         """
975         .. deprecated:: 7.0
976             Use :meth:`~load` instead
977
978         Import given data in given module
979
980         This method is used when importing data via client menu.
981
982         Example of fields to import for a sale.order::
983
984             .id,                         (=database_id)
985             partner_id,                  (=name_search)
986             order_line/.id,              (=database_id)
987             order_line/name,
988             order_line/product_id/id,    (=xml id)
989             order_line/price_unit,
990             order_line/product_uom_qty,
991             order_line/product_uom/id    (=xml_id)
992
993         This method returns a 4-tuple with the following structure::
994
995             (return_code, errored_resource, error_message, unused)
996
997         * The first item is a return code, it is ``-1`` in case of
998           import error, or the last imported row number in case of success
999         * The second item contains the record data dict that failed to import
1000           in case of error, otherwise it's 0
1001         * The third item contains an error message string in case of error,
1002           otherwise it's 0
1003         * The last item is currently unused, with no specific semantics
1004
1005         :param fields: list of fields to import
1006         :param datas: data to import
1007         :param mode: 'init' or 'update' for record creation
1008         :param current_module: module name
1009         :param noupdate: flag for record creation
1010         :param filename: optional file to store partial import state for recovery
1011         :returns: 4-tuple in the form (return_code, errored_resource, error_message, unused)
1012         :rtype: (int, dict or 0, str or 0, str or 0)
1013         """
1014         context = dict(context) if context is not None else {}
1015         context['_import_current_module'] = current_module
1016
1017         fields = map(fix_import_export_id_paths, fields)
1018         ir_model_data_obj = self.pool.get('ir.model.data')
1019
1020         def log(m):
1021             if m['type'] == 'error':
1022                 raise Exception(m['message'])
1023
1024         if config.get('import_partial') and filename:
1025             with open(config.get('import_partial'), 'rb') as partial_import_file:
1026                 data = pickle.load(partial_import_file)
1027                 position = data.get(filename, 0)
1028
1029         position = 0
1030         try:
1031             for res_id, xml_id, res, info in self._convert_records(cr, uid,
1032                             self._extract_records(cr, uid, fields, datas,
1033                                                   context=context, log=log),
1034                             context=context, log=log):
1035                 ir_model_data_obj._update(cr, uid, self._name,
1036                      current_module, res, mode=mode, xml_id=xml_id,
1037                      noupdate=noupdate, res_id=res_id, context=context)
1038                 position = info.get('rows', {}).get('to', 0) + 1
1039                 if config.get('import_partial') and filename and (not (position%100)):
1040                     with open(config.get('import_partial'), 'rb') as partial_import:
1041                         data = pickle.load(partial_import)
1042                     data[filename] = position
1043                     with open(config.get('import_partial'), 'wb') as partial_import:
1044                         pickle.dump(data, partial_import)
1045                     if context.get('defer_parent_store_computation'):
1046                         self._parent_store_compute(cr)
1047                     cr.commit()
1048         except Exception, e:
1049             cr.rollback()
1050             return -1, {}, 'Line %d : %s' % (position + 1, tools.ustr(e)), ''
1051
1052         if context.get('defer_parent_store_computation'):
1053             self._parent_store_compute(cr)
1054         return position, 0, 0, 0
1055
1056     def load(self, cr, uid, fields, data, context=None):
1057         """
1058         Attempts to load the data matrix, and returns a list of ids (or
1059         ``False`` if there was an error and no id could be generated) and a
1060         list of messages.
1061
1062         The ids are those of the records created and saved (in database), in
1063         the same order they were extracted from the file. They can be passed
1064         directly to :meth:`~read`
1065
1066         :param fields: list of fields to import, at the same index as the corresponding data
1067         :type fields: list(str)
1068         :param data: row-major matrix of data to import
1069         :type data: list(list(str))
1070         :param dict context:
1071         :returns: {ids: list(int)|False, messages: [Message]}
1072         """
1073         cr.execute('SAVEPOINT model_load')
1074         messages = []
1075
1076         fields = map(fix_import_export_id_paths, fields)
1077         ModelData = self.pool['ir.model.data'].clear_caches()
1078
1079         fg = self.fields_get(cr, uid, context=context)
1080
1081         mode = 'init'
1082         current_module = ''
1083         noupdate = False
1084
1085         ids = []
1086         for id, xid, record, info in self._convert_records(cr, uid,
1087                 self._extract_records(cr, uid, fields, data,
1088                                       context=context, log=messages.append),
1089                 context=context, log=messages.append):
1090             try:
1091                 cr.execute('SAVEPOINT model_load_save')
1092             except psycopg2.InternalError, e:
1093                 # broken transaction, exit and hope the source error was
1094                 # already logged
1095                 if not any(message['type'] == 'error' for message in messages):
1096                     messages.append(dict(info, type='error',message=
1097                         u"Unknown database error: '%s'" % e))
1098                 break
1099             try:
1100                 ids.append(ModelData._update(cr, uid, self._name,
1101                      current_module, record, mode=mode, xml_id=xid,
1102                      noupdate=noupdate, res_id=id, context=context))
1103                 cr.execute('RELEASE SAVEPOINT model_load_save')
1104             except psycopg2.Warning, e:
1105                 messages.append(dict(info, type='warning', message=str(e)))
1106                 cr.execute('ROLLBACK TO SAVEPOINT model_load_save')
1107             except psycopg2.Error, e:
1108                 messages.append(dict(
1109                     info, type='error',
1110                     **PGERROR_TO_OE[e.pgcode](self, fg, info, e)))
1111                 # Failed to write, log to messages, rollback savepoint (to
1112                 # avoid broken transaction) and keep going
1113                 cr.execute('ROLLBACK TO SAVEPOINT model_load_save')
1114             except Exception, e:
1115                 message = (_('Unknown error during import:') +
1116                            ' %s: %s' % (type(e), unicode(e)))
1117                 moreinfo = _('Resolve other errors first')
1118                 messages.append(dict(info, type='error',
1119                                      message=message,
1120                                      moreinfo=moreinfo))
1121                 # Failed for some reason, perhaps due to invalid data supplied,
1122                 # rollback savepoint and keep going
1123                 cr.execute('ROLLBACK TO SAVEPOINT model_load_save')
1124         if any(message['type'] == 'error' for message in messages):
1125             cr.execute('ROLLBACK TO SAVEPOINT model_load')
1126             ids = False
1127         return {'ids': ids, 'messages': messages}
1128
1129     def _extract_records(self, cr, uid, fields_, data,
1130                          context=None, log=lambda a: None):
1131         """ Generates record dicts from the data sequence.
1132
1133         The result is a generator of dicts mapping field names to raw
1134         (unconverted, unvalidated) values.
1135
1136         For relational fields, if sub-fields were provided the value will be
1137         a list of sub-records
1138
1139         The following sub-fields may be set on the record (by key):
1140         * None is the name_get for the record (to use with name_create/name_search)
1141         * "id" is the External ID for the record
1142         * ".id" is the Database ID for the record
1143         """
1144         columns = dict((k, v.column) for k, v in self._all_columns.iteritems())
1145         # Fake columns to avoid special cases in extractor
1146         columns[None] = fields.char('rec_name')
1147         columns['id'] = fields.char('External ID')
1148         columns['.id'] = fields.integer('Database ID')
1149
1150         # m2o fields can't be on multiple lines so exclude them from the
1151         # is_relational field rows filter, but special-case it later on to
1152         # be handled with relational fields (as it can have subfields)
1153         is_relational = lambda field: columns[field]._type in ('one2many', 'many2many', 'many2one')
1154         get_o2m_values = itemgetter_tuple(
1155             [index for index, field in enumerate(fields_)
1156                   if columns[field[0]]._type == 'one2many'])
1157         get_nono2m_values = itemgetter_tuple(
1158             [index for index, field in enumerate(fields_)
1159                   if columns[field[0]]._type != 'one2many'])
1160         # Checks if the provided row has any non-empty non-relational field
1161         def only_o2m_values(row, f=get_nono2m_values, g=get_o2m_values):
1162             return any(g(row)) and not any(f(row))
1163
1164         index = 0
1165         while True:
1166             if index >= len(data): return
1167
1168             row = data[index]
1169             # copy non-relational fields to record dict
1170             record = dict((field[0], value)
1171                 for field, value in itertools.izip(fields_, row)
1172                 if not is_relational(field[0]))
1173
1174             # Get all following rows which have relational values attached to
1175             # the current record (no non-relational values)
1176             record_span = itertools.takewhile(
1177                 only_o2m_values, itertools.islice(data, index + 1, None))
1178             # stitch record row back on for relational fields
1179             record_span = list(itertools.chain([row], record_span))
1180             for relfield in set(
1181                     field[0] for field in fields_
1182                              if is_relational(field[0])):
1183                 column = columns[relfield]
1184                 # FIXME: how to not use _obj without relying on fields_get?
1185                 Model = self.pool[column._obj]
1186
1187                 # get only cells for this sub-field, should be strictly
1188                 # non-empty, field path [None] is for name_get column
1189                 indices, subfields = zip(*((index, field[1:] or [None])
1190                                            for index, field in enumerate(fields_)
1191                                            if field[0] == relfield))
1192
1193                 # return all rows which have at least one value for the
1194                 # subfields of relfield
1195                 relfield_data = filter(any, map(itemgetter_tuple(indices), record_span))
1196                 record[relfield] = [subrecord
1197                     for subrecord, _subinfo in Model._extract_records(
1198                         cr, uid, subfields, relfield_data,
1199                         context=context, log=log)]
1200
1201             yield record, {'rows': {
1202                 'from': index,
1203                 'to': index + len(record_span) - 1
1204             }}
1205             index += len(record_span)
1206     
1207     def _convert_records(self, cr, uid, records,
1208                          context=None, log=lambda a: None):
1209         """ Converts records from the source iterable (recursive dicts of
1210         strings) into forms which can be written to the database (via
1211         self.create or (ir.model.data)._update)
1212
1213         :returns: a list of triplets of (id, xid, record)
1214         :rtype: list((int|None, str|None, dict))
1215         """
1216         if context is None: context = {}
1217         Converter = self.pool['ir.fields.converter']
1218         columns = dict((k, v.column) for k, v in self._all_columns.iteritems())
1219         Translation = self.pool['ir.translation']
1220         field_names = dict(
1221             (f, (Translation._get_source(cr, uid, self._name + ',' + f, 'field',
1222                                          context.get('lang'))
1223                  or column.string))
1224             for f, column in columns.iteritems())
1225
1226         convert = Converter.for_model(cr, uid, self, context=context)
1227
1228         def _log(base, field, exception):
1229             type = 'warning' if isinstance(exception, Warning) else 'error'
1230             # logs the logical (not human-readable) field name for automated
1231             # processing of response, but injects human readable in message
1232             record = dict(base, type=type, field=field,
1233                           message=unicode(exception.args[0]) % base)
1234             if len(exception.args) > 1 and exception.args[1]:
1235                 record.update(exception.args[1])
1236             log(record)
1237
1238         stream = CountingStream(records)
1239         for record, extras in stream:
1240             dbid = False
1241             xid = False
1242             # name_get/name_create
1243             if None in record: pass
1244             # xid
1245             if 'id' in record:
1246                 xid = record['id']
1247             # dbid
1248             if '.id' in record:
1249                 try:
1250                     dbid = int(record['.id'])
1251                 except ValueError:
1252                     # in case of overridden id column
1253                     dbid = record['.id']
1254                 if not self.search(cr, uid, [('id', '=', dbid)], context=context):
1255                     log(dict(extras,
1256                         type='error',
1257                         record=stream.index,
1258                         field='.id',
1259                         message=_(u"Unknown database identifier '%s'") % dbid))
1260                     dbid = False
1261
1262             converted = convert(record, lambda field, err:\
1263                 _log(dict(extras, record=stream.index, field=field_names[field]), field, err))
1264
1265             yield dbid, xid, converted, dict(extras, record=stream.index)
1266
1267     @api.multi
1268     def _validate_fields(self, field_names):
1269         field_names = set(field_names)
1270
1271         # old-style constraint methods
1272         trans = self.env['ir.translation']
1273         cr, uid, context = self.env.args
1274         ids = self.ids
1275         errors = []
1276         for fun, msg, names in self._constraints:
1277             try:
1278                 # validation must be context-independent; call `fun` without context
1279                 valid = not (set(names) & field_names) or fun(self._model, cr, uid, ids)
1280                 extra_error = None
1281             except Exception, e:
1282                 _logger.debug('Exception while validating constraint', exc_info=True)
1283                 valid = False
1284                 extra_error = tools.ustr(e)
1285             if not valid:
1286                 if callable(msg):
1287                     res_msg = msg(self._model, cr, uid, ids, context=context)
1288                     if isinstance(res_msg, tuple):
1289                         template, params = res_msg
1290                         res_msg = template % params
1291                 else:
1292                     res_msg = trans._get_source(self._name, 'constraint', self.env.lang, msg)
1293                 if extra_error:
1294                     res_msg += "\n\n%s\n%s" % (_('Error details:'), extra_error)
1295                 errors.append(
1296                     _("Field(s) `%s` failed against a constraint: %s") %
1297                         (', '.join(names), res_msg)
1298                 )
1299         if errors:
1300             raise ValidationError('\n'.join(errors))
1301
1302         # new-style constraint methods
1303         for check in self._constraint_methods:
1304             if set(check._constrains) & field_names:
1305                 try:
1306                     check(self)
1307                 except ValidationError, e:
1308                     raise
1309                 except Exception, e:
1310                     raise ValidationError("Error while validating constraint\n\n%s" % tools.ustr(e))
1311
1312     @api.model
1313     def default_get(self, fields_list):
1314         """ default_get(fields) -> default_values
1315
1316         Return default values for the fields in `fields_list`. Default
1317         values are determined by the context, user defaults, and the model
1318         itself.
1319
1320         :param fields_list: a list of field names
1321         :return: a dictionary mapping each field name to its corresponding
1322             default value, if it has one.
1323
1324         """
1325         # trigger view init hook
1326         self.view_init(fields_list)
1327
1328         defaults = {}
1329         parent_fields = defaultdict(list)
1330
1331         for name in fields_list:
1332             # 1. look up context
1333             key = 'default_' + name
1334             if key in self._context:
1335                 defaults[name] = self._context[key]
1336                 continue
1337
1338             # 2. look up ir_values
1339             #    Note: performance is good, because get_defaults_dict is cached!
1340             ir_values_dict = self.env['ir.values'].get_defaults_dict(self._name)
1341             if name in ir_values_dict:
1342                 defaults[name] = ir_values_dict[name]
1343                 continue
1344
1345             field = self._fields.get(name)
1346
1347             # 3. look up property fields
1348             #    TODO: get rid of this one
1349             if field and field.company_dependent:
1350                 defaults[name] = self.env['ir.property'].get(name, self._name)
1351                 continue
1352
1353             # 4. look up field.default
1354             if field and field.default:
1355                 defaults[name] = field.default(self)
1356                 continue
1357
1358             # 5. delegate to parent model
1359             if field and field.inherited:
1360                 field = field.related_field
1361                 parent_fields[field.model_name].append(field.name)
1362
1363         # convert default values to the right format
1364         defaults = self._convert_to_cache(defaults, validate=False)
1365         defaults = self._convert_to_write(defaults)
1366
1367         # add default values for inherited fields
1368         for model, names in parent_fields.iteritems():
1369             defaults.update(self.env[model].default_get(names))
1370
1371         return defaults
1372
1373     def fields_get_keys(self, cr, user, context=None):
1374         res = self._columns.keys()
1375         # TODO I believe this loop can be replace by
1376         # res.extend(self._inherit_fields.key())
1377         for parent in self._inherits:
1378             res.extend(self.pool[parent].fields_get_keys(cr, user, context))
1379         return res
1380
1381     def _rec_name_fallback(self, cr, uid, context=None):
1382         rec_name = self._rec_name
1383         if rec_name not in self._columns:
1384             rec_name = self._columns.keys()[0] if len(self._columns.keys()) > 0 else "id"
1385         return rec_name
1386
1387     #
1388     # Overload this method if you need a window title which depends on the context
1389     #
1390     def view_header_get(self, cr, user, view_id=None, view_type='form', context=None):
1391         return False
1392
1393     def user_has_groups(self, cr, uid, groups, context=None):
1394         """Return true if the user is at least member of one of the groups
1395            in groups_str. Typically used to resolve `groups` attribute
1396            in view and model definitions.
1397
1398            :param str groups: comma-separated list of fully-qualified group
1399                               external IDs, e.g.: ``base.group_user,base.group_system``
1400            :return: True if the current user is a member of one of the
1401                     given groups
1402         """
1403         return any(self.pool['res.users'].has_group(cr, uid, group_ext_id)
1404                    for group_ext_id in groups.split(','))
1405
1406     def _get_default_form_view(self, cr, user, context=None):
1407         """ Generates a default single-line form view using all fields
1408         of the current model except the m2m and o2m ones.
1409
1410         :param cr: database cursor
1411         :param int user: user id
1412         :param dict context: connection context
1413         :returns: a form view as an lxml document
1414         :rtype: etree._Element
1415         """
1416         view = etree.Element('form', string=self._description)
1417         group = etree.SubElement(view, 'group', col="4")
1418         for fname, field in self._fields.iteritems():
1419             if field.automatic or field.type in ('one2many', 'many2many'):
1420                 continue
1421
1422             etree.SubElement(group, 'field', name=fname)
1423             if field.type == 'text':
1424                 etree.SubElement(group, 'newline')
1425         return view
1426
1427     def _get_default_search_view(self, cr, user, context=None):
1428         """ Generates a single-field search view, based on _rec_name.
1429
1430         :param cr: database cursor
1431         :param int user: user id
1432         :param dict context: connection context
1433         :returns: a tree view as an lxml document
1434         :rtype: etree._Element
1435         """
1436         view = etree.Element('search', string=self._description)
1437         etree.SubElement(view, 'field', name=self._rec_name_fallback(cr, user, context))
1438         return view
1439
1440     def _get_default_tree_view(self, cr, user, context=None):
1441         """ Generates a single-field tree view, based on _rec_name.
1442
1443         :param cr: database cursor
1444         :param int user: user id
1445         :param dict context: connection context
1446         :returns: a tree view as an lxml document
1447         :rtype: etree._Element
1448         """
1449         view = etree.Element('tree', string=self._description)
1450         etree.SubElement(view, 'field', name=self._rec_name_fallback(cr, user, context))
1451         return view
1452
1453     def _get_default_calendar_view(self, cr, user, context=None):
1454         """ Generates a default calendar view by trying to infer
1455         calendar fields from a number of pre-set attribute names
1456
1457         :param cr: database cursor
1458         :param int user: user id
1459         :param dict context: connection context
1460         :returns: a calendar view
1461         :rtype: etree._Element
1462         """
1463         def set_first_of(seq, in_, to):
1464             """Sets the first value of `seq` also found in `in_` to
1465             the `to` attribute of the view being closed over.
1466
1467             Returns whether it's found a suitable value (and set it on
1468             the attribute) or not
1469             """
1470             for item in seq:
1471                 if item in in_:
1472                     view.set(to, item)
1473                     return True
1474             return False
1475
1476         view = etree.Element('calendar', string=self._description)
1477         etree.SubElement(view, 'field', name=self._rec_name_fallback(cr, user, context))
1478
1479         if self._date_name not in self._columns:
1480             date_found = False
1481             for dt in ['date', 'date_start', 'x_date', 'x_date_start']:
1482                 if dt in self._columns:
1483                     self._date_name = dt
1484                     date_found = True
1485                     break
1486
1487             if not date_found:
1488                 raise except_orm(_('Invalid Object Architecture!'), _("Insufficient fields for Calendar View!"))
1489         view.set('date_start', self._date_name)
1490
1491         set_first_of(["user_id", "partner_id", "x_user_id", "x_partner_id"],
1492                      self._columns, 'color')
1493
1494         if not set_first_of(["date_stop", "date_end", "x_date_stop", "x_date_end"],
1495                             self._columns, 'date_stop'):
1496             if not set_first_of(["date_delay", "planned_hours", "x_date_delay", "x_planned_hours"],
1497                                 self._columns, 'date_delay'):
1498                 raise except_orm(
1499                     _('Invalid Object Architecture!'),
1500                     _("Insufficient fields to generate a Calendar View for %s, missing a date_stop or a date_delay" % self._name))
1501
1502         return view
1503
1504     def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
1505         """ fields_view_get([view_id | view_type='form'])
1506
1507         Get the detailed composition of the requested view like fields, model, view architecture
1508
1509         :param view_id: id of the view or None
1510         :param view_type: type of the view to return if view_id is None ('form', tree', ...)
1511         :param toolbar: true to include contextual actions
1512         :param submenu: deprecated
1513         :return: dictionary describing the composition of the requested view (including inherited views and extensions)
1514         :raise AttributeError:
1515                             * if the inherited view has unknown position to work with other than 'before', 'after', 'inside', 'replace'
1516                             * if some tag other than 'position' is found in parent view
1517         :raise Invalid ArchitectureError: if there is view type other than form, tree, calendar, search etc defined on the structure
1518         """
1519         if context is None:
1520             context = {}
1521         View = self.pool['ir.ui.view']
1522
1523         result = {
1524             'model': self._name,
1525             'field_parent': False,
1526         }
1527
1528         # try to find a view_id if none provided
1529         if not view_id:
1530             # <view_type>_view_ref in context can be used to overrride the default view
1531             view_ref_key = view_type + '_view_ref'
1532             view_ref = context.get(view_ref_key)
1533             if view_ref:
1534                 if '.' in view_ref:
1535                     module, view_ref = view_ref.split('.', 1)
1536                     cr.execute("SELECT res_id FROM ir_model_data WHERE model='ir.ui.view' AND module=%s AND name=%s", (module, view_ref))
1537                     view_ref_res = cr.fetchone()
1538                     if view_ref_res:
1539                         view_id = view_ref_res[0]
1540                 else:
1541                     _logger.warning('%r requires a fully-qualified external id (got: %r for model %s). '
1542                         'Please use the complete `module.view_id` form instead.', view_ref_key, view_ref,
1543                         self._name)
1544
1545             if not view_id:
1546                 # otherwise try to find the lowest priority matching ir.ui.view
1547                 view_id = View.default_view(cr, uid, self._name, view_type, context=context)
1548
1549         # context for post-processing might be overriden
1550         ctx = context
1551         if view_id:
1552             # read the view with inherited views applied
1553             root_view = View.read_combined(cr, uid, view_id, fields=['id', 'name', 'field_parent', 'type', 'model', 'arch'], context=context)
1554             result['arch'] = root_view['arch']
1555             result['name'] = root_view['name']
1556             result['type'] = root_view['type']
1557             result['view_id'] = root_view['id']
1558             result['field_parent'] = root_view['field_parent']
1559             # override context fro postprocessing
1560             if root_view.get('model') != self._name:
1561                 ctx = dict(context, base_model_name=root_view.get('model'))
1562         else:
1563             # fallback on default views methods if no ir.ui.view could be found
1564             try:
1565                 get_func = getattr(self, '_get_default_%s_view' % view_type)
1566                 arch_etree = get_func(cr, uid, context)
1567                 result['arch'] = etree.tostring(arch_etree, encoding='utf-8')
1568                 result['type'] = view_type
1569                 result['name'] = 'default'
1570             except AttributeError:
1571                 raise except_orm(_('Invalid Architecture!'), _("No default view of type '%s' could be found !") % view_type)
1572
1573         # Apply post processing, groups and modifiers etc...
1574         xarch, xfields = View.postprocess_and_fields(cr, uid, self._name, etree.fromstring(result['arch']), view_id, context=ctx)
1575         result['arch'] = xarch
1576         result['fields'] = xfields
1577
1578         # Add related action information if aksed
1579         if toolbar:
1580             toclean = ('report_sxw_content', 'report_rml_content', 'report_sxw', 'report_rml', 'report_sxw_content_data', 'report_rml_content_data')
1581             def clean(x):
1582                 x = x[2]
1583                 for key in toclean:
1584                     x.pop(key, None)
1585                 return x
1586             ir_values_obj = self.pool.get('ir.values')
1587             resprint = ir_values_obj.get(cr, uid, 'action', 'client_print_multi', [(self._name, False)], False, context)
1588             resaction = ir_values_obj.get(cr, uid, 'action', 'client_action_multi', [(self._name, False)], False, context)
1589             resrelate = ir_values_obj.get(cr, uid, 'action', 'client_action_relate', [(self._name, False)], False, context)
1590             resaction = [clean(action) for action in resaction if view_type == 'tree' or not action[2].get('multi')]
1591             resprint = [clean(print_) for print_ in resprint if view_type == 'tree' or not print_[2].get('multi')]
1592             #When multi="True" set it will display only in More of the list view
1593             resrelate = [clean(action) for action in resrelate
1594                          if (action[2].get('multi') and view_type == 'tree') or (not action[2].get('multi') and view_type == 'form')]
1595
1596             for x in itertools.chain(resprint, resaction, resrelate):
1597                 x['string'] = x['name']
1598
1599             result['toolbar'] = {
1600                 'print': resprint,
1601                 'action': resaction,
1602                 'relate': resrelate
1603             }
1604         return result
1605
1606     def get_formview_id(self, cr, uid, id, context=None):
1607         """ Return an view id to open the document with. This method is meant to be
1608             overridden in addons that want to give specific view ids for example.
1609
1610             :param int id: id of the document to open
1611         """
1612         return False
1613
1614     def get_formview_action(self, cr, uid, id, context=None):
1615         """ Return an action to open the document. This method is meant to be
1616             overridden in addons that want to give specific view ids for example.
1617
1618             :param int id: id of the document to open
1619         """
1620         view_id = self.get_formview_id(cr, uid, id, context=context)
1621         return {
1622             'type': 'ir.actions.act_window',
1623             'res_model': self._name,
1624             'view_type': 'form',
1625             'view_mode': 'form',
1626             'views': [(view_id, 'form')],
1627             'target': 'current',
1628             'res_id': id,
1629         }
1630
1631     def get_access_action(self, cr, uid, id, context=None):
1632         """ Return an action to open the document. This method is meant to be
1633         overridden in addons that want to give specific access to the document.
1634         By default it opens the formview of the document.
1635
1636         :paramt int id: id of the document to open
1637         """
1638         return self.get_formview_action(cr, uid, id, context=context)
1639
1640     def _view_look_dom_arch(self, cr, uid, node, view_id, context=None):
1641         return self.pool['ir.ui.view'].postprocess_and_fields(
1642             cr, uid, self._name, node, view_id, context=context)
1643
1644     def search_count(self, cr, user, args, context=None):
1645         """ search_count(args) -> int
1646
1647         Returns the number of records in the current model matching :ref:`the
1648         provided domain <reference/orm/domains>`.
1649         """
1650         res = self.search(cr, user, args, context=context, count=True)
1651         if isinstance(res, list):
1652             return len(res)
1653         return res
1654
1655     @api.returns('self')
1656     def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
1657         """ search(args[, offset=0][, limit=None][, order=None][, count=False])
1658
1659         Searches for records based on the ``args``
1660         :ref:`search domain <reference/orm/domains>`.
1661
1662         :param args: :ref:`A search domain <reference/orm/domains>`. Use an empty
1663                      list to match all records.
1664         :param int offset: number of results to ignore (default: none)
1665         :param int limit: maximum number of records to return (default: all)
1666         :param str order: sort string
1667         :param bool count: if ``True``, the call should return the number of
1668                            records matching ``args`` rather than the records
1669                            themselves.
1670         :returns: at most ``limit`` records matching the search criteria
1671
1672         :raise AccessError: * if user tries to bypass access rules for read on the requested object.
1673         """
1674         return self._search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count)
1675
1676     #
1677     # display_name, name_get, name_create, name_search
1678     #
1679
1680     @api.depends(lambda self: (self._rec_name,) if self._rec_name else ())
1681     def _compute_display_name(self):
1682         names = dict(self.name_get())
1683         for record in self:
1684             record.display_name = names.get(record.id, False)
1685
1686     @api.multi
1687     def name_get(self):
1688         """ name_get() -> [(id, name), ...]
1689
1690         Returns a textual representation for the records in ``self``.
1691         By default this is the value of the ``display_name`` field.
1692
1693         :return: list of pairs ``(id, text_repr)`` for each records
1694         :rtype: list(tuple)
1695         """
1696         result = []
1697         name = self._rec_name
1698         if name in self._fields:
1699             convert = self._fields[name].convert_to_display_name
1700             for record in self:
1701                 result.append((record.id, convert(record[name])))
1702         else:
1703             for record in self:
1704                 result.append((record.id, "%s,%s" % (record._name, record.id)))
1705
1706         return result
1707
1708     @api.model
1709     def name_create(self, name):
1710         """ name_create(name) -> record
1711
1712         Create a new record by calling :meth:`~.create` with only one value
1713         provided: the display name of the new record.
1714
1715         The new record will be initialized with any default values
1716         applicable to this model, or provided through the context. The usual
1717         behavior of :meth:`~.create` applies.
1718
1719         :param name: display name of the record to create
1720         :rtype: tuple
1721         :return: the :meth:`~.name_get` pair value of the created record
1722         """
1723         if self._rec_name:
1724             record = self.create({self._rec_name: name})
1725             return record.name_get()[0]
1726         else:
1727             _logger.warning("Cannot execute name_create, no _rec_name defined on %s", self._name)
1728             return False
1729
1730     @api.model
1731     def name_search(self, name='', args=None, operator='ilike', limit=100):
1732         """ name_search(name='', args=None, operator='ilike', limit=100) -> records
1733
1734         Search for records that have a display name matching the given
1735         `name` pattern when compared with the given `operator`, while also
1736         matching the optional search domain (`args`).
1737
1738         This is used for example to provide suggestions based on a partial
1739         value for a relational field. Sometimes be seen as the inverse
1740         function of :meth:`~.name_get`, but it is not guaranteed to be.
1741
1742         This method is equivalent to calling :meth:`~.search` with a search
1743         domain based on ``display_name`` and then :meth:`~.name_get` on the
1744         result of the search.
1745
1746         :param str name: the name pattern to match
1747         :param list args: optional search domain (see :meth:`~.search` for
1748                           syntax), specifying further restrictions
1749         :param str operator: domain operator for matching `name`, such as
1750                              ``'like'`` or ``'='``.
1751         :param int limit: optional max number of records to return
1752         :rtype: list
1753         :return: list of pairs ``(id, text_repr)`` for all matching records.
1754         """
1755         return self._name_search(name, args, operator, limit=limit)
1756
1757     def _name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100, name_get_uid=None):
1758         # private implementation of name_search, allows passing a dedicated user
1759         # for the name_get part to solve some access rights issues
1760         args = list(args or [])
1761         # optimize out the default criterion of ``ilike ''`` that matches everything
1762         if not self._rec_name:
1763             _logger.warning("Cannot execute name_search, no _rec_name defined on %s", self._name)
1764         elif not (name == '' and operator == 'ilike'):
1765             args += [(self._rec_name, operator, name)]
1766         access_rights_uid = name_get_uid or user
1767         ids = self._search(cr, user, args, limit=limit, context=context, access_rights_uid=access_rights_uid)
1768         res = self.name_get(cr, access_rights_uid, ids, context)
1769         return res
1770
1771     def read_string(self, cr, uid, id, langs, fields=None, context=None):
1772         res = {}
1773         res2 = {}
1774         self.pool.get('ir.translation').check_access_rights(cr, uid, 'read')
1775         if not fields:
1776             fields = self._columns.keys() + self._inherit_fields.keys()
1777         #FIXME: collect all calls to _get_source into one SQL call.
1778         for lang in langs:
1779             res[lang] = {'code': lang}
1780             for f in fields:
1781                 if f in self._columns:
1782                     res_trans = self.pool.get('ir.translation')._get_source(cr, uid, self._name+','+f, 'field', lang)
1783                     if res_trans:
1784                         res[lang][f] = res_trans
1785                     else:
1786                         res[lang][f] = self._columns[f].string
1787         for table in self._inherits:
1788             cols = intersect(self._inherit_fields.keys(), fields)
1789             res2 = self.pool[table].read_string(cr, uid, id, langs, cols, context)
1790         for lang in res2:
1791             if lang in res:
1792                 res[lang]['code'] = lang
1793             for f in res2[lang]:
1794                 res[lang][f] = res2[lang][f]
1795         return res
1796
1797     def write_string(self, cr, uid, id, langs, vals, context=None):
1798         self.pool.get('ir.translation').check_access_rights(cr, uid, 'write')
1799         #FIXME: try to only call the translation in one SQL
1800         for lang in langs:
1801             for field in vals:
1802                 if field in self._columns:
1803                     src = self._columns[field].string
1804                     self.pool.get('ir.translation')._set_ids(cr, uid, self._name+','+field, 'field', lang, [0], vals[field], src)
1805         for table in self._inherits:
1806             cols = intersect(self._inherit_fields.keys(), vals)
1807             if cols:
1808                 self.pool[table].write_string(cr, uid, id, langs, vals, context)
1809         return True
1810
1811     def _add_missing_default_values(self, cr, uid, values, context=None):
1812         # avoid overriding inherited values when parent is set
1813         avoid_tables = []
1814         for tables, parent_field in self._inherits.items():
1815             if parent_field in values:
1816                 avoid_tables.append(tables)
1817
1818         # compute missing fields
1819         missing_defaults = set()
1820         for field in self._columns.keys():
1821             if not field in values:
1822                 missing_defaults.add(field)
1823         for field in self._inherit_fields.keys():
1824             if (field not in values) and (self._inherit_fields[field][0] not in avoid_tables):
1825                 missing_defaults.add(field)
1826         # discard magic fields
1827         missing_defaults -= set(MAGIC_COLUMNS)
1828
1829         if missing_defaults:
1830             # override defaults with the provided values, never allow the other way around
1831             defaults = self.default_get(cr, uid, list(missing_defaults), context)
1832             for dv in defaults:
1833                 if ((dv in self._columns and self._columns[dv]._type == 'many2many') \
1834                      or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'many2many')) \
1835                         and defaults[dv] and isinstance(defaults[dv][0], (int, long)):
1836                     defaults[dv] = [(6, 0, defaults[dv])]
1837                 if (dv in self._columns and self._columns[dv]._type == 'one2many' \
1838                     or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'one2many')) \
1839                         and isinstance(defaults[dv], (list, tuple)) and defaults[dv] and isinstance(defaults[dv][0], dict):
1840                     defaults[dv] = [(0, 0, x) for x in defaults[dv]]
1841             defaults.update(values)
1842             values = defaults
1843         return values
1844
1845     def clear_caches(self):
1846         """ Clear the caches
1847
1848         This clears the caches associated to methods decorated with
1849         ``tools.ormcache`` or ``tools.ormcache_multi``.
1850         """
1851         try:
1852             self._ormcache.clear()
1853             self.pool._any_cache_cleared = True
1854         except AttributeError:
1855             pass
1856
1857
1858     def _read_group_fill_results(self, cr, uid, domain, groupby, remaining_groupbys,
1859                                  aggregated_fields, count_field,
1860                                  read_group_result, read_group_order=None, context=None):
1861         """Helper method for filling in empty groups for all possible values of
1862            the field being grouped by"""
1863
1864         # self._group_by_full should map groupable fields to a method that returns
1865         # a list of all aggregated values that we want to display for this field,
1866         # in the form of a m2o-like pair (key,label).
1867         # This is useful to implement kanban views for instance, where all columns
1868         # should be displayed even if they don't contain any record.
1869
1870         # Grab the list of all groups that should be displayed, including all present groups
1871         present_group_ids = [x[groupby][0] for x in read_group_result if x[groupby]]
1872         all_groups,folded = self._group_by_full[groupby](self, cr, uid, present_group_ids, domain,
1873                                                   read_group_order=read_group_order,
1874                                                   access_rights_uid=openerp.SUPERUSER_ID,
1875                                                   context=context)
1876
1877         result_template = dict.fromkeys(aggregated_fields, False)
1878         result_template[groupby + '_count'] = 0
1879         if remaining_groupbys:
1880             result_template['__context'] = {'group_by': remaining_groupbys}
1881
1882         # Merge the left_side (current results as dicts) with the right_side (all
1883         # possible values as m2o pairs). Both lists are supposed to be using the
1884         # same ordering, and can be merged in one pass.
1885         result = []
1886         known_values = {}
1887         def append_left(left_side):
1888             grouped_value = left_side[groupby] and left_side[groupby][0]
1889             if not grouped_value in known_values:
1890                 result.append(left_side)
1891                 known_values[grouped_value] = left_side
1892             else:
1893                 known_values[grouped_value].update({count_field: left_side[count_field]})
1894         def append_right(right_side):
1895             grouped_value = right_side[0]
1896             if not grouped_value in known_values:
1897                 line = dict(result_template)
1898                 line[groupby] = right_side
1899                 line['__domain'] = [(groupby,'=',grouped_value)] + domain
1900                 result.append(line)
1901                 known_values[grouped_value] = line
1902         while read_group_result or all_groups:
1903             left_side = read_group_result[0] if read_group_result else None
1904             right_side = all_groups[0] if all_groups else None
1905             assert left_side is None or left_side[groupby] is False \
1906                  or isinstance(left_side[groupby], (tuple,list)), \
1907                 'M2O-like pair expected, got %r' % left_side[groupby]
1908             assert right_side is None or isinstance(right_side, (tuple,list)), \
1909                 'M2O-like pair expected, got %r' % right_side
1910             if left_side is None:
1911                 append_right(all_groups.pop(0))
1912             elif right_side is None:
1913                 append_left(read_group_result.pop(0))
1914             elif left_side[groupby] == right_side:
1915                 append_left(read_group_result.pop(0))
1916                 all_groups.pop(0) # discard right_side
1917             elif not left_side[groupby] or not left_side[groupby][0]:
1918                 # left side == "Undefined" entry, not present on right_side
1919                 append_left(read_group_result.pop(0))
1920             else:
1921                 append_right(all_groups.pop(0))
1922
1923         if folded:
1924             for r in result:
1925                 r['__fold'] = folded.get(r[groupby] and r[groupby][0], False)
1926         return result
1927
1928     def _read_group_prepare(self, orderby, aggregated_fields, annotated_groupbys, query):
1929         """
1930         Prepares the GROUP BY and ORDER BY terms for the read_group method. Adds the missing JOIN clause
1931         to the query if order should be computed against m2o field. 
1932         :param orderby: the orderby definition in the form "%(field)s %(order)s"
1933         :param aggregated_fields: list of aggregated fields in the query
1934         :param annotated_groupbys: list of dictionaries returned by _read_group_process_groupby
1935                 These dictionaries contains the qualified name of each groupby
1936                 (fully qualified SQL name for the corresponding field),
1937                 and the (non raw) field name.
1938         :param osv.Query query: the query under construction
1939         :return: (groupby_terms, orderby_terms)
1940         """
1941         orderby_terms = []
1942         groupby_terms = [gb['qualified_field'] for gb in annotated_groupbys]
1943         groupby_fields = [gb['groupby'] for gb in annotated_groupbys]
1944         if not orderby:
1945             return groupby_terms, orderby_terms
1946
1947         self._check_qorder(orderby)
1948         for order_part in orderby.split(','):
1949             order_split = order_part.split()
1950             order_field = order_split[0]
1951             if order_field in groupby_fields:
1952
1953                 if self._all_columns[order_field.split(':')[0]].column._type == 'many2one':
1954                     order_clause = self._generate_order_by(order_part, query).replace('ORDER BY ', '')
1955                     if order_clause:
1956                         orderby_terms.append(order_clause)
1957                         groupby_terms += [order_term.split()[0] for order_term in order_clause.split(',')]
1958                 else:
1959                     order = '"%s" %s' % (order_field, '' if len(order_split) == 1 else order_split[1])
1960                     orderby_terms.append(order)
1961             elif order_field in aggregated_fields:
1962                 orderby_terms.append(order_part)
1963             else:
1964                 # Cannot order by a field that will not appear in the results (needs to be grouped or aggregated)
1965                 _logger.warn('%s: read_group order by `%s` ignored, cannot sort on empty columns (not grouped/aggregated)',
1966                              self._name, order_part)
1967         return groupby_terms, orderby_terms
1968
1969     def _read_group_process_groupby(self, gb, query, context):
1970         """
1971             Helper method to collect important information about groupbys: raw
1972             field name, type, time informations, qualified name, ...
1973         """
1974         split = gb.split(':')
1975         field_type = self._all_columns[split[0]].column._type
1976         gb_function = split[1] if len(split) == 2 else None
1977         temporal = field_type in ('date', 'datetime')
1978         tz_convert = field_type == 'datetime' and context.get('tz') in pytz.all_timezones
1979         qualified_field = self._inherits_join_calc(split[0], query)
1980         if temporal:
1981             display_formats = {
1982                 # Careful with week/year formats:
1983                 #  - yyyy (lower) must always be used, *except* for week+year formats
1984                 #  - YYYY (upper) must always be used for week+year format
1985                 #         e.g. 2006-01-01 is W52 2005 in some locales (de_DE),
1986                 #                         and W1 2006 for others
1987                 #
1988                 # Mixing both formats, e.g. 'MMM YYYY' would yield wrong results,
1989                 # such as 2006-01-01 being formatted as "January 2005" in some locales.
1990                 # Cfr: http://babel.pocoo.org/docs/dates/#date-fields
1991                 'day': 'dd MMM yyyy', # yyyy = normal year
1992                 'week': "'W'w YYYY",  # w YYYY = ISO week-year
1993                 'month': 'MMMM yyyy',
1994                 'quarter': 'QQQ yyyy',
1995                 'year': 'yyyy',
1996             }
1997             time_intervals = {
1998                 'day': dateutil.relativedelta.relativedelta(days=1),
1999                 'week': datetime.timedelta(days=7),
2000                 'month': dateutil.relativedelta.relativedelta(months=1),
2001                 'quarter': dateutil.relativedelta.relativedelta(months=3),
2002                 'year': dateutil.relativedelta.relativedelta(years=1)
2003             }
2004             if tz_convert:
2005                 qualified_field = "timezone('%s', timezone('UTC',%s))" % (context.get('tz', 'UTC'), qualified_field)
2006             qualified_field = "date_trunc('%s', %s)" % (gb_function or 'month', qualified_field)
2007         if field_type == 'boolean':
2008             qualified_field = "coalesce(%s,false)" % qualified_field
2009         return {
2010             'field': split[0],
2011             'groupby': gb,
2012             'type': field_type, 
2013             'display_format': display_formats[gb_function or 'month'] if temporal else None,
2014             'interval': time_intervals[gb_function or 'month'] if temporal else None,                
2015             'tz_convert': tz_convert,
2016             'qualified_field': qualified_field
2017         }
2018
2019     def _read_group_prepare_data(self, key, value, groupby_dict, context):
2020         """
2021             Helper method to sanitize the data received by read_group. The None
2022             values are converted to False, and the date/datetime are formatted,
2023             and corrected according to the timezones.
2024         """
2025         value = False if value is None else value
2026         gb = groupby_dict.get(key)
2027         if gb and gb['type'] in ('date', 'datetime') and value:
2028             if isinstance(value, basestring):
2029                 dt_format = DEFAULT_SERVER_DATETIME_FORMAT if gb['type'] == 'datetime' else DEFAULT_SERVER_DATE_FORMAT
2030                 value = datetime.datetime.strptime(value, dt_format)
2031             if gb['tz_convert']:
2032                 value =  pytz.timezone(context['tz']).localize(value)
2033         return value
2034
2035     def _read_group_get_domain(self, groupby, value):
2036         """
2037             Helper method to construct the domain corresponding to a groupby and 
2038             a given value. This is mostly relevant for date/datetime.
2039         """
2040         if groupby['type'] in ('date', 'datetime') and value:
2041             dt_format = DEFAULT_SERVER_DATETIME_FORMAT if groupby['type'] == 'datetime' else DEFAULT_SERVER_DATE_FORMAT
2042             domain_dt_begin = value
2043             domain_dt_end = value + groupby['interval']
2044             if groupby['tz_convert']:
2045                 domain_dt_begin = domain_dt_begin.astimezone(pytz.utc)
2046                 domain_dt_end = domain_dt_end.astimezone(pytz.utc)
2047             return [(groupby['field'], '>=', domain_dt_begin.strftime(dt_format)),
2048                    (groupby['field'], '<', domain_dt_end.strftime(dt_format))]
2049         if groupby['type'] == 'many2one' and value:
2050                 value = value[0]
2051         return [(groupby['field'], '=', value)]
2052
2053     def _read_group_format_result(self, data, annotated_groupbys, groupby, groupby_dict, domain, context):
2054         """
2055             Helper method to format the data contained in the dictianary data by 
2056             adding the domain corresponding to its values, the groupbys in the 
2057             context and by properly formatting the date/datetime values. 
2058         """
2059         domain_group = [dom for gb in annotated_groupbys for dom in self._read_group_get_domain(gb, data[gb['groupby']])]
2060         for k,v in data.iteritems():
2061             gb = groupby_dict.get(k)
2062             if gb and gb['type'] in ('date', 'datetime') and v:
2063                 data[k] = babel.dates.format_date(v, format=gb['display_format'], locale=context.get('lang', 'en_US'))
2064
2065         data['__domain'] = domain_group + domain 
2066         if len(groupby) - len(annotated_groupbys) >= 1:
2067             data['__context'] = { 'group_by': groupby[len(annotated_groupbys):]}
2068         del data['id']
2069         return data
2070
2071     def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False, lazy=True):
2072         """
2073         Get the list of records in list view grouped by the given ``groupby`` fields
2074
2075         :param cr: database cursor
2076         :param uid: current user id
2077         :param domain: list specifying search criteria [['field_name', 'operator', 'value'], ...]
2078         :param list fields: list of fields present in the list view specified on the object
2079         :param list groupby: list of groupby descriptions by which the records will be grouped.  
2080                 A groupby description is either a field (then it will be grouped by that field)
2081                 or a string 'field:groupby_function'.  Right now, the only functions supported
2082                 are 'day', 'week', 'month', 'quarter' or 'year', and they only make sense for 
2083                 date/datetime fields.
2084         :param int offset: optional number of records to skip
2085         :param int limit: optional max number of records to return
2086         :param dict context: context arguments, like lang, time zone. 
2087         :param list orderby: optional ``order by`` specification, for
2088                              overriding the natural sort ordering of the
2089                              groups, see also :py:meth:`~osv.osv.osv.search`
2090                              (supported only for many2one fields currently)
2091         :param bool lazy: if true, the results are only grouped by the first groupby and the 
2092                 remaining groupbys are put in the __context key.  If false, all the groupbys are
2093                 done in one call.
2094         :return: list of dictionaries(one dictionary for each record) containing:
2095
2096                     * the values of fields grouped by the fields in ``groupby`` argument
2097                     * __domain: list of tuples specifying the search criteria
2098                     * __context: dictionary with argument like ``groupby``
2099         :rtype: [{'field_name_1': value, ...]
2100         :raise AccessError: * if user has no read rights on the requested object
2101                             * if user tries to bypass access rules for read on the requested object
2102         """
2103         if context is None:
2104             context = {}
2105         self.check_access_rights(cr, uid, 'read')
2106         query = self._where_calc(cr, uid, domain, context=context) 
2107         fields = fields or self._columns.keys()
2108
2109         groupby = [groupby] if isinstance(groupby, basestring) else groupby
2110         groupby_list = groupby[:1] if lazy else groupby
2111         annotated_groupbys = [self._read_group_process_groupby(gb, query, context) 
2112                                     for gb in groupby_list]
2113         groupby_fields = [g['field'] for g in annotated_groupbys]
2114         order = orderby or ','.join([g for g in groupby_list])
2115         groupby_dict = {gb['groupby']: gb for gb in annotated_groupbys}
2116
2117         self._apply_ir_rules(cr, uid, query, 'read', context=context)
2118         for gb in groupby_fields:
2119             assert gb in fields, "Fields in 'groupby' must appear in the list of fields to read (perhaps it's missing in the list view?)"
2120             groupby_def = self._columns.get(gb) or (self._inherit_fields.get(gb) and self._inherit_fields.get(gb)[2])
2121             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"
2122             if not (gb in self._all_columns):
2123                 # Don't allow arbitrary values, as this would be a SQL injection vector!
2124                 raise except_orm(_('Invalid group_by'),
2125                                  _('Invalid group_by specification: "%s".\nA group_by specification must be a list of valid fields.')%(gb,))
2126
2127         aggregated_fields = [
2128             f for f in fields
2129             if f not in ('id', 'sequence')
2130             if f not in groupby_fields
2131             if f in self._all_columns
2132             if self._all_columns[f].column._type in ('integer', 'float')
2133             if getattr(self._all_columns[f].column, '_classic_write')]
2134
2135         field_formatter = lambda f: (self._all_columns[f].column.group_operator or 'sum', self._inherits_join_calc(f, query), f)
2136         select_terms = ["%s(%s) AS %s" % field_formatter(f) for f in aggregated_fields]
2137
2138         for gb in annotated_groupbys:
2139             select_terms.append('%s as "%s" ' % (gb['qualified_field'], gb['groupby']))
2140
2141         groupby_terms, orderby_terms = self._read_group_prepare(order, aggregated_fields, annotated_groupbys, query)
2142         from_clause, where_clause, where_clause_params = query.get_sql()
2143         if lazy and (len(groupby_fields) >= 2 or not context.get('group_by_no_leaf')):
2144             count_field = groupby_fields[0] if len(groupby_fields) >= 1 else '_'
2145         else:
2146             count_field = '_'
2147         count_field += '_count'
2148
2149         prefix_terms = lambda prefix, terms: (prefix + " " + ",".join(terms)) if terms else ''
2150         prefix_term = lambda prefix, term: ('%s %s' % (prefix, term)) if term else ''
2151
2152         query = """
2153             SELECT min(%(table)s.id) AS id, count(%(table)s.id) AS %(count_field)s %(extra_fields)s
2154             FROM %(from)s
2155             %(where)s
2156             %(groupby)s
2157             %(orderby)s
2158             %(limit)s
2159             %(offset)s
2160         """ % {
2161             'table': self._table,
2162             'count_field': count_field,
2163             'extra_fields': prefix_terms(',', select_terms),
2164             'from': from_clause,
2165             'where': prefix_term('WHERE', where_clause),
2166             'groupby': prefix_terms('GROUP BY', groupby_terms),
2167             'orderby': prefix_terms('ORDER BY', orderby_terms),
2168             'limit': prefix_term('LIMIT', int(limit) if limit else None),
2169             'offset': prefix_term('OFFSET', int(offset) if limit else None),
2170         }
2171         cr.execute(query, where_clause_params)
2172         fetched_data = cr.dictfetchall()
2173
2174         if not groupby_fields:
2175             return fetched_data
2176
2177         many2onefields = [gb['field'] for gb in annotated_groupbys if gb['type'] == 'many2one']
2178         if many2onefields:
2179             data_ids = [r['id'] for r in fetched_data]
2180             many2onefields = list(set(many2onefields))
2181             data_dict = {d['id']: d for d in self.read(cr, uid, data_ids, many2onefields, context=context)} 
2182             for d in fetched_data:
2183                 d.update(data_dict[d['id']])
2184
2185         data = map(lambda r: {k: self._read_group_prepare_data(k,v, groupby_dict, context) for k,v in r.iteritems()}, fetched_data)
2186         result = [self._read_group_format_result(d, annotated_groupbys, groupby, groupby_dict, domain, context) for d in data]
2187         if lazy and groupby_fields[0] in self._group_by_full:
2188             # Right now, read_group only fill results in lazy mode (by default).
2189             # If you need to have the empty groups in 'eager' mode, then the
2190             # method _read_group_fill_results need to be completely reimplemented
2191             # in a sane way 
2192             result = self._read_group_fill_results(cr, uid, domain, groupby_fields[0], groupby[len(annotated_groupbys):],
2193                                                        aggregated_fields, count_field, result, read_group_order=order,
2194                                                        context=context)
2195         return result
2196
2197     def _inherits_join_add(self, current_model, parent_model_name, query):
2198         """
2199         Add missing table SELECT and JOIN clause to ``query`` for reaching the parent table (no duplicates)
2200         :param current_model: current model object
2201         :param parent_model_name: name of the parent model for which the clauses should be added
2202         :param query: query object on which the JOIN should be added
2203         """
2204         inherits_field = current_model._inherits[parent_model_name]
2205         parent_model = self.pool[parent_model_name]
2206         parent_alias, parent_alias_statement = query.add_join((current_model._table, parent_model._table, inherits_field, 'id', inherits_field), implicit=True)
2207         return parent_alias
2208
2209     def _inherits_join_calc(self, field, query):
2210         """
2211         Adds missing table select and join clause(s) to ``query`` for reaching
2212         the field coming from an '_inherits' parent table (no duplicates).
2213
2214         :param field: name of inherited field to reach
2215         :param query: query object on which the JOIN should be added
2216         :return: qualified name of field, to be used in SELECT clause
2217         """
2218         current_table = self
2219         parent_alias = '"%s"' % current_table._table
2220         while field in current_table._inherit_fields and not field in current_table._columns:
2221             parent_model_name = current_table._inherit_fields[field][0]
2222             parent_table = self.pool[parent_model_name]
2223             parent_alias = self._inherits_join_add(current_table, parent_model_name, query)
2224             current_table = parent_table
2225         return '%s."%s"' % (parent_alias, field)
2226
2227     def _parent_store_compute(self, cr):
2228         if not self._parent_store:
2229             return
2230         _logger.info('Computing parent left and right for table %s...', self._table)
2231         def browse_rec(root, pos=0):
2232             # TODO: set order
2233             where = self._parent_name+'='+str(root)
2234             if not root:
2235                 where = self._parent_name+' IS NULL'
2236             if self._parent_order:
2237                 where += ' order by '+self._parent_order
2238             cr.execute('SELECT id FROM '+self._table+' WHERE '+where)
2239             pos2 = pos + 1
2240             for id in cr.fetchall():
2241                 pos2 = browse_rec(id[0], pos2)
2242             cr.execute('update '+self._table+' set parent_left=%s, parent_right=%s where id=%s', (pos, pos2, root))
2243             return pos2 + 1
2244         query = 'SELECT id FROM '+self._table+' WHERE '+self._parent_name+' IS NULL'
2245         if self._parent_order:
2246             query += ' order by ' + self._parent_order
2247         pos = 0
2248         cr.execute(query)
2249         for (root,) in cr.fetchall():
2250             pos = browse_rec(root, pos)
2251         self.invalidate_cache(cr, SUPERUSER_ID, ['parent_left', 'parent_right'])
2252         return True
2253
2254     def _update_store(self, cr, f, k):
2255         _logger.info("storing computed values of fields.function '%s'", k)
2256         ss = self._columns[k]._symbol_set
2257         update_query = 'UPDATE "%s" SET "%s"=%s WHERE id=%%s' % (self._table, k, ss[0])
2258         cr.execute('select id from '+self._table)
2259         ids_lst = map(lambda x: x[0], cr.fetchall())
2260         while ids_lst:
2261             iids = ids_lst[:AUTOINIT_RECALCULATE_STORED_FIELDS]
2262             ids_lst = ids_lst[AUTOINIT_RECALCULATE_STORED_FIELDS:]
2263             res = f.get(cr, self, iids, k, SUPERUSER_ID, {})
2264             for key, val in res.items():
2265                 if f._multi:
2266                     val = val[k]
2267                 # if val is a many2one, just write the ID
2268                 if type(val) == tuple:
2269                     val = val[0]
2270                 if val is not False:
2271                     cr.execute(update_query, (ss[1](val), key))
2272
2273     @api.model
2274     def _check_selection_field_value(self, field, value):
2275         """ Check whether value is among the valid values for the given
2276             selection/reference field, and raise an exception if not.
2277         """
2278         field = self._fields[field]
2279         field.convert_to_cache(value, self)
2280
2281     def _check_removed_columns(self, cr, log=False):
2282         # iterate on the database columns to drop the NOT NULL constraints
2283         # of fields which were required but have been removed (or will be added by another module)
2284         columns = [c for c in self._columns if not (isinstance(self._columns[c], fields.function) and not self._columns[c].store)]
2285         columns += MAGIC_COLUMNS
2286         cr.execute("SELECT a.attname, a.attnotnull"
2287                    "  FROM pg_class c, pg_attribute a"
2288                    " WHERE c.relname=%s"
2289                    "   AND c.oid=a.attrelid"
2290                    "   AND a.attisdropped=%s"
2291                    "   AND pg_catalog.format_type(a.atttypid, a.atttypmod) NOT IN ('cid', 'tid', 'oid', 'xid')"
2292                    "   AND a.attname NOT IN %s", (self._table, False, tuple(columns))),
2293
2294         for column in cr.dictfetchall():
2295             if log:
2296                 _logger.debug("column %s is in the table %s but not in the corresponding object %s",
2297                               column['attname'], self._table, self._name)
2298             if column['attnotnull']:
2299                 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, column['attname']))
2300                 _schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
2301                               self._table, column['attname'])
2302
2303     def _save_constraint(self, cr, constraint_name, type, definition):
2304         """
2305         Record the creation of a constraint for this model, to make it possible
2306         to delete it later when the module is uninstalled. Type can be either
2307         'f' or 'u' depending on the constraint being a foreign key or not.
2308         """
2309         if not self._module:
2310             # no need to save constraints for custom models as they're not part
2311             # of any module
2312             return
2313         assert type in ('f', 'u')
2314         cr.execute("""
2315             SELECT type, definition FROM ir_model_constraint, ir_module_module
2316             WHERE ir_model_constraint.module=ir_module_module.id
2317                 AND ir_model_constraint.name=%s
2318                 AND ir_module_module.name=%s
2319             """, (constraint_name, self._module))
2320         constraints = cr.dictfetchone()
2321         if not constraints:
2322             cr.execute("""
2323                 INSERT INTO ir_model_constraint
2324                     (name, date_init, date_update, module, model, type, definition)
2325                 VALUES (%s, now() AT TIME ZONE 'UTC', now() AT TIME ZONE 'UTC',
2326                     (SELECT id FROM ir_module_module WHERE name=%s),
2327                     (SELECT id FROM ir_model WHERE model=%s), %s, %s)""",
2328                     (constraint_name, self._module, self._name, type, definition))
2329         elif constraints['type'] != type or (definition and constraints['definition'] != definition):
2330             cr.execute("""
2331                 UPDATE ir_model_constraint
2332                 SET date_update=now() AT TIME ZONE 'UTC', type=%s, definition=%s
2333                 WHERE name=%s AND module = (SELECT id FROM ir_module_module WHERE name=%s)""",
2334                     (type, definition, constraint_name, self._module))
2335
2336     def _save_relation_table(self, cr, relation_table):
2337         """
2338         Record the creation of a many2many for this model, to make it possible
2339         to delete it later when the module is uninstalled.
2340         """
2341         cr.execute("""
2342             SELECT 1 FROM ir_model_relation, ir_module_module
2343             WHERE ir_model_relation.module=ir_module_module.id
2344                 AND ir_model_relation.name=%s
2345                 AND ir_module_module.name=%s
2346             """, (relation_table, self._module))
2347         if not cr.rowcount:
2348             cr.execute("""INSERT INTO ir_model_relation (name, date_init, date_update, module, model)
2349                                  VALUES (%s, now() AT TIME ZONE 'UTC', now() AT TIME ZONE 'UTC',
2350                     (SELECT id FROM ir_module_module WHERE name=%s),
2351                     (SELECT id FROM ir_model WHERE model=%s))""",
2352                        (relation_table, self._module, self._name))
2353             self.invalidate_cache(cr, SUPERUSER_ID)
2354
2355     # checked version: for direct m2o starting from `self`
2356     def _m2o_add_foreign_key_checked(self, source_field, dest_model, ondelete):
2357         assert self.is_transient() or not dest_model.is_transient(), \
2358             'Many2One relationships from non-transient Model to TransientModel are forbidden'
2359         if self.is_transient() and not dest_model.is_transient():
2360             # TransientModel relationships to regular Models are annoying
2361             # usually because they could block deletion due to the FKs.
2362             # So unless stated otherwise we default them to ondelete=cascade.
2363             ondelete = ondelete or 'cascade'
2364         fk_def = (self._table, source_field, dest_model._table, ondelete or 'set null')
2365         self._foreign_keys.add(fk_def)
2366         _schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s", *fk_def)
2367
2368     # unchecked version: for custom cases, such as m2m relationships
2369     def _m2o_add_foreign_key_unchecked(self, source_table, source_field, dest_model, ondelete):
2370         fk_def = (source_table, source_field, dest_model._table, ondelete or 'set null')
2371         self._foreign_keys.add(fk_def)
2372         _schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s", *fk_def)
2373
2374     def _drop_constraint(self, cr, source_table, constraint_name):
2375         cr.execute("ALTER TABLE %s DROP CONSTRAINT %s" % (source_table,constraint_name))
2376
2377     def _m2o_fix_foreign_key(self, cr, source_table, source_field, dest_model, ondelete):
2378         # Find FK constraint(s) currently established for the m2o field,
2379         # and see whether they are stale or not
2380         cr.execute("""SELECT confdeltype as ondelete_rule, conname as constraint_name,
2381                              cl2.relname as foreign_table
2382                       FROM pg_constraint as con, pg_class as cl1, pg_class as cl2,
2383                            pg_attribute as att1, pg_attribute as att2
2384                       WHERE con.conrelid = cl1.oid
2385                         AND cl1.relname = %s
2386                         AND con.confrelid = cl2.oid
2387                         AND array_lower(con.conkey, 1) = 1
2388                         AND con.conkey[1] = att1.attnum
2389                         AND att1.attrelid = cl1.oid
2390                         AND att1.attname = %s
2391                         AND array_lower(con.confkey, 1) = 1
2392                         AND con.confkey[1] = att2.attnum
2393                         AND att2.attrelid = cl2.oid
2394                         AND att2.attname = %s
2395                         AND con.contype = 'f'""", (source_table, source_field, 'id'))
2396         constraints = cr.dictfetchall()
2397         if constraints:
2398             if len(constraints) == 1:
2399                 # Is it the right constraint?
2400                 cons, = constraints
2401                 if cons['ondelete_rule'] != POSTGRES_CONFDELTYPES.get((ondelete or 'set null').upper(), 'a')\
2402                     or cons['foreign_table'] != dest_model._table:
2403                     # Wrong FK: drop it and recreate
2404                     _schema.debug("Table '%s': dropping obsolete FK constraint: '%s'",
2405                                   source_table, cons['constraint_name'])
2406                     self._drop_constraint(cr, source_table, cons['constraint_name'])
2407                 else:
2408                     # it's all good, nothing to do!
2409                     return
2410             else:
2411                 # Multiple FKs found for the same field, drop them all, and re-create
2412                 for cons in constraints:
2413                     _schema.debug("Table '%s': dropping duplicate FK constraints: '%s'",
2414                                   source_table, cons['constraint_name'])
2415                     self._drop_constraint(cr, source_table, cons['constraint_name'])
2416
2417         # (re-)create the FK
2418         self._m2o_add_foreign_key_checked(source_field, dest_model, ondelete)
2419
2420
2421     def _set_default_value_on_column(self, cr, column_name, context=None):
2422         # ideally, we should use default_get(), but it fails due to ir.values
2423         # not being ready
2424
2425         # get default value
2426         default = self._defaults.get(column_name)
2427         if callable(default):
2428             default = default(self, cr, SUPERUSER_ID, context)
2429
2430         column = self._columns[column_name]
2431         ss = column._symbol_set
2432         db_default = ss[1](default)
2433         # Write default if non-NULL, except for booleans for which False means
2434         # the same as NULL - this saves us an expensive query on large tables.
2435         write_default = (db_default is not None if column._type != 'boolean'
2436                             else db_default)
2437         if write_default:
2438             _logger.debug("Table '%s': setting default value of new column %s to %r",
2439                           self._table, column_name, default)
2440             query = 'UPDATE "%s" SET "%s"=%s WHERE "%s" is NULL' % (
2441                 self._table, column_name, ss[0], column_name)
2442             cr.execute(query, (db_default,))
2443             # this is a disgrace
2444             cr.commit()
2445
2446     def _auto_init(self, cr, context=None):
2447         """
2448
2449         Call _field_create and, unless _auto is False:
2450
2451         - create the corresponding table in database for the model,
2452         - possibly add the parent columns in database,
2453         - possibly add the columns 'create_uid', 'create_date', 'write_uid',
2454           'write_date' in database if _log_access is True (the default),
2455         - report on database columns no more existing in _columns,
2456         - remove no more existing not null constraints,
2457         - alter existing database columns to match _columns,
2458         - create database tables to match _columns,
2459         - add database indices to match _columns,
2460         - save in self._foreign_keys a list a foreign keys to create (see
2461           _auto_end).
2462
2463         """
2464         self._foreign_keys = set()
2465         raise_on_invalid_object_name(self._name)
2466         if context is None:
2467             context = {}
2468         store_compute = False
2469         stored_fields = []              # new-style stored fields with compute
2470         todo_end = []
2471         update_custom_fields = context.get('update_custom_fields', False)
2472         self._field_create(cr, context=context)
2473         create = not self._table_exist(cr)
2474         if self._auto:
2475
2476             if create:
2477                 self._create_table(cr)
2478                 has_rows = False
2479             else:
2480                 cr.execute('SELECT 1 FROM "%s" LIMIT 1' % self._table)
2481                 has_rows = cr.rowcount
2482
2483             cr.commit()
2484             if self._parent_store:
2485                 if not self._parent_columns_exist(cr):
2486                     self._create_parent_columns(cr)
2487                     store_compute = True
2488
2489             self._check_removed_columns(cr, log=False)
2490
2491             # iterate on the "object columns"
2492             column_data = self._select_column_data(cr)
2493
2494             for k, f in self._columns.iteritems():
2495                 if k == 'id': # FIXME: maybe id should be a regular column?
2496                     continue
2497                 # Don't update custom (also called manual) fields
2498                 if f.manual and not update_custom_fields:
2499                     continue
2500
2501                 if isinstance(f, fields.one2many):
2502                     self._o2m_raise_on_missing_reference(cr, f)
2503
2504                 elif isinstance(f, fields.many2many):
2505                     self._m2m_raise_or_create_relation(cr, f)
2506
2507                 else:
2508                     res = column_data.get(k)
2509
2510                     # The field is not found as-is in database, try if it
2511                     # exists with an old name.
2512                     if not res and hasattr(f, 'oldname'):
2513                         res = column_data.get(f.oldname)
2514                         if res:
2515                             cr.execute('ALTER TABLE "%s" RENAME "%s" TO "%s"' % (self._table, f.oldname, k))
2516                             res['attname'] = k
2517                             column_data[k] = res
2518                             _schema.debug("Table '%s': renamed column '%s' to '%s'",
2519                                 self._table, f.oldname, k)
2520
2521                     # The field already exists in database. Possibly
2522                     # change its type, rename it, drop it or change its
2523                     # constraints.
2524                     if res:
2525                         f_pg_type = res['typname']
2526                         f_pg_size = res['size']
2527                         f_pg_notnull = res['attnotnull']
2528                         if isinstance(f, fields.function) and not f.store and\
2529                                 not getattr(f, 'nodrop', False):
2530                             _logger.info('column %s (%s) converted to a function, removed from table %s',
2531                                          k, f.string, self._table)
2532                             cr.execute('ALTER TABLE "%s" DROP COLUMN "%s" CASCADE' % (self._table, k))
2533                             cr.commit()
2534                             _schema.debug("Table '%s': dropped column '%s' with cascade",
2535                                 self._table, k)
2536                             f_obj_type = None
2537                         else:
2538                             f_obj_type = get_pg_type(f) and get_pg_type(f)[0]
2539
2540                         if f_obj_type:
2541                             ok = False
2542                             casts = [
2543                                 ('text', 'char', pg_varchar(f.size), '::%s' % pg_varchar(f.size)),
2544                                 ('varchar', 'text', 'TEXT', ''),
2545                                 ('int4', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
2546                                 ('date', 'datetime', 'TIMESTAMP', '::TIMESTAMP'),
2547                                 ('timestamp', 'date', 'date', '::date'),
2548                                 ('numeric', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
2549                                 ('float8', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
2550                             ]
2551                             if f_pg_type == 'varchar' and f._type == 'char' and f_pg_size and (f.size is None or f_pg_size < f.size):
2552                                 try:
2553                                     with cr.savepoint():
2554                                         cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" TYPE %s' % (self._table, k, pg_varchar(f.size)))
2555                                 except psycopg2.NotSupportedError:
2556                                     # In place alter table cannot be done because a view is depending of this field.
2557                                     # Do a manual copy. This will drop the view (that will be recreated later)
2558                                     cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
2559                                     cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, pg_varchar(f.size)))
2560                                     cr.execute('UPDATE "%s" SET "%s"=temp_change_size::%s' % (self._table, k, pg_varchar(f.size)))
2561                                     cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
2562                                 cr.commit()
2563                                 _schema.debug("Table '%s': column '%s' (type varchar) changed size from %s to %s",
2564                                     self._table, k, f_pg_size or 'unlimited', f.size or 'unlimited')
2565                             for c in casts:
2566                                 if (f_pg_type==c[0]) and (f._type==c[1]):
2567                                     if f_pg_type != f_obj_type:
2568                                         ok = True
2569                                         cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO __temp_type_cast' % (self._table, k))
2570                                         cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, c[2]))
2571                                         cr.execute(('UPDATE "%s" SET "%s"= __temp_type_cast'+c[3]) % (self._table, k))
2572                                         cr.execute('ALTER TABLE "%s" DROP COLUMN  __temp_type_cast CASCADE' % (self._table,))
2573                                         cr.commit()
2574                                         _schema.debug("Table '%s': column '%s' changed type from %s to %s",
2575                                             self._table, k, c[0], c[1])
2576                                     break
2577
2578                             if f_pg_type != f_obj_type:
2579                                 if not ok:
2580                                     i = 0
2581                                     while True:
2582                                         newname = k + '_moved' + str(i)
2583                                         cr.execute("SELECT count(1) FROM pg_class c,pg_attribute a " \
2584                                             "WHERE c.relname=%s " \
2585                                             "AND a.attname=%s " \
2586                                             "AND c.oid=a.attrelid ", (self._table, newname))
2587                                         if not cr.fetchone()[0]:
2588                                             break
2589                                         i += 1
2590                                     if f_pg_notnull:
2591                                         cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
2592                                     cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO "%s"' % (self._table, k, newname))
2593                                     cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
2594                                     cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,))
2595                                     _schema.debug("Table '%s': column '%s' has changed type (DB=%s, def=%s), data moved to column %s !",
2596                                         self._table, k, f_pg_type, f._type, newname)
2597
2598                             # if the field is required and hasn't got a NOT NULL constraint
2599                             if f.required and f_pg_notnull == 0:
2600                                 if has_rows:
2601                                     self._set_default_value_on_column(cr, k, context=context)
2602                                 # add the NOT NULL constraint
2603                                 try:
2604                                     cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False)
2605                                     cr.commit()
2606                                     _schema.debug("Table '%s': column '%s': added NOT NULL constraint",
2607                                         self._table, k)
2608                                 except Exception:
2609                                     msg = "Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\
2610                                         "If you want to have it, you should update the records and execute manually:\n"\
2611                                         "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
2612                                     _schema.warning(msg, self._table, k, self._table, k)
2613                                 cr.commit()
2614                             elif not f.required and f_pg_notnull == 1:
2615                                 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
2616                                 cr.commit()
2617                                 _schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
2618                                     self._table, k)
2619                             # Verify index
2620                             indexname = '%s_%s_index' % (self._table, k)
2621                             cr.execute("SELECT indexname FROM pg_indexes WHERE indexname = %s and tablename = %s", (indexname, self._table))
2622                             res2 = cr.dictfetchall()
2623                             if not res2 and f.select:
2624                                 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
2625                                 cr.commit()
2626                                 if f._type == 'text':
2627                                     # FIXME: for fields.text columns we should try creating GIN indexes instead (seems most suitable for an ERP context)
2628                                     msg = "Table '%s': Adding (b-tree) index for %s column '%s'."\
2629                                         "This is probably useless (does not work for fulltext search) and prevents INSERTs of long texts"\
2630                                         " because there is a length limit for indexable btree values!\n"\
2631                                         "Use a search view instead if you simply want to make the field searchable."
2632                                     _schema.warning(msg, self._table, f._type, k)
2633                             if res2 and not f.select:
2634                                 cr.execute('DROP INDEX "%s_%s_index"' % (self._table, k))
2635                                 cr.commit()
2636                                 msg = "Table '%s': dropping index for column '%s' of type '%s' as it is not required anymore"
2637                                 _schema.debug(msg, self._table, k, f._type)
2638
2639                             if isinstance(f, fields.many2one) or (isinstance(f, fields.function) and f._type == 'many2one' and f.store):
2640                                 dest_model = self.pool[f._obj]
2641                                 if dest_model._auto and dest_model._table != 'ir_actions':
2642                                     self._m2o_fix_foreign_key(cr, self._table, k, dest_model, f.ondelete)
2643
2644                     # The field doesn't exist in database. Create it if necessary.
2645                     else:
2646                         if not isinstance(f, fields.function) or f.store:
2647                             # add the missing field
2648                             cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
2649                             cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,))
2650                             _schema.debug("Table '%s': added column '%s' with definition=%s",
2651                                 self._table, k, get_pg_type(f)[1])
2652
2653                             # initialize it
2654                             if has_rows:
2655                                 self._set_default_value_on_column(cr, k, context=context)
2656
2657                             # remember the functions to call for the stored fields
2658                             if isinstance(f, fields.function):
2659                                 order = 10
2660                                 if f.store is not True: # i.e. if f.store is a dict
2661                                     order = f.store[f.store.keys()[0]][2]
2662                                 todo_end.append((order, self._update_store, (f, k)))
2663
2664                             # remember new-style stored fields with compute method
2665                             if k in self._fields and self._fields[k].depends:
2666                                 stored_fields.append(self._fields[k])
2667
2668                             # and add constraints if needed
2669                             if isinstance(f, fields.many2one) or (isinstance(f, fields.function) and f._type == 'many2one' and f.store):
2670                                 if f._obj not in self.pool:
2671                                     raise except_orm('Programming Error', 'There is no reference available for %s' % (f._obj,))
2672                                 dest_model = self.pool[f._obj]
2673                                 ref = dest_model._table
2674                                 # ir_actions is inherited so foreign key doesn't work on it
2675                                 if dest_model._auto and ref != 'ir_actions':
2676                                     self._m2o_add_foreign_key_checked(k, dest_model, f.ondelete)
2677                             if f.select:
2678                                 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
2679                             if f.required:
2680                                 try:
2681                                     cr.commit()
2682                                     cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k))
2683                                     _schema.debug("Table '%s': column '%s': added a NOT NULL constraint",
2684                                         self._table, k)
2685                                 except Exception:
2686                                     msg = "WARNING: unable to set column %s of table %s not null !\n"\
2687                                         "Try to re-run: openerp-server --update=module\n"\
2688                                         "If it doesn't work, update records and execute manually:\n"\
2689                                         "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
2690                                     _logger.warning(msg, k, self._table, self._table, k, exc_info=True)
2691                             cr.commit()
2692
2693         else:
2694             cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
2695             create = not bool(cr.fetchone())
2696
2697         cr.commit()     # start a new transaction
2698
2699         if self._auto:
2700             self._add_sql_constraints(cr)
2701
2702         if create:
2703             self._execute_sql(cr)
2704
2705         if store_compute:
2706             self._parent_store_compute(cr)
2707             cr.commit()
2708
2709         if stored_fields:
2710             # trigger computation of new-style stored fields with a compute
2711             def func(cr):
2712                 _logger.info("Storing computed values of %s fields %s",
2713                     self._name, ', '.join(sorted(f.name for f in stored_fields)))
2714                 recs = self.browse(cr, SUPERUSER_ID, [], {'active_test': False})
2715                 recs = recs.search([])
2716                 if recs:
2717                     map(recs._recompute_todo, stored_fields)
2718                     recs.recompute()
2719
2720             todo_end.append((1000, func, ()))
2721
2722         return todo_end
2723
2724     def _auto_end(self, cr, context=None):
2725         """ Create the foreign keys recorded by _auto_init. """
2726         for t, k, r, d in self._foreign_keys:
2727             cr.execute('ALTER TABLE "%s" ADD FOREIGN KEY ("%s") REFERENCES "%s" ON DELETE %s' % (t, k, r, d))
2728             self._save_constraint(cr, "%s_%s_fkey" % (t, k), 'f', False)
2729         cr.commit()
2730         del self._foreign_keys
2731
2732
2733     def _table_exist(self, cr):
2734         cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
2735         return cr.rowcount
2736
2737
2738     def _create_table(self, cr):
2739         cr.execute('CREATE TABLE "%s" (id SERIAL NOT NULL, PRIMARY KEY(id))' % (self._table,))
2740         cr.execute(("COMMENT ON TABLE \"%s\" IS %%s" % self._table), (self._description,))
2741         _schema.debug("Table '%s': created", self._table)
2742
2743
2744     def _parent_columns_exist(self, cr):
2745         cr.execute("""SELECT c.relname
2746             FROM pg_class c, pg_attribute a
2747             WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
2748             """, (self._table, 'parent_left'))
2749         return cr.rowcount
2750
2751
2752     def _create_parent_columns(self, cr):
2753         cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_left" INTEGER' % (self._table,))
2754         cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_right" INTEGER' % (self._table,))
2755         if 'parent_left' not in self._columns:
2756             _logger.error('create a column parent_left on object %s: fields.integer(\'Left Parent\', select=1)',
2757                           self._table)
2758             _schema.debug("Table '%s': added column '%s' with definition=%s",
2759                 self._table, 'parent_left', 'INTEGER')
2760         elif not self._columns['parent_left'].select:
2761             _logger.error('parent_left column on object %s must be indexed! Add select=1 to the field definition)',
2762                           self._table)
2763         if 'parent_right' not in self._columns:
2764             _logger.error('create a column parent_right on object %s: fields.integer(\'Right Parent\', select=1)',
2765                           self._table)
2766             _schema.debug("Table '%s': added column '%s' with definition=%s",
2767                 self._table, 'parent_right', 'INTEGER')
2768         elif not self._columns['parent_right'].select:
2769             _logger.error('parent_right column on object %s must be indexed! Add select=1 to the field definition)',
2770                           self._table)
2771         if self._columns[self._parent_name].ondelete not in ('cascade', 'restrict'):
2772             _logger.error("The column %s on object %s must be set as ondelete='cascade' or 'restrict'",
2773                           self._parent_name, self._name)
2774
2775         cr.commit()
2776
2777
2778     def _select_column_data(self, cr):
2779         # attlen is the number of bytes necessary to represent the type when
2780         # the type has a fixed size. If the type has a varying size attlen is
2781         # -1 and atttypmod is the size limit + 4, or -1 if there is no limit.
2782         cr.execute("SELECT c.relname,a.attname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,t.typname,CASE WHEN a.attlen=-1 THEN (CASE WHEN a.atttypmod=-1 THEN 0 ELSE a.atttypmod-4 END) ELSE a.attlen END as size " \
2783            "FROM pg_class c,pg_attribute a,pg_type t " \
2784            "WHERE c.relname=%s " \
2785            "AND c.oid=a.attrelid " \
2786            "AND a.atttypid=t.oid", (self._table,))
2787         return dict(map(lambda x: (x['attname'], x),cr.dictfetchall()))
2788
2789
2790     def _o2m_raise_on_missing_reference(self, cr, f):
2791         # TODO this check should be a method on fields.one2many.
2792         if f._obj in self.pool:
2793             other = self.pool[f._obj]
2794             # TODO the condition could use fields_get_keys().
2795             if f._fields_id not in other._columns.keys():
2796                 if f._fields_id not in other._inherit_fields.keys():
2797                     raise except_orm('Programming Error', "There is no reference field '%s' found for '%s'" % (f._fields_id, f._obj,))
2798
2799     def _m2m_raise_or_create_relation(self, cr, f):
2800         m2m_tbl, col1, col2 = f._sql_names(self)
2801         # do not create relations for custom fields as they do not belong to a module
2802         # they will be automatically removed when dropping the corresponding ir.model.field
2803         # table name for custom relation all starts with x_, see __init__
2804         if not m2m_tbl.startswith('x_'):
2805             self._save_relation_table(cr, m2m_tbl)
2806         cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (m2m_tbl,))
2807         if not cr.dictfetchall():
2808             if f._obj not in self.pool:
2809                 raise except_orm('Programming Error', 'Many2Many destination model does not exist: `%s`' % (f._obj,))
2810             dest_model = self.pool[f._obj]
2811             ref = dest_model._table
2812             cr.execute('CREATE TABLE "%s" ("%s" INTEGER NOT NULL, "%s" INTEGER NOT NULL, UNIQUE("%s","%s"))' % (m2m_tbl, col1, col2, col1, col2))
2813             # create foreign key references with ondelete=cascade, unless the targets are SQL views
2814             cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (ref,))
2815             if not cr.fetchall():
2816                 self._m2o_add_foreign_key_unchecked(m2m_tbl, col2, dest_model, 'cascade')
2817             cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (self._table,))
2818             if not cr.fetchall():
2819                 self._m2o_add_foreign_key_unchecked(m2m_tbl, col1, self, 'cascade')
2820
2821             cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col1, m2m_tbl, col1))
2822             cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col2, m2m_tbl, col2))
2823             cr.execute("COMMENT ON TABLE \"%s\" IS 'RELATION BETWEEN %s AND %s'" % (m2m_tbl, self._table, ref))
2824             cr.commit()
2825             _schema.debug("Create table '%s': m2m relation between '%s' and '%s'", m2m_tbl, self._table, ref)
2826
2827
2828     def _add_sql_constraints(self, cr):
2829         """
2830
2831         Modify this model's database table constraints so they match the one in
2832         _sql_constraints.
2833
2834         """
2835         def unify_cons_text(txt):
2836             return txt.lower().replace(', ',',').replace(' (','(')
2837
2838         for (key, con, _) in self._sql_constraints:
2839             conname = '%s_%s' % (self._table, key)
2840
2841             # using 1 to get result if no imc but one pgc
2842             cr.execute("""SELECT definition, 1
2843                           FROM ir_model_constraint imc
2844                           RIGHT JOIN pg_constraint pgc
2845                           ON (pgc.conname = imc.name)
2846                           WHERE pgc.conname=%s
2847                           """, (conname, ))
2848             existing_constraints = cr.dictfetchone()
2849             sql_actions = {
2850                 'drop': {
2851                     'execute': False,
2852                     'query': 'ALTER TABLE "%s" DROP CONSTRAINT "%s"' % (self._table, conname, ),
2853                     'msg_ok': "Table '%s': dropped constraint '%s'. Reason: its definition changed from '%%s' to '%s'" % (
2854                         self._table, conname, con),
2855                     'msg_err': "Table '%s': unable to drop \'%s\' constraint !" % (self._table, con),
2856                     'order': 1,
2857                 },
2858                 'add': {
2859                     'execute': False,
2860                     'query': 'ALTER TABLE "%s" ADD CONSTRAINT "%s" %s' % (self._table, conname, con,),
2861                     'msg_ok': "Table '%s': added constraint '%s' with definition=%s" % (self._table, conname, con),
2862                     '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" % (
2863                         self._table, con),
2864                     'order': 2,
2865                 },
2866             }
2867
2868             if not existing_constraints:
2869                 # constraint does not exists:
2870                 sql_actions['add']['execute'] = True
2871                 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
2872             elif unify_cons_text(con) != existing_constraints['definition']:
2873                 # constraint exists but its definition has changed:
2874                 sql_actions['drop']['execute'] = True
2875                 sql_actions['drop']['msg_ok'] = sql_actions['drop']['msg_ok'] % (existing_constraints['definition'] or '', )
2876                 sql_actions['add']['execute'] = True
2877                 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
2878
2879             # we need to add the constraint:
2880             self._save_constraint(cr, conname, 'u', unify_cons_text(con))
2881             sql_actions = [item for item in sql_actions.values()]
2882             sql_actions.sort(key=lambda x: x['order'])
2883             for sql_action in [action for action in sql_actions if action['execute']]:
2884                 try:
2885                     cr.execute(sql_action['query'])
2886                     cr.commit()
2887                     _schema.debug(sql_action['msg_ok'])
2888                 except:
2889                     _schema.warning(sql_action['msg_err'])
2890                     cr.rollback()
2891
2892
2893     def _execute_sql(self, cr):
2894         """ Execute the SQL code from the _sql attribute (if any)."""
2895         if hasattr(self, "_sql"):
2896             for line in self._sql.split(';'):
2897                 line2 = line.replace('\n', '').strip()
2898                 if line2:
2899                     cr.execute(line2)
2900                     cr.commit()
2901
2902     #
2903     # Update objects that uses this one to update their _inherits fields
2904     #
2905
2906     @classmethod
2907     def _inherits_reload_src(cls):
2908         """ Recompute the _inherit_fields mapping on each _inherits'd child model."""
2909         for model in cls.pool.values():
2910             if cls._name in model._inherits:
2911                 model._inherits_reload()
2912
2913     @classmethod
2914     def _inherits_reload(cls):
2915         """ Recompute the _inherit_fields mapping.
2916
2917         This will also call itself on each inherits'd child model.
2918
2919         """
2920         res = {}
2921         for table in cls._inherits:
2922             other = cls.pool[table]
2923             for col in other._columns.keys():
2924                 res[col] = (table, cls._inherits[table], other._columns[col], table)
2925             for col in other._inherit_fields.keys():
2926                 res[col] = (table, cls._inherits[table], other._inherit_fields[col][2], other._inherit_fields[col][3])
2927         cls._inherit_fields = res
2928         cls._all_columns = cls._get_column_infos()
2929
2930         # interface columns with new-style fields
2931         for attr, column in cls._columns.items():
2932             if attr not in cls._fields:
2933                 cls._add_field(attr, column.to_field())
2934
2935         # interface inherited fields with new-style fields (note that the
2936         # reverse order is for being consistent with _all_columns above)
2937         for parent_model, parent_field in reversed(cls._inherits.items()):
2938             for attr, field in cls.pool[parent_model]._fields.iteritems():
2939                 if attr not in cls._fields:
2940                     cls._add_field(attr, field.new(
2941                         inherited=True,
2942                         related=(parent_field, attr),
2943                         related_sudo=False,
2944                     ))
2945
2946         cls._inherits_reload_src()
2947
2948     @classmethod
2949     def _get_column_infos(cls):
2950         """Returns a dict mapping all fields names (direct fields and
2951            inherited field via _inherits) to a ``column_info`` struct
2952            giving detailed columns """
2953         result = {}
2954         # do not inverse for loops, since local fields may hide inherited ones!
2955         for k, (parent, m2o, col, original_parent) in cls._inherit_fields.iteritems():
2956             result[k] = fields.column_info(k, col, parent, m2o, original_parent)
2957         for k, col in cls._columns.iteritems():
2958             result[k] = fields.column_info(k, col)
2959         return result
2960
2961     @classmethod
2962     def _inherits_check(cls):
2963         for table, field_name in cls._inherits.items():
2964             if field_name not in cls._columns:
2965                 _logger.info('Missing many2one field definition for _inherits reference "%s" in "%s", using default one.', field_name, cls._name)
2966                 cls._columns[field_name] = fields.many2one(table, string="Automatically created field to link to parent %s" % table,
2967                                                              required=True, ondelete="cascade")
2968             elif not cls._columns[field_name].required or cls._columns[field_name].ondelete.lower() not in ("cascade", "restrict"):
2969                 _logger.warning('Field definition for _inherits reference "%s" in "%s" must be marked as "required" with ondelete="cascade" or "restrict", forcing it to required + cascade.', field_name, cls._name)
2970                 cls._columns[field_name].required = True
2971                 cls._columns[field_name].ondelete = "cascade"
2972
2973         # reflect fields with delegate=True in dictionary cls._inherits
2974         for field in cls._fields.itervalues():
2975             if field.type == 'many2one' and not field.related and field.delegate:
2976                 if not field.required:
2977                     _logger.warning("Field %s with delegate=True must be required.", field)
2978                     field.required = True
2979                 if field.ondelete.lower() not in ('cascade', 'restrict'):
2980                     field.ondelete = 'cascade'
2981                 cls._inherits[field.comodel_name] = field.name
2982
2983     @api.model
2984     def _prepare_setup_fields(self):
2985         """ Prepare the setup of fields once the models have been loaded. """
2986         for field in self._fields.itervalues():
2987             field.reset()
2988
2989     @api.model
2990     def _setup_fields(self, partial=False):
2991         """ Setup the fields (dependency triggers, etc). """
2992         for field in self._fields.itervalues():
2993             try:
2994                 field.setup(self.env)
2995             except Exception:
2996                 if not partial:
2997                     raise
2998
2999         # group fields by compute to determine field.computed_fields
3000         fields_by_compute = defaultdict(list)
3001         for field in self._fields.itervalues():
3002             if field.compute:
3003                 field.computed_fields = fields_by_compute[field.compute]
3004                 field.computed_fields.append(field)
3005             else:
3006                 field.computed_fields = []
3007
3008     def fields_get(self, cr, user, allfields=None, context=None, write_access=True):
3009         """ fields_get([fields])
3010
3011         Return the definition of each field.
3012
3013         The returned value is a dictionary (indiced by field name) of
3014         dictionaries. The _inherits'd fields are included. The string, help,
3015         and selection (if present) attributes are translated.
3016
3017         :param cr: database cursor
3018         :param user: current user id
3019         :param allfields: list of fields
3020         :param context: context arguments, like lang, time zone
3021         :return: dictionary of field dictionaries, each one describing a field of the business object
3022         :raise AccessError: * if user has no create/write rights on the requested object
3023
3024         """
3025         recs = self.browse(cr, user, [], context)
3026
3027         res = {}
3028         for fname, field in self._fields.iteritems():
3029             if allfields and fname not in allfields:
3030                 continue
3031             if not field.setup_done:
3032                 continue
3033             if field.groups and not recs.user_has_groups(field.groups):
3034                 continue
3035             res[fname] = field.get_description(recs.env)
3036
3037         # if user cannot create or modify records, make all fields readonly
3038         has_access = functools.partial(recs.check_access_rights, raise_exception=False)
3039         if not (has_access('write') or has_access('create')):
3040             for description in res.itervalues():
3041                 description['readonly'] = True
3042                 description['states'] = {}
3043
3044         return res
3045
3046     def get_empty_list_help(self, cr, user, help, context=None):
3047         """ Generic method giving the help message displayed when having
3048             no result to display in a list or kanban view. By default it returns
3049             the help given in parameter that is generally the help message
3050             defined in the action.
3051         """
3052         return help
3053
3054     def check_field_access_rights(self, cr, user, operation, fields, context=None):
3055         """
3056         Check the user access rights on the given fields. This raises Access
3057         Denied if the user does not have the rights. Otherwise it returns the
3058         fields (as is if the fields is not falsy, or the readable/writable
3059         fields if fields is falsy).
3060         """
3061         if user == SUPERUSER_ID:
3062             return fields or list(self._fields)
3063
3064         def valid(fname):
3065             """ determine whether user has access to field `fname` """
3066             field = self._fields.get(fname)
3067             if field and field.groups:
3068                 return self.user_has_groups(cr, user, groups=field.groups, context=context)
3069             else:
3070                 return True
3071
3072         if not fields:
3073             fields = filter(valid, self._fields)
3074         else:
3075             invalid_fields = set(filter(lambda name: not valid(name), fields))
3076             if invalid_fields:
3077                 _logger.warning('Access Denied by ACLs for operation: %s, uid: %s, model: %s, fields: %s',
3078                     operation, user, self._name, ', '.join(invalid_fields))
3079                 raise AccessError(
3080                     _('The requested operation cannot be completed due to security restrictions. '
3081                     'Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \
3082                     (self._description, operation))
3083
3084         return fields
3085
3086     # add explicit old-style implementation to read()
3087     @api.v7
3088     def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
3089         records = self.browse(cr, user, ids, context)
3090         result = BaseModel.read(records, fields, load=load)
3091         return result if isinstance(ids, list) else (bool(result) and result[0])
3092
3093     # new-style implementation of read()
3094     @api.v8
3095     def read(self, fields=None, load='_classic_read'):
3096         """ read([fields])
3097
3098         Reads the requested fields for the records in `self`, low-level/RPC
3099         method. In Python code, prefer :meth:`~.browse`.
3100
3101         :param fields: list of field names to return (default is all fields)
3102         :return: a list of dictionaries mapping field names to their values,
3103                  with one dictionary per record
3104         :raise AccessError: if user has no read rights on some of the given
3105                 records
3106         """
3107         # check access rights
3108         self.check_access_rights('read')
3109         fields = self.check_field_access_rights('read', fields)
3110
3111         # split fields into stored and computed fields
3112         stored, computed = [], []
3113         for name in fields:
3114             if name in self._columns:
3115                 stored.append(name)
3116             elif name in self._fields:
3117                 computed.append(name)
3118             else:
3119                 _logger.warning("%s.read() with unknown field '%s'", self._name, name)
3120
3121         # fetch stored fields from the database to the cache
3122         self._read_from_database(stored)
3123
3124         # retrieve results from records; this takes values from the cache and
3125         # computes remaining fields
3126         result = []
3127         name_fields = [(name, self._fields[name]) for name in (stored + computed)]
3128         use_name_get = (load == '_classic_read')
3129         for record in self:
3130             try:
3131                 values = {'id': record.id}
3132                 for name, field in name_fields:
3133                     values[name] = field.convert_to_read(record[name], use_name_get)
3134                 result.append(values)
3135             except MissingError:
3136                 pass
3137
3138         return result
3139
3140     @api.multi
3141     def _prefetch_field(self, field):
3142         """ Read from the database in order to fetch `field` (:class:`Field`
3143             instance) for `self` in cache.
3144         """
3145         # fetch the records of this model without field_name in their cache
3146         records = self._in_cache_without(field)
3147
3148         if len(records) > PREFETCH_MAX:
3149             records = records[:PREFETCH_MAX] | self
3150
3151         # determine which fields can be prefetched
3152         if not self.env.in_draft and \
3153                 self._context.get('prefetch_fields', True) and \
3154                 self._columns[field.name]._prefetch:
3155             # prefetch all classic and many2one fields that the user can access
3156             fnames = {fname
3157                 for fname, fcolumn in self._columns.iteritems()
3158                 if fcolumn._prefetch
3159                 if not fcolumn.groups or self.user_has_groups(fcolumn.groups)
3160             }
3161         else:
3162             fnames = {field.name}
3163
3164         # important: never prefetch fields to recompute!
3165         get_recs_todo = self.env.field_todo
3166         for fname in list(fnames):
3167             if get_recs_todo(self._fields[fname]):
3168                 if fname == field.name:
3169                     records -= get_recs_todo(field)
3170                 else:
3171                     fnames.discard(fname)
3172
3173         # fetch records with read()
3174         assert self in records and field.name in fnames
3175         result = []
3176         try:
3177             result = records.read(list(fnames), load='_classic_write')
3178         except AccessError:
3179             pass
3180
3181         # check the cache, and update it if necessary
3182         if not self._cache.contains(field):
3183             for values in result:
3184                 record = self.browse(values.pop('id'))
3185                 record._cache.update(record._convert_to_cache(values, validate=False))
3186             if not self._cache.contains(field):
3187                 e = AccessError("No value found for %s.%s" % (self, field.name))
3188                 self._cache[field] = FailedValue(e)
3189
3190     @api.multi
3191     def _read_from_database(self, field_names):
3192         """ Read the given fields of the records in `self` from the database,
3193             and store them in cache. Access errors are also stored in cache.
3194         """
3195         env = self.env
3196         cr, user, context = env.args
3197
3198         # FIXME: The query construction needs to be rewritten using the internal Query
3199         # object, as in search(), to avoid ambiguous column references when
3200         # reading/sorting on a table that is auto_joined to another table with
3201         # common columns (e.g. the magical columns)
3202
3203         # Construct a clause for the security rules.
3204         # 'tables' holds the list of tables necessary for the SELECT, including
3205         # the ir.rule clauses, and contains at least self._table.
3206         rule_clause, rule_params, tables = env['ir.rule'].domain_get(self._name, 'read')
3207
3208         # determine the fields that are stored as columns in self._table
3209         fields_pre = [f for f in field_names if self._columns[f]._classic_write]
3210
3211         # we need fully-qualified column names in case len(tables) > 1
3212         def qualify(f):
3213             if isinstance(self._columns.get(f), fields.binary) and \
3214                     context.get('bin_size_%s' % f, context.get('bin_size')):
3215                 # PG 9.2 introduces conflicting pg_size_pretty(numeric) -> need ::cast 
3216                 return 'pg_size_pretty(length(%s."%s")::bigint) as "%s"' % (self._table, f, f)
3217             else:
3218                 return '%s."%s"' % (self._table, f)
3219         qual_names = map(qualify, set(fields_pre + ['id']))
3220
3221         query = """ SELECT %(qual_names)s FROM %(tables)s
3222                     WHERE %(table)s.id IN %%s AND (%(extra)s)
3223                     ORDER BY %(order)s
3224                 """ % {
3225                     'qual_names': ",".join(qual_names),
3226                     'tables': ",".join(tables),
3227                     'table': self._table,
3228                     'extra': " OR ".join(rule_clause) if rule_clause else "TRUE",
3229                     'order': self._parent_order or self._order,
3230                 }
3231
3232         result = []
3233         for sub_ids in cr.split_for_in_conditions(self.ids):
3234             cr.execute(query, [tuple(sub_ids)] + rule_params)
3235             result.extend(cr.dictfetchall())
3236
3237         ids = [vals['id'] for vals in result]
3238
3239         if ids:
3240             # translate the fields if necessary
3241             if context.get('lang'):
3242                 ir_translation = env['ir.translation']
3243                 for f in fields_pre:
3244                     if self._columns[f].translate:
3245                         #TODO: optimize out of this loop
3246                         res_trans = ir_translation._get_ids(
3247                             '%s,%s' % (self._name, f), 'model', context['lang'], ids)
3248                         for vals in result:
3249                             vals[f] = res_trans.get(vals['id'], False) or vals[f]
3250
3251             # apply the symbol_get functions of the fields we just read
3252             for f in fields_pre:
3253                 symbol_get = self._columns[f]._symbol_get
3254                 if symbol_get:
3255                     for vals in result:
3256                         vals[f] = symbol_get(vals[f])
3257
3258             # store result in cache for POST fields
3259             for vals in result:
3260                 record = self.browse(vals['id'])
3261                 record._cache.update(record._convert_to_cache(vals, validate=False))
3262
3263             # determine the fields that must be processed now
3264             fields_post = [f for f in field_names if not self._columns[f]._classic_write]
3265
3266             # Compute POST fields, grouped by multi
3267             by_multi = defaultdict(list)
3268             for f in fields_post:
3269                 by_multi[self._columns[f]._multi].append(f)
3270
3271             for multi, fs in by_multi.iteritems():
3272                 if multi:
3273                     res2 = self._columns[fs[0]].get(cr, self._model, ids, fs, user, context=context, values=result)
3274                     assert res2 is not None, \
3275                         'The function field "%s" on the "%s" model returned None\n' \
3276                         '(a dictionary was expected).' % (fs[0], self._name)
3277                     for vals in result:
3278                         # TOCHECK : why got string instend of dict in python2.6
3279                         # if isinstance(res2[vals['id']], str): res2[vals['id']] = eval(res2[vals['id']])
3280                         multi_fields = res2.get(vals['id'], {})
3281                         if multi_fields:
3282                             for f in fs:
3283                                 vals[f] = multi_fields.get(f, [])
3284                 else:
3285                     for f in fs:
3286                         res2 = self._columns[f].get(cr, self._model, ids, f, user, context=context, values=result)
3287                         for vals in result:
3288                             if res2:
3289                                 vals[f] = res2[vals['id']]
3290                             else:
3291                                 vals[f] = []
3292
3293         # Warn about deprecated fields now that fields_pre and fields_post are computed
3294         for f in field_names:
3295             column = self._columns[f]
3296             if column.deprecated:
3297                 _logger.warning('Field %s.%s is deprecated: %s', self._name, f, column.deprecated)
3298
3299         # store result in cache
3300         for vals in result:
3301             record = self.browse(vals.pop('id'))
3302             record._cache.update(record._convert_to_cache(vals, validate=False))
3303
3304         # store failed values in cache for the records that could not be read
3305         fetched = self.browse(ids)
3306         missing = self - fetched
3307         if missing:
3308             extras = fetched - self
3309             if extras:
3310                 raise AccessError(
3311                     _("Database fetch misses ids ({}) and has extra ids ({}), may be caused by a type incoherence in a previous request").format(
3312                         ', '.join(map(repr, missing._ids)),
3313                         ', '.join(map(repr, extras._ids)),
3314                     ))
3315             # store an access error exception in existing records
3316             exc = AccessError(
3317                 _('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \
3318                 (self._name, 'read')
3319             )
3320             forbidden = missing.exists()
3321             forbidden._cache.update(FailedValue(exc))
3322             # store a missing error exception in non-existing records
3323             exc = MissingError(
3324                 _('One of the documents you are trying to access has been deleted, please try again after refreshing.')
3325             )
3326             (missing - forbidden)._cache.update(FailedValue(exc))
3327
3328     @api.multi
3329     def get_metadata(self):
3330         """
3331         Returns some metadata about the given records.
3332
3333         :return: list of ownership dictionaries for each requested record
3334         :rtype: list of dictionaries with the following keys:
3335
3336                     * id: object id
3337                     * create_uid: user who created the record
3338                     * create_date: date when the record was created
3339                     * write_uid: last user who changed the record
3340                     * write_date: date of the last change to the record
3341                     * xmlid: XML ID to use to refer to this record (if there is one), in format ``module.name``
3342         """
3343         fields = ['id']
3344         if self._log_access:
3345             fields += ['create_uid', 'create_date', 'write_uid', 'write_date']
3346         quoted_table = '"%s"' % self._table
3347         fields_str = ",".join('%s.%s' % (quoted_table, field) for field in fields)
3348         query = '''SELECT %s, __imd.module, __imd.name
3349                    FROM %s LEFT JOIN ir_model_data __imd
3350                        ON (__imd.model = %%s and __imd.res_id = %s.id)
3351                    WHERE %s.id IN %%s''' % (fields_str, quoted_table, quoted_table, quoted_table)
3352         self._cr.execute(query, (self._name, tuple(self.ids)))
3353         res = self._cr.dictfetchall()
3354
3355         uids = set(r[k] for r in res for k in ['write_uid', 'create_uid'] if r.get(k))
3356         names = dict(self.env['res.users'].browse(uids).name_get())
3357
3358         for r in res:
3359             for key in r:
3360                 value = r[key] = r[key] or False
3361                 if key in ('write_uid', 'create_uid') and value in names:
3362                     r[key] = (value, names[value])
3363             r['xmlid'] = ("%(module)s.%(name)s" % r) if r['name'] else False
3364             del r['name'], r['module']
3365         return res
3366
3367     def _check_concurrency(self, cr, ids, context):
3368         if not context:
3369             return
3370         if not (context.get(self.CONCURRENCY_CHECK_FIELD) and self._log_access):
3371             return
3372         check_clause = "(id = %s AND %s < COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp)"
3373         for sub_ids in cr.split_for_in_conditions(ids):
3374             ids_to_check = []
3375             for id in sub_ids:
3376                 id_ref = "%s,%s" % (self._name, id)
3377                 update_date = context[self.CONCURRENCY_CHECK_FIELD].pop(id_ref, None)
3378                 if update_date:
3379                     ids_to_check.extend([id, update_date])
3380             if not ids_to_check:
3381                 continue
3382             cr.execute("SELECT id FROM %s WHERE %s" % (self._table, " OR ".join([check_clause]*(len(ids_to_check)/2))), tuple(ids_to_check))
3383             res = cr.fetchone()
3384             if res:
3385                 # mention the first one only to keep the error message readable
3386                 raise except_orm('ConcurrencyException', _('A document was modified since you last viewed it (%s:%d)') % (self._description, res[0]))
3387
3388     def _check_record_rules_result_count(self, cr, uid, ids, result_ids, operation, context=None):
3389         """Verify the returned rows after applying record rules matches
3390            the length of `ids`, and raise an appropriate exception if it does not.
3391         """
3392         if context is None:
3393             context = {}
3394         ids, result_ids = set(ids), set(result_ids)
3395         missing_ids = ids - result_ids
3396         if missing_ids:
3397             # Attempt to distinguish record rule restriction vs deleted records,
3398             # to provide a more specific error message - check if the missinf
3399             cr.execute('SELECT id FROM ' + self._table + ' WHERE id IN %s', (tuple(missing_ids),))
3400             forbidden_ids = [x[0] for x in cr.fetchall()]
3401             if forbidden_ids:
3402                 # the missing ids are (at least partially) hidden by access rules
3403                 if uid == SUPERUSER_ID:
3404                     return
3405                 _logger.warning('Access Denied by record rules for operation: %s on record ids: %r, uid: %s, model: %s', operation, forbidden_ids, uid, self._name)
3406                 raise except_orm(_('Access Denied'),
3407                                  _('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \
3408                                     (self._description, operation))
3409             else:
3410                 # If we get here, the missing_ids are not in the database
3411                 if operation in ('read','unlink'):
3412                     # No need to warn about deleting an already deleted record.
3413                     # And no error when reading a record that was deleted, to prevent spurious
3414                     # errors for non-transactional search/read sequences coming from clients
3415                     return
3416                 _logger.warning('Failed operation on deleted record(s): %s, uid: %s, model: %s', operation, uid, self._name)
3417                 raise except_orm(_('Missing document(s)'),
3418                                  _('One of the documents you are trying to access has been deleted, please try again after refreshing.'))
3419
3420
3421     def check_access_rights(self, cr, uid, operation, raise_exception=True): # no context on purpose.
3422         """Verifies that the operation given by ``operation`` is allowed for the user
3423            according to the access rights."""
3424         return self.pool.get('ir.model.access').check(cr, uid, self._name, operation, raise_exception)
3425
3426     def check_access_rule(self, cr, uid, ids, operation, context=None):
3427         """Verifies that the operation given by ``operation`` is allowed for the user
3428            according to ir.rules.
3429
3430            :param operation: one of ``write``, ``unlink``
3431            :raise except_orm: * if current ir.rules do not permit this operation.
3432            :return: None if the operation is allowed
3433         """
3434         if uid == SUPERUSER_ID:
3435             return
3436
3437         if self.is_transient():
3438             # Only one single implicit access rule for transient models: owner only!
3439             # This is ok to hardcode because we assert that TransientModels always
3440             # have log_access enabled so that the create_uid column is always there.
3441             # And even with _inherits, these fields are always present in the local
3442             # table too, so no need for JOINs.
3443             cr.execute("""SELECT distinct create_uid
3444                           FROM %s
3445                           WHERE id IN %%s""" % self._table, (tuple(ids),))
3446             uids = [x[0] for x in cr.fetchall()]
3447             if len(uids) != 1 or uids[0] != uid:
3448                 raise except_orm(_('Access Denied'),
3449                                  _('For this kind of document, you may only access records you created yourself.\n\n(Document type: %s)') % (self._description,))
3450         else:
3451             where_clause, where_params, tables = self.pool.get('ir.rule').domain_get(cr, uid, self._name, operation, context=context)
3452             if where_clause:
3453                 where_clause = ' and ' + ' and '.join(where_clause)
3454                 for sub_ids in cr.split_for_in_conditions(ids):
3455                     cr.execute('SELECT ' + self._table + '.id FROM ' + ','.join(tables) +
3456                                ' WHERE ' + self._table + '.id IN %s' + where_clause,
3457                                [sub_ids] + where_params)
3458                     returned_ids = [x['id'] for x in cr.dictfetchall()]
3459                     self._check_record_rules_result_count(cr, uid, sub_ids, returned_ids, operation, context=context)
3460
3461     def create_workflow(self, cr, uid, ids, context=None):
3462         """Create a workflow instance for each given record IDs."""
3463         from openerp import workflow
3464         for res_id in ids:
3465             workflow.trg_create(uid, self._name, res_id, cr)
3466         # self.invalidate_cache(cr, uid, context=context) ?
3467         return True
3468
3469     def delete_workflow(self, cr, uid, ids, context=None):
3470         """Delete the workflow instances bound to the given record IDs."""
3471         from openerp import workflow
3472         for res_id in ids:
3473             workflow.trg_delete(uid, self._name, res_id, cr)
3474         self.invalidate_cache(cr, uid, context=context)
3475         return True
3476
3477     def step_workflow(self, cr, uid, ids, context=None):
3478         """Reevaluate the workflow instances of the given record IDs."""
3479         from openerp import workflow
3480         for res_id in ids:
3481             workflow.trg_write(uid, self._name, res_id, cr)
3482         # self.invalidate_cache(cr, uid, context=context) ?
3483         return True
3484
3485     def signal_workflow(self, cr, uid, ids, signal, context=None):
3486         """Send given workflow signal and return a dict mapping ids to workflow results"""
3487         from openerp import workflow
3488         result = {}
3489         for res_id in ids:
3490             result[res_id] = workflow.trg_validate(uid, self._name, res_id, signal, cr)
3491         # self.invalidate_cache(cr, uid, context=context) ?
3492         return result
3493
3494     def redirect_workflow(self, cr, uid, old_new_ids, context=None):
3495         """ Rebind the workflow instance bound to the given 'old' record IDs to
3496             the given 'new' IDs. (``old_new_ids`` is a list of pairs ``(old, new)``.
3497         """
3498         from openerp import workflow
3499         for old_id, new_id in old_new_ids:
3500             workflow.trg_redirect(uid, self._name, old_id, new_id, cr)
3501         self.invalidate_cache(cr, uid, context=context)
3502         return True
3503
3504     def unlink(self, cr, uid, ids, context=None):
3505         """ unlink()
3506
3507         Deletes the records of the current set
3508
3509         :raise AccessError: * if user has no unlink rights on the requested object
3510                             * if user tries to bypass access rules for unlink on the requested object
3511         :raise UserError: if the record is default property for other records
3512
3513         """
3514         if not ids:
3515             return True
3516         if isinstance(ids, (int, long)):
3517             ids = [ids]
3518
3519         result_store = self._store_get_values(cr, uid, ids, self._all_columns.keys(), context)
3520
3521         # for recomputing new-style fields
3522         recs = self.browse(cr, uid, ids, context)
3523         recs.modified(self._fields)
3524
3525         self._check_concurrency(cr, ids, context)
3526
3527         self.check_access_rights(cr, uid, 'unlink')
3528
3529         ir_property = self.pool.get('ir.property')
3530
3531         # Check if the records are used as default properties.
3532         domain = [('res_id', '=', False),
3533                   ('value_reference', 'in', ['%s,%s' % (self._name, i) for i in ids]),
3534                  ]
3535         if ir_property.search(cr, uid, domain, context=context):
3536             raise except_orm(_('Error'), _('Unable to delete this document because it is used as a default property'))
3537
3538         # Delete the records' properties.
3539         property_ids = ir_property.search(cr, uid, [('res_id', 'in', ['%s,%s' % (self._name, i) for i in ids])], context=context)
3540         ir_property.unlink(cr, uid, property_ids, context=context)
3541
3542         self.delete_workflow(cr, uid, ids, context=context)
3543
3544         self.check_access_rule(cr, uid, ids, 'unlink', context=context)
3545         pool_model_data = self.pool.get('ir.model.data')
3546         ir_values_obj = self.pool.get('ir.values')
3547         ir_attachment_obj = self.pool.get('ir.attachment')
3548         for sub_ids in cr.split_for_in_conditions(ids):
3549             cr.execute('delete from ' + self._table + ' ' \
3550                        'where id IN %s', (sub_ids,))
3551
3552             # Removing the ir_model_data reference if the record being deleted is a record created by xml/csv file,
3553             # as these are not connected with real database foreign keys, and would be dangling references.
3554             # Note: following steps performed as admin to avoid access rights restrictions, and with no context
3555             #       to avoid possible side-effects during admin calls.
3556             # Step 1. Calling unlink of ir_model_data only for the affected IDS
3557             reference_ids = pool_model_data.search(cr, SUPERUSER_ID, [('res_id','in',list(sub_ids)),('model','=',self._name)])
3558             # Step 2. Marching towards the real deletion of referenced records
3559             if reference_ids:
3560                 pool_model_data.unlink(cr, SUPERUSER_ID, reference_ids)
3561
3562             # For the same reason, removing the record relevant to ir_values
3563             ir_value_ids = ir_values_obj.search(cr, uid,
3564                     ['|',('value','in',['%s,%s' % (self._name, sid) for sid in sub_ids]),'&',('res_id','in',list(sub_ids)),('model','=',self._name)],
3565                     context=context)
3566             if ir_value_ids:
3567                 ir_values_obj.unlink(cr, uid, ir_value_ids, context=context)
3568
3569             # For the same reason, removing the record relevant to ir_attachment
3570             # The search is performed with sql as the search method of ir_attachment is overridden to hide attachments of deleted records
3571             cr.execute('select id from ir_attachment where res_model = %s and res_id in %s', (self._name, sub_ids))
3572             ir_attachment_ids = [ir_attachment[0] for ir_attachment in cr.fetchall()]
3573             if ir_attachment_ids:
3574                 ir_attachment_obj.unlink(cr, uid, ir_attachment_ids, context=context)
3575
3576         # invalidate the *whole* cache, since the orm does not handle all
3577         # changes made in the database, like cascading delete!
3578         recs.invalidate_cache()
3579
3580         for order, obj_name, store_ids, fields in result_store:
3581             if obj_name == self._name:
3582                 effective_store_ids = set(store_ids) - set(ids)
3583             else:
3584                 effective_store_ids = store_ids
3585             if effective_store_ids:
3586                 obj = self.pool[obj_name]
3587                 cr.execute('select id from '+obj._table+' where id IN %s', (tuple(effective_store_ids),))
3588                 rids = map(lambda x: x[0], cr.fetchall())
3589                 if rids:
3590                     obj._store_set_values(cr, uid, rids, fields, context)
3591
3592         # recompute new-style fields
3593         recs.recompute()
3594
3595         return True
3596
3597     #
3598     # TODO: Validate
3599     #
3600     @api.multi
3601     def write(self, vals):
3602         """ write(vals)
3603
3604         Updates all records in the current set with the provided values.
3605
3606         :param dict vals: fields to update and the value to set on them e.g::
3607
3608                 {'foo': 1, 'bar': "Qux"}
3609
3610             will set the field ``foo`` to ``1`` and the field ``bar`` to
3611             ``"Qux"`` if those are valid (otherwise it will trigger an error).
3612
3613         :raise AccessError: * if user has no write rights on the requested object
3614                             * if user tries to bypass access rules for write on the requested object
3615         :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
3616         :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)
3617
3618         .. _openerp/models/relationals/format:
3619
3620         .. note:: Relational fields use a special "commands" format to manipulate their values
3621
3622             This format is a list of command triplets executed sequentially,
3623             possible command triplets are:
3624
3625             ``(0, _, values: dict)``
3626                 links to a new record created from the provided values
3627             ``(1, id, values: dict)``
3628                 updates the already-linked record of id ``id`` with the
3629                 provided ``values``
3630             ``(2, id, _)``
3631                 unlinks and deletes the linked record of id ``id``
3632             ``(3, id, _)``
3633                 unlinks the linked record of id ``id`` without deleting it
3634             ``(4, id, _)``
3635                 links to an existing record of id ``id``
3636             ``(5, _, _)``
3637                 unlinks all records in the relation, equivalent to using
3638                 the command ``3`` on every linked record
3639             ``(6, _, ids)``
3640                 replaces the existing list of linked records by the provoded
3641                 ones, equivalent to using ``5`` then ``4`` for each id in
3642                 ``ids``)
3643
3644             (in command triplets, ``_`` values are ignored and can be
3645             anything, generally ``0`` or ``False``)
3646
3647             Any command can be used on :class:`~openerp.fields.Many2many`,
3648             only ``0``, ``1`` and ``2`` can be used on
3649             :class:`~openerp.fields.One2many`.
3650         """
3651         if not self:
3652             return True
3653
3654         self._check_concurrency(self._ids)
3655         self.check_access_rights('write')
3656
3657         # No user-driven update of these columns
3658         for field in itertools.chain(MAGIC_COLUMNS, ('parent_left', 'parent_right')):
3659             vals.pop(field, None)
3660
3661         # split up fields into old-style and pure new-style ones
3662         old_vals, new_vals, unknown = {}, {}, []
3663         for key, val in vals.iteritems():
3664             field = self._fields.get(key)
3665             if field:
3666                 if field.store or field.inherited:
3667                     old_vals[key] = val
3668                 if field.inverse and not field.inherited:
3669                     new_vals[key] = val
3670             else:
3671                 unknown.append(key)
3672
3673         if unknown:
3674             _logger.warning("%s.write() with unknown fields: %s", self._name, ', '.join(sorted(unknown)))
3675
3676         # write old-style fields with (low-level) method _write
3677         if old_vals:
3678             self._write(old_vals)
3679
3680         # put the values of pure new-style fields into cache, and inverse them
3681         if new_vals:
3682             for record in self:
3683                 record._cache.update(record._convert_to_cache(new_vals, update=True))
3684             for key in new_vals:
3685                 self._fields[key].determine_inverse(self)
3686
3687         return True
3688
3689     def _write(self, cr, user, ids, vals, context=None):
3690         # low-level implementation of write()
3691         if not context:
3692             context = {}
3693
3694         readonly = None
3695         self.check_field_access_rights(cr, user, 'write', vals.keys())
3696         deleted_related = defaultdict(list)
3697         for field in vals.keys():
3698             fobj = None
3699             if field in self._columns:
3700                 fobj = self._columns[field]
3701             elif field in self._inherit_fields:
3702                 fobj = self._inherit_fields[field][2]
3703             if not fobj:
3704                 continue
3705             if fobj._type in ['one2many', 'many2many'] and vals[field]:
3706                 for wtuple in vals[field]:
3707                     if isinstance(wtuple, (tuple, list)) and wtuple[0] == 2:
3708                         deleted_related[fobj._obj].append(wtuple[1])
3709             groups = fobj.write
3710
3711             if groups:
3712                 edit = False
3713                 for group in groups:
3714                     module = group.split(".")[0]
3715                     grp = group.split(".")[1]
3716                     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", \
3717                                (grp, module, 'res.groups', user))
3718                     readonly = cr.fetchall()
3719                     if readonly[0][0] >= 1:
3720                         edit = True
3721                         break
3722
3723                 if not edit:
3724                     vals.pop(field)
3725
3726         result = self._store_get_values(cr, user, ids, vals.keys(), context) or []
3727
3728         # for recomputing new-style fields
3729         recs = self.browse(cr, user, ids, context)
3730         modified_fields = list(vals)
3731         if self._log_access:
3732             modified_fields += ['write_date', 'write_uid']
3733         recs.modified(modified_fields)
3734
3735         parents_changed = []
3736         parent_order = self._parent_order or self._order
3737         if self._parent_store and (self._parent_name in vals) and not context.get('defer_parent_store_computation'):
3738             # The parent_left/right computation may take up to
3739             # 5 seconds. No need to recompute the values if the
3740             # parent is the same.
3741             # Note: to respect parent_order, nodes must be processed in
3742             # order, so ``parents_changed`` must be ordered properly.
3743             parent_val = vals[self._parent_name]
3744             if parent_val:
3745                 query = "SELECT id FROM %s WHERE id IN %%s AND (%s != %%s OR %s IS NULL) ORDER BY %s" % \
3746                                 (self._table, self._parent_name, self._parent_name, parent_order)
3747                 cr.execute(query, (tuple(ids), parent_val))
3748             else:
3749                 query = "SELECT id FROM %s WHERE id IN %%s AND (%s IS NOT NULL) ORDER BY %s" % \
3750                                 (self._table, self._parent_name, parent_order)
3751                 cr.execute(query, (tuple(ids),))
3752             parents_changed = map(operator.itemgetter(0), cr.fetchall())
3753
3754         upd0 = []
3755         upd1 = []
3756         upd_todo = []
3757         updend = []
3758         direct = []
3759         totranslate = context.get('lang', False) and (context['lang'] != 'en_US')
3760         for field in vals:
3761             field_column = self._all_columns.get(field) and self._all_columns.get(field).column
3762             if field_column and field_column.deprecated:
3763                 _logger.warning('Field %s.%s is deprecated: %s', self._name, field, field_column.deprecated)
3764             if field in self._columns:
3765                 if self._columns[field]._classic_write and not (hasattr(self._columns[field], '_fnct_inv')):
3766                     if (not totranslate) or not self._columns[field].translate:
3767                         upd0.append('"'+field+'"='+self._columns[field]._symbol_set[0])
3768                         upd1.append(self._columns[field]._symbol_set[1](vals[field]))
3769                     direct.append(field)
3770                 else:
3771                     upd_todo.append(field)
3772             else:
3773                 updend.append(field)
3774             if field in self._columns \
3775                     and hasattr(self._columns[field], 'selection') \
3776                     and vals[field]:
3777                 self._check_selection_field_value(cr, user, field, vals[field], context=context)
3778
3779         if self._log_access:
3780             upd0.append('write_uid=%s')
3781             upd0.append("write_date=(now() at time zone 'UTC')")
3782             upd1.append(user)
3783             direct.append('write_uid')
3784             direct.append('write_date')
3785
3786         if len(upd0):
3787             self.check_access_rule(cr, user, ids, 'write', context=context)
3788             for sub_ids in cr.split_for_in_conditions(ids):
3789                 cr.execute('update ' + self._table + ' set ' + ','.join(upd0) + ' ' \
3790                            'where id IN %s', upd1 + [sub_ids])
3791                 if cr.rowcount != len(sub_ids):
3792                     raise MissingError(_('One of the records you are trying to modify has already been deleted (Document type: %s).') % self._description)
3793
3794             if totranslate:
3795                 # TODO: optimize
3796                 for f in direct:
3797                     if self._columns[f].translate:
3798                         src_trans = self.pool[self._name].read(cr, user, ids, [f])[0][f]
3799                         if not src_trans:
3800                             src_trans = vals[f]
3801                             # Inserting value to DB
3802                             context_wo_lang = dict(context, lang=None)
3803                             self.write(cr, user, ids, {f: vals[f]}, context=context_wo_lang)
3804                         self.pool.get('ir.translation')._set_ids(cr, user, self._name+','+f, 'model', context['lang'], ids, vals[f], src_trans)
3805
3806         # invalidate and mark new-style fields to recompute; do this before
3807         # setting other fields, because it can require the value of computed
3808         # fields, e.g., a one2many checking constraints on records
3809         recs.modified(direct)
3810
3811         # call the 'set' method of fields which are not classic_write
3812         upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
3813
3814         # default element in context must be removed when call a one2many or many2many
3815         rel_context = context.copy()
3816         for c in context.items():
3817             if c[0].startswith('default_'):
3818                 del rel_context[c[0]]
3819
3820         for field in upd_todo:
3821             for id in ids:
3822                 result += self._columns[field].set(cr, self, id, field, vals[field], user, context=rel_context) or []
3823
3824         # for recomputing new-style fields
3825         recs.modified(upd_todo)
3826
3827         unknown_fields = updend[:]
3828         for table in self._inherits:
3829             col = self._inherits[table]
3830             nids = []
3831             for sub_ids in cr.split_for_in_conditions(ids):
3832                 cr.execute('select distinct "'+col+'" from "'+self._table+'" ' \
3833                            'where id IN %s', (sub_ids,))
3834                 nids.extend([x[0] for x in cr.fetchall()])
3835
3836             v = {}
3837             for val in updend:
3838                 if self._inherit_fields[val][0] == table:
3839                     v[val] = vals[val]
3840                     unknown_fields.remove(val)
3841             if v:
3842                 self.pool[table].write(cr, user, nids, v, context)
3843
3844         if unknown_fields:
3845             _logger.warning(
3846                 'No such field(s) in model %s: %s.',
3847                 self._name, ', '.join(unknown_fields))
3848
3849         # check Python constraints
3850         recs._validate_fields(vals)
3851
3852         # TODO: use _order to set dest at the right position and not first node of parent
3853         # We can't defer parent_store computation because the stored function
3854         # fields that are computer may refer (directly or indirectly) to
3855         # parent_left/right (via a child_of domain)
3856         if parents_changed:
3857             if self.pool._init:
3858                 self.pool._init_parent[self._name] = True
3859             else:
3860                 order = self._parent_order or self._order
3861                 parent_val = vals[self._parent_name]
3862                 if parent_val:
3863                     clause, params = '%s=%%s' % (self._parent_name,), (parent_val,)
3864                 else:
3865                     clause, params = '%s IS NULL' % (self._parent_name,), ()
3866
3867                 for id in parents_changed:
3868                     cr.execute('SELECT parent_left, parent_right FROM %s WHERE id=%%s' % (self._table,), (id,))
3869                     pleft, pright = cr.fetchone()
3870                     distance = pright - pleft + 1
3871
3872                     # Positions of current siblings, to locate proper insertion point;
3873                     # this can _not_ be fetched outside the loop, as it needs to be refreshed
3874                     # after each update, in case several nodes are sequentially inserted one
3875                     # next to the other (i.e computed incrementally)
3876                     cr.execute('SELECT parent_right, id FROM %s WHERE %s ORDER BY %s' % (self._table, clause, parent_order), params)
3877                     parents = cr.fetchall()
3878
3879                     # Find Position of the element
3880                     position = None
3881                     for (parent_pright, parent_id) in parents:
3882                         if parent_id == id:
3883                             break
3884                         position = parent_pright and parent_pright + 1 or 1
3885
3886                     # It's the first node of the parent
3887                     if not position:
3888                         if not parent_val:
3889                             position = 1
3890                         else:
3891                             cr.execute('select parent_left from '+self._table+' where id=%s', (parent_val,))
3892                             position = cr.fetchone()[0] + 1
3893
3894                     if pleft < position <= pright:
3895                         raise except_orm(_('UserError'), _('Recursivity Detected.'))
3896
3897                     if pleft < position:
3898                         cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
3899                         cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
3900                         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))
3901                     else:
3902                         cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
3903                         cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
3904                         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))
3905                     recs.invalidate_cache(['parent_left', 'parent_right'])
3906
3907         result += self._store_get_values(cr, user, ids, vals.keys(), context)
3908         result.sort()
3909
3910         done = {}
3911         for order, model_name, ids_to_update, fields_to_recompute in result:
3912             key = (model_name, tuple(fields_to_recompute))
3913             done.setdefault(key, {})
3914             # avoid to do several times the same computation
3915             todo = []
3916             for id in ids_to_update:
3917                 if id not in done[key]:
3918                     done[key][id] = True
3919                     if id not in deleted_related[model_name]:
3920                         todo.append(id)
3921             self.pool[model_name]._store_set_values(cr, user, todo, fields_to_recompute, context)
3922
3923         # recompute new-style fields
3924         if context.get('recompute', True):
3925             recs.recompute()
3926
3927         self.step_workflow(cr, user, ids, context=context)
3928         return True
3929
3930     #
3931     # TODO: Should set perm to user.xxx
3932     #
3933     @api.model
3934     @api.returns('self', lambda value: value.id)
3935     def create(self, vals):
3936         """ create(vals) -> record
3937
3938         Creates a new record for the model.
3939
3940         The new record is initialized using the values from ``vals`` and
3941         if necessary those from :meth:`~.default_get`.
3942
3943         :param dict vals:
3944             values for the model's fields, as a dictionary::
3945
3946                 {'field_name': field_value, ...}
3947
3948             see :meth:`~.write` for details
3949         :return: new record created
3950         :raise AccessError: * if user has no create rights on the requested object
3951                             * if user tries to bypass access rules for create on the requested object
3952         :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
3953         :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)
3954         """
3955         self.check_access_rights('create')
3956
3957         # add missing defaults, and drop fields that may not be set by user
3958         vals = self._add_missing_default_values(vals)
3959         for field in itertools.chain(MAGIC_COLUMNS, ('parent_left', 'parent_right')):
3960             vals.pop(field, None)
3961
3962         # split up fields into old-style and pure new-style ones
3963         old_vals, new_vals, unknown = {}, {}, []
3964         for key, val in vals.iteritems():
3965             field = self._fields.get(key)
3966             if field:
3967                 if field.store or field.inherited:
3968                     old_vals[key] = val
3969                 if field.inverse and not field.inherited:
3970                     new_vals[key] = val
3971             else:
3972                 unknown.append(key)
3973
3974         if unknown:
3975             _logger.warning("%s.create() with unknown fields: %s", self._name, ', '.join(sorted(unknown)))
3976
3977         # create record with old-style fields
3978         record = self.browse(self._create(old_vals))
3979
3980         # put the values of pure new-style fields into cache, and inverse them
3981         record._cache.update(record._convert_to_cache(new_vals))
3982         for key in new_vals:
3983             self._fields[key].determine_inverse(record)
3984
3985         return record
3986
3987     def _create(self, cr, user, vals, context=None):
3988         # low-level implementation of create()
3989         if not context:
3990             context = {}
3991
3992         if self.is_transient():
3993             self._transient_vacuum(cr, user)
3994
3995         tocreate = {}
3996         for v in self._inherits:
3997             if self._inherits[v] not in vals:
3998                 tocreate[v] = {}
3999             else:
4000                 tocreate[v] = {'id': vals[self._inherits[v]]}
4001
4002         updates = [
4003             # list of column assignments defined as tuples like:
4004             #   (column_name, format_string, column_value)
4005             #   (column_name, sql_formula)
4006             # Those tuples will be used by the string formatting for the INSERT
4007             # statement below.
4008             ('id', "nextval('%s')" % self._sequence),
4009         ]
4010
4011         upd_todo = []
4012         unknown_fields = []
4013         for v in vals.keys():
4014             if v in self._inherit_fields and v not in self._columns:
4015                 (table, col, col_detail, original_parent) = self._inherit_fields[v]
4016                 tocreate[table][v] = vals[v]
4017                 del vals[v]
4018             else:
4019                 if (v not in self._inherit_fields) and (v not in self._columns):
4020                     del vals[v]
4021                     unknown_fields.append(v)
4022         if unknown_fields:
4023             _logger.warning(
4024                 'No such field(s) in model %s: %s.',
4025                 self._name, ', '.join(unknown_fields))
4026
4027         for table in tocreate:
4028             if self._inherits[table] in vals:
4029                 del vals[self._inherits[table]]
4030
4031             record_id = tocreate[table].pop('id', None)
4032
4033             if record_id is None or not record_id:
4034                 record_id = self.pool[table].create(cr, user, tocreate[table], context=context)
4035             else:
4036                 self.pool[table].write(cr, user, [record_id], tocreate[table], context=context)
4037
4038             updates.append((self._inherits[table], '%s', record_id))
4039
4040         #Start : Set bool fields to be False if they are not touched(to make search more powerful)
4041         bool_fields = [x for x in self._columns.keys() if self._columns[x]._type=='boolean']
4042
4043         for bool_field in bool_fields:
4044             if bool_field not in vals:
4045                 vals[bool_field] = False
4046         #End
4047         for field in vals.keys():
4048             fobj = None
4049             if field in self._columns:
4050                 fobj = self._columns[field]
4051             else:
4052                 fobj = self._inherit_fields[field][2]
4053             if not fobj:
4054                 continue
4055             groups = fobj.write
4056             if groups:
4057                 edit = False
4058                 for group in groups:
4059                     module = group.split(".")[0]
4060                     grp = group.split(".")[1]
4061                     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" % \
4062                                (grp, module, 'res.groups', user))
4063                     readonly = cr.fetchall()
4064                     if readonly[0][0] >= 1:
4065                         edit = True
4066                         break
4067                     elif readonly[0][0] == 0:
4068                         edit = False
4069                     else:
4070                         edit = False
4071
4072                 if not edit:
4073                     vals.pop(field)
4074         for field in vals:
4075             current_field = self._columns[field]
4076             if current_field._classic_write:
4077                 updates.append((field, '%s', current_field._symbol_set[1](vals[field])))
4078
4079                 #for the function fields that receive a value, we set them directly in the database
4080                 #(they may be required), but we also need to trigger the _fct_inv()
4081                 if (hasattr(current_field, '_fnct_inv')) and not isinstance(current_field, fields.related):
4082                     #TODO: this way to special case the related fields is really creepy but it shouldn't be changed at
4083                     #one week of the release candidate. It seems the only good way to handle correctly this is to add an
4084                     #attribute to make a field `really readonly´ and thus totally ignored by the create()... otherwise
4085                     #if, for example, the related has a default value (for usability) then the fct_inv is called and it
4086                     #may raise some access rights error. Changing this is a too big change for now, and is thus postponed
4087                     #after the release but, definitively, the behavior shouldn't be different for related and function
4088                     #fields.
4089                     upd_todo.append(field)
4090             else:
4091                 #TODO: this `if´ statement should be removed because there is no good reason to special case the fields
4092                 #related. See the above TODO comment for further explanations.
4093                 if not isinstance(current_field, fields.related):
4094                     upd_todo.append(field)
4095             if field in self._columns \
4096                     and hasattr(current_field, 'selection') \
4097                     and vals[field]:
4098                 self._check_selection_field_value(cr, user, field, vals[field], context=context)
4099         if self._log_access:
4100             updates.append(('create_uid', '%s', user))
4101             updates.append(('write_uid', '%s', user))
4102             updates.append(('create_date', "(now() at time zone 'UTC')"))
4103             updates.append(('write_date', "(now() at time zone 'UTC')"))
4104
4105         # the list of tuples used in this formatting corresponds to
4106         # tuple(field_name, format, value)
4107         # In some case, for example (id, create_date, write_date) we does not
4108         # need to read the third value of the tuple, because the real value is
4109         # encoded in the second value (the format).
4110         cr.execute(
4111             """INSERT INTO "%s" (%s) VALUES(%s) RETURNING id""" % (
4112                 self._table,
4113                 ', '.join('"%s"' % u[0] for u in updates),
4114                 ', '.join(u[1] for u in updates)
4115             ),
4116             tuple([u[2] for u in updates if len(u) > 2])
4117         )
4118
4119         id_new, = cr.fetchone()
4120         recs = self.browse(cr, user, id_new, context)
4121
4122         if self._parent_store and not context.get('defer_parent_store_computation'):
4123             if self.pool._init:
4124                 self.pool._init_parent[self._name] = True
4125             else:
4126                 parent = vals.get(self._parent_name, False)
4127                 if parent:
4128                     cr.execute('select parent_right from '+self._table+' where '+self._parent_name+'=%s order by '+(self._parent_order or self._order), (parent,))
4129                     pleft_old = None
4130                     result_p = cr.fetchall()
4131                     for (pleft,) in result_p:
4132                         if not pleft:
4133                             break
4134                         pleft_old = pleft
4135                     if not pleft_old:
4136                         cr.execute('select parent_left from '+self._table+' where id=%s', (parent,))
4137                         pleft_old = cr.fetchone()[0]
4138                     pleft = pleft_old
4139                 else:
4140                     cr.execute('select max(parent_right) from '+self._table)
4141                     pleft = cr.fetchone()[0] or 0
4142                 cr.execute('update '+self._table+' set parent_left=parent_left+2 where parent_left>%s', (pleft,))
4143                 cr.execute('update '+self._table+' set parent_right=parent_right+2 where parent_right>%s', (pleft,))
4144                 cr.execute('update '+self._table+' set parent_left=%s,parent_right=%s where id=%s', (pleft+1, pleft+2, id_new))
4145                 recs.invalidate_cache(['parent_left', 'parent_right'])
4146
4147         # invalidate and mark new-style fields to recompute; do this before
4148         # setting other fields, because it can require the value of computed
4149         # fields, e.g., a one2many checking constraints on records
4150         recs.modified([u[0] for u in updates])
4151
4152         # call the 'set' method of fields which are not classic_write
4153         upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
4154
4155         # default element in context must be remove when call a one2many or many2many
4156         rel_context = context.copy()
4157         for c in context.items():
4158             if c[0].startswith('default_'):
4159                 del rel_context[c[0]]
4160
4161         result = []
4162         for field in upd_todo:
4163             result += self._columns[field].set(cr, self, id_new, field, vals[field], user, rel_context) or []
4164
4165         # for recomputing new-style fields
4166         recs.modified(upd_todo)
4167
4168         # check Python constraints
4169         recs._validate_fields(vals)
4170
4171         if context.get('recompute', True):
4172             result += self._store_get_values(cr, user, [id_new],
4173                 list(set(vals.keys() + self._inherits.values())),
4174                 context)
4175             result.sort()
4176             done = []
4177             for order, model_name, ids, fields2 in result:
4178                 if not (model_name, ids, fields2) in done:
4179                     self.pool[model_name]._store_set_values(cr, user, ids, fields2, context)
4180                     done.append((model_name, ids, fields2))
4181             # recompute new-style fields
4182             recs.recompute()
4183
4184         if self._log_create and context.get('recompute', True):
4185             message = self._description + \
4186                 " '" + \
4187                 self.name_get(cr, user, [id_new], context=context)[0][1] + \
4188                 "' " + _("created.")
4189             self.log(cr, user, id_new, message, True, context=context)
4190
4191         self.check_access_rule(cr, user, [id_new], 'create', context=context)
4192         self.create_workflow(cr, user, [id_new], context=context)
4193         return id_new
4194
4195     def _store_get_values(self, cr, uid, ids, fields, context):
4196         """Returns an ordered list of fields.function to call due to
4197            an update operation on ``fields`` of records with ``ids``,
4198            obtained by calling the 'store' triggers of these fields,
4199            as setup by their 'store' attribute.
4200
4201            :return: [(priority, model_name, [record_ids,], [function_fields,])]
4202         """
4203         if fields is None: fields = []
4204         stored_functions = self.pool._store_function.get(self._name, [])
4205
4206         # use indexed names for the details of the stored_functions:
4207         model_name_, func_field_to_compute_, target_ids_func_, trigger_fields_, priority_ = range(5)
4208
4209         # only keep store triggers that should be triggered for the ``fields``
4210         # being written to.
4211         triggers_to_compute = (
4212             f for f in stored_functions
4213             if not f[trigger_fields_] or set(fields).intersection(f[trigger_fields_])
4214         )
4215
4216         to_compute_map = {}
4217         target_id_results = {}
4218         for store_trigger in triggers_to_compute:
4219             target_func_id_ = id(store_trigger[target_ids_func_])
4220             if target_func_id_ not in target_id_results:
4221                 # use admin user for accessing objects having rules defined on store fields
4222                 target_id_results[target_func_id_] = [i for i in store_trigger[target_ids_func_](self, cr, SUPERUSER_ID, ids, context) if i]
4223             target_ids = target_id_results[target_func_id_]
4224
4225             # the compound key must consider the priority and model name
4226             key = (store_trigger[priority_], store_trigger[model_name_])
4227             for target_id in target_ids:
4228                 to_compute_map.setdefault(key, {}).setdefault(target_id,set()).add(tuple(store_trigger))
4229
4230         # Here to_compute_map looks like:
4231         # { (10, 'model_a') : { target_id1: [ (trigger_1_tuple, trigger_2_tuple) ], ... }
4232         #   (20, 'model_a') : { target_id2: [ (trigger_3_tuple, trigger_4_tuple) ], ... }
4233         #   (99, 'model_a') : { target_id1: [ (trigger_5_tuple, trigger_6_tuple) ], ... }
4234         # }
4235
4236         # Now we need to generate the batch function calls list
4237         # call_map =
4238         #   { (10, 'model_a') : [(10, 'model_a', [record_ids,], [function_fields,])] }
4239         call_map = {}
4240         for ((priority,model), id_map) in to_compute_map.iteritems():
4241             trigger_ids_maps = {}
4242             # function_ids_maps =
4243             #   { (function_1_tuple, function_2_tuple) : [target_id1, target_id2, ..] }
4244             for target_id, triggers in id_map.iteritems():
4245                 trigger_ids_maps.setdefault(tuple(triggers), []).append(target_id)
4246             for triggers, target_ids in trigger_ids_maps.iteritems():
4247                 call_map.setdefault((priority,model),[]).append((priority, model, target_ids,
4248                                                                  [t[func_field_to_compute_] for t in triggers]))
4249         result = []
4250         if call_map:
4251             result = reduce(operator.add, (call_map[k] for k in sorted(call_map)))
4252         return result
4253
4254     def _store_set_values(self, cr, uid, ids, fields, context):
4255         """Calls the fields.function's "implementation function" for all ``fields``, on records with ``ids`` (taking care of
4256            respecting ``multi`` attributes), and stores the resulting values in the database directly."""
4257         if not ids:
4258             return True
4259         field_flag = False
4260         field_dict = {}
4261         if self._log_access:
4262             cr.execute('select id,write_date from '+self._table+' where id IN %s', (tuple(ids),))
4263             res = cr.fetchall()
4264             for r in res:
4265                 if r[1]:
4266                     field_dict.setdefault(r[0], [])
4267                     res_date = time.strptime((r[1])[:19], '%Y-%m-%d %H:%M:%S')
4268                     write_date = datetime.datetime.fromtimestamp(time.mktime(res_date))
4269                     for i in self.pool._store_function.get(self._name, []):
4270                         if i[5]:
4271                             up_write_date = write_date + datetime.timedelta(hours=i[5])
4272                             if datetime.datetime.now() < up_write_date:
4273                                 if i[1] in fields:
4274                                     field_dict[r[0]].append(i[1])
4275                                     if not field_flag:
4276                                         field_flag = True
4277         todo = {}
4278         keys = []
4279         for f in fields:
4280             if self._columns[f]._multi not in keys:
4281                 keys.append(self._columns[f]._multi)
4282             todo.setdefault(self._columns[f]._multi, [])
4283             todo[self._columns[f]._multi].append(f)
4284         for key in keys:
4285             val = todo[key]
4286             if key:
4287                 # use admin user for accessing objects having rules defined on store fields
4288                 result = self._columns[val[0]].get(cr, self, ids, val, SUPERUSER_ID, context=context)
4289                 for id, value in result.items():
4290                     if field_flag:
4291                         for f in value.keys():
4292                             if f in field_dict[id]:
4293                                 value.pop(f)
4294                     upd0 = []
4295                     upd1 = []
4296                     for v in value:
4297                         if v not in val:
4298                             continue
4299                         if self._columns[v]._type == 'many2one':
4300                             try:
4301                                 value[v] = value[v][0]
4302                             except:
4303                                 pass
4304                         upd0.append('"'+v+'"='+self._columns[v]._symbol_set[0])
4305                         upd1.append(self._columns[v]._symbol_set[1](value[v]))
4306                     upd1.append(id)
4307                     if upd0 and upd1:
4308                         cr.execute('update "' + self._table + '" set ' + \
4309                             ','.join(upd0) + ' where id = %s', upd1)
4310
4311             else:
4312                 for f in val:
4313                     # use admin user for accessing objects having rules defined on store fields
4314                     result = self._columns[f].get(cr, self, ids, f, SUPERUSER_ID, context=context)
4315                     for r in result.keys():
4316                         if field_flag:
4317                             if r in field_dict.keys():
4318                                 if f in field_dict[r]:
4319                                     result.pop(r)
4320                     for id, value in result.items():
4321                         if self._columns[f]._type == 'many2one':
4322                             try:
4323                                 value = value[0]
4324                             except:
4325                                 pass
4326                         cr.execute('update "' + self._table + '" set ' + \
4327                             '"'+f+'"='+self._columns[f]._symbol_set[0] + ' where id = %s', (self._columns[f]._symbol_set[1](value), id))
4328
4329         # invalidate and mark new-style fields to recompute
4330         self.browse(cr, uid, ids, context).modified(fields)
4331
4332         return True
4333
4334     # TODO: ameliorer avec NULL
4335     def _where_calc(self, cr, user, domain, active_test=True, context=None):
4336         """Computes the WHERE clause needed to implement an OpenERP domain.
4337         :param domain: the domain to compute
4338         :type domain: list
4339         :param active_test: whether the default filtering of records with ``active``
4340                             field set to ``False`` should be applied.
4341         :return: the query expressing the given domain as provided in domain
4342         :rtype: osv.query.Query
4343         """
4344         if not context:
4345             context = {}
4346         domain = domain[:]
4347         # if the object has a field named 'active', filter out all inactive
4348         # records unless they were explicitely asked for
4349         if 'active' in self._all_columns and (active_test and context.get('active_test', True)):
4350             if domain:
4351                 # the item[0] trick below works for domain items and '&'/'|'/'!'
4352                 # operators too
4353                 if not any(item[0] == 'active' for item in domain):
4354                     domain.insert(0, ('active', '=', 1))
4355             else:
4356                 domain = [('active', '=', 1)]
4357
4358         if domain:
4359             e = expression.expression(cr, user, domain, self, context)
4360             tables = e.get_tables()
4361             where_clause, where_params = e.to_sql()
4362             where_clause = where_clause and [where_clause] or []
4363         else:
4364             where_clause, where_params, tables = [], [], ['"%s"' % self._table]
4365
4366         return Query(tables, where_clause, where_params)
4367
4368     def _check_qorder(self, word):
4369         if not regex_order.match(word):
4370             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)'))
4371         return True
4372
4373     def _apply_ir_rules(self, cr, uid, query, mode='read', context=None):
4374         """Add what's missing in ``query`` to implement all appropriate ir.rules
4375           (using the ``model_name``'s rules or the current model's rules if ``model_name`` is None)
4376
4377            :param query: the current query object
4378         """
4379         if uid == SUPERUSER_ID:
4380             return
4381
4382         def apply_rule(added_clause, added_params, added_tables, parent_model=None):
4383             """ :param parent_model: name of the parent model, if the added
4384                     clause comes from a parent model
4385             """
4386             if added_clause:
4387                 if parent_model:
4388                     # as inherited rules are being applied, we need to add the missing JOIN
4389                     # to reach the parent table (if it was not JOINed yet in the query)
4390                     parent_alias = self._inherits_join_add(self, parent_model, query)
4391                     # inherited rules are applied on the external table -> need to get the alias and replace
4392                     parent_table = self.pool[parent_model]._table
4393                     added_clause = [clause.replace('"%s"' % parent_table, '"%s"' % parent_alias) for clause in added_clause]
4394                     # change references to parent_table to parent_alias, because we now use the alias to refer to the table
4395                     new_tables = []
4396                     for table in added_tables:
4397                         # table is just a table name -> switch to the full alias
4398                         if table == '"%s"' % parent_table:
4399                             new_tables.append('"%s" as "%s"' % (parent_table, parent_alias))
4400                         # table is already a full statement -> replace reference to the table to its alias, is correct with the way aliases are generated
4401                         else:
4402                             new_tables.append(table.replace('"%s"' % parent_table, '"%s"' % parent_alias))
4403                     added_tables = new_tables
4404                 query.where_clause += added_clause
4405                 query.where_clause_params += added_params
4406                 for table in added_tables:
4407                     if table not in query.tables:
4408                         query.tables.append(table)
4409                 return True
4410             return False
4411
4412         # apply main rules on the object
4413         rule_obj = self.pool.get('ir.rule')
4414         rule_where_clause, rule_where_clause_params, rule_tables = rule_obj.domain_get(cr, uid, self._name, mode, context=context)
4415         apply_rule(rule_where_clause, rule_where_clause_params, rule_tables)
4416
4417         # apply ir.rules from the parents (through _inherits)
4418         for inherited_model in self._inherits:
4419             rule_where_clause, rule_where_clause_params, rule_tables = rule_obj.domain_get(cr, uid, inherited_model, mode, context=context)
4420             apply_rule(rule_where_clause, rule_where_clause_params, rule_tables,
4421                         parent_model=inherited_model)
4422
4423     def _generate_m2o_order_by(self, order_field, query):
4424         """
4425         Add possibly missing JOIN to ``query`` and generate the ORDER BY clause for m2o fields,
4426         either native m2o fields or function/related fields that are stored, including
4427         intermediate JOINs for inheritance if required.
4428
4429         :return: the qualified field name to use in an ORDER BY clause to sort by ``order_field``
4430         """
4431         if order_field not in self._columns and order_field in self._inherit_fields:
4432             # also add missing joins for reaching the table containing the m2o field
4433             qualified_field = self._inherits_join_calc(order_field, query)
4434             order_field_column = self._inherit_fields[order_field][2]
4435         else:
4436             qualified_field = '"%s"."%s"' % (self._table, order_field)
4437             order_field_column = self._columns[order_field]
4438
4439         assert order_field_column._type == 'many2one', 'Invalid field passed to _generate_m2o_order_by()'
4440         if not order_field_column._classic_write and not getattr(order_field_column, 'store', False):
4441             _logger.debug("Many2one function/related fields must be stored " \
4442                 "to be used as ordering fields! Ignoring sorting for %s.%s",
4443                 self._name, order_field)
4444             return
4445
4446         # figure out the applicable order_by for the m2o
4447         dest_model = self.pool[order_field_column._obj]
4448         m2o_order = dest_model._order
4449         if not regex_order.match(m2o_order):
4450             # _order is complex, can't use it here, so we default to _rec_name
4451             m2o_order = dest_model._rec_name
4452         else:
4453             # extract the field names, to be able to qualify them and add desc/asc
4454             m2o_order_list = []
4455             for order_part in m2o_order.split(","):
4456                 m2o_order_list.append(order_part.strip().split(" ", 1)[0].strip())
4457             m2o_order = m2o_order_list
4458
4459         # Join the dest m2o table if it's not joined yet. We use [LEFT] OUTER join here
4460         # as we don't want to exclude results that have NULL values for the m2o
4461         src_table, src_field = qualified_field.replace('"', '').split('.', 1)
4462         dst_alias, dst_alias_statement = query.add_join((src_table, dest_model._table, src_field, 'id', src_field), implicit=False, outer=True)
4463         qualify = lambda field: '"%s"."%s"' % (dst_alias, field)
4464         return map(qualify, m2o_order) if isinstance(m2o_order, list) else qualify(m2o_order)
4465
4466     def _generate_order_by(self, order_spec, query):
4467         """
4468         Attempt to consruct an appropriate ORDER BY clause based on order_spec, which must be
4469         a comma-separated list of valid field names, optionally followed by an ASC or DESC direction.
4470
4471         :raise" except_orm in case order_spec is malformed
4472         """
4473         order_by_clause = ''
4474         order_spec = order_spec or self._order
4475         if order_spec:
4476             order_by_elements = []
4477             self._check_qorder(order_spec)
4478             for order_part in order_spec.split(','):
4479                 order_split = order_part.strip().split(' ')
4480                 order_field = order_split[0].strip()
4481                 order_direction = order_split[1].strip() if len(order_split) == 2 else ''
4482                 order_column = None
4483                 inner_clause = None
4484                 if order_field == 'id':
4485                     order_by_elements.append('"%s"."%s" %s' % (self._table, order_field, order_direction))
4486                 elif order_field in self._columns:
4487                     order_column = self._columns[order_field]
4488                     if order_column._classic_read:
4489                         inner_clause = '"%s"."%s"' % (self._table, order_field)
4490                     elif order_column._type == 'many2one':
4491                         inner_clause = self._generate_m2o_order_by(order_field, query)
4492                     else:
4493                         continue  # ignore non-readable or "non-joinable" fields
4494                 elif order_field in self._inherit_fields:
4495                     parent_obj = self.pool[self._inherit_fields[order_field][3]]
4496                     order_column = parent_obj._columns[order_field]
4497                     if order_column._classic_read:
4498                         inner_clause = self._inherits_join_calc(order_field, query)
4499                     elif order_column._type == 'many2one':
4500                         inner_clause = self._generate_m2o_order_by(order_field, query)
4501                     else:
4502                         continue  # ignore non-readable or "non-joinable" fields
4503                 else:
4504                     raise ValueError( _("Sorting field %s not found on model %s") %( order_field, self._name))
4505                 if order_column and order_column._type == 'boolean':
4506                     inner_clause = "COALESCE(%s, false)" % inner_clause
4507                 if inner_clause:
4508                     if isinstance(inner_clause, list):
4509                         for clause in inner_clause:
4510                             order_by_elements.append("%s %s" % (clause, order_direction))
4511                     else:
4512                         order_by_elements.append("%s %s" % (inner_clause, order_direction))
4513             if order_by_elements:
4514                 order_by_clause = ",".join(order_by_elements)
4515
4516         return order_by_clause and (' ORDER BY %s ' % order_by_clause) or ''
4517
4518     def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
4519         """
4520         Private implementation of search() method, allowing specifying the uid to use for the access right check.
4521         This is useful for example when filling in the selection list for a drop-down and avoiding access rights errors,
4522         by specifying ``access_rights_uid=1`` to bypass access rights check, but not ir.rules!
4523         This is ok at the security level because this method is private and not callable through XML-RPC.
4524
4525         :param access_rights_uid: optional user ID to use when checking access rights
4526                                   (not for ir.rules, this is only for ir.model.access)
4527         """
4528         if context is None:
4529             context = {}
4530         self.check_access_rights(cr, access_rights_uid or user, 'read')
4531
4532         # For transient models, restrict acces to the current user, except for the super-user
4533         if self.is_transient() and self._log_access and user != SUPERUSER_ID:
4534             args = expression.AND(([('create_uid', '=', user)], args or []))
4535
4536         query = self._where_calc(cr, user, args, context=context)
4537         self._apply_ir_rules(cr, user, query, 'read', context=context)
4538         order_by = self._generate_order_by(order, query)
4539         from_clause, where_clause, where_clause_params = query.get_sql()
4540
4541         where_str = where_clause and (" WHERE %s" % where_clause) or ''
4542
4543         if count:
4544             # Ignore order, limit and offset when just counting, they don't make sense and could
4545             # hurt performance
4546             query_str = 'SELECT count(1) FROM ' + from_clause + where_str
4547             cr.execute(query_str, where_clause_params)
4548             res = cr.fetchone()
4549             return res[0]
4550
4551         limit_str = limit and ' limit %d' % limit or ''
4552         offset_str = offset and ' offset %d' % offset or ''
4553         query_str = 'SELECT "%s".id FROM ' % self._table + from_clause + where_str + order_by + limit_str + offset_str
4554         cr.execute(query_str, where_clause_params)
4555         res = cr.fetchall()
4556
4557         # TDE note: with auto_join, we could have several lines about the same result
4558         # i.e. a lead with several unread messages; we uniquify the result using
4559         # a fast way to do it while preserving order (http://www.peterbe.com/plog/uniqifiers-benchmark)
4560         def _uniquify_list(seq):
4561             seen = set()
4562             return [x for x in seq if x not in seen and not seen.add(x)]
4563
4564         return _uniquify_list([x[0] for x in res])
4565
4566     # returns the different values ever entered for one field
4567     # this is used, for example, in the client when the user hits enter on
4568     # a char field
4569     def distinct_field_get(self, cr, uid, field, value, args=None, offset=0, limit=None):
4570         if not args:
4571             args = []
4572         if field in self._inherit_fields:
4573             return self.pool[self._inherit_fields[field][0]].distinct_field_get(cr, uid, field, value, args, offset, limit)
4574         else:
4575             return self._columns[field].search(cr, self, args, field, value, offset, limit, uid)
4576
4577     def copy_data(self, cr, uid, id, default=None, context=None):
4578         """
4579         Copy given record's data with all its fields values
4580
4581         :param cr: database cursor
4582         :param uid: current user id
4583         :param id: id of the record to copy
4584         :param default: field values to override in the original values of the copied record
4585         :type default: dictionary
4586         :param context: context arguments, like lang, time zone
4587         :type context: dictionary
4588         :return: dictionary containing all the field values
4589         """
4590
4591         if context is None:
4592             context = {}
4593
4594         # avoid recursion through already copied records in case of circular relationship
4595         seen_map = context.setdefault('__copy_data_seen', {})
4596         if id in seen_map.setdefault(self._name, []):
4597             return
4598         seen_map[self._name].append(id)
4599
4600         if default is None:
4601             default = {}
4602         if 'state' not in default:
4603             if 'state' in self._defaults:
4604                 if callable(self._defaults['state']):
4605                     default['state'] = self._defaults['state'](self, cr, uid, context)
4606                 else:
4607                     default['state'] = self._defaults['state']
4608
4609         # build a black list of fields that should not be copied
4610         blacklist = set(MAGIC_COLUMNS + ['parent_left', 'parent_right'])
4611         def blacklist_given_fields(obj):
4612             # blacklist the fields that are given by inheritance
4613             for other, field_to_other in obj._inherits.items():
4614                 blacklist.add(field_to_other)
4615                 if field_to_other in default:
4616                     # all the fields of 'other' are given by the record: default[field_to_other],
4617                     # except the ones redefined in self
4618                     blacklist.update(set(self.pool[other]._all_columns) - set(self._columns))
4619                 else:
4620                     blacklist_given_fields(self.pool[other])
4621             # blacklist deprecated fields
4622             for name, field in obj._columns.items():
4623                 if field.deprecated:
4624                     blacklist.add(name)
4625
4626         blacklist_given_fields(self)
4627
4628
4629         fields_to_copy = dict((f,fi) for f, fi in self._all_columns.iteritems()
4630                                      if fi.column.copy
4631                                      if f not in default
4632                                      if f not in blacklist)
4633
4634         data = self.read(cr, uid, [id], fields_to_copy.keys(), context=context)
4635         if data:
4636             data = data[0]
4637         else:
4638             raise IndexError( _("Record #%d of %s not found, cannot copy!") %( id, self._name))
4639
4640         res = dict(default)
4641         for f, colinfo in fields_to_copy.iteritems():
4642             field = colinfo.column
4643             if field._type == 'many2one':
4644                 res[f] = data[f] and data[f][0]
4645             elif field._type == 'one2many':
4646                 other = self.pool[field._obj]
4647                 # duplicate following the order of the ids because we'll rely on
4648                 # it later for copying translations in copy_translation()!
4649                 lines = [other.copy_data(cr, uid, line_id, context=context) for line_id in sorted(data[f])]
4650                 # the lines are duplicated using the wrong (old) parent, but then
4651                 # are reassigned to the correct one thanks to the (0, 0, ...)
4652                 res[f] = [(0, 0, line) for line in lines if line]
4653             elif field._type == 'many2many':
4654                 res[f] = [(6, 0, data[f])]
4655             else:
4656                 res[f] = data[f]
4657
4658         return res
4659
4660     def copy_translations(self, cr, uid, old_id, new_id, context=None):
4661         if context is None:
4662             context = {}
4663
4664         # avoid recursion through already copied records in case of circular relationship
4665         seen_map = context.setdefault('__copy_translations_seen',{})
4666         if old_id in seen_map.setdefault(self._name,[]):
4667             return
4668         seen_map[self._name].append(old_id)
4669
4670         trans_obj = self.pool.get('ir.translation')
4671         # TODO it seems fields_get can be replaced by _all_columns (no need for translation)
4672         fields = self.fields_get(cr, uid, context=context)
4673
4674         for field_name, field_def in fields.items():
4675             # removing the lang to compare untranslated values
4676             context_wo_lang = dict(context, lang=None)
4677             old_record, new_record = self.browse(cr, uid, [old_id, new_id], context=context_wo_lang)
4678             # we must recursively copy the translations for o2o and o2m
4679             if field_def['type'] == 'one2many':
4680                 target_obj = self.pool[field_def['relation']]
4681                 # here we rely on the order of the ids to match the translations
4682                 # as foreseen in copy_data()
4683                 old_children = sorted(r.id for r in old_record[field_name])
4684                 new_children = sorted(r.id for r in new_record[field_name])
4685                 for (old_child, new_child) in zip(old_children, new_children):
4686                     target_obj.copy_translations(cr, uid, old_child, new_child, context=context)
4687             # and for translatable fields we keep them for copy
4688             elif field_def.get('translate'):
4689                 if field_name in self._columns:
4690                     trans_name = self._name + "," + field_name
4691                     target_id = new_id
4692                     source_id = old_id
4693                 elif field_name in self._inherit_fields:
4694                     trans_name = self._inherit_fields[field_name][0] + "," + field_name
4695                     # get the id of the parent record to set the translation
4696                     inherit_field_name = self._inherit_fields[field_name][1]
4697                     target_id = new_record[inherit_field_name].id
4698                     source_id = old_record[inherit_field_name].id
4699                 else:
4700                     continue
4701
4702                 trans_ids = trans_obj.search(cr, uid, [
4703                         ('name', '=', trans_name),
4704                         ('res_id', '=', source_id)
4705                 ])
4706                 user_lang = context.get('lang')
4707                 for record in trans_obj.read(cr, uid, trans_ids, context=context):
4708                     del record['id']
4709                     # remove source to avoid triggering _set_src
4710                     del record['source']
4711                     record.update({'res_id': target_id})
4712                     if user_lang and user_lang == record['lang']:
4713                         # 'source' to force the call to _set_src
4714                         # 'value' needed if value is changed in copy(), want to see the new_value
4715                         record['source'] = old_record[field_name]
4716                         record['value'] = new_record[field_name]
4717                     trans_obj.create(cr, uid, record, context=context)
4718
4719     @api.returns('self', lambda value: value.id)
4720     def copy(self, cr, uid, id, default=None, context=None):
4721         """ copy(default=None)
4722
4723         Duplicate record with given id updating it with default values
4724
4725         :param dict default: dictionary of field values to override in the
4726                original values of the copied record, e.g: ``{'field_name': overriden_value, ...}``
4727         :returns: new record
4728
4729         """
4730         if context is None:
4731             context = {}
4732         context = context.copy()
4733         data = self.copy_data(cr, uid, id, default, context)
4734         new_id = self.create(cr, uid, data, context)
4735         self.copy_translations(cr, uid, id, new_id, context)
4736         return new_id
4737
4738     @api.multi
4739     @api.returns('self')
4740     def exists(self):
4741         """  exists() -> records
4742
4743         Returns the subset of records in `self` that exist, and marks deleted
4744         records as such in cache. It can be used as a test on records::
4745
4746             if record.exists():
4747                 ...
4748
4749         By convention, new records are returned as existing.
4750         """
4751         ids = filter(None, self._ids)           # ids to check in database
4752         if not ids:
4753             return self
4754         query = """SELECT id FROM "%s" WHERE id IN %%s""" % self._table
4755         self._cr.execute(query, (ids,))
4756         ids = ([r[0] for r in self._cr.fetchall()] +    # ids in database
4757                [id for id in self._ids if not id])      # new ids
4758         existing = self.browse(ids)
4759         if len(existing) < len(self):
4760             # mark missing records in cache with a failed value
4761             exc = MissingError(_("Record does not exist or has been deleted."))
4762             (self - existing)._cache.update(FailedValue(exc))
4763         return existing
4764
4765     def check_recursion(self, cr, uid, ids, context=None, parent=None):
4766         _logger.warning("You are using deprecated %s.check_recursion(). Please use the '_check_recursion()' instead!" % \
4767                         self._name)
4768         assert parent is None or parent in self._columns or parent in self._inherit_fields,\
4769                     "The 'parent' parameter passed to check_recursion() must be None or a valid field name"
4770         return self._check_recursion(cr, uid, ids, context, parent)
4771
4772     def _check_recursion(self, cr, uid, ids, context=None, parent=None):
4773         """
4774         Verifies that there is no loop in a hierarchical structure of records,
4775         by following the parent relationship using the **parent** field until a loop
4776         is detected or until a top-level record is found.
4777
4778         :param cr: database cursor
4779         :param uid: current user id
4780         :param ids: list of ids of records to check
4781         :param parent: optional parent field name (default: ``self._parent_name = parent_id``)
4782         :return: **True** if the operation can proceed safely, or **False** if an infinite loop is detected.
4783         """
4784         if not parent:
4785             parent = self._parent_name
4786
4787         # must ignore 'active' flag, ir.rules, etc. => direct SQL query
4788         query = 'SELECT "%s" FROM "%s" WHERE id = %%s' % (parent, self._table)
4789         for id in ids:
4790             current_id = id
4791             while current_id is not None:
4792                 cr.execute(query, (current_id,))
4793                 result = cr.fetchone()
4794                 current_id = result[0] if result else None
4795                 if current_id == id:
4796                     return False
4797         return True
4798
4799     def _check_m2m_recursion(self, cr, uid, ids, field_name):
4800         """
4801         Verifies that there is no loop in a hierarchical structure of records,
4802         by following the parent relationship using the **parent** field until a loop
4803         is detected or until a top-level record is found.
4804
4805         :param cr: database cursor
4806         :param uid: current user id
4807         :param ids: list of ids of records to check
4808         :param field_name: field to check
4809         :return: **True** if the operation can proceed safely, or **False** if an infinite loop is detected.
4810         """
4811
4812         field = self._all_columns.get(field_name)
4813         field = field.column if field else None
4814         if not field or field._type != 'many2many' or field._obj != self._name:
4815             # field must be a many2many on itself
4816             raise ValueError('invalid field_name: %r' % (field_name,))
4817
4818         query = 'SELECT distinct "%s" FROM "%s" WHERE "%s" IN %%s' % (field._id2, field._rel, field._id1)
4819         ids_parent = ids[:]
4820         while ids_parent:
4821             ids_parent2 = []
4822             for i in range(0, len(ids_parent), cr.IN_MAX):
4823                 j = i + cr.IN_MAX
4824                 sub_ids_parent = ids_parent[i:j]
4825                 cr.execute(query, (tuple(sub_ids_parent),))
4826                 ids_parent2.extend(filter(None, map(lambda x: x[0], cr.fetchall())))
4827             ids_parent = ids_parent2
4828             for i in ids_parent:
4829                 if i in ids:
4830                     return False
4831         return True
4832
4833     def _get_external_ids(self, cr, uid, ids, *args, **kwargs):
4834         """Retrieve the External ID(s) of any database record.
4835
4836         **Synopsis**: ``_get_xml_ids(cr, uid, ids) -> { 'id': ['module.xml_id'] }``
4837
4838         :return: map of ids to the list of their fully qualified External IDs
4839                  in the form ``module.key``, or an empty list when there's no External
4840                  ID for a record, e.g.::
4841
4842                      { 'id': ['module.ext_id', 'module.ext_id_bis'],
4843                        'id2': [] }
4844         """
4845         ir_model_data = self.pool.get('ir.model.data')
4846         data_ids = ir_model_data.search(cr, uid, [('model', '=', self._name), ('res_id', 'in', ids)])
4847         data_results = ir_model_data.read(cr, uid, data_ids, ['module', 'name', 'res_id'])
4848         result = {}
4849         for id in ids:
4850             # can't use dict.fromkeys() as the list would be shared!
4851             result[id] = []
4852         for record in data_results:
4853             result[record['res_id']].append('%(module)s.%(name)s' % record)
4854         return result
4855
4856     def get_external_id(self, cr, uid, ids, *args, **kwargs):
4857         """Retrieve the External ID of any database record, if there
4858         is one. This method works as a possible implementation
4859         for a function field, to be able to add it to any
4860         model object easily, referencing it as ``Model.get_external_id``.
4861
4862         When multiple External IDs exist for a record, only one
4863         of them is returned (randomly).
4864
4865         :return: map of ids to their fully qualified XML ID,
4866                  defaulting to an empty string when there's none
4867                  (to be usable as a function field),
4868                  e.g.::
4869
4870                      { 'id': 'module.ext_id',
4871                        'id2': '' }
4872         """
4873         results = self._get_xml_ids(cr, uid, ids)
4874         for k, v in results.iteritems():
4875             if results[k]:
4876                 results[k] = v[0]
4877             else:
4878                 results[k] = ''
4879         return results
4880
4881     # backwards compatibility
4882     get_xml_id = get_external_id
4883     _get_xml_ids = _get_external_ids
4884
4885     def print_report(self, cr, uid, ids, name, data, context=None):
4886         """
4887         Render the report `name` for the given IDs. The report must be defined
4888         for this model, not another.
4889         """
4890         report = self.pool['ir.actions.report.xml']._lookup_report(cr, name)
4891         assert self._name == report.table
4892         return report.create(cr, uid, ids, data, context)
4893
4894     # Transience
4895     @classmethod
4896     def is_transient(cls):
4897         """ Return whether the model is transient.
4898
4899         See :class:`TransientModel`.
4900
4901         """
4902         return cls._transient
4903
4904     def _transient_clean_rows_older_than(self, cr, seconds):
4905         assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
4906         # Never delete rows used in last 5 minutes
4907         seconds = max(seconds, 300)
4908         query = ("SELECT id FROM " + self._table + " WHERE"
4909             " COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp"
4910             " < ((now() at time zone 'UTC') - interval %s)")
4911         cr.execute(query, ("%s seconds" % seconds,))
4912         ids = [x[0] for x in cr.fetchall()]
4913         self.unlink(cr, SUPERUSER_ID, ids)
4914
4915     def _transient_clean_old_rows(self, cr, max_count):
4916         # Check how many rows we have in the table
4917         cr.execute("SELECT count(*) AS row_count FROM " + self._table)
4918         res = cr.fetchall()
4919         if res[0][0] <= max_count:
4920             return  # max not reached, nothing to do
4921         self._transient_clean_rows_older_than(cr, 300)
4922
4923     def _transient_vacuum(self, cr, uid, force=False):
4924         """Clean the transient records.
4925
4926         This unlinks old records from the transient model tables whenever the
4927         "_transient_max_count" or "_max_age" conditions (if any) are reached.
4928         Actual cleaning will happen only once every "_transient_check_time" calls.
4929         This means this method can be called frequently called (e.g. whenever
4930         a new record is created).
4931         Example with both max_hours and max_count active:
4932         Suppose max_hours = 0.2 (e.g. 12 minutes), max_count = 20, there are 55 rows in the
4933         table, 10 created/changed in the last 5 minutes, an additional 12 created/changed between
4934         5 and 10 minutes ago, the rest created/changed more then 12 minutes ago.
4935         - age based vacuum will leave the 22 rows created/changed in the last 12 minutes
4936         - count based vacuum will wipe out another 12 rows. Not just 2, otherwise each addition
4937           would immediately cause the maximum to be reached again.
4938         - the 10 rows that have been created/changed the last 5 minutes will NOT be deleted
4939         """
4940         assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
4941         _transient_check_time = 20          # arbitrary limit on vacuum executions
4942         self._transient_check_count += 1
4943         if not force and (self._transient_check_count < _transient_check_time):
4944             return True  # no vacuum cleaning this time
4945         self._transient_check_count = 0
4946
4947         # Age-based expiration
4948         if self._transient_max_hours:
4949             self._transient_clean_rows_older_than(cr, self._transient_max_hours * 60 * 60)
4950
4951         # Count-based expiration
4952         if self._transient_max_count:
4953             self._transient_clean_old_rows(cr, self._transient_max_count)
4954
4955         return True
4956
4957     def resolve_2many_commands(self, cr, uid, field_name, commands, fields=None, context=None):
4958         """ Serializes one2many and many2many commands into record dictionaries
4959             (as if all the records came from the database via a read()).  This
4960             method is aimed at onchange methods on one2many and many2many fields.
4961
4962             Because commands might be creation commands, not all record dicts
4963             will contain an ``id`` field.  Commands matching an existing record
4964             will have an ``id``.
4965
4966             :param field_name: name of the one2many or many2many field matching the commands
4967             :type field_name: str
4968             :param commands: one2many or many2many commands to execute on ``field_name``
4969             :type commands: list((int|False, int|False, dict|False))
4970             :param fields: list of fields to read from the database, when applicable
4971             :type fields: list(str)
4972             :returns: records in a shape similar to that returned by ``read()``
4973                 (except records may be missing the ``id`` field if they don't exist in db)
4974             :rtype: list(dict)
4975         """
4976         result = []             # result (list of dict)
4977         record_ids = []         # ids of records to read
4978         updates = {}            # {id: dict} of updates on particular records
4979
4980         for command in commands or []:
4981             if not isinstance(command, (list, tuple)):
4982                 record_ids.append(command)
4983             elif command[0] == 0:
4984                 result.append(command[2])
4985             elif command[0] == 1:
4986                 record_ids.append(command[1])
4987                 updates.setdefault(command[1], {}).update(command[2])
4988             elif command[0] in (2, 3):
4989                 record_ids = [id for id in record_ids if id != command[1]]
4990             elif command[0] == 4:
4991                 record_ids.append(command[1])
4992             elif command[0] == 5:
4993                 result, record_ids = [], []
4994             elif command[0] == 6:
4995                 result, record_ids = [], list(command[2])
4996
4997         # read the records and apply the updates
4998         other_model = self.pool[self._all_columns[field_name].column._obj]
4999         for record in other_model.read(cr, uid, record_ids, fields=fields, context=context):
5000             record.update(updates.get(record['id'], {}))
5001             result.append(record)
5002
5003         return result
5004
5005     # for backward compatibility
5006     resolve_o2m_commands_to_record_dicts = resolve_2many_commands
5007
5008     def search_read(self, cr, uid, domain=None, fields=None, offset=0, limit=None, order=None, context=None):
5009         """
5010         Performs a ``search()`` followed by a ``read()``.
5011
5012         :param cr: database cursor
5013         :param user: current user id
5014         :param domain: Search domain, see ``args`` parameter in ``search()``. Defaults to an empty domain that will match all records.
5015         :param fields: List of fields to read, see ``fields`` parameter in ``read()``. Defaults to all fields.
5016         :param offset: Number of records to skip, see ``offset`` parameter in ``search()``. Defaults to 0.
5017         :param limit: Maximum number of records to return, see ``limit`` parameter in ``search()``. Defaults to no limit.
5018         :param order: Columns to sort result, see ``order`` parameter in ``search()``. Defaults to no sort.
5019         :param context: context arguments.
5020         :return: List of dictionaries containing the asked fields.
5021         :rtype: List of dictionaries.
5022
5023         """
5024         record_ids = self.search(cr, uid, domain or [], offset=offset, limit=limit, order=order, context=context)
5025         if not record_ids:
5026             return []
5027
5028         if fields and fields == ['id']:
5029             # shortcut read if we only want the ids
5030             return [{'id': id} for id in record_ids]
5031
5032         # read() ignores active_test, but it would forward it to any downstream search call
5033         # (e.g. for x2m or function fields), and this is not the desired behavior, the flag
5034         # was presumably only meant for the main search().
5035         # TODO: Move this to read() directly?                                                                                                
5036         read_ctx = dict(context or {})                                                                                                       
5037         read_ctx.pop('active_test', None)                                                                                                    
5038                                                                                                                                              
5039         result = self.read(cr, uid, record_ids, fields, context=read_ctx) 
5040         if len(result) <= 1:
5041             return result
5042
5043         # reorder read
5044         index = dict((r['id'], r) for r in result)
5045         return [index[x] for x in record_ids if x in index]
5046
5047     def _register_hook(self, cr):
5048         """ stuff to do right after the registry is built """
5049         pass
5050
5051     @classmethod
5052     def _patch_method(cls, name, method):
5053         """ Monkey-patch a method for all instances of this model. This replaces
5054             the method called `name` by `method` in the given class.
5055             The original method is then accessible via ``method.origin``, and it
5056             can be restored with :meth:`~._revert_method`.
5057
5058             Example::
5059
5060                 @api.multi
5061                 def do_write(self, values):
5062                     # do stuff, and call the original method
5063                     return do_write.origin(self, values)
5064
5065                 # patch method write of model
5066                 model._patch_method('write', do_write)
5067
5068                 # this will call do_write
5069                 records = model.search([...])
5070                 records.write(...)
5071
5072                 # restore the original method
5073                 model._revert_method('write')
5074         """
5075         origin = getattr(cls, name)
5076         method.origin = origin
5077         # propagate decorators from origin to method, and apply api decorator
5078         wrapped = api.guess(api.propagate(origin, method))
5079         wrapped.origin = origin
5080         setattr(cls, name, wrapped)
5081
5082     @classmethod
5083     def _revert_method(cls, name):
5084         """ Revert the original method called `name` in the given class.
5085             See :meth:`~._patch_method`.
5086         """
5087         method = getattr(cls, name)
5088         setattr(cls, name, method.origin)
5089
5090     #
5091     # Instance creation
5092     #
5093     # An instance represents an ordered collection of records in a given
5094     # execution environment. The instance object refers to the environment, and
5095     # the records themselves are represented by their cache dictionary. The 'id'
5096     # of each record is found in its corresponding cache dictionary.
5097     #
5098     # This design has the following advantages:
5099     #  - cache access is direct and thus fast;
5100     #  - one can consider records without an 'id' (see new records);
5101     #  - the global cache is only an index to "resolve" a record 'id'.
5102     #
5103
5104     @classmethod
5105     def _browse(cls, env, ids):
5106         """ Create an instance attached to `env`; `ids` is a tuple of record
5107             ids.
5108         """
5109         records = object.__new__(cls)
5110         records.env = env
5111         records._ids = ids
5112         env.prefetch[cls._name].update(ids)
5113         return records
5114
5115     @api.v7
5116     def browse(self, cr, uid, arg=None, context=None):
5117         ids = _normalize_ids(arg)
5118         #assert all(isinstance(id, IdType) for id in ids), "Browsing invalid ids: %s" % ids
5119         return self._browse(Environment(cr, uid, context or {}), ids)
5120
5121     @api.v8
5122     def browse(self, arg=None):
5123         """ browse([ids]) -> records
5124
5125         Returns a recordset for the ids provided as parameter in the current
5126         environment.
5127
5128         Can take no ids, a single id or a sequence of ids.
5129         """
5130         ids = _normalize_ids(arg)
5131         #assert all(isinstance(id, IdType) for id in ids), "Browsing invalid ids: %s" % ids
5132         return self._browse(self.env, ids)
5133
5134     #
5135     # Internal properties, for manipulating the instance's implementation
5136     #
5137
5138     @property
5139     def ids(self):
5140         """ List of actual record ids in this recordset (ignores placeholder
5141         ids for records to create)
5142         """
5143         return filter(None, list(self._ids))
5144
5145     # backward-compatibility with former browse records
5146     _cr = property(lambda self: self.env.cr)
5147     _uid = property(lambda self: self.env.uid)
5148     _context = property(lambda self: self.env.context)
5149
5150     #
5151     # Conversion methods
5152     #
5153
5154     def ensure_one(self):
5155         """ Verifies that the current recorset holds a single record. Raises
5156         an exception otherwise.
5157         """
5158         if len(self) == 1:
5159             return self
5160         raise except_orm("ValueError", "Expected singleton: %s" % self)
5161
5162     def with_env(self, env):
5163         """ Returns a new version of this recordset attached to the provided
5164         environment
5165
5166         :type env: :class:`~openerp.api.Environment`
5167         """
5168         return self._browse(env, self._ids)
5169
5170     def sudo(self, user=SUPERUSER_ID):
5171         """ sudo([user=SUPERUSER])
5172
5173         Returns a new version of this recordset attached to the provided
5174         user.
5175         """
5176         return self.with_env(self.env(user=user))
5177
5178     def with_context(self, *args, **kwargs):
5179         """ with_context([context][, **overrides]) -> records
5180
5181         Returns a new version of this recordset attached to an extended
5182         context.
5183
5184         The extended context is either the provided ``context`` in which
5185         ``overrides`` are merged or the *current* context in which
5186         ``overrides`` are merged e.g.::
5187
5188             # current context is {'key1': True}
5189             r2 = records.with_context({}, key2=True)
5190             # -> r2._context is {'key2': True}
5191             r2 = records.with_context(key2=True)
5192             # -> r2._context is {'key1': True, 'key2': True}
5193         """
5194         context = dict(args[0] if args else self._context, **kwargs)
5195         return self.with_env(self.env(context=context))
5196
5197     def _convert_to_cache(self, values, update=False, validate=True):
5198         """ Convert the `values` dictionary into cached values.
5199
5200             :param update: whether the conversion is made for updating `self`;
5201                 this is necessary for interpreting the commands of *2many fields
5202             :param validate: whether values must be checked
5203         """
5204         fields = self._fields
5205         target = self if update else self.browse()
5206         return {
5207             name: fields[name].convert_to_cache(value, target, validate=validate)
5208             for name, value in values.iteritems()
5209             if name in fields
5210         }
5211
5212     def _convert_to_write(self, values):
5213         """ Convert the `values` dictionary into the format of :meth:`write`. """
5214         fields = self._fields
5215         result = {}
5216         for name, value in values.iteritems():
5217             if name in fields:
5218                 value = fields[name].convert_to_write(value)
5219                 if not isinstance(value, NewId):
5220                     result[name] = value
5221         return result
5222
5223     #
5224     # Record traversal and update
5225     #
5226
5227     def _mapped_func(self, func):
5228         """ Apply function `func` on all records in `self`, and return the
5229             result as a list or a recordset (if `func` return recordsets).
5230         """
5231         vals = [func(rec) for rec in self]
5232         val0 = vals[0] if vals else func(self)
5233         if isinstance(val0, BaseModel):
5234             return reduce(operator.or_, vals, val0)
5235         return vals
5236
5237     def mapped(self, func):
5238         """ Apply `func` on all records in `self`, and return the result as a
5239             list or a recordset (if `func` return recordsets). In the latter
5240             case, the order of the returned recordset is arbritrary.
5241
5242             :param func: a function or a dot-separated sequence of field names
5243         """
5244         if isinstance(func, basestring):
5245             recs = self
5246             for name in func.split('.'):
5247                 recs = recs._mapped_func(operator.itemgetter(name))
5248             return recs
5249         else:
5250             return self._mapped_func(func)
5251
5252     def _mapped_cache(self, name_seq):
5253         """ Same as `~.mapped`, but `name_seq` is a dot-separated sequence of
5254             field names, and only cached values are used.
5255         """
5256         recs = self
5257         for name in name_seq.split('.'):
5258             field = recs._fields[name]
5259             null = field.null(self.env)
5260             recs = recs.mapped(lambda rec: rec._cache.get(field, null))
5261         return recs
5262
5263     def filtered(self, func):
5264         """ Select the records in `self` such that `func(rec)` is true, and
5265             return them as a recordset.
5266
5267             :param func: a function or a dot-separated sequence of field names
5268         """
5269         if isinstance(func, basestring):
5270             name = func
5271             func = lambda rec: filter(None, rec.mapped(name))
5272         return self.browse([rec.id for rec in self if func(rec)])
5273
5274     def sorted(self, key=None):
5275         """ Return the recordset `self` ordered by `key` """
5276         if key is None:
5277             return self.search([('id', 'in', self.ids)])
5278         else:
5279             return self.browse(map(int, sorted(self, key=key)))
5280
5281     def update(self, values):
5282         """ Update record `self[0]` with `values`. """
5283         for name, value in values.iteritems():
5284             self[name] = value
5285
5286     #
5287     # New records - represent records that do not exist in the database yet;
5288     # they are used to perform onchanges.
5289     #
5290
5291     @api.model
5292     def new(self, values={}):
5293         """ new([values]) -> record
5294
5295         Return a new record instance attached to the current environment and
5296         initialized with the provided ``value``. The record is *not* created
5297         in database, it only exists in memory.
5298         """
5299         record = self.browse([NewId()])
5300         record._cache.update(record._convert_to_cache(values, update=True))
5301
5302         if record.env.in_onchange:
5303             # The cache update does not set inverse fields, so do it manually.
5304             # This is useful for computing a function field on secondary
5305             # records, if that field depends on the main record.
5306             for name in values:
5307                 field = self._fields.get(name)
5308                 if field:
5309                     for invf in field.inverse_fields:
5310                         invf._update(record[name], record)
5311
5312         return record
5313
5314     #
5315     # Dirty flag, to mark records modified (in draft mode)
5316     #
5317
5318     @property
5319     def _dirty(self):
5320         """ Return whether any record in `self` is dirty. """
5321         dirty = self.env.dirty
5322         return any(record in dirty for record in self)
5323
5324     @_dirty.setter
5325     def _dirty(self, value):
5326         """ Mark the records in `self` as dirty. """
5327         if value:
5328             map(self.env.dirty.add, self)
5329         else:
5330             map(self.env.dirty.discard, self)
5331
5332     #
5333     # "Dunder" methods
5334     #
5335
5336     def __nonzero__(self):
5337         """ Test whether `self` is nonempty. """
5338         return bool(getattr(self, '_ids', True))
5339
5340     def __len__(self):
5341         """ Return the size of `self`. """
5342         return len(self._ids)
5343
5344     def __iter__(self):
5345         """ Return an iterator over `self`. """
5346         for id in self._ids:
5347             yield self._browse(self.env, (id,))
5348
5349     def __contains__(self, item):
5350         """ Test whether `item` (record or field name) is an element of `self`.
5351             In the first case, the test is fully equivalent to::
5352
5353                 any(item == record for record in self)
5354         """
5355         if isinstance(item, BaseModel) and self._name == item._name:
5356             return len(item) == 1 and item.id in self._ids
5357         elif isinstance(item, basestring):
5358             return item in self._fields
5359         else:
5360             raise except_orm("ValueError", "Mixing apples and oranges: %s in %s" % (item, self))
5361
5362     def __add__(self, other):
5363         """ Return the concatenation of two recordsets. """
5364         if not isinstance(other, BaseModel) or self._name != other._name:
5365             raise except_orm("ValueError", "Mixing apples and oranges: %s + %s" % (self, other))
5366         return self.browse(self._ids + other._ids)
5367
5368     def __sub__(self, other):
5369         """ Return the recordset of all the records in `self` that are not in `other`. """
5370         if not isinstance(other, BaseModel) or self._name != other._name:
5371             raise except_orm("ValueError", "Mixing apples and oranges: %s - %s" % (self, other))
5372         other_ids = set(other._ids)
5373         return self.browse([id for id in self._ids if id not in other_ids])
5374
5375     def __and__(self, other):
5376         """ Return the intersection of two recordsets.
5377             Note that recordset order is not preserved.
5378         """
5379         if not isinstance(other, BaseModel) or self._name != other._name:
5380             raise except_orm("ValueError", "Mixing apples and oranges: %s & %s" % (self, other))
5381         return self.browse(set(self._ids) & set(other._ids))
5382
5383     def __or__(self, other):
5384         """ Return the union of two recordsets.
5385             Note that recordset order is not preserved.
5386         """
5387         if not isinstance(other, BaseModel) or self._name != other._name:
5388             raise except_orm("ValueError", "Mixing apples and oranges: %s | %s" % (self, other))
5389         return self.browse(set(self._ids) | set(other._ids))
5390
5391     def __eq__(self, other):
5392         """ Test whether two recordsets are equivalent (up to reordering). """
5393         if not isinstance(other, BaseModel):
5394             if other:
5395                 _logger.warning("Comparing apples and oranges: %s == %s", self, other)
5396             return False
5397         return self._name == other._name and set(self._ids) == set(other._ids)
5398
5399     def __ne__(self, other):
5400         return not self == other
5401
5402     def __lt__(self, other):
5403         if not isinstance(other, BaseModel) or self._name != other._name:
5404             raise except_orm("ValueError", "Mixing apples and oranges: %s < %s" % (self, other))
5405         return set(self._ids) < set(other._ids)
5406
5407     def __le__(self, other):
5408         if not isinstance(other, BaseModel) or self._name != other._name:
5409             raise except_orm("ValueError", "Mixing apples and oranges: %s <= %s" % (self, other))
5410         return set(self._ids) <= set(other._ids)
5411
5412     def __gt__(self, other):
5413         if not isinstance(other, BaseModel) or self._name != other._name:
5414             raise except_orm("ValueError", "Mixing apples and oranges: %s > %s" % (self, other))
5415         return set(self._ids) > set(other._ids)
5416
5417     def __ge__(self, other):
5418         if not isinstance(other, BaseModel) or self._name != other._name:
5419             raise except_orm("ValueError", "Mixing apples and oranges: %s >= %s" % (self, other))
5420         return set(self._ids) >= set(other._ids)
5421
5422     def __int__(self):
5423         return self.id
5424
5425     def __str__(self):
5426         return "%s%s" % (self._name, getattr(self, '_ids', ""))
5427
5428     def __unicode__(self):
5429         return unicode(str(self))
5430
5431     __repr__ = __str__
5432
5433     def __hash__(self):
5434         if hasattr(self, '_ids'):
5435             return hash((self._name, frozenset(self._ids)))
5436         else:
5437             return hash(self._name)
5438
5439     def __getitem__(self, key):
5440         """ If `key` is an integer or a slice, return the corresponding record
5441             selection as an instance (attached to `self.env`).
5442             Otherwise read the field `key` of the first record in `self`.
5443
5444             Examples::
5445
5446                 inst = model.search(dom)    # inst is a recordset
5447                 r4 = inst[3]                # fourth record in inst
5448                 rs = inst[10:20]            # subset of inst
5449                 nm = rs['name']             # name of first record in inst
5450         """
5451         if isinstance(key, basestring):
5452             # important: one must call the field's getter
5453             return self._fields[key].__get__(self, type(self))
5454         elif isinstance(key, slice):
5455             return self._browse(self.env, self._ids[key])
5456         else:
5457             return self._browse(self.env, (self._ids[key],))
5458
5459     def __setitem__(self, key, value):
5460         """ Assign the field `key` to `value` in record `self`. """
5461         # important: one must call the field's setter
5462         return self._fields[key].__set__(self, value)
5463
5464     #
5465     # Cache and recomputation management
5466     #
5467
5468     @lazy_property
5469     def _cache(self):
5470         """ Return the cache of `self`, mapping field names to values. """
5471         return RecordCache(self)
5472
5473     @api.model
5474     def _in_cache_without(self, field):
5475         """ Make sure `self` is present in cache (for prefetching), and return
5476             the records of model `self` in cache that have no value for `field`
5477             (:class:`Field` instance).
5478         """
5479         env = self.env
5480         prefetch_ids = env.prefetch[self._name]
5481         prefetch_ids.update(self._ids)
5482         ids = filter(None, prefetch_ids - set(env.cache[field]))
5483         return self.browse(ids)
5484
5485     @api.model
5486     def refresh(self):
5487         """ Clear the records cache.
5488
5489             .. deprecated:: 8.0
5490                 The record cache is automatically invalidated.
5491         """
5492         self.invalidate_cache()
5493
5494     @api.model
5495     def invalidate_cache(self, fnames=None, ids=None):
5496         """ Invalidate the record caches after some records have been modified.
5497             If both `fnames` and `ids` are ``None``, the whole cache is cleared.
5498
5499             :param fnames: the list of modified fields, or ``None`` for all fields
5500             :param ids: the list of modified record ids, or ``None`` for all
5501         """
5502         if fnames is None:
5503             if ids is None:
5504                 return self.env.invalidate_all()
5505             fields = self._fields.values()
5506         else:
5507             fields = map(self._fields.__getitem__, fnames)
5508
5509         # invalidate fields and inverse fields, too
5510         spec = [(f, ids) for f in fields] + \
5511                [(invf, None) for f in fields for invf in f.inverse_fields]
5512         self.env.invalidate(spec)
5513
5514     @api.multi
5515     def modified(self, fnames):
5516         """ Notify that fields have been modified on `self`. This invalidates
5517             the cache, and prepares the recomputation of stored function fields
5518             (new-style fields only).
5519
5520             :param fnames: iterable of field names that have been modified on
5521                 records `self`
5522         """
5523         # each field knows what to invalidate and recompute
5524         spec = []
5525         for fname in fnames:
5526             spec += self._fields[fname].modified(self)
5527
5528         cached_fields = {
5529             field
5530             for env in self.env.all
5531             for field in env.cache
5532         }
5533         # invalidate non-stored fields.function which are currently cached
5534         spec += [(f, None) for f in self.pool.pure_function_fields
5535                  if f in cached_fields]
5536
5537         self.env.invalidate(spec)
5538
5539     def _recompute_check(self, field):
5540         """ If `field` must be recomputed on some record in `self`, return the
5541             corresponding records that must be recomputed.
5542         """
5543         return self.env.check_todo(field, self)
5544
5545     def _recompute_todo(self, field):
5546         """ Mark `field` to be recomputed. """
5547         self.env.add_todo(field, self)
5548
5549     def _recompute_done(self, field):
5550         """ Mark `field` as recomputed. """
5551         self.env.remove_todo(field, self)
5552
5553     @api.model
5554     def recompute(self):
5555         """ Recompute stored function fields. The fields and records to
5556             recompute have been determined by method :meth:`modified`.
5557         """
5558         while self.env.has_todo():
5559             field, recs = self.env.get_todo()
5560             # evaluate the fields to recompute, and save them to database
5561             for rec, rec1 in zip(recs, recs.with_context(recompute=False)):
5562                 try:
5563                     values = rec._convert_to_write({
5564                         f.name: rec[f.name] for f in field.computed_fields
5565                     })
5566                     rec1._write(values)
5567                 except MissingError:
5568                     pass
5569             # mark the computed fields as done
5570             map(recs._recompute_done, field.computed_fields)
5571
5572     #
5573     # Generic onchange method
5574     #
5575
5576     def _has_onchange(self, field, other_fields):
5577         """ Return whether `field` should trigger an onchange event in the
5578             presence of `other_fields`.
5579         """
5580         # test whether self has an onchange method for field, or field is a
5581         # dependency of any field in other_fields
5582         return field.name in self._onchange_methods or \
5583             any(dep in other_fields for dep in field.dependents)
5584
5585     @api.model
5586     def _onchange_spec(self, view_info=None):
5587         """ Return the onchange spec from a view description; if not given, the
5588             result of ``self.fields_view_get()`` is used.
5589         """
5590         result = {}
5591
5592         # for traversing the XML arch and populating result
5593         def process(node, info, prefix):
5594             if node.tag == 'field':
5595                 name = node.attrib['name']
5596                 names = "%s.%s" % (prefix, name) if prefix else name
5597                 if not result.get(names):
5598                     result[names] = node.attrib.get('on_change')
5599                 # traverse the subviews included in relational fields
5600                 for subinfo in info['fields'][name].get('views', {}).itervalues():
5601                     process(etree.fromstring(subinfo['arch']), subinfo, names)
5602             else:
5603                 for child in node:
5604                     process(child, info, prefix)
5605
5606         if view_info is None:
5607             view_info = self.fields_view_get()
5608         process(etree.fromstring(view_info['arch']), view_info, '')
5609         return result
5610
5611     def _onchange_eval(self, field_name, onchange, result):
5612         """ Apply onchange method(s) for field `field_name` with spec `onchange`
5613             on record `self`. Value assignments are applied on `self`, while
5614             domain and warning messages are put in dictionary `result`.
5615         """
5616         onchange = onchange.strip()
5617
5618         # onchange V8
5619         if onchange in ("1", "true"):
5620             for method in self._onchange_methods.get(field_name, ()):
5621                 method_res = method(self)
5622                 if not method_res:
5623                     continue
5624                 if 'domain' in method_res:
5625                     result.setdefault('domain', {}).update(method_res['domain'])
5626                 if 'warning' in method_res:
5627                     result['warning'] = method_res['warning']
5628             return
5629
5630         # onchange V7
5631         match = onchange_v7.match(onchange)
5632         if match:
5633             method, params = match.groups()
5634
5635             # evaluate params -> tuple
5636             global_vars = {'context': self._context, 'uid': self._uid}
5637             if self._context.get('field_parent'):
5638                 class RawRecord(object):
5639                     def __init__(self, record):
5640                         self._record = record
5641                     def __getattr__(self, name):
5642                         field = self._record._fields[name]
5643                         value = self._record[name]
5644                         return field.convert_to_onchange(value)
5645                 record = self[self._context['field_parent']]
5646                 global_vars['parent'] = RawRecord(record)
5647             field_vars = {
5648                 key: self._fields[key].convert_to_onchange(val)
5649                 for key, val in self._cache.iteritems()
5650             }
5651             params = eval("[%s]" % params, global_vars, field_vars)
5652
5653             # call onchange method
5654             args = (self._cr, self._uid, self._origin.ids) + tuple(params)
5655             method_res = getattr(self._model, method)(*args)
5656             if not isinstance(method_res, dict):
5657                 return
5658             if 'value' in method_res:
5659                 method_res['value'].pop('id', None)
5660                 self.update(self._convert_to_cache(method_res['value'], validate=False))
5661             if 'domain' in method_res:
5662                 result.setdefault('domain', {}).update(method_res['domain'])
5663             if 'warning' in method_res:
5664                 result['warning'] = method_res['warning']
5665
5666     @api.multi
5667     def onchange(self, values, field_name, field_onchange):
5668         """ Perform an onchange on the given field.
5669
5670             :param values: dictionary mapping field names to values, giving the
5671                 current state of modification
5672             :param field_name: name of the modified field_name
5673             :param field_onchange: dictionary mapping field names to their
5674                 on_change attribute
5675         """
5676         env = self.env
5677
5678         if field_name and field_name not in self._fields:
5679             return {}
5680
5681         # determine subfields for field.convert_to_write() below
5682         secondary = []
5683         subfields = defaultdict(set)
5684         for dotname in field_onchange:
5685             if '.' in dotname:
5686                 secondary.append(dotname)
5687                 name, subname = dotname.split('.')
5688                 subfields[name].add(subname)
5689
5690         # create a new record with values, and attach `self` to it
5691         with env.do_in_onchange():
5692             record = self.new(values)
5693             values = dict(record._cache)
5694             # attach `self` with a different context (for cache consistency)
5695             record._origin = self.with_context(__onchange=True)
5696
5697         # determine which field should be triggered an onchange
5698         todo = set([field_name]) if field_name else set(values)
5699         done = set()
5700
5701         # dummy assignment: trigger invalidations on the record
5702         for name in todo:
5703             value = record[name]
5704             field = self._fields[name]
5705             if not field_name and field.type == 'many2one' and field.delegate and not value:
5706                 # do not nullify all fields of parent record for new records
5707                 continue
5708             record[name] = value
5709
5710         result = {'value': {}}
5711
5712         while todo:
5713             name = todo.pop()
5714             if name in done:
5715                 continue
5716             done.add(name)
5717
5718             with env.do_in_onchange():
5719                 # apply field-specific onchange methods
5720                 if field_onchange.get(name):
5721                     record._onchange_eval(name, field_onchange[name], result)
5722
5723                 # force re-evaluation of function fields on secondary records
5724                 for field_seq in secondary:
5725                     record.mapped(field_seq)
5726
5727                 # determine which fields have been modified
5728                 for name, oldval in values.iteritems():
5729                     field = self._fields[name]
5730                     newval = record[name]
5731                     if field.type in ('one2many', 'many2many'):
5732                         if newval != oldval or newval._dirty:
5733                             # put new value in result
5734                             result['value'][name] = field.convert_to_write(
5735                                 newval, record._origin, subfields.get(name),
5736                             )
5737                             todo.add(name)
5738                         else:
5739                             # keep result: newval may have been dirty before
5740                             pass
5741                     else:
5742                         if newval != oldval:
5743                             # put new value in result
5744                             result['value'][name] = field.convert_to_write(
5745                                 newval, record._origin, subfields.get(name),
5746                             )
5747                             todo.add(name)
5748                         else:
5749                             # clean up result to not return another value
5750                             result['value'].pop(name, None)
5751
5752         # At the moment, the client does not support updates on a *2many field
5753         # while this one is modified by the user.
5754         if field_name and self._fields[field_name].type in ('one2many', 'many2many'):
5755             result['value'].pop(field_name, None)
5756
5757         return result
5758
5759
5760 class RecordCache(MutableMapping):
5761     """ Implements a proxy dictionary to read/update the cache of a record.
5762         Upon iteration, it looks like a dictionary mapping field names to
5763         values. However, fields may be used as keys as well.
5764     """
5765     def __init__(self, records):
5766         self._recs = records
5767
5768     def contains(self, field):
5769         """ Return whether `records[0]` has a value for `field` in cache. """
5770         if isinstance(field, basestring):
5771             field = self._recs._fields[field]
5772         return self._recs.id in self._recs.env.cache[field]
5773
5774     def __contains__(self, field):
5775         """ Return whether `records[0]` has a regular value for `field` in cache. """
5776         if isinstance(field, basestring):
5777             field = self._recs._fields[field]
5778         dummy = SpecialValue(None)
5779         value = self._recs.env.cache[field].get(self._recs.id, dummy)
5780         return not isinstance(value, SpecialValue)
5781
5782     def __getitem__(self, field):
5783         """ Return the cached value of `field` for `records[0]`. """
5784         if isinstance(field, basestring):
5785             field = self._recs._fields[field]
5786         value = self._recs.env.cache[field][self._recs.id]
5787         return value.get() if isinstance(value, SpecialValue) else value
5788
5789     def __setitem__(self, field, value):
5790         """ Assign the cached value of `field` for all records in `records`. """
5791         if isinstance(field, basestring):
5792             field = self._recs._fields[field]
5793         values = dict.fromkeys(self._recs._ids, value)
5794         self._recs.env.cache[field].update(values)
5795
5796     def update(self, *args, **kwargs):
5797         """ Update the cache of all records in `records`. If the argument is a
5798             `SpecialValue`, update all fields (except "magic" columns).
5799         """
5800         if args and isinstance(args[0], SpecialValue):
5801             values = dict.fromkeys(self._recs._ids, args[0])
5802             for name, field in self._recs._fields.iteritems():
5803                 if name != 'id':
5804                     self._recs.env.cache[field].update(values)
5805         else:
5806             return super(RecordCache, self).update(*args, **kwargs)
5807
5808     def __delitem__(self, field):
5809         """ Remove the cached value of `field` for all `records`. """
5810         if isinstance(field, basestring):
5811             field = self._recs._fields[field]
5812         field_cache = self._recs.env.cache[field]
5813         for id in self._recs._ids:
5814             field_cache.pop(id, None)
5815
5816     def __iter__(self):
5817         """ Iterate over the field names with a regular value in cache. """
5818         cache, id = self._recs.env.cache, self._recs.id
5819         dummy = SpecialValue(None)
5820         for name, field in self._recs._fields.iteritems():
5821             if name != 'id' and not isinstance(cache[field].get(id, dummy), SpecialValue):
5822                 yield name
5823
5824     def __len__(self):
5825         """ Return the number of fields with a regular value in cache. """
5826         return sum(1 for name in self)
5827
5828 class Model(BaseModel):
5829     """Main super-class for regular database-persisted OpenERP models.
5830
5831     OpenERP models are created by inheriting from this class::
5832
5833         class user(Model):
5834             ...
5835
5836     The system will later instantiate the class once per database (on
5837     which the class' module is installed).
5838     """
5839     _auto = True
5840     _register = False # not visible in ORM registry, meant to be python-inherited only
5841     _transient = False # True in a TransientModel
5842
5843 class TransientModel(BaseModel):
5844     """Model super-class for transient records, meant to be temporarily
5845        persisted, and regularly vaccuum-cleaned.
5846
5847        A TransientModel has a simplified access rights management,
5848        all users can create new records, and may only access the
5849        records they created. The super-user has unrestricted access
5850        to all TransientModel records.
5851     """
5852     _auto = True
5853     _register = False # not visible in ORM registry, meant to be python-inherited only
5854     _transient = True
5855
5856 class AbstractModel(BaseModel):
5857     """Abstract Model super-class for creating an abstract class meant to be
5858        inherited by regular models (Models or TransientModels) but not meant to
5859        be usable on its own, or persisted.
5860
5861        Technical note: we don't want to make AbstractModel the super-class of
5862        Model or BaseModel because it would not make sense to put the main
5863        definition of persistence methods such as create() in it, and still we
5864        should be able to override them within an AbstractModel.
5865        """
5866     _auto = False # don't create any database backend for AbstractModels
5867     _register = False # not visible in ORM registry, meant to be python-inherited only
5868     _transient = False
5869
5870 def itemgetter_tuple(items):
5871     """ Fixes itemgetter inconsistency (useful in some cases) of not returning
5872     a tuple if len(items) == 1: always returns an n-tuple where n = len(items)
5873     """
5874     if len(items) == 0:
5875         return lambda a: ()
5876     if len(items) == 1:
5877         return lambda gettable: (gettable[items[0]],)
5878     return operator.itemgetter(*items)
5879
5880 def convert_pgerror_23502(model, fields, info, e):
5881     m = re.match(r'^null value in column "(?P<field>\w+)" violates '
5882                  r'not-null constraint\n',
5883                  str(e))
5884     field_name = m and m.group('field')
5885     if not m or field_name not in fields:
5886         return {'message': unicode(e)}
5887     message = _(u"Missing required value for the field '%s'.") % field_name
5888     field = fields.get(field_name)
5889     if field:
5890         message = _(u"Missing required value for the field '%s' (%s)") % (field['string'], field_name)
5891     return {
5892         'message': message,
5893         'field': field_name,
5894     }
5895
5896 def convert_pgerror_23505(model, fields, info, e):
5897     m = re.match(r'^duplicate key (?P<field>\w+) violates unique constraint',
5898                  str(e))
5899     field_name = m and m.group('field')
5900     if not m or field_name not in fields:
5901         return {'message': unicode(e)}
5902     message = _(u"The value for the field '%s' already exists.") % field_name
5903     field = fields.get(field_name)
5904     if field:
5905         message = _(u"%s This might be '%s' in the current model, or a field "
5906                     u"of the same name in an o2m.") % (message, field['string'])
5907     return {
5908         'message': message,
5909         'field': field_name,
5910     }
5911
5912 PGERROR_TO_OE = defaultdict(
5913     # shape of mapped converters
5914     lambda: (lambda model, fvg, info, pgerror: {'message': unicode(pgerror)}), {
5915     # not_null_violation
5916     '23502': convert_pgerror_23502,
5917     # unique constraint error
5918     '23505': convert_pgerror_23505,
5919 })
5920
5921 def _normalize_ids(arg, atoms={int, long, str, unicode, NewId}):
5922     """ Normalizes the ids argument for ``browse`` (v7 and v8) to a tuple.
5923
5924     Various implementations were tested on the corpus of all browse() calls
5925     performed during a full crawler run (after having installed all website_*
5926     modules) and this one was the most efficient overall.
5927
5928     A possible bit of correctness was sacrificed by not doing any test on
5929     Iterable and just assuming that any non-atomic type was an iterable of
5930     some kind.
5931
5932     :rtype: tuple
5933     """
5934     # much of the corpus is falsy objects (empty list, tuple or set, None)
5935     if not arg:
5936         return ()
5937
5938     # `type in set` is significantly faster (because more restrictive) than
5939     # isinstance(arg, set) or issubclass(type, set); and for new-style classes
5940     # obj.__class__ is equivalent to but faster than type(obj). Not relevant
5941     # (and looks much worse) in most cases, but over millions of calls it
5942     # does have a very minor effect.
5943     if arg.__class__ in atoms:
5944         return arg,
5945
5946     return tuple(arg)
5947
5948 # keep those imports here to avoid dependency cycle errors
5949 from .osv import expression
5950 from .fields import Field, SpecialValue, FailedValue
5951
5952 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: