Services#
Async Services#
- class advanced_alchemy.service.SQLAlchemyAsyncRepositoryReadService(
- session,
- *,
- statement=None,
- auto_expunge=False,
- auto_refresh=True,
- auto_commit=False,
- order_by=None,
- error_messages=Empty,
- wrap_exceptions=True,
- load=None,
- execution_options=None,
- uniquify=None,
- count_with_window_function=None,
- **repo_kwargs,
Bases:
ResultConverter,Generic[ModelT,SQLAlchemyAsyncRepositoryT]Service object that operates on a repository object.
- repository_type: type[SQLAlchemyAsyncRepositoryT]#
Type of the repository to use.
- async count(
- *filters,
- statement=None,
- error_messages=Empty,
- load=None,
- execution_options=None,
- uniquify=None,
- bind_group=None,
- **kwargs,
Count of records returned by query.
- Parameters:
*filters (StatementFilter | ColumnElement[bool]) – arguments for filtering.
statement (Select | None) – To facilitate customization of the underlying select query.
error_messages (ErrorMessages | type[Empty] | None) – An optional dictionary of templates to use for friendlier error messages to clients
load (LoadSpec | None) – Set relationships to be loaded
execution_options (dict[str, Any] | None) – Set default execution options
uniquify (bool | None) – Optionally apply the
unique()method to results before returning.bind_group (str | None) – The bind group to use for the operation.
**kwargs (Any) – key value pairs of filter types.
- Returns:
A count of the collection, filtered, but ignoring pagination.
- Return type:
int
- async get(
- item_id,
- *,
- statement=None,
- id_attribute=None,
- auto_expunge=None,
- error_messages=Empty,
- load=None,
- execution_options=None,
- uniquify=None,
- bind_group=None,
Wrap repository scalar operation.
- Parameters:
item_id (Any | tuple[Any, ...] | dict[str, Any]) – Identifier of instance to be retrieved. For single primary key models, pass a scalar value (int, str, UUID, etc.). For composite primary key models, pass a tuple of values in column order, or a dict mapping attribute names to values.
auto_expunge (bool | None) – Remove object from session before returning.
statement (Select | None) – To facilitate customization of the underlying select query.
id_attribute (str | InstrumentedAttribute[Any] | None) – Allows customization of the unique identifier to use for model fetching. Defaults to id, but can reference any surrogate or candidate key for the table. Only applicable for single primary key models.
error_messages (ErrorMessages | type[Empty] | None) – An optional dictionary of templates to use for friendlier error messages to clients
load (LoadSpec | None) – Set relationships to be loaded
execution_options (dict[str, Any] | None) – Set default execution options
uniquify (bool | None) – Optionally apply the
unique()method to results before returning.bind_group (str | None) – The bind group to use for the operation.
- Returns:
Representation of instance with identifier item_id.
- Return type:
Examples
# Single primary key >>> user = await service.get(123)
# Composite primary key (tuple format) >>> assignment = await service.get((user_id, role_id))
# Composite primary key (dict format) >>> assignment = await service.get({“user_id”: 1, “role_id”: 5})
- async list_and_count(
- *filters,
- statement=None,
- auto_expunge=None,
- count_with_window_function=None,
- order_by=None,
- error_messages=Empty,
- load=None,
- execution_options=None,
- uniquify=None,
- use_cache=True,
- bind_group=None,
- **kwargs,
List of records and total count returned by query.
Deprecated since version 1.10.0: Use
get_many_and_count()instead.- Return type:
tuple[Sequence[ModelT], int]
- async list(
- *filters,
- statement=None,
- auto_expunge=None,
- order_by=None,
- error_messages=Empty,
- load=None,
- execution_options=None,
- uniquify=None,
- use_cache=True,
- bind_group=None,
- **kwargs,
Wrap repository scalars operation.
Deprecated since version 1.10.0: Use
get_many()instead.- Return type:
Sequence[ModelT]
- class advanced_alchemy.service.SQLAlchemyAsyncRepositoryService#
Bases:
SQLAlchemyAsyncRepositoryReadService[ModelT,SQLAlchemyAsyncRepositoryT],Generic[ModelT,SQLAlchemyAsyncRepositoryT]Service object that operates on a repository object.
- async create(
- data,
- *,
- auto_commit=None,
- auto_expunge=None,
- auto_refresh=None,
- error_messages=Empty,
- bind_group=None,
- schema_dump_config=None,
Wrap repository instance creation.
- Parameters:
data (ModelDictT[ModelT]) – Representation to be created.
auto_expunge (bool | None) – Remove object from session before returning.
auto_refresh (bool | None) – Refresh object from session before returning.
auto_commit (bool | None) – Commit objects before returning.
error_messages (ErrorMessages | type[Empty] | None) – An optional dictionary of templates to use for friendlier error messages to clients
bind_group (str | None) – Optional routing group to use for the operation.
schema_dump_config (SchemaDumpConfig | None) – Optional schema dump behavior for this operation.
- Returns:
Representation of created instance.
- Return type:
- async update(
- data,
- item_id=None,
- *,
- attribute_names=None,
- with_for_update=None,
- auto_commit=None,
- auto_expunge=None,
- auto_refresh=None,
- id_attribute=None,
- error_messages=Empty,
- load=None,
- execution_options=None,
- uniquify=None,
- bind_group=None,
- schema_dump_config=None,
Wrap repository update operation.
- Parameters:
data (ModelDictT[ModelT]) – Representation to be updated.
item_id (Any | None) – Identifier of item to be updated.
attribute_names (Iterable[str] | None) – an iterable of attribute names to pass into the
updatemethod.with_for_update (ForUpdateArg | None | bool | Dict[str, Any]) – indicating FOR UPDATE should be used, or may be a dictionary containing flags to indicate a more specific set of FOR UPDATE flags for the SELECT
auto_expunge (bool | None) – Remove object from session before returning.
auto_refresh (bool | None) – Refresh object from session before returning.
auto_commit (bool | None) – Commit objects before returning.
id_attribute (str | InstrumentedAttribute[Any] | None) – Allows customization of the unique identifier to use for model fetching. Defaults to id, but can reference any surrogate or candidate key for the table.
error_messages (ErrorMessages | type[Empty] | None) – An optional dictionary of templates to use for friendlier error messages to clients
load (LoadSpec | None) – Set default relationships to be loaded
execution_options (dict[str, Any] | None) – Set default execution options
uniquify (bool | None) – Optionally apply the
unique()method to results before returning.bind_group (str | None) – Optional routing group to use for the operation.
schema_dump_config (SchemaDumpConfig | None) – Optional schema dump behavior for this operation.
- Raises:
RepositoryError – If no configuration or session is provided.
- Returns:
Updated representation.
- Return type:
- async to_model(
- data,
- operation=None,
- schema_dump_config=None,
Parse and Convert input into a model.
- Parameters:
data (ModelDictT[ModelT]) – Representations to be created.
operation (str | None) – Optional operation flag so that you can provide behavior based on CRUD operation
schema_dump_config (SchemaDumpConfig | None) – Optional schema dump behavior for this conversion.
- Returns:
Representation of created instances.
- Return type:
- async upsert(
- data,
- item_id=None,
- *,
- attribute_names=None,
- with_for_update=None,
- auto_expunge=None,
- auto_commit=None,
- auto_refresh=None,
- match_fields=None,
- error_messages=Empty,
- load=None,
- execution_options=None,
- uniquify=None,
- bind_group=None,
- schema_dump_config=None,
Wrap repository upsert operation.
- Parameters:
data (ModelDictT[ModelT]) – Instance to update existing, or be created. Identifier used to determine if an existing instance exists is the value of an attribute on data named as value of self.id_attribute.
item_id (Any | None) – Identifier of the object for upsert.
attribute_names (Iterable[str] | None) – an iterable of attribute names to pass into the
updatemethod.with_for_update (ForUpdateArg | None | bool | Dict[str, Any]) – indicating FOR UPDATE should be used, or may be a dictionary containing flags to indicate a more specific set of FOR UPDATE flags for the SELECT
auto_expunge (bool | None) – Remove object from session before returning.
auto_refresh (bool | None) – Refresh object from session before returning.
auto_commit (bool | None) – Commit objects before returning.
match_fields (List[str] | str | None) – a list of keys to use to match the existing model. When empty, all fields are matched.
error_messages (ErrorMessages | type[Empty] | None) – An optional dictionary of templates to use for friendlier error messages to clients
load (LoadSpec | None) – Set default relationships to be loaded
execution_options (dict[str, Any] | None) – Set default execution options
uniquify (bool | None) – Optionally apply the
unique()method to results before returning.bind_group (str | None) – Optional routing group to use for the operation.
schema_dump_config (SchemaDumpConfig | None) – Optional schema dump behavior for this operation.
- Returns:
Updated or created representation.
- Return type:
- async delete(
- item_id,
- *,
- auto_commit=None,
- auto_expunge=None,
- id_attribute=None,
- error_messages=Empty,
- load=None,
- execution_options=None,
- uniquify=None,
- bind_group=None,
Wrap repository delete operation.
- Parameters:
item_id (Any | tuple[Any, ...] | dict[str, Any]) – Identifier of instance to be deleted. For single primary key models, pass a scalar value (int, str, UUID, etc.). For composite primary key models, pass a tuple of values in column order, or a dict mapping attribute names to values.
auto_commit (bool | None) – Commit objects before returning.
auto_expunge (bool | None) – Remove object from session before returning.
id_attribute (str | InstrumentedAttribute[Any] | None) – Allows customization of the unique identifier to use for model fetching. Defaults to id, but can reference any surrogate or candidate key for the table. Only applicable for single primary key models.
error_messages (ErrorMessages | type[Empty] | None) – An optional dictionary of templates to use for friendlier error messages to clients
load (LoadSpec | None) – Set default relationships to be loaded
execution_options (dict[str, Any] | None) – Set default execution options
uniquify (bool | None) – Optionally apply the
unique()method to results before returning.bind_group (str | None) – Optional routing group to use for the operation.
- Returns:
Representation of the deleted instance.
- Return type:
Examples
# Single primary key >>> deleted_user = await service.delete(123)
# Composite primary key (tuple format) >>> deleted = await service.delete((user_id, role_id))
# Composite primary key (dict format) >>> deleted = await service.delete({“user_id”: 1, “role_id”: 5})
- class advanced_alchemy.service.SQLAlchemyAsyncQueryService(session, **repo_kwargs)#
Bases:
ResultConverterSimple service to execute the basic Query repository..
Sync Services#
- class advanced_alchemy.service.SQLAlchemySyncRepositoryReadService(
- session,
- *,
- statement=None,
- auto_expunge=False,
- auto_refresh=True,
- auto_commit=False,
- order_by=None,
- error_messages=Empty,
- wrap_exceptions=True,
- load=None,
- execution_options=None,
- uniquify=None,
- count_with_window_function=None,
- **repo_kwargs,
Bases:
ResultConverter,Generic[ModelT,SQLAlchemySyncRepositoryT]Service object that operates on a repository object.
- repository_type: type[SQLAlchemySyncRepositoryT]#
Type of the repository to use.
- class advanced_alchemy.service.SQLAlchemySyncRepositoryService#
Bases:
SQLAlchemySyncRepositoryReadService[ModelT,SQLAlchemySyncRepositoryT],Generic[ModelT,SQLAlchemySyncRepositoryT]Service object that operates on a repository object.
- class advanced_alchemy.service.SQLAlchemySyncQueryService(session, **repo_kwargs)#
Bases:
ResultConverterSimple service to execute the basic Query repository..
Conversion, Pagination & Helpers#
- class advanced_alchemy.service.ResultConverter#
Bases:
objectSimple mixin to help convert to a paginated response model.
Single objects are transformed to the supplied schema type, and lists of objects are automatically transformed into an OffsetPagination response of the supplied schema type.
- Parameters:
data – A database model instance or row mapping. Type:
ModelOrRowMappingT- Returns:
The converted schema object.
- to_schema(
- data,
- total=None,
- filters=None,
- *,
- schema_type=None,
Convert the object to a response schema.
When schema_type is None, the model is returned with no conversion.
- Parameters:
data (Union[ModelOrRowMappingT, Sequence[ModelOrRowMappingT], ModelProtocol, Sequence[ModelProtocol], RowMapping, Sequence[RowMapping], Row[Any], Sequence[Row[Any]], dict[str, Any], Sequence[dict[str, Any]]]) – The return from one of the service calls. Type:
ModelOrRowMappingTtotal (Optional[int]) – The total number of rows in the data.
filters (Union[Sequence[Union[StatementFilter, ColumnElement[bool]]], Sequence[StatementFilter], None]) –
StatementFilter|ColumnElementcollection of route filters.schema_type (Optional[type[ModelDTOT]]) –
ModelDTOTOptional schema type to convert the data to
- Raises:
AdvancedAlchemyError – If schema_type is not a valid Pydantic, Msgspec, or attrs schema and all libraries are not installed.
- Returns:
ModelProtocol|RowMapping|OffsetPagination|msgspec.Struct|pydantic.BaseModel|attrsclass- Return type:
Union[ModelOrRowMappingT, OffsetPagination[ModelOrRowMappingT], ModelDTOT, OffsetPagination[ModelDTOT]]
- class advanced_alchemy.service.OffsetPagination(items, limit, offset, total)#
Bases:
Generic[T]Container for data returned using limit/offset pagination.
- items: Sequence[T]#
List of data being sent as part of the response.
- limit: int#
Maximal number of items to send.
- offset: int#
Offset from the beginning of the query.
Identical to an index.
- total: int#
Total number of items.
- advanced_alchemy.service.find_filter(filter_type, filters)#
Get the filter specified by filter type from the filters.
- Parameters:
filter_type (type[FilterTypeT]) – The type of filter to find.
filters (Union[Sequence[Union[StatementFilter, ColumnElement[bool]]], Sequence[StatementFilter]]) – filter types to apply to the query
- Returns:
The match filter instance or None
- Return type:
Union[FilterTypeT, None]
- class advanced_alchemy.service.SchemaDumpConfig(
- exclude_unset=True,
- exclude_none=False,
- exclude_defaults=False,
- exclude_sentinels=True,
Bases:
objectConfiguration for dumping schema-like service input data.
- advanced_alchemy.service.schema_dump(data, exclude_unset=True, *, config=None)#
Dump a data object to a dictionary.
- Return type:
Union[dict[str, Any], ModelT]
- advanced_alchemy.service.fields(cls)#
Return the tuple of attrs attributes for a class or instance.
The tuple also allows accessing the fields by their names (see below for examples).
- Parameters:
cls (
type) – Class or instance to introspect.- Raises:
TypeError – If cls is neither a class nor an attrs instance.
attrs.exceptions.NotAnAttrsClassError – If cls is not an attrs class.
- Returns:
tuple (with name accessors) of attrs.Attribute
Changed in version 16.2.0: Returned tuple allows accessing the fields by name.
Changed in version 23.1.0: Add support for generic classes.
Changed in version 26.1.0: Add support for instances.
- advanced_alchemy.service.ModelDTOT#
- advanced_alchemy.service.ModelDictT#
str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.
- advanced_alchemy.service.ModelDictListT#
str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to ‘utf-8’. errors defaults to ‘strict’.
- advanced_alchemy.service.FilterTypeT#
- advanced_alchemy.service.SupportedSchemaModel#
- class advanced_alchemy.service.AttrsInstance(*args, **kwargs)#
Bases:
Protocol
- advanced_alchemy.service.ATTRS_INSTALLED: bool#
Boolean flag indicating whether
attrsis installed.