Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions py_spring_model/core/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def create_session(cls) -> PySpringSession:

@classmethod
@contextlib.contextmanager
def create_managed_session(cls) -> Iterator[PySpringSession]:
def create_managed_session(cls, should_commit: bool = True) -> Iterator[PySpringSession]:
"""
Creates a managed session context that will automatically close the session when the context is exited.
## Example Syntax:
Expand All @@ -103,7 +103,8 @@ def create_managed_session(cls) -> Iterator[PySpringSession]:
session = cls.create_session()
yield session
logger.debug("[MANAGED SESSION COMMIT] Session committing...")
session.commit()
if should_commit:
session.commit()
logger.debug(
"[MANAGED SESSION COMMIT] Session committed, refreshing instances..."
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@

class QueryExecutionService:
@classmethod
def execute_query(cls, query_template: str, func: Callable[P, RT], kwargs: dict) -> RT:
def execute_query(cls,
query_template: str,
func: Callable[P, RT],
kwargs: dict,
is_modifying: bool
) -> RT:
RETURN = "return"

annotations = func.__annotations__
Expand All @@ -42,7 +47,7 @@ def execute_query(cls, query_template: str, func: Callable[P, RT], kwargs: dict)
processed_kwargs = cls._process_kwargs(kwargs)

sql = query_template.format(**processed_kwargs)
with PySpringModel.create_session() as session:
with PySpringModel.create_managed_session(should_commit=is_modifying) as session:
reutrn_origin = get_origin(return_type)
return_args = get_args(return_type)

Expand Down Expand Up @@ -95,7 +100,7 @@ def _validate_return_type(cls, actual_type, return_type):
def _process_single_result(cls, result: Row, actual_type: Type[BaseModel]) -> Optional[BaseModel]:
return actual_type.model_validate(result._asdict())

def Query(query_template: str) -> Callable[[Callable[P, RT]], Callable[P, RT]]:
def Query(query_template: str, is_modifying: bool = False) -> Callable[[Callable[P, RT]], Callable[P, RT]]:
"""
Decorator to mark a method as a query method.
The method will be implemented automatically by the `CrudRepositoryImplementationService`.
Expand Down Expand Up @@ -130,6 +135,6 @@ def decorator(func: Callable[P, RT]) -> Callable[P, RT]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> RT:
nonlocal query_template
return QueryExecutionService.execute_query(query_template, func, kwargs)
return QueryExecutionService.execute_query(query_template, func, kwargs, is_modifying)
return wrapper
return decorator
Loading