### Development setup with mise Source: https://github.com/alteian/strawberry-alchemy/blob/master/CONTRIBUTING.md Clone the repository and install dependencies using mise, which manages Python and uv from mise.toml. Run make sync, make doctor, and optionally make hooks to install pre-commit. ```bash git clone https://github.com/Alteian/strawberry-alchemy.git cd strawberry-alchemy mise install # Python + uv from mise.toml make sync make doctor make hooks # optional: install pre-commit ``` -------------------------------- ### Define Strawberry schema with query and mutation Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/getting-started.md Creates the Strawberry schema by combining the Query and Mutation classes. Place this in schema.py and import the query and mutation types from your project's modules. ```python # schema.py import strawberry from .mutations import Mutation from .queries import Query schema = strawberry.Schema(query=Query, mutation=Mutation) ``` -------------------------------- ### Install strawberry-alchemy with pip or uv Source: https://github.com/alteian/strawberry-alchemy/blob/master/README.md Install the package using pip or uv. Requires Python >= 3.13, Strawberry GraphQL >= 0.339.1, sqlalchemy[asyncio] >= 2.1.6, and Pydantic >= 2.14. ```bash pip install strawberry-alchemy # or uv add strawberry-alchemy ``` -------------------------------- ### Run example tests with make test Source: https://github.com/alteian/strawberry-alchemy/blob/master/README.md Runs the runnable core patterns (ACL, OR filters, @optimize_field, ClassVar repos, deletion handler, soft-delete, prepare_mutation_resources) located in examples/blog. ```bash make test ARGS="tests/examples" ``` -------------------------------- ### Define ExampleContext dataclass for Strawberry context Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/getting-started.md Provides the context contract required by BaseNodeType.resolve_*: an async get_session() returning an AsyncSession, an identity awaitable or user for ACL/permissions, and an asyncio.Lock named db_execution_lock for serializing optimizer DB work. Wire this into your ASGI/FastAPI context getter like any Strawberry context. ```python # context.py import asyncio from dataclasses import dataclass, field from typing import Any from uuid import UUID from sqlalchemy.ext.asyncio import AsyncSession @dataclass class ExampleUser: id: UUID role: str = "user" @dataclass class ExampleContext: session: AsyncSession user: ExampleUser | None db_execution_lock: asyncio.Lock = field(default_factory=asyncio.Lock) async def get_session(self) -> AsyncSession: return self.session @property def identity(self) -> Any: async def _identity() -> ExampleUser | None: return self.user return _identity() ``` -------------------------------- ### QueryAnalyzer.begin Source: https://github.com/alteian/strawberry-alchemy Starts the analysis session by recording the model name and start time. ```APIDOC ## QueryAnalyzer.begin ### Description Starts the analysis session by recording the model name and start time. ### Method begin ### Parameters - **model** (type) - Required - The model class being analyzed. ### Response None ``` -------------------------------- ### Mutations: create_post, update_post, delete_post with permissions Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/getting-started.md Defines GraphQL mutations for creating, updating, and deleting posts. Uses strawberry input types, PostRepository, and prepare_mutation_resources with IsAuthenticated and OwnerPermission. The delete_post mutation uses PostDeletionHandler and returns whether any failures occurred. ```python # mutations.py import strawberry from strawberry.relay import GlobalID from strawberry.types import Info from strawberry_alchemy import IsAuthenticated, OwnerPermission, prepare_mutation_resources from .deletion import PostDeletionHandler from .repositories import PostRepository from .schemas import PostSchema from .types import PostType @strawberry.input class CreatePostInput: title: str body: str @strawberry.input class UpdatePostInput: id: GlobalID title: str body: str @strawberry.input class DeletePostInput: id: GlobalID @strawberry.type class PostMutations: @strawberry.mutation async def create_post(self, info: Info, input: CreatePostInput) -> PostType: session = await info.context.get_session() user = await info.context.identity schema = PostSchema.from_input(input, user_id=user.id) created = await PostRepository(session).create(schema=schema) return created.to_type(PostType) @strawberry.mutation async def update_post(self, info: Info, input: UpdatePostInput) -> PostType: session = await info.context.get_session() schema = PostSchema.from_input( input, user_id=(await info.context.identity).id ) result = await PostRepository(session).update(schema=schema) return result.to_type(PostType) @strawberry.mutation async def delete_post(self, info: Info, input: DeletePostInput) -> bool: session = await info.context.get_session() repo = PostRepository(session, deletion_handler=PostDeletionHandler()) schema = PostSchema.from_input(input) await prepare_mutation_resources( info, {"post_id": input.id}, loaders={"post_id": lambda value: repo.get_by_id(value)}, permissions=[ IsAuthenticated(), OwnerPermission(owner_field="user_id", resource_key="post_id"), ], ) report = await repo.delete(id=schema.id, strict=False) return not report.has_failures ``` -------------------------------- ### Set up development environment with mise and make Source: https://github.com/alteian/strawberry-alchemy/blob/master/README.md Clones the repository, installs pinned tool versions via mise, syncs dependencies, runs doctor, and executes CI tasks. Tool versions are pinned in mise.toml. ```bash git clone https://github.com/Alteian/strawberry-alchemy.git cd strawberry-alchemy mise install make sync && make doctor make ci ``` -------------------------------- ### Custom PostPermissionResolver example Source: https://github.com/alteian/strawberry-alchemy Example subclass of BasePermissionResolver that returns different permission lists based on the operation: create, update, or other operations. ```python from strawberry_alchemy import BasePermissionResolver class PostPermissionResolver(BasePermissionResolver): def resolve(self, operation: str, *, data=None, **kwargs) -> list[Any]: if operation == "create": return [IsAuthenticated()] if operation == "update": return [IsAuthenticated(), OwnerPermission()] return [IsAuthenticated(), RolePermission(role="admin")] ``` -------------------------------- ### FieldPath usage example Source: https://github.com/alteian/strawberry-alchemy Shows constructing a FieldPath from a dotted string, joining it, and appending a child segment. ```python from strawberry_alchemy import FieldPath path = FieldPath("comments.items") assert path.join() == "comments.items" assert path.child("body").parts == ("comments", "items", "body") ``` -------------------------------- ### OwnerPermission usage example Source: https://github.com/alteian/strawberry-alchemy Shows how to instantiate OwnerPermission and call has_permission with a resource bag. The resource_instances parameter must be passed explicitly. ```python perm = OwnerPermission(owner_field="user_id") perm.has_permission(info, resource_instances=bag) ``` -------------------------------- ### Usage example with multiple permissions Source: https://github.com/alteian/strawberry-alchemy Shows how to call `fetch_and_check_permissions` with a list of permission objects and a `resource_instances` bag. Catches `PermissionError` and re-raises as `PermissionDenied` to surface to GraphQL. ```python from strawberry_alchemy import fetch_and_check_permissions try: await fetch_and_check_permissions( info, permissions=[IsAuthenticated(), OwnerPermission()], resource_instances=bag, ) except PermissionError as e: raise PermissionDenied(str(e)) # surface to GraphQL ``` -------------------------------- ### Define repositories with BaseRepository and ClassVars Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/getting-started.md Defines PostRepository and CommentRepository using strawberry-alchemy's BaseRepository. ClassVars set model_cls, schema_cls, relation_models, and soft_delete_field so callers can use PostRepository(session) without repeating types. PostRepository configures a comments relation and soft delete on deleted_at. ```python # repositories.py from typing import ClassVar from strawberry_alchemy import BaseRepository from .models import Comment, Post from .schemas import CommentSchema, PostSchema class PostRepository(BaseRepository[Post, PostSchema]): model_cls: ClassVar[type[Post]] = Post schema_cls: ClassVar[type[PostSchema]] = PostSchema relation_models: ClassVar[dict[str, type]] = {"comments": Comment} soft_delete_field: ClassVar[str | None] = "deleted_at" class CommentRepository(BaseRepository[Comment, CommentSchema]): model_cls: ClassVar[type[Comment]] = Comment schema_cls: ClassVar[type[CommentSchema]] = CommentSchema ``` -------------------------------- ### AnnotateCustom usage example Source: https://github.com/alteian/strawberry-alchemy Shows how to use AnnotateCustom with a custom expression and to_attr to annotate a field. The expression receives user_id as the 4th argument when filter_current_user is True. ```python @strawberry.field @optimize_field(AnnotateCustom("likes", expression=lambda model, rel, prop, user_id: rel.count() > 3, to_attr="popular")) async def is_popular(self, info: Info) -> bool: return bool(getattr(self, "popular", False)) ``` -------------------------------- ### Define SQLAlchemy models with SoftDeleteMixin for Strawberry-Alchemy Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/getting-started.md Defines a declarative base and Post/Comment models using UUID primary keys and created_at/updated_at timestamps. For SQLite tests, use sqlalchemy.Uuid instead of the library's Postgres UUID dialect types. Soft-delete is optional via SoftDeleteMixin. ```python # models.py import uuid from datetime import datetime from sqlalchemy import DateTime, ForeignKey, String, Uuid, func from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship from strawberry_alchemy import SoftDeleteMixin class ExampleBase(DeclarativeBase): pass class Post(SoftDeleteMixin, ExampleBase): __tablename__ = "post" id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4) user_id: Mapped[uuid.UUID] = mapped_column(Uuid, index=True) title: Mapped[str] = mapped_column(String(255)) body: Mapped[str] = mapped_column(String) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) updated_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), server_default=func.now(), onupdate=func.now() ) comments: Mapped[list["Comment"]] = relationship(back_populates="post") class Comment(ExampleBase): __tablename__ = "comment" id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4) post_id: Mapped[uuid.UUID] = mapped_column(Uuid, ForeignKey("post.id"), index=True) body: Mapped[str] = mapped_column(String) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) updated_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), server_default=func.now(), onupdate=func.now() ) post: Mapped[Post] = relationship(back_populates="comments") ``` -------------------------------- ### PostAccessFilter example Source: https://github.com/alteian/strawberry-alchemy Example access filter that restricts rows to the current user. Returns query.where(False) when context_user is None, otherwise filters by model.user_id == context_user.id. ```python from typing import Any from strawberry_alchemy.filtering import AccessControlFilter class PostAccessFilter(AccessControlFilter): model_class = Post @staticmethod async def apply_filter(query: Any, model: type[Any], context_user: Any) -> Any: if context_user is None: return query.where(False) return query.where(model.user_id == context_user.id) ``` -------------------------------- ### PostRepository subclass and mutation usage Source: https://github.com/alteian/strawberry-alchemy Example from examples/blog/repositories.py and mutations.py showing how to subclass BaseRepository with model_cls, schema_cls, and relation_models, then use the repository in a mutation to create and delete posts. ```python from typing import ClassVar from strawberry_alchemy import BaseRepository from my_app.models import Post from my_app.schemas import PostSchema class PostRepository(BaseRepository[Post, PostSchema]): model_cls: ClassVar[type[Post]] = Post schema_cls: ClassVar[type[PostSchema]] = PostSchema relation_models: ClassVar[dict[str, type]] = {"comments": Comment} # in a mutation: repo = PostRepository(session, deletion_handler=PostDeletionHandler()) created = await repo.create(schema=PostSchema(title=..., body=..., user_id=user.id)) await repo.delete(id=uuid.UUID(input.id.node_id)) ``` -------------------------------- ### Define __version__ using importlib.metadata Source: https://github.com/alteian/strawberry-alchemy Reads the installed distribution version from package metadata at import time. Raises PackageNotFoundError if the distribution is not installed. ```python from importlib.metadata import version as _version __version__ = _version("strawberry-alchemy") ``` -------------------------------- ### Usage example: wiring IDs to models for permission checks Source: https://github.com/alteian/strawberry-alchemy Shows how to use map_ids_to_models in a mutation: extract global IDs from input, load resources with loaders, then fetch and check permissions with OwnerPermission and IsAuthenticated. ```python from strawberry_alchemy import ( ResourceInstances, extract_global_ids_from_info, fetch_and_check_permissions, map_ids_to_models, OwnerPermission, IsAuthenticated, ) ids = extract_global_ids_from_info(data=vars(input)) # decode all *._id bag = await map_ids_to_models(ids, loaders={"post_id": load_post}) # load resources await fetch_and_check_permissions(info, [IsAuthenticated(), OwnerPermission()], resource_instances=bag) ``` -------------------------------- ### Usage example for SliceMetadata.from_arguments Source: https://github.com/alteian/strawberry-alchemy Shows how to create a SliceMetadata instance from pagination arguments and use it to fetch rows with a limit and offset. The fetch_limit property returns requested_count + 1 to detect has_next_page. ```python meta = SliceMetadata.from_arguments(info=info, after=after, first=10) rows = await session.execute(select(Post).limit(meta.fetch_limit).offset(meta.start or 0)) ``` -------------------------------- ### Manual analyzer attachment with error handling Source: https://github.com/alteian/strawberry-alchemy Shows how to attach a QueryAnalyzer manually to a QueryOptimizer. The try/finally ensures the report is fetched even when the query fails. The example prints the summary and each query's label, SQL, and duration. ```python import logging from strawberry_alchemy.optimizer.query_analyzer import QueryAnalyzer analyzer = QueryAnalyzer(log_sql=True, log_level=logging.DEBUG) optimizer = QueryOptimizer(info, session, analyzer=analyzer) try: await optimizer.optimize_query(model=Post, strawberry_type=PostType) finally: report = analyzer.report() print(report.summary()) for q in report.queries: print(f"[{q.label}] {q.sql} ({q.duration_ms:.1f}ms)") ``` -------------------------------- ### Print package version Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/api-reference.md Imports the strawberry_alchemy package and prints its version. Useful for verifying installation. ```python import strawberry_alchemy print(strawberry_alchemy.__version__) ``` -------------------------------- ### Usage example: parse selection tree and extract targets Source: https://github.com/alteian/strawberry-alchemy Shows how to classify a normalized selection and extract node fields and dotted-path dependency trees. Uses parse_selection_tree, selection_to_model_fields, extract_at_path, and source_path_to_dependency_tree. ```python from strawberry_alchemy import FieldPath, extract_at_path, parse_selection_tree, selection_to_model_fields tree = parse_selection_tree({"edges": {"node": {"id": True, "comments": {"id": True}}}, "pageInfo": {}, "totalCount": True}) if type(tree).__name__ == "RelayConnectionSelection": node_fields = selection_to_model_fields(tree) # {"id": True, "comments": {"id": True}} comments = extract_at_path(node_fields, FieldPath("comments")) # {"id": True} # dotted-path dependency tree for target_field_path narrowing: tree_dict = source_path_to_dependency_tree("comments.items") # {"comments": {"items": True}} ``` -------------------------------- ### resolve_nodes usage example Source: https://github.com/alteian/strawberry-alchemy Shows how to call resolve_nodes directly, passing node IDs and an order option. The order parameter is forwarded to QueryOptimizer.optimize_query. ```python results = await PostType.resolve_nodes(info=info, node_ids=["a1", "b2"], order={"created_at": Ordering.DESC}) ``` -------------------------------- ### Minimal application schema with ListResult and StrawberryConfig Source: https://github.com/alteian/strawberry-alchemy Defines a minimal Strawberry GraphQL schema using the ListResult type and StrawberryConfig with auto_camel_case and relay_max_results. A full runnable example is available in the repository at examples/blog/. ```python import strawberry from strawberry.schema.config import StrawberryConfig from strawberry_alchemy import ListResult from my_app.types import PostType from my_app.queries import posts @strawberry.type class Query: posts: ListResult[PostType] = strawberry.field(resolver=posts) schema = strawberry.Schema( query=Query, config=StrawberryConfig(auto_camel_case=True, relay_max_results=100), ) ``` -------------------------------- ### Usage example for resolve_connection in a Strawberry field Source: https://github.com/alteian/strawberry-alchemy Shows how to call `resolve_connection` from a Strawberry field resolver. Passes `info` and pagination/filter arguments (`after`, `before`, `first`, `last`, `filters`) to return an `OptimizedListConnection[PostType]`. ```python @strawberry.field async def connection( self, info: Info, after: str | None = None, before: str | None = None, first: int | None = None, last: int | None = None, filters: PostFilter | None = strawberry.UNSET, ) -> OptimizedListConnection[PostType]: return await PostType.resolve_connection( info=info, after=after, before=before, first=first, last=last, filters=filters, ) ``` -------------------------------- ### Usage: define a model with Mapped-style hints Source: https://github.com/alteian/strawberry-alchemy Example of defining a model class that inherits from Base. Uses PostgreSQL UUID primary key and ForeignKey. Requires importing uuid, ForeignKey, UUID, Mapped, mapped_column, and Base. ```python import uuid from sqlalchemy import ForeignKey from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import Mapped, mapped_column from strawberry_alchemy.models import Base class Post(Base): user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("user.id")) title: Mapped[str] body: Mapped[str] ``` -------------------------------- ### Usage of Edge and PageInfo Source: https://github.com/alteian/strawberry-alchemy Example usage of Edge and PageInfo from strawberry_alchemy. Edge takes node and cursor; PageInfo takes has_next_page, has_previous_page, start_cursor, end_cursor. ```python from strawberry_alchemy import Edge, PageInfo edge = Edge(node=post_type, cursor="YXJyYXljb25uZWN0aW9uOjA=") page_info = PageInfo(has_next_page=False, has_previous_page=False, start_cursor=edge.cursor, end_cursor=edge.cursor) ``` -------------------------------- ### Defining a composed filter input with PostFilter Source: https://github.com/alteian/strawberry-alchemy Shows how to define a composed filter input class using strawberry.input and the provided filter types. Each field defaults to strawberry.UNSET, and custom filters can be added as regular fields. This example is from examples/blog/filters.py. ```python import strawberry from strawberry_alchemy.filtering import IDFilter, StringFilter @strawberry.input class PostFilter: title: StringFilter | None = strawberry.UNSET body: StringFilter | None = strawberry.UNSET user_id: IDFilter | None = strawberry.UNSET title_search: str | None = strawberry.UNSET # custom filter (CUSTOM_FILTERS) AND: list[PostFilter] | None = strawberry.UNSET OR: list[PostFilter] | None = strawberry.UNSET ``` -------------------------------- ### apply_rls_context usage example Source: https://github.com/alteian/strawberry-alchemy Populates tenant/ownership context at request start by passing a mapping of GUC names to values. ```python from strawberry_alchemy.postgres import apply_rls_context await apply_rls_context(session, {"user_id": user.id, "tenant_id": tenant_id}) ``` -------------------------------- ### Compose filter inputs with StringFilter, IDFilter, AND/OR Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/getting-started.md Compose operator inputs (StringFilter, IDFilter, etc.) into a @strawberry.input. AND/OR lists nest; non-column fields can be handled via CUSTOM_FILTERS on the type (see next section). ```python # filters.py import strawberry from strawberry_alchemy import IDFilter, StringFilter @strawberry.input class PostFilter: title: StringFilter | None = strawberry.UNSET body: StringFilter | None = strawberry.UNSET user_id: IDFilter | None = strawberry.UNSET title_search: str | None = strawberry.UNSET AND: list["PostFilter"] | None = strawberry.UNSET OR: list["PostFilter"] | None = strawberry.UNSET ``` -------------------------------- ### Build and preview documentation Source: https://github.com/alteian/strawberry-alchemy/blob/master/CONTRIBUTING.md Build the MkDocs Material documentation with make docs (strict mode) and serve it with live reload using make docs-serve. ```bash make docs # mkdocs build --strict → site/ make docs-serve # live reload ``` -------------------------------- ### Define schemas with BaseSchema for Comment and Post Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/getting-started.md Defines CommentSchema and PostSchema using strawberry-alchemy's BaseSchema. PostSchema includes a soft delete field (deleted_at) and a comments relationship to CommentSchema. These schemas are used by repositories to map database models. ```python # schemas.py import uuid from datetime import datetime from strawberry_alchemy import BaseSchema class CommentSchema(BaseSchema): id: uuid.UUID | None = None post_id: uuid.UUID | None = None body: str class PostSchema(BaseSchema): id: uuid.UUID | None = None user_id: uuid.UUID title: str body: str deleted_at: datetime | None = None comments: list[CommentSchema] | None = None ``` -------------------------------- ### QueryOptimizer __init__ method Source: https://github.com/alteian/strawberry-alchemy Initializes the optimizer with Strawberry info and an async session. If no analyzer is provided, one is created only when the `QUERY_ANALYZER_ENABLED` environment variable is set; otherwise `analyzer` is `None`. Default access filters are registered. ```python class QueryOptimizer: def __init__( self, info: Info, session: AsyncSession, *, analyzer: QueryAnalyzer | None = None, ) -> None: self.info = info self.session = session self.access_filters: dict[type[Any], type[AccessControlFilter] | AccessControlFilter] = {} self.analyzer: QueryAnalyzer | None if analyzer is not None: self.analyzer = analyzer elif _ANALYZER_ENABLED: self.analyzer = _create_analyzer() else: self.analyzer = None self._register_default_filters() ``` -------------------------------- ### QueryAnalyzer.__init__ Source: https://github.com/alteian/strawberry-alchemy Initializes a QueryAnalyzer instance with optional SQL logging and log level configuration. ```APIDOC ## QueryAnalyzer.__init__ ### Description Initializes a QueryAnalyzer instance with optional SQL logging and log level configuration. ### Method Constructor ### Parameters - **log_sql** (bool) - Optional - Record SQL text/params in events (else ``) - **log_level** (int) - Optional - Level used by `log_report` (logger name `"query_analyzer"`) ### Response Returns a new QueryAnalyzer instance. ``` -------------------------------- ### Define GraphQL types with BaseNodeType and custom filters Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/getting-started.md Defines CommentType and PostType using BaseNodeType, with access filters, custom filters, and an optimized field. Scalar/relationship fields default to strawberry.UNSET so unrequested values are not required on construction. BaseNodeType provides Relay id, created_at, and updated_at. ```python # types.py from __future__ import annotations import uuid from collections.abc import Callable from typing import Annotated, Any, ClassVar import strawberry from sqlalchemy import or_ from strawberry.types import Info from strawberry_alchemy import AnnotateExists, BaseNodeType, optimize_field from .access_filters import CommentAccessFilter, PostAccessFilter def _title_search_filter(model: type[Any], value: Any) -> Any: term = f"%{value}%" return or_(model.title.ilike(term), model.body.ilike(term)) @strawberry.type class CommentType(BaseNodeType): access_filter: ClassVar[type[CommentAccessFilter]] = CommentAccessFilter post_id: uuid.UUID | None = strawberry.UNSET body: str | None = strawberry.UNSET post: Annotated[PostType | None, strawberry.lazy(".types")] = strawberry.UNSET @strawberry.type class PostType(BaseNodeType): access_filter: ClassVar[type[PostAccessFilter]] = PostAccessFilter CUSTOM_FILTERS: ClassVar[dict[str, Callable[..., Any]]] = { "title_search": _title_search_filter, } user_id: uuid.UUID | None = strawberry.UNSET title: str | None = strawberry.UNSET body: str | None = strawberry.UNSET comments: list[Annotated[CommentType, strawberry.lazy(".types")]] | None = strawberry.UNSET @strawberry.field @optimize_field(AnnotateExists("comments")) async def has_comments(self, info: Info) -> bool: return bool(getattr(self, "_comments_exists", False)) ``` -------------------------------- ### Define AccessControlFilter subclasses for Post and Comment Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/getting-started.md Every BaseNodeType requires an AccessControlFilter subclass whose name ends with 'AccessFilter'. It is applied to root queries and nested selectinloads for the model. The apply_filter method returns query.where(False) when context_user is None, otherwise filters by user ownership. ```python # access_filters.py from typing import Any from strawberry_alchemy import AccessControlFilter from .models import Comment, Post class PostAccessFilter(AccessControlFilter): model_class = Post @staticmethod async def apply_filter(query: Any, model: type[Any], context_user: Any) -> Any: if context_user is None: return query.where(False) return query.where(model.user_id == context_user.id) class CommentAccessFilter(AccessControlFilter): model_class = Comment @staticmethod async def apply_filter(query: Any, model: type[Any], context_user: Any) -> Any: if context_user is None: return query.where(False) return query.join(Post, model.post_id == Post.id).where(Post.user_id == context_user.id) ``` -------------------------------- ### Commit, tag, and push release Source: https://github.com/alteian/strawberry-alchemy/blob/master/CONTRIBUTING.md Stage the version files, commit with a release message, create an annotated tag, and push with --follow-tags. CI builds, tests, and publishes to PyPI when a v* tag is pushed. ```bash git add pyproject.toml src/ CHANGELOG.md git commit -m "Release v$(make version)" git tag -a "v$(make version)" -m "Release v$(make version)" git push origin master --follow-tags ``` -------------------------------- ### QueryOptimizer.__init__ Source: https://github.com/alteian/strawberry-alchemy Initializes a QueryOptimizer instance with the Strawberry resolver info and SQLAlchemy async session. Optionally accepts an explicit QueryAnalyzer; otherwise one is created only if the QUERY_ANALYZER_ENABLED environment variable is set. ```APIDOC ## QueryOptimizer.__init__ ### Description Initializes a QueryOptimizer instance with the Strawberry resolver info and SQLAlchemy async session. Optionally accepts an explicit QueryAnalyzer; otherwise one is created only if the QUERY_ANALYZER_ENABLED environment variable is set. ### Method Constructor ### Signature ```python QueryOptimizer( info: Info, session: AsyncSession, *, analyzer: QueryAnalyzer | None = None, ) -> None ``` ### Parameters - **info** (Info) - Required - Strawberry resolver info — supplies `info.context`, `info.schema` (type lookup, `relay_max_results`), and `info.selected_fields` - **session** (AsyncSession) - Required - SQLAlchemy async session used to execute queries - **analyzer** (QueryAnalyzer | None) - Optional - Explicit diagnostics instance; when omitted, one is created only if env `QUERY_ANALYZER_ENABLED` is set ### Usage Example ```python session = await info.context.get_session() optimizer = QueryOptimizer(info, session) optimizer.register_access_filter(Post, PostAccessFilter) ``` ``` -------------------------------- ### Define GraphQL queries with node, list, and connection fields Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/getting-started.md Defines a PostQueries type with node, list, and connection fields using strawberry-alchemy's ListResult and OptimizedListConnection. The node field resolves a single PostType by GlobalID; list and connection support pagination and filters. The Query type exposes posts as a nested PostQueries object. ```python # queries.py import strawberry from strawberry.relay import GlobalID from strawberry.types import Info from strawberry_alchemy import ListResult, OptimizedListConnection from .filters import PostFilter from .types import PostType @strawberry.type class PostQueries: @strawberry.field async def node(self, info: Info, id: GlobalID) -> PostType | None: return await PostType.resolve_node(node_id=id.node_id, info=info) @strawberry.field async def list( self, info: Info, limit: int | None = None, offset: int | None = None, filters: PostFilter | None = strawberry.UNSET, ) -> ListResult[PostType]: return await PostType.resolve_list( info=info, limit=limit, offset=offset, filters=filters ) @strawberry.field async def connection( self, info: Info, after: str | None = None, before: str | None = None, first: int | None = None, last: int | None = None, filters: PostFilter | None = strawberry.UNSET, ) -> OptimizedListConnection[PostType]: return await PostType.resolve_connection( info=info, after=after, before=before, first=first, last=last, filters=filters, ) @strawberry.type class Query: @strawberry.field def posts(self) -> PostQueries: return PostQueries() ``` -------------------------------- ### FieldSelectionDict usage example Source: https://github.com/alteian/strawberry-alchemy Example of a `FieldSelectionDict` value with nested selections for relationships. ```python selected: FieldSelectionDict = { "id": True, "title": True, "comments": {"id": True, "body": True}, } ``` -------------------------------- ### Typical mutation flow Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/mapping-and-schema.md Creates a schema from input, persists via repository, and returns the Strawberry type. For deletes/updates needing permission checks first, see Permissions (prepare_mutation_resources). ```python session = await info.context.get_session() schema = PostSchema.from_input(input, user_id=(await info.context.identity).id) created = await PostRepository(session).create(schema=schema) return created.to_type(PostType) ``` -------------------------------- ### ResourceInstances Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/permissions.md A bag for storing and retrieving resource instances by key. ```APIDOC ## ResourceInstances ### Description A bag for storing and retrieving resource instances by key. ### Methods - **add(key, instance)** - Adds a single instance. - **add_list(key, instances)** - Adds a list of instances. - **get(key)** - Retrieves an instance by key. - **get_id(key)** - Retrieves the ID of an instance by key. - **all()** - Returns all instances. ``` -------------------------------- ### Apply RLS context at start of request Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/postgres-rls.md Application code at the start of a request or unit of work. Wraps apply_rls_context inside a transaction so the GUCs are set locally for that transaction. ```python async with session.begin(): await apply_rls_context(session, {"company_id": ctx.company_id}) ... ``` -------------------------------- ### OwnerPermission.__init__ Source: https://github.com/alteian/strawberry-alchemy Constructor for the OwnerPermission class. Initializes the permission with an owner field and optional resource key. ```APIDOC ## OwnerPermission.__init__ ### Description Constructor for the OwnerPermission class. Initializes the permission with an owner field and optional resource key. ### Method `__init__` ### Parameters #### Constructor Parameters - **owner_field** (`str`) - Optional - Attribute on the instance holding the owner id. Default: `"user_id"`. - **resource_key** (`str | None`) - Optional - Key to look up in `resource_instances`; when `None`, uses the first instance from `all()`. Default: `None`. ### Returns `None` ``` -------------------------------- ### prepare_mutation_resources Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/permissions.md One-shot helper for mutation resolvers that decodes GlobalIDs, loads models, runs permissions, and returns a ResourceInstances bag. ```APIDOC ## prepare_mutation_resources ### Description One-shot helper for mutation resolvers: decodes GlobalIDs from `input_data`, loads models via `loaders`, runs `permissions` against the bag, and returns `ResourceInstances`. ### Method await prepare_mutation_resources(info, input_data, loaders, permissions, id_fields=None) ### Parameters - **info** (GraphQLResolveInfo) - Required - The GraphQL info object. - **input_data** (dict) - Required - The input data containing GlobalIDs. - **loaders** (dict) - Required - A mapping of keys to loader functions that fetch models by ID. - **permissions** (list) - Required - A list of permission objects to check. - **id_fields** (list, optional) - Optional - Overrides which keys are treated as IDs (default: keys ending with `_id`). ### Response Returns a `ResourceInstances` bag containing the loaded resources. ### Request Example ```python await prepare_mutation_resources( info, {"post_id": input.id}, loaders={"post_id": lambda value: repo.get_by_id(value)}, permissions=[ IsAuthenticated(), OwnerPermission(owner_field="user_id", resource_key="post_id"), ], ) ``` ``` -------------------------------- ### Custom cascade handler example (PostDeletionHandler) Source: https://github.com/alteian/strawberry-alchemy Example from examples/blog/deletion.py showing how to override collect_dependents and handle_cascade to delete related Comment rows. The collect_dependents method returns a DependentMap with comment IDs, and handle_cascade executes a bulk delete using those IDs. ```python import uuid from sqlalchemy import delete, select from sqlalchemy.ext.asyncio import AsyncSession from strawberry_alchemy.repository import BaseDeletionHandler, DependentMap class PostDeletionHandler(BaseDeletionHandler[Post]): async def collect_dependents(self, session, entity_id, instance) -> DependentMap: rows = (await session.execute(select(Comment.id).where(Comment.post_id == entity_id))).scalars().all() return {"comments": list(rows)} async def handle_cascade(self, session, entity_id, dependents) -> None: comment_ids = dependents.get("comments") or [] if comment_ids: await session.execute(delete(Comment).where(Comment.id.in_(comment_ids))) ``` -------------------------------- ### SliceMetadata class definition Source: https://github.com/alteian/strawberry-alchemy Pure-python pagination math used by OptimizedListConnection. Key rules: max_results resolves to info.schema.config.relay_max_results when None; Base64 after/before cursors are decoded with strawberry.relay.utils.from_base64; start = int(after_parsed) + 1, end = int(before_parsed); first < 0 or first > max_results raises ValueError; with no bounds, end = (start or 0) + max_results. ```python class SliceMetadata: def __init__(self, start: int | None, end: int | None, requested_count: int | None) -> None: self.start = start self.end = end self.requested_count = requested_count @property def fetch_limit(self) -> int | None: if self.requested_count is not None: return self.requested_count + 1 return None @classmethod def from_arguments( cls, info: Info, before: str | None = None, after: str | None = None, first: int | None = None, last: int | None = None, max_results: int | None = None, ) -> "SliceMetadata": ``` -------------------------------- ### Run local CI pipeline Source: https://github.com/alteian/strawberry-alchemy/blob/master/CONTRIBUTING.md Run the full local CI pipeline with make ci to ensure all checks pass before opening a pull request. ```bash make ci ``` -------------------------------- ### clear_rls_context usage example Source: https://github.com/alteian/strawberry-alchemy Resets scoping after the transaction by clearing the specified GUC names. ```python from strawberry_alchemy.postgres import clear_rls_context # ... transaction work ... await clear_rls_context(session, ["user_id", "tenant_id"]) ``` -------------------------------- ### PostSchema definition with BaseSchema Source: https://github.com/alteian/strawberry-alchemy Schema definition example from examples/blog/schemas.py. Defines a PostSchema with fields including id, user_id, title, body, and comments. ```python import uuid from strawberry_alchemy.schema import BaseSchema class PostSchema(BaseSchema): id: uuid.UUID | None = None user_id: uuid.UUID title: str body: str comments: list[CommentSchema] | None = None ``` -------------------------------- ### QueryOptimizer direct usage Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/queries.md Construct the optimizer yourself when you need a custom path (shared session, manual mapping). ```APIDOC ## QueryOptimizer direct usage ### Description Construct the optimizer yourself when you need a custom path (shared session, manual mapping). ### Method Class instantiation and method calls ### Parameters - **info** (Info) - Required - GraphQL resolver info. - **session** (Session) - Required - SQLAlchemy session. - **model_class** - Required - SQLAlchemy model class. - **strawberry_type** - Required - Strawberry type class. - **kwargs** - Optional - Additional arguments forwarded to `optimize_query`. ### Response Returns a tuple of `result` and `items`. ### Request Example ```python from strawberry_alchemy import QueryOptimizer, map_sqlalchemy_list_to_types async def _get_optimized_result(cls, info: Info, **kwargs): session = await info.context.get_shared_session() # app-specific optimizer = QueryOptimizer(info, session) optimizer.register_access_filter(cls.model_class, cls.access_filter) result = await optimizer.optimize_query( cls.model_class, strawberry_type=cls, **kwargs, ) items = await map_sqlalchemy_list_to_types( result.items, info, cls, result.selected_fields ) return result, items ``` ``` -------------------------------- ### BaseSchema.from_input / schema_from_input Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/mapping-and-schema.md Build a schema (or any Pydantic BaseModel) from a Strawberry input object. ```APIDOC ### Description Build a schema (or any Pydantic `BaseModel`) from a Strawberry input object. Rules: Same-named fields are copied; `relay.GlobalID` → `uuid.UUID` (lists decoded item-wise); Omitted / `UNSET` fields keep model defaults; Explicit `None` is preserved; Keyword arguments always win (inject `actor_user_id`, `company_id`, …). Use plain `BaseModel` command objects via `schema_from_input` in application adapters when you do not want `BaseSchema`. ### Example ```python from strawberry_alchemy import schema_from_input schema = PostSchema.from_input(input, user_id=actor.id) # equivalent: schema = schema_from_input(PostSchema, input, user_id=actor.id) ``` ``` -------------------------------- ### GraphQL query using filter input Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/filtering.md Example GraphQL query that uses the PostFilter input with OR conditions. Demonstrates icontains and exact operators on nested fields. ```graphql query { posts { list(filters: { OR: [ { title: { icontains: "alchemy" } } { userId: { exact: "…" } } ] }) { items { id title } totalCount } } } ``` -------------------------------- ### EmploymentDeletionHandler and delete_employment with hard/soft policy Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/recipes.md Build soft-vs-hard decisions and audit on top of BaseDeletionHandler instead of a second protocol. Keep cascade SQL inside the handler; keep product policy (when hard is allowed) in the application service. ```python class EmploymentDeletionHandler(BaseDeletionHandler[Employment]): async def collect_dependents(self, session, entity_id, instance) -> DependentMap: ... async def handle_cascade(self, session, entity_id, dependents) -> None: ... async def delete_employment(repo, employment_id, *, hard: bool): if hard: report = await repo.delete(id=employment_id, strict=True) audit("hard_delete", report) return report return await repo.soft_delete(id=employment_id) ``` -------------------------------- ### Schema creation and mutation round-trip Source: https://github.com/alteian/strawberry-alchemy Usage example from examples/blog/mutations.py. Creates a PostSchema instance, persists it via PostRepository, and converts to PostType using to_type. ```python schema = PostSchema(title=input.title, body=input.body, user_id=user.id) created = await PostRepository(session).create(schema=schema) return created.to_type(PostType) # BaseSchema.to_type → PostType.from_schema ``` -------------------------------- ### Typical QueryOptimizer construction Source: https://github.com/alteian/strawberry-alchemy Shows the typical construction inside `BaseNodeType` resolvers: obtain the session from `info.context.get_session()`, create the optimizer, and register an access filter for a model class. ```python session = await info.context.get_session() optimizer = QueryOptimizer(info, session) optimizer.register_access_filter(Post, PostAccessFilter) ``` -------------------------------- ### Use prepare_mutation_resources in a mutation resolver Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/permissions.md One-shot helper that decodes GlobalIDs, loads models via loaders, runs permissions against the bag, and returns ResourceInstances. Optional id_fields= overrides which keys are treated as IDs (default: keys ending with _id). ```python await prepare_mutation_resources( info, {"post_id": input.id}, loaders={"post_id": lambda value: repo.get_by_id(value)}, permissions=[ IsAuthenticated(), OwnerPermission(owner_field="user_id", resource_key="post_id"), ], ) ``` -------------------------------- ### Run tests with pytest Source: https://github.com/alteian/strawberry-alchemy/blob/master/CONTRIBUTING.md Run the test suite with make test. Use make test ARGS="-k filter_or" to filter tests. Tests use pytest-asyncio and aiosqlite for in-memory database integration tests. ```bash make test # or: make test ARGS="-k filter_or" ``` -------------------------------- ### ObjectAccessPermission.__init__ Source: https://github.com/alteian/strawberry-alchemy Constructor for the ObjectAccessPermission class. Initializes the permission checker with an access field and an optional resource key. ```APIDOC ## ObjectAccessPermission.__init__ ### Description Constructor for the ObjectAccessPermission class. Initializes the permission checker with an access field and an optional resource key. ### Method Constructor ### Signature ```python def __init__( self, *, access_field: str = "allowed_user_ids", resource_key: str | None = None, ) -> None: ``` ### Parameters - **access_field** (str) - Optional - Attribute holding an iterable of allowed ids (entries may be objects with `.id`). Default: `"allowed_user_ids"`. - **resource_key** (str | None) - Optional - Resource bag lookup key; `None` uses the first instance. Default: `None`. ### Returns None ``` -------------------------------- ### resolve_list usage in a Strawberry field Source: https://github.com/alteian/strawberry-alchemy Example of using resolve_list in a Strawberry field resolver to return a paginated list of posts with optional limit, offset, and filters. ```python @strawberry.field async def posts( self, info: Info, limit: int | None = None, offset: int | None = None, filters: PostFilter | None = strawberry.UNSET, ) -> ListResult[PostType]: return await PostType.resolve_list(info=info, limit=limit, offset=offset, filters=filters) ``` -------------------------------- ### Usage of Ordering in a Strawberry input Source: https://github.com/alteian/strawberry-alchemy Shows how to use Ordering in a Strawberry input for ordering a connection/list. The resolver call passes an Ordering value to the order parameter. ```python import strawberry from strawberry_alchemy import Ordering @strawberry.input class PostOrder: created_at: Ordering | None = strawberry.UNSET title: Ordering | None = strawberry.UNSET # In a resolver: result = await PostType.resolve_list(info=info, order=PostOrder(created_at=Ordering.DESC)) ``` -------------------------------- ### SQL: CREATE POLICY for tenant isolation Source: https://github.com/alteian/strawberry-alchemy Example DDL policy for tenant isolation using current_setting('app.tenant_id', true). Note: DDL policy side is out of scope for this module. ```sql CREATE POLICY tenant_isolation ON post USING (tenant_id = current_setting('app.tenant_id', true)); ``` -------------------------------- ### resolve_node usage in a Strawberry field Source: https://github.com/alteian/strawberry-alchemy Example of using resolve_node inside a Strawberry field resolver. It extracts the node_id from a GlobalID and passes it along with the info object. ```python @strawberry.field async def node(self, info: Info, id: GlobalID) -> PostType | None: return await PostType.resolve_node(node_id=id.node_id, info=info) ``` -------------------------------- ### Architecture flow diagram (Mermaid) Source: https://github.com/alteian/strawberry-alchemy/blob/master/docs/index.md Shows how the QueryOptimizer, AccessControlFilter, FilterBuilder, @optimize_field hints, and SQLAlchemy query fit together to map rows to BaseNodeType. ```mermaid flowchart LR Client[GraphQL client] --> Resolver[resolve_list / resolve_connection] Resolver --> Opt[QueryOptimizer] Opt --> ACL[AccessControlFilter] Opt --> Filters[FilterBuilder] Opt --> Hints["@optimize_field hints"] Opt --> SQL[SQLAlchemy query] SQL --> Map[map_sqlalchemy_to_type] Map --> Type[BaseNodeType] ```