| | 22 | |
|---|
| | 23 | def smart_basestring(s, charset): |
|---|
| | 24 | if isinstance(s, unicode): |
|---|
| | 25 | return s.encode(charset) |
|---|
| | 26 | return s |
|---|
| | 27 | |
|---|
| | 28 | class 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) |
|---|