Skip to content

Add support for sqlalchemy.dialects.postgresql fields #172

Closed

Description

@dgouldin

When I try to register a SQLAlchemyNode whose model has a postgres-specific field, I receive the error message Don't know how to convert the SQLAlchemy field [table_name].[field_name] (<class 'sqlalchemy.sql.schema.Column'>). It'd be great if these fields worked out of the box.

Activity

  1. syrusakbary commented on May 20, 2016

    @syrusakbary
    Member

    That could be a good idea.

    It this field type inside sqlalchemy, or in a third party library?

  2. dgouldin commented on May 20, 2016

    @dgouldin
    Author

    Inside sqlalchemy. It's an entire module of fields. Types listed in the docs starting here:

    http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#array-types

  3. karec commented on Jun 7, 2016

    @karec
    Contributor

    👍

    Some fields could be really simple to implement within the existing code, I will try to work on it this week if I have some times.

    It could be nice to define a list for all fields that we need to add

  4. dgouldin commented on Jun 7, 2016

    @dgouldin
    Author

    ARRAY, JSON, JSONB, HSTORE, ENUM, and UUID are IMO the most common postgres-specific types.

  5. tgdn commented on Jun 19, 2016

    @tgdn

    TSVECTOR is probably important to mention here if full text search is needed. Not sure if an implementation is required but at least exclude the field by default as it would probably only used in the resolve method to search.

  6. karec commented on Jun 21, 2016

    @karec
    Contributor

    @dgouldin I've added all this fields to sqlalchemy converters, I still need to make some tests before pull request but my fork is up to date if you need to test it

  7. syrusakbary commented on Sep 11, 2016

    @syrusakbary
    Member

    Postgresql SQLAlchemy field conversion is now available in 1.0.dev (master branch).

    Closing the issue!

  8. patvdleer commented on Jun 6, 2018

    @patvdleer

    Due a wrapper (for JSONB on Sqlite) I wrote (and stole/copied) I ran into the same error. Maybe this will help others.

    import json
    
    from graphene import JSONString
    from graphene_sqlalchemy.converter import convert_sqlalchemy_type, get_column_doc, is_column_nullable
    from sqlalchemy import types, TypeDecorator
    from sqlalchemy.dialects.postgresql import JSONB
    from sqlalchemy.ext.compiler import compiles
    from sqlalchemy.sql import sqltypes
    from sqlalchemy.sql.functions import FunctionElement
    
    
    class SqliteJsonElement(FunctionElement):
        type = types.Text()
        name = "JsonElement"
    
        @property
        def astext(self):
            return self
    
    
    @compiles(SqliteJsonElement)
    def compileSqliteJsonElement(element, compiler, **kw):
        return "jsonExtract(%s)" % compiler.process(element.clauses)
    
    
    class SqliteJson(TypeDecorator):
        impl = types.Text
    
        def process_bind_param(self, value, dialect):
            if isinstance(value, tuple) and len(value) == 1:
                value = value[0]
            return json.dumps(value or {})
    
        def process_result_value(self, value, dialect):
            if value is None:
                return {}
            return json.loads(value)
    
        class comparator_factory(sqltypes.Concatenable.Comparator):
            def __getitem__(self, other):
                """Get the value at a given key."""
                return SqliteJsonElement(self.expr, other)
    
    
    class SqliteCompatiblePostgresOptimizedJson(TypeDecorator):
        # See: http://docs.sqlalchemy.org/en/latest/core/custom_types.html
        # impl = None
        impl = types.JSON
    
        def load_dialect_impl(self, dialect):
            dialectTypeMap = {
                'sqlite': SqliteJson,
                'postgresql': JSONB
            }
    
            self.impl = dialect.type_descriptor(dialectTypeMap[dialect.name])
            return self.impl
    
        def process_bind_param(self, value, dialect):
            return value
    
        def process_result_value(self, value, dialect):
            # Todo: refactor
            if isinstance(value, (tuple, list)) and len(value) == 1:
                value = value[0]
            if isinstance(value, dict) and len(value.keys()) == 1 and "meta" in value.keys():
                value = value["meta"]
            return value
    
        @property
        def comparator_factory(self):
            """express comparison behavior in terms of the base type"""
            return self.impl.comparator_factory
    
    
    @convert_sqlalchemy_type.register(SqliteCompatiblePostgresOptimizedJson)
    def convert_json_to_string(type, column, registry=None):
        return JSONString(description=get_column_doc(column), required=not(is_column_nullable(column)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions