Skip to content

Querying a JSON column on a boolean field: type_coerce doesn't coerce True #4969

Closed

Description

@JPFrancoia

TL;DR

It all boils down to:

# This doesn't work
foods = session.query(Food).filter(Food.properties["is_it_good"].in_(type_coerce(True, JSON))

# This works
foods = session.query(Food).filter(Food.properties["is_it_good"].in_(type_coerce(1, JSON))

More info:

I have a Food model with a JSON column. I use sqlite3.

class Food(Base):
    
    __tablename__ = "foods"
    properties = Column(JSON)

In this JSON properties field, I can have several type of fields: string, integer and boolean.

If I want to query properties for a string json field:

from sqlalchemy import type_coerce
from sqlalchemy.dialects.sqlite import JSON
    
tastes_ok = ["yummy", "beurk"]
coerced_values = [type_coerce(v, JSON) for v in tastes_ok]
    
foods = session.query(Food).filter(Food.properties["taste"].in_(coerced_values))

Or for a json field that contains an integer:

number_of_eggs = [1, 2, 3]
coerced_values = [type_coerce(v, JSON) for v in number_of_eggs]
    
foods = session.query(Food).filter(Food.properties["number_of_eggs"].in_(coerced_values))

But this approach doesn't work on booleans:

is_it_good = [True, False]
# is_it_good = [True]  # doesn't work either
coerced_values = [type_coerce(v, JSON) for v is_it_good]
    
foods = session.query(Food).filter(Food.properties["is_it_good"].in_(coerced_values))

However, this works:

foods = session.query(Food).filter(Food.properties["is_it_good"] == cast(True, JSON))

But this doesn't:

foods = session.query(Food).filter(Food.properties["is_it_good"].in_([cast(True, JSON)])

NOTE: in this post when I say something doesn't work, I mean that I don't get any record back (yes the database has records, yes I also execute the query with foods.all()

Activity

  1. zzzeek commented on Nov 7, 2019

    @zzzeek
    Member

    hi -

    can you save me some time, take all of these snippets and put them into a front-to-back SQL script I can run? Here's a template. change it to just have A with the JSON column, put some data in, run the query, ill take a look. thanks!

    from sqlalchemy import *
    from sqlalchemy.orm import *
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.ext.declarative import declared_attr
    
    Base = declarative_base()
    
    
    class A(Base):
        __tablename__ = 'a'
    
        id = Column(Integer, primary_key=True)
        data = Column(String)
        bs = relationship("B")
    
    
    class B(Base):
        __tablename__ = 'b'
        id = Column(Integer, primary_key=True)
        a_id = Column(ForeignKey("a.id"))
        data = Column(String)
    
    e = create_engine("sqlite://", echo=True)
    Base.metadata.create_all(e)
    
    s = Session(e)
    
    s.add(A(bs=[B()]))
    s.commit()
    
  2. added
    datatypes
    question
    on Nov 7, 2019
  3. JPFrancoia commented on Nov 7, 2019

    @JPFrancoia
    Author

    Hi - sure, here you are. Let me know is you need something else.

    from sqlalchemy import *
    from sqlalchemy.orm import *
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.ext.declarative import declared_attr
    
    Base = declarative_base()
    
    
    class A(Base):
        __tablename__ = 'a'
    
        id = Column(Integer, primary_key=True)
        props = Column(JSON)
    
    
    e = create_engine("sqlite://", echo=True)
    Base.metadata.create_all(e)
    
    s = Session(e)
    
    
    props = {"taste": "yummy", "nbr_of_eggs": 2, "good": True}
    
    s.add(A(props=props))
    s.commit()
    
    
    # Check we properly inserted 1 record
    res = s.query(A).all()
    assert len(res) == 1
    
    # Check we can get 1 record by querying a json string field
    coerced_values = [type_coerce(v, JSON) for v in ["yummy"]]
    res = s.query(A).filter(A.props["taste"].in_(coerced_values)).all()
    assert len(res) == 1
    
    # Check we can get 1 record by querying a json integer field
    coerced_values = [type_coerce(v, JSON) for v in [2]]
    res = s.query(A).filter(A.props["nbr_of_eggs"].in_(coerced_values)).all()
    assert len(res) == 1
    
    # Check we can get 1 record by querying a json boolean field
    # ONLY IF the integer representation of boolean is used (1 or 0)
    coerced_values = [type_coerce(v, JSON) for v in [1]]
    res = s.query(A).filter(A.props["good"].in_(coerced_values)).all()
    assert len(res) == 1
    
    # Check we can get 1 record by querying a json boolean field
    # This will raise an AssertionError
    coerced_values = [type_coerce(v, JSON) for v in [True]]
    res = s.query(A).filter(A.props["good"].in_(coerced_values)).all()
    assert len(res) == 1

    And here is the SQL output:

    2019-11-07 16:53:23,449 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1
    2019-11-07 16:53:23,449 INFO sqlalchemy.engine.base.Engine ()
    2019-11-07 16:53:23,449 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1
    2019-11-07 16:53:23,449 INFO sqlalchemy.engine.base.Engine ()
    2019-11-07 16:53:23,450 INFO sqlalchemy.engine.base.Engine PRAGMA main.table_info("a")
    2019-11-07 16:53:23,450 INFO sqlalchemy.engine.base.Engine ()
    2019-11-07 16:53:23,450 INFO sqlalchemy.engine.base.Engine PRAGMA temp.table_info("a")
    2019-11-07 16:53:23,450 INFO sqlalchemy.engine.base.Engine ()
    2019-11-07 16:53:23,451 INFO sqlalchemy.engine.base.Engine
    CREATE TABLE a (
    	id INTEGER NOT NULL,
    	props JSON,
    	PRIMARY KEY (id)
    )
    
    
    2019-11-07 16:53:23,451 INFO sqlalchemy.engine.base.Engine ()
    2019-11-07 16:53:23,451 INFO sqlalchemy.engine.base.Engine COMMIT
    2019-11-07 16:53:23,452 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
    2019-11-07 16:53:23,452 INFO sqlalchemy.engine.base.Engine INSERT INTO a (props) VALUES (?)
    2019-11-07 16:53:23,452 INFO sqlalchemy.engine.base.Engine ('{"taste": "yummy", "nbr_of_eggs": 2, "good": true}',)
    2019-11-07 16:53:23,453 INFO sqlalchemy.engine.base.Engine COMMIT
    2019-11-07 16:53:23,453 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
    2019-11-07 16:53:23,453 INFO sqlalchemy.engine.base.Engine SELECT a.id AS a_id, a.props AS a_props
    FROM a
    2019-11-07 16:53:23,453 INFO sqlalchemy.engine.base.Engine ()
    2019-11-07 16:53:23,454 INFO sqlalchemy.engine.base.Engine SELECT a.id AS a_id, a.props AS a_props
    FROM a
    WHERE JSON_QUOTE(JSON_EXTRACT(a.props, ?)) IN (?)
    2019-11-07 16:53:23,454 INFO sqlalchemy.engine.base.Engine ('$."taste"', '"yummy"')
    2019-11-07 16:53:23,455 INFO sqlalchemy.engine.base.Engine SELECT a.id AS a_id, a.props AS a_props
    FROM a
    WHERE JSON_QUOTE(JSON_EXTRACT(a.props, ?)) IN (?)
    2019-11-07 16:53:23,455 INFO sqlalchemy.engine.base.Engine ('$."nbr_of_eggs"', '2')
    2019-11-07 16:53:23,456 INFO sqlalchemy.engine.base.Engine SELECT a.id AS a_id, a.props AS a_props
    FROM a
    WHERE JSON_QUOTE(JSON_EXTRACT(a.props, ?)) IN (?)
    2019-11-07 16:53:23,456 INFO sqlalchemy.engine.base.Engine ('$."good"', '1')
    2019-11-07 16:53:23,456 INFO sqlalchemy.engine.base.Engine SELECT a.id AS a_id, a.props AS a_props
    FROM a
    WHERE JSON_QUOTE(JSON_EXTRACT(a.props, ?)) IN (?)
    2019-11-07 16:53:23,457 INFO sqlalchemy.engine.base.Engine ('$."good"', 'true')
  4. zzzeek commented on Nov 7, 2019

    @zzzeek
    Member

    the SQL emitted looks correct. see the last two SQL statements and the parameters?

    SELECT a.id AS a_id, a.props AS a_props
    FROM a
    WHERE JSON_QUOTE(JSON_EXTRACT(a.props, ?)) IN (?)
    2019-11-07 16:53:23,456 INFO sqlalchemy.engine.base.Engine ('$."good"', '1')

    SELECT a.id AS a_id, a.props AS a_props
    FROM a
    WHERE JSON_QUOTE(JSON_EXTRACT(a.props, ?)) IN (?)
    2019-11-07 16:53:23,457 INFO sqlalchemy.engine.base.Engine ('$."good"', 'true')

    first one has the "1" you sent, the second one has the "true". The JSON inserted is also correct:

    INSERT INTO a (props) VALUES (?)
    2019-11-07 16:53:23,452 INFO sqlalchemy.engine.base.Engine ('{"taste": "yummy", "nbr_of_eggs": 2, "good": true}',)

    hypothesize SQLite's JSON_EXTRACT and/or comparison is not doing the right thing.

  5. zzzeek commented on Nov 7, 2019

    @zzzeek
    Member

    yup it's wrong.

    JSON_EXTRACT is supposed to return JSON:

    sqlite> select json_extract('{"good": {"more": "json"}}', '$."good"');
    {"more":"json"}
    
    

    however for the boolean, it is not returning JSON:

    sqlite> select json_extract('{"good": true}', '$."good"');
    1
    
    

    here's MySQL, where these functions came from:

    MariaDB [(none)]> select json_extract('{"good": {"more": "json"}}', '$."good"');
    +--------------------------------------------------------+
    | json_extract('{"good": {"more": "json"}}', '$."good"') |
    +--------------------------------------------------------+
    | {"more": "json"}                                       |
    +--------------------------------------------------------+
    1 row in set (0.007 sec)
    
    MariaDB [(none)]> select json_extract('{"good": true}', '$."good"');
    +--------------------------------------------+
    | json_extract('{"good": true}', '$."good"') |
    +--------------------------------------------+
    | true                                       |
    +--------------------------------------------+
    1 row in set (0.000 sec)
    
    
    

    suggest working around it for now and reporting the issue to SQLite. unfortunately SQLite makes it difficult to report issues as you have to subscribe to their mailing list and report it there.

  6. added
    external driver issues
    on Nov 7, 2019
  7. zzzeek commented on Nov 7, 2019

    @zzzeek
    Member

    welp they documented it as doing what it did:

    https://www.sqlite.org/json1.html#jex

    "the SQL datatype of the result is NULL for a JSON null, INTEGER or REAL for a JSON numeric value, an INTEGER zero for a JSON false value, an INTEGER one for a JSON true value, the dequoted text for a JSON string value, and a text representation for JSON object and array values."

    no point reporting it then, as usual, SQLite thinks it knows better than you.

  8. JPFrancoia commented on Nov 7, 2019

    @JPFrancoia
    Author

    Yes the SQL seemed right to me and I couldn't figure out why this query wouldn't. Thanks for your help, I'll work around it and report it to sqlite if possible.

    Thanks again. Feel free to close if needed.

  9. zzzeek commented on Nov 7, 2019

    @zzzeek
    Member

    well they documented it, which suggests we do need to work aroudn it. but this is literally the behavior:

    sqlite> select json_quote(json_extract('{"good": true}', '$."good"'));
    1
    
    

    im going to post it. i know they will just dismiss it because that's their style. but that's unworkable.

  10. zzzeek commented on Nov 7, 2019

    @zzzeek
    Member

    mmm well it could still be a "bug", because there is no "true" constant in SQLite hwihc means when it sees "true" it is interpreting it as JSON

  11. zzzeek commented on Nov 7, 2019

    @zzzeek
    Member

    oh there is a true constant. huh.

  12. zzzeek commented on Nov 7, 2019

    @zzzeek
    Member

    this works....

    sqlite> select json_quote(json_extract('{"good": true}', '$."good"')) in (json_quote(true));
    1
    
    

    that's what we should be doing?

  13. zzzeek commented on Nov 7, 2019

    @zzzeek
    Member

    here's how i documented this awhile back:

    https://docs.sqlalchemy.org/en/13/core/type_basics.html?highlight=json#sqlalchemy.types.JSON

    in this case, just need to use CAST:

    res = s.query(A).filter(cast(A.props["good"], Boolean).in_([True])).all()
    

    that's IMO much clearer.

  14. zzzeek commented on Nov 7, 2019

    @zzzeek
    Member

    but that is specific to SQLite. so we still have a problem that SQLite's json_extract() does not work like MySQL's

  15. added
    bug
    and removed
    external driver issues
    question
    on Nov 7, 2019
  16. added this to the 1.4 milestone on Nov 7, 2019
  17. zzzeek commented on Nov 7, 2019

    @zzzeek
    Member

    this is sort of a dupe of #4276 so might be made to be part of that

  18. zzzeek commented on Nov 7, 2019

    @zzzeek
    Member

    it's a dupe. for 1.3.x things are just hacky for now, will see if we can do #4276.

  19. added
    duplicate
    on Nov 7, 2019
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

    bugdatatypesduplicatesqlite

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions