SQLAlchemy utilizes connection pooling. This means that the same connection can be reused across different SQLAlchemy Sessions. However, a single SQLAlchemy session is contained within itself and discarded after closing. The connection however, stays 'active'.
I want to save something into the database session storage in Postgresql, using set_config:
PERFORM set_config('session.storage', 'remember-me-across-this-session', false)
Now, this is in scope of a database session. My question is: When SQLAlchemy creates a new SQLAlchemy Session using the same connection, does this also create a new database session, or will the connection re-use the same database session across it's lifetime?
Note: I have tried to test this already by setting all the relevant pool sizes to minimum (max_overflow 0, pool_size 1, pool_recycle 600) and then running the following script (simplified):
print(DBSESSION.execute(text("SELECT set_config('session.storage', 'remember-me-across-this-session', false)")).first())
print(DBSESSION.execute(text("SELECT current_setting('session.storage')")).first())
transaction.commit()
DBSESSION.close()
for _ in range(5):
print(DBSESSION.execute(text("SELECT current_setting('session.storage')")).first())
transaction.commit()
DBSESSION.close()
This test did not "remember" the value set in the first line across the following sessions in the loop, thus confirming that the database session does get reset between SQLAlchemy sessions across the same connection. However because this is a critical part of the logic, I'd love a second opinion / affirmation to make sure I didn't screw up.