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