22from promise import is_thenable , Promise
33from sqlalchemy .orm .query import Query
44
5- from graphene .relay import ConnectionField
5+ from graphene .relay import Connection , ConnectionField
66from graphene .relay .connection import PageInfo
77from graphql_relay .connection .arrayconnection import connection_from_list_slice
88
9- from .utils import get_query
9+ from .utils import get_query , sort_argument_for_model
1010
1111
12- class SQLAlchemyConnectionField (ConnectionField ):
12+ class UnsortedSQLAlchemyConnectionField (ConnectionField ):
1313
1414 @property
1515 def model (self ):
1616 return self .type ._meta .node ._meta .model
1717
1818 @classmethod
19- def get_query (cls , model , info , ** args ):
20- return get_query (model , info .context )
19+ def get_query (cls , model , info , sort = None , ** args ):
20+ query = get_query (model , info .context )
21+ if sort is not None :
22+ if isinstance (sort , str ):
23+ query = query .order_by (sort .value )
24+ else :
25+ query = query .order_by (* (col .value for col in sort ))
26+ return query
2127
2228 @classmethod
2329 def resolve_connection (cls , connection_type , model , info , args , resolved ):
@@ -55,7 +61,25 @@ def get_resolver(self, parent_resolver):
5561 return partial (self .connection_resolver , parent_resolver , self .type , self .model )
5662
5763
58- __connectionFactory = SQLAlchemyConnectionField
64+ class SQLAlchemyConnectionField (UnsortedSQLAlchemyConnectionField ):
65+
66+ def __init__ (self , type , * args , ** kwargs ):
67+ if 'sort' not in kwargs and issubclass (type , Connection ):
68+ # Let super class raise if type is not a Connection
69+ try :
70+ model = type .Edge .node ._type ._meta .model
71+ kwargs .setdefault ('sort' , sort_argument_for_model (model ))
72+ except Exception :
73+ raise Exception (
74+ 'Cannot create sort argument for {}. A model is required. Set the "sort" argument'
75+ ' to None to disabling the creation of the sort query argument' .format (type .__name__ )
76+ )
77+ elif 'sort' in kwargs and kwargs ['sort' ] is None :
78+ del kwargs ['sort' ]
79+ super (SQLAlchemyConnectionField , self ).__init__ (type , * args , ** kwargs )
80+
81+
82+ __connectionFactory = UnsortedSQLAlchemyConnectionField
5983
6084
6185def createConnectionField (_type ):
@@ -69,4 +93,4 @@ def registerConnectionFieldFactory(factoryMethod):
6993
7094def unregisterConnectionFieldFactory ():
7195 global __connectionFactory
72- __connectionFactory = SQLAlchemyConnectionField
96+ __connectionFactory = UnsortedSQLAlchemyConnectionField
0 commit comments