| | 11 | |
|---|
| | 12 | def smart_basestring(s, charset): |
|---|
| | 13 | if isinstance(s, unicode): |
|---|
| | 14 | return s.encode(charset) |
|---|
| | 15 | return s |
|---|
| | 16 | |
|---|
| | 17 | class UnicodeCursorWrapper(object): |
|---|
| | 18 | """ |
|---|
| | 19 | A thin wrapper around psycopg cursors that allows them to accept Unicode |
|---|
| | 20 | strings as params. |
|---|
| | 21 | |
|---|
| | 22 | This is necessary because psycopg doesn't apply any DB quoting to |
|---|
| | 23 | parameters that are Unicode strings. If a param is Unicode, this will |
|---|
| | 24 | convert it to a bytestring using DEFAULT_CHARSET before passing it to |
|---|
| | 25 | psycopg. |
|---|
| | 26 | """ |
|---|
| | 27 | def __init__(self, cursor, charset): |
|---|
| | 28 | self.cursor = cursor |
|---|
| | 29 | self.charset = charset |
|---|
| | 30 | |
|---|
| | 31 | def execute(self, sql, params=()): |
|---|
| | 32 | return self.cursor.execute(sql, [smart_basestring(p, self.charset) for p in params]) |
|---|
| | 33 | |
|---|
| | 34 | def executemany(self, sql, param_list): |
|---|
| | 35 | new_param_list = [tuple([smart_basestring(p, self.charset) for p in params]) for params in param_list] |
|---|
| | 36 | return self.cursor.executemany(sql, new_param_list) |
|---|
| | 37 | |
|---|
| | 38 | def __getattr__(self, attr): |
|---|
| | 39 | if self.__dict__.has_key(attr): |
|---|
| | 40 | return self.__dict__[attr] |
|---|
| | 41 | else: |
|---|
| | 42 | return getattr(self.cursor, attr) |
|---|