Esempio n. 1
0
def registry_sqlalchemy_model_from_str(model_name: str) -> Optional[Any]:
    try:
        return next(
            filter(lambda x: x.__name__ == model_name,
                   list(get_global_registry()._registry.keys())))
    except StopIteration:
        pass
Esempio n. 2
0
def _register_composite_class(cls, registry=None):
    if registry is None:
        # from .registry import get_global_registry

        registry = get_global_registry()

    def inner(fn):
        registry.register_composite_converter(cls, fn)

    return inner
Esempio n. 3
0
    def __new__(cls, name, bases, attrs):
        # Also ensure initialization is only performed for subclasses of
        # SQLAlchemyInterface (excluding SQLAlchemyInterface class itself).
        if not is_base_type(bases, SQLAlchemyInterfaceMeta):
            return type.__new__(cls, name, bases, attrs)

        options = Options(
            attrs.pop('Meta', None),
            name=name,
            description=attrs.pop('__doc__', None),
            model=None,
            local_fields=None,
            only_fields=(),
            exclude_fields=(),
            # id='id',
            registry=None
        )

        if not options.registry:
            options.registry = get_global_registry()
        assert isinstance(options.registry, Registry), (
            'The attribute registry in {}.Meta needs to be an'
            ' instance of Registry, received "{}".'
        ).format(name, options.registry)
        assert is_mapped(options.model), (
            'You need to pass a valid SQLAlchemy Model in '
            '{}.Meta, received "{}".'
        ).format(name, options.model)

        cls = type.__new__(cls, name, bases, dict(attrs, _meta=options))

        options.base_fields = ()
        options.base_fields = get_base_fields(bases, _as=Field)
        if not options.local_fields:
            options.local_fields = yank_fields_from_attrs(attrs, _as=Field)

        # options.registry.register(cls)

        options.fields = merge(
            options.base_fields,
            options.local_fields
        )

        options.sqlalchemy_fields = yank_fields_from_attrs(
            construct_fields(options),
            _as=Field,
        )
        options.fields = merge(
            options.sqlalchemy_fields,
            options.base_fields,
            options.local_fields
        )

        return cls
def _construct_union(union_name, models, registry=None):
    if registry is None:
        registry = get_global_registry()

    typs = []
    for model in models:
        typ = registry.get_type_for_model(model)
        if typ:
            typs.append(typ)

    class Meta:
        types = typs

    return type(union_name, (Union,), {'Meta': Meta})()
Esempio n. 5
0
    def __init_subclass_with_meta__(cls,
                                    model=None,
                                    registry=None,
                                    only_fields=None,
                                    exclude_fields=None,
                                    **options):
        if exclude_fields is None:
            exclude_fields = []
        if only_fields is None:
            only_fields = []
        if not registry:
            registry = get_global_registry()
        auto_exclude = []
        foreign_keys = []
        # always pull ids out to a separate argument
        for col in sqlalchemy.inspect(model).columns:
            if col.foreign_keys:
                foreign_keys.append(col.name)
                continue
            if (col.primary_key and col.autoincrement) or (
                    isinstance(col.type, sqlalchemy.types.TIMESTAMP)
                    and col.server_default is not None):
                auto_exclude.append(col.name)
        sqlalchemy_fields = yank_fields_from_attrs(
            construct_fields(
                obj_type=SQLAlchemyObjectTypes().get(model),
                model=model,
                registry=registry,
                only_fields=tuple(only_fields),
                exclude_fields=tuple(exclude_fields + auto_exclude),
                connection_field_factory=default_connection_field_factory,
                batching=True,
            ),
            _as=graphene.Field,
        )
        # Add all of the fields to the input type

        for key, value in sqlalchemy_fields.items():
            if not (isinstance(value, Dynamic) or hasattr(cls, key)):
                if key in foreign_keys:
                    value = graphene.ID(description="graphene global id")
                setattr(cls, key, value)
        for key, value in model.__mapper__.relationships.items(
        ):  # many to many input,you should input [dbIds]
            if isinstance(value.secondary, sqlalchemy.Table):
                value = graphene.List(graphene.ID)
                setattr(cls, key, value)
        super(SQLAlchemyInputObjectType,
              cls).__init_subclass_with_meta__(**options)
Esempio n. 6
0
    def __new__(cls, name, bases, attrs):
        # Also ensure initialization is only performed for subclasses of SQLAlchemyInterface
        # (excluding SQLAlchemyInterface class itself).
        if not is_base_type(bases, SQLAlchemyInterfaceMeta):
            return type.__new__(cls, name, bases, attrs)

        options = Options(
            attrs.pop('Meta', None),
            name=name,
            description=attrs.pop('__doc__', None),
            model=None,
            local_fields=None,
            only_fields=(),
            exclude_fields=(),
            # id='id',
            registry=None)

        if not options.registry:
            options.registry = get_global_registry()
        assert isinstance(
            options.registry,
            Registry), ('The attribute registry in {}.Meta needs to be an'
                        ' instance of Registry, received "{}".').format(
                            name, options.registry)
        assert is_mapped(
            options.model), ('You need to pass a valid SQLAlchemy Model in '
                             '{}.Meta, received "{}".').format(
                                 name, options.model)

        cls = type.__new__(cls, name, bases, dict(attrs, _meta=options))

        options.base_fields = ()
        options.base_fields = get_base_fields(bases, _as=Field)
        if not options.local_fields:
            options.local_fields = yank_fields_from_attrs(attrs, _as=Field)

        # options.registry.register(cls)

        options.fields = merge(options.base_fields, options.local_fields)

        options.sqlalchemy_fields = yank_fields_from_attrs(
            construct_fields(options),
            _as=Field,
        )
        options.fields = merge(options.sqlalchemy_fields, options.base_fields,
                               options.local_fields)

        return cls
Esempio n. 7
0
 def __init__(self, type, *args, **kwargs):
     options = Options(
         meta=None,  # attrs.pop('Meta', None),
         name=type._meta.name,  # name,
         description=None,  # attrs.pop('__doc__', None),
         model=type._meta.model,  # None,
         local_fields=None,
         only_fields=(),
         exclude_fields=('password', 'search_vector'),
         id='id',
         interfaces=(),
         registry=get_global_registry(),
         fields=(),
     )
     fields = construct_fields(options)
     for field_name, field_type in fields.items():
         if hasattr(field_type,
                    'kwargs') and 'required' in field_type.kwargs:
             field_type.kwargs['required'] = False
         if not isinstance(field_type, Dynamic):  # and field_name != 'id':
             kwargs.setdefault(field_name, field_type)
     super(FilterableConnectionField, self).__init__(type, *args, **kwargs)