KERNEL: add rollback when exception occurs in tags parsing
[odoo/odoo.git] / bin / tools / convert.py
1 #----------------------------------------------------------
2 # Convert 
3 #----------------------------------------------------------
4 import re
5 import StringIO,xml.dom.minidom
6 import osv,ir,pooler
7
8 import csv
9 import os.path
10
11 from config import config
12
13
14 # Number of imported lines between two commit (see convert_csv_import()):
15 COMMIT_STEP = 500 
16
17
18 class ConvertError(Exception):
19         def __init__(self, doc, orig_excpt):
20                 self.d = doc
21                 self.orig = orig_excpt
22         
23         def __str__(self):
24                 return 'Exception:\n\t%s\nUsing file:\n%s' % (self.orig, self.d)
25
26 def _eval_xml(self,node, pool, cr, uid, idref):
27         if node.nodeType == node.TEXT_NODE:
28                 return node.data.encode("utf8")
29         elif node.nodeType == node.ELEMENT_NODE:
30                 if node.nodeName in ('field','value'):
31                         t = node.getAttribute('type') or 'char'
32                         if len(node.getAttribute('search')):
33                                 f_search = node.getAttribute("search").encode('utf-8')
34                                 f_model = node.getAttribute("model").encode('ascii')
35                                 f_use = node.getAttribute("use").encode('ascii')
36                                 f_name = node.getAttribute("name").encode('utf-8')
37                                 if len(f_use)==0:
38                                         f_use = "id"
39                                 q = eval(f_search, idref)
40                                 ids = pool.get(f_model).search(cr, uid, q)
41                                 if f_use<>'id':
42                                         ids = map(lambda x: x[f_use], pool.get(f_model).read(cr, uid, ids, [f_use]))
43                                 _cols = pool.get(f_model)._columns
44                                 if (f_name in _cols) and _cols[f_name]._type=='many2many':
45                                         return ids
46                                 f_val = False
47                                 if len(ids):
48                                         f_val = ids[0]
49                                         if isinstance(f_val, tuple):
50                                                 f_val = f_val[0]
51                                 return f_val
52                         a_eval = node.getAttribute('eval')
53                         if len(a_eval):
54                                 import time
55                                 idref['time'] = time
56                                 idref['ref'] = lambda x: self.id_get(cr, False, x)
57                                 try:
58                                         import pytz
59                                 except:
60                                         import netsvc
61                                         logger = netsvc.Logger()
62                                         logger.notifyChannel("init", netsvc.LOG_INFO, 'could not find pytz library')
63                                         class pytzclass(object):
64                                                 all_timezones=[]
65                                         pytz=pytzclass()
66                                 idref['pytz'] = pytz
67                                 return eval(a_eval, idref)
68                         if t == 'xml':
69                                 def _process(s, idref):
70                                         m = re.findall('[^%]%\((.*?)\)[ds]', s)
71                                         for id in m:
72                                                 if not id in idref:
73                                                         idref[id]=self.id_get(cr, False, id)
74                                         return s % idref
75                                 txt = '<?xml version="1.0"?>\n'+_process("".join([i.toxml().encode("utf8") for i in node.childNodes]), idref)
76 #                               txt = '<?xml version="1.0"?>\n'+"".join([i.toxml().encode("utf8") for i in node.childNodes]) % idref
77
78                                 return txt
79                         if t in ('char', 'int', 'float'):
80                                 d = ""
81                                 for n in [i for i in node.childNodes]:
82                                         d+=str(_eval_xml(self,n,pool,cr,uid,idref))
83                                 if t == 'int':
84                                         d = d.strip()
85                                         if d=='None':
86                                                 return None
87                                         else:
88                                                 d=int(d.strip())
89                                 elif t=='float':
90                                         d=float(d.strip())
91                                 return d
92                         elif t in ('list','tuple'):
93                                 res=[]
94                                 for n in [i for i in node.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=='value')]:
95                                         res.append(_eval_xml(self,n,pool,cr,uid,idref))
96                                 if t=='tuple':
97                                         return tuple(res)
98                                 return res
99                 elif node.nodeName=="getitem":
100                         for n in [i for i in node.childNodes if (i.nodeType == i.ELEMENT_NODE)]:
101                                 res=_eval_xml(self,n,pool,cr,uid,idref)
102                         if not res:
103                                 raise LookupError
104                         elif node.getAttribute('type') in ("int", "list"):
105                                 return res[int(node.getAttribute('index'))]
106                         else:
107                                 return res[node.getAttribute('index').encode("utf8")]
108                 elif node.nodeName=="function":
109                         args = []
110                         a_eval = node.getAttribute('eval')
111                         if len(a_eval):
112                                 idref['ref'] = lambda x: self.id_get(cr, False, x)
113                                 args = eval(a_eval, idref)
114                         for n in [i for i in node.childNodes if (i.nodeType == i.ELEMENT_NODE)]:
115                                 args.append(_eval_xml(self,n, pool, cr, uid, idref))
116                         model = pool.get(node.getAttribute('model'))
117                         method = node.getAttribute('name')
118                         res = getattr(model, method)(cr, uid, *args)
119                         return res
120
121 escape_re = re.compile(r'(?<!\\)/')
122 def escape(x):
123         return x.replace('\\/', '/')
124
125 class xml_import(object):
126         def _tag_delete(self, cr, rec, data_node=None):
127                 d_model = rec.getAttribute("model")
128                 d_search = rec.getAttribute("search")
129                 ids = self.pool.get(d_model).search(cr,self.uid,eval(d_search))
130                 if len(ids):
131                         self.pool.get(d_model).unlink(cr, self.uid, ids)
132                         #self.pool.get('ir.model.data')._unlink(cr, self.uid, d_model, ids, direct=True)
133                 return False
134
135         def _tag_report(self, cr, rec, data_node=None):
136                 res = {}
137                 for dest,f in (('name','string'),('model','model'),('report_name','name')):
138                         res[dest] = rec.getAttribute(f).encode('utf8')
139                         assert res[dest], "Attribute %s of report is empty !" % (f,)
140                 for field,dest in (('rml','report_rml'),('xml','report_xml'),('xsl','report_xsl')):
141                         if rec.hasAttribute(field):
142                                 res[dest] = rec.getAttribute(field).encode('utf8')
143                 if rec.hasAttribute('auto'):
144                         res['auto'] = eval(rec.getAttribute('auto'))
145                 if rec.hasAttribute('header'):
146                         res['header'] = eval(rec.getAttribute('header'))
147                 xml_id = rec.getAttribute('id').encode('utf8')
148                 id = self.pool.get('ir.model.data')._update(cr, self.uid, "ir.actions.report.xml", self.module, res, xml_id, mode=self.mode)
149                 self.idref[xml_id] = id
150                 if not rec.hasAttribute('menu') or eval(rec.getAttribute('menu')):
151                         keyword = str(rec.getAttribute('keyword') or 'client_print_multi')
152                         keys = [('action',keyword),('res_model',res['model'])]
153                         value = 'ir.actions.report.xml,'+str(id)
154                         replace = rec.hasAttribute('replace') and rec.getAttribute("replace")
155                         self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, res['name'], [res['model']], value, replace=replace, isobject=True)
156                 return False
157
158         def _tag_function(self, cr, rec, data_node=None):
159                 _eval_xml(self,rec, self.pool, cr, self.uid, self.idref)
160                 return False
161
162         def _tag_wizard(self, cr, rec, data_node=None):
163                 string = rec.getAttribute("string").encode('utf8')
164                 model = rec.getAttribute("model").encode('utf8')
165                 name = rec.getAttribute("name").encode('utf8')
166                 xml_id = rec.getAttribute('id').encode('utf8')
167                 multi = rec.hasAttribute('multi') and  eval(rec.getAttribute('multi'))
168                 res = {'name': string, 'wiz_name': name, 'multi':multi}
169
170                 id = self.pool.get('ir.model.data')._update(cr, self.uid, "ir.actions.wizard", self.module, res, xml_id, mode=self.mode)
171                 self.idref[xml_id] = id
172                 # ir_set
173                 if not rec.hasAttribute('menu') or eval(rec.getAttribute('menu')):
174                         keyword = str(rec.getAttribute('keyword') or 'client_action_multi')
175                         keys = [('action',keyword),('res_model',model)]
176                         value = 'ir.actions.wizard,'+str(id)
177                         replace = rec.hasAttribute('replace') and rec.getAttribute("replace")
178                         self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, string, [model], value, replace=replace, isobject=True)
179                 return False
180
181         def _tag_ir_set(self, cr, rec, data_node=None):
182                 if not self.mode=='init':
183                         return False
184                 res = {}
185                 for field in [i for i in rec.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=="field")]:
186                         f_name = field.getAttribute("name").encode('utf-8')
187                         f_val = _eval_xml(self,field,self.pool, cr, self.uid, self.idref)
188                         res[f_name] = f_val
189                 self.pool.get('ir.model.data').ir_set(cr, self.uid, res['key'], res['key2'], res['name'], res['models'], res['value'], replace=res.get('replace',True), isobject=res.get('isobject', False), meta=res.get('meta',None))
190                 return False
191
192         def _tag_workflow(self, cr, rec, data_node=None):
193                 import netsvc
194                 model = str(rec.getAttribute('model'))
195                 wf_service = netsvc.LocalService("workflow")
196                 wf_service.trg_validate(self.uid, model,
197                         self.id_get(cr, model, rec.getAttribute('ref')),
198                         str(rec.getAttribute('action')), cr)
199                 return False
200
201         def _tag_menuitem(self, cr, rec, data_node=None):
202                 rec_id = rec.getAttribute("id").encode('ascii')
203                 m_l = map(escape, escape_re.split(rec.getAttribute("name").encode('utf8')))
204                 pid = False
205                 for idx, menu_elem in enumerate(m_l):
206                         if pid:
207                                 cr.execute('select id from ir_ui_menu where parent_id=%d and name=%s', (pid, menu_elem))
208                         else:
209                                 cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (menu_elem,))
210                         res = cr.fetchone()
211                         if idx==len(m_l)-1:
212                                 # we are at the last menu element/level (it's a leaf)
213                                 values = {'parent_id': pid,'name':menu_elem}
214
215                                 if rec.hasAttribute('action'):
216                                         a_action = rec.getAttribute('action').encode('utf8')
217                                         a_type = rec.getAttribute('type').encode('utf8') or 'act_window'
218                                         icons = {
219                                                 "act_window": 'STOCK_NEW',
220                                                 "report.xml": 'STOCK_PASTE',
221                                                 "wizard": 'STOCK_EXECUTE',
222                                         }
223                                         values['icon'] = icons.get(a_type,'STOCK_NEW')
224                                         if a_type=='act_window':
225                                                 a_id = self.id_get(cr, 'ir.actions.%s'% a_type, a_action)
226                                                 cr.execute('select view_type,view_mode from ir_act_window where id=%d', (int(a_id),))
227                                                 action_type,action_mode = cr.fetchone()
228                                                 if action_type=='tree':
229                                                         values['icon'] = 'STOCK_INDENT'
230                                                 elif action_mode and action_mode.startswith('tree'):
231                                                         values['icon'] = 'STOCK_JUSTIFY_FILL'
232                                                 elif action_mode and action_mode.startswith('graph'):
233                                                         values['icon'] = 'terp-account'
234                                 if rec.hasAttribute('sequence'):
235                                         values['sequence'] = int(rec.getAttribute('sequence'))
236                                 if rec.hasAttribute('icon'):
237                                         values['icon'] = str(rec.getAttribute('icon'))
238                                 if rec.hasAttribute('groups'):
239                                         g_names = rec.getAttribute('groups').split(',')
240                                         g_ids = []
241                                         for group in g_names:
242                                                 g_ids.extend(self.pool.get('res.groups').search(cr, self.uid, [('name', '=', group)]))
243                                         values['groups_id'] = [(6, 0, g_ids)]
244                                 xml_id = rec.getAttribute('id').encode('utf8')
245                                 pid = self.pool.get('ir.model.data')._update(cr, self.uid, 'ir.ui.menu', self.module, values, xml_id, idx==len(m_l)-1, mode=self.mode, res_id=res and res[0] or False)
246                         elif res:
247                                 # the menuitem already exists
248                                 pid = res[0]
249                                 xml_id = idx==len(m_l)-1 and rec.getAttribute('id').encode('utf8')
250                                 try:
251                                         npid = self.pool.get('ir.model.data')._update_dummy(cr, self.uid, 'ir.ui.menu', self.module, xml_id, idx==len(m_l)-1)
252                                 except:
253                                         print 'Menu Error', self.module, xml_id, idx==len(m_l)-1
254                         else:
255                                 # the menuitem does't exist but we are in branch (not a leaf)
256                                 pid = self.pool.get('ir.ui.menu').create(cr, self.uid, {'parent_id' : pid, 'name' : menu_elem})
257                 if rec_id and pid:
258                         self.idref[rec_id] = pid
259
260                 if rec.hasAttribute('action') and pid:
261                         a_action = rec.getAttribute('action').encode('utf8')
262                         a_type = rec.getAttribute('type').encode('utf8') or 'act_window'
263                         a_id = self.id_get(cr, 'ir.actions.%s' % a_type, a_action)
264                         action = "ir.actions.%s,%d" % (a_type, a_id)
265                         self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', 'tree_but_open', 'Menuitem', [('ir.ui.menu', int(pid))], action, True, True)
266                 return ('ir.ui.menu', pid)
267
268         def _tag_record(self, cr, rec, data_node=None):
269                 rec_model = rec.getAttribute("model").encode('ascii')
270                 model = self.pool.get(rec_model)
271                 assert model, "The model %s does not exist !" % (rec_model,)
272                 rec_id = rec.getAttribute("id").encode('ascii')
273
274 #               if not rec_id and not data_node.getAttribute('noupdate'):
275 #                       print "Warning", rec_model
276
277                 if data_node.getAttribute('noupdate') and not self.mode == 'init':
278                         # check if the xml record has an id string
279                         if rec_id:
280                                 id = self.pool.get('ir.model.data')._update_dummy(cr, self.uid, rec_model, self.module, rec_id)
281                                 # check if the resource already existed at the last update
282                                 if id:
283                                         # if it existed, we don't update the data, but we need to 
284                                         # know the id of the existing record anyway
285                                         self.idref[rec_id] = id
286                                         return None
287                                 else:
288                                         # if the resource didn't exist
289                                         if rec.getAttribute("forcecreate"):
290                                                 # we want to create it, so we let the normal "update" behavior happen
291                                                 pass
292                                         else:
293                                                 # otherwise do nothing
294                                                 return None
295                         else:
296                                 # otherwise it is skipped
297                                 return None
298                                 
299                 res = {}
300                 for field in [i for i in rec.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=="field")]:
301 #TODO: most of this code is duplicated above (in _eval_xml)...
302                         f_name = field.getAttribute("name").encode('utf-8')
303                         f_ref = field.getAttribute("ref").encode('ascii')
304                         f_search = field.getAttribute("search").encode('utf-8')
305                         f_model = field.getAttribute("model").encode('ascii')
306                         if not f_model and model._columns.get(f_name,False):
307                                 f_model = model._columns[f_name]._obj
308                         f_use = field.getAttribute("use").encode('ascii') or 'id'
309                         f_val = False
310
311                         if len(f_search):
312                                 q = eval(f_search, self.idref)
313                                 field = []
314                                 assert f_model, 'Define an attribute model="..." in your .XML file !'
315                                 f_obj = self.pool.get(f_model)
316                                 # browse the objects searched
317                                 s = f_obj.browse(cr, self.uid, f_obj.search(cr, self.uid, q))
318                                 # column definitions of the "local" object
319                                 _cols = self.pool.get(rec_model)._columns
320                                 # if the current field is many2many
321                                 if (f_name in _cols) and _cols[f_name]._type=='many2many':
322                                         f_val = [(6, 0, map(lambda x: x[f_use], s))]
323                                 elif len(s):
324                                         # otherwise (we are probably in a many2one field),
325                                         # take the first element of the search
326                                         f_val = s[0][f_use]
327                         elif len(f_ref):
328                                 if f_ref=="null":
329                                         f_val = False
330                                 else:
331                                         f_val = self.id_get(cr, f_model, f_ref)
332                         else:
333                                 f_val = _eval_xml(self,field, self.pool, cr, self.uid, self.idref)
334                                 if model._columns.has_key(f_name):
335                                         if isinstance(model._columns[f_name], osv.fields.integer):
336                                                 f_val = int(f_val)
337                         res[f_name] = f_val
338                 id = self.pool.get('ir.model.data')._update(cr, self.uid, rec_model, self.module, res, rec_id or False, not data_node.getAttribute('noupdate'), noupdate=data_node.getAttribute('noupdate'), mode=self.mode )
339                 if rec_id:
340                         self.idref[rec_id] = id
341                 return rec_model, id
342
343         def id_get(self, cr, model, id_str):
344                 if id_str in self.idref:
345                         return self.idref[id_str]
346                 mod = self.module
347                 if '.' in id_str:
348                         mod,id_str = id_str.split('.')
349                 result = self.pool.get('ir.model.data')._get_id(cr, self.uid, mod, id_str)
350                 return self.pool.get('ir.model.data').read(cr, self.uid, [result], ['res_id'])[0]['res_id']
351
352         def parse(self, xmlstr):
353                 d = xml.dom.minidom.parseString(xmlstr)
354                 de = d.documentElement
355                 for n in [i for i in de.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=="data")]:
356                         for rec in n.childNodes:
357                                 if rec.nodeType == rec.ELEMENT_NODE:
358                                         if rec.nodeName in self._tags:
359                                                 try:
360                                                         self._tags[rec.nodeName](self.cr, rec, n)
361                                                 except:
362                                                         import netsvc
363                                                         logger = netsvc.Logger()
364                                                         logger.notifyChannel("init", netsvc.LOG_INFO, '\n'+rec.toxml())
365                                                         self.cr.rollback()
366                                                         raise
367                 self.cr.commit()
368                 return True
369
370         def __init__(self, cr, module, idref, mode):
371                 self.mode = mode
372                 self.module = module
373                 self.cr = cr
374                 self.idref = idref
375                 self.pool = pooler.get_pool(cr.dbname)
376 #               self.pool = osv.osv.FakePool(module)
377                 self.uid = 1
378                 self._tags = {
379                         'menuitem': self._tag_menuitem,
380                         'record': self._tag_record,
381                         'report': self._tag_report,
382                         'wizard': self._tag_wizard,
383                         'delete': self._tag_delete,
384                         'ir_set': self._tag_ir_set,
385                         'function': self._tag_function,
386                         'workflow': self._tag_workflow,
387                 }
388
389 #
390 # Import a CSV file:
391 #     quote: "
392 #     delimiter: ,
393 #     encoding: UTF8
394 #
395 def convert_csv_import(cr, module, fname, csvcontent, idref={}, mode='init'):
396         if mode != 'init':
397                 return
398         model = ('.'.join(fname.split('.')[:-1]).split('-'))[0]
399         #model = fname.split('.')[0].replace('_', '.')
400
401         #remove folder path from model
402         head, model = os.path.split(model)
403
404         pool = pooler.get_pool(cr.dbname)
405 #       pool = osv.osv.FakePool(module)
406
407         input=StringIO.StringIO(csvcontent)
408         reader = csv.reader(input, quotechar='"', delimiter=',')
409         fields = reader.next()
410
411         uid = 1
412         datas = []
413         for line in reader:
414                 datas.append( map(lambda x:x.decode('utf8').encode('utf8'), line))
415                 if len(datas) > COMMIT_STEP:
416                         pool.get(model).import_data(cr, uid, fields, datas)
417                         cr.commit()
418                         datas=[]
419
420         if datas:
421                 pool.get(model).import_data(cr, uid, fields, datas)
422                 cr.commit()
423
424 #
425 # xml import/export
426 #
427 def convert_xml_import(cr, module, xmlstr, idref={}, mode='init'):
428         obj = xml_import(cr, module, idref, mode)
429         obj.parse(xmlstr)
430         del obj
431         return True
432
433 def convert_xml_export(res):
434         uid=1
435         pool=pooler.get_pool(cr.dbname)
436         cr=pooler.db.cursor()
437         idref = {}
438         d = xml.dom.minidom.getDOMImplementation().createDocument(None, "terp", None)
439         de = d.documentElement
440         data=d.createElement("data")
441         de.appendChild(data)
442         de.appendChild(d.createTextNode('Some textual content.'))
443         cr.commit()
444         cr.close()
445