Django

Code

Changeset 4244

Show
Ignore:
Timestamp:
12/26/06 23:14:02 (2 years ago)
Author:
adrian
Message:

Fixed #3115 -- Changed postgresql backend to convert all Unicode strings to bytestrings according to DEFAULT_CHARSET. This is necessary because psycopg1 does not apply database quoting to Unicode strings

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/django/db/backends/postgresql/base.py

    r4215 r4244  
    2020    # Import copy of _thread_local.py from Python 2.4 
    2121    from django.utils._threading_local import local 
     22 
     23def smart_basestring(s, charset): 
     24    if isinstance(s, unicode): 
     25        return s.encode(charset) 
     26    return s 
     27 
     28class UnicodeCursorWrapper(object): 
     29    """ 
     30    A thin wrapper around psycopg cursors that allows them to accept Unicode 
     31    strings as params. 
     32 
     33    This is necessary because psycopg doesn't apply any DB quoting to 
     34    parameters that are Unicode strings. If a param is Unicode, this will 
     35    convert it to a bytestring using DEFAULT_CHARSET before passing it to 
     36    psycopg. 
     37    """ 
     38    def __init__(self, cursor, charset): 
     39        self.cursor = cursor 
     40        self.charset = charset 
     41 
     42    def execute(self, sql, params=()): 
     43        return self.cursor.execute(sql, [smart_basestring(p, self.charset) for p in params]) 
     44 
     45    def executemany(self, sql, param_list): 
     46        new_param_list = [[smart_basestring(p, self.charset) for p in params] for params in param_list] 
     47        return self.cursor.executemany(sql, new_param_list) 
     48 
     49    def __getattr__(self, attr): 
     50        if self.__dict__.has_key(attr): 
     51            return self.__dict__[attr] 
     52        else: 
     53            return getattr(self.cursor, attr) 
    2254 
    2355class DatabaseWrapper(local): 
     
    4678        cursor = self.connection.cursor() 
    4779        cursor.execute("SET TIME ZONE %s", [settings.TIME_ZONE]) 
     80        cursor = UnicodeCursorWrapper(cursor, settings.DEFAULT_CHARSET) 
    4881        if settings.DEBUG: 
    4982            return util.CursorDebugWrapper(cursor, self)