Don't leak session vars back to connection pool on tx commit/rollback #4468
+13
−2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Currently, the sql driver correctly handles resetting session vars when non in transactional mode by providing a cleanup function that wraps the
Close()on the connection so that the sql vars are reset on the connection when it is returned to the pool.However, in transaction mode, no cleanup function is returned, which means that when
Commit()orRollback()is called on theent.Txand the connection is returned to the pool, set sql vars persist and leak so that the next user of that pooled connection will still see those sql vars set.Since many applications (and the guide here suggests: https://entgo.io/docs/migration/row-level-security/) use sql vars to implement RLS, it seems like a footgun that these vars persist. If this is expected, maybe the docs should be updated to indicate that users are responsible for clearing their own sql vars when using transactions?
For transactions this is complicated by the fact that each statement within a transaction may set different sql vars, so it is difficult to track which sql vars to reset without storing every sql var name every set for that transaction. Using
SET LOCALin PostgreSQL offloads that responsibility to PostgreSQL, since that ensure that these will be cleared when the transaction rolls back / commits. However this only works in PostgreSQLThis is one possible fix for this, another might be returning a cleanup function even in transaction context so that sql vars are reset after every statement even in a transaction (results in some extra round-trips to the server but only if sql vars were used). This would have the advantage of working in MySQL