Is it possible to inject parameters values into already compiled statement without recompiling?

20 views
Skip to first unread message

Andrei Pashkin

unread,
Jan 21, 2020, 6:39:39 AM1/21/20
to sqlalchemy
Let's suppose I have a compiled SA expression statement which I want to cache to avoid repetitive compilation. Let's also suppose that I can't use "literal_binds" because I want to provide parameter values late, after getting the compiled query from the cache. 

Is it somehow possible to inject values into compiled query without executing it?

Here is a full example:

Mike Bayer

unread,
Jan 21, 2020, 10:33:39 AM1/21/20
to noreply-spamdigest via sqlalchemy
When you execute a compiled statement using Core there is always a dictionary of parameters you pass along.    Whatever parameters you put here take precedence.    in your example you're using bindparam() directly, so this is the easiest case, just pass "id":

def my_cached_thing():
    cache = {}
    stmt = sa.select([User.__table__]).where(User.__table__.c.id == sa.bindparam('id'))
    def go(engine, id):
        with engine.connect() as conn:
            return conn.execution_options(compiled_cache=cache).execute(stmt, id=id)
    return go


# in your code
cached_lookup = my_cached_thing()

for id in [1, 10, 15, 27, 19, 38]:
    result = cached_lookup(engine, id)   # will only compile the statement once
    # ... etc

The above thing I did with the nested function etc. is arbitrary, just the main point is, same statement object and same cache dictionary.     as stated before, 1.4 will hopefully have an improvement to make all of this transparent.
 
Also note you can use Core select() constructs etc with the ORM classes directly:

select([User]).where(User.id == bindparam('id'))






--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
 
 
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.

Andrei Pashkin

unread,
Jan 21, 2020, 1:35:09 PM1/21/20
to sqlalchemy
Yes, you are right, thank you, Mike.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlal...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages