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