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