Repository navigation
How to turn off sqlite json query with JSON_QUOTE? There are different between SQLAlchemy's sqlite and mysql json query. #9480
Answered
by
zzzeek
vba34520
asked this question in
Usage Questions
|
MySQL JSON query statement is clear and beautiful like this. from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Column, Integer, JSON
Base = declarative_base()
class Person(Base):
__tablename__ = 'person'
id = Column(Integer(), primary_key=True)
message = Column(JSON)
engine = create_engine('mysql+pymysql://root:123456@localhost:3306/test', pool_recycle=3600) # MySQL
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
person = Person(message={'name': 'Bob'}) # Insert a record
session.add(person)
session.commit()
query = session.query(Person.id).filter(Person.message['name'] == 'Bob') # MySQL will work, clear and beautiful
print(query[0].id) # 1
print(query)
# SELECT person.id AS person_id
# FROM person
# WHERE JSON_EXTRACT(person.message, %(message_1)s) = %(param_1)sSQLite It uses needless How can I solve this? from sqlalchemy import func
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Column, Integer, JSON
Base = declarative_base()
class Person(Base):
__tablename__ = 'person'
id = Column(Integer(), primary_key=True)
message = Column(JSON)
engine = create_engine('sqlite:///:memory:') # SQLite
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
person = Person(message={'name': 'Bob'}) # Insert a record
session.add(person)
session.commit()
query = session.query(Person.id).filter(Person.message['name'] == func.json_quote('Bob')) # SQLite will work, but need to use json_quote
print(query[0].id) # 1
print(query)
# SELECT person.id AS person_id
# FROM person
# WHERE JSON_QUOTE(JSON_EXTRACT(person.message, ?)) = json_quote(?) |
Answered by
zzzeek
Mar 14, 2023
Replies: 1 comment 2 replies
|
hi - take a look at "Casting JSON Elements to other types" at https://docs.sqlalchemy.org/en/20/core/type_basics.html#sqlalchemy.types.JSON . basically |
2 replies
Answer selected by
vba34520
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi -
take a look at "Casting JSON Elements to other types" at https://docs.sqlalchemy.org/en/20/core/type_basics.html#sqlalchemy.types.JSON . basically
struct["key"]can be any JSON, and in the case of MySQL, it's working by accident. the correct, platform agnostic way to compare an element in a json struct as a string to a string is to use as_string(); otherwise SQLAlchemy doesn't know what kind of comparison you want to do: