Skip to content

Conversation

@NFUChen
Copy link
Contributor

@NFUChen NFUChen commented Jun 19, 2025

Add Modifiable Query Support with Commit Control

🎯 Overview

This PR introduces fine-grained control over database transaction commits in the PySpringModel query system. The new is_modifying parameter allows developers to specify whether a query operation should automatically commit changes to the database.

🚀 Features Added

1. Enhanced Session Management

  • Modified PySpringModel.create_managed_session() to accept a should_commit parameter
  • Backward compatible: Default behavior remains unchanged (commits by default)
  • Flexible commit control: Can now disable automatic commits when needed

2. Query Decorator Enhancement

  • Added is_modifying parameter to the @Query decorator
  • Default behavior: is_modifying=False (no automatic commit)
  • Explicit control: Set is_modifying=True for operations that should commit (INSERT, UPDATE, DELETE)

3. Service Layer Updates

  • Enhanced QueryExecutionService.execute_query() to handle the modifying flag
  • Proper parameter propagation from decorator to session management
  • Maintains existing functionality while adding new capabilities

📝 Usage Examples

Read-Only Queries (Default)

@Query("SELECT * FROM users WHERE email = {email}") def find_by_email(self, email: str) -> Optional[User]: """Read-only query - no commit needed""" ...

Modifying Queries

@Query("INSERT INTO users (name, email) VALUES ({name}, {email})", is_modifying=True) def create_user(self, name: str, email: str) -> User: """Insert operation - commits changes""" ... @Query("UPDATE users SET name = {name} WHERE id = {id}", is_modifying=True) def update_user_name(self, id: int, name: str) -> User: """Update operation - commits changes""" ...

🔧 Technical Implementation

Core Changes

  1. py_spring_model/core/model.py

    • Added should_commit: bool = True parameter to create_managed_session()
    • Conditional commit logic based on the parameter
    • Maintains backward compatibility
  2. py_spring_model/py_spring_model_rest/service/query_service/query.py

    • Added is_modifying: bool parameter to QueryExecutionService.execute_query()
    • Added is_modifying: bool = False parameter to Query decorator
    • Updated session creation to use create_managed_session(should_commit=is_modifying)

Session Management Flow

@Query(sql, is_modifying=True) ↓ QueryExecutionService.execute_query(..., is_modifying=True) ↓ PySpringModel.create_managed_session(should_commit=True) ↓ Automatic commit on context exit 

🧪 Testing

Comprehensive Test Suite Added

  • Unit tests for both commit and no-commit scenarios
  • Integration tests with real database operations
  • Mock testing to verify session behavior
  • Parameter propagation verification

Test Coverage

  • ✅ INSERT operations with/without commit
  • ✅ UPDATE operations with/without commit
  • ✅ SELECT operations (read-only)
  • ✅ Default parameter behavior
  • ✅ Session commit parameter propagation
  • ✅ Real database persistence verification
  • ✅ Error handling and edge cases

🔄 Backward Compatibility

  • Existing code remains unchanged: All current @Query decorators work as before
  • Default behavior preserved: Sessions still commit by default unless explicitly disabled
  • Gradual adoption: Teams can migrate to explicit is_modifying flags incrementally

🎯 Benefits

1. Performance Optimization

  • Avoid unnecessary commits for read-only operations
  • Better control over transaction boundaries
  • Reduced database overhead for SELECT queries

2. Explicit Intent

  • Clear distinction between read and write operations
  • Self-documenting code through parameter usage
  • Prevents accidental commits in read-only contexts

3. Transaction Control

  • Fine-grained control over when commits occur
  • Better support for complex transaction scenarios
  • Enables batching operations without intermediate commits

🚨 Breaking Changes

None - This is a fully backward-compatible change.

📋 Checklist

  • Feature implementation completed
  • Comprehensive tests added (336 lines)
  • Backward compatibility maintained
  • Documentation examples provided
  • Parameter validation included
  • Integration tests passing
  • Mock tests for session behavior
  • Edge cases covered

🔍 Review Focus Areas

  1. Session Management: Verify should_commit parameter handling
  2. Parameter Propagation: Check flow from decorator to session
  3. Test Coverage: Review comprehensive test scenarios
  4. Backward Compatibility: Ensure existing code unaffected
  5. Error Handling: Validate edge cases and error scenarios
- Updated `create_managed_session` method in `PySpringModel` to accept a `should_commit` parameter, allowing conditional session commits. - Modified `execute_query` method in `QueryExecutionService` to include an `is_modifying` parameter, enabling the use of managed sessions based on query type. - Adjusted `Query` decorator to pass the `is_modifying` flag to the query execution service, improving control over session behavior.
…tory - Introduced a new test suite `TestQueryModifyingOperations` to validate INSERT and UPDATE operations with varying `is_modifying` parameters. - Implemented tests to ensure correct session commit behavior based on the `is_modifying` flag. - Added integration tests to verify persistence of operations in a real database context. - Enhanced mocking strategies to validate session management during query execution.
@NFUChen NFUChen changed the title Feat/modifiable query Add Modifiable Query Support with Commit Control Jun 19, 2025
@NFUChen NFUChen self-assigned this Jun 19, 2025
@NFUChen NFUChen added the enhancement New feature or request label Jun 19, 2025
@NFUChen NFUChen merged commit da4ccde into main Jun 19, 2025
1 check passed
@NFUChen NFUChen deleted the feat/modifiable-query branch June 19, 2025 12:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

3 participants