summaryrefslogtreecommitdiff
path: root/psycopg/utils.c
diff options
context:
space:
mode:
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>2016-12-26 12:06:21 +0100
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>2016-12-26 12:06:21 +0100
commit7caba160b7083c64197329e17d0d0e0eb17c8639 (patch)
tree9c7a8221ccdbbf3efdbac0ccd49287cc90647a6f /psycopg/utils.c
parent121cf3b8f8426765d983579d3a4b2e932429cd9f (diff)
parente9577e9b890fd9a27bb146e8ea1c24eb562f28b2 (diff)
downloadpsycopg2-7caba160b7083c64197329e17d0d0e0eb17c8639.tar.gz
Merge branch 'master' into fast-codecs
Diffstat (limited to 'psycopg/utils.c')
-rw-r--r--psycopg/utils.c41
1 files changed, 19 insertions, 22 deletions
diff --git a/psycopg/utils.c b/psycopg/utils.c
index 631b839..bc6f7be 100644
--- a/psycopg/utils.c
+++ b/psycopg/utils.c
@@ -90,43 +90,40 @@ psycopg_escape_string(connectionObject *conn, const char *from, Py_ssize_t len,
return to;
}
-/* Escape a string to build a valid PostgreSQL identifier.
+/* Escape a string for inclusion in a query as identifier.
*
- * Allocate a new buffer on the Python heap containing the new string.
* 'len' is optional: if 0 the length is calculated.
*
- * The returned string doesn't include quotes.
- *
- * WARNING: this function is not so safe to allow untrusted input: it does no
- * check for multibyte chars. Such a function should be built on
- * PQescapeIdentifier, which is only available from PostgreSQL 9.0.
+ * Return a string allocated by Postgres: free it using PQfreemem
+ * In case of error set a Python exception.
*/
char *
-psycopg_escape_identifier_easy(const char *from, Py_ssize_t len)
+psycopg_escape_identifier(connectionObject *conn, const char *str, size_t len)
{
- char *rv;
- const char *src;
- char *dst;
+ char *rv = NULL;
- if (!len) { len = strlen(from); }
- if (!(rv = PyMem_New(char, 1 + 2 * len))) {
- PyErr_NoMemory();
- return NULL;
+ if (!conn || !conn->pgconn) {
+ PyErr_SetString(InterfaceError, "connection not valid");
+ goto exit;
}
- /* The only thing to do is double quotes */
- for (src = from, dst = rv; *src; ++src, ++dst) {
- *dst = *src;
- if ('"' == *src) {
- *++dst = '"';
+ if (!len) { len = strlen(str); }
+
+ rv = PQescapeIdentifier(conn->pgconn, str, len);
+ if (!rv) {
+ char *msg;
+ msg = PQerrorMessage(conn->pgconn);
+ if (!msg || !msg[0]) {
+ msg = "no message provided";
}
+ PyErr_Format(InterfaceError, "failed to escape identifier: %s", msg);
}
- *dst = '\0';
-
+exit:
return rv;
}
+
/* Duplicate a string.
*
* Allocate a new buffer on the Python heap containing the new string.