|
| 1 | +from graphene import Argument, Enum, List |
1 | 2 | from sqlalchemy.exc import ArgumentError
|
| 3 | +from sqlalchemy.inspection import inspect |
2 | 4 | from sqlalchemy.orm import class_mapper, object_mapper
|
3 | 5 | from sqlalchemy.orm.exc import UnmappedClassError, UnmappedInstanceError
|
4 | 6 |
|
@@ -34,3 +36,51 @@ def is_mapped_instance(cls):
|
34 | 36 | return False
|
35 | 37 | else:
|
36 | 38 | return True
|
| 39 | + |
| 40 | + |
| 41 | +def _symbol_name(column_name, is_asc): |
| 42 | + return column_name + ('_asc' if is_asc else '_desc') |
| 43 | + |
| 44 | + |
| 45 | +def _sort_enum_for_model(cls, name=None, symbol_name=_symbol_name): |
| 46 | + name = name or cls.__name__ + 'SortEnum' |
| 47 | + items = [] |
| 48 | + default = [] |
| 49 | + for column in inspect(cls).columns.values(): |
| 50 | + asc = symbol_name(column.name, True), column.asc() |
| 51 | + desc = symbol_name(column.name, False), column.desc() |
| 52 | + if column.primary_key: |
| 53 | + default.append(asc[1]) |
| 54 | + items.extend((asc, desc)) |
| 55 | + return Enum(name, items), default |
| 56 | + |
| 57 | + |
| 58 | +def sort_enum_for_model(cls, name=None, symbol_name=_symbol_name): |
| 59 | + '''Create Graphene Enum for sorting a SQLAlchemy class query |
| 60 | +
|
| 61 | + Parameters |
| 62 | + - cls : Sqlalchemy model class |
| 63 | + Model used to create the sort enumerator |
| 64 | + - name : str, optional, default None |
| 65 | + Name to use for the enumerator. If not provided it will be set to `cls.__name__ + 'SortEnum'` |
| 66 | + - symbol_name : function, optional, default `_symbol_name` |
| 67 | + Function which takes the column name and a boolean indicating if the sort direction is ascending, |
| 68 | + and returns the symbol name for the current column and sort direction. |
| 69 | + The default function will create, for a column named 'foo', the symbols 'foo_asc' and 'foo_desc' |
| 70 | +
|
| 71 | + Returns |
| 72 | + - Enum |
| 73 | + The Graphene enumerator |
| 74 | + ''' |
| 75 | + enum, _ = _sort_enum_for_model(cls, name, symbol_name) |
| 76 | + return enum |
| 77 | + |
| 78 | + |
| 79 | +def sort_argument_for_model(cls, has_default=True): |
| 80 | + '''Returns an Graphene argument for the sort field that accepts a list of sorting directions for a model. |
| 81 | + If `has_default` is True (the default) it will sort the result by the primary key(s) |
| 82 | + ''' |
| 83 | + enum, default = _sort_enum_for_model(cls) |
| 84 | + if not has_default: |
| 85 | + default = None |
| 86 | + return Argument(List(enum), default_value=default) |
0 commit comments