Skip to content

Mapper ​

The Strawchemy mapper, whose decorators and field factories generate a schema from SQLAlchemy models.

Strawchemy ​

source

python
Strawchemy(config: StrawchemyConfig | SupportedDialect, strawberry_config: StrawberryConfig | None = None) -> None

Main entry point for integrating SQLAlchemy models with Strawberry GraphQL.

This class provides a cohesive interface to generate Strawberry GraphQL types, inputs, filters, and fields based on SQLAlchemy models. It manages configuration, type registration, and various factories for DTO generation.

Attributes:

NameTypeDescription
configStrawchemyConfigThe configuration object for Strawchemy.
registryStrawberryRegistryThe registry for Strawberry types.
filterFactory for creating boolean filter input types.
aggregate_filterFactory for creating aggregate filter input types.
distinct_onDecorator for creating distinct_on enum types.
inputFactory for creating general input types.
create_inputFactory for creating input types for create mutations.
pk_update_inputFactory for creating input types for update-by-PK mutations.
filter_update_inputFactory for creating input types for update-by-filter mutations.
orderFactory for creating order_by input types.
typeFactory for creating Strawberry output types.
aggregateFactory for creating aggregation root types.
upsert_update_fieldsFactory for creating enum DTOs for upsert update fields.
upsert_conflict_fieldsFactory for creating enum DTOs for upsert conflict fields.
pydanticPydanticMapperA mapper for generating Pydantic models.

Initializes the Strawchemy instance.

Sets up the configuration, registry, and various DTO factories required for type and field generation.

Parameters:

NameTypeDescriptionDefault
configStrawchemyConfig | SupportedDialectA StrawchemyConfig instance or a supported dialect string (e.g., "postgresql", "mysql") to initialize a default config.required
strawberry_configStrawberryConfig | NoneA StrawberryConfig instance to initialize the registry. If not provided, a default StrawberryConfig will be used.None

aggregate ​

python
aggregate = partial(self.aggregation_factory.type, mode='aggregate_type')

aggregate_filter ​

python
aggregate_filter = partial(self.aggregate_filter_factory.input, mode='aggregate_filter')

aggregate_filter_factory ​

python
aggregate_filter_factory = AggregateFilterFactory(self)

aggregation_factory ​

python
aggregation_factory = AggregateRootTypeFactory(self, strawberry_backend, type_factory=self.type_factory)

config ​

python
config = StrawchemyConfig(cast('SupportedDialect', config)) if isinstance(config, str) else config

create ​

python
create(input_type: type[Any], resolver: Any | None = None, *, validation: ValidationProtocol[T] | None = None, **field_kwargs: Unpack[MutationFieldKwargs]) -> Any

Creates a Strawberry GraphQL mutation field for creating new model instances.

This method generates a mutation field that handles the creation of SQLAlchemy model instances based on the provided input type. It integrates with Strawchemy's strawberry system for data persistence and allows for custom validation.

Parameters:

NameTypeDescriptionDefault
input_typetype[Any]The Strawberry input type representing the data for creating a new model instance. This should be a MappedGraphQLDTO.required
resolverAny | NoneAn optional custom resolver function for the mutation. If not provided, Strawchemy will use a default resolver.None
validationValidationProtocol[T] | NoneAn optional validation protocol instance to validate the input data before creation.None
**field_kwargsUnpack[MutationFieldKwargs]Common strawberry.field / repository arguments (see MutationFieldKwargs); graphql_type sets the mutation return type.{}

Returns:

TypeDescription
AnyA StrawchemyCreateMutationField instance, which is a specialized
AnyStrawberryField configured for create mutations.

create_input ​

python
create_input = partial(self.input_factory.input, mode='create_input')

delete ​

python
delete(filter_input: type[BooleanFilterDTO] | None = None, resolver: Any | None = None, **field_kwargs: Unpack[MutationFieldKwargs]) -> Any

Creates a Strawberry GraphQL mutation field for deleting model instances.

This method generates a mutation field that handles the deletion of SQLAlchemy model instances. Deletion can be based on filter criteria provided via filter_input or by ID if the filter_input is structured to accept primary key(s). It integrates with Strawchemy's strawberry system for data persistence.

Parameters:

NameTypeDescriptionDefault
filter_inputtype[BooleanFilterDTO] | NoneThe Strawberry input type used to filter which model instances should be deleted. This should be a BooleanFilterDTO. If deleting by ID, this DTO should contain the ID field(s). If None, the mutation might be configured to delete a single record based on an ID passed directly (implementation dependent).None
resolverAny | NoneAn optional custom resolver function for the mutation. If not provided, Strawchemy will use a default resolver.None
**field_kwargsUnpack[MutationFieldKwargs]Common strawberry.field / repository arguments (see MutationFieldKwargs); graphql_type sets the mutation return type.{}

Returns:

TypeDescription
AnyA StrawchemyDeleteMutationField instance, which is a specialized
AnyStrawberryField configured for delete mutations.

distinct_on ​

python
distinct_on = self.distinct_on_enum_factory.decorator

distinct_on_enum_factory ​

python
distinct_on_enum_factory = DistinctOnEnumFactory(self)

enum_factory ​

python
enum_factory = EnumFactory(self, enum_backend)

field ​

python
field(resolver: Any | None = None, *, filter_input: type[BooleanFilterDTO] | bool | None = None, order_by_input: FieldSpec | type[OrderByDTO] | None = None, default_order_by: Sequence[OrderByExpr] | OrderByExpr | None = None, pagination: bool | DefaultOffsetPagination | None = None, distinct_on: FieldSpec | type[EnumDTO] | None = None, arguments: list[StrawberryArgument] | None = None, model_field: str | None = None, id_field_name: str | None = None, root_aggregations: bool = False, filter_statement: FilterStatementCallable | None = None, execution_options: dict[str, Any] | None = None, query_hook: QueryHookCallable[Any] | Sequence[QueryHookCallable[Any]] | None = None, repository_type: AnyRepositoryType | None = None, root_field: bool = True, **field_kwargs: Unpack[OutputFieldKwargs]) -> Any

Creates a Strawberry GraphQL field with enhanced SQLAlchemy capabilities.

This method extends the standard Strawberry field creation by integrating SQLAlchemy-specific features like automatic filtering, ordering, pagination, and aggregations based on SQLAlchemy models.

Parameters:

NameTypeDescriptionDefault
resolverAny | NoneThe resolver function for the field. If not provided, Strawchemy will attempt to generate one based on the model.None
filter_inputtype[BooleanFilterDTO] | bool | NoneThe input type for filtering results.None
order_by_inputFieldSpec | type[OrderByDTO] | NoneThe input type for ordering results.None
default_order_bySequence[OrderByExpr] | OrderByExpr | NoneDefault ordering for a list field as one or more SQLAlchemy column ordering expressions (e.g. Model.name.asc()). Applied only when the client supplies no order_by. Overrides deterministic_ordering: when set, an ordering is always emitted; the primary-key tiebreaker is still appended when deterministic_ordering is True.None
distinct_onFieldSpec | type[EnumDTO] | NoneThe enum type for 'distinct on' clauses (PostgreSQL).None
paginationbool | DefaultOffsetPagination | NoneEnables pagination for the field. Can be True for default offset pagination or a DefaultOffsetPagination instance for customization.None
argumentslist[StrawberryArgument] | NoneA list of additional StrawberryArgument instances for the field.None
model_fieldstr | NoneName of the model attribute this field maps to. Lets a schema field use a different name than the underlying model field. Raises StrawchemyFieldError at decoration time if the named model field does not exist.None
id_field_namestr | NoneThe name of the ID field, used for certain operations.None
root_aggregationsboolIf True, enables root-level aggregations for the field.False
filter_statementFilterStatementCallable | NoneA callable to generate a filter statement for the query.None
execution_optionsdict[str, Any] | NoneSQLAlchemy execution options for the query.None
query_hookQueryHookCallable[Any] | Sequence[QueryHookCallable[Any]] | NoneA callable or sequence of callables to modify the SQLAlchemy query.None
repository_typeAnyRepositoryType | NoneA custom strawberry class for data fetching logic.None
root_fieldboolIndicates if this is a root-level field.True
**field_kwargsUnpack[OutputFieldKwargs]strawberry.field arguments forwarded to the generated field (see OutputFieldKwargs). name maps to the GraphQL field name.{}

Returns:

TypeDescription
AnyA StrawchemyField instance, which is a specialized StrawberryField.

filter ​

python
filter = self.filter_factory.input

filter_factory ​

python
filter_factory = BooleanFilterFactory(self, aggregate_filter_factory=self.aggregate_filter_factory)

filter_field ​

python
filter_field(*, ops: Sequence[ComparisonOperator] | None = None, arguments: Sequence[str] | None = None, apply: CustomFilterApply | None = None, join: JoinStrategy = 'exists', **field_kwargs: Unpack[StrawberryFieldKwargs]) -> Any

Declares a fine-grained filter field default.

The field's annotation supplies the comparison data type. With ops the field exposes only those GraphQL operators; with apply it becomes a custom virtual scalar input; with neither it force-includes the column's full default comparison.

Parameters:

NameTypeDescriptionDefault
opsSequence[ComparisonOperator] | NoneGraphQL operator names to expose (restricted field). Mutually exclusive with apply.None
argumentsSequence[str] | NoneArgument column names to expose on an aggregation function field. Only valid inside a class decorated with aggregate_filter. Mutually exclusive with apply.None
applyCustomFilterApply | NoneCustom filter callable (statement, value, *, dialect, model) returning a mutated Select.None
joinJoinStrategyFold-back strategy when apply is set ("exists" or "in").'exists'
**field_kwargsUnpack[StrawberryFieldKwargs]strawberry.field arguments applied to the generated GraphQL field (name, description, metadata, deprecation_reason, directives, graphql_type).{}

Returns:

TypeDescription
AnyA FilterFieldMarker consumed by the filter factory. Typed Any so it can sit as
Anya default under any annotation.

Raises:

TypeDescription
StrawchemyFieldErrorIf ops and apply are both given, if arguments and apply are both given, or if join is unsupported.

filter_update_input ​

python
filter_update_input = partial(self.input_factory.input, mode='update_by_filter_input')

input ​

python
input = self.input_factory.input

input_factory ​

python
input_factory = MutationInputFactory(self, strawberry_backend)

order ​

python
order = partial(self.order_by_factory.input, mode='order_by')

order_by_factory ​

python
order_by_factory = OrderByFactory(self)

pk_update_input ​

python
pk_update_input = partial(self.input_factory.input, mode='update_by_pk_input')

pydantic ​

python
pydantic: PydanticMapper

Provides access to a PydanticMapper instance.

This mapper is used for generating Pydantic models corresponding to the SQLAlchemy models and Strawberry types.

Returns:

TypeDescription
PydanticMapperAn instance of PydanticMapper.

registry ​

python
registry = StrawberryRegistry(strawberry_config or StrawberryConfig())

type ​

python
type = self.type_factory.type

type_factory ​

python
type_factory = ObjectTypeFactory(self, strawberry_backend, order_by_factory=self.order_by_factory, distinct_on_factory=self.distinct_on_enum_factory)

update ​

python
update(input_type: type[Any], filter_input: type[BooleanFilterDTO], resolver: Any | None = None, *, validation: ValidationProtocol[T] | None = None, **field_kwargs: Unpack[MutationFieldKwargs]) -> Any

Creates a Strawberry GraphQL mutation field for updating model instances.

This method generates a mutation field that handles updating existing SQLAlchemy model instances based on filter criteria. It uses the provided input type for the update data and a filter input type to specify which records to update. It integrates with Strawchemy's strawberry system and allows for custom validation.

Parameters:

NameTypeDescriptionDefault
input_typetype[Any]The Strawberry input type representing the data to update on the model instances. This should be a MappedGraphQLDTO.required
filter_inputtype[BooleanFilterDTO]The Strawberry input type used to filter which model instances should be updated. This should be a BooleanFilterDTO.required
resolverAny | NoneAn optional custom resolver function for the mutation. If not provided, Strawchemy will use a default resolver.None
validationValidationProtocol[T] | NoneAn optional validation protocol instance to validate the input data before the update operation.None
**field_kwargsUnpack[MutationFieldKwargs]Common strawberry.field / repository arguments (see MutationFieldKwargs); graphql_type sets the mutation return type.{}

Returns:

TypeDescription
AnyA StrawchemyUpdateMutationField instance, which is a specialized
AnyStrawberryField configured for update mutations.

update_by_ids ​

python
update_by_ids(input_type: type[Any], resolver: Any | None = None, *, validation: ValidationProtocol[T] | None = None, **field_kwargs: Unpack[MutationFieldKwargs]) -> Any

Creates a Strawberry GraphQL mutation field for updating model instances by IDs.

This method generates a mutation field that handles updating existing SQLAlchemy model instances based on their primary key(s). The input type should typically include the ID(s) of the record(s) to update and the data to apply. It integrates with Strawchemy's strawberry system and allows for custom validation.

Parameters:

NameTypeDescriptionDefault
input_typetype[Any]The Strawberry input type representing the data for updating model instances. This should be a MappedGraphQLDTO, usually generated by pk_update_input, which includes primary key fields.required
resolverAny | NoneAn optional custom resolver function for the mutation. If not provided, Strawchemy will use a default resolver.None
validationValidationProtocol[T] | NoneAn optional validation protocol instance to validate the input data before the update operation.None
**field_kwargsUnpack[MutationFieldKwargs]Common strawberry.field / repository arguments (see MutationFieldKwargs); graphql_type sets the mutation return type.{}

Returns:

TypeDescription
AnyA StrawchemyUpdateMutationField instance, specialized for updates
Anyby ID.

upsert ​

python
upsert(input_type: type[Any], update_fields: type[EnumDTO], conflict_fields: type[EnumDTO], resolver: Any | None = None, *, validation: ValidationProtocol[T] | None = None, **field_kwargs: Unpack[MutationFieldKwargs]) -> Any

Creates a Strawberry GraphQL mutation field for upserting model instances.

This method generates a mutation field that handles the "upsert" (update or insert) of SQLAlchemy model instances. It uses the provided input type, update fields enum, and conflict fields enum to determine the behavior on conflict. It integrates with Strawchemy's strawberry system and allows for custom validation.

Parameters:

NameTypeDescriptionDefault
input_typetype[Any]The Strawberry input type representing the data for the upsert operation. This should be a MappedGraphQLDTO.required
update_fieldstype[EnumDTO]An EnumDTO specifying which fields to update if a conflict occurs and an update is performed.required
conflict_fieldstype[EnumDTO]An EnumDTO specifying the fields to use for conflict detection (e.g., primary key or unique constraints).required
resolverAny | NoneAn optional custom resolver function for the mutation. If not provided, Strawchemy will use a default resolver.None
validationValidationProtocol[T] | NoneAn optional validation protocol instance to validate the input data before the upsert operation.None
**field_kwargsUnpack[MutationFieldKwargs]Common strawberry.field / repository arguments (see MutationFieldKwargs); graphql_type sets the mutation return type.{}

Returns:

TypeDescription
AnyA StrawchemyUpsertMutationField instance, which is a specialized
AnyStrawberryField configured for upsert mutations.

upsert_conflict_factory ​

python
upsert_conflict_factory = UpsertConflictEnumFactory(self, upsert_conflict_fields_enum_backend)

upsert_conflict_fields ​

python
upsert_conflict_fields = self.upsert_conflict_factory.input

upsert_update_fields ​

python
upsert_update_fields = self.enum_factory.input

ModelInstance ​

source

python
ModelInstance = Annotated[T, MapperModelInstance()]

When defined on a strawchemy type, it allows accessing the model instance in resolvers.

python
@strawchemy.type(User)
class UserObjectType:
    instance: ModelInstance

    @strawberry.field
    def name(self) -> str:
        return f"Hello, {self.first_name} {self.last_name}"