Ticket #9633: 9633-adaptor-query-params-sqlite3.diff

File 9633-adaptor-query-params-sqlite3.diff, 2.6 KB (added by mdh, 6 years ago)

A first patch to support adaptor objects as query parameters with sqlite3

  • django/db/backends/sqlite3/base.py

     
    1010from django.db.backends.sqlite3.client import DatabaseClient
    1111from django.db.backends.sqlite3.creation import DatabaseCreation
    1212from django.db.backends.sqlite3.introspection import DatabaseIntrospection
     13from django.utils.encoding import force_unicode
    1314
    1415try:
    1516    try:
     
    165166    """
    166167    def execute(self, query, params=()):
    167168        query = self.convert_query(query, len(params))
    168         return Database.Cursor.execute(self, query, params)
     169        new_params = [self.convert_param(p) for p in params]
     170        return Database.Cursor.execute(self, query, new_params)
    169171
    170172    def executemany(self, query, param_list):
    171173        try:
    172174          query = self.convert_query(query, len(param_list[0]))
    173           return Database.Cursor.executemany(self, query, param_list)
     175          new_param_list = [[self.convert_param(p) for p in params] for params in param_list]
     176          return Database.Cursor.executemany(self, query, new_param_list)
    174177        except (IndexError,TypeError):
    175178          # No parameter list provided
    176179          return None
     
    178181    def convert_query(self, query, num_params):
    179182        return query % tuple("?" * num_params)
    180183
     184    def convert_param(self, param):
     185        # These are the types that sqlite3 can handle directly
     186        if param is None or type(param) in (int,long,float,str,unicode,buffer,bool):
     187            return param
     188        # The rest we must convert to unicode first
     189        return force_unicode(param)
     190
    181191def _sqlite_extract(lookup_type, dt):
    182192    if dt is None:
    183193        return None
  • tests/regressiontests/backends/models.py

     
    1515    def __unicode__(self):
    1616        return u'%s %s' % (self.first_name, self.last_name)
    1717
     18class Adaptor(object):
     19    def __init__(self, value):
     20        self.value = value
     21
     22    def __str__(self):
     23        return self.value
     24
    1825qn = connection.ops.quote_name
    1926
    2027__test__ = {'API_TESTS': """
     
    5663>>> list(cursor.fetchall())
    5764[(u'Mary', u'Agnelline'), (u'Peter', u'Parker')]
    5865
     66#9633: Using adaptor objects as query parameters with sqlite3
     67>>> query = 'SELECT %s'
     68>>> param = Adaptor(u'Arthur')
     69>>> foo = cursor.execute(query, (param,))
     70>>> cursor.fetchone()
     71(u'Arthur',)
    5972"""}
Back to Top