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