Skip to content

sqltypes.py: add json (de)serializers for dialects which lack corresp… - #443

Closed
Nutigoodpipes wants to merge 1 commit into
zzzeek:masterfrom
Nutigoodpipes:fix_json_serializers
Closed

Nutigoodpipes wants to merge 1 commit into
zzzeek:masterfrom
Nutigoodpipes:fix_json_serializers

Conversation

@Nutigoodpipes

Copy link
Copy Markdown
  • Summary
    When implementing json type for dialects which doesn't support it, default json serializer is not defined.

  • Details
    All methods and classes here to keep the example minimal but complete are void to keep the example minimal and complete. Removing the coerce_compared_value would not trigger the bug, but this is needed thereafter for comparators to work with native python dictionnary.

Running with 'master' triggers
(exceptions.AttributeError) 'SQLiteDialect_pysqlite' object has no attribute '_json_serializer'

  • MCVE
    Tested with python 3.6 and 2.7
import json
import sqlalchemy

from sqlalchemy import insert, select, Column, Text, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql.expression import literal
from sqlalchemy.types import TypeDecorator, Boolean, JSON


class DefaultJSON(TypeDecorator):
    
    impl = Text

    def load_dialect_impl(self, dialect):
        return dialect.type_descriptor(Text())

    def coerce_compared_value(self, op, value):
        return JSON().coerce_compared_value(op, value)

    class Comparator(JSON.comparator_factory):
        """Mixed comparator_factory."""
    comparator_factory = Comparator

    def process_bind_param(self, value, dialect):
        if value is None:
            return value
        value = json.dumps(value)
        return value

    def process_result_value(self, value, dialect):
        if value is None:
            return value
        value = json.loads(value)
        return value

SQLJSON = DefaultJSON
Base = declarative_base()
db = sqlalchemy.create_engine("sqlite:////tmp/db.db", echo=True)

class Users(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    infos = Column(SQLJSON)

def main():
    Users.__table__.create(bind=db)
    insrt = insert(Users)
    insrt = insrt.values({'name': 'user1', 'infos': {"1": 1, "4": 4, "tab": "stab"}})
    db.execute(insrt)
    slct = select([Users])
    slct = slct.where(Users.infos == {"1": 1, "4": 4, "tab": "stab"})
    row = db.execute(slct)
    return row

@zzzeek

zzzeek commented May 16, 2018

Copy link
Copy Markdown
Owner

So, you probably know there's a real SQLite JSON type happening at: https://gerrit.sqlalchemy.org/#/c/zzzeek/sqlalchemy/+/706/, in case that's helpful.

Here, I'm not understanding why you need to use the actual JSON() type for coerce_compared_value(). JSON doesn't implement that method, you can just use the default implementation on TypeDecorator and then your example works - coerce_compared_value() returns the datatype that can handle the given value, and in this case it's your DefaultJSON type, so it returns "self".

@Nutigoodpipes

Copy link
Copy Markdown
Author

Thanks for your answer, I haven't heard about that incoming type. Will look at it.

What I need basically is dialects.postgresql.JSONB().with_variant(my_JSONB, 'sqlite')
This works as intended but, the problem is that my_JSONB is supposed to be a default type for backends that don't implement it. So using the postgresql specific one as a base is not acceptable for further development.

I was going for Text().with_variant( ... ).with_variant( ... ) but ended up with errors. Especially, using the ->> and -> trying to compare "string" string with '"string"' jsonb.

Maybe I'm doing it the wrong way, but the only solutions that works for me was to implement a decorated type with coerce_compared_value returning the dialects.postgresql.JSONB one. (I know this doesn't implement that method either, but enforcing the postgresql type coerce here is far more comprehensive.)

@zzzeek

zzzeek commented May 17, 2018

Copy link
Copy Markdown
Owner

You can't use the "->>" operators in your program because you are trying to be compatible with SQLite, unless you are implementing those operators as well. In your example above, I can use Text().with_variant(SQLJSON(), "sqlite").with_variant(postgresql.JSONB(), "postgresql") and run the script against Postgresql without issue (because I'm not doing JSON member access). It does seem like there's a separate bug in that we should be able to use SQLJSON().with_variant() too but the TypeDecorator seems to not be doing the right thing there.

If you can just send me an example of the whole thing you are doing and where it's failing, that would help.

@zzzeek

zzzeek commented May 17, 2018

Copy link
Copy Markdown
Owner

The ->> operator is linked to the "astext" method in any case, and per the guidelines at http://docs.sqlalchemy.org/en/latest/core/type_basics.html?highlight=json#sqlalchemy.types.JSON, to do platform agnostic JSON you need to use cast. In your program, this works too:


class Users(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    infos = Column(JSON().with_variant(SQLJSON(), "sqlite").with_variant(postgresql.JSONB(), "postgresql"))

def main():
    # ...
    slct = slct.where(cast(Users.infos["tab"], String) == "stab")

    # ...

on postgresql this renders as:

SELECT users.id, users.name, users.infos 
FROM users 
WHERE CAST((users.infos -> %(infos_1)s) AS VARCHAR) = %(param_1)s

@zzzeek

zzzeek commented May 17, 2018

Copy link
Copy Markdown
Owner

more correctly, according to the docs:

slct = slct.where(cast(Users.infos["tab"], String) == type_coerce("stab", JSON()))

@Nutigoodpipes

Copy link
Copy Markdown
Author

Here is a more complete example for the reason why those methods are needed. What I would like to do is match columns or json fields with inserted values directly (except with explicit casts such as ->> or astext). In the example I put different flavour of the same request that I'm trying to keep working.

Yes I saw the documentation, and that's also a reason why I went for custom JSON. Using this I can match just knowing the structure and given that I implemented the backend agnostic layer correctly.

Given that this is a module of a project that already have postgresql support, I really would like to be consistent with this syntax especially for types and operators that are not implemented (->>, ->, ~, ~*, !~, !~*, actually).

@zzzeek

zzzeek commented May 18, 2018

Copy link
Copy Markdown
Owner

OK, it looks like you want a SQLIte JSON type that also has the "astext" bit. See that's a big deal because that is completely at odds with how I've designed the whole thing, and if there is really really a reason people need this "astext" approach like this, I need to know.

now why exactly do you need to say:

slct.where(Users.infos["4"].astext == str(values_dict['infos']["4"]))

and not:

slct.where(cast(Users.infos["4"], String) == cast(values_dict['infos']["4"], JSON))

?

is it strictly the verbosity? or is there some other quality (performance, collation, or something) of the "->>" operator you are trying to get? Because really, the feature we want then is some kind of magic operator on the base JSON type that does that cast() thing that's currently in the docs. We can work on making PG's "astext" something that invokes from the base JSON type, and does the cast() thing or whatever on other backends. That would be way better here, because at the moment, even when I implement the SQLite JSON type, it doesn't do what you want and that is a big failure on my end.

I'm sorry this has to be a longer process but this is why I always need to understand what it is someone wants to do, it often refers to some much bigger issue that needs to be addressed.

@Nutigoodpipes

Copy link
Copy Markdown
Author

I cannot talk about performance because I haven't done any benchmark for now. But the goal here was indeed to render astext with ->> operator as it is for now with postgresql. My example in this way is not correct since I put the cast in astext but for now it is :

@property
def astext(self):
    return self.expr.left.op('->>')(self.expr.right)

in the Comparator subclass. This operator being interpreted with the access_astext function for sqlite wich do the cast.

That's fine to take time to put things clearly. This may be an error of mine in the first design so I'm coming back if I have more elements.

@zzzeek

zzzeek commented May 19, 2018

Copy link
Copy Markdown
Owner

as always we need to focus on the end result.

if we get the base JSON type to have data['foo'].astext == 'bar' and make that work for MySQL as well as the SQLite JSON type in gerrit, that's what you want, right? because everybody wants that anyway. you can work on that if you want to contribute code.

@zzzeek

zzzeek commented May 19, 2018

Copy link
Copy Markdown
Owner

also, the code here is weird that it assumes the base dialect has that attribute and it's None otherwise, sure, but it bothered me that you'd have your code using your SQLite-level json translator for some cases and the base JSON json translator in others. that was the problem.

@zzzeek

zzzeek commented Jun 13, 2018

Copy link
Copy Markdown
Owner

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants