| | 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) |
|---|