-
Notifications
You must be signed in to change notification settings - Fork 0
Implement Context-based Transactional Session Management #10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
…rations - Introduced `SessionContextHolder` to manage SQLAlchemy sessions using context variables. - Added `Transactional` decorator to ensure session commits and rollbacks during CRUD operations. - Refactored `CrudRepository` methods to utilize the new session management, enhancing code clarity and reducing session handling boilerplate. - Updated tests to reflect changes in the repository methods, ensuring proper functionality without session parameters.
…Management - Updated CRUD methods in `PySpringModelRestService` and `CrudRepositoryImplementationService` to use `SessionContextHolder` for session handling, replacing the previous context manager approach. - Added `@Transactional` decorator to relevant methods to ensure proper transaction management. - Enhanced error handling in the `Transactional` decorator to raise specific exceptions. - Updated tests to clear session state before and after tests to maintain isolation and prevent side effects.
…iguration for clarity
- Implement outermost transaction detection using SessionContextHolder.has_session() - Session lifecycle (commit/rollback/close) only managed by outermost @transactional - Nested @transactional methods reuse existing session without interference - Prevent premature session closure in nested transaction scenarios - Maintain transaction integrity across multiple decorated method calls
…` for improving readability.
… session management
- Removed commented-out explanations for clarity. - Streamlined the docstring to focus on the transaction behavior of the decorator.
- Added TransactionalDepth enum to define transaction levels. - Enhanced SessionContextHolder with methods to manage session depth. - Updated @transactional decorator to utilize session depth for commit/rollback operations. - Introduced tests for session depth tracking and behavior in nested transactions.
- Changed the condition for clearing the session from checking if the depth is 0 to using TransactionalDepth.ON_EXIT.value for better clarity and alignment with transaction management.
…ved transaction management - Added @transactional decorator to multiple CRUD methods in CrudRepository to ensure proper transaction handling. - Updated commit logic in PySpringSession to warn against committing managed transactions. - Refactored clone method in PySpringModel to return the correct type. - Improved logging during session commit in PySpringModel for better clarity. - Introduced a method in SessionContextHolder to check if a transaction is managed.
- Introduced TypeVar for PySpringModel to improve type hinting in the clone method. - Updated the clone method signature to return the correct type, enhancing clarity and type safety.
…and session context
- Introduced __version__ attribute to specify the current version of the package. - Updated __all__ to include Query for better module accessibility.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
🚀 Implement Context-based Transactional Session Management with Depth Tracking
📋 Overview
This PR introduces a robust, nested-safe transactional session management system for PySpringModel with explicit session depth tracking. The implementation replaces manual session handling with a context-aware approach that automatically manages database sessions and transactions across the entire application stack, ensuring proper transaction boundaries through depth monitoring.
🎯 Problem Statement
Previously, the codebase had several session management issues:
with
blockscreate_session()
andcreate_managed_session()
usage🛠️ Solution
Implemented a Context Variable-based Session Management system with explicit depth tracking featuring the following components:
🔧 Core Components
1. SessionContextHolder with Depth Tracking (
py_spring_model/core/session_context_holder.py
)contextvars
_session_depth
ContextVarget_or_create_session()
,has_session()
, andclear_session()
methodsget_session_depth()
: Returns current nesting levelenter_session()
: Increments depth and returns new levelexit_session()
: Decrements depth and cleans up session at level 02. @transactional Decorator with Depth Awareness
@Transactional
methods reuse the outer transaction's session3. TransactionalDepth Enum
4. Session Middleware (
py_spring_model/py_spring_model_rest/controller/session_controller.py
)🔄 Key Changes
Repository Layer (
py_spring_model/repository/crud_repository.py
)with self.create_managed_session()
SessionContextHolder.get_or_create_session()
and@Transactional
decoratorService Layer (
py_spring_model/py_spring_model_rest/service/
)@Transactional
decoratorwith PySpringModel.create_session()
patternsModule Exports (
py_spring_model/__init__.py
)SessionContextHolder
to public API for depth management accessSessionController
to REST controller registration🎁 Benefits
🔒 Transaction Safety with Depth Control
🎯 Smart Nested Transaction Support
📊 Depth-Aware Transaction Monitoring
🧹 Automatic Resource Management
with session
blocks needed🚀 Performance Improvements
🧪 Testing Updates
Core Session Depth Tests (
tests/test_session_depth.py
)Enhanced Transactional Tests (
tests/test_transactional_decorator.py
)Repository & Service Tests
tests/test_crud_repository.py
tests/test_crud_repository_implementation_service.py
tests/test_query_modifying_operations.py
🔄 Migration Guide
For Application Code:
For Repository Usage:
For Debugging Transaction Hierarchy:
session
parameterswith session
blocks may need updates🔍 Backwards Compatibility
save()
,find_by_id()
, etc.)SessionContextHolder
🧪 How to Test
📚 Usage Examples
Simple Transaction
Complex Nested Transactions
Depth-Aware Error Handling
🔧 Session Depth Architecture
Depth Management Flow
Session Lifecycle with Depth
This implementation provides a solid foundation for reliable, performant database transaction management with intelligent depth tracking, ensuring proper transaction boundaries while maintaining clean, readable code patterns. The explicit depth management eliminates guesswork about transaction hierarchy and provides robust nested transaction support. 🎉