Changeset 2712

Show
Ignore:
Timestamp:
01/17/07 20:41:49 (2 years ago)
Author:
carl
Message:

parameterized the SQL commands.
pyformat is the default.
if the back end uses something else, override in the backend class.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • branches/carl2/dabo/db/dBackend.py

    r2679 r2712  
    3838            self._encoding = dabo.defaultEncoding 
    3939 
     40        self.emptyParamValues = {} 
     41 
     42    def mkMarker(self, key): 
     43        return '%('+key+')s' 
     44 
     45    def addParam(self, paramList, key, value): 
     46        paramList[key] = value 
     47        return paramList 
    4048 
    4149    def isValidModule(self): 
     
    268276            exp = "%(exp)s as %(alias)s" % locals() 
    269277        indent = len("select ") * " " 
    270         # Give the backend-specific code a chance to update the format 
    271         exp = self.processFields(exp) 
    272278        return self.addWithSep(clause, exp, sep=",\n%s" % indent) 
    273279 
    274      
     280 
    275281    def addFrom(self, clause, exp): 
    276282        """ Add a table to the sql statement.""" 
     
    283289        """ Add an expression to the where clause.""" 
    284290        indent = (len("select ") - len(comp)) * " " 
    285         exp = self.processFields(exp) 
    286291        return self.addWithSep(clause, exp, sep="\n%s%s " % (indent, comp)) 
    287292 
  • branches/carl2/dabo/db/dCursorMixin.py

    r2681 r2712  
    3939        ##      which we are mixed-in will take the __init__. 
    4040        dObject.__init__(self, *args, **kwargs) 
    41          
     41 
    4242        # Just in case this is used outside of the context of a bizobj 
    4343        if not hasattr(self, "superCursor") or self.superCursor is None: 
     
    218218        #### NOTE: NEEDS TO BE TESTED THOROUGHLY!!!!  #### 
    219219 
    220        # Some backends, notably Firebird, require that fields be specially marked. 
     220    # Some backends, notably Firebird, require that fields be specially marked. 
    221221        if not isinstance(sql, unicode): 
    222222            sql = unicode(sql, self.Encoding) 
     
    234234                res = self.superCursor.execute(self, sqlEX) 
    235235            else: 
    236                 res = self.superCursor.execute(self, sqlEX, params) 
     236                   res = self.superCursor.execute(self, sqlEX, params) 
    237237        except Exception, e: 
    238238            # If this is due to a broken connection, let the user know. 
     
    10301030        if useTransaction: 
    10311031            self.commitTransaction() 
    1032  
    1033  
     1032     
    10341033    def __saverow(self, row): 
    10351034        rec = self._records[row] 
     
    10381037        if diff or newrec: 
    10391038            if newrec: 
    1040                 flds = "" 
    1041                 vals = "" 
     1039                 
     1040                flds = []  ## list of field names 
     1041                markers = [] ## list of markers  
     1042                params = self.BackendObject.emptyParamValues   ## list of parameters 
     1043 
    10421044                kf = self.KeyField 
    10431045                for kk, vv in diff.items(): 
     
    10531055                        # Skip it. 
    10541056                        continue 
    1055                     # Append the field and its value. 
    1056                     flds += ", " + self.BackendObject.encloseSpaces(kk) 
    1057                     # add value to expression 
    1058                     vals += ", %s" % (self.formatForQuery(vv[1]),) 
     1057                    # Append the field, a marker and its value. 
     1058                    fieldName = self.BackendObject.encloseSpaces(kk) 
     1059                    flds.append( fieldName ) 
     1060                    markers.append( self.BackendObject.mkMarker(fieldName) ) 
     1061                    params = self.BackendObject.addParam( params, fieldName, vv[1] ) 
    10591062                     
    1060                 # Trim leading comma-space from the strings 
    1061                 flds = flds[2:] 
    1062                 vals = vals[2:] 
    10631063                if not flds: 
    10641064                    # Some backends (sqlite) require non-empty field clauses. We already 
    10651065                    # know that we are expecting the backend to generate the PK, so send 
    10661066                    # NULL as the PK Value: 
    1067                     flds = self.KeyField 
    1068                     vals = "NULL" 
    1069                 sql = "insert into %s (%s) values (%s) " % ( 
    1070                         self.BackendObject.encloseSpaces(self.Table), flds, vals) 
     1067                    flds = (self.KeyField,) 
     1068                    markers.append( self.BackendObject.mkMarker('KeyField')) 
     1069                    params = self.BackendObject.addParam(params, 'KeyField', None) 
     1070 
     1071                table=self.BackendObject.encloseSpaces(self.Table) 
     1072                fields=', '.join( flds ) 
     1073                markers=', '.join(markers) 
     1074                sql = "insert into %(t)s (%(f)s) values (%(m)s)" \ 
     1075                    % {'t':table, 'f':fields, 'm':markers } 
    10711076 
    10721077            else: 
    1073                 pkWhere = self.makePkWhere(row) 
    1074                 updClause = self.makeUpdClause(diff) 
    1075                 sql = "update %s set %s where %s" % (self.BackendObject.encloseSpaces(self.Table),  
    1076                         updClause, pkWhere) 
     1078                updClause, params = self.makeUpdClause(diff)   
     1079                 
     1080                pkWhere, pkParamsDict = self.makePkWhere(row)   
     1081                for fieldName, value in pkParamsDict.items(): 
     1082                    params = self.BackendObject.addParam(params, fieldName, value ) 
     1083                                 
     1084                table=self.BackendObject.encloseSpaces(self.Table) 
     1085                sql = "update %(table)s set %(sets)s where %(w)s" \ 
     1086                    % {'table':table, 'sets':updClause, 'w':pkWhere } 
     1087 
     1088                # sql = "update %s set %s where %s" % (self.BackendObject.encloseSpaces(self.Table),  
     1089                #       updClause, pkWhere) 
    10771090            oldPKVal = rec[self.KeyField] 
    10781091            newPKVal = None 
     
    10891102            #run the update 
    10901103            aux = self.AuxCursor 
    1091             res = aux.execute(sql
     1104            res = aux.execute(sql,params
    10921105 
    10931106            if newrec and self.AutoPopulatePK and (newPKVal is None): 
     
    12251238            res = True 
    12261239        else: 
    1227             pkWhere = self.makePkWhere() 
     1240            aux = self.AuxCursor 
     1241            table=self.BackendObject.encloseSpaces(self.Table) 
     1242            pkWhere, pkParamsDict = self.makePkWhere()  
     1243            params = self.BackendObject.emptyParamValues 
     1244            for fieldName, value in pkParamsDict.items(): 
     1245                params = self.BackendObject.addParam(params, fieldName, value ) 
     1246             
    12281247            # some backends(PostgreSQL) don't return information about number of deleted rows 
    12291248            # try to fetch it before 
    1230             sql = "select count(*) as cnt from %s where %s" % (self.Table, pkWhere) 
    1231             aux = self.AuxCursor 
    1232             aux.execute(sql
     1249            sql = "select count(*) as cnt from %(table)s where %(w)s" \ 
     1250               % {'table':table, 'w':pkWhere } 
     1251            aux.execute(sql, params
    12331252            res = aux.getFieldVal('cnt') 
    12341253            if res: 
    1235                 sql = "delete from %s where %s" % (self.Table, pkWhere) 
    1236                 aux.execute(sql) 
    1237  
     1254                sql = "delete from %(table)s where %(w)s" \ 
     1255                    % {'table':table, 'w':pkWhere } 
     1256                aux.execute(sql, params) 
    12381257 
    12391258        if not res: 
     
    14701489        return ret 
    14711490 
    1472  
    14731491    def checkPK(self): 
    14741492        """ Verify that the field(s) specified in the KeyField prop exist.""" 
     
    14871505            raise dException.MissingPKException, _("Primary key field does not exist in the data set: ") + fld 
    14881506 
    1489  
    14901507    def makePkWhere(self, row=None): 
    14911508        """ Create the WHERE clause used for updates, based on the pk field.  
     
    15111528                return rec[fld] 
    15121529             
    1513         ret = "" 
     1530        exprs = [] 
     1531        params = {} 
    15141532        for fld in keyFields: 
    15151533            fldSafe = bo.encloseSpaces(fld) 
    1516             if ret: 
    1517                 ret += " AND " 
     1534            marker = bo.mkMarker(fldSafe) 
    15181535            pkVal = getPkVal(fld) 
    1519             if isinstance(pkVal, basestring): 
    1520                 ret += tblPrefix + fldSafe + "='" + pkVal.encode(self.Encoding) + "' " 
    1521             elif isinstance(pkVal, (datetime.date, datetime.datetime)): 
    1522                 ret += tblPrefix + fldSafe + "=" + self.formatDateTime(pkVal) + " " 
    1523             else: 
    1524                 ret += tblPrefix + fldSafe + "=" + str(pkVal) + " " 
    1525         return ret 
    1526  
     1536            exprs.append( tblPrefix + fldSafe + "=" + marker )  
     1537            params[fldSafe]=pkVal 
     1538         
     1539        exprs = " AND ".join(exprs) 
     1540 
     1541        return (exprs,params) 
    15271542 
    15281543    def makeUpdClause(self, diff): 
    15291544        """ Create the 'set field=val' section of the Update statement. """ 
    1530         ret = "" 
    15311545        bo = self.BackendObject 
     1546        sets = [] 
     1547        params = bo.emptyParamValues 
    15321548        tblPrefix = bo.getUpdateTablePrefix(bo.encloseSpaces(self.Table)) 
    15331549        for fld, val in diff.items(): 
     
    15361552            if fld in self.getNonUpdateFields(): 
    15371553                continue 
    1538             if ret: 
    1539                 ret += ", " 
    1540             ret += tblPrefix + bo.encloseSpaces(fld) + " = " + self.formatForQuery(new_val) 
    1541         return ret 
    1542  
     1554            fldSafe = bo.encloseSpaces(fld) 
     1555            marker = bo.mkMarker( fldSafe ) 
     1556            sets.append( tblPrefix + bo.encloseSpaces(fld) + " = " + marker ) 
     1557            params = bo.addParam( params, fldSafe, new_val ) 
     1558        sets = ", ".join(sets) 
     1559        return (sets,params) 
    15431560 
    15441561    def processFields(self, txt): 
     
    19862003    def _setKeyField(self, kf): 
    19872004        if "," in kf: 
     2005        # if True: 
    19882006            flds = [f.strip() for f in kf.split(",")] 
    19892007            self._keyField = tuple(flds) 
  • branches/carl2/dabo/db/dbFirebird.py

    r2679 r2712  
    1616        self.dbapi = kinterbasdb 
    1717 
     18        self.emptyParamValues = () 
     19 
     20    def addParam(self, paramList, key, value): 
     21        paramList = list( paramList) 
     22        paramList.append(value) 
     23        parmList = tuple(paramList) 
     24        marker = '?' 
     25        return (paramList,marker) 
    1826 
    1927    def getConnection(self, connectInfo): 
     
    3139        return self._connection 
    3240         
    33          
    3441    def getDictCursorClass(self): 
    3542        return self.dbapi.Cursor 
    36          
    3743     
    3844    def noResultsOnSave(self): 
  • branches/carl2/dabo/db/dbSQLite.py

    r2681 r2712  
    1414            import sqlite3 as dbapi 
    1515        self.dbapi = dbapi 
    16          
     16 
     17        self.emptyParamValues = {} 
     18 
     19    def mkMarker(self, key): 
     20        return ':'+key 
     21 
     22    def addParam(self, paramList, key, value): 
     23        paramList[key] = value 
     24        return paramList 
    1725 
    1826    def getConnection(self, connectInfo):