Mapper
The Strawchemy mapper, whose decorators and field factories generate a schema from SQLAlchemy models.
Strawchemy
Strawchemy(config: StrawchemyConfig | SupportedDialect, strawberry_config: StrawberryConfig | None = None) -> NoneMain 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:
| Name | Type | Description |
|---|---|---|
config | StrawchemyConfig | The configuration object for Strawchemy. |
registry | StrawberryRegistry | The registry for Strawberry types. |
filter | Factory for creating boolean filter input types. | |
aggregate_filter | Factory for creating aggregate filter input types. | |
distinct_on | Decorator for creating distinct_on enum types. | |
input | Factory for creating general input types. | |
create_input | Factory for creating input types for create mutations. | |
pk_update_input | Factory for creating input types for update-by-PK mutations. | |
filter_update_input | Factory for creating input types for update-by-filter mutations. | |
order | Factory for creating order_by input types. | |
type | Factory for creating Strawberry output types. | |
aggregate | Factory for creating aggregation root types. | |
upsert_update_fields | Factory for creating enum DTOs for upsert update fields. | |
upsert_conflict_fields | Factory for creating enum DTOs for upsert conflict fields. | |
pydantic | PydanticMapper | A 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:
| Name | Type | Description | Default |
|---|---|---|---|
config | StrawchemyConfig | SupportedDialect | A StrawchemyConfig instance or a supported dialect string (e.g., "postgresql", "mysql") to initialize a default config. | required |
strawberry_config | StrawberryConfig | None | A StrawberryConfig instance to initialize the registry. If not provided, a default StrawberryConfig will be used. | None |
aggregate
aggregate = partial(self.aggregation_factory.type, mode='aggregate_type')aggregate_filter
aggregate_filter = partial(self.aggregate_filter_factory.input, mode='aggregate_filter')aggregate_filter_factory
aggregate_filter_factory = AggregateFilterFactory(self)aggregation_factory
aggregation_factory = AggregateRootTypeFactory(self, strawberry_backend, type_factory=self.type_factory)config
config = StrawchemyConfig(cast('SupportedDialect', config)) if isinstance(config, str) else configcreate
create(input_type: type[Any], resolver: Any | None = None, *, validation: ValidationProtocol[T] | None = None, **field_kwargs: Unpack[MutationFieldKwargs]) -> AnyCreates 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:
| Name | Type | Description | Default |
|---|---|---|---|
input_type | type[Any] | The Strawberry input type representing the data for creating a new model instance. This should be a MappedGraphQLDTO. | required |
resolver | Any | None | An optional custom resolver function for the mutation. If not provided, Strawchemy will use a default resolver. | None |
validation | ValidationProtocol[T] | None | An optional validation protocol instance to validate the input data before creation. | None |
**field_kwargs | Unpack[MutationFieldKwargs] | Common strawberry.field / repository arguments (see MutationFieldKwargs); graphql_type sets the mutation return type. | {} |
Returns:
| Type | Description |
|---|---|
Any | A StrawchemyCreateMutationField instance, which is a specialized |
Any | StrawberryField configured for create mutations. |
create_input
create_input = partial(self.input_factory.input, mode='create_input')delete
delete(filter_input: type[BooleanFilterDTO] | None = None, resolver: Any | None = None, **field_kwargs: Unpack[MutationFieldKwargs]) -> AnyCreates 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:
| Name | Type | Description | Default |
|---|---|---|---|
filter_input | type[BooleanFilterDTO] | None | The 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 |
resolver | Any | None | An optional custom resolver function for the mutation. If not provided, Strawchemy will use a default resolver. | None |
**field_kwargs | Unpack[MutationFieldKwargs] | Common strawberry.field / repository arguments (see MutationFieldKwargs); graphql_type sets the mutation return type. | {} |
Returns:
| Type | Description |
|---|---|
Any | A StrawchemyDeleteMutationField instance, which is a specialized |
Any | StrawberryField configured for delete mutations. |
distinct_on
distinct_on = self.distinct_on_enum_factory.decoratordistinct_on_enum_factory
distinct_on_enum_factory = DistinctOnEnumFactory(self)enum_factory
enum_factory = EnumFactory(self, enum_backend)field
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]) -> AnyCreates 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:
| Name | Type | Description | Default |
|---|---|---|---|
resolver | Any | None | The resolver function for the field. If not provided, Strawchemy will attempt to generate one based on the model. | None |
filter_input | type[BooleanFilterDTO] | bool | None | The input type for filtering results. | None |
order_by_input | FieldSpec | type[OrderByDTO] | None | The input type for ordering results. | None |
default_order_by | Sequence[OrderByExpr] | OrderByExpr | None | Default 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_on | FieldSpec | type[EnumDTO] | None | The enum type for 'distinct on' clauses (PostgreSQL). | None |
pagination | bool | DefaultOffsetPagination | None | Enables pagination for the field. Can be True for default offset pagination or a DefaultOffsetPagination instance for customization. | None |
arguments | list[StrawberryArgument] | None | A list of additional StrawberryArgument instances for the field. | None |
model_field | str | None | Name 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_name | str | None | The name of the ID field, used for certain operations. | None |
root_aggregations | bool | If True, enables root-level aggregations for the field. | False |
filter_statement | FilterStatementCallable | None | A callable to generate a filter statement for the query. | None |
execution_options | dict[str, Any] | None | SQLAlchemy execution options for the query. | None |
query_hook | QueryHookCallable[Any] | Sequence[QueryHookCallable[Any]] | None | A callable or sequence of callables to modify the SQLAlchemy query. | None |
repository_type | AnyRepositoryType | None | A custom strawberry class for data fetching logic. | None |
root_field | bool | Indicates if this is a root-level field. | True |
**field_kwargs | Unpack[OutputFieldKwargs] | strawberry.field arguments forwarded to the generated field (see OutputFieldKwargs). name maps to the GraphQL field name. | {} |
Returns:
| Type | Description |
|---|---|
Any | A StrawchemyField instance, which is a specialized StrawberryField. |
filter
filter = self.filter_factory.inputfilter_factory
filter_factory = BooleanFilterFactory(self, aggregate_filter_factory=self.aggregate_filter_factory)filter_field
filter_field(*, ops: Sequence[ComparisonOperator] | None = None, arguments: Sequence[str] | None = None, apply: CustomFilterApply | None = None, join: JoinStrategy = 'exists', **field_kwargs: Unpack[StrawberryFieldKwargs]) -> AnyDeclares 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:
| Name | Type | Description | Default |
|---|---|---|---|
ops | Sequence[ComparisonOperator] | None | GraphQL operator names to expose (restricted field). Mutually exclusive with apply. | None |
arguments | Sequence[str] | None | Argument column names to expose on an aggregation function field. Only valid inside a class decorated with aggregate_filter. Mutually exclusive with apply. | None |
apply | CustomFilterApply | None | Custom filter callable (statement, value, *, dialect, model) returning a mutated Select. | None |
join | JoinStrategy | Fold-back strategy when apply is set ("exists" or "in"). | 'exists' |
**field_kwargs | Unpack[StrawberryFieldKwargs] | strawberry.field arguments applied to the generated GraphQL field (name, description, metadata, deprecation_reason, directives, graphql_type). | {} |
Returns:
| Type | Description |
|---|---|
Any | A FilterFieldMarker consumed by the filter factory. Typed Any so it can sit as |
Any | a default under any annotation. |
Raises:
| Type | Description |
|---|---|
StrawchemyFieldError | If ops and apply are both given, if arguments and apply are both given, or if join is unsupported. |
filter_update_input
filter_update_input = partial(self.input_factory.input, mode='update_by_filter_input')input
input = self.input_factory.inputinput_factory
input_factory = MutationInputFactory(self, strawberry_backend)order
order = partial(self.order_by_factory.input, mode='order_by')order_by_factory
order_by_factory = OrderByFactory(self)pk_update_input
pk_update_input = partial(self.input_factory.input, mode='update_by_pk_input')pydantic
pydantic: PydanticMapperProvides access to a PydanticMapper instance.
This mapper is used for generating Pydantic models corresponding to the SQLAlchemy models and Strawberry types.
Returns:
| Type | Description |
|---|---|
PydanticMapper | An instance of PydanticMapper. |
registry
registry = StrawberryRegistry(strawberry_config or StrawberryConfig())type
type = self.type_factory.typetype_factory
type_factory = ObjectTypeFactory(self, strawberry_backend, order_by_factory=self.order_by_factory, distinct_on_factory=self.distinct_on_enum_factory)update
update(input_type: type[Any], filter_input: type[BooleanFilterDTO], resolver: Any | None = None, *, validation: ValidationProtocol[T] | None = None, **field_kwargs: Unpack[MutationFieldKwargs]) -> AnyCreates 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:
| Name | Type | Description | Default |
|---|---|---|---|
input_type | type[Any] | The Strawberry input type representing the data to update on the model instances. This should be a MappedGraphQLDTO. | required |
filter_input | type[BooleanFilterDTO] | The Strawberry input type used to filter which model instances should be updated. This should be a BooleanFilterDTO. | required |
resolver | Any | None | An optional custom resolver function for the mutation. If not provided, Strawchemy will use a default resolver. | None |
validation | ValidationProtocol[T] | None | An optional validation protocol instance to validate the input data before the update operation. | None |
**field_kwargs | Unpack[MutationFieldKwargs] | Common strawberry.field / repository arguments (see MutationFieldKwargs); graphql_type sets the mutation return type. | {} |
Returns:
| Type | Description |
|---|---|
Any | A StrawchemyUpdateMutationField instance, which is a specialized |
Any | StrawberryField configured for update mutations. |
update_by_ids
update_by_ids(input_type: type[Any], resolver: Any | None = None, *, validation: ValidationProtocol[T] | None = None, **field_kwargs: Unpack[MutationFieldKwargs]) -> AnyCreates 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:
| Name | Type | Description | Default |
|---|---|---|---|
input_type | type[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 |
resolver | Any | None | An optional custom resolver function for the mutation. If not provided, Strawchemy will use a default resolver. | None |
validation | ValidationProtocol[T] | None | An optional validation protocol instance to validate the input data before the update operation. | None |
**field_kwargs | Unpack[MutationFieldKwargs] | Common strawberry.field / repository arguments (see MutationFieldKwargs); graphql_type sets the mutation return type. | {} |
Returns:
| Type | Description |
|---|---|
Any | A StrawchemyUpdateMutationField instance, specialized for updates |
Any | by ID. |
upsert
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]) -> AnyCreates 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:
| Name | Type | Description | Default |
|---|---|---|---|
input_type | type[Any] | The Strawberry input type representing the data for the upsert operation. This should be a MappedGraphQLDTO. | required |
update_fields | type[EnumDTO] | An EnumDTO specifying which fields to update if a conflict occurs and an update is performed. | required |
conflict_fields | type[EnumDTO] | An EnumDTO specifying the fields to use for conflict detection (e.g., primary key or unique constraints). | required |
resolver | Any | None | An optional custom resolver function for the mutation. If not provided, Strawchemy will use a default resolver. | None |
validation | ValidationProtocol[T] | None | An optional validation protocol instance to validate the input data before the upsert operation. | None |
**field_kwargs | Unpack[MutationFieldKwargs] | Common strawberry.field / repository arguments (see MutationFieldKwargs); graphql_type sets the mutation return type. | {} |
Returns:
| Type | Description |
|---|---|
Any | A StrawchemyUpsertMutationField instance, which is a specialized |
Any | StrawberryField configured for upsert mutations. |
upsert_conflict_factory
upsert_conflict_factory = UpsertConflictEnumFactory(self, upsert_conflict_fields_enum_backend)upsert_conflict_fields
upsert_conflict_fields = self.upsert_conflict_factory.inputupsert_update_fields
upsert_update_fields = self.enum_factory.inputModelInstance
ModelInstance = Annotated[T, MapperModelInstance()]When defined on a strawchemy type, it allows accessing the model instance in resolvers.
@strawchemy.type(User)
class UserObjectType:
instance: ModelInstance
@strawberry.field
def name(self) -> str:
return f"Hello, {self.first_name} {self.last_name}"