Enhancements
- **Bulk Operations Support:**
- **`add` Method:**
- Now accepts single instances or sequences of instances, enabling efficient bulk additions.
- Supports creating instances directly using keyword arguments (`**kwargs`).
- **`delete` Method:**
- Can handle single instances or sequences of instances for bulk deletions.
- **`update` Method:**
- Allows updating single or multiple instances simultaneously with provided keyword arguments.
- **Advanced Filtering Capabilities:**
- **`get`, `get_all`, and `get_all_count` Methods:**
- Enhanced to accept arbitrary filter expressions (`*expressions`) in addition to keyword arguments (`**kwargs`), facilitating more complex query constructions.
Return Type Modifications
- **`add` Method:**
- Now returns the added instance(s) (`ModelType`) instead of `None`, allowing immediate access to the updated data post-addition.
Type Annotations and Imports
- **Updated Imports:**
- Added `Union`, `Sequence`, and `Any` from the `typing` module to support the new method signatures and type annotations.
Code Examples
python
from sqlalchemy import and_
from your_crud_module import get_crud
from your_models import YourModel
Initialize CRUD for YourModel
crud = get_crud(YourModel)
Adding multiple instances
await crud.add(session, instances=[instance1, instance2, instance3])
Adding an instance using keyword arguments
await crud.add(session, name="New Instance", value=123)
Updating multiple instances
await crud.update(session, instances=[instance1, instance2], name="Updated Name")
Retrieving with complex filters
results = await crud.get_all(
session,
and_(YourModel.field1 == value1, YourModel.field2 < value2)
)
Counting records with filters
count = await crud.get_all_count(
session,
YourModel.status == "active"
)
Summary of Changes
- **CRUD Class:**
- Enhanced methods to support both single and multiple instances.
- Improved flexibility in creating and manipulating model instances.
- Expanded filtering options for more precise data retrieval.
- **Type Annotations:**
- Enhanced type safety and clarity with updated type hints.
Notes
- These updates aim to increase flexibility and performance in handling CRUD operations within asynchronous SQLAlchemy sessions.
- Ensure to review the updated method signatures and adjust your implementation accordingly to leverage the new features effectively.
---