Skip to content

document the "as_string" / "as_int" etc JSON methods not as "CAST" methods, since this is not accurate as to their purpose #11065

Closed

Description

@matthew-mcallister

Describe the bug

When using the SQLite driver, calling .as_string() on a JSON column in a query does not cast the result to a string. For example, if a have a table Table with a JSON column json, I may write a query such as select(Table.data['foo'].as_string()). If a row has the value {"foo": 1}, the result should be '1', a string. Instead, SQLAlchemy returns 1, an int.

Optional link from https://docs.sqlalchemy.org which documents the behavior that is expected

https://docs.sqlalchemy.org/en/20/core/type_basics.html#sqlalchemy.types.JSON.Comparator.as_string

SQLAlchemy Version in Use

2.0.27

DBAPI (i.e. the database driver)

pysqlite

Database Vendor and Major Version

3.45.1

Python Version

3.10.13

Operating system

OSX

To Reproduce

import sqlalchemy as sa

engine = sa.create_engine('sqlite://')
meta = sa.MetaData()
table = sa.Table(
    'example',
    meta,
    sa.Column('json', sa.JSON),
)

cxn = engine.connect()
meta.create_all(cxn)
cxn.execute(sa.insert(table).values(json={'foo': 1}))
res = cxn.execute(sa.select(table.c.json['foo'].as_string()))
row = res.first()
assert row
print(row[0], type(row[0]))
# Expected: 1 <class 'str'>
# Got: 1 <class 'int'>

Error

n/a

Additional context

I don't believe this is relevant to the current SQLite driver implementation, but SQLite's JSON access operators are not compatible with postgresql. In postgres, -> returns JSON while ->> returns text. In SQLite, -> returns text while ->> may return NULL, INT, REAL, or JSON.

Activity

  1. added
    requires triage
    on Feb 27, 2024
  2. added
    bug
    json
    PRs (with tests!) welcome
    and removed
    requires triage
    on Feb 28, 2024
  3. added this to the 2.0.x milestone on Feb 28, 2024
  4. CaselIT commented on Feb 28, 2024

    @CaselIT
    Member

    Hi,

    Thanks for reporting. The sql being rendered is as follows:

    res = cxn.execute(sa.select(table.c.json['foo'].as_string(), table.c.json['foo']))
    
    SELECT JSON_EXTRACT(example.json, ?) AS anon_1, JSON_QUOTE(JSON_EXTRACT(example.json, ?)) AS anon_2
    FROM example
    ('$."foo"', '$."foo"')
    

    Looking at the sql and the documentation of sqlite https://sqlite.org/json1.html#the_json_extract_function it seems that the implementation was taken from mysql but it's not correct.
    It seems that it should render:

    • table.c.json['foo'] -> JSON_EXTRACT(example.json, '$."foo"')
    • table.c.json['foo'].as_string() -> CAST(JSON_EXTRACT(example.json, '$."foo"') AS TEXT) (of varchar, not sure it's any different in sqlite)

    does that work for you @matthew-mcallister ?
    A PR would be apprecited for this

  5. CaselIT commented on Feb 28, 2024

    @CaselIT
    Member

    as_integer() and as_float() also does not seem to work, while as_boolean() does but it's not rendering a cast in sql

    @zzzeek is there a reason for this behaviour?

  6. zzzeek commented on Mar 1, 2024

    @zzzeek
    Member

    all of as_integer(), as_float(), as_boolean() pass all tests for sqlite which we have here: https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/testing/suite/test_types.py#L1495 based on these fixtures https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/testing/suite/test_types.py#L1364

    i haven't looked carefully at the code above but that's the current behavioral contract, see how the test suite maps to the script above and see what's different

  7. added
    expected behavior
    and removed
    bug
    PRs (with tests!) welcome
    on Mar 1, 2024
  8. removed this from the 2.0.x milestone on Mar 1, 2024
  9. changed the title [-]SQLite: JSON.as_string does not cast to string[/-] [+]document the "as_string" / "as_int" etc JSON methods not as "CAST" methods, since this is not accurate as to their purpose[/+] on Mar 1, 2024
  10. zzzeek commented on Mar 1, 2024

    @zzzeek
    Member

    OK these methods make use of CAST, however they are not all-purpose "CAST" operations. that is, these two operations are not equivalent:

        table.c.json['foo'].as_string()
        cast(table.c.json['foo'], String)

    The first operation says, "The JSON data in this element is encoded as a string; please return it as a string, and not as another JSON element". The second operation says, "please cast the data from this element to STRING".

    If you have a JSON value that is of unknown type and you'd like it to be unconditionally string you would use CAST just like for any other SQL value that may already not be a string.

    the documentation at https://docs.sqlalchemy.org/en/20/core/type_basics.html#sqlalchemy.types.JSON can be amended to not use the word "CAST" in the way it does right now; "Casting JSON Elements to Other Types" should more accurately say, "Retrieving JSON Elements as their scalar type" or something like that. There should be a note: "note: the JSON type-specification methods should not be relied upon as general purpose CAST methods, as it is assumed the JSON values present already match the requested type. for true type cross-casting, e.g. strings as ints, ints as strings and similar, use the cast() function. A future release of SQLAlchemy may further enhance the type-specification methods to function as fully unconditional CAST methods".

  11. zzzeek commented on Mar 1, 2024

    @zzzeek
    Member

    that said, it looks like the PostgreSQL dialect, which is built around the assumption of a native JSON type, does apply a VARCHAR CAST for the as_string() operation. for non-native JSON dialects, which historically have been "all the rest", JSON elements were always returned as strings so no cast is needed.

    this is not as yet a "bug" because no tests were written assuming someone wanted to retrieve JSON elements with a type other than the one specified without using CAST explicitly. however, since this is the apparent behavior of the other dialects, it likely should be added for SQLIte but I will open that as a separate use case since this was not the original purpose.

  12. zzzeek commented on Mar 1, 2024

    @zzzeek
    Member

    this is #11074

  13. CaselIT commented on Mar 1, 2024

    @CaselIT
    Member

    Understood the rationale, but having experience mainly with pg that use cast the behaviour is a bit strange.
    I guess they should be intended more as type coerce that casts, meaning that the contract is "treat the value as this database type".

    Given that pg is very rigid with the types, and a json str/boolean/float are not the same as its db str/boolean/float, so cast is needed otherwise it will raise type errors.

    Overall though #11074 is probably what people expect

  14. zzzeek commented on Mar 1, 2024

    @zzzeek
    Member

    I was looking to not have unnecessary SQL / CAST verbosity in these expressions and to that degree it's pretty nice that SQLite JSON returns elements in their native type automatically. if we make as_XYZ() always assume a cross-cast, there will always be CAST verbiage.

  15. added this to the 2.0.x milestone on Mar 27, 2024
  16. sqla-tester commented on Mar 27, 2024

    @sqla-tester
    Collaborator

    Federico Caselli has proposed a fix for this issue in the main branch:

    Improve the documentation of json.as method https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/5240

  17. added a commit that references this issue on Jun 18, 2024
    a6f2c4e
  18. zzzeek commented on Aug 22, 2025

    @zzzeek
    Member

    this is really just sqlite. the other dialects that do JSON all do the casting right now

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

    documentationexpected behaviorjsonsqlite

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions