Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Expose libpq PQescapeIdentifier #308
How about adding
Proposed ideas (exposed in #358):
Add a "compose" method to the cursor to the object returning a sql statement to pass to execute:
from psycopg2.extensions import Identifier cur.execute( cur.compose( "insert into %(table)s %(field)s values (%%s)", dict(table=Identifier("tbl"), field=Identifier("fld"))), )
Rough ideas are:
All in all we have this pseudostuff:
class Composable: def __init__(self, wrapped): self.wrapped = wrapped def adapt(self, conn_or_cur): raise NotImplementedError class Identifier(Composable): def adapt(self, conn_or_cur): pgconn = get_it_from(conn_or_cur) return libpq.PQescapeIdentifier(pgconn, self.wrapped) # etc for Literal, String, Bytea class cursor: def compose(sql, args): adapted =  # TODO: handle args dict for arg in args: if isinstance(arg, Composable): adapted.append(arg.adapt()) else: # TODO: prepare() etc adapted.append(psycopg2.extensions.adapt(arg).getquoted()) return sql % adapted
@fogzot what do you think?
I'm not very interested in all the compose magic, but one thing I can see is that you still need
That could be a separate patch to just add
@fogzot I wouldn't put every new feature on the cursor, but I think this specific one is better on the cursor than on the connection or as a global function (which would need a connection or cursor anyway), because I assume you want to compose the query close to where you are going to use it and you already have a cursor. Composing a SQL string is not even really the connection task, which is to manage the db connection and the transaction. We just happen to need one to invoke these functions.
@a1exsh no, the above is just pseudocode to say "use the libpq function here". the hack could be used to put together a Python demo, but I don't really think we need it. I'd write the entire feature in C.
If I wanted a quick and dirty
So, to summarize, my preferences for the interface of these quoting functions are in order: