Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"set session" in a SQLAlchemy session object

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?

like image 248
Suman Avatar asked Aug 23 '13 18:08

Suman


People also ask

What function creates a Session object in SQLAlchemy?

The sessionmaker factory generates new Session objects when called, creating them given the configurational arguments established here.

What is Sessionmaker in SQLAlchemy?

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.

What does First () do in SQLAlchemy?

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).

What is Session flush in SQLAlchemy?

session. flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction.


2 Answers

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.

like image 65
javex Avatar answered Sep 24 '22 05:09

javex


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.

like image 31
Suman Avatar answered Sep 26 '22 05:09

Suman