[IMP] removed the possible SQL injection server.
authorAnup (OpenERP) <ach@tinyerp.com>
Tue, 15 Jun 2010 13:27:22 +0000 (18:57 +0530)
committerAnup (OpenERP) <ach@tinyerp.com>
Tue, 15 Jun 2010 13:27:22 +0000 (18:57 +0530)
bzr revid: ach@tinyerp.com-20100615132722-zbua6ciz3dz43qd8

13 files changed:
bin/addons/base/ir/ir_attachment.py
bin/addons/base/ir/ir_translation.py
bin/addons/base/ir/ir_values.py
bin/addons/base/ir/workflow/print_instance.py
bin/addons/base/module/module.py
bin/addons/base/res/partner/partner.py
bin/addons/base/res/res_company.py
bin/addons/base/res/res_currency.py
bin/osv/expression.py
bin/osv/fields.py
bin/osv/orm.py
bin/tools/misc.py
bin/tools/translate.py

index 4ca585a..cac1bee 100644 (file)
@@ -30,7 +30,7 @@ class ir_attachment(osv.osv):
         ima = self.pool.get('ir.model.access')
         if isinstance(ids, (int, long)):
             ids = [ids]
-        cr.execute('select distinct res_model from ir_attachment where id = ANY (%s)', (ids,))
+        cr.execute('select distinct res_model from ir_attachment where id in %s', (tuple(ids),))
         for obj in cr.fetchall():
             if obj[0]:
                 ima.check(cr, uid, obj[0], mode, context=context)
@@ -84,7 +84,7 @@ class ir_attachment(osv.osv):
         dataobj = self.pool.get('ir.model.data')
         data_id = dataobj._get_id(cr, 1, 'base', 'action_attachment')
         res_id = dataobj.browse(cr, uid, data_id, context).res_id
-        return self.pool.get('ir.actions.act_window').read(cr, uid, res_id, [], context)    
+        return self.pool.get('ir.actions.act_window').read(cr, uid, res_id, [], context)
 
     def _name_get_resname(self, cr, uid, ids, object,method, context):
         data = {}
index 8e575b6..1a36328 100644 (file)
@@ -88,8 +88,8 @@ class ir_translation(osv.osv):
                     'where lang=%s ' \
                         'and type=%s ' \
                         'and name=%s ' \
-                        'and res_id in ('+','.join(map(str, ids))+')',
-                    (lang,tt,name))
+                        'and res_id in %s',
+                    (lang,tt,name,tuple(ids)))
             for res_id, value in cr.fetchall():
                 translations[res_id] = value
         return translations
index 7299b45..c33aba0 100644 (file)
@@ -1,6 +1,6 @@
 # -*- coding: utf-8 -*-
 ##############################################################################
-#    
+#
 #    OpenERP, Open Source Management Solution
 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
 #
@@ -15,7 +15,7 @@
 #    GNU Affero General Public License for more details.
 #
 #    You should have received a copy of the GNU Affero General Public License
-#    along with this program.  If not, see <http://www.gnu.org/licenses/>.     
+#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 #
 ##############################################################################
 
@@ -161,54 +161,33 @@ class ir_values(osv.osv):
             else:
                 res_id=False
 
-            where1 = ['key=%s','model=%s']
-            where2 = [key,str(m)]
-            where_opt = []
+            where = ['key=%s','model=%s']
+            params = [key, str(m)]
             if key2:
-                where1.append('key2=%s')
-                where2.append(key2[:200])
+                where.append('key2=%s')
+                params.append(key2[:200])
             else:
-                dest = where1
-                if not key2_req or meta:
-                    dest=where_opt
-                dest.append('key2 is null')
-
+                if key2_req and not meta:
+                    where.append('key2 is null')
             if res_id_req and (models[-1][0]==m):
                 if res_id:
-                    where1.append('res_id=%d' % (res_id,))
+                    where.append('res_id=%s')
+                    params.append(res_id)
                 else:
-                    where1.append('(res_id is NULL)')
+                    where.append('(res_id is NULL)')
             elif res_id:
                 if (models[-1][0]==m):
-                    where1.append('(res_id=%d or (res_id is null))' % (res_id,))
-                    where_opt.append('res_id=%d' % (res_id,))
+                    where.append('(res_id=%s or (res_id is null))')
+                    params.append(res_id)
                 else:
-                    where1.append('res_id=%d' % (res_id,))
-
-#           if not without_user:
-            where_opt.append('user_id=%d' % (uid,))
-
-            result = []
-            ok = True
-            result_ids = {}
-            while ok:
-                if not where_opt:
-                    cr.execute('select id,name,value,object,meta, key from ir_values where ' +\
-                            ' and '.join(where1)+' and user_id is null', where2)
-                else:
-                    cr.execute('select id,name,value,object,meta, key from ir_values where ' +\
-                            ' and '.join(where1+where_opt), where2)
-                for rec in cr.fetchall():
-                    if rec[0] in result_ids:
-                        continue
-                    if rec[2]:                    
-                        result.append(rec)
-                        result_ids[rec[0]] = True
-                if len(where_opt):
-                    where_opt.pop()
-                else:
-                    ok = False
-
+                    where.append('res_id=%s')
+                    params.append(res_id)
+
+            where.append('(user_id=%s or (user_id IS NULL))')
+            params.append(uid)
+            clause = ' and '.join(where)
+            cr.execute('select id,name,value,object,meta, key from ir_values where ' + clause, params)
+            result = cr.fetchall()
             if result:
                 break
 
@@ -250,16 +229,16 @@ class ir_values(osv.osv):
         res2 = res[:]
         for r in res:
             if type(r[2])==type({}) and 'type' in r[2]:
-                if r[2]['type'] in ('ir.actions.report.xml','ir.actions.act_window','ir.actions.wizard'):
-                    if r[2].has_key('groups_id'):
-                        groups = r[2]['groups_id']
-                        if len(groups) > 0:
-                            cr.execute("SELECT count(*) FROM res_groups_users_rel WHERE gid = ANY(%s) AND uid=%s",(groups, uid))
-                            gr_ids = cr.fetchall()
-                            if not gr_ids[0][0] > 0:
-                                res2.remove(r)
-                            if r[1]=='Menuitem' and not res2:
-                                  raise osv.except_osv('Error !','You do not have the permission to perform this operation !!!')
+                groups = r[2].get('groups_id')
+                if groups:
+                        cr.execute('SELECT COUNT(1) FROM res_groups_users_rel WHERE gid IN %s AND uid=%s',
+                                   (tuple(groups), uid)
+                                  )
+                        cnt = cr.fetchone()[0]
+                        if cnt:
+                            res2.remove(r)
+                        if r[1] == 'Menuitem' and not res2:
+                            raise osv.except_osv('Error !','You do not have the permission to perform this operation !!!')
         return res2
 ir_values()
 
index bac8eed..f34bb71 100644 (file)
@@ -1,6 +1,6 @@
 # -*- coding: utf-8 -*-
 ##############################################################################
-#    
+#
 #    OpenERP, Open Source Management Solution
 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
 #
@@ -15,7 +15,7 @@
 #    GNU Affero General Public License for more details.
 #
 #    You should have received a copy of the GNU Affero General Public License
-#    along with this program.  If not, see <http://www.gnu.org/licenses/>.     
+#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 #
 ##############################################################################
 
@@ -23,7 +23,7 @@ import time, os
 
 import netsvc
 import report,pooler,tools
-
+from operator import itemgetter
 
 def graph_get(cr, graph, wkf_id, nested=False, workitem={}):
     import pydot
@@ -56,7 +56,8 @@ def graph_get(cr, graph, wkf_id, nested=False, workitem={}):
             graph.add_node(pydot.Node(n['id'], **args))
             actfrom[n['id']] = (n['id'],{})
             actto[n['id']] = (n['id'],{})
-    cr.execute('select * from wkf_transition where act_from in ('+','.join(map(lambda x: str(x['id']),nodes))+')')
+            node_ids = tuple(map(itemgetter('id'), nodes))
+    cr.execute('select * from wkf_transition where act_from in %s', (node_ids,))
     transitions = cr.dictfetchall()
     for t in transitions:
         args = {}
@@ -146,7 +147,7 @@ showpage'''
                 else:
                     inst_id = inst_id[0]
                     graph = pydot.Dot(fontsize='16', label="""\\\n\\nWorkflow: %s\\n OSV: %s""" % (wkfinfo['name'],wkfinfo['osv']),
-                                      size='7.3, 10.1', center='1', ratio='auto', rotate='0', rankdir='TB',                                      
+                                      size='7.3, 10.1', center='1', ratio='auto', rotate='0', rankdir='TB',
                                      )
                     graph_instance_get(cr, graph, inst_id, data.get('nested', False))
                     ps_string = graph.create(prog='dot', format='ps')
index e29e95b..9d4ba1d 100644 (file)
@@ -44,7 +44,14 @@ class module_category(osv.osv):
     _description = "Module Category"
 
     def _module_nbr(self,cr,uid, ids, prop, unknow_none,context):
-        cr.execute('select category_id,count(*) from ir_module_module where category_id in ('+','.join(map(str, ids))+') or category_id in (select id from ir_module_category where parent_id in ('+','.join(map(str, ids))+')) group by category_id')
+        cr.execute('SELECT category_id, COUNT(*) \
+                      FROM ir_module_module \
+                     WHERE category_id IN %(ids)s \
+                        OR category_id IN (SELECT id \
+                                             FROM ir_module_category \
+                                            WHERE parent_id IN %(ids)s) \
+                     GROUP BY category_id', {'ids': tuple(ids)}
+                    )
         result = dict(cr.fetchall())
         for id in ids:
             cr.execute('select id from ir_module_category where parent_id=%s', (id,))
index 3a12868..bb186d3 100644 (file)
@@ -55,7 +55,7 @@ class res_partner_category(osv.osv):
     def _check_recursion(self, cr, uid, ids):
         level = 100
         while len(ids):
-            cr.execute('select distinct parent_id from res_partner_category where id in ('+','.join(map(str, ids))+')')
+            cr.execute('select distinct parent_id from res_partner_category where id in %s',(tuple(ids),))
             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
             if not level:
                 return False
@@ -226,7 +226,7 @@ class res_partner(osv.osv):
         return True
 
     def address_get(self, cr, uid, ids, adr_pref=['default']):
-        cr.execute('select type,id from res_partner_address where partner_id in ('+','.join(map(str,map(int, ids)))+')')
+        cr.execute('select type,id from res_partner_address where partner_id in %s',(tuple(ids),))
         res = cr.fetchall()
         adr = dict(res)
         # get the id of the (first) default address if there is one,
index 4b6ec1d..67f3b54 100644 (file)
@@ -179,7 +179,7 @@ class res_company(osv.osv):
     def _check_recursion(self, cr, uid, ids):
         level = 100
         while len(ids):
-            cr.execute('select distinct parent_id from res_company where id in ('+','.join(map(str, ids))+')')
+            cr.execute('select distinct parent_id from res_company where id in %s',(tuple(ids),))
             ids = filter(None, map(lambda x:x[0], cr.fetchall()))
             if not level:
                 return False
index 0e4faa6..86742dc 100644 (file)
@@ -1,6 +1,6 @@
 # -*- coding: utf-8 -*-
 ##############################################################################
-#    
+#
 #    OpenERP, Open Source Management Solution
 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
 #
@@ -15,7 +15,7 @@
 #    GNU Affero General Public License for more details.
 #
 #    You should have received a copy of the GNU Affero General Public License
-#    along with this program.  If not, see <http://www.gnu.org/licenses/>.     
+#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 #
 ##############################################################################
 import time
@@ -35,7 +35,7 @@ class res_currency(osv.osv):
             date=time.strftime('%Y-%m-%d')
         date= date or time.strftime('%Y-%m-%d')
         for id in ids:
-            cr.execute("SELECT currency_id, rate FROM res_currency_rate WHERE currency_id = %s AND name <= '%s' ORDER BY name desc LIMIT 1" % (id, date))
+            cr.execute("SELECT currency_id, rate FROM res_currency_rate WHERE currency_id = %s AND name <= %s ORDER BY name desc LIMIT 1" ,(id, date))
             if cr.rowcount:
                 id, rate=cr.fetchall()[0]
                 res[id]=rate
index 4da2a70..16f34c7 100644 (file)
@@ -29,7 +29,7 @@ class expression(object):
     parse a domain expression
     use a real polish notation
     leafs are still in a ('foo', '=', 'bar') format
-    For more info: http://christophe-simonis-at-tiny.blogspot.com/2008/08/new-new-domain-notation.html 
+    For more info: http://christophe-simonis-at-tiny.blogspot.com/2008/08/new-new-domain-notation.html
     """
 
     def _is_operator(self, element):
@@ -50,16 +50,15 @@ class expression(object):
             if op in ['<','>','>=','<=']:
                 cr.execute('SELECT "%s"'    \
                                '  FROM "%s"'    \
-                               ' WHERE "%s" %s %s' % (s, f, w, op, ids[0]))
+                               ' WHERE "%s" %s %%s' % (s, f, w, op), (ids[0],))
                 res.extend([r[0] for r in cr.fetchall()])
             else:
                 for i in range(0, len(ids), cr.IN_MAX):
                     subids = ids[i:i+cr.IN_MAX]
                     cr.execute('SELECT "%s"'    \
                                '  FROM "%s"'    \
-                               '  WHERE "%s" in (%s)' % (s, f, w, ','.join(['%s']*len(subids))),
-                               subids)
-                    res.extend([r[0] for r in cr.fetchall()])                                     
+                               '  WHERE "%s" in %%s' % (s, f, w),(tuple(subids),))
+                    res.extend([r[0] for r in cr.fetchall()])
         else:
             cr.execute('SELECT distinct("%s")'    \
                            '  FROM "%s" where "%s" is not null'  % (s, f, s)),
@@ -128,7 +127,7 @@ class expression(object):
                         self.__joins.append('%s.%s=%s.%s' % (working_table._table, 'id', main_table._table, main_table._inherits[working_table._name]))
                         self.__all_tables.add(working_table)
                     main_table = working_table
-            
+
             field = working_table._columns.get(fargs[0], False)
             if not field:
                 if left == 'id' and operator == 'child_of':
@@ -176,20 +175,20 @@ class expression(object):
                     else:
                         dom = _rec_get(ids2, working_table, parent=left)
                     self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
-                
-                else:    
+
+                else:
                     call_null = True
-                    
+
                     if right:
                         if isinstance(right, basestring):
                             ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator, context=context, limit=None)]
                             if ids2:
-                                operator = 'in' 
+                                operator = 'in'
                         else:
                             if not isinstance(right,list):
                                 ids2 = [right]
                             else:
-                                ids2 = right    
+                                ids2 = right
                         if not ids2:
                             if operator in ['like','ilike','in','=']:
                                 #no result found with given search criteria
@@ -204,12 +203,12 @@ class expression(object):
                             if operator in  ['not like','not ilike','not in','<>','!=']:
                                 o2m_op = 'not in'
                             self.__exp[i] = ('id', o2m_op, self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', ids2, operator, field._type))
-                    
+
                     if call_null:
                         o2m_op = 'not in'
                         if operator in  ['not like','not ilike','not in','<>','!=']:
-                            o2m_op = 'in'                         
-                        self.__exp[i] = ('id', o2m_op, self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', [], operator, field._type) or [0])      
+                            o2m_op = 'in'
+                        self.__exp[i] = ('id', o2m_op, self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', [], operator, field._type) or [0])
 
             elif field._type == 'many2many':
                 #FIXME
@@ -244,20 +243,20 @@ class expression(object):
                                 #no result found with given search criteria
                                 call_null_m2m = False
                                 self.__exp[i] = ('id','=',0)
-                            else: 
+                            else:
                                 call_null_m2m = True
                                 operator = 'in' # operator changed because ids are directly related to main object
                         else:
                             call_null_m2m = False
-                            m2m_op = 'in'        
+                            m2m_op = 'in'
                             if operator in  ['not like','not ilike','not in','<>','!=']:
                                 m2m_op = 'not in'
-                            
+
                             self.__exp[i] = ('id', m2m_op, self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, res_ids, operator, field._type) or [0])
                     if call_null_m2m:
                         m2m_op = 'not in'
                         if operator in  ['not like','not ilike','not in','<>','!=']:
-                            m2m_op = 'in'                         
+                            m2m_op = 'in'
                         self.__exp[i] = ('id', m2m_op, self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, [], operator,  field._type) or [0])
 
             elif field._type == 'many2one':
@@ -289,16 +288,16 @@ class expression(object):
                 # other field type
                 # add the time part to datetime field when it's not there:
                 if field._type == 'datetime' and self.__exp[i][2] and len(self.__exp[i][2]) == 10:
-                    
+
                     self.__exp[i] = list(self.__exp[i])
-                    
+
                     if operator in ('>', '>='):
                         self.__exp[i][2] += ' 00:00:00'
                     elif operator in ('<', '<='):
                         self.__exp[i][2] += ' 23:59:59'
-                    
+
                     self.__exp[i] = tuple(self.__exp[i])
-                        
+
                 if field.translate:
                     if operator in ('like', 'ilike', 'not like', 'not ilike'):
                         right = '%%%s%%' % right
@@ -341,7 +340,7 @@ class expression(object):
         if leaf == self.__DUMMY_LEAF:
             return ('(1=1)', [])
         left, operator, right = leaf
-        
+
         if operator == 'inselect':
             query = '(%s.%s in (%s))' % (table._table, left, right[0])
             params = right[1]
@@ -355,7 +354,7 @@ class expression(object):
             len_after = len(params)
             check_nulls = len_after != len_before
             query = '(1=0)'
-            
+
             if len_after:
                 if left == 'id':
                     instr = ','.join(['%s'] * len_after)
@@ -372,7 +371,7 @@ class expression(object):
                 query = '(%s OR %s.%s IS NULL)' % (query, table._table, left)
         else:
             params = []
-            
+
             if right == False and (leaf[0] in table._columns)  and table._columns[leaf[0]]._type=="boolean"  and (operator == '='):
                 query = '(%s.%s IS NULL or %s.%s = false )' % (table._table, left,table._table, left)
             elif (((right == False) and (type(right)==bool)) or (right is None)) and (operator == '='):
index ffb0a87..623ab94 100644 (file)
@@ -469,7 +469,7 @@ class one2many(_column):
             elif act[0] == 6:
                 obj.write(cr, user, act[2], {self._fields_id:id}, context=context or {})
                 ids2 = act[2] or [0]
-                cr.execute('select id from '+_table+' where '+self._fields_id+'=%s and id <> ALL (%s)', (id,ids2))
+                cr.execute('select id from '+_table+' where '+self._fields_id+'=%s and id <> ALL %s', (id,tuple(ids2)))
                 ids3 = map(lambda x:x[0], cr.fetchall())
                 obj.write(cr, user, ids3, {self._fields_id:False}, context=context or {})
         return result
@@ -521,13 +521,24 @@ class many2many(_column):
         if d1:
             d1 = ' and ' + ' and '.join(d1)
         else: d1 = ''
-
-        cr.execute('SELECT '+self._rel+'.'+self._id2+','+self._rel+'.'+self._id1+' \
-                FROM '+self._rel+' , '+(','.join(tables))+' \
-                WHERE '+self._rel+'.'+self._id1+' = ANY (%s) \
-                    AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+d1
-                +limit_str+' order by '+obj._table+'.'+obj._order+' offset %s',
-                [ids,]+d2+[offset])
+        query = 'SELECT %(rel)s.%(id2)s, %(rel)s.%(id1)s \
+                   FROM %(rel)s, %(tbl)s \
+                  WHERE %(rel)s.%(id1)s in %%s \
+                    AND %(rel)s.%(id2)s = %(tbl)s.id \
+                 %(d1)s  \
+                 %(limit)s \
+                  ORDER BY %(tbl)s.%(order)s \
+                 OFFSET %(offset)d' \
+            % {'rel': self._rel,
+               'tbl': obj._table,
+               'id1': self._id1,
+               'id2': self._id2,
+               'd1': d1,
+               'limit': limit_str,
+               'order': obj._order,
+               'offset': offset,
+              }
+        cr.execute(query, [tuple(ids)] + d2)
         for r in cr.fetchall():
             res[r[1]].append(r[0])
         return res
index 7aa1a4c..e4b3d92 100644 (file)
@@ -987,7 +987,7 @@ class orm_template(object):
                     return (-1, res, 'Line ' + str(counter) +' : ' + msg, '' )
                 #Raising Uncaught exception
                 return (-1, res, 'Line ' + str(counter) +' : ' + str(e), '' )
-            
+
             for lang in translate:
                 context2 = context.copy()
                 context2['lang'] = lang
@@ -1538,8 +1538,12 @@ class orm_template(object):
                         view_id = view_ref_res[0]
 
             if view_id:
-                where = (model and (" and model='%s'" % (self._name,))) or ''
-                cr.execute('SELECT arch,name,field_parent,id,type,inherit_id FROM ir_ui_view WHERE id=%s'+where, (view_id,))
+                query = "SELECT arch,name,field_parent,id,type,inherit_id FROM ir_ui_view WHERE id=%s"
+                params = (view_id,)
+                if model:
+                    query += " AND model=%s"
+                    params += (self._name,)
+                cr.execute(query, params)
             else:
                 cr.execute('''SELECT
                         arch,name,field_parent,id,type,inherit_id
@@ -1981,7 +1985,7 @@ class orm_memory(orm_template):
             if id in self.datas:
                 del self.datas[id]
         if len(ids):
-            cr.execute('delete from wkf_instance where res_type=%s and res_id = ANY  (%s)', (self._name,ids))
+            cr.execute('delete from wkf_instance where res_type=%s and res_id in %s', (self._name, tuple(ids)))
         return True
 
     def perm_read(self, cr, user, ids, context=None, details=True):
@@ -2194,12 +2198,12 @@ class orm(orm_template):
         columns += ('id', 'write_uid', 'write_date', 'create_uid', 'create_date') # openerp access columns
         cr.execute("SELECT a.attname, a.attnotnull"
                    "  FROM pg_class c, pg_attribute a"
-                   " WHERE c.relname=%%s"
+                   " WHERE c.relname=%s"
                    "   AND c.oid=a.attrelid"
-                   "   AND a.attisdropped=%%s"
+                   "   AND a.attisdropped=%s"
                    "   AND pg_catalog.format_type(a.atttypid, a.atttypmod) NOT IN ('cid', 'tid', 'oid', 'xid')"
-                   "   AND a.attname NOT IN (%s)" % ",".join(['%s']*len(columns)),
-                       [self._table, False] + columns)
+                   "   AND a.attname NOT IN %s" ,(self._table, False, tuple(columns))),
+
         for column in cr.dictfetchall():
             if log:
                 logger.notifyChannel("orm", netsvc.LOG_DEBUG, "column %s is in the table %s but not in the corresponding object %s" % (column['attname'], self._table, self._name))
@@ -2213,9 +2217,9 @@ class orm(orm_template):
         todo_end = []
         self._field_create(cr, context=context)
         if getattr(self, '_auto', True):
-            cr.execute("SELECT relname FROM pg_class WHERE relkind in ('r','v') AND relname='%s'" % self._table)
+            cr.execute("SELECT relname FROM pg_class WHERE relkind in ('r','v') AND relname=%s" ,( self._table,))
             if not cr.rowcount:
-                cr.execute("CREATE TABLE \"%s\" (id SERIAL NOT NULL, PRIMARY KEY(id)) WITHOUT OIDS" % self._table)
+                cr.execute('CREATE TABLE "%s" (id SERIAL NOT NULL, PRIMARY KEY(id)) WITHOUT OIDS' % (self._table,))
                 cr.execute("COMMENT ON TABLE \"%s\" IS '%s'" % (self._table, self._description.replace("'","''")))
                 create = True
             cr.commit()
@@ -2357,7 +2361,7 @@ class orm(orm_template):
                                 try:
                                     cr.commit()
                                     cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k))
-                                except Exception, e:
+                                except Exception:
                                     logger.notifyChannel('orm', netsvc.LOG_WARNING, 'WARNING: unable to set column %s of table %s not null !\nTry to re-run: openerp-server.py --update=module\nIf it doesn\'t work, update records and execute manually:\nALTER TABLE %s ALTER COLUMN %s SET NOT NULL' % (k, self._table, self._table, k))
                             cr.commit()
                     elif len(res)==1:
@@ -2428,7 +2432,7 @@ class orm(orm_template):
                                 try:
                                     cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k))
                                     cr.commit()
-                                except Exception, e:
+                                except Exception:
                                     logger.notifyChannel('orm', netsvc.LOG_WARNING, 'unable to set a NOT NULL constraint on column %s of the %s table !\nIf you want to have it, you should update the records and execute manually:\nALTER TABLE %s ALTER COLUMN %s SET NOT NULL' % (k, self._table, self._table, k))
                                 cr.commit()
                             elif not f.required and f_pg_notnull == 1:
@@ -2482,11 +2486,12 @@ class orm(orm_template):
             conname = '%s_%s' % (self._table, key)
             cr.execute("SELECT conname FROM pg_constraint where conname=%s", (conname,))
             if not cr.dictfetchall():
+                query = 'ALTER TABLE "%s" ADD CONSTRAINT "%s" %s' % (self._table, conname, con,)
                 try:
-                    cr.execute('alter table "%s" add constraint "%s_%s" %s' % (self._table, self._table, key, con,))
+                    cr.execute(query)
                     cr.commit()
                 except:
-                    logger.notifyChannel('orm', netsvc.LOG_WARNING, 'unable to add \'%s\' constraint on table %s !\n If you want to have it, you should update the records and execute manually:\nALTER table %s ADD CONSTRAINT %s_%s %s' % (con, self._table, self._table, self._table, key, con,))
+                    logger.notifyChannel('orm', netsvc.LOG_WARNING, 'unable to add \'%s\' constraint on table %s !\n If you want to have it, you should update the records and execute manually:\n%s' % (con, self._table, query))
                     cr.rollback()
 
         if create:
@@ -2717,7 +2722,7 @@ class orm(orm_template):
             return getattr(proxy, name)(cr, uid, lst, *args, **kwargs)
 
         return _proxy
-        
+
 
     def fields_get(self, cr, user, fields=None, context=None):
         """
@@ -2823,18 +2828,19 @@ class orm(orm_template):
                 return '"%s"' % (f,)
             fields_pre2 = map(convert_field, fields_pre)
             order_by = self._parent_order or self._order
+            select_fields = ','.join(fields_pre2 + ['id'])
+            query = 'SELECT %s FROM "%s" WHERE id in %%s' % (select_fields, self._table)
+            if d1:
+                query += " AND " + d1
+            query += " ORDER BY " + order_by
             for sub_ids in cr.split_for_in_conditions(ids):
                 if d1:
-                    cr.execute('SELECT %s FROM %s WHERE %s.id IN %%s AND %s ORDER BY %s' % \
-                            (','.join(fields_pre2 + [self._table + '.id']), ','.join(tables), self._table, ' and '.join(d1),
-                                order_by),[sub_ids,]+d2)
+                    cr.execute(query, [tuple(sub_ids)] + d2)
                     if cr.rowcount != len(sub_ids):
                         raise except_orm(_('AccessError'),
                                 _('You try to bypass an access rule while reading (Document type: %s).') % self._description)
                 else:
-                    cr.execute('SELECT %s FROM \"%s\" WHERE id IN %%s ORDER BY %s' %
-                               (','.join(fields_pre2 + ['id']), self._table,
-                                order_by), (sub_ids,))
+                    cr.execute(query, (tuple(sub_ids),))
                 res.extend(cr.dictfetchall())
         else:
             res = map(lambda x: {'id': x}, ids)
@@ -2921,7 +2927,7 @@ class orm(orm_template):
                     for group in groups:
                         module = group.split(".")[0]
                         grp = group.split(".")[1]
-                        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" % \
+                        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"  \
                                    (grp, module, 'res.groups', user))
                         readonly = cr.fetchall()
                         if readonly[0][0] >= 1:
@@ -2967,13 +2973,14 @@ class orm(orm_template):
         if not ids:
             return []
         fields = ''
+        uniq = isinstance(ids, (int, long))
+        if uniq:
+            ids = [ids]
+        fields = 'id'
         if self._log_access:
-            fields = ', u.create_uid, u.create_date, u.write_uid, u.write_date'
-        if isinstance(ids, (int, long)):
-            ids_str = str(ids)
-        else:
-            ids_str = string.join(map(lambda x: str(x), ids), ',')
-        cr.execute('select u.id'+fields+' from "'+self._table+'" u where u.id in ('+ids_str+')')
+            fields += ', create_uid, create_date, write_uid, write_date'
+        query = 'SELECT %s FROM "%s" WHERE id in %%s' % (fields, self._table)
+        cr.execute(query, (tuple(ids),))
         res = cr.dictfetchall()
         for r in res:
             for key in r:
@@ -2981,8 +2988,8 @@ class orm(orm_template):
                 if key in ('write_uid', 'create_uid', 'uid') and details:
                     if r[key]:
                         r[key] = self.pool.get('res.users').name_get(cr, user, [r[key]])[0]
-        if isinstance(ids, (int, long)):
-            return res[ids]
+        if uniq:
+            return res[ids[0]]
         return res
 
     def _check_concurrency(self, cr, ids, context):
@@ -3058,11 +3065,6 @@ class orm(orm_template):
         for oid in ids:
             wf_service.trg_delete(uid, self._name, oid, cr)
 
-        #cr.execute('select * from '+self._table+' where id in ('+str_d+')', ids)
-        #res = cr.dictfetchall()
-        #for key in self._inherits:
-        #   ids2 = [x[self._inherits[key]] for x in res]
-        #   self.pool.get(key).unlink(cr, uid, ids2)
 
         self.check_access_rule(cr, uid, ids, 'unlink', context=context)
         for sub_ids in cr.split_for_in_conditions(ids):
@@ -3071,7 +3073,7 @@ class orm(orm_template):
         for order, object, store_ids, fields in result_store:
             if object != self._name:
                 obj =  self.pool.get(object)
-                cr.execute('select id from '+obj._table+' where id in ('+','.join(map(str, store_ids))+')')
+                cr.execute('select id from '+obj._table+' where id in %s',(tuple(store_ids),))
                 rids = map(lambda x: x[0], cr.fetchall())
                 if rids:
                     obj._store_set_values(cr, uid, rids, fields, context)
@@ -3121,7 +3123,7 @@ class orm(orm_template):
                 for group in groups:
                     module = group.split(".")[0]
                     grp = group.split(".")[1]
-                    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" % \
+                    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" \
                                (grp, module, 'res.groups', user))
                     readonly = cr.fetchall()
                     if readonly[0][0] >= 1:
@@ -3942,13 +3944,12 @@ class orm(orm_template):
         if not parent:
             parent = self._parent_name
         ids_parent = ids[:]
-        while len(ids_parent):
+        query = 'SELECT distinct "%s" FROM "%s" WHERE id IN %%s' % (parent, self._table)
+        while ids_parent:
             ids_parent2 = []
             for i in range(0, len(ids), cr.IN_MAX):
                 sub_ids_parent = ids_parent[i:i+cr.IN_MAX]
-                cr.execute('SELECT distinct "'+parent+'"'+
-                    ' FROM "'+self._table+'" ' \
-                    'WHERE id = ANY(%s)',(sub_ids_parent,))
+                cr.execute(query, (tuple(sub_ids_parent),))
                 ids_parent2.extend(filter(None, map(lambda x: x[0], cr.fetchall())))
             ids_parent = ids_parent2
             for i in ids_parent:
index 89f3f72..9b246e5 100644 (file)
@@ -982,14 +982,15 @@ def get_user_companies(cr, user):
     def _get_company_children(cr, ids):
         if not ids:
             return []
-        cr.execute('SELECT id FROM res_company WHERE parent_id = ANY (%s)', (ids,))
-        res=[x[0] for x in cr.fetchall()]
+        cr.execute('SELECT id FROM res_company WHERE parent_id IN %s', (tuple(ids),))
+        res = [x[0] for x in cr.fetchall()]
         res.extend(_get_company_children(cr, res))
         return res
-    cr.execute('SELECT comp.id FROM res_company AS comp, res_users AS u WHERE u.id = %s AND comp.id = u.company_id', (user,))
-    compids=[cr.fetchone()[0]]
-    compids.extend(_get_company_children(cr, compids))
-    return compids
+    cr.execute('SELECT company_id FROM res_users WHERE id=%s', (user,))
+    user_comp = cr.fetchone()[0]
+    if not user_comp:
+        return []
+    return [user_comp] + _get_company_children(cr, [user_comp])
 
 def mod10r(number):
     """
index 9277bf6..8874b8b 100644 (file)
@@ -446,9 +446,10 @@ def trans_generate(lang, modules, dbname=None):
     query_param = None
     if 'all_installed' in modules:
         query += ' WHERE module IN ( SELECT name FROM ir_module_module WHERE state = \'installed\') '
-    elif not 'all' in modules:
-        query += ' WHERE module IN (%s)' % ','.join(['%s']*len(modules))
-        query_param = modules
+    query_param = None
+    if 'all' not in modules:
+        query += ' WHERE module IN %s'
+        query_param = (tuple(modules),)
     query += ' ORDER BY module, model, name'
 
     cr.execute(query, query_param)