Skip to content

Use existing session where possible#4552

Merged
kitsuta merged 2 commits intomainfrom
no-new-sessions
Mar 17, 2026
Merged

Use existing session where possible#4552
kitsuta merged 2 commits intomainfrom
no-new-sessions

Conversation

@kitsuta
Copy link
Copy Markdown
Member

@kitsuta kitsuta commented Mar 17, 2026

This is a redux of #4549 with a slightly different approach: instead of always returning a 'nested' session (it's not actually nested -- more on that below), we just return the current session unless a flag is passed to specifically enable nesting. We add this flag to the few cases where a rollback is used in a with Session() as session block.

True nested sessions are no longer supported in SQLAlchemy. Instead, when you run session.begin_nested, the session is flushed to the database along with the SAVEPOINT command. This allows you to run session.rollback() to go back to the savepoint.

The problem is, we inspect session state for objects -- particularly via the is_new property. Since running session.begin_nested flushes the current session, is_new returns False for any objects that were pending when you made a 'nested' session. We don't want that in most cases, so we want to use nested sessions sparingly.

kitsuta added 2 commits March 17, 2026 17:14
This is a redux of #4549 with a slightly different approach: instead of always returning a 'nested' session (it's not actually nested -- more on that below), we just return the current session unless a flag is passed to specifically enable nesting. We add this flag to the few cases where a rollback is used in a `with Session() as session` block.

True nested sessions are no longer supported in SQLAlchemy. Instead, when you run `session.begin_nested`, the session is flushed to the database along with the SAVEPOINT command. This allows you to run session.rollback() to go back to the savepoint.

The problem is, we inspect session state for objects -- particularly via the `is_new` property. Since running session.begin_nested flushes the current session, `is_new` returns False for any objects that were pending when you made a 'nested' session. We don't want that in most cases, so we want to use nested sessions sparingly.
@kitsuta kitsuta merged commit 6875411 into main Mar 17, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant