strawberry-sqlalchemy: Can't get relationships to work. Unexpected type ForwardRef?
python 3.11 sqlalchemy 2.0.23 strawberry-graphql 0.216.0 strawberry-sqlalchemy-mapper 0.4.0
Trying to use this mapper and was playing around with some basics but can’t get relationships to work. It doesn’t seem like i do something wrong, this is literally the example from readme:
models.py
from sqlalchemy import Column, UUID, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class Employee(Base):
__tablename__ = "employee"
id = Column(UUID, primary_key=True)
name = Column(String, nullable=False)
password_hash = Column(String, nullable=False)
department_id = Column(UUID, ForeignKey("department.id"))
department = relationship("Department", back_populates="employees")
class Department(Base):
__tablename__ = "department"
id = Column(UUID, primary_key=True)
name = Column(String, nullable=False)
employees = relationship("Employee", back_populates="department")
app.py
from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter
import strawberry, models
from strawberry_sqlalchemy_mapper import StrawberrySQLAlchemyMapper
strawberry_sqlalchemy_mapper = StrawberrySQLAlchemyMapper()
@strawberry_sqlalchemy_mapper.type(models.Employee)
class Employee:
__exclude__ = ["password_hash"]
@strawberry_sqlalchemy_mapper.type(models.Department)
class Department:
pass
@strawberry.type
class Query:
@strawberry.field
def departments(self) -> Department:
return Department(name="Test", employees=[Employee(name="1"), Employee(name="2")])
strawberry_sqlalchemy_mapper.finalize()
schema = strawberry.Schema(
query=Query,
)
app = FastAPI()
graphql_app = GraphQLRouter(schema)
app.include_router(graphql_app, prefix='/graphql')
main.py
import uvicorn
from app import app
if __name__ == "__main__":
uvicorn.run(app, port=5000, log_level="info")
Got this error:
Traceback (most recent call last):
File "/usr/local/lib/python3.11/site-packages/graphql/type/definition.py", line 808, in fields
fields = resolve_thunk(self._fields)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/graphql/type/definition.py", line 300, in resolve_thunk
return thunk() if callable(thunk) else thunk
^^^^^^^
File "/usr/local/lib/python3.11/site-packages/strawberry/schema/schema_converter.py", line 514, in <lambda>
fields=lambda: self.get_graphql_fields(object_type),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/strawberry/schema/schema_converter.py", line 373, in get_graphql_fields
return _get_thunk_mapping(
^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/strawberry/schema/schema_converter.py", line 133, in _get_thunk_mapping
thunk_mapping[name_converter(field)] = field_converter(
^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/strawberry/schema/schema_converter.py", line 314, in from_field
self.from_maybe_optional(
File "/usr/local/lib/python3.11/site-packages/strawberry/schema/schema_converter.py", line 768, in from_maybe_optional
return GraphQLNonNull(self.from_type(type_))
^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/strawberry/schema/schema_converter.py", line 801, in from_type
raise TypeError(f"Unexpected type '{type_}'")
TypeError: Unexpected type 'ForwardRef('Employee')'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/app/app.py", line 28, in <module>
schema = strawberry.Schema(
^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/strawberry/schema/schema.py", line 141, in __init__
self._schema = GraphQLSchema(
^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/graphql/type/schema.py", line 224, in __init__
collect_referenced_types(query)
File "/usr/local/lib/python3.11/site-packages/graphql/type/schema.py", line 433, in collect_referenced_types
collect_referenced_types(field.type)
File "/usr/local/lib/python3.11/site-packages/graphql/type/schema.py", line 433, in collect_referenced_types
collect_referenced_types(field.type)
File "/usr/local/lib/python3.11/site-packages/graphql/type/schema.py", line 433, in collect_referenced_types
collect_referenced_types(field.type)
File "/usr/local/lib/python3.11/site-packages/graphql/type/schema.py", line 432, in collect_referenced_types
for field in named_type.fields.values():
^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/functools.py", line 1001, in __get__
val = self.func(instance)
^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/graphql/type/definition.py", line 811, in fields
raise cls(f"{self.name} fields cannot be resolved. {error}") from error
TypeError: EmployeeEdge fields cannot be resolved. Unexpected type 'ForwardRef('Employee')'
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 1
- Comments: 15 (8 by maintainers)
Commits related to this issue
- fix: Use lazy type to specialize `Edge`/`Connection` Use a lazy type to properly resolve and specialize the `Edge`/`Connection` types that are created from the model. The reason we are using a subcl... — committed to bellini666/strawberry-sqlalchemy by bellini666 3 years ago
- fix: Use lazy type to specialize `Edge`/`Connection` Use a lazy type to properly resolve and specialize the `Edge`/`Connection` types that are created from the model. The reason we are using a subcl... — committed to bellini666/strawberry-sqlalchemy by bellini666 3 years ago
- fix: Use lazy type to specialize `Edge`/`Connection` (#106) Use a lazy type to properly resolve and specialize the `Edge`/`Connection` types that are created from the model. The reason we are usi... — committed to strawberry-graphql/strawberry-sqlalchemy by bellini666 3 years ago
- fix: Fix missing fields from auto generated connections We changed auto generated edges/connections to inherit from `relay.Edge`/`relay.Connection`, which requires some extra fields to be instantiate... — committed to bellini666/strawberry-sqlalchemy by bellini666 3 years ago
- fix: Fix missing fields from auto generated connections We changed auto generated edges/connections to inherit from `relay.Edge`/`relay.Connection`, which requires some extra fields to be instantiate... — committed to bellini666/strawberry-sqlalchemy by bellini666 3 years ago
- fix: Fix missing fields from auto generated connections We changed auto generated edges/connections to inherit from `relay.Edge`/`relay.Connection`, which requires some extra fields to be instantiate... — committed to bellini666/strawberry-sqlalchemy by bellini666 3 years ago
- fix: Fix missing fields from auto generated connections We changed auto generated edges/connections to inherit from `relay.Edge`/`relay.Connection`, which requires some extra fields to be instantiate... — committed to clutchsecurity/strawberry-sqlalchemy by bellini666 3 years ago
- fix: Fix missing fields from auto generated connections (#137) We changed auto generated edges/connections to inherit from `relay.Edge`/`relay.Connection`, which requires some extra fields to be in... — committed to strawberry-graphql/strawberry-sqlalchemy by bellini666 2 years ago
Got the same issues in my project. A one-to-many relationship not working with
missing 1 required keyword-only argument: 'cursor'. My simple Schema:Downgrading from 0.4.2 to 0.3.1 fixes relationships for the time being. I don’t know the project enough yet to help you on this.
I’ve investigated further. The issue is this change, specifically L289. The node type names are now passed as a
ForwardRefto the generic. This ref is not resolved correctly. https://github.com/strawberry-graphql/strawberry-sqlalchemy/blob/4fa950fac41b56cb48b82d78a69b625f3f92afd3/src/strawberry_sqlalchemy_mapper/mapper.py#L278-L293Since
relay.Edgeis generic, we save the value of the TypeVar for the node type inside ofStrawberryField.specialized_type_var_mapto later replace it inStrawberryField.resolve_type:https://github.com/strawberry-graphql/strawberry/blob/aad305b0036de8bfd4d08ef9571aee68f04eb0d1/strawberry/field.py#L360-L375
The problem in this case: the mapped type is not a
StrawberryType, but a ForwardRef equaling the type name we expect it to be. This cannot be resolved, because the generic resolver does not convert the ForwardRef into a StrawberryAnnotation to call evaluate on it.I did this as a test, but this yielded another error: the type
Employeeis not defined in the scope. This is because we have no strawberry.lazy info about the actual location of the typeEmployeebecause we just expect that it will exist under this name later.I’m still looking for a quick and easy fix, but long-term I see this being fixed through one of these options:
For me personally, a central registry is the preferred approach since it gives full control over the way we access types. This is a mid-term effort and requires heavy refactoring, so having something that works short-term to fix the occurring issues would be preferable.
/cc @mattalbr
Thanks for the report! I’ll try to look into it this weekend. Has anyone gathered some more detail of what could have caused the issue? That would really help me dive straight into the fixing 🙂
+1
Have the same exception