summaryrefslogtreecommitdiff
path: root/psycopg/utils.c
diff options
context:
space:
mode:
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>2011-02-05 15:12:37 +0100
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>2011-02-05 15:12:37 +0100
commitb544354db2603e753dd2e07b80f880001ec4ccae (patch)
tree60bafe0170875cc9796e95774e90e9aff6d98d11 /psycopg/utils.c
parentd40b394c507fb3db49f659c57741cdfe09bb9d39 (diff)
downloadpsycopg2-b544354db2603e753dd2e07b80f880001ec4ccae.tar.gz
COPY sends unicode to a file if it derives from io.TextIoBase
Fixes ticket #36.
Diffstat (limited to 'psycopg/utils.c')
-rw-r--r--psycopg/utils.c40
1 files changed, 40 insertions, 0 deletions
diff --git a/psycopg/utils.c b/psycopg/utils.c
index 539081b..4e5c83e 100644
--- a/psycopg/utils.c
+++ b/psycopg/utils.c
@@ -149,3 +149,43 @@ psycopg_ensure_text(PyObject *obj)
}
#endif
}
+
+/* Check if a file derives from TextIOBase.
+ *
+ * Return 1 if it does, else 0, -1 on errors.
+ */
+int
+psycopg_is_text_file(PyObject *f)
+{
+ /* NULL before any call.
+ * then io.TextIOBase if exists, else None. */
+ static PyObject *base;
+
+ /* Try to import os.TextIOBase */
+ if (NULL == base) {
+ PyObject *m;
+ Dprintf("psycopg_is_text_file: importing io.TextIOBase");
+ if (!(m = PyImport_ImportModule("io"))) {
+ Dprintf("psycopg_is_text_file: io module not found");
+ PyErr_Clear();
+ Py_INCREF(Py_None);
+ base = Py_None;
+ }
+ else {
+ if (!(base = PyObject_GetAttrString(m, "TextIOBase"))) {
+ Dprintf("psycopg_is_text_file: io.TextIOBase not found");
+ PyErr_Clear();
+ Py_INCREF(Py_None);
+ base = Py_None;
+ }
+ }
+ Py_XDECREF(m);
+ }
+
+ if (base != Py_None) {
+ return PyObject_IsInstance(f, base);
+ } else {
+ return 0;
+ }
+}
+