strawberry-graphql / strawberry

A GraphQL library for Python that leverages type annotations 🍓
https://strawberry.rocks
MIT License
4.02k stars 533 forks source link

PEP 484 Forward References is causing an Error #2539

Closed besteman closed 1 year ago

besteman commented 1 year ago

We have released updated to SQLalchemy 2 and we are rewriting our schema to use the Mapped feature instead of Column. We are doing this so we can get better typing checks. https://docs.sqlalchemy.org/en/20/changelog/whatsnew_20.html#orm-declarative-models

For example, we have two tables:

class Material(Base):
    __tablename__ = "material"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
    )
    additional columns........
    queries: Mapped["Query"] = relationship("Query", cascade="all, delete")

class Query(Base):
    __tablename__ = "query"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
    )
    material_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), ForeignKey("material.id", ondelete="CASCADE")
    )
    additional columns........
    material: Mapped["Material"] = relationship("Material", back_populates="queries")

We have updated the relationships of queries: Mapped["Query"] and material: Mapped["Material"].

We have the strawberry types here:

@strawberry.type
class Query:
    id: uuid.UUID
    parts: list[QueryPart]

@strawberry.type
class Material:
    id: uuid.UUID
    queries: list[Query]

Describe the Bug

When I have double quotes, queries: Mapped["Query"], we get this error:

 2023-02-13 19:42:13,065 ERROR: [strawberry.execution] Expected Iterable, but did not find one for field 'Material.queries'.
api       |
api       | GraphQL request:4:5
api       | 4 |     queries {
api       |   |     ^
api       | 5 |       parts {

When I remove the double quotes, queries: Mapped[Query], and move the class Query to the top of the file it works as expected.

How do I use the PEP 484 Forward References with Strawberry? https://peps.python.org/pep-0484/#forward-references Or is there something else I am missing?

System Information

Additional Context

Have made a post of Discord as well: https://discord.com/channels/689806334337482765/1074780506413088939/1074780506413088939

Upvote & Fund

Fund with Polar

besteman commented 1 year ago

I found the problem. It was me.

it needs to be material: Mapped[list["Material"]]