I'm using SQLAlchemy for a project, and need to be able to specify a session variable/setting for one specific call for performance reasons:
set session max_heap_table_size = 1024 * 1024 * 64;
I can of course do this in MySQL directly (on the shell), but how do I set this session variable in a SQLAlchemy session?
The sessionmaker factory generates new Session objects when called, creating them given the configurational arguments established here.
Session in SQLAlchemy ORM However, to standardize how sessions are configured and acquired, the sessionmaker class is normally used to create a top-level Session configuration which can then be used throughout an application without the need to repeat the configurational arguments.
Return the first result of this Query or None if the result doesn't contain any row. first() applies a limit of one within the generated SQL, so that only one primary entity row is generated on the server side (note this may consist of multiple result rows if join-loaded collections are present).
session. flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction.
Use a session event to execute an arbitrary SQL statement on each new transaction. You can also use events on the connection level, it depends on your use case.
Here is how I would do it on the session level:
Session = sessionmaker()
@event.listens_for(Session, 'before_flush')
def set_max_heap_table_size(session, transaction, connection):
session.execute('SET max_heap_table_size = 1024 * 1024 * 64')
If you are unsure which way works for you, just try them, write some test cases and find out if that works for you.
There may be one caveat (unsure): Since the connection is not dropped but returned to the pool, the setting might persist. In this case you might also want to attach something to restore the default, e.g. on the after_flush
event. I am not entirely sure on this one, you might want to experiment. If this is unnecessary, you could also use the after_begin
event, but there is no real before_close
event that wraps it, so it could create issues.
I finally ended up doing this to get it working:
Session = sessionmaker()
...
session.connection().execute('SET max_heap_table_size = 1024 * 1024 * 64');
The SQLAlchemy event didn't seem to work, but then again, its possible I wasn't doing it exactly right.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With