Skip to content

Commit 161e49f

Browse files
authored
Merge branch 'master' into id-conversion-changes
2 parents b0a9b84 + 1436807 commit 161e49f

File tree

7 files changed

+172
-3
lines changed

7 files changed

+172
-3
lines changed

README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,21 @@ class Query(graphene.ObjectType):
6363
schema = graphene.Schema(query=Query)
6464
```
6565

66+
We need a database session first:
67+
68+
```python
69+
from sqlalchemy import (create_engine)
70+
from sqlalchemy.orm import (scoped_session, sessionmaker)
71+
72+
engine = create_engine('sqlite:///database.sqlite3', convert_unicode=True)
73+
db_session = scoped_session(sessionmaker(autocommit=False,
74+
autoflush=False,
75+
bind=engine))
76+
# We will need this for querying, Graphene extracts the session from the base.
77+
# Alternatively it can be provided in the GraphQLResolveInfo.context dictionary under context["session"]
78+
Base.query = db_session.query_property()
79+
```
80+
6681
Then you can simply query the schema:
6782

6883
```python

graphene_sqlalchemy/converter.py

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,14 @@
77

88
from sqlalchemy import types as sqa_types
99
from sqlalchemy.dialects import postgresql
10+
from sqlalchemy.orm import (
11+
ColumnProperty,
12+
RelationshipProperty,
13+
class_mapper,
14+
interfaces,
15+
strategies,
16+
)
1017
from sqlalchemy.ext.hybrid import hybrid_property
11-
from sqlalchemy.orm import interfaces, strategies
1218

1319
import graphene
1420
from graphene.types.json import JSONString
@@ -109,6 +115,49 @@ def is_column_nullable(column):
109115
return bool(getattr(column, "nullable", True))
110116

111117

118+
def convert_sqlalchemy_association_proxy(
119+
parent,
120+
assoc_prop,
121+
obj_type,
122+
registry,
123+
connection_field_factory,
124+
batching,
125+
resolver,
126+
**field_kwargs,
127+
):
128+
def dynamic_type():
129+
prop = class_mapper(parent).attrs[assoc_prop.target_collection]
130+
scalar = not prop.uselist
131+
model = prop.mapper.class_
132+
attr = class_mapper(model).attrs[assoc_prop.value_attr]
133+
134+
if isinstance(attr, ColumnProperty):
135+
field = convert_sqlalchemy_column(attr, registry, resolver, **field_kwargs)
136+
if not scalar:
137+
# repackage as List
138+
field.__dict__["_type"] = graphene.List(field.type)
139+
return field
140+
elif isinstance(attr, RelationshipProperty):
141+
return convert_sqlalchemy_relationship(
142+
attr,
143+
obj_type,
144+
connection_field_factory,
145+
field_kwargs.pop("batching", batching),
146+
assoc_prop.value_attr,
147+
**field_kwargs,
148+
).get_type()
149+
else:
150+
raise TypeError(
151+
"Unsupported association proxy target type: {} for prop {} on type {}. "
152+
"Please disable the conversion of this field using an ORMField.".format(
153+
type(attr), assoc_prop, obj_type
154+
)
155+
)
156+
# else, not supported
157+
158+
return graphene.Dynamic(dynamic_type)
159+
160+
112161
def convert_sqlalchemy_relationship(
113162
relationship_prop,
114163
obj_type,

graphene_sqlalchemy/tests/models.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
Table,
1818
func,
1919
)
20+
from sqlalchemy.ext.associationproxy import association_proxy
2021
from sqlalchemy.ext.declarative import declarative_base
2122
from sqlalchemy.ext.hybrid import hybrid_property
2223
from sqlalchemy.orm import backref, column_property, composite, mapper, relationship
@@ -77,6 +78,18 @@ def __repr__(self):
7778
return "{} {}".format(self.first_name, self.last_name)
7879

7980

81+
class ProxiedReporter(Base):
82+
__tablename__ = "reporters_error"
83+
id = Column(Integer(), primary_key=True)
84+
first_name = Column(String(30), doc="First name")
85+
last_name = Column(String(30), doc="Last name")
86+
reporter_id = Column(Integer(), ForeignKey("reporters.id"))
87+
reporter = relationship("Reporter", uselist=False)
88+
89+
# This is a hybrid property, we don't support proxies on hybrids yet
90+
composite_prop = association_proxy("reporter", "composite_prop")
91+
92+
8093
class Reporter(Base):
8194
__tablename__ = "reporters"
8295

@@ -134,6 +147,8 @@ def hybrid_prop_list(self) -> List[int]:
134147
CompositeFullName, first_name, last_name, doc="Composite"
135148
)
136149

150+
headlines = association_proxy("articles", "headline")
151+
137152

138153
class Article(Base):
139154
__tablename__ = "articles"
@@ -144,6 +159,7 @@ class Article(Base):
144159
readers = relationship(
145160
"Reader", secondary="articles_readers", back_populates="articles"
146161
)
162+
recommended_reads = association_proxy("reporter", "articles")
147163

148164

149165
class Reader(Base):

graphene_sqlalchemy/tests/test_converter.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
)
2626
from .utils import wrap_select_func
2727
from ..converter import (
28+
convert_sqlalchemy_association_proxy,
2829
convert_sqlalchemy_column,
2930
convert_sqlalchemy_composite,
3031
convert_sqlalchemy_hybrid_method,
@@ -41,6 +42,7 @@
4142
CompositeFullName,
4243
CustomColumnModel,
4344
Pet,
45+
ProxiedReporter,
4446
Reporter,
4547
ShoppingCart,
4648
ShoppingCartItem,
@@ -674,6 +676,64 @@ class Meta:
674676
assert graphene_type.type == A
675677

676678

679+
def test_should_convert_association_proxy():
680+
class ReporterType(SQLAlchemyObjectType):
681+
class Meta:
682+
model = Reporter
683+
684+
class ArticleType(SQLAlchemyObjectType):
685+
class Meta:
686+
model = Article
687+
688+
field = convert_sqlalchemy_association_proxy(
689+
Reporter,
690+
Reporter.headlines,
691+
ReporterType,
692+
get_global_registry(),
693+
default_connection_field_factory,
694+
True,
695+
mock_resolver,
696+
)
697+
assert isinstance(field, graphene.Dynamic)
698+
assert isinstance(field.get_type().type, graphene.List)
699+
assert field.get_type().type.of_type == graphene.String
700+
701+
dynamic_field = convert_sqlalchemy_association_proxy(
702+
Article,
703+
Article.recommended_reads,
704+
ArticleType,
705+
get_global_registry(),
706+
default_connection_field_factory,
707+
True,
708+
mock_resolver,
709+
)
710+
dynamic_field_type = dynamic_field.get_type().type
711+
assert isinstance(dynamic_field, graphene.Dynamic)
712+
assert isinstance(dynamic_field_type, graphene.NonNull)
713+
assert isinstance(dynamic_field_type.of_type, graphene.List)
714+
assert isinstance(dynamic_field_type.of_type.of_type, graphene.NonNull)
715+
assert dynamic_field_type.of_type.of_type.of_type == ArticleType
716+
717+
718+
def test_should_throw_error_association_proxy_unsupported_target():
719+
class ProxiedReporterType(SQLAlchemyObjectType):
720+
class Meta:
721+
model = ProxiedReporter
722+
723+
field = convert_sqlalchemy_association_proxy(
724+
ProxiedReporter,
725+
ProxiedReporter.composite_prop,
726+
ProxiedReporterType,
727+
get_global_registry(),
728+
default_connection_field_factory,
729+
True,
730+
mock_resolver,
731+
)
732+
733+
with pytest.raises(TypeError):
734+
field.get_type()
735+
736+
677737
def test_should_postgresql_uuid_convert():
678738
assert get_field(postgresql.UUID()).type == graphene.UUID
679739

graphene_sqlalchemy/tests/test_query.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ async def resolve_reporters(self, _info):
8080
columnProp
8181
hybridProp
8282
compositeProp
83+
headlines
8384
}
8485
reporters {
8586
firstName
@@ -92,6 +93,7 @@ async def resolve_reporters(self, _info):
9293
"hybridProp": "John",
9394
"columnProp": 2,
9495
"compositeProp": "John Doe",
96+
"headlines": ["Hi!"],
9597
},
9698
"reporters": [{"firstName": "John"}, {"firstName": "Jane"}],
9799
}

graphene_sqlalchemy/tests/test_types.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,8 @@ class Meta:
138138
"pets",
139139
"articles",
140140
"favorite_article",
141+
# AssociationProxy
142+
"headlines",
141143
]
142144
)
143145

@@ -206,6 +208,16 @@ class Meta:
206208
assert favorite_article_field.type().type == ArticleType
207209
assert favorite_article_field.type().description is None
208210

211+
# assocation proxy
212+
assoc_field = ReporterType._meta.fields["headlines"]
213+
assert isinstance(assoc_field, Dynamic)
214+
assert isinstance(assoc_field.type().type, List)
215+
assert assoc_field.type().type.of_type == String
216+
217+
assoc_field = ArticleType._meta.fields["recommended_reads"]
218+
assert isinstance(assoc_field, Dynamic)
219+
assert assoc_field.type().type == ArticleType.connection
220+
209221

210222
def test_sqlalchemy_override_fields():
211223
@convert_sqlalchemy_composite.register(CompositeFullName)
@@ -275,6 +287,7 @@ class Meta:
275287
"hybrid_prop_float",
276288
"hybrid_prop_bool",
277289
"hybrid_prop_list",
290+
"headlines",
278291
]
279292
)
280293

@@ -390,6 +403,7 @@ class Meta:
390403
"pets",
391404
"articles",
392405
"favorite_article",
406+
"headlines",
393407
]
394408
)
395409

@@ -510,7 +524,7 @@ class Meta:
510524

511525
assert issubclass(CustomReporterType, ObjectType)
512526
assert CustomReporterType._meta.model == Reporter
513-
assert len(CustomReporterType._meta.fields) == 17
527+
assert len(CustomReporterType._meta.fields) == 18
514528

515529

516530
# Test Custom SQLAlchemyObjectType with Custom Options

graphene_sqlalchemy/types.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from typing import Any
44

55
import sqlalchemy
6+
from sqlalchemy.ext.associationproxy import AssociationProxy
67
from sqlalchemy.ext.hybrid import hybrid_property
78
from sqlalchemy.orm import ColumnProperty, CompositeProperty, RelationshipProperty
89
from sqlalchemy.orm.exc import NoResultFound
@@ -16,6 +17,7 @@
1617
from graphene.utils.orderedtype import OrderedType
1718

1819
from .converter import (
20+
convert_sqlalchemy_association_proxy,
1921
convert_sqlalchemy_column,
2022
convert_sqlalchemy_composite,
2123
convert_sqlalchemy_hybrid_method,
@@ -152,7 +154,7 @@ def construct_fields(
152154
+ [
153155
(name, item)
154156
for name, item in inspected_model.all_orm_descriptors.items()
155-
if isinstance(item, hybrid_property)
157+
if isinstance(item, hybrid_property) or isinstance(item, AssociationProxy)
156158
]
157159
+ inspected_model.relationships.items()
158160
)
@@ -230,6 +232,17 @@ def construct_fields(
230232
field = convert_sqlalchemy_composite(attr, registry, resolver)
231233
elif isinstance(attr, hybrid_property):
232234
field = convert_sqlalchemy_hybrid_method(attr, resolver, **orm_field.kwargs)
235+
elif isinstance(attr, AssociationProxy):
236+
field = convert_sqlalchemy_association_proxy(
237+
model,
238+
attr,
239+
obj_type,
240+
registry,
241+
connection_field_factory,
242+
batching,
243+
resolver,
244+
**orm_field.kwargs
245+
)
233246
else:
234247
raise Exception("Property type is not supported") # Should never happen
235248

0 commit comments

Comments
 (0)