Exemple #1
0
def build_schema(config, engine, subset=None):
    """
    Build the object types for all the indexes. Subset is a list of
    index names that the schema should include. If no subset is
    provided, then all indexes are built and added to the schema.
    """
    fields = {}

    for i in Index.list_indexes(engine):
        if not subset or i.name in subset:
            try:
                output_type, args = build_index_type(config, engine, i)
                resolver = ql_resolver(config, engine, i)

                # create the field for this table, with arguments and resolver
                fields[f'{i.table.name}'] = graphql.GraphQLField(
                    graphql.GraphQLList(output_type),
                    args=args,
                    resolve=resolver,
                )
            except (ValueError, AssertionError) as ex:
                logging.error('%s; skipping %s...', str(ex), i.name)

    # construct the query object for the root object type
    root = graphql.GraphQLObjectType('Query', fields)

    # build the schema
    return graphql.GraphQLSchema(query=root)
    def generate_graphql_type(graph_type):
        if graph_type == schema.Boolean:
            return graphql.GraphQLNonNull(graphql.GraphQLBoolean)
        elif graph_type == schema.Float:
            return graphql.GraphQLNonNull(graphql.GraphQLFloat)
        elif graph_type == schema.Int:
            return graphql.GraphQLNonNull(graphql.GraphQLInt)
        elif graph_type == schema.String:
            return graphql.GraphQLNonNull(graphql.GraphQLString)

        elif isinstance(graph_type, schema.EnumType):
            # TODO: should enums map names or values?
            values = iterables.to_dict(
                (member.value, graphql.GraphQLEnumValue(member.value))
                for member in graph_type.enum)
            graphql_type = graphql.GraphQLEnumType(graph_type.name,
                                                   values=values)
            return graphql.GraphQLNonNull(graphql_type)

        elif isinstance(graph_type, schema.InputObjectType):
            return graphql.GraphQLNonNull(
                graphql.GraphQLInputObjectType(
                    name=graph_type.name,
                    fields=lambda: iterables.to_dict(
                        (snake_case_to_camel_case(field.name),
                         to_graphql_input_field(field))
                        for field in graph_type.fields),
                ))

        elif isinstance(graph_type, schema.InterfaceType):
            return graphql.GraphQLNonNull(
                graphql.GraphQLInterfaceType(
                    name=graph_type.name,
                    fields=to_graphql_fields(graph_type.fields),
                    resolve_type=lambda: None,
                ))

        elif isinstance(graph_type, schema.ListType):
            return graphql.GraphQLNonNull(
                graphql.GraphQLList(to_graphql_type(graph_type.element_type)))

        elif isinstance(graph_type, schema.NullableType):
            return to_graphql_type(graph_type.element_type).of_type

        elif isinstance(graph_type, schema.ObjectType):
            return graphql.GraphQLNonNull(
                graphql.GraphQLObjectType(
                    name=graph_type.name,
                    fields=to_graphql_fields(graph_type.fields),
                    interfaces=tuple(
                        to_graphql_type(interface).of_type
                        for interface in graph_type.interfaces),
                ))

        else:
            raise ValueError("unsupported type: {}".format(graph_type))
Exemple #3
0
def map_custom_type(mapper, obj):
    if isinstance(obj, CustomType):
        if not obj.fields:
            return BLANK_VALUE
        return graphql.GraphQLObjectType(
            name=obj.name,
            fields=partial(obj._map_fields, mapper),
            interfaces=partial(obj._map_interfaces, mapper),
            description=obj.description,
        )
Exemple #4
0
def _transform_class_to_output_type(cls, ctx: TransformContext):
    fields = []

    dc_fields = {}
    if is_dataclass(cls):
        dc_fields = {f.name: f for f in dataclass_fields(cls)}

    for name, definition, field_kw in iterate_class_attributes_for_output_type(
            cls, ctx):
        type_ = definition.type_

        dataclass_field = dc_fields.get(name)
        if dataclass_field:
            field_kw.update(dataclass_field.metadata)

        fields.append((name, type_, field_kw))

    if not fields:
        raise TypeError(
            f"Please define proper attributes on {cls.__qualname__}")

    if is_interface(cls):
        resolve_type = ctx.get("resolve_type",
                               getattr(cls, "resolve_type", None))

        if resolve_type is None:
            resolve_type = ctx.hook__prepare_default_interface_type_resolver(
                cls)
        else:
            resolve_type = ctx.hook__prepare_interface_type_resolver(
                resolve_type, cls)

        return graphql.GraphQLInterfaceType(
            name=get_name(cls),
            fields=_lazy_fields(ctx, fields),
            description=get_doc(cls),
            resolve_type=resolve_type,
        )

    interfaces = lambda: [
        _transform_class_to_output_type(interface_cls, ctx)
        for interface_cls in get_interfaces(cls)
    ]

    return graphql.GraphQLObjectType(
        name=get_name(cls),
        fields=_lazy_fields(ctx, fields),
        description=get_doc(cls),
        interfaces=interfaces,
    )
Exemple #5
0
 def factory(
     name: Optional[str], description: Optional[str]
 ) -> Union[graphql.GraphQLObjectType, graphql.GraphQLInterfaceType]:
     name = unwrap_name(name, cls)
     if is_interface(cls):
         return graphql.GraphQLInterfaceType(name,
                                             field_thunk,
                                             interface_thunk,
                                             description=description)
     else:
         return graphql.GraphQLObjectType(
             name,
             field_thunk,
             interface_thunk,
             is_type_of=lambda obj, _: isinstance(obj, cls),
             description=description,
         )
Exemple #6
0
 def map_type(
     self,
     source: Type[Any],
     interfaces: Optional[Sequence[GraphQLInterfaceType]] = None,
     alias: Optional[str] = None,
 ) -> GraphQLObjectType:
     name = alias or self.type_name(source)
     if name in self.query_types:
         return self.query_types[name]
     description = self.type_description(source)
     helper = Helper(source, self)
     _type = graphql.GraphQLObjectType(
         name,
         description=description,
         fields=helper.query_fields,
         interfaces=interfaces,
     )
     self.query_types[name] = _type
     return _type
Exemple #7
0
def build_object_type(name, objs):
    """
    Create the object type of a given set of objects, which is the
    union of all fields across the objects.
    """
    all_columns = set([k for obj in objs for k in obj.keys()])

    # transpose the objects into columns of values
    columns = {}
    for k in all_columns:
        if not ql_is_valid_field(k):
            logging.warning(
                '%s is not a valid GraphQL field name; skipping...', k)
        else:
            columns[k] = [obj[k] for obj in objs if k in obj]

    # determine the type of each field (ignore nulls)
    fields = {}
    for field_name, xs in columns.items():
        this_type = ql_type(name, field_name, xs)
        fields[field_name] = graphql.GraphQLField(this_type)

    # build the final object
    return graphql.GraphQLObjectType(name, fields)
Exemple #8
0
import typing as t
import graphql as g
from handofcats import as_command
from dictknife import loading

Person = g.GraphQLObjectType(
    "Person",
    lambda: {
        "name": g.GraphQLField(g.GraphQLNonNull(g.GraphQLString)),
        "age": g.GraphQLField(g.GraphQLNonNull(g.GraphQLInt)),
        "nickname": g.GraphQLField(g.GraphQLString),
    },
)


query_type = g.GraphQLObjectType(
    "Query",
    lambda: {
        "person": g.GraphQLField(
            Person, args={"name": g.GraphQLArgument(g.GraphQLString)},
        )
    },
)

Person = t.Dict[str, t.Any]


class Root:
    def __init__(self, data):
        self.data = data
Exemple #9
0
import graphql
from graphql.utilities import print_schema

Person = graphql.GraphQLObjectType(
    "Person",
    lambda: {
        "name":
        graphql.GraphQLField(graphql.GraphQLNonNull(graphql.GraphQLString, )),
    },
)
Query = graphql.GraphQLObjectType(
    "Query",
    lambda: {
        "people":
        graphql.GraphQLField(
            graphql.GraphQLNonNull(graphql.GraphQLList(Person)))
    },
)
schema = graphql.GraphQLSchema(Query)

print(print_schema(schema))
# or graphql.print_schema(schema)
Exemple #10
0
import graphql as g
from handofcats import as_command
from minidb import Table

Person = g.GraphQLObjectType(
    "Person",
    lambda: {
        "name": g.GraphQLField(g.GraphQLNonNull(g.GraphQLString)),
        "age": g.GraphQLField(g.GraphQLNonNull(g.GraphQLInt)),
        "nickname": g.GraphQLField(g.GraphQLString),
    },
)


query_type = g.GraphQLObjectType(
    "Query", lambda: {"people": g.GraphQLField(g.GraphQLList(Person))},
)


class Root:
    def __init__(self, tables):
        self.tables = tables

    def people(self, info):
        return self.tables["people"].find_all()


schema = g.GraphQLSchema(query_type)


@as_command
Exemple #11
0
        i += 1


def resolve_counter(root: float, info: graphql.GraphQLResolveInfo, ceil: int):
    # pylint: disable=W0613, unused-argument
    return f"{root} :: {info.operation.name.value}"


schema = graphql.GraphQLSchema(
    query=graphql.GraphQLObjectType(
        name="RootQueryType",
        fields={
            "name": graphql.GraphQLField(
                graphql.GraphQLString,
                resolve=resolve_name,
                args={
                    "title": graphql.GraphQLArgument(
                        graphql.GraphQLNonNull(graphql.GraphQLString)
                    )
                },
            )
        },
    ),
    subscription=graphql.GraphQLObjectType(
        name="RootSubscriptionType",
        fields={
            "counter": graphql.GraphQLField(
                graphql.GraphQLString,
                resolve=resolve_counter,
                subscribe=subscribe_counter,
                args={
                    "ceil": graphql.GraphQLArgument(
Exemple #12
0
import graphql as g

Person = g.GraphQLObjectType(
    "Person",
    lambda: {
        "name": g.GraphQLField(g.GraphQLNonNull(g.GraphQLString)),
        "age": g.GraphQLField(g.GraphQLNonNull(g.GraphQLInt)),
        "nickname": g.GraphQLField(g.GraphQLString),
        "father": g.GraphQLField(Person),
        "mother": g.GraphQLField(Person),
    },
)


class Root:
    def __init__(self, data):
        self.data = data

    def person(self, _info):
        return self.data["person"]


query_type = g.GraphQLObjectType(
    "Query",
    lambda: {"person": g.GraphQLField(Person)},
)

schema = g.GraphQLSchema(query_type)
q = """
{ person { name, age, nickname, father, mother } }
"""
"""
GraphQL Subscriptions
"""

import graphql

from .system_subscriptions import SystemSubscription

# pylint: disable=invalid-name
RootSubscriptionType = graphql.GraphQLObjectType(
    "Subscriptions",
    {
        "system": SystemSubscription
    }
)

__all__ = ['RootSubscriptionType']
Exemple #14
0
import graphql as g
from handofcats import as_command
from dictknife import loading

person_order_input_enum = g.GraphQLEnumType(
    "PersonOrderInput",
    {
        "name_ASC": g.GraphQLEnumValue("name_ASC"),
        "name_DESC": g.GraphQLEnumValue("name_DESC"),
    },
)

Person = g.GraphQLObjectType(
    "Person",
    lambda: {
        "name": g.GraphQLField(g.GraphQLNonNull(g.GraphQLString)),
        "age": g.GraphQLField(g.GraphQLNonNull(g.GraphQLInt)),
        "nickname": g.GraphQLField(g.GraphQLString),
    },
)

query_type = g.GraphQLObjectType(
    "Query",
    lambda: {
        "people":
        g.GraphQLField(
            g.GraphQLList(Person),
            args={"order_by": g.GraphQLArgument(person_order_input_enum)},
        )
    },
)
Exemple #15
0
    def object(
        self,
        cls: Type,
        fields: Collection[ObjectField],
        merged_types: Mapping[str, Thunk[graphql.GraphQLType]] = None,
    ) -> Thunk[graphql.GraphQLType]:
        fields_and_resolvers = list(fields)
        try:
            name, description = self._ref_and_desc
        except MissingRef:
            if cls.__name__ not in ("Query", "Mutation", "Subscription"):
                raise
            name, description = cls.__name__, self._description
        for resolver_name, resolver in get_resolvers(cls).items():
            resolve = resolver_resolve(resolver,
                                       self.aliaser,
                                       error_as_null=self.error_as_null)
            resolver_field = ObjectField(
                resolver_name,
                wrap_return_type(resolver.return_type, self.error_as_null),
                conversions=resolver.conversions,
                parameters=field_parameters(resolver),
                resolve=resolve,
            )
            fields_and_resolvers.append(resolver_field)
        visited_fields = dict(map(self._field, fields_and_resolvers))

        def field_thunk() -> graphql.GraphQLFieldMap:
            return merge_fields(
                cls,
                visited_fields,
                merged_types or {},
                deref_merged_field,
            )

        interfaces = list(map(self.visit, get_interfaces(cls)))
        interface_thunk = None
        if interfaces:

            def interface_thunk() -> Collection[graphql.GraphQLInterfaceType]:
                result = {exec_thunk(i, non_null=False) for i in interfaces}
                for merged_thunk in (merged_types or {}).values():
                    merged = cast(
                        Union[graphql.GraphQLObjectType,
                              graphql.GraphQLInterfaceType],
                        exec_thunk(merged_thunk, non_null=False),
                    )
                    result.update(merged.interfaces)
                return sorted(result, key=lambda i: i.name)

        if is_interface(cls):
            return lambda: graphql.GraphQLInterfaceType(
                name,
                field_thunk,
                interface_thunk,
                description=description,
            )

        else:
            return lambda: graphql.GraphQLObjectType(
                name,
                field_thunk,
                interface_thunk,
                is_type_of=lambda obj, _: isinstance(obj, cls),
                description=description,
            )