You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Querying a JSON column on a boolean field: type_coerce doesn't coerce True #4969
# This doesn't workfoods=session.query(Food).filter(Food.properties["is_it_good"].in_(type_coerce(True, JSON))
# This worksfoods=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.
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()
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()
Hi - sure, here you are. Let me know is you need something else.
fromsqlalchemyimport*fromsqlalchemy.ormimport*fromsqlalchemy.ext.declarativeimportdeclarative_basefromsqlalchemy.ext.declarativeimportdeclared_attrBase=declarative_base()
classA(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 recordres=s.query(A).all()
assertlen(res) ==1# Check we can get 1 record by querying a json string fieldcoerced_values= [type_coerce(v, JSON) forvin ["yummy"]]
res=s.query(A).filter(A.props["taste"].in_(coerced_values)).all()
assertlen(res) ==1# Check we can get 1 record by querying a json integer fieldcoerced_values= [type_coerce(v, JSON) forvin [2]]
res=s.query(A).filter(A.props["nbr_of_eggs"].in_(coerced_values)).all()
assertlen(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) forvin [1]]
res=s.query(A).filter(A.props["good"].in_(coerced_values)).all()
assertlen(res) ==1# Check we can get 1 record by querying a json boolean field# This will raise an AssertionErrorcoerced_values= [type_coerce(v, JSON) forvin [True]]
res=s.query(A).filter(A.props["good"].in_(coerced_values)).all()
assertlen(res) ==1
And here is the SQL output:
2019-11-0716:53:23,449 INFO sqlalchemy.engine.base.EngineSELECT CAST('test plain returns'ASVARCHAR(60)) AS anon_1
2019-11-0716:53:23,449 INFO sqlalchemy.engine.base.Engine ()
2019-11-0716:53:23,449 INFO sqlalchemy.engine.base.EngineSELECT CAST('test unicode returns'ASVARCHAR(60)) AS anon_1
2019-11-0716:53:23,449 INFO sqlalchemy.engine.base.Engine ()
2019-11-0716:53:23,450 INFO sqlalchemy.engine.base.Engine PRAGMA main.table_info("a")
2019-11-0716:53:23,450 INFO sqlalchemy.engine.base.Engine ()
2019-11-0716:53:23,450 INFO sqlalchemy.engine.base.Engine PRAGMA temp.table_info("a")
2019-11-0716:53:23,450 INFO sqlalchemy.engine.base.Engine ()
2019-11-0716:53:23,451 INFO sqlalchemy.engine.base.EngineCREATETABLEa (
id INTEGERNOT NULL,
props JSON,
PRIMARY KEY (id)
)
2019-11-0716:53:23,451 INFO sqlalchemy.engine.base.Engine ()
2019-11-0716:53:23,451 INFO sqlalchemy.engine.base.EngineCOMMIT2019-11-0716:53:23,452 INFO sqlalchemy.engine.base.EngineBEGIN (implicit)
2019-11-0716:53:23,452 INFO sqlalchemy.engine.base.EngineINSERT INTO a (props) VALUES (?)
2019-11-0716:53:23,452 INFO sqlalchemy.engine.base.Engine ('{"taste": "yummy", "nbr_of_eggs": 2, "good": true}',)
2019-11-0716:53:23,453 INFO sqlalchemy.engine.base.EngineCOMMIT2019-11-0716:53:23,453 INFO sqlalchemy.engine.base.EngineBEGIN (implicit)
2019-11-0716:53:23,453 INFO sqlalchemy.engine.base.EngineSELECTa.idAS a_id, a.propsAS a_props
FROM a
2019-11-0716:53:23,453 INFO sqlalchemy.engine.base.Engine ()
2019-11-0716:53:23,454 INFO sqlalchemy.engine.base.EngineSELECTa.idAS a_id, a.propsAS a_props
FROM a
WHERE JSON_QUOTE(JSON_EXTRACT(a.props, ?)) IN (?)
2019-11-0716:53:23,454 INFO sqlalchemy.engine.base.Engine ('$."taste"', '"yummy"')
2019-11-0716:53:23,455 INFO sqlalchemy.engine.base.EngineSELECTa.idAS a_id, a.propsAS a_props
FROM a
WHERE JSON_QUOTE(JSON_EXTRACT(a.props, ?)) IN (?)
2019-11-0716:53:23,455 INFO sqlalchemy.engine.base.Engine ('$."nbr_of_eggs"', '2')
2019-11-0716:53:23,456 INFO sqlalchemy.engine.base.EngineSELECTa.idAS a_id, a.propsAS a_props
FROM a
WHERE JSON_QUOTE(JSON_EXTRACT(a.props, ?)) IN (?)
2019-11-0716:53:23,456 INFO sqlalchemy.engine.base.Engine ('$."good"', '1')
2019-11-0716:53:23,456 INFO sqlalchemy.engine.base.EngineSELECTa.idAS a_id, a.propsAS a_props
FROM a
WHERE JSON_QUOTE(JSON_EXTRACT(a.props, ?)) IN (?)
2019-11-0716:53:23,457 INFO sqlalchemy.engine.base.Engine ('$."good"', 'true')
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.
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.
"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.
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.
Activity
zzzeek commentedon Nov 7, 2019
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!
JPFrancoia commentedon Nov 7, 2019
Hi - sure, here you are. Let me know is you need something else.
And here is the SQL output:
zzzeek commentedon Nov 7, 2019
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.
zzzeek commentedon Nov 7, 2019
yup it's wrong.
JSON_EXTRACT is supposed to return JSON:
however for the boolean, it is not returning JSON:
here's MySQL, where these functions came from:
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.
zzzeek commentedon Nov 7, 2019
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.
JPFrancoia commentedon Nov 7, 2019
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.
zzzeek commentedon Nov 7, 2019
well they documented it, which suggests we do need to work aroudn it. but this is literally the behavior:
im going to post it. i know they will just dismiss it because that's their style. but that's unworkable.
zzzeek commentedon Nov 7, 2019
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
zzzeek commentedon Nov 7, 2019
oh there is a true constant. huh.
zzzeek commentedon Nov 7, 2019
this works....
that's what we should be doing?
zzzeek commentedon Nov 7, 2019
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:
that's IMO much clearer.
zzzeek commentedon Nov 7, 2019
but that is specific to SQLite. so we still have a problem that SQLite's json_extract() does not work like MySQL's
zzzeek commentedon Nov 7, 2019
this is sort of a dupe of #4276 so might be made to be part of that
zzzeek commentedon Nov 7, 2019
it's a dupe. for 1.3.x things are just hacky for now, will see if we can do #4276.