1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
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
32 # . Multi-level caching system
33 # . 2 different inheritancies
35 # - classicals (varchar, integer, boolean, ...)
36 # - relations (one2many, many2one, many2many)
52 from lxml import etree
53 from tools.config import config
54 from tools.translate import _
57 from query import Query
59 from tools.safe_eval import safe_eval as eval
61 regex_order = re.compile('^(([a-z0-9_]+|"[a-z0-9_]+")( *desc| *asc)?( *, *|))+$', re.I)
64 POSTGRES_CONFDELTYPES = {
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)
77 def intersect(la, lb):
78 return filter(lambda x: x in lb, la)
80 class except_orm(Exception):
81 def __init__(self, name, value):
84 self.args = (name, value)
86 class BrowseRecordError(Exception):
89 # Readonly python database object browser
90 class browse_null(object):
95 def __getitem__(self, name):
98 def __getattr__(self, name):
99 return None # XXX: return self ?
107 def __nonzero__(self):
110 def __unicode__(self):
115 # TODO: execute an object method on browse_record_list
117 class browse_record_list(list):
119 def __init__(self, lst, context=None):
122 super(browse_record_list, self).__init__(lst)
123 self.context = context
126 class browse_record(object):
127 logger = netsvc.Logger()
129 def __init__(self, cr, uid, id, table, cache, context=None, list_class = None, fields_process={}):
131 table : the object (inherited from orm)
132 context : dictionary with an optional context
136 self._list_class = list_class or browse_record_list
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
147 cache.setdefault(table._name, {})
148 self._data = cache[table._name]
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,))
155 if id not in self._data:
156 self._data[id] = {'id': id}
160 def __getitem__(self, name):
164 if name not in self._data[self._id]:
165 # build the list of fields we will fetch
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)
175 if isinstance(attr, (types.MethodType, types.LambdaType, types.FunctionType)):
176 return lambda *args, **argv: attr(self._cr, self._uid, [self._id], *args, **argv)
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'" % (
186 # if the field is a classic one or a many2one, we'll fetch all classic and many2one fields
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
196 fields_to_fetch = [(name, col)]
197 ids = filter(lambda id: name not in self._data[id], self._data.keys())
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)])
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])
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)
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:
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]
229 value = result_line[field_name]
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)
242 new_data[field_name] = value
244 new_data[field_name] = browse_null()
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]
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)
259 new_data[field_name] = browse_null()
261 new_data[field_name] = result_line[field_name]
262 self._data[result_line['id']].update(new_data)
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]
273 def __getattr__(self, name):
277 raise AttributeError(e)
279 def __contains__(self, name):
280 return (name in self._table._columns) or (name in self._table._inherit_fields) or hasattr(self._table, name)
282 def __hasattr__(self, name):
289 return "browse_record(%s, %d)" % (self._table_name, self._id)
291 def __eq__(self, other):
292 if not isinstance(other, browse_record):
294 return (self._table_name, self._id) == (other._table_name, other._id)
296 def __ne__(self, other):
297 if not isinstance(other, browse_record):
299 return (self._table_name, self._id) != (other._table_name, other._id)
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))
307 return hash((self._table_name, self._id))
315 (type returned by postgres when the column was created, type expression to create the column)
319 fields.boolean: 'bool',
320 fields.integer: 'int4',
321 fields.integer_big: 'int8',
325 fields.datetime: 'timestamp',
326 fields.binary: 'bytea',
327 fields.many2one: 'int4',
329 if type(f) in type_dict:
330 f_type = (type_dict[type(f)], type_dict[type(f)])
331 elif isinstance(f, fields.float):
333 f_type = ('numeric', 'NUMERIC')
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):
344 f_size = getattr(f, 'size', None) or 16
347 f_type = ('int4', 'INTEGER')
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':
355 f_type = ('numeric', 'NUMERIC')
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))
363 logger = netsvc.Logger()
364 logger.notifyChannel("init", netsvc.LOG_WARNING, '%s type not supported!' % (type(f)))
369 class orm_template(object):
375 _parent_name = 'parent_id'
376 _parent_store = False
377 _parent_order = False
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, {
391 'res_model': self._name,
392 'secondary': secondary,
397 def view_init(self, cr, uid, fields_list, context=None):
398 """Override this method to do specific things when a view on the object is opened."""
401 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None):
402 raise NotImplementedError(_('The read_group method is not implemented on this object !'))
404 def _field_create(self, cr, context={}):
405 cr.execute("SELECT id FROM ir_model WHERE model=%s", (self._name,))
407 cr.execute('SELECT nextval(%s)', ('ir_model_id_seq',))
408 model_id = cr.fetchone()[0]
409 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'))
411 model_id = cr.fetchone()[0]
412 if 'module' in context:
413 name_id = 'model_'+self._name.replace('.', '_')
414 cr.execute('select * from ir_model_data where name=%s and res_id=%s and module=%s', (name_id, model_id, context['module']))
416 cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, now(), now(), %s, %s, %s)", \
417 (name_id, context['module'], 'ir.model', model_id)
422 cr.execute("SELECT * FROM ir_model_fields WHERE model=%s", (self._name,))
424 for rec in cr.dictfetchall():
425 cols[rec['name']] = rec
427 for (k, f) in self._columns.items():
429 'model_id': model_id,
432 'field_description': f.string.replace("'", " "),
434 'relation': f._obj or '',
435 'view_load': (f.view_load and 1) or 0,
436 'select_level': tools.ustr(f.select or 0),
437 'readonly': (f.readonly and 1) or 0,
438 'required': (f.required and 1) or 0,
439 'selectable': (f.selectable and 1) or 0,
440 'relation_field': (f._type=='one2many' and isinstance(f, fields.one2many)) and f._fields_id or '',
442 # When its a custom field,it does not contain f.select
443 if context.get('field_state', 'base') == 'manual':
444 if context.get('field_name', '') == k:
445 vals['select_level'] = context.get('select', '0')
446 #setting value to let the problem NOT occur next time
448 vals['select_level'] = cols[k]['select_level']
451 cr.execute('select nextval(%s)', ('ir_model_fields_id_seq',))
452 id = cr.fetchone()[0]
454 cr.execute("""INSERT INTO ir_model_fields (
455 id, model_id, model, name, field_description, ttype,
456 relation,view_load,state,select_level,relation_field
458 %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s
460 id, vals['model_id'], vals['model'], vals['name'], vals['field_description'], vals['ttype'],
461 vals['relation'], bool(vals['view_load']), 'base',
462 vals['select_level'], vals['relation_field']
464 if 'module' in context:
465 name1 = 'field_' + self._table + '_' + k
466 cr.execute("select name from ir_model_data where name=%s", (name1,))
468 name1 = name1 + "_" + str(id)
469 cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, now(), now(), %s, %s, %s)", \
470 (name1, context['module'], 'ir.model.fields', id)
473 for key, val in vals.items():
474 if cols[k][key] != vals[key]:
475 cr.execute('update ir_model_fields set field_description=%s where model=%s and name=%s', (vals['field_description'], vals['model'], vals['name']))
477 cr.execute("""UPDATE ir_model_fields SET
478 model_id=%s, field_description=%s, ttype=%s, relation=%s,
479 view_load=%s, select_level=%s, readonly=%s ,required=%s, selectable=%s, relation_field=%s
481 model=%s AND name=%s""", (
482 vals['model_id'], vals['field_description'], vals['ttype'],
483 vals['relation'], bool(vals['view_load']),
484 vals['select_level'], bool(vals['readonly']), bool(vals['required']), bool(vals['selectable']), vals['relation_field'], vals['model'], vals['name']
489 def _auto_init(self, cr, context={}):
490 self._field_create(cr, context)
492 def __init__(self, cr):
493 if not self._name and not hasattr(self, '_inherit'):
494 name = type(self).__name__.split('.')[0]
495 msg = "The class %s has to have a _name attribute" % name
497 logger = netsvc.Logger()
498 logger.notifyChannel('orm', netsvc.LOG_ERROR, msg)
499 raise except_orm('ValueError', msg)
501 if not self._description:
502 self._description = self._name
504 self._table = self._name.replace('.', '_')
506 def browse(self, cr, uid, select, context=None, list_class=None, fields_process={}):
508 Fetch records as objects allowing to use dot notation to browse fields and relations
510 :param cr: database cursor
511 :param user: current user id
512 :param select: id or list of ids
513 :param context: context arguments, like lang, time zone
514 :rtype: object or list of objects requested
519 self._list_class = list_class or browse_record_list
521 # need to accepts ints and longs because ids coming from a method
522 # launched by button in the interface have a type long...
523 if isinstance(select, (int, long)):
524 return browse_record(cr, uid, select, self, cache, context=context, list_class=self._list_class, fields_process=fields_process)
525 elif isinstance(select, list):
526 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 def __export_row(self, cr, uid, row, fields, context=None):
534 def check_type(field_type):
535 if field_type == 'float':
537 elif field_type == 'integer':
539 elif field_type == 'boolean':
543 def selection_field(in_field):
544 col_obj = self.pool.get(in_field.keys()[0])
545 if f[i] in col_obj._columns.keys():
546 return col_obj._columns[f[i]]
547 elif f[i] in col_obj._inherits.keys():
548 selection_field(col_obj._inherits)
553 data = map(lambda x: '', range(len(fields)))
554 for fpos in range(len(fields)):
564 model_data = self.pool.get('ir.model.data')
565 data_ids = model_data.search(cr, uid, [('model', '=', r._table_name), ('res_id', '=', r['id'])])
567 d = model_data.read(cr, uid, data_ids, ['name', 'module'])[0]
569 r = '%s.%s' % (d['module'], d['name'])
576 # To display external name of selection field when its exported
577 if not context.get('import_comp', False):# Allow external name only if its not import compatible
579 if f[i] in self._columns.keys():
580 cols = self._columns[f[i]]
581 elif f[i] in self._inherit_fields.keys():
582 cols = selection_field(self._inherits)
583 if cols and cols._type == 'selection':
584 sel_list = cols.selection
585 if r and type(sel_list) == type([]):
586 r = [x[1] for x in sel_list if r==x[0]]
587 r = r and r[0] or False
589 if f[i] in self._columns:
590 r = check_type(self._columns[f[i]]._type)
591 elif f[i] in self._inherit_fields:
592 r = check_type(self._inherit_fields[f[i]][2]._type)
595 if isinstance(r, (browse_record_list, list)):
597 fields2 = map(lambda x: (x[:i+1]==f[:i+1] and x[i+1:]) \
603 lines2 = self.__export_row(cr, uid, row2, fields2,
606 for fpos2 in range(len(fields)):
607 if lines2 and lines2[0][fpos2]:
608 data[fpos2] = lines2[0][fpos2]
612 if isinstance(rr.name, browse_record):
614 rr_name = self.pool.get(rr._table_name).name_get(cr, uid, [rr.id], context=context)
615 rr_name = rr_name and rr_name[0] and rr_name[0][1] or ''
616 dt += tools.ustr(rr_name or '') + ','
626 if isinstance(r, browse_record):
627 r = self.pool.get(r._table_name).name_get(cr, uid, [r.id], context=context)
628 r = r and r[0] and r[0][1] or ''
629 data[fpos] = tools.ustr(r or '')
630 return [data] + lines
632 def export_data(self, cr, uid, ids, fields_to_export, context=None):
634 Export fields for selected objects
636 :param cr: database cursor
637 :param uid: current user id
638 :param ids: list of ids
639 :param fields_to_export: list of fields
640 :param context: context arguments, like lang, time zone, may contain import_comp(default: False) to make exported data compatible with import_data()
641 :rtype: dictionary with a *datas* matrix
643 This method is used when exporting data via client menu
648 imp_comp = context.get('import_comp', False)
649 cols = self._columns.copy()
650 for f in self._inherit_fields:
651 cols.update({f: self._inherit_fields[f][2]})
652 fields_to_export = map(lambda x: x.split('/'), fields_to_export)
653 fields_export = fields_to_export + []
656 for field in fields_export:
657 if imp_comp and len(field) > 1:
658 warning_fields.append('/'.join(map(lambda x: x in cols and cols[x].string or x,field)))
659 elif len (field) <= 1:
660 if imp_comp and cols.get(field and field[0], False):
661 if ((isinstance(cols[field[0]], fields.function) and not cols[field[0]].store) \
662 or isinstance(cols[field[0]], fields.related)\
663 or isinstance(cols[field[0]], fields.one2many)):
664 warning_fields.append('/'.join(map(lambda x: x in cols and cols[x].string or x,field)))
666 if imp_comp and len(warning_fields):
667 warning = 'Following columns cannot be exported since you select to be import compatible.\n%s' % ('\n'.join(warning_fields))
669 return {'warning': warning}
670 for row in self.browse(cr, uid, ids, context):
671 datas += self.__export_row(cr, uid, row, fields_to_export, context)
672 return {'datas': datas}
674 def import_data(self, cr, uid, fields, datas, mode='init', current_module='', noupdate=False, context=None, filename=None):
676 Import given data in given module
678 :param cr: database cursor
679 :param uid: current user id
680 :param ids: list of ids
681 :param fields: list of fields
682 :param data: data to import
683 :param mode: 'init' or 'update' for record creation
684 :param current_module: module name
685 :param noupdate: flag for record creation
686 :param context: context arguments, like lang, time zone,
687 :param filename: optional file to store partial import state for recovery
690 This method is used when importing data via client menu
695 fields = map(lambda x: x.split('/'), fields)
696 logger = netsvc.Logger()
697 ir_model_data_obj = self.pool.get('ir.model.data')
699 def _check_db_id(self, model_name, db_id):
700 obj_model = self.pool.get(model_name)
701 ids = obj_model.search(cr, uid, [('id', '=', int(db_id))])
703 raise Exception(_("Database ID doesn't exist: %s : %s") %(model_name, db_id))
706 def process_liness(self, datas, prefix, current_module, model_name, fields_def, position=0):
707 line = datas[position]
716 ir_model_data_obj = self.pool.get('ir.model.data')
718 # Import normal fields
720 for i in range(len(fields)):
722 raise Exception(_('Please check that all your lines have %d columns.') % (len(fields),))
727 if prefix and not prefix[0] in field:
730 if (len(field)==len(prefix)+1) and field[len(prefix)].endswith(':db_id'):
734 field_name = field[0].split(':')[0]
735 model_rel = fields_def[field_name]['relation']
737 if fields_def[field[len(prefix)][:-6]]['type'] == 'many2many':
739 for db_id in line[i].split(config.get('csv_internal_sep')):
741 _check_db_id(self, model_rel, db_id)
744 warning += [tools.exception_to_unicode(e)]
745 logger.notifyChannel("import", netsvc.LOG_ERROR,
746 tools.exception_to_unicode(e))
748 res = [(6, 0, res_id)]
751 _check_db_id(self, model_rel, line[i])
754 warning += [tools.exception_to_unicode(e)]
755 logger.notifyChannel("import", netsvc.LOG_ERROR,
756 tools.exception_to_unicode(e))
757 row[field_name] = res or False
760 if (len(field)==len(prefix)+1) and field[len(prefix)].endswith(':id'):
763 if fields_def[field[len(prefix)][:-3]]['type'] == 'many2many':
765 for word in line[i].split(config.get('csv_internal_sep')):
767 module, xml_id = word.rsplit('.', 1)
769 module, xml_id = current_module, word
770 id = ir_model_data_obj._get_id(cr, uid, module,
772 res_id2 = ir_model_data_obj.read(cr, uid, [id],
773 ['res_id'])[0]['res_id']
775 res_id.append(res_id2)
777 res_id = [(6, 0, res_id)]
780 module, xml_id = line[i].rsplit('.', 1)
782 module, xml_id = current_module, line[i]
783 record_id = ir_model_data_obj._get_id(cr, uid, module, xml_id)
784 ir_model_data = ir_model_data_obj.read(cr, uid, [record_id], ['res_id'])
786 res_id = ir_model_data[0]['res_id']
788 raise ValueError('No references to %s.%s' % (module, xml_id))
789 row[field[-1][:-3]] = res_id or False
791 if (len(field) == len(prefix)+1) and \
792 len(field[len(prefix)].split(':lang=')) == 2:
793 f, lang = field[len(prefix)].split(':lang=')
794 translate.setdefault(lang, {})[f] = line[i] or False
796 if (len(field) == len(prefix)+1) and \
797 (prefix == field[0:len(prefix)]):
798 if field[len(prefix)] == "id":
801 is_xml_id = data_id = line[i]
802 d = data_id.split('.')
803 module = len(d) > 1 and d[0] or ''
804 name = len(d) > 1 and d[1] or d[0]
805 data_ids = ir_model_data_obj.search(cr, uid, [('module', '=', module), ('model', '=', model_name), ('name', '=', name)])
807 d = ir_model_data_obj.read(cr, uid, data_ids, ['res_id'])[0]
809 if is_db_id and not db_id:
810 data_ids = ir_model_data_obj.search(cr, uid, [('module', '=', module), ('model', '=', model_name), ('res_id', '=', is_db_id)])
811 if not len(data_ids):
812 ir_model_data_obj.create(cr, uid, {'module': module, 'model': model_name, 'name': name, 'res_id': is_db_id})
814 if is_db_id and int(db_id) != int(is_db_id):
815 warning += [_("Id is not the same than existing one: %s") % (is_db_id)]
816 logger.notifyChannel("import", netsvc.LOG_ERROR,
817 _("Id is not the same than existing one: %s") % (is_db_id))
820 if field[len(prefix)] == "db_id":
823 _check_db_id(self, model_name, line[i])
824 data_res_id = is_db_id = int(line[i])
826 warning += [tools.exception_to_unicode(e)]
827 logger.notifyChannel("import", netsvc.LOG_ERROR,
828 tools.exception_to_unicode(e))
830 data_ids = ir_model_data_obj.search(cr, uid, [('model', '=', model_name), ('res_id', '=', line[i])])
832 d = ir_model_data_obj.read(cr, uid, data_ids, ['name', 'module'])[0]
835 data_id = '%s.%s' % (d['module'], d['name'])
838 if is_xml_id and not data_id:
840 if is_xml_id and is_xml_id != data_id:
841 warning += [_("Id is not the same than existing one: %s") % (line[i])]
842 logger.notifyChannel("import", netsvc.LOG_ERROR,
843 _("Id is not the same than existing one: %s") % (line[i]))
846 if fields_def[field[len(prefix)]]['type'] == 'integer':
847 res = line[i] and int(line[i])
848 elif fields_def[field[len(prefix)]]['type'] == 'boolean':
849 res = line[i].lower() not in ('0', 'false', 'off')
850 elif fields_def[field[len(prefix)]]['type'] == 'float':
851 res = line[i] and float(line[i])
852 elif fields_def[field[len(prefix)]]['type'] == 'selection':
854 if isinstance(fields_def[field[len(prefix)]]['selection'],
856 sel = fields_def[field[len(prefix)]]['selection']
858 sel = fields_def[field[len(prefix)]]['selection'](self,
861 if line[i] in [tools.ustr(key), tools.ustr(val)]: #Acepting key or value for selection field
864 if line[i] and not res:
865 logger.notifyChannel("import", netsvc.LOG_WARNING,
866 _("key '%s' not found in selection field '%s'") % \
867 (line[i], field[len(prefix)]))
869 warning += [_("Key/value '%s' not found in selection field '%s'") % (line[i], field[len(prefix)])]
871 elif fields_def[field[len(prefix)]]['type'] == 'many2one':
874 relation = fields_def[field[len(prefix)]]['relation']
875 res2 = self.pool.get(relation).name_search(cr, uid,
876 line[i], [], operator='=', context=context)
877 res = (res2 and res2[0][0]) or False
879 warning += [_("Relation not found: %s on '%s'") % (line[i], relation)]
880 logger.notifyChannel("import", netsvc.LOG_WARNING,
881 _("Relation not found: %s on '%s'") % (line[i], relation))
882 elif fields_def[field[len(prefix)]]['type'] == 'many2many':
885 relation = fields_def[field[len(prefix)]]['relation']
886 for word in line[i].split(config.get('csv_internal_sep')):
887 res2 = self.pool.get(relation).name_search(cr,
888 uid, word, [], operator='=', context=context)
889 res3 = (res2 and res2[0][0]) or False
891 warning += [_("Relation not found: %s on '%s'") % (line[i], relation)]
892 logger.notifyChannel("import",
894 _("Relation not found: %s on '%s'") % (line[i], relation))
900 res = line[i] or False
901 row[field[len(prefix)]] = res
902 elif (prefix==field[0:len(prefix)]):
903 if field[0] not in todo:
904 todo.append(field[len(prefix)])
906 # Import one2many, many2many fields
910 relation_obj = self.pool.get(fields_def[field]['relation'])
911 newfd = relation_obj.fields_get(
912 cr, uid, context=context)
913 res = process_liness(self, datas, prefix + [field], current_module, relation_obj._name, newfd, position)
914 (newrow, max2, w2, translate2, data_id2, data_res_id2) = res
915 nbrmax = max(nbrmax, max2)
916 warning = warning + w2
917 reduce(lambda x, y: x and y, newrow)
918 row[field] = newrow and (reduce(lambda x, y: x or y, newrow.values()) and \
919 [(0, 0, newrow)]) or []
921 while (position+i) < len(datas):
923 for j in range(len(fields)):
925 if (len(field2) <= (len(prefix)+1)) and datas[position+i][j]:
930 (newrow, max2, w2, translate2, data_id2, data_res_id2) = process_liness(
931 self, datas, prefix+[field], current_module, relation_obj._name, newfd, position+i)
932 warning = warning + w2
933 if newrow and reduce(lambda x, y: x or y, newrow.values()):
934 row[field].append((0, 0, newrow))
936 nbrmax = max(nbrmax, i)
939 for i in range(max(nbrmax, 1)):
942 result = (row, nbrmax, warning, translate, data_id, data_res_id)
945 fields_def = self.fields_get(cr, uid, context=context)
948 initial_size = len(datas)
949 if config.get('import_partial', False) and filename:
950 data = pickle.load(file(config.get('import_partial')))
951 original_value = data.get(filename, 0)
957 (res, other, warning, translate, data_id, res_id) = \
958 process_liness(self, datas, [], current_module, self._name, fields_def)
961 return (-1, res, 'Line ' + str(counter) +' : ' + '!\n'.join(warning), '')
964 id = ir_model_data_obj._update(cr, uid, self._name,
965 current_module, res, xml_id=data_id, mode=mode,
966 noupdate=noupdate, res_id=res_id, context=context)
971 if isinstance(e, psycopg2.IntegrityError):
972 msg = _('Insertion Failed! ')
973 for key in self.pool._sql_error.keys():
975 msg = self.pool._sql_error[key]
977 return (-1, res, 'Line ' + str(counter) +' : ' + msg, '')
978 if isinstance(e, osv.orm.except_orm):
979 msg = _('Insertion Failed! ' + e[1])
980 return (-1, res, 'Line ' + str(counter) +' : ' + msg, '')
981 #Raising Uncaught exception
982 return (-1, res, 'Line ' + str(counter) +' : ' + str(e), '')
984 for lang in translate:
985 context2 = context.copy()
986 context2['lang'] = lang
987 self.write(cr, uid, [id], translate[lang], context2)
988 if config.get('import_partial', False) and filename and (not (counter%100)):
989 data = pickle.load(file(config.get('import_partial')))
990 data[filename] = initial_size - len(datas) + original_value
991 pickle.dump(data, file(config.get('import_partial'), 'wb'))
992 if context.get('defer_parent_store_computation'):
993 self._parent_store_compute(cr)
996 #except Exception, e:
997 # logger.notifyChannel("import", netsvc.LOG_ERROR, e)
1000 # return (-1, res, e[0], warning)
1002 # return (-1, res, e[0], '')
1005 # TODO: Send a request with the result and multi-thread !
1007 if context.get('defer_parent_store_computation'):
1008 self._parent_store_compute(cr)
1009 return (done, 0, 0, 0)
1011 def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
1012 raise NotImplementedError(_('The read method is not implemented on this object !'))
1014 def get_invalid_fields(self, cr, uid):
1015 return list(self._invalids)
1017 def _validate(self, cr, uid, ids, context=None):
1018 context = context or {}
1019 lng = context.get('lang', False) or 'en_US'
1020 trans = self.pool.get('ir.translation')
1022 for constraint in self._constraints:
1023 fun, msg, fields = constraint
1024 if not fun(self, cr, uid, ids):
1025 # Check presence of __call__ directly instead of using
1026 # callable() because it will be deprecated as of Python 3.0
1027 if hasattr(msg, '__call__'):
1028 txt_msg, params = msg(self, cr, uid, ids)
1029 tmp_msg = trans._get_source(cr, uid, self._name, 'constraint', lng, source=txt_msg) or txt_msg
1030 translated_msg = tmp_msg % params
1032 translated_msg = trans._get_source(cr, uid, self._name, 'constraint', lng, source=msg) or msg
1034 _("Error occurred while validating the field(s) %s: %s") % (','.join(fields), translated_msg)
1036 self._invalids.update(fields)
1039 raise except_orm('ValidateError', '\n'.join(error_msgs))
1041 self._invalids.clear()
1043 def default_get(self, cr, uid, fields_list, context=None):
1045 Returns default values for the fields in fields_list.
1047 :param fields_list: list of fields to get the default values for (example ['field1', 'field2',])
1048 :type fields_list: list
1049 :param context: usual context dictionary - it may contains keys in the form ``default_XXX``,
1050 where XXX is a field name to set or override a default value.
1051 :return: dictionary of the default values (set on the object model class, through user preferences, or in the context)
1053 # trigger view init hook
1054 self.view_init(cr, uid, fields_list, context)
1060 # get the default values for the inherited fields
1061 for t in self._inherits.keys():
1062 defaults.update(self.pool.get(t).default_get(cr, uid, fields_list,
1065 # get the default values defined in the object
1066 for f in fields_list:
1067 if f in self._defaults:
1068 if callable(self._defaults[f]):
1069 defaults[f] = self._defaults[f](self, cr, uid, context)
1071 defaults[f] = self._defaults[f]
1073 fld_def = ((f in self._columns) and self._columns[f]) \
1074 or ((f in self._inherit_fields) and self._inherit_fields[f][2]) \
1077 if isinstance(fld_def, fields.property):
1078 property_obj = self.pool.get('ir.property')
1079 prop_value = property_obj.get(cr, uid, f, self._name, context=context)
1081 if isinstance(prop_value, (browse_record, browse_null)):
1082 defaults[f] = prop_value.id
1084 defaults[f] = prop_value
1086 if f not in defaults:
1089 # get the default values set by the user and override the default
1090 # values defined in the object
1091 ir_values_obj = self.pool.get('ir.values')
1092 res = ir_values_obj.get(cr, uid, 'default', False, [self._name])
1093 for id, field, field_value in res:
1094 if field in fields_list:
1095 fld_def = (field in self._columns) and self._columns[field] or self._inherit_fields[field][2]
1096 if fld_def._type in ('many2one', 'one2one'):
1097 obj = self.pool.get(fld_def._obj)
1098 if not obj.search(cr, uid, [('id', '=', field_value or False)]):
1100 if fld_def._type in ('many2many'):
1101 obj = self.pool.get(fld_def._obj)
1103 for i in range(len(field_value)):
1104 if not obj.search(cr, uid, [('id', '=',
1107 field_value2.append(field_value[i])
1108 field_value = field_value2
1109 if fld_def._type in ('one2many'):
1110 obj = self.pool.get(fld_def._obj)
1112 for i in range(len(field_value)):
1113 field_value2.append({})
1114 for field2 in field_value[i]:
1115 if field2 in obj._columns.keys() and obj._columns[field2]._type in ('many2one', 'one2one'):
1116 obj2 = self.pool.get(obj._columns[field2]._obj)
1117 if not obj2.search(cr, uid,
1118 [('id', '=', field_value[i][field2])]):
1120 elif field2 in obj._inherit_fields.keys() and obj._inherit_fields[field2][2]._type in ('many2one', 'one2one'):
1121 obj2 = self.pool.get(obj._inherit_fields[field2][2]._obj)
1122 if not obj2.search(cr, uid,
1123 [('id', '=', field_value[i][field2])]):
1125 # TODO add test for many2many and one2many
1126 field_value2[i][field2] = field_value[i][field2]
1127 field_value = field_value2
1128 defaults[field] = field_value
1130 # get the default values from the context
1131 for key in context or {}:
1132 if key.startswith('default_') and (key[8:] in fields_list):
1133 defaults[key[8:]] = context[key]
1137 def perm_read(self, cr, user, ids, context=None, details=True):
1138 raise NotImplementedError(_('The perm_read method is not implemented on this object !'))
1140 def unlink(self, cr, uid, ids, context=None):
1141 raise NotImplementedError(_('The unlink method is not implemented on this object !'))
1143 def write(self, cr, user, ids, vals, context=None):
1144 raise NotImplementedError(_('The write method is not implemented on this object !'))
1146 def create(self, cr, user, vals, context=None):
1147 raise NotImplementedError(_('The create method is not implemented on this object !'))
1149 def fields_get_keys(self, cr, user, context=None):
1150 res = self._columns.keys()
1151 for parent in self._inherits:
1152 res.extend(self.pool.get(parent).fields_get_keys(cr, user, context))
1155 # returns the definition of each field in the object
1156 # the optional fields parameter can limit the result to some fields
1157 def fields_get(self, cr, user, allfields=None, context=None, write_access=True):
1161 translation_obj = self.pool.get('ir.translation')
1162 for parent in self._inherits:
1163 res.update(self.pool.get(parent).fields_get(cr, user, allfields, context))
1165 if self._columns.keys():
1166 for f in self._columns.keys():
1167 if allfields and f not in allfields:
1169 res[f] = {'type': self._columns[f]._type}
1170 # This additional attributes for M2M and function field is added
1171 # because we need to display tooltip with this additional information
1172 # when client is started in debug mode.
1173 if isinstance(self._columns[f], fields.function):
1174 res[f]['function'] = self._columns[f]._fnct and self._columns[f]._fnct.func_name or False
1175 res[f]['store'] = self._columns[f].store
1176 if isinstance(self._columns[f].store, dict):
1177 res[f]['store'] = str(self._columns[f].store)
1178 res[f]['fnct_search'] = self._columns[f]._fnct_search and self._columns[f]._fnct_search.func_name or False
1179 res[f]['fnct_inv'] = self._columns[f]._fnct_inv and self._columns[f]._fnct_inv.func_name or False
1180 res[f]['fnct_inv_arg'] = self._columns[f]._fnct_inv_arg or False
1181 res[f]['func_obj'] = self._columns[f]._obj or False
1182 res[f]['func_method'] = self._columns[f]._method
1183 if isinstance(self._columns[f], fields.many2many):
1184 res[f]['related_columns'] = list((self._columns[f]._id1, self._columns[f]._id2))
1185 res[f]['third_table'] = self._columns[f]._rel
1186 for arg in ('string', 'readonly', 'states', 'size', 'required', 'group_operator',
1187 'change_default', 'translate', 'help', 'select', 'selectable'):
1188 if getattr(self._columns[f], arg):
1189 res[f][arg] = getattr(self._columns[f], arg)
1190 if not write_access:
1191 res[f]['readonly'] = True
1192 res[f]['states'] = {}
1193 for arg in ('digits', 'invisible', 'filters'):
1194 if getattr(self._columns[f], arg, None):
1195 res[f][arg] = getattr(self._columns[f], arg)
1197 res_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'field', context.get('lang', False) or 'en_US', self._columns[f].string)
1199 res[f]['string'] = res_trans
1200 help_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'help', context.get('lang', False) or 'en_US')
1202 res[f]['help'] = help_trans
1204 if hasattr(self._columns[f], 'selection'):
1205 if isinstance(self._columns[f].selection, (tuple, list)):
1206 sel = self._columns[f].selection
1207 # translate each selection option
1209 for (key, val) in sel:
1212 val2 = translation_obj._get_source(cr, user, self._name + ',' + f, 'selection', context.get('lang', False) or 'en_US', val)
1213 sel2.append((key, val2 or val))
1215 res[f]['selection'] = sel
1217 # call the 'dynamic selection' function
1218 res[f]['selection'] = self._columns[f].selection(self, cr,
1220 if res[f]['type'] in ('one2many', 'many2many', 'many2one', 'one2one'):
1221 res[f]['relation'] = self._columns[f]._obj
1222 res[f]['domain'] = self._columns[f]._domain
1223 res[f]['context'] = self._columns[f]._context
1225 #TODO : read the fields from the database
1229 # filter out fields which aren't in the fields list
1230 for r in res.keys():
1231 if r not in allfields:
1236 # Overload this method if you need a window title which depends on the context
1238 def view_header_get(self, cr, user, view_id=None, view_type='form', context=None):
1241 def __view_look_dom(self, cr, user, node, view_id, context=None):
1249 if isinstance(s, unicode):
1250 return s.encode('utf8')
1253 # return True if node can be displayed to current user
1254 def check_group(node):
1255 if node.get('groups'):
1256 groups = node.get('groups').split(',')
1257 access_pool = self.pool.get('ir.model.access')
1258 can_see = any(access_pool.check_groups(cr, user, group) for group in groups)
1260 node.set('invisible', '1')
1261 if 'attrs' in node.attrib:
1262 del(node.attrib['attrs']) #avoid making field visible later
1263 del(node.attrib['groups'])
1268 if node.tag in ('field', 'node', 'arrow'):
1269 if node.get('object'):
1274 if f.tag in ('field'):
1275 xml += etree.tostring(f, encoding="utf-8")
1277 new_xml = etree.fromstring(encode(xml))
1278 ctx = context.copy()
1279 ctx['base_model_name'] = self._name
1280 xarch, xfields = self.pool.get(node.get('object', False)).__view_look_dom_arch(cr, user, new_xml, view_id, ctx)
1281 views[str(f.tag)] = {
1285 attrs = {'views': views}
1287 fields = views.get('field', False) and views['field'].get('fields', False)
1288 if node.get('name'):
1291 if node.get('name') in self._columns:
1292 column = self._columns[node.get('name')]
1294 column = self._inherit_fields[node.get('name')][2]
1299 relation = self.pool.get(column._obj)
1304 if f.tag in ('form', 'tree', 'graph'):
1306 ctx = context.copy()
1307 ctx['base_model_name'] = self._name
1308 xarch, xfields = relation.__view_look_dom_arch(cr, user, f, view_id, ctx)
1309 views[str(f.tag)] = {
1313 attrs = {'views': views}
1314 if node.get('widget') and node.get('widget') == 'selection':
1315 # Prepare the cached selection list for the client. This needs to be
1316 # done even when the field is invisible to the current user, because
1317 # other events could need to change its value to any of the selectable ones
1318 # (such as on_change events, refreshes, etc.)
1320 # If domain and context are strings, we keep them for client-side, otherwise
1321 # we evaluate them server-side to consider them when generating the list of
1323 # TODO: find a way to remove this hack, by allow dynamic domains
1325 if column._domain and not isinstance(column._domain, basestring):
1326 dom = column._domain
1327 dom += eval(node.get('domain', '[]'), {'uid': user, 'time': time})
1328 search_context = dict(context)
1329 if column._context and not isinstance(column._context, basestring):
1330 search_context.update(column._context)
1331 attrs['selection'] = relation._name_search(cr, user, '', dom, context=search_context, limit=None, name_get_uid=1)
1332 if (node.get('required') and not int(node.get('required'))) or not column.required:
1333 attrs['selection'].append((False, ''))
1334 fields[node.get('name')] = attrs
1336 elif node.tag in ('form', 'tree'):
1337 result = self.view_header_get(cr, user, False, node.tag, context)
1339 node.set('string', result)
1341 elif node.tag == 'calendar':
1342 for additional_field in ('date_start', 'date_delay', 'date_stop', 'color'):
1343 if node.get(additional_field):
1344 fields[node.get(additional_field)] = {}
1346 if 'groups' in node.attrib:
1350 if ('lang' in context) and not result:
1351 if node.get('string'):
1352 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('string'))
1353 if not trans and ('base_model_name' in context):
1354 trans = self.pool.get('ir.translation')._get_source(cr, user, context['base_model_name'], 'view', context['lang'], node.get('string'))
1356 node.set('string', trans)
1358 trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('sum'))
1360 node.set('sum', trans)
1363 if childs or (node.tag == 'field' and f.tag in ('filter','separator')):
1364 fields.update(self.__view_look_dom(cr, user, f, view_id, context))
1368 def __view_look_dom_arch(self, cr, user, node, view_id, context=None):
1369 fields_def = self.__view_look_dom(cr, user, node, view_id, context=context)
1371 rolesobj = self.pool.get('res.roles')
1372 usersobj = self.pool.get('res.users')
1374 buttons = (n for n in node.getiterator('button') if n.get('type') != 'object')
1375 for button in buttons:
1377 if user != 1: # admin user has all roles
1378 user_roles = usersobj.read(cr, user, [user], ['roles_id'])[0]['roles_id']
1379 # TODO handle the case of more than one workflow for a model
1380 cr.execute("""SELECT DISTINCT t.role_id
1382 INNER JOIN wkf_activity a ON a.wkf_id = wkf.id
1383 INNER JOIN wkf_transition t ON (t.act_to = a.id)
1386 """, (self._name, button.get('name'),))
1387 roles = cr.fetchall()
1389 # draft -> valid = signal_next (role X)
1390 # draft -> cancel = signal_cancel (no role)
1392 # valid -> running = signal_next (role Y)
1393 # valid -> cancel = signal_cancel (role Z)
1395 # running -> done = signal_next (role Z)
1396 # running -> cancel = signal_cancel (role Z)
1398 # As we don't know the object state, in this scenario,
1399 # the button "signal_cancel" will be always shown as there is no restriction to cancel in draft
1400 # the button "signal_next" will be show if the user has any of the roles (X Y or Z)
1401 # The verification will be made later in workflow process...
1403 can_click = any((not role) or rolesobj.check(cr, user, user_roles, role) for (role,) in roles)
1405 button.set('readonly', str(int(not can_click)))
1407 arch = etree.tostring(node, encoding="utf-8").replace('\t', '')
1410 if node.tag == 'diagram':
1411 if node.getchildren()[0].tag == 'node':
1412 node_fields = self.pool.get(node.getchildren()[0].get('object')).fields_get(cr, user, fields_def.keys(), context)
1413 if node.getchildren()[1].tag == 'arrow':
1414 arrow_fields = self.pool.get(node.getchildren()[1].get('object')).fields_get(cr, user, fields_def.keys(), context)
1415 for key, value in node_fields.items():
1417 for key, value in arrow_fields.items():
1420 fields = self.fields_get(cr, user, fields_def.keys(), context)
1421 for field in fields_def:
1423 # sometime, the view may containt the (invisible) field 'id' needed for a domain (when 2 objects have cross references)
1424 fields['id'] = {'readonly': True, 'type': 'integer', 'string': 'ID'}
1425 elif field in fields:
1426 fields[field].update(fields_def[field])
1428 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))
1429 res = cr.fetchall()[:]
1431 res.insert(0, ("Can't find field '%s' in the following view parts composing the view of object model '%s':" % (field, model), None))
1432 msg = "\n * ".join([r[0] for r in res])
1433 msg += "\n\nEither you wrongly customised this view, or some modules bringing those views are not compatible with your current data model"
1434 netsvc.Logger().notifyChannel('orm', netsvc.LOG_ERROR, msg)
1435 raise except_orm('View error', msg)
1438 def __get_default_calendar_view(self):
1439 """Generate a default calendar view (For internal use only).
1442 arch = ('<?xml version="1.0" encoding="utf-8"?>\n'
1443 '<calendar string="%s"') % (self._description)
1445 if (self._date_name not in self._columns):
1447 for dt in ['date', 'date_start', 'x_date', 'x_date_start']:
1448 if dt in self._columns:
1449 self._date_name = dt
1454 raise except_orm(_('Invalid Object Architecture!'), _("Insufficient fields for Calendar View!"))
1457 arch += ' date_start="%s"' % (self._date_name)
1459 for color in ["user_id", "partner_id", "x_user_id", "x_partner_id"]:
1460 if color in self._columns:
1461 arch += ' color="' + color + '"'
1464 dt_stop_flag = False
1466 for dt_stop in ["date_stop", "date_end", "x_date_stop", "x_date_end"]:
1467 if dt_stop in self._columns:
1468 arch += ' date_stop="' + dt_stop + '"'
1472 if not dt_stop_flag:
1473 for dt_delay in ["date_delay", "planned_hours", "x_date_delay", "x_planned_hours"]:
1474 if dt_delay in self._columns:
1475 arch += ' date_delay="' + dt_delay + '"'
1479 ' <field name="%s"/>\n'
1480 '</calendar>') % (self._rec_name)
1484 def __get_default_search_view(self, cr, uid, context={}):
1487 if isinstance(s, unicode):
1488 return s.encode('utf8')
1491 view = self.fields_view_get(cr, uid, False, 'form', context)
1493 root = etree.fromstring(encode(view['arch']))
1494 res = etree.XML("""<search string="%s"></search>""" % root.get("string", ""))
1495 node = etree.Element("group")
1498 fields = root.xpath("//field[@select=1]")
1499 for field in fields:
1502 return etree.tostring(res, encoding="utf-8").replace('\t', '')
1505 # if view_id, view_type is not required
1507 def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
1509 Get the detailed composition of the requested view like fields, model, view architecture
1511 :param cr: database cursor
1512 :param user: current user id
1513 :param view_id: id of the view or None
1514 :param view_type: type of the view to return if view_id is None ('form', tree', ...)
1515 :param context: context arguments, like lang, time zone
1516 :param toolbar: true to include contextual actions
1517 :param submenu: example (portal_project module)
1518 :return: dictionary describing the composition of the requested view (including inherited views and extensions)
1519 :raise AttributeError:
1520 * if the inherited view has unknown position to work with other than 'before', 'after', 'inside', 'replace'
1521 * if some tag other than 'position' is found in parent view
1522 :raise Invalid ArchitectureError: if there is view type other than form, tree, calendar, search etc defined on the structure
1529 if isinstance(s, unicode):
1530 return s.encode('utf8')
1533 def _inherit_apply(src, inherit):
1534 def _find(node, node2):
1535 if node2.tag == 'xpath':
1536 res = node.xpath(node2.get('expr'))
1542 for n in node.getiterator(node2.tag):
1544 if node2.tag == 'field':
1545 # only compare field names, a field can be only once in a given view
1546 # at a given level (and for multilevel expressions, we should use xpath
1547 # inheritance spec anyway)
1548 if node2.get('name') == n.get('name'):
1552 for attr in node2.attrib:
1553 if attr == 'position':
1556 if n.get(attr) == node2.get(attr):
1563 # End: _find(node, node2)
1565 doc_dest = etree.fromstring(encode(inherit))
1566 toparse = [doc_dest]
1569 node2 = toparse.pop(0)
1570 if node2.tag == 'data':
1571 toparse += [ c for c in doc_dest ]
1573 node = _find(src, node2)
1574 if node is not None:
1576 if node2.get('position'):
1577 pos = node2.get('position')
1578 if pos == 'replace':
1579 parent = node.getparent()
1581 src = copy.deepcopy(node2[0])
1584 node.addprevious(child)
1585 node.getparent().remove(node)
1586 elif pos == 'attributes':
1587 for child in node2.getiterator('attribute'):
1588 attribute = (child.get('name'), child.text and child.text.encode('utf8') or None)
1590 node.set(attribute[0], attribute[1])
1592 del(node.attrib[attribute[0]])
1594 sib = node.getnext()
1598 elif pos == 'after':
1602 sib.addprevious(child)
1603 elif pos == 'before':
1604 node.addprevious(child)
1606 raise AttributeError(_('Unknown position in inherited view %s !') % pos)
1609 ' %s="%s"' % (attr, node2.get(attr))
1610 for attr in node2.attrib
1611 if attr != 'position'
1613 tag = "<%s%s>" % (node2.tag, attrs)
1614 raise AttributeError(_("Couldn't find tag '%s' in parent view !") % tag)
1616 # End: _inherit_apply(src, inherit)
1618 result = {'type': view_type, 'model': self._name}
1624 view_ref = context.get(view_type + '_view_ref', False)
1625 if view_ref and not view_id:
1627 module, view_ref = view_ref.split('.', 1)
1628 cr.execute("SELECT res_id FROM ir_model_data WHERE model='ir.ui.view' AND module=%s AND name=%s", (module, view_ref))
1629 view_ref_res = cr.fetchone()
1631 view_id = view_ref_res[0]
1634 query = "SELECT arch,name,field_parent,id,type,inherit_id FROM ir_ui_view WHERE id=%s"
1637 query += " AND model=%s"
1638 params += (self._name,)
1639 cr.execute(query, params)
1641 cr.execute('''SELECT
1642 arch,name,field_parent,id,type,inherit_id
1649 ORDER BY priority''', (self._name, view_type))
1650 sql_res = cr.fetchone()
1656 view_id = ok or sql_res[3]
1659 # if a view was found
1661 result['type'] = sql_res[4]
1662 result['view_id'] = sql_res[3]
1663 result['arch'] = sql_res[0]
1665 def _inherit_apply_rec(result, inherit_id):
1666 # get all views which inherit from (ie modify) this view
1667 cr.execute('select arch,id from ir_ui_view where inherit_id=%s and model=%s order by priority', (inherit_id, self._name))
1668 sql_inherit = cr.fetchall()
1669 for (inherit, id) in sql_inherit:
1670 result = _inherit_apply(result, inherit)
1671 result = _inherit_apply_rec(result, id)
1674 inherit_result = etree.fromstring(encode(result['arch']))
1675 result['arch'] = _inherit_apply_rec(inherit_result, sql_res[3])
1677 result['name'] = sql_res[1]
1678 result['field_parent'] = sql_res[2] or False
1681 # otherwise, build some kind of default view
1682 if view_type == 'form':
1683 res = self.fields_get(cr, user, context=context)
1684 xml = '<?xml version="1.0" encoding="utf-8"?> ' \
1685 '<form string="%s">' % (self._description,)
1687 if res[x]['type'] not in ('one2many', 'many2many'):
1688 xml += '<field name="%s"/>' % (x,)
1689 if res[x]['type'] == 'text':
1693 elif view_type == 'tree':
1694 _rec_name = self._rec_name
1695 if _rec_name not in self._columns:
1696 _rec_name = self._columns.keys()[0]
1697 xml = '<?xml version="1.0" encoding="utf-8"?>' \
1698 '<tree string="%s"><field name="%s"/></tree>' \
1699 % (self._description, self._rec_name)
1701 elif view_type == 'calendar':
1702 xml = self.__get_default_calendar_view()
1704 elif view_type == 'search':
1705 xml = self.__get_default_search_view(cr, user, context)
1708 xml = '<?xml version="1.0"?>' # what happens here, graph case?
1709 raise except_orm(_('Invalid Architecture!'), _("There is no view of type '%s' defined for the structure!") % view_type)
1710 result['arch'] = etree.fromstring(encode(xml))
1711 result['name'] = 'default'
1712 result['field_parent'] = False
1713 result['view_id'] = 0
1715 xarch, xfields = self.__view_look_dom_arch(cr, user, result['arch'], view_id, context=context)
1716 result['arch'] = xarch
1717 result['fields'] = xfields
1720 if context and context.get('active_id', False):
1721 data_menu = self.pool.get('ir.ui.menu').browse(cr, user, context['active_id'], context).action
1723 act_id = data_menu.id
1725 data_action = self.pool.get('ir.actions.act_window').browse(cr, user, [act_id], context)[0]
1726 result['submenu'] = getattr(data_action, 'menus', False)
1730 for key in ('report_sxw_content', 'report_rml_content',
1731 'report_sxw', 'report_rml',
1732 'report_sxw_content_data', 'report_rml_content_data'):
1736 ir_values_obj = self.pool.get('ir.values')
1737 resprint = ir_values_obj.get(cr, user, 'action',
1738 'client_print_multi', [(self._name, False)], False,
1741 resaction = ir_values_obj.get(cr, user, 'action',
1742 'client_action_multi', [(self._name, False)], False,
1745 resrelate = ir_values_obj.get(cr, user, 'action',
1746 'client_action_relate', [(self._name, False)], False,
1748 resprint = map(clean, resprint)
1749 resaction = map(clean, resaction)
1750 resaction = filter(lambda x: not x.get('multi', False), resaction)
1751 resprint = filter(lambda x: not x.get('multi', False), resprint)
1752 resrelate = map(lambda x: x[2], resrelate)
1754 for x in resprint + resaction + resrelate:
1755 x['string'] = x['name']
1757 result['toolbar'] = {
1759 'action': resaction,
1764 _view_look_dom_arch = __view_look_dom_arch
1766 def search_count(self, cr, user, args, context=None):
1769 res = self.search(cr, user, args, context=context, count=True)
1770 if isinstance(res, list):
1774 def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
1776 Search for records based on a search domain.
1778 :param cr: database cursor
1779 :param user: current user id
1780 :param args: list of tuples specifying the search domain [('field_name', 'operator', value), ...]. Pass an empty list to match all records.
1781 :param offset: optional number of results to skip in the returned values (default: 0)
1782 :param limit: optional max number of records to return (default: **None**)
1783 :param order: optional columns to sort by (default: self._order=id )
1784 :param context: optional context arguments, like lang, time zone
1785 :type context: dictionary
1786 :param count: optional (default: **False**), if **True**, returns only the number of records matching the criteria, not their ids
1787 :return: id or list of ids of records matching the criteria
1788 :rtype: integer or list of integers
1789 :raise AccessError: * if user tries to bypass access rules for read on the requested object.
1791 **Expressing a search domain (args)**
1793 Each tuple in the search domain needs to have 3 elements, in the form: **('field_name', 'operator', value)**, where:
1795 * **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.
1796 * **operator** must be a string with a valid comparison operator from this list: ``=, !=, >, >=, <, <=, like, ilike, in, not in, child_of, parent_left, parent_right``
1797 The semantics of most of these operators are obvious.
1798 The ``child_of`` operator will look for records who are children or grand-children of a given record,
1799 according to the semantics of this model (i.e following the relationship field named by
1800 ``self._parent_name``, by default ``parent_id``.
1801 * **value** must be a valid value to compare with the values of **field_name**, depending on its type.
1803 Domain criteria can be combined using 3 logical operators than can be added between tuples: '**&**' (logical AND, default), '**|**' (logical OR), '**!**' (logical NOT).
1804 These are **prefix** operators and the arity of the '**&**' and '**|**' operator is 2, while the arity of the '**!**' is just 1.
1805 Be very careful about this when you combine them the first time.
1807 Here is an example of searching for Partners named *ABC* from Belgium and Germany whose language is not english ::
1809 [('name','=','ABC'),'!',('language.code','=','en_US'),'|',('country_id.code','=','be'),('country_id.code','=','de'))
1811 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::
1813 (name is 'ABC' AND (language is NOT english) AND (country is Belgium OR Germany))
1816 return self._search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count)
1818 def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
1820 Private implementation of search() method, allowing specifying the uid to use for the access right check.
1821 This is useful for example when filling in the selection list for a drop-down and avoiding access rights errors,
1822 by specifying ``access_rights_uid=1`` to bypass access rights check, but not ir.rules!
1824 :param access_rights_uid: optional user ID to use when checking access rights
1825 (not for ir.rules, this is only for ir.model.access)
1827 raise NotImplementedError(_('The search method is not implemented on this object !'))
1829 def name_get(self, cr, user, ids, context=None):
1832 :param cr: database cursor
1833 :param user: current user id
1835 :param ids: list of ids
1836 :param context: context arguments, like lang, time zone
1837 :type context: dictionary
1838 :return: tuples with the text representation of requested objects for to-many relationships
1845 if isinstance(ids, (int, long)):
1847 return [(r['id'], tools.ustr(r[self._rec_name])) for r in self.read(cr, user, ids,
1848 [self._rec_name], context, load='_classic_write')]
1850 def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
1852 Search for records and their display names according to a search domain.
1854 :param cr: database cursor
1855 :param user: current user id
1856 :param name: object name to search
1857 :param args: list of tuples specifying search criteria [('field_name', 'operator', 'value'), ...]
1858 :param operator: operator for search criterion
1859 :param context: context arguments, like lang, time zone
1860 :type context: dictionary
1861 :param limit: optional max number of records to return
1862 :return: list of object names matching the search criteria, used to provide completion for to-many relationships
1864 This method is equivalent of :py:meth:`~osv.osv.osv.search` on **name** + :py:meth:`~osv.osv.osv.name_get` on the result.
1865 See :py:meth:`~osv.osv.osv.search` for an explanation of the possible values for the search domain specified in **args**.
1868 return self._name_search(cr, user, name, args, operator, context, limit)
1870 # private implementation of name_search, allows passing a dedicated user for the name_get part to
1871 # solve some access rights issues
1872 def _name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100, name_get_uid=None):
1879 args += [(self._rec_name, operator, name)]
1880 access_rights_uid = name_get_uid or user
1881 ids = self._search(cr, user, args, limit=limit, context=context, access_rights_uid=access_rights_uid)
1882 res = self.name_get(cr, access_rights_uid, ids, context)
1885 def copy(self, cr, uid, id, default=None, context=None):
1886 raise NotImplementedError(_('The copy method is not implemented on this object !'))
1888 def exists(self, cr, uid, id, context=None):
1889 raise NotImplementedError(_('The exists method is not implemented on this object !'))
1891 def read_string(self, cr, uid, id, langs, fields=None, context=None):
1894 self.pool.get('ir.model.access').check(cr, uid, 'ir.translation', 'read', context=context)
1896 fields = self._columns.keys() + self._inherit_fields.keys()
1897 #FIXME: collect all calls to _get_source into one SQL call.
1899 res[lang] = {'code': lang}
1901 if f in self._columns:
1902 res_trans = self.pool.get('ir.translation')._get_source(cr, uid, self._name+','+f, 'field', lang)
1904 res[lang][f] = res_trans
1906 res[lang][f] = self._columns[f].string
1907 for table in self._inherits:
1908 cols = intersect(self._inherit_fields.keys(), fields)
1909 res2 = self.pool.get(table).read_string(cr, uid, id, langs, cols, context)
1912 res[lang]['code'] = lang
1913 for f in res2[lang]:
1914 res[lang][f] = res2[lang][f]
1917 def write_string(self, cr, uid, id, langs, vals, context=None):
1918 self.pool.get('ir.model.access').check(cr, uid, 'ir.translation', 'write', context=context)
1919 #FIXME: try to only call the translation in one SQL
1922 if field in self._columns:
1923 src = self._columns[field].string
1924 self.pool.get('ir.translation')._set_ids(cr, uid, self._name+','+field, 'field', lang, [0], vals[field], src)
1925 for table in self._inherits:
1926 cols = intersect(self._inherit_fields.keys(), vals)
1928 self.pool.get(table).write_string(cr, uid, id, langs, vals, context)
1931 def _check_removed_columns(self, cr, log=False):
1932 raise NotImplementedError()
1934 def _add_missing_default_values(self, cr, uid, values, context=None):
1935 missing_defaults = []
1936 avoid_tables = [] # avoid overriding inherited values when parent is set
1937 for tables, parent_field in self._inherits.items():
1938 if parent_field in values:
1939 avoid_tables.append(tables)
1940 for field in self._columns.keys():
1941 if not field in values:
1942 missing_defaults.append(field)
1943 for field in self._inherit_fields.keys():
1944 if (field not in values) and (self._inherit_fields[field][0] not in avoid_tables):
1945 missing_defaults.append(field)
1947 if len(missing_defaults):
1948 # override defaults with the provided values, never allow the other way around
1949 defaults = self.default_get(cr, uid, missing_defaults, context)
1951 # FIXME: also handle inherited m2m
1952 if dv in self._columns and self._columns[dv]._type == 'many2many' \
1953 and defaults[dv] and isinstance(defaults[dv][0], (int, long)):
1954 defaults[dv] = [(6, 0, defaults[dv])]
1955 defaults.update(values)
1959 class orm_memory(orm_template):
1961 _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']
1962 _inherit_fields = {}
1967 def __init__(self, cr):
1968 super(orm_memory, self).__init__(cr)
1972 cr.execute('delete from wkf_instance where res_type=%s', (self._name,))
1974 def _check_access(self, uid, object_id, mode):
1975 if uid != 1 and self.datas[object_id]['internal.create_uid'] != uid:
1976 raise except_orm(_('AccessError'), '%s access is only allowed on your own records for osv_memory objects except for the super-user' % mode.capitalize())
1978 def vaccum(self, cr, uid):
1980 if self.check_id % self._check_time:
1983 max = time.time() - self._max_hours * 60 * 60
1984 for id in self.datas:
1985 if self.datas[id]['internal.date_access'] < max:
1987 self.unlink(cr, 1, tounlink)
1988 if len(self.datas) > self._max_count:
1989 sorted = map(lambda x: (x[1]['internal.date_access'], x[0]), self.datas.items())
1991 ids = map(lambda x: x[1], sorted[:len(self.datas)-self._max_count])
1992 self.unlink(cr, uid, ids)
1995 def read(self, cr, user, ids, fields_to_read=None, context=None, load='_classic_read'):
1998 if not fields_to_read:
1999 fields_to_read = self._columns.keys()
2003 if isinstance(ids, (int, long)):
2007 for f in fields_to_read:
2008 record = self.datas.get(id)
2010 self._check_access(user, id, 'read')
2011 r[f] = record.get(f, False)
2012 if r[f] and isinstance(self._columns[f], fields.binary) and context.get('bin_size', False):
2015 if id in self.datas:
2016 self.datas[id]['internal.date_access'] = time.time()
2017 fields_post = filter(lambda x: x in self._columns and not getattr(self._columns[x], load), fields_to_read)
2018 for f in fields_post:
2019 res2 = self._columns[f].get_memory(cr, self, ids, f, user, context=context, values=result)
2020 for record in result:
2021 record[f] = res2[record['id']]
2022 if isinstance(ids_orig, (int, long)):
2026 def write(self, cr, user, ids, vals, context=None):
2032 if self._columns[field]._classic_write:
2033 vals2[field] = vals[field]
2035 upd_todo.append(field)
2036 for object_id in ids:
2037 self._check_access(user, object_id, mode='write')
2038 self.datas[object_id].update(vals2)
2039 self.datas[object_id]['internal.date_access'] = time.time()
2040 for field in upd_todo:
2041 self._columns[field].set_memory(cr, self, object_id, field, vals[field], user, context)
2042 self._validate(cr, user, [object_id], context)
2043 wf_service = netsvc.LocalService("workflow")
2044 wf_service.trg_write(user, self._name, object_id, cr)
2047 def create(self, cr, user, vals, context=None):
2048 self.vaccum(cr, user)
2050 id_new = self.next_id
2052 vals = self._add_missing_default_values(cr, user, vals, context)
2057 if self._columns[field]._classic_write:
2058 vals2[field] = vals[field]
2060 upd_todo.append(field)
2061 self.datas[id_new] = vals2
2062 self.datas[id_new]['internal.date_access'] = time.time()
2063 self.datas[id_new]['internal.create_uid'] = user
2065 for field in upd_todo:
2066 self._columns[field].set_memory(cr, self, id_new, field, vals[field], user, context)
2067 self._validate(cr, user, [id_new], context)
2068 if self._log_create and not (context and context.get('no_store_function', False)):
2069 message = self._description + \
2071 self.name_get(cr, user, [id_new], context=context)[0][1] + \
2073 self.log(cr, user, id_new, message, True, context=context)
2074 wf_service = netsvc.LocalService("workflow")
2075 wf_service.trg_create(user, self._name, id_new, cr)
2078 def _where_calc(self, cr, user, args, active_test=True, context=None):
2083 # if the object has a field named 'active', filter out all inactive
2084 # records unless they were explicitely asked for
2085 if 'active' in self._columns and (active_test and context.get('active_test', True)):
2087 active_in_args = False
2089 if a[0] == 'active':
2090 active_in_args = True
2091 if not active_in_args:
2092 args.insert(0, ('active', '=', 1))
2094 args = [('active', '=', 1)]
2097 e = expression.expression(args)
2098 e.parse(cr, user, self, context)
2102 def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
2106 # implicit filter on current user except for superuser
2110 args.insert(0, ('internal.create_uid', '=', user))
2112 result = self._where_calc(cr, user, args, context=context)
2114 return self.datas.keys()
2118 #Find the value of dict
2121 for id, data in self.datas.items():
2122 counter = counter + 1
2124 if limit and (counter > int(limit)):
2129 val = eval('data[arg[0]]'+'==' +' arg[2]', locals())
2130 elif arg[1] in ['<', '>', 'in', 'not in', '<=', '>=', '<>']:
2131 val = eval('data[arg[0]]'+arg[1] +' arg[2]', locals())
2132 elif arg[1] in ['ilike']:
2133 val = (str(data[arg[0]]).find(str(arg[2]))!=-1)
2143 def unlink(self, cr, uid, ids, context=None):
2145 self._check_access(uid, id, 'unlink')
2146 self.datas.pop(id, None)
2148 cr.execute('delete from wkf_instance where res_type=%s and res_id IN %s', (self._name, tuple(ids)))
2151 def perm_read(self, cr, user, ids, context=None, details=True):
2153 credentials = self.pool.get('res.users').name_get(cr, user, [user])[0]
2154 create_date = time.strftime('%Y-%m-%d %H:%M:%S')
2156 self._check_access(user, id, 'read')
2158 'create_uid': credentials,
2159 'create_date': create_date,
2161 'write_date': False,
2166 def _check_removed_columns(self, cr, log=False):
2167 # nothing to check in memory...
2170 def exists(self, cr, uid, id, context=None):
2171 return id in self.datas
2173 class orm(orm_template):
2174 _sql_constraints = []
2176 _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']
2177 __logger = logging.getLogger('orm')
2178 __schema = logging.getLogger('orm.schema')
2179 def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None):
2181 Get the list of records in list view grouped by the given ``groupby`` fields
2183 :param cr: database cursor
2184 :param uid: current user id
2185 :param domain: list specifying search criteria [['field_name', 'operator', 'value'], ...]
2186 :param fields: list of fields present in the list view specified on the object
2187 :param groupby: list of fields on which to groupby the records
2188 :type fields_list: list (example ['field_name_1', ...])
2189 :param offset: optional number of records to skip
2190 :param limit: optional max number of records to return
2191 :param context: context arguments, like lang, time zone
2192 :return: list of dictionaries(one dictionary for each record) containing:
2194 * the values of fields grouped by the fields in ``groupby`` argument
2195 * __domain: list of tuples specifying the search criteria
2196 * __context: dictionary with argument like ``groupby``
2197 :rtype: [{'field_name_1': value, ...]
2198 :raise AccessError: * if user has no read rights on the requested object
2199 * if user tries to bypass access rules for read on the requested object
2202 context = context or {}
2203 self.pool.get('ir.model.access').check(cr, uid, self._name, 'read', context=context)
2205 fields = self._columns.keys()
2207 query = self._where_calc(cr, uid, domain, context=context)
2208 self._apply_ir_rules(cr, uid, query, 'read', context=context)
2210 # Take care of adding join(s) if groupby is an '_inherits'ed field
2211 groupby_list = groupby
2213 if isinstance(groupby, list):
2214 groupby = groupby[0]
2215 self._inherits_join_calc(groupby, query)
2217 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?)"
2219 fget = self.fields_get(cr, uid, fields)
2220 float_int_fields = filter(lambda x: fget[x]['type'] in ('float', 'integer'), fields)
2225 if fget.get(groupby):
2226 if fget[groupby]['type'] in ('date', 'datetime'):
2227 flist = "to_char(%s,'yyyy-mm') as %s " % (groupby, groupby)
2228 groupby = "to_char(%s,'yyyy-mm')" % (groupby)
2232 # Don't allow arbitrary values, as this would be a SQL injection vector!
2233 raise except_orm(_('Invalid group_by'),
2234 _('Invalid group_by specification: "%s".\nA group_by specification must be a list of valid fields.')%(groupby,))
2237 fields_pre = [f for f in float_int_fields if
2238 f == self.CONCURRENCY_CHECK_FIELD
2239 or (f in self._columns and getattr(self._columns[f], '_classic_write'))]
2240 for f in fields_pre:
2241 if f not in ['id', 'sequence']:
2242 operator = fget[f].get('group_operator', 'sum')
2245 flist += operator+'('+f+') as '+f
2247 gb = groupby and (' GROUP BY '+groupby) or ''
2249 from_clause, where_clause, where_clause_params = query.get_sql()
2250 where_clause = where_clause and ' WHERE ' + where_clause
2251 limit_str = limit and ' limit %d' % limit or ''
2252 offset_str = offset and ' offset %d' % offset or ''
2253 cr.execute('SELECT min(%s.id) AS id,' % self._table + flist + ' FROM ' + from_clause + where_clause + gb + limit_str + offset_str, where_clause_params)
2256 for r in cr.dictfetchall():
2257 for fld, val in r.items():
2258 if val == None: r[fld] = False
2259 alldata[r['id']] = r
2261 if groupby and fget[groupby]['type'] == 'many2one':
2262 data_ids = self.search(cr, uid, [('id', 'in', alldata.keys())], order=groupby, context=context)
2263 # the IDS of the records that has groupby field value = False or ''
2264 # should be added too
2265 data_ids += filter(lambda x:x not in data_ids, alldata.keys())
2266 data = self.read(cr, uid, data_ids, groupby and [groupby] or ['id'], context=context)
2267 # 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):
2268 data.sort(lambda x,y: cmp(data_ids.index(x['id']), data_ids.index(y['id'])))
2270 data = self.read(cr, uid, alldata.keys(), groupby and [groupby] or ['id'], context=context)
2272 data.sort(lambda x,y:cmp(x[groupby],y[groupby]))
2275 d['__domain'] = [(groupby, '=', alldata[d['id']][groupby] or False)] + domain
2276 if not isinstance(groupby_list, (str, unicode)):
2277 if groupby or not context.get('group_by_no_leaf', False):
2278 d['__context'] = {'group_by': groupby_list[1:]}
2279 if groupby and groupby in fget:
2280 if d[groupby] and fget[groupby]['type'] in ('date', 'datetime'):
2281 dt = datetime.datetime.strptime(alldata[d['id']][groupby][:7], '%Y-%m')
2282 days = calendar.monthrange(dt.year, dt.month)[1]
2284 d[groupby] = datetime.datetime.strptime(d[groupby][:10], '%Y-%m-%d').strftime('%B %Y')
2285 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),\
2286 (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
2287 del alldata[d['id']][groupby]
2288 d.update(alldata[d['id']])
2292 def _inherits_join_add(self, parent_model_name, query):
2294 Add missing table SELECT and JOIN clause to ``query`` for reaching the parent table (no duplicates)
2296 :param parent_model_name: name of the parent model for which the clauses should be added
2297 :param query: query object on which the JOIN should be added
2299 inherits_field = self._inherits[parent_model_name]
2300 parent_model = self.pool.get(parent_model_name)
2301 parent_table_name = parent_model._table
2302 quoted_parent_table_name = '"%s"' % parent_table_name
2303 if quoted_parent_table_name not in query.tables:
2304 query.tables.append(quoted_parent_table_name)
2305 query.where_clause.append('("%s".%s = %s.id)' % (self._table, inherits_field, parent_table_name))
2307 def _inherits_join_calc(self, field, query):
2309 Adds missing table select and join clause(s) to ``query`` for reaching
2310 the field coming from an '_inherits' parent table (no duplicates).
2312 :param field: name of inherited field to reach
2313 :param query: query object on which the JOIN should be added
2314 :return: qualified name of field, to be used in SELECT clause
2316 current_table = self
2317 while field in current_table._inherit_fields and not field in current_table._columns:
2318 parent_model_name = current_table._inherit_fields[field][0]
2319 parent_table = self.pool.get(parent_model_name)
2320 self._inherits_join_add(parent_model_name, query)
2321 current_table = parent_table
2322 return '"%s".%s' % (current_table._table, field)
2324 def _parent_store_compute(self, cr):
2325 if not self._parent_store:
2327 logger = netsvc.Logger()
2328 logger.notifyChannel('data', netsvc.LOG_INFO, 'Computing parent left and right for table %s...' % (self._table, ))
2329 def browse_rec(root, pos=0):
2331 where = self._parent_name+'='+str(root)
2333 where = self._parent_name+' IS NULL'
2334 if self._parent_order:
2335 where += ' order by '+self._parent_order
2336 cr.execute('SELECT id FROM '+self._table+' WHERE '+where)
2338 childs = cr.fetchall()
2340 pos2 = browse_rec(id[0], pos2)
2341 cr.execute('update '+self._table+' set parent_left=%s, parent_right=%s where id=%s', (pos, pos2, root))
2343 query = 'SELECT id FROM '+self._table+' WHERE '+self._parent_name+' IS NULL'
2344 if self._parent_order:
2345 query += ' order by ' + self._parent_order
2348 for (root,) in cr.fetchall():
2349 pos = browse_rec(root, pos)
2352 def _update_store(self, cr, f, k):
2353 logger = netsvc.Logger()
2354 logger.notifyChannel('data', netsvc.LOG_INFO, "storing computed values of fields.function '%s'" % (k,))
2355 ss = self._columns[k]._symbol_set
2356 update_query = 'UPDATE "%s" SET "%s"=%s WHERE id=%%s' % (self._table, k, ss[0])
2357 cr.execute('select id from '+self._table)
2358 ids_lst = map(lambda x: x[0], cr.fetchall())
2361 ids_lst = ids_lst[40:]
2362 res = f.get(cr, self, iids, k, 1, {})
2363 for key, val in res.items():
2366 # if val is a many2one, just write the ID
2367 if type(val) == tuple:
2369 if (val<>False) or (type(val)<>bool):
2370 cr.execute(update_query, (ss[1](val), key))
2372 def _check_removed_columns(self, cr, log=False):
2373 # iterate on the database columns to drop the NOT NULL constraints
2374 # of fields which were required but have been removed (or will be added by another module)
2375 columns = [c for c in self._columns if not (isinstance(self._columns[c], fields.function) and not self._columns[c].store)]
2376 columns += ('id', 'write_uid', 'write_date', 'create_uid', 'create_date') # openerp access columns
2377 cr.execute("SELECT a.attname, a.attnotnull"
2378 " FROM pg_class c, pg_attribute a"
2379 " WHERE c.relname=%s"
2380 " AND c.oid=a.attrelid"
2381 " AND a.attisdropped=%s"
2382 " AND pg_catalog.format_type(a.atttypid, a.atttypmod) NOT IN ('cid', 'tid', 'oid', 'xid')"
2383 " AND a.attname NOT IN %s", (self._table, False, tuple(columns))),
2385 for column in cr.dictfetchall():
2387 self.__logger.debug("column %s is in the table %s but not in the corresponding object %s",
2388 column['attname'], self._table, self._name)
2389 if column['attnotnull']:
2390 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, column['attname']))
2391 self.__schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
2392 self._table, column['attname'])
2394 def _auto_init(self, cr, context={}):
2395 store_compute = False
2398 self._field_create(cr, context=context)
2399 if getattr(self, '_auto', True):
2400 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
2402 cr.execute('CREATE TABLE "%s" (id SERIAL NOT NULL, PRIMARY KEY(id)) WITHOUT OIDS' % (self._table,))
2403 cr.execute("COMMENT ON TABLE \"%s\" IS '%s'" % (self._table, self._description.replace("'", "''")))
2406 self.__schema.debug("Table '%s': created", self._table)
2409 if self._parent_store:
2410 cr.execute("""SELECT c.relname
2411 FROM pg_class c, pg_attribute a
2412 WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
2413 """, (self._table, 'parent_left'))
2415 cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_left" INTEGER' % (self._table,))
2416 cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_right" INTEGER' % (self._table,))
2417 if 'parent_left' not in self._columns:
2418 self.__logger.error('create a column parent_left on object %s: fields.integer(\'Left Parent\', select=1)',
2420 self.__schema.debug("Table '%s': added column '%s' with definition=%s",
2421 self._table, 'parent_left', 'INTEGER')
2422 if 'parent_right' not in self._columns:
2423 self.__logger.error('create a column parent_right on object %s: fields.integer(\'Right Parent\', select=1)',
2425 self.__schema.debug("Table '%s': added column '%s' with definition=%s",
2426 self._table, 'parent_right', 'INTEGER')
2427 if self._columns[self._parent_name].ondelete != 'cascade':
2428 self.__logger.error("The column %s on object %s must be set as ondelete='cascade'",
2429 self._parent_name, self._name)
2432 store_compute = True
2434 if self._log_access:
2436 'create_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
2437 'create_date': 'TIMESTAMP',
2438 'write_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
2439 'write_date': 'TIMESTAMP'
2444 FROM pg_class c, pg_attribute a
2445 WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
2446 """, (self._table, k))
2448 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, logs[k]))
2450 self.__schema.debug("Table '%s': added column '%s' with definition=%s",
2451 self._table, k, logs[k])
2453 self._check_removed_columns(cr, log=False)
2455 # iterate on the "object columns"
2456 todo_update_store = []
2457 update_custom_fields = context.get('update_custom_fields', False)
2458 for k in self._columns:
2459 if k in ('id', 'write_uid', 'write_date', 'create_uid', 'create_date'):
2461 #raise _('Can not define a column %s. Reserved keyword !') % (k,)
2462 #Not Updating Custom fields
2463 if k.startswith('x_') and not update_custom_fields:
2465 f = self._columns[k]
2467 if isinstance(f, fields.one2many):
2468 cr.execute("SELECT relname FROM pg_class WHERE relkind='r' AND relname=%s", (f._obj,))
2470 if self.pool.get(f._obj):
2471 if f._fields_id not in self.pool.get(f._obj)._columns.keys():
2472 if not self.pool.get(f._obj)._inherits or (f._fields_id not in self.pool.get(f._obj)._inherit_fields.keys()):
2473 raise except_orm('Programming Error', ("There is no reference field '%s' found for '%s'") % (f._fields_id, f._obj,))
2476 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))
2477 res = cr.fetchone()[0]
2479 cr.execute('ALTER TABLE "%s" ADD FOREIGN KEY (%s) REFERENCES "%s" ON DELETE SET NULL' % (self._obj, f._fields_id, f._table))
2480 self.__schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE SET NULL",
2481 self._obj, f._fields_id, f._table)
2482 elif isinstance(f, fields.many2many):
2483 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (f._rel,))
2484 if not cr.dictfetchall():
2485 if not self.pool.get(f._obj):
2486 raise except_orm('Programming Error', ('There is no reference available for %s') % (f._obj,))
2487 ref = self.pool.get(f._obj)._table
2488 # ref = f._obj.replace('.', '_')
2489 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))
2490 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (f._rel, f._id1, f._rel, f._id1))
2491 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (f._rel, f._id2, f._rel, f._id2))
2492 cr.execute("COMMENT ON TABLE \"%s\" IS 'RELATION BETWEEN %s AND %s'" % (f._rel, self._table, ref))
2494 self.__schema.debug("Create table '%s': relation between '%s' and '%s'",
2495 f._rel, self._table, ref)
2497 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 " \
2498 "FROM pg_class c,pg_attribute a,pg_type t " \
2499 "WHERE c.relname=%s " \
2500 "AND a.attname=%s " \
2501 "AND c.oid=a.attrelid " \
2502 "AND a.atttypid=t.oid", (self._table, k))
2503 res = cr.dictfetchall()
2504 if not res and hasattr(f, 'oldname'):
2505 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 " \
2506 "FROM pg_class c,pg_attribute a,pg_type t " \
2507 "WHERE c.relname=%s " \
2508 "AND a.attname=%s " \
2509 "AND c.oid=a.attrelid " \
2510 "AND a.atttypid=t.oid", (self._table, f.oldname))
2511 res_old = cr.dictfetchall()
2512 if res_old and len(res_old) == 1:
2513 cr.execute('ALTER TABLE "%s" RENAME "%s" TO "%s"' % (self._table, f.oldname, k))
2515 res[0]['attname'] = k
2516 self.__schema.debug("Table '%s': renamed column '%s' to '%s'",
2517 self._table, f.oldname, k)
2521 f_pg_type = f_pg_def['typname']
2522 f_pg_size = f_pg_def['size']
2523 f_pg_notnull = f_pg_def['attnotnull']
2524 if isinstance(f, fields.function) and not f.store and\
2525 not getattr(f, 'nodrop', False):
2526 self.__logger.info('column %s (%s) in table %s removed: converted to a function !\n',
2527 k, f.string, self._table)
2528 cr.execute('ALTER TABLE "%s" DROP COLUMN "%s" CASCADE' % (self._table, k))
2530 self.__schema.debug("Table '%s': dropped column '%s' with cascade",
2534 f_obj_type = get_pg_type(f) and get_pg_type(f)[0]
2539 ('text', 'char', 'VARCHAR(%d)' % (f.size or 0,), '::VARCHAR(%d)'%(f.size or 0,)),
2540 ('varchar', 'text', 'TEXT', ''),
2541 ('int4', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
2542 ('date', 'datetime', 'TIMESTAMP', '::TIMESTAMP'),
2543 ('timestamp', 'date', 'date', '::date'),
2544 ('numeric', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
2545 ('float8', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
2547 if f_pg_type == 'varchar' and f._type == 'char' and f_pg_size < f.size:
2548 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
2549 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" VARCHAR(%d)' % (self._table, k, f.size))
2550 cr.execute('UPDATE "%s" SET "%s"=temp_change_size::VARCHAR(%d)' % (self._table, k, f.size))
2551 cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
2553 self.__schema.debug("Table '%s': column '%s' (type varchar) changed size from %s to %s",
2554 self._table, k, f_pg_size, f.size)
2556 if (f_pg_type==c[0]) and (f._type==c[1]):
2557 if f_pg_type != f_obj_type:
2559 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
2560 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, c[2]))
2561 cr.execute(('UPDATE "%s" SET "%s"=temp_change_size'+c[3]) % (self._table, k))
2562 cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
2564 self.__schema.debug("Table '%s': column '%s' changed type from %s to %s",
2565 self._table, k, c[0], c[1])
2568 if f_pg_type != f_obj_type:
2572 newname = self._table + '_moved' + str(i)
2573 cr.execute("SELECT count(1) FROM pg_class c,pg_attribute a " \
2574 "WHERE c.relname=%s " \
2575 "AND a.attname=%s " \
2576 "AND c.oid=a.attrelid ", (self._table, newname))
2577 if not cr.fetchone()[0]:
2581 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
2582 cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO "%s"' % (self._table, k, newname))
2583 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
2584 cr.execute("COMMENT ON COLUMN %s.%s IS '%s'" % (self._table, k, f.string.replace("'", "''")))
2585 self.__schema.debug("Table '%s': column '%s' has changed type (DB=%s, def=%s), data moved to column %s !",
2586 self._table, k, f_pg_type, f._type, newname)
2588 # if the field is required and hasn't got a NOT NULL constraint
2589 if f.required and f_pg_notnull == 0:
2590 # set the field to the default value if any
2591 if k in self._defaults:
2592 if callable(self._defaults[k]):
2593 default = self._defaults[k](self, cr, 1, context)
2595 default = self._defaults[k]
2597 if (default is not None):
2598 ss = self._columns[k]._symbol_set
2599 query = 'UPDATE "%s" SET "%s"=%s WHERE "%s" is NULL' % (self._table, k, ss[0], k)
2600 cr.execute(query, (ss[1](default),))
2601 # add the NOT NULL constraint
2604 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k))
2606 self.__schema.debug("Table '%s': column '%s': added NOT NULL constraint",
2609 msg = "Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\
2610 "If you want to have it, you should update the records and execute manually:\n"\
2611 "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
2612 self.__schema.warn(msg, self._table, k, self._table, k)
2614 elif not f.required and f_pg_notnull == 1:
2615 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
2617 self.__schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
2620 indexname = '%s_%s_index' % (self._table, k)
2621 cr.execute("SELECT indexname FROM pg_indexes WHERE indexname = %s and tablename = %s", (indexname, self._table))
2622 res2 = cr.dictfetchall()
2623 if not res2 and f.select:
2624 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
2626 if f._type == 'text':
2627 # FIXME: for fields.text columns we should try creating GIN indexes instead (seems most suitable for an ERP context)
2628 msg = "Table '%s': Adding (b-tree) index for text column '%s'."\
2629 "This is probably useless (does not work for fulltext search) and prevents INSERTs of long texts"\
2630 " because there is a length limit for indexable btree values!\n"\
2631 "Use a search view instead if you simply want to make the field searchable."
2632 self.__schema.warn(msg, self._table, k, f._type)
2633 if res2 and not f.select:
2634 cr.execute('DROP INDEX "%s_%s_index"' % (self._table, k))
2636 msg = "Table '%s': dropping index for column '%s' of type '%s' as it is not required anymore"
2637 self.__schema.warn(msg, self._table, k, f._type)
2639 if isinstance(f, fields.many2one):
2640 ref = self.pool.get(f._obj)._table
2641 if ref != 'ir_actions':
2642 cr.execute('SELECT confdeltype, conname FROM pg_constraint as con, pg_class as cl1, pg_class as cl2, '
2643 'pg_attribute as att1, pg_attribute as att2 '
2644 'WHERE con.conrelid = cl1.oid '
2645 'AND cl1.relname = %s '
2646 'AND con.confrelid = cl2.oid '
2647 'AND cl2.relname = %s '
2648 'AND array_lower(con.conkey, 1) = 1 '
2649 'AND con.conkey[1] = att1.attnum '
2650 'AND att1.attrelid = cl1.oid '
2651 'AND att1.attname = %s '
2652 'AND array_lower(con.confkey, 1) = 1 '
2653 'AND con.confkey[1] = att2.attnum '
2654 'AND att2.attrelid = cl2.oid '
2655 'AND att2.attname = %s '
2656 "AND con.contype = 'f'", (self._table, ref, k, 'id'))
2657 res2 = cr.dictfetchall()
2659 if res2[0]['confdeltype'] != POSTGRES_CONFDELTYPES.get(f.ondelete.upper(), 'a'):
2660 cr.execute('ALTER TABLE "' + self._table + '" DROP CONSTRAINT "' + res2[0]['conname'] + '"')
2661 cr.execute('ALTER TABLE "' + self._table + '" ADD FOREIGN KEY ("' + k + '") REFERENCES "' + ref + '" ON DELETE ' + f.ondelete)
2663 self.__schema.debug("Table '%s': column '%s': XXX",
2666 netsvc.Logger().notifyChannel('orm', netsvc.LOG_ERROR, "Programming error, column %s->%s has multiple instances !" % (self._table, k))
2668 if not isinstance(f, fields.function) or f.store:
2669 # add the missing field
2670 cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
2671 cr.execute("COMMENT ON COLUMN %s.%s IS '%s'" % (self._table, k, f.string.replace("'", "''")))
2672 self.__schema.debug("Table '%s': added column '%s' with definition=%s",
2673 self._table, k, get_pg_type(f)[1])
2676 if not create and k in self._defaults:
2677 if callable(self._defaults[k]):
2678 default = self._defaults[k](self, cr, 1, context)
2680 default = self._defaults[k]
2682 ss = self._columns[k]._symbol_set
2683 query = 'UPDATE "%s" SET "%s"=%s' % (self._table, k, ss[0])
2684 cr.execute(query, (ss[1](default),))
2686 netsvc.Logger().notifyChannel('data', netsvc.LOG_DEBUG, "Table '%s': setting default value of new column %s" % (self._table, k))
2688 if isinstance(f, fields.function):
2690 if f.store is not True:
2691 order = f.store[f.store.keys()[0]][2]
2692 todo_update_store.append((order, f, k))
2694 # and add constraints if needed
2695 if isinstance(f, fields.many2one):
2696 if not self.pool.get(f._obj):
2697 raise except_orm('Programming Error', ('There is no reference available for %s') % (f._obj,))
2698 ref = self.pool.get(f._obj)._table
2699 # ref = f._obj.replace('.', '_')
2700 # ir_actions is inherited so foreign key doesn't work on it
2701 if ref != 'ir_actions':
2702 cr.execute('ALTER TABLE "%s" ADD FOREIGN KEY ("%s") REFERENCES "%s" ON DELETE %s' % (self._table, k, ref, f.ondelete))
2703 self.__schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s",
2704 self._table, k, ref, f.ondelete)
2706 cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
2710 cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k))
2711 self.__schema.debug("Table '%s': column '%s': added a NOT NULL constraint",
2714 msg = "WARNING: unable to set column %s of table %s not null !\n"\
2715 "Try to re-run: openerp-server.py --update=module\n"\
2716 "If it doesn't work, update records and execute manually:\n"\
2717 "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
2718 self.__logger.warn(msg, k, self._table, self._table, k)
2720 for order, f, k in todo_update_store:
2721 todo_end.append((order, self._update_store, (f, k)))
2724 cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
2725 create = not bool(cr.fetchone())
2727 cr.commit() # start a new transaction
2729 for (key, con, _) in self._sql_constraints:
2730 conname = '%s_%s' % (self._table, key)
2732 cr.execute("SELECT conname, pg_catalog.pg_get_constraintdef(oid, true) as condef FROM pg_constraint where conname=%s", (conname,))
2733 existing_constraints = cr.dictfetchall()
2738 'query': 'ALTER TABLE "%s" DROP CONSTRAINT "%s"' % (self._table, conname, ),
2739 'msg_ok': "Table '%s': dropped constraint '%s'. Reason: its definition changed from '%%s' to '%s'" % (
2740 self._table, conname, con),
2741 'msg_err': "Table '%s': unable to drop \'%s\' constraint !" % (self._table, con),
2746 'query': 'ALTER TABLE "%s" ADD CONSTRAINT "%s" %s' % (self._table, conname, con,),
2747 'msg_ok': "Table '%s': added constraint '%s' with definition=%s" % (self._table, conname, con),
2748 '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" % (
2754 if not existing_constraints:
2755 # constraint does not exists:
2756 sql_actions['add']['execute'] = True
2757 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
2758 elif con.lower() not in [item['condef'].lower() for item in existing_constraints]:
2759 # constraint exists but its definition has changed:
2760 sql_actions['drop']['execute'] = True
2761 sql_actions['drop']['msg_ok'] = sql_actions['drop']['msg_ok'] % (existing_constraints[0]['condef'].lower(), )
2762 sql_actions['add']['execute'] = True
2763 sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
2765 # we need to add the constraint:
2766 sql_actions = [item for item in sql_actions.values()]
2767 sql_actions.sort(key=lambda x: x['order'])
2768 for sql_action in [action for action in sql_actions if action['execute']]:
2770 cr.execute(sql_action['query'])
2772 self.__schema.debug(sql_action['msg_ok'])
2774 self.__schema.warn(sql_action['msg_err'])
2778 if hasattr(self, "_sql"):
2779 for line in self._sql.split(';'):
2780 line2 = line.replace('\n', '').strip()
2785 self._parent_store_compute(cr)
2789 def __init__(self, cr):
2790 super(orm, self).__init__(cr)
2792 if not hasattr(self, '_log_access'):
2793 # if not access is not specify, it is the same value as _auto
2794 self._log_access = getattr(self, "_auto", True)
2796 self._columns = self._columns.copy()
2797 for store_field in self._columns:
2798 f = self._columns[store_field]
2799 if hasattr(f, 'digits_change'):
2801 if not isinstance(f, fields.function):
2805 if self._columns[store_field].store is True:
2806 sm = {self._name: (lambda self, cr, uid, ids, c={}: ids, None, 10, None)}
2808 sm = self._columns[store_field].store
2809 for object, aa in sm.items():
2811 (fnct, fields2, order, length) = aa
2813 (fnct, fields2, order) = aa
2816 raise except_orm('Error',
2817 ('Invalid function definition %s in object %s !\nYou must use the definition: store={object:(fnct, fields, priority, time length)}.' % (store_field, self._name)))
2818 self.pool._store_function.setdefault(object, [])
2820 for x, y, z, e, f, l in self.pool._store_function[object]:
2821 if (x==self._name) and (y==store_field) and (e==fields2):
2825 self.pool._store_function[object].append( (self._name, store_field, fnct, fields2, order, length))
2826 self.pool._store_function[object].sort(lambda x, y: cmp(x[4], y[4]))
2828 for (key, _, msg) in self._sql_constraints:
2829 self.pool._sql_error[self._table+'_'+key] = msg
2831 # Load manual fields
2833 cr.execute("SELECT id FROM ir_model_fields WHERE name=%s AND model=%s", ('state', 'ir.model.fields'))
2835 cr.execute('SELECT * FROM ir_model_fields WHERE model=%s AND state=%s', (self._name, 'manual'))
2836 for field in cr.dictfetchall():
2837 if field['name'] in self._columns:
2840 'string': field['field_description'],
2841 'required': bool(field['required']),
2842 'readonly': bool(field['readonly']),
2843 'domain': field['domain'] or None,
2844 'size': field['size'],
2845 'ondelete': field['on_delete'],
2846 'translate': (field['translate']),
2847 #'select': int(field['select_level'])
2850 if field['ttype'] == 'selection':
2851 self._columns[field['name']] = getattr(fields, field['ttype'])(eval(field['selection']), **attrs)
2852 elif field['ttype'] == 'reference':
2853 self._columns[field['name']] = getattr(fields, field['ttype'])(selection=eval(field['selection']), **attrs)
2854 elif field['ttype'] == 'many2one':
2855 self._columns[field['name']] = getattr(fields, field['ttype'])(field['relation'], **attrs)
2856 elif field['ttype'] == 'one2many':
2857 self._columns[field['name']] = getattr(fields, field['ttype'])(field['relation'], field['relation_field'], **attrs)
2858 elif field['ttype'] == 'many2many':
2859 _rel1 = field['relation'].replace('.', '_')
2860 _rel2 = field['model'].replace('.', '_')
2861 _rel_name = 'x_%s_%s_%s_rel' % (_rel1, _rel2, field['name'])
2862 self._columns[field['name']] = getattr(fields, field['ttype'])(field['relation'], _rel_name, 'id1', 'id2', **attrs)
2864 self._columns[field['name']] = getattr(fields, field['ttype'])(**attrs)
2865 self._inherits_check()
2866 self._inherits_reload()
2867 if not self._sequence:
2868 self._sequence = self._table + '_id_seq'
2869 for k in self._defaults:
2870 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,)
2871 for f in self._columns:
2872 self._columns[f].restart()
2875 # Update objects that uses this one to update their _inherits fields
2878 def _inherits_reload_src(self):
2879 for obj in self.pool.obj_pool.values():
2880 if self._name in obj._inherits:
2881 obj._inherits_reload()
2883 def _inherits_reload(self):
2885 for table in self._inherits:
2886 res.update(self.pool.get(table)._inherit_fields)
2887 for col in self.pool.get(table)._columns.keys():
2888 res[col] = (table, self._inherits[table], self.pool.get(table)._columns[col])
2889 for col in self.pool.get(table)._inherit_fields.keys():
2890 res[col] = (table, self._inherits[table], self.pool.get(table)._inherit_fields[col][2])
2891 self._inherit_fields = res
2892 self._inherits_reload_src()
2894 def _inherits_check(self):
2895 for table, field_name in self._inherits.items():
2896 if field_name not in self._columns:
2897 logging.getLogger('init').info('Missing many2one field definition for _inherits reference "%s" in "%s", using default one.' % (field_name, self._name))
2898 self._columns[field_name] = fields.many2one(table, string="Automatically created field to link to parent %s" % table,
2899 required=True, ondelete="cascade")
2900 elif not self._columns[field_name].required or self._columns[field_name].ondelete.lower() != "cascade":
2901 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))
2902 self._columns[field_name].required = True
2903 self._columns[field_name].ondelete = "cascade"
2905 #def __getattr__(self, name):
2907 # Proxies attribute accesses to the `inherits` parent so we can call methods defined on the inherited parent
2908 # (though inherits doesn't use Python inheritance).
2909 # Handles translating between local ids and remote ids.
2910 # Known issue: doesn't work correctly when using python's own super(), don't involve inherit-based inheritance
2911 # when you have inherits.
2913 # for model, field in self._inherits.iteritems():
2914 # proxy = self.pool.get(model)
2915 # if hasattr(proxy, name):
2916 # attribute = getattr(proxy, name)
2917 # if not hasattr(attribute, '__call__'):
2921 # return super(orm, self).__getattr__(name)
2923 # def _proxy(cr, uid, ids, *args, **kwargs):
2924 # objects = self.browse(cr, uid, ids, kwargs.get('context', None))
2925 # lst = [obj[field].id for obj in objects if obj[field]]
2926 # return getattr(proxy, name)(cr, uid, lst, *args, **kwargs)
2931 def fields_get(self, cr, user, fields=None, context=None):
2933 Get the description of list of fields
2935 :param cr: database cursor
2936 :param user: current user id
2937 :param fields: list of fields
2938 :param context: context arguments, like lang, time zone
2939 :return: dictionary of field dictionaries, each one describing a field of the business object
2940 :raise AccessError: * if user has no create/write rights on the requested object
2943 ira = self.pool.get('ir.model.access')
2944 write_access = ira.check(cr, user, self._name, 'write', raise_exception=False, context=context) or \
2945 ira.check(cr, user, self._name, 'create', raise_exception=False, context=context)
2946 return super(orm, self).fields_get(cr, user, fields, context, write_access)
2948 def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
2950 Read records with given ids with the given fields
2952 :param cr: database cursor
2953 :param user: current user id
2954 :param ids: id or list of the ids of the records to read
2955 :param fields: optional list of field names to return (default: all fields would be returned)
2956 :type fields: list (example ['field_name_1', ...])
2957 :param context: (optional) context arguments, like lang, time zone
2958 :return: list of dictionaries((dictionary per record asked)) with requested field values
2959 :rtype: [{‘name_of_the_field’: value, ...}, ...]
2960 :raise AccessError: * if user has no read rights on the requested object
2961 * if user tries to bypass access rules for read on the requested object
2966 self.pool.get('ir.model.access').check(cr, user, self._name, 'read', context=context)
2968 fields = self._columns.keys() + self._inherit_fields.keys()
2969 if isinstance(ids, (int, long)):
2973 select = map(lambda x: isinstance(x, dict) and x['id'] or x, select)
2974 result = self._read_flat(cr, user, select, fields, context, load)
2977 for key, v in r.items():
2980 if key in self._columns:
2981 column = self._columns[key]
2982 elif key in self._inherit_fields:
2983 column = self._inherit_fields[key][2]
2986 # TODO: removed this, it's too slow
2987 # if v and column._type == 'reference':
2988 # model_name, ref_id = v.split(',', 1)
2989 # model = self.pool.get(model_name)
2993 # cr.execute('SELECT count(1) FROM "%s" WHERE id=%%s' % (model._table,), (ref_id,))
2994 # reset = not cr.fetchone()[0]
2996 # if column._classic_write:
2997 # query = 'UPDATE "%s" SET "%s"=NULL WHERE id=%%s' % (self._table, key)
2998 # cr.execute(query, (r['id'],))
3001 if isinstance(ids, (int, long, dict)):
3002 return result and result[0] or False
3005 def _read_flat(self, cr, user, ids, fields_to_read, context=None, load='_classic_read'):
3010 if fields_to_read == None:
3011 fields_to_read = self._columns.keys()
3013 # Construct a clause for the security rules.
3014 # 'tables' hold the list of tables necessary for the SELECT including the ir.rule clauses,
3015 # or will at least contain self._table.
3016 rule_clause, rule_params, tables = self.pool.get('ir.rule').domain_get(cr, user, self._name, 'read', context=context)
3018 # all inherited fields + all non inherited fields for which the attribute whose name is in load is True
3019 fields_pre = [f for f in fields_to_read if
3020 f == self.CONCURRENCY_CHECK_FIELD
3021 or (f in self._columns and getattr(self._columns[f], '_classic_write'))
3022 ] + self._inherits.values()
3026 def convert_field(f):
3027 f_qual = "%s.%s" % (self._table, f) # need fully-qualified references in case len(tables) > 1
3028 if f in ('create_date', 'write_date'):
3029 return "date_trunc('second', %s) as %s" % (f_qual, f)
3030 if f == self.CONCURRENCY_CHECK_FIELD:
3031 if self._log_access:
3032 return "COALESCE(%s.write_date, %s.create_date, now())::timestamp AS %s" % (self._table, self._table, f,)
3033 return "now()::timestamp AS %s" % (f,)
3034 if isinstance(self._columns[f], fields.binary) and context.get('bin_size', False):
3035 return 'length(%s) as "%s"' % (f_qual, f)
3038 fields_pre2 = map(convert_field, fields_pre)
3039 order_by = self._parent_order or self._order
3040 select_fields = ','.join(fields_pre2 + [self._table + '.id'])
3041 query = 'SELECT %s FROM %s WHERE %s.id IN %%s' % (select_fields, ','.join(tables), self._table)
3043 query += " AND " + (' OR '.join(rule_clause))
3044 query += " ORDER BY " + order_by
3045 for sub_ids in cr.split_for_in_conditions(ids):
3047 cr.execute(query, [tuple(sub_ids)] + rule_params)
3048 if cr.rowcount != len(sub_ids):
3049 raise except_orm(_('AccessError'),
3050 _('You try to bypass an access rule while reading (Document type: %s).') % self._description)
3052 cr.execute(query, (tuple(sub_ids),))
3053 res.extend(cr.dictfetchall())
3055 res = map(lambda x: {'id': x}, ids)
3058 res = map(lambda x: {'id': x}, ids)
3060 for f in fields_to_read:
3062 if f in self._columns.keys():
3063 ftype = self._columns[f]._type
3064 elif f in self._inherit_fields.keys():
3065 ftype = self._inherit_fields[f][2]._type
3068 if ftype in ('one2many', 'many2many'):
3070 record.update({f:field_val})
3072 for f in fields_pre:
3073 if f == self.CONCURRENCY_CHECK_FIELD:
3075 if self._columns[f].translate:
3076 ids = [x['id'] for x in res]
3077 #TODO: optimize out of this loop
3078 res_trans = self.pool.get('ir.translation')._get_ids(cr, user, self._name+','+f, 'model', context.get('lang', False) or 'en_US', ids)
3080 r[f] = res_trans.get(r['id'], False) or r[f]
3082 for table in self._inherits:
3083 col = self._inherits[table]
3084 cols = intersect(self._inherit_fields.keys(), set(fields_to_read) - set(self._columns.keys()))
3087 res2 = self.pool.get(table).read(cr, user, [x[col] for x in res], cols, context, load)
3095 if not record[col]: # if the record is deleted from _inherits table?
3097 record.update(res3[record[col]])
3098 if col not in fields_to_read:
3101 # all fields which need to be post-processed by a simple function (symbol_get)
3102 fields_post = filter(lambda x: x in self._columns and self._columns[x]._symbol_get, fields_to_read)
3105 for f in fields_post:
3106 r[f] = self._columns[f]._symbol_get(r[f])
3107 ids = [x['id'] for x in res]
3109 # all non inherited fields for which the attribute whose name is in load is False
3110 fields_post = filter(lambda x: x in self._columns and not getattr(self._columns[x], load), fields_to_read)
3112 # Compute POST fields
3114 for f in fields_post:
3115 todo.setdefault(self._columns[f]._multi, [])
3116 todo[self._columns[f]._multi].append(f)
3117 for key, val in todo.items():
3119 res2 = self._columns[val[0]].get(cr, self, ids, val, user, context=context, values=res)
3122 if isinstance(res2[record['id']], str): res2[record['id']] = eval(res2[record['id']]) #TOCHECK : why got string instend of dict in python2.6
3123 record[pos] = res2[record['id']][pos]
3126 res2 = self._columns[f].get(cr, self, ids, f, user, context=context, values=res)
3129 record[f] = res2[record['id']]
3134 for field in vals.copy():
3136 if field in self._columns:
3137 fobj = self._columns[field]
3144 for group in groups:
3145 module = group.split(".")[0]
3146 grp = group.split(".")[1]
3147 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" \
3148 (grp, module, 'res.groups', user))
3149 readonly = cr.fetchall()
3150 if readonly[0][0] >= 1:
3153 elif readonly[0][0] == 0:
3159 if type(vals[field]) == type([]):
3161 elif type(vals[field]) == type(0.0):
3163 elif type(vals[field]) == type(''):
3164 vals[field] = '=No Permission='
3169 def perm_read(self, cr, user, ids, context=None, details=True):
3171 Read the permission for record of the given ids
3173 :param cr: database cursor
3174 :param user: current user id
3175 :param ids: id or list of ids
3176 :param context: context arguments, like lang, time zone
3177 :param details: if True, \*_uid fields are replaced with the name of the user
3178 :return: list of ownership dictionaries for each requested record
3179 :rtype: list of dictionaries with the following keys:
3182 * create_uid: user who created the record
3183 * create_date: date when the record was created
3184 * write_uid: last user who changed the record
3185 * write_date: date of the last change to the record
3193 uniq = isinstance(ids, (int, long))
3197 if self._log_access:
3198 fields += ', create_uid, create_date, write_uid, write_date'
3199 query = 'SELECT %s FROM "%s" WHERE id IN %%s' % (fields, self._table)
3200 cr.execute(query, (tuple(ids),))
3201 res = cr.dictfetchall()
3204 r[key] = r[key] or False
3205 if key in ('write_uid', 'create_uid', 'uid') and details:
3207 r[key] = self.pool.get('res.users').name_get(cr, user, [r[key]])[0]
3212 def _check_concurrency(self, cr, ids, context):
3215 if context.get(self.CONCURRENCY_CHECK_FIELD) and self._log_access:
3217 return "%s,%s" % (self._name, oid)
3218 santa = "(id = %s AND %s < COALESCE(write_date, create_date, now())::timestamp)"
3219 for i in range(0, len(ids), cr.IN_MAX):
3220 sub_ids = tools.flatten(((oid, context[self.CONCURRENCY_CHECK_FIELD][key(oid)])
3221 for oid in ids[i:i+cr.IN_MAX]
3222 if key(oid) in context[self.CONCURRENCY_CHECK_FIELD]))
3224 cr.execute("SELECT count(1) FROM %s WHERE %s" % (self._table, " OR ".join([santa]*(len(sub_ids)/2))), sub_ids)
3227 raise except_orm('ConcurrencyException', _('Records were modified in the meanwhile'))
3229 def check_access_rule(self, cr, uid, ids, operation, context=None):
3230 """Verifies that the operation given by ``operation`` is allowed for the user
3231 according to ir.rules.
3233 :param operation: one of ``write``, ``unlink``
3234 :raise except_orm: * if current ir.rules do not permit this operation.
3235 :return: None if the operation is allowed
3237 where_clause, where_params, tables = self.pool.get('ir.rule').domain_get(cr, uid, self._name, operation, context=context)
3239 where_clause = ' and ' + ' and '.join(where_clause)
3240 for sub_ids in cr.split_for_in_conditions(ids):
3241 cr.execute('SELECT ' + self._table + '.id FROM ' + ','.join(tables) +
3242 ' WHERE ' + self._table + '.id IN %s' + where_clause,
3243 [sub_ids] + where_params)
3244 if cr.rowcount != len(sub_ids):
3245 raise except_orm(_('AccessError'),
3246 _('Operation prohibited by access rules (Operation: %s, Document type: %s).')
3247 % (operation, self._name))
3249 def unlink(self, cr, uid, ids, context=None):
3251 Delete records with given ids
3253 :param cr: database cursor
3254 :param uid: current user id
3255 :param ids: id or list of ids
3256 :param context: (optional) context arguments, like lang, time zone
3258 :raise AccessError: * if user has no unlink rights on the requested object
3259 * if user tries to bypass access rules for unlink on the requested object
3260 :raise UserError: if the record is default property for other records
3265 if isinstance(ids, (int, long)):
3268 result_store = self._store_get_values(cr, uid, ids, None, context)
3270 self._check_concurrency(cr, ids, context)
3272 self.pool.get('ir.model.access').check(cr, uid, self._name, 'unlink', context=context)
3274 properties = self.pool.get('ir.property')
3275 domain = [('res_id', '=', False),
3276 ('value_reference', 'in', ['%s,%s' % (self._name, i) for i in ids]),
3278 if properties.search(cr, uid, domain, context=context):
3279 raise except_orm(_('Error'), _('Unable to delete this document because it is used as a default property'))
3281 wf_service = netsvc.LocalService("workflow")
3283 wf_service.trg_delete(uid, self._name, oid, cr)
3286 self.check_access_rule(cr, uid, ids, 'unlink', context=context)
3287 for sub_ids in cr.split_for_in_conditions(ids):
3288 cr.execute('delete from ' + self._table + ' ' \
3289 'where id IN %s', (sub_ids,))
3290 for order, object, store_ids, fields in result_store:
3291 if object != self._name:
3292 obj = self.pool.get(object)
3293 cr.execute('select id from '+obj._table+' where id IN %s', (tuple(store_ids),))
3294 rids = map(lambda x: x[0], cr.fetchall())
3296 obj._store_set_values(cr, uid, rids, fields, context)
3302 def write(self, cr, user, ids, vals, context=None):
3304 Update records with given ids with the given field values
3306 :param cr: database cursor
3307 :param user: current user id
3309 :param ids: object id or list of object ids to update according to **vals**
3310 :param vals: field values to update, e.g {'field_name': new_field_value, ...}
3311 :type vals: dictionary
3312 :param context: (optional) context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...}
3313 :type context: dictionary
3315 :raise AccessError: * if user has no write rights on the requested object
3316 * if user tries to bypass access rules for write on the requested object
3317 :raise ValidateError: if user tries to enter invalid value for a field that is not in selection
3318 :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)
3320 **Note**: The type of field values to pass in ``vals`` for relationship fields is specific:
3322 + For a many2many field, a list of tuples is expected.
3323 Here is the list of tuple that are accepted, with the corresponding semantics ::
3325 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
3326 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
3327 (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)
3328 (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)
3329 (4, ID) link to existing record with id = ID (adds a relationship)
3330 (5) unlink all (like using (3,ID) for all linked records)
3331 (6, 0, [IDs]) replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)
3334 [(6, 0, [8, 5, 6, 4])] sets the many2many to ids [8, 5, 6, 4]
3336 + For a one2many field, a lits of tuples is expected.
3337 Here is the list of tuple that are accepted, with the corresponding semantics ::
3339 (0, 0, { values }) link to a new record that needs to be created with the given values dictionary
3340 (1, ID, { values }) update the linked record with id = ID (write *values* on it)
3341 (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)
3344 [(0, 0, {'field_name':field_value_record1, ...}), (0, 0, {'field_name':field_value_record2, ...})]
3346 + For a many2one field, simply use the ID of target record, which must already exist, or ``False`` to remove the link.
3347 + For a reference field, use a string with the model name, a comma, and the target object id (example: ``'product.product, 5'``)
3351 for field in vals.copy():
3353 if field in self._columns:
3354 fobj = self._columns[field]
3356 fobj = self._inherit_fields[field][2]
3363 for group in groups:
3364 module = group.split(".")[0]
3365 grp = group.split(".")[1]
3366 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", \
3367 (grp, module, 'res.groups', user))
3368 readonly = cr.fetchall()
3369 if readonly[0][0] >= 1:
3372 elif readonly[0][0] == 0:
3384 if isinstance(ids, (int, long)):
3387 self._check_concurrency(cr, ids, context)
3388 self.pool.get('ir.model.access').check(cr, user, self._name, 'write', context=context)
3390 result = self._store_get_values(cr, user, ids, vals.keys(), context) or []
3392 # No direct update of parent_left/right
3393 vals.pop('parent_left', None)
3394 vals.pop('parent_right', None)
3396 parents_changed = []
3397 if self._parent_store and (self._parent_name in vals):
3398 # The parent_left/right computation may take up to
3399 # 5 seconds. No need to recompute the values if the
3400 # parent is the same. Get the current value of the parent
3401 parent_val = vals[self._parent_name]
3403 query = "SELECT id FROM %s WHERE id IN %%s AND (%s != %%s OR %s IS NULL)" % \
3404 (self._table, self._parent_name, self._parent_name)
3405 cr.execute(query, (tuple(ids), parent_val))
3407 query = "SELECT id FROM %s WHERE id IN %%s AND (%s IS NOT NULL)" % \
3408 (self._table, self._parent_name)
3409 cr.execute(query, (tuple(ids),))
3410 parents_changed = map(operator.itemgetter(0), cr.fetchall())
3417 totranslate = context.get('lang', False) and (context['lang'] != 'en_US')
3419 if field in self._columns:
3420 if self._columns[field]._classic_write and not (hasattr(self._columns[field], '_fnct_inv')):
3421 if (not totranslate) or not self._columns[field].translate:
3422 upd0.append('"'+field+'"='+self._columns[field]._symbol_set[0])
3423 upd1.append(self._columns[field]._symbol_set[1](vals[field]))
3424 direct.append(field)
3426 upd_todo.append(field)
3428 updend.append(field)
3429 if field in self._columns \
3430 and hasattr(self._columns[field], 'selection') \
3432 if self._columns[field]._type == 'reference':
3433 val = vals[field].split(',')[0]
3436 if isinstance(self._columns[field].selection, (tuple, list)):
3437 if val not in dict(self._columns[field].selection):
3438 raise except_orm(_('ValidateError'),
3439 _('The value "%s" for the field "%s" is not in the selection') \
3440 % (vals[field], field))
3442 if val not in dict(self._columns[field].selection(
3443 self, cr, user, context=context)):
3444 raise except_orm(_('ValidateError'),
3445 _('The value "%s" for the field "%s" is not in the selection') \
3446 % (vals[field], field))
3448 if self._log_access:
3449 upd0.append('write_uid=%s')
3450 upd0.append('write_date=now()')
3454 self.check_access_rule(cr, user, ids, 'write', context=context)
3455 for sub_ids in cr.split_for_in_conditions(ids):
3456 cr.execute('update ' + self._table + ' set ' + ','.join(upd0) + ' ' \
3457 'where id IN %s', upd1 + [sub_ids])
3462 if self._columns[f].translate:
3463 src_trans = self.pool.get(self._name).read(cr, user, ids, [f])[0][f]
3466 # Inserting value to DB
3467 self.write(cr, user, ids, {f: vals[f]})
3468 self.pool.get('ir.translation')._set_ids(cr, user, self._name+','+f, 'model', context['lang'], ids, vals[f], src_trans)
3471 # call the 'set' method of fields which are not classic_write
3472 upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
3474 # default element in context must be removed when call a one2many or many2many
3475 rel_context = context.copy()
3476 for c in context.items():
3477 if c[0].startswith('default_'):
3478 del rel_context[c[0]]
3480 for field in upd_todo:
3482 result += self._columns[field].set(cr, self, id, field, vals[field], user, context=rel_context) or []
3484 for table in self._inherits:
3485 col = self._inherits[table]
3487 for sub_ids in cr.split_for_in_conditions(ids):
3488 cr.execute('select distinct "'+col+'" from "'+self._table+'" ' \
3489 'where id IN %s', (sub_ids,))
3490 nids.extend([x[0] for x in cr.fetchall()])
3494 if self._inherit_fields[val][0] == table:
3496 self.pool.get(table).write(cr, user, nids, v, context)
3498 self._validate(cr, user, ids, context)
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)
3506 self.pool._init_parent[self._name] = True
3508 order = self._parent_order or self._order
3509 parent_val = vals[self._parent_name]
3511 clause, params = '%s=%%s' % (self._parent_name,), (parent_val,)
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()
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
3522 # Find Position of the element
3524 for (parent_pright, parent_id) in parents:
3527 position = parent_pright + 1
3529 # It's the first node of the parent
3534 cr.execute('select parent_left from '+self._table+' where id=%s', (parent_val,))
3535 position = cr.fetchone()[0] + 1
3537 if pleft < position <= pright:
3538 raise except_orm(_('UserError'), _('Recursivity Detected.'))
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))
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))
3549 result += self._store_get_values(cr, user, ids, vals.keys(), context)
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
3559 if id not in done[key]:
3560 done[key][id] = True
3562 self.pool.get(object)._store_set_values(cr, user, todo, fields, context)
3564 wf_service = netsvc.LocalService("workflow")
3566 wf_service.trg_write(user, self._name, id, cr)
3570 # TODO: Should set perm to user.xxx
3572 def create(self, cr, user, vals, context=None):
3574 Create new record with specified value
3576 :param cr: database cursor
3577 :param user: current user id
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)
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
3596 self.pool.get('ir.model.access').check(cr, user, self._name, 'create', context=context)
3598 vals = self._add_missing_default_values(cr, user, vals, context)
3601 for v in self._inherits:
3602 if self._inherits[v] not in vals:
3605 tocreate[v] = {'id': vals[self._inherits[v]]}
3606 (upd0, upd1, upd2) = ('', '', [])
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]
3614 if (v not in self._inherit_fields) and (v not in self._columns):
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))
3620 cr.execute("SELECT nextval('"+self._sequence+"')")
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.'))
3625 id_new = cr.fetchone()[0]
3626 for table in tocreate:
3627 if self._inherits[table] in vals:
3628 del vals[self._inherits[table]]
3630 record_id = tocreate[table].pop('id', None)
3632 if record_id is None or not record_id:
3633 record_id = self.pool.get(table).create(cr, user, tocreate[table], context=context)
3635 self.pool.get(table).write(cr, user, [record_id], tocreate[table], context=context)
3637 upd0 += ',' + self._inherits[table]
3639 upd2.append(record_id)
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']
3644 for bool_field in bool_fields:
3645 if bool_field not in vals:
3646 vals[bool_field] = False
3648 for field in vals.copy():
3650 if field in self._columns:
3651 fobj = self._columns[field]
3653 fobj = self._inherit_fields[field][2]
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:
3668 elif readonly[0][0] == 0:
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]))
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') \
3686 if self._columns[field]._type == 'reference':
3687 val = vals[field].split(',')[0]
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))
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'
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)
3709 if self._parent_store and not context.get('defer_parent_store_computation'):
3711 self.pool._init_parent[self._name] = True
3713 parent = vals.get(self._parent_name, False)
3715 cr.execute('select parent_right from '+self._table+' where '+self._parent_name+'=%s order by '+(self._parent_order or self._order), (parent,))
3717 result_p = cr.fetchall()
3718 for (pleft,) in result_p:
3723 cr.execute('select parent_left from '+self._table+' where id=%s', (parent,))
3724 pleft_old = cr.fetchone()[0]
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))
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]]
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)
3744 if not context.get('no_store_function', False):
3745 result += self._store_get_values(cr, user, [id_new], vals.keys(), context)
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))
3753 if self._log_create and not (context and context.get('no_store_function', False)):
3754 message = self._description + \
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)
3763 def _store_get_values(self, cr, uid, ids, fields, context):
3765 fncts = self.pool._store_function.get(self._name, [])
3766 for fnct in range(len(fncts)):
3771 for f in (fields or []):
3772 if f in fncts[fnct][3]:
3778 result.setdefault(fncts[fnct][0], {})
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)
3786 for object in result:
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)))
3801 def _store_set_values(self, cr, uid, ids, fields, context):
3806 if self._log_access:
3807 cr.execute('select id,write_date from '+self._table+' where id IN %s', (tuple(ids),))
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, []):
3816 up_write_date = write_date + datetime.timedelta(hours=i[5])
3817 if datetime.datetime.now() < up_write_date:
3819 field_dict[r[0]].append(i[1])
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)
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():
3836 for f in value.keys():
3837 if f in field_dict[id]:
3844 if self._columns[v]._type in ('many2one', 'one2one'):
3846 value[v] = value[v][0]
3849 upd0.append('"'+v+'"='+self._columns[v]._symbol_set[0])
3850 upd1.append(self._columns[v]._symbol_set[1](value[v]))
3853 cr.execute('update "' + self._table + '" set ' + \
3854 ','.join(upd0) + ' where id = %s', upd1)
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():
3862 if r in field_dict.keys():
3863 if f in field_dict[r]:
3865 for id, value in result.items():
3866 if self._columns[f]._type in ('many2one', 'one2one'):
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))
3878 def perm_write(self, cr, user, ids, fields, context=None):
3879 raise NotImplementedError(_('This method does not exist anymore'))
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
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
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)):
3898 active_in_args = False
3900 if a[0] == 'active':
3901 active_in_args = True
3902 if not active_in_args:
3903 domain.insert(0, ('active', '=', 1))
3905 domain = [('active', '=', 1)]
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 []
3915 where_clause, where_params, tables = [], [], ['"%s"' % self._table]
3917 return Query(tables, where_clause, where_params)
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)'))
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)
3928 :param query: the current query object
3930 def apply_rule(added_clause, added_params, added_tables):
3932 query.where_clause += added_clause
3933 query.where_clause_params += added_params
3934 for table in added_tables:
3935 if table not in query.tables:
3936 query.tables.append(table)
3940 # apply main rules on the object
3941 rule_obj = self.pool.get('ir.rule')
3942 apply_rule(*rule_obj.domain_get(cr, uid, self._name, mode, context=context))
3944 # apply ir.rules from the parents (through _inherits), adding the appropriate JOINs if needed
3945 for inherited_model in self._inherits:
3946 if apply_rule(*rule_obj.domain_get(cr, uid, inherited_model, mode, context=context)):
3947 # if some rules were applied, need to add the missing JOIN for them to make sense, passing the previous
3948 # list of table in case the inherited table was not in the list before (as that means the corresponding
3949 # JOIN(s) was(were) not present)
3950 self._inherits_join_add(inherited_model, query)
3952 def _generate_m2o_order_by(self, order_field, query):
3954 Add possibly missing JOIN to ``query`` and generate the ORDER BY clause for m2o fields,
3955 either native m2o fields or function/related fields that are stored, including
3956 intermediate JOINs for inheritance if required.
3958 :return: the qualified field name to use in an ORDER BY clause to sort by ``order_field``
3960 if order_field not in self._columns and order_field in self._inherit_fields:
3961 # also add missing joins for reaching the table containing the m2o field
3962 qualified_field = self._inherits_join_calc(order_field, query)
3963 order_field_column = self._inherit_fields[order_field][2]
3965 qualified_field = '"%s"."%s"' % (self._table, order_field)
3966 order_field_column = self._columns[order_field]
3968 assert order_field_column._type == 'many2one', 'Invalid field passed to _generate_m2o_order_by()'
3969 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 # figure out the applicable order_by for the m2o
3972 dest_model = self.pool.get(order_field_column._obj)
3973 m2o_order = dest_model._order
3974 if not regex_order.match(m2o_order):
3975 # _order is complex, can't use it here, so we default to _rec_name
3976 m2o_order = dest_model._rec_name
3978 # extract the first field name, to be able to qualify it and add desc/asc
3979 m2o_order = m2o_order.split(",",1)[0].strip().split(" ",1)[0]
3981 # Join the dest m2o table if it's not joined yet. We use [LEFT] OUTER join here
3982 # as we don't want to exclude results that have NULL values for the m2o
3983 src_table, src_field = qualified_field.replace('"','').split('.', 1)
3984 query.join((src_table, dest_model._table, src_field, 'id'), outer=True)
3985 return '"%s"."%s"' % (dest_model._table, m2o_order)
3988 def _generate_order_by(self, order_spec, query):
3990 Attempt to consruct an appropriate ORDER BY clause based on order_spec, which must be
3991 a comma-separated list of valid field names, optionally followed by an ASC or DESC direction.
3993 :raise" except_orm in case order_spec is malformed
3995 order_by_clause = self._order
3997 order_by_elements = []
3998 self._check_qorder(order_spec)
3999 for order_part in order_spec.split(','):
4000 order_split = order_part.strip().split(' ')
4001 order_field = order_split[0].strip()
4002 order_direction = order_split[1].strip() if len(order_split) == 2 else ''
4003 if order_field in self._columns:
4004 order_column = self._columns[order_field]
4005 if order_column._classic_read:
4006 order_by_clause = '"%s"."%s"' % (self._table, order_field)
4007 elif order_column._type == 'many2one':
4008 order_by_clause = self._generate_m2o_order_by(order_field, query)
4010 continue # ignore non-readable or "non-joignable" fields
4011 elif order_field in self._inherit_fields:
4012 parent_obj = self.pool.get(self._inherit_fields[order_field][0])
4013 order_column = parent_obj._columns[order_field]
4014 if order_column._classic_read:
4015 order_by_clause = self._inherits_join_calc(order_field, query)
4016 elif order_column._type == 'many2one':
4017 order_by_clause = self._generate_m2o_order_by(order_field, query)
4019 continue # ignore non-readable or "non-joignable" fields
4020 order_by_elements.append("%s %s" % (order_by_clause, order_direction))
4021 order_by_clause = ",".join(order_by_elements)
4023 return order_by_clause and (' ORDER BY %s ' % order_by_clause) or ''
4025 def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
4027 Private implementation of search() method, allowing specifying the uid to use for the access right check.
4028 This is useful for example when filling in the selection list for a drop-down and avoiding access rights errors,
4029 by specifying ``access_rights_uid=1`` to bypass access rights check, but not ir.rules!
4030 This is ok at the security level because this method is private and not callable through XML-RPC.
4032 :param access_rights_uid: optional user ID to use when checking access rights
4033 (not for ir.rules, this is only for ir.model.access)
4037 self.pool.get('ir.model.access').check(cr, access_rights_uid or user, self._name, 'read', context=context)
4039 query = self._where_calc(cr, user, args, context=context)
4040 self._apply_ir_rules(cr, user, query, 'read', context=context)
4041 order_by = self._generate_order_by(order, query)
4042 from_clause, where_clause, where_clause_params = query.get_sql()
4044 limit_str = limit and ' limit %d' % limit or ''
4045 offset_str = offset and ' offset %d' % offset or ''
4046 where_str = where_clause and (" WHERE %s" % where_clause) or ''
4049 cr.execute('SELECT count("%s".id) FROM ' % self._table + from_clause + where_str + limit_str + offset_str, where_clause_params)
4052 cr.execute('SELECT "%s".id FROM ' % self._table + from_clause + where_str + order_by + limit_str + offset_str, where_clause_params)
4054 return [x[0] for x in res]
4056 # returns the different values ever entered for one field
4057 # this is used, for example, in the client when the user hits enter on
4059 def distinct_field_get(self, cr, uid, field, value, args=None, offset=0, limit=None):
4062 if field in self._inherit_fields:
4063 return self.pool.get(self._inherit_fields[field][0]).distinct_field_get(cr, uid, field, value, args, offset, limit)
4065 return self._columns[field].search(cr, self, args, field, value, offset, limit, uid)
4067 def copy_data(self, cr, uid, id, default=None, context=None):
4069 Copy given record's data with all its fields values
4071 :param cr: database cursor
4072 :param user: current user id
4073 :param id: id of the record to copy
4074 :param default: field values to override in the original values of the copied record
4075 :type default: dictionary
4076 :param context: context arguments, like lang, time zone
4077 :type context: dictionary
4078 :return: dictionary containing all the field values
4085 if 'state' not in default:
4086 if 'state' in self._defaults:
4087 if callable(self._defaults['state']):
4088 default['state'] = self._defaults['state'](self, cr, uid, context)
4090 default['state'] = self._defaults['state']
4092 context_wo_lang = context
4093 if 'lang' in context:
4094 del context_wo_lang['lang']
4095 data = self.read(cr, uid, [id], context=context_wo_lang)[0]
4097 fields = self.fields_get(cr, uid, context=context)
4099 ftype = fields[f]['type']
4101 if self._log_access and f in ('create_date', 'create_uid', 'write_date', 'write_uid'):
4105 data[f] = default[f]
4106 elif ftype == 'function':
4108 elif ftype == 'many2one':
4110 data[f] = data[f] and data[f][0]
4113 elif ftype in ('one2many', 'one2one'):
4115 rel = self.pool.get(fields[f]['relation'])
4117 # duplicate following the order of the ids
4118 # because we'll rely on it later for copying
4119 # translations in copy_translation()!
4121 for rel_id in data[f]:
4122 # the lines are first duplicated using the wrong (old)
4123 # parent but then are reassigned to the correct one thanks
4124 # to the (0, 0, ...)
4125 d = rel.copy_data(cr, uid, rel_id, context=context)
4126 res.append((0, 0, d))
4128 elif ftype == 'many2many':
4129 data[f] = [(6, 0, data[f])]
4133 # make sure we don't break the current parent_store structure and
4134 # force a clean recompute!
4135 for parent_column in ['parent_left', 'parent_right']:
4136 data.pop(parent_column, None)
4138 for v in self._inherits:
4139 del data[self._inherits[v]]
4142 def copy_translations(self, cr, uid, old_id, new_id, context=None):
4143 trans_obj = self.pool.get('ir.translation')
4144 fields = self.fields_get(cr, uid, context=context)
4146 translation_records = []
4147 for field_name, field_def in fields.items():
4148 # we must recursively copy the translations for o2o and o2m
4149 if field_def['type'] in ('one2one', 'one2many'):
4150 target_obj = self.pool.get(field_def['relation'])
4151 old_record, new_record = self.read(cr, uid, [old_id, new_id], [field_name], context=context)
4152 # here we rely on the order of the ids to match the translations
4153 # as foreseen in copy_data()
4154 old_childs = sorted(old_record[field_name])
4155 new_childs = sorted(new_record[field_name])
4156 for (old_child, new_child) in zip(old_childs, new_childs):
4157 # recursive copy of translations here
4158 target_obj.copy_translations(cr, uid, old_child, new_child, context=context)
4159 # and for translatable fields we keep them for copy
4160 elif field_def.get('translate'):
4162 if field_name in self._columns:
4163 trans_name = self._name + "," + field_name
4164 elif field_name in self._inherit_fields:
4165 trans_name = self._inherit_fields[field_name][0] + "," + field_name
4167 trans_ids = trans_obj.search(cr, uid, [
4168 ('name', '=', trans_name),
4169 ('res_id', '=', old_id)
4171 translation_records.extend(trans_obj.read(cr, uid, trans_ids, context=context))
4173 for record in translation_records:
4175 record['res_id'] = new_id
4176 trans_obj.create(cr, uid, record, context=context)
4179 def copy(self, cr, uid, id, default=None, context=None):
4181 Duplicate record with given id updating it with default values
4183 :param cr: database cursor
4184 :param uid: current user id
4185 :param id: id of the record to copy
4186 :param default: dictionary of field values to override in the original values of the copied record, e.g: ``{'field_name': overriden_value, ...}``
4187 :type default: dictionary
4188 :param context: context arguments, like lang, time zone
4189 :type context: dictionary
4193 data = self.copy_data(cr, uid, id, default, context)
4194 new_id = self.create(cr, uid, data, context)
4195 self.copy_translations(cr, uid, id, new_id, context)
4198 def exists(self, cr, uid, ids, context=None):
4199 if type(ids) in (int, long):
4201 query = 'SELECT count(1) FROM "%s"' % (self._table)
4202 cr.execute(query + "WHERE ID IN %s", (tuple(ids),))
4203 return cr.fetchone()[0] == len(ids)
4205 def check_recursion(self, cr, uid, ids, parent=None):
4207 Verifies that there is no loop in a hierarchical structure of records,
4208 by following the parent relationship using the **parent** field until a loop
4209 is detected or until a top-level record is found.
4211 :param cr: database cursor
4212 :param uid: current user id
4213 :param ids: list of ids of records to check
4214 :param parent: optional parent field name (default: ``self._parent_name = parent_id``)
4215 :return: **True** if the operation can proceed safely, or **False** if an infinite loop is detected.
4219 parent = self._parent_name
4221 query = 'SELECT distinct "%s" FROM "%s" WHERE id IN %%s' % (parent, self._table)
4224 for i in range(0, len(ids), cr.IN_MAX):
4225 sub_ids_parent = ids_parent[i:i+cr.IN_MAX]
4226 cr.execute(query, (tuple(sub_ids_parent),))
4227 ids_parent2.extend(filter(None, map(lambda x: x[0], cr.fetchall())))
4228 ids_parent = ids_parent2
4229 for i in ids_parent:
4234 def get_xml_id(self, cr, uid, ids, *args, **kwargs):
4235 """Find out the XML ID of any database record, if there
4236 is one. This method works as a possible implementation
4237 for a function field, to be able to add it to any
4238 model object easily, referencing it as ``osv.osv.get_xml_id``.
4240 **Synopsis**: ``get_xml_id(cr, uid, ids) -> { 'id': 'module.xml_id' }``
4242 :return: the fully qualified XML ID of the given object,
4243 defaulting to an empty string when there's none
4244 (to be usable as a function field).
4246 result = dict.fromkeys(ids, '')
4247 model_data_obj = self.pool.get('ir.model.data')
4248 data_ids = model_data_obj.search(cr, uid,
4249 [('model', '=', self._name), ('res_id', 'in', ids)])
4250 data_results = model_data_obj.read(cr, uid, data_ids,
4251 ['name', 'module', 'res_id'])
4252 for record in data_results:
4253 result[record['res_id']] = '%(module)s.%(name)s' % record
4256 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: