title: Compile query from raw string (without using .text(...)) using Sqlalchemy connection and Postgres
body: <p>I am using Sqlalchemy 1.3 to connect to a PostgreSQL 9.6 database (through Psycopg).</p>
  
  <p>I have a very, <em>very</em> raw Sql string formatted using <a href="http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries" rel="nofollow noreferrer">Psycopg2</a> syntax which I can not modify because of some legacy issues:</p>
  
  <p><code>statement_str = SELECT * FROM users WHERE user_id=%(user_id)s</code></p>
  
  <p>Notice the <code>%(user_id)s</code></p>
  
  <p>I can happily execute that using a sqlalchemy connection just by doing:</p>
  
  <pre><code>connection = sqlalch_engine.connect()
  rows = conn.execute(statement_str, user_id=self.user_id)
  </code></pre>
  
  <p>And it works fine. I get my user and all is nice and good.</p>
  
  <p>Now, for debugging purposes I'd like to get the actual query with the <code>%(user_id)s</code> argument expanded to the actual value. For instance: If <code>user_id = "foo"</code>, then get <code>SELECT * FROM users WHERE user_id = 'foo'</code></p>
  
  <p>I've seen tons of examples using <a href="https://docs.sqlalchemy.org/en/13/core/tutorial.html#using-text-fragments-inside-bigger-statements" rel="nofollow noreferrer"><code>sqlalchemy.text(...)</code></a> to produce a statement and then get a compiled version. I have that thanks to other answers like <a href="https://stackoverflow.com/questions/4617291/how-do-i-get-a-raw-compiled-sql-query-from-a-sqlalchemy-expression">this one</a> or <a href="https://stackoverflow.com/questions/38353653/how-to-get-sqlalchemy-query-object-from-raw-sql-string">this one</a> been able to produce a decent <code>str</code> when I have an SqlAlchemy query.</p>
  
  <p>However, in this particular case, since I'm using a more cursor-specific syntax <code>%(user_id)</code> I can't do that. If I try:</p>
  
  <p><code>text(statement_str).bindparams(user_id="foo")</code> </p>
  
  <p>I get:
  <code>This text() construct doesn't define a bound parameter named 'user_id'</code></p>
  
  <p>So I guess what I'm looking for would be something like</p>
  
  <pre><code>conn.compile(statement_str, user_id=self.user_id)
  </code></pre>
  
  <p>But I haven't been able to get that.</p>