Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

0.91-bufixes: Backport [4244] for those using legacy Django with psyc…

…opg1

git-svn-id: http://code.djangoproject.com/svn/django/branches/0.91-bugfixes@4419 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit d0672a7344ea2eba53073f597f6adbed9023a279 1 parent f931905
James Bennett authored January 24, 2007

Showing 1 changed file with 33 additions and 0 deletions. Show diff stats Hide diff stats

  1. 33  django/core/db/backends/postgresql.py
33  django/core/db/backends/postgresql.py
@@ -16,6 +16,38 @@
16 16
     # Import copy of _thread_local.py from python 2.4
17 17
     from django.utils._threading_local import local
18 18
 
  19
+def smart_basestring(s, charset):
  20
+    if isinstance(s, unicode):
  21
+        return s.encode(charset)
  22
+    return s
  23
+
  24
+class UnicodeCursorWrapper(object):
  25
+    """
  26
+    A thin wrapper around psycopg cursors that allows them to accept Unicode
  27
+    strings as params.
  28
+
  29
+    This is necessary because psycopg doesn't apply any DB quoting to
  30
+    parameters that are Unicode strings. If a param is Unicode, this will
  31
+    convert it to a bytestring using DEFAULT_CHARSET before passing it to
  32
+    psycopg.
  33
+    """
  34
+    def __init__(self, cursor, charset):
  35
+        self.cursor = cursor
  36
+        self.charset = charset
  37
+
  38
+    def execute(self, sql, params=()):
  39
+        return self.cursor.execute(sql, [smart_basestring(p, self.charset) for p in params])
  40
+
  41
+    def executemany(self, sql, param_list):
  42
+        new_param_list = [tuple([smart_basestring(p, self.charset) for p in params]) for params in param_list]
  43
+        return self.cursor.executemany(sql, new_param_list)
  44
+
  45
+    def __getattr__(self, attr):
  46
+        if self.__dict__.has_key(attr):
  47
+            return self.__dict__[attr]
  48
+        else:
  49
+            return getattr(self.cursor, attr)
  50
+
19 51
 class DatabaseWrapper(local):
20 52
     def __init__(self):
21 53
         self.connection = None
@@ -40,6 +72,7 @@ def cursor(self):
40 72
             self.connection.set_isolation_level(1) # make transactions transparent to all cursors
41 73
         cursor = self.connection.cursor()
42 74
         cursor.execute("SET TIME ZONE %s", [TIME_ZONE])
  75
+        cursor = UnicodeCursorWrapper(cursor, settings.DEFAULT_CHARSET)
43 76
         if DEBUG:
44 77
             return base.CursorDebugWrapper(cursor, self)
45 78
         return cursor

0 notes on commit d0672a7

Please sign in to comment.
Something went wrong with that request. Please try again.