Skip to content

Road to 2.0 #57

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Aug 27, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,4 @@ deploy:
tags: true
password:
secure: q0ey31cWljGB30l43aEd1KIPuAHRutzmsd2lBb/2zvD79ReBrzvCdFAkH2xcyo4Volk3aazQQTNUIurnTuvBxmtqja0e+gUaO5LdOcokVdOGyLABXh7qhd2kdvbTDWgSwA4EWneLGXn/SjXSe0f3pCcrwc6WDcLAHxtffMvO9gulpYQtUoOqXfMipMOkRD9iDWTJBsSo3trL70X1FHOVr6Yqi0mfkX2Y/imxn6wlTWRz28Ru94xrj27OmUnCv7qcG0taO8LNlUCquNFAr2sZ+l+U/GkQrrM1y+ehPz3pmI0cCCd7SX/7+EG9ViZ07BZ31nk4pgnqjmj3nFwqnCE/4IApGnduqtrMDF63C9TnB1TU8oJmbbUCu4ODwRpBPZMnwzaHsLnrpdrB89/98NtTfujdrh3U5bVB+t33yxrXVh+FjgLYj9PVeDixpFDn6V/Xcnv4BbRMNOhXIQT7a7/5b99RiXBjCk6KRu+Jdu5DZ+3G4Nbr4oim3kZFPUHa555qbzTlwAfkrQxKv3C3OdVJR7eGc9ADsbHyEJbdPNAh/T+xblXTXLS3hPYDvgM+WEGy3CytBDG3JVcXm25ZP96EDWjweJ7MyfylubhuKj/iR1Y1wiHeIsYq9CqRrFQUWL8gFJBfmgjs96xRXXXnvyLtKUKpKw3wFg5cR/6FnLeYZ8k=
distributions: "sdist bdist_wheel"
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
Please read [UPGRADE-v1.0.md](https://github.com/graphql-python/graphene/blob/master/UPGRADE-v1.0.md)
to learn how to upgrade to Graphene `1.0`.
Please read [UPGRADE-v2.0.md](https://github.com/graphql-python/graphene/blob/master/UPGRADE-v2.0.md)
to learn how to upgrade to Graphene `2.0`.

---

Expand All @@ -13,7 +13,7 @@ A [SQLAlchemy](http://www.sqlalchemy.org/) integration for [Graphene](http://gra
For instaling graphene, just run this command in your shell

```bash
pip install "graphene-sqlalchemy>=1.0"
pip install "graphene-sqlalchemy>=2.0"
```

## Examples
Expand Down Expand Up @@ -47,8 +47,8 @@ class User(SQLAlchemyObjectType):
class Query(graphene.ObjectType):
users = graphene.List(User)

def resolve_users(self, args, context, info):
query = User.get_query(context) # SQLAlchemy query
def resolve_users(self, info):
query = User.get_query(info.context) # SQLAlchemy query
return query.all()

schema = graphene.Schema(query=Query)
Expand Down
10 changes: 5 additions & 5 deletions README.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Please read
`UPGRADE-v1.0.md <https://github.com/graphql-python/graphene/blob/master/UPGRADE-v1.0.md>`__
to learn how to upgrade to Graphene ``1.0``.
`UPGRADE-v2.0.md <https://github.com/graphql-python/graphene/blob/master/UPGRADE-v2.0.md>`__
to learn how to upgrade to Graphene ``2.0``.

--------------

Expand All @@ -17,7 +17,7 @@ For instaling graphene, just run this command in your shell

.. code:: bash

pip install "graphene-sqlalchemy>=1.0"
pip install "graphene-sqlalchemy>=2.0"

Examples
--------
Expand Down Expand Up @@ -53,8 +53,8 @@ following:
class Query(graphene.ObjectType):
users = graphene.List(User)

def resolve_users(self, args, context, info):
query = User.get_query(context) # SQLAlchemy query
def resolve_users(self, info):
query = User.get_query(info.context) # SQLAlchemy query
return query.all()

schema = graphene.Schema(query=Query)
Expand Down
13 changes: 9 additions & 4 deletions graphene_sqlalchemy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@
get_session
)

__all__ = ['SQLAlchemyObjectType',
'SQLAlchemyConnectionField',
'get_query',
'get_session']
__version__ = '2.0.dev2017073101'

__all__ = [
'__version__',
'SQLAlchemyObjectType',
'SQLAlchemyConnectionField',
'get_query',
'get_session'
]
11 changes: 6 additions & 5 deletions graphene_sqlalchemy/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

from graphene import (ID, Boolean, Dynamic, Enum, Field, Float, Int, List,
String)
from graphene.relay import is_node
from graphene.types.json import JSONString

from .fields import createConnectionField
Expand Down Expand Up @@ -43,15 +42,17 @@ def dynamic_type():
return Field(_type)
elif (direction == interfaces.ONETOMANY or
direction == interfaces.MANYTOMANY):
if is_node(_type):
if _type._meta.connection:
return createConnectionField(_type)
return Field(List(_type))

return Dynamic(dynamic_type)



def convert_sqlalchemy_hybrid_method(hybrid_item):
return String(description=getattr(hybrid_item, '__doc__', None),
required=False)
return String(description=getattr(hybrid_item, '__doc__', None),
required=False)


def convert_sqlalchemy_composite(composite, registry):
converter = registry.get_converter_for_composite(composite.composite_class)
Expand Down
20 changes: 15 additions & 5 deletions graphene_sqlalchemy/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,24 @@ def model(self):
return self.type._meta.node._meta.model

@classmethod
def get_query(cls, model, context, info, args):
return get_query(model, context)
def get_query(cls, model, info, **args):
return get_query(model, info.context)

@property
def type(self):
from .types import SQLAlchemyObjectType
_type = super(ConnectionField, self).type
assert issubclass(_type, SQLAlchemyObjectType), (
"SQLAlchemyConnectionField only accepts SQLAlchemyObjectType types"
)
assert _type._meta.connection, "The type {} doesn't have a connection".format(_type.__name__)
return _type._meta.connection

@classmethod
def connection_resolver(cls, resolver, connection, model, root, args, context, info):
iterable = resolver(root, args, context, info)
def connection_resolver(cls, resolver, connection, model, root, info, **args):
iterable = resolver(root, info, **args)
if iterable is None:
iterable = cls.get_query(model, context, info, args)
iterable = cls.get_query(model, info, **args)
if isinstance(iterable, Query):
_len = iterable.count()
else:
Expand Down
6 changes: 3 additions & 3 deletions graphene_sqlalchemy/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ def __init__(self):
self._registry_composites = {}

def register(self, cls):
from .types import SQLAlchemyObjectTypeMeta
assert issubclass(type(cls), SQLAlchemyObjectTypeMeta), (
'Only classes of type SQLAlchemyObjectTypeMeta can be registered, ',
from .types import SQLAlchemyObjectType
assert issubclass(cls, SQLAlchemyObjectType), (
'Only classes of type SQLAlchemyObjectType can be registered, ',
'received "{}"'
).format(cls.__name__)
assert cls._meta.registry == self, 'Registry for a Model have to match.'
Expand Down
11 changes: 10 additions & 1 deletion graphene_sqlalchemy/tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ class Reporter(Base):
articles = relationship('Article', backref='reporter')
favorite_article = relationship("Article", uselist=False)

# total = column_property(
# select([
# func.cast(func.count(PersonInfo.id), Float)
# ])
# )


class Article(Base):
__tablename__ = 'articles'
Expand All @@ -43,8 +49,11 @@ class Article(Base):
reporter_id = Column(Integer(), ForeignKey('reporters.id'))


class ReflectedEditor:
class ReflectedEditor(type):
"""Same as Editor, but using reflected table."""
@classmethod
def __subclasses__(cls):
return []

editor_table = Table('editors', Base.metadata, autoload=True)

Expand Down
21 changes: 19 additions & 2 deletions graphene_sqlalchemy/tests/test_converter.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from py.test import raises
from sqlalchemy import Column, Table, case, types
from sqlalchemy import Column, Table, case, types, select, func
from sqlalchemy.dialects import postgresql
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import composite
from sqlalchemy.orm import composite, column_property
from sqlalchemy.sql.elements import Label
from sqlalchemy_utils import ChoiceType, JSONType, ScalarListType

Expand Down Expand Up @@ -136,6 +136,23 @@ def test_should_choice_convert_enum():
assert graphene_type._meta.enum.__members__['en'].value == 'English'


def test_should_columproperty_convert():

Base = declarative_base()

class Test(Base):
__tablename__ = 'test'
id = Column(types.Integer, primary_key=True)
column = column_property(
select([func.sum(func.cast(id, types.Integer))]).where(
id==1
)
)

graphene_type = convert_sqlalchemy_column(Test.column)
assert graphene_type.kwargs['required'] == False


def test_should_scalar_list_convert_list():
assert_column_conversion(ScalarListType(), graphene.List)

Expand Down
9 changes: 4 additions & 5 deletions graphene_sqlalchemy/tests/test_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,18 +270,17 @@ class Meta:

class CreateArticle(graphene.Mutation):

class Input:
class Arguments:
headline = graphene.String()
reporter_id = graphene.ID()

ok = graphene.Boolean()
article = graphene.Field(ArticleNode)

@classmethod
def mutate(cls, instance, args, context, info):
def mutate(self, info, headline, reporter_id):
new_article = Article(
headline=args.get('headline'),
reporter_id=args.get('reporter_id'),
headline=headline,
reporter_id=reporter_id,
)

session.add(new_article)
Expand Down
17 changes: 15 additions & 2 deletions graphene_sqlalchemy/tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import six

from ..registry import Registry
from ..types import SQLAlchemyObjectType, SQLAlchemyObjectTypeMeta
from ..types import SQLAlchemyObjectType
from .models import Article, Reporter

registry = Registry()
Expand Down Expand Up @@ -72,8 +72,21 @@ def test_node_replacedfield():


def test_object_type():


class Human(SQLAlchemyObjectType):
'''Human description'''

pub_date = Int()

class Meta:
model = Article
# exclude_fields = ('id', )
registry = registry
interfaces = (Node, )

assert issubclass(Human, ObjectType)
assert list(Human._meta.fields.keys()) == ['id', 'headline', 'reporter_id', 'reporter', 'pub_date']
assert list(Human._meta.fields.keys()) == ['id', 'headline', 'pub_date', 'reporter_id', 'reporter']
assert is_node(Human)


Expand Down
4 changes: 2 additions & 2 deletions graphene_sqlalchemy/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ def test_get_session():
class Query(ObjectType):
x = String()

def resolve_x(self, args, context, info):
return get_session(context)
def resolve_x(self, info):
return get_session(info.context)

query = '''
query ReporterQuery {
Expand Down
Loading