Skip to content

SQLite3 + JSON. json_quote erroring with no function #4437

Closed

Description

@erichiller
Component Version
SQLAlchemy: 1.3.0b1
Python: 3.6.6
SQLite3 (binary) 3.24.0 2018-06-04

In a table SQLAlchemy created as:

CREATE TABLE base_extended_json (
	uid INTEGER NOT NULL, 
	data JSON, 
	PRIMARY KEY (uid)
)

In a row `I have a series of rows that have the value in their 'data' field all set to the same:

{
    "key1": "val1",
    "key2": "val2"
}

I receive the error when selecting, the query I run is:

_sql_session.query(BaseExtendedJson).filter( sqlalchemy.cast(BaseExtendedJson.data["key2"], String) == 'value2').all()`

The error I receive is:

(sqlite3.OperationalError) no such function: JSON_EXTRACT [SQL: 'SELECT base_extended_json.uid AS base_extended_json_uid, base_extended_json.data AS base_extended_json_data \nFROM base_extended_json \nWHERE CAST(JSON_QUOTE(JSON_EXTRACT(base_extended_json.data, ?)) AS VARCHAR) = ?'] [parameters: ('$."key2"', 'value2')] (Background on this error at: http://sqlalche.me/e/e3q8) <class 'sqlalchemy.exc.OperationalError'>

At first I thought I had to specifically install the json1 extension, but then I tried the same operations in DB Browser for SQLite.

When querying via DB Browser for SQLite The following works:

SELECT json_extract(data, '$."key2"') as k2 FROM base_extended_json WHERE k2 = 'val2'

(returns a 'k2' column with a series of 'val2' rows)

While this query gets no results, but does not error:

SELECT data FROM base_extended_json WHERE cast(json_quote(json_extract(data, '$."key2"')) as varchar) = 'val2'

In a query on a different database, using json_quote does seem to work (in DB Browser), but the same error persists when running from python & SQLAlchemy.

I am at a loss as to what is up. Am I missing something, or is this a bug?

Activity

  1. zzzeek commented on Jan 9, 2019

    @zzzeek
    Member

    can you please share the python code, e.g. simple demo of the model with the query following it so I can run it? thanks

  2. added
    bug
    datatypes
    on Jan 9, 2019
  3. zzzeek commented on Jan 9, 2019

    @zzzeek
    Member

    also have you tried your local sqlite3 executable? note that your Python interpreter may be built against a different version of SQLite. can you run:

    
    >>> from sqlalchemy import create_engine
    e >>> e = create_engine("sqlite://")
    >>> e.connect()
    <sqlalchemy.engine.base.Connection object at 0x7f04f1856860>
    >>> e.dialect.server_version_info
    (3, 22, 0)
    
    
  4. erichiller commented on Jan 9, 2019

    @erichiller
    Author

    Thanks for the quick response, very much appreciated!

    my local sqlite can execute a simple query

    SELECT json_extract(data, '$."key2"') as k2 FROM base_extended_json WHERE k2 = 'val2';
    k2
    ----------
    val2
    val2
    val2
    val2
    val2
    val2
    val2
    val2
    val2
    

    full table:

    select * from base_extended_json;
    uid         data
    ----------  --------------------------------
    496915      {"key1": "val1", "key2": "val2"}
    531733      {"key1": "val1", "key2": "val2"}
    1007444     {"key1": "val1", "key2": "val2"}
    1014772     {"key1": "val1", "key2": "val2"}
    1156495     {"key1": "val1", "key2": "val2"}
    1189271     {"key1": "val1", "key2": "val2"}
    1526464     {"key1": "val1", "key2": "val2"}
    1635200     {"key1": "val1", "key2": "val2"}
    1977604     {"key1": "val1", "key2": "val2"}
    

    Here is the code as a gist

    And my output from the above engine version checker:

    Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 03:37:03) [MSC v.1900 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from sqlalchemy import create_engine
    >>> e = create_engine("sqlite://")
    >>> e.connect()
    <sqlalchemy.engine.base.Connection object at 0x000001C7E536A6A0>
    >>> e.dialect.server_version_info
    (3, 21, 0)
  5. mikeywaites commented on Jan 9, 2019

    @mikeywaites

    @erichiller Thanks for the extra info. I'll be taking a look to see if I can replicate this issue. Hopefully we'll get to the bottom of it fairly quickly!

  6. mikeywaites commented on Jan 9, 2019

    @mikeywaites

    @erichiller Something else that would be useful and might save me some time would be for you to run the following query and share the output please.

    >>> import sqlite3
    >>> con = sqlite3.connect(':memory:')
    >>> cur = con.cursor()
    >>> cur.execute('pragma compile_options;')
    <sqlite3.Cursor object at 0x7fd35c4f0810>
    >>> available_pragmas = cur.fetchall()
    >>> available_pragmas
    >>> con.close()
    
  7. erichiller commented on Jan 9, 2019

    @erichiller
    Author

    From running the above:

    Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 03:37:03) [MSC v.1900 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import sqlite3
    >>> con = sqlite3.connect(':memory:')
    >>> cur = con.cursor()
    >>> cur.execute('pragma compile_options;')
    <sqlite3.Cursor object at 0x0000019C5C5B5EA0>
    >>> available_pragmas = cur.fetchall(
    ... )
    >>> print(available_pragmas)
    [('COMPILER=msvc-1900',), ('ENABLE_FTS4',), ('ENABLE_FTS5',), ('THREADSAFE=1',)]
    >>> con.close()

    It appears it is not using json1 ; the same from my commandline client:

    sqlite> pragma compile_options;
    COMPILER=gcc-5.2.0
    ENABLE_DBSTAT_VTAB
    ENABLE_FTS3
    ENABLE_FTS5
    ENABLE_JSON1
    ENABLE_RTREE
    ENABLE_STMTVTAB
    ENABLE_UNKNOWN_SQL_FUNCTION
    THREADSAFE=0
    

    Is python using an incredibly old sqlite ? Or is it just not compiled ? Do you know if either of these, how can I resolve it ?

  8. mikeywaites commented on Jan 10, 2019

    @mikeywaites

    @erichiller thanks for getting back to us with that info. I'm afraid I don't have any answers for you. I span up a Docker container running this version of python and didn't see this issue and was able to run the script you shared. I'm not sure what OS you're using but maybe there's something different there?

    You can of course enable the extensions manually but I guess that might not be ideal.

    In any case as this is not an issue with SQLAlchemy i'm going to close this ticket. I'd suggest reaching out to the python community on irc or stack overflow or something.

    Sorry I couldn't be more help.

  9. zzzeek commented on Jan 10, 2019

    @zzzeek
    Member

    @erichiller looks like you're on windows so this is likely something specific to that windows build of Python 3.6. if you can specify where you got it from (was it downloaded from python.org?) you can look to see if there are newer versions that include the extension built in.

  10. erichiller commented on Jan 10, 2019

    @erichiller
    Author

    Thank you very much for pointing me in the right direction. Turns out to upgrade sqlite3 on windows all you need to do is download the DLLs from sqlite3's site, then copy/paste into pythondir/DLLs/ -> and overwrite the prior sqlite3.dll.

    Results:

    >>> con = sqlite3.connect(':memory:')
    >>> cur = con.cursor()
    >>> cur.execute('pragma compile_options;')
    <sqlite3.Cursor object at 0x000001937151BD50>
    >>> available_pragmas = cur.fetchall()
    >>> print(available_pragmas)
    [('COMPILER=msvc-1500',), ('ENABLE_COLUMN_METADATA',), ('ENABLE_DBSTAT_VTAB',), ('ENABLE_FTS3',), ('ENABLE_FTS4',), ('ENABLE_FTS5',), ('ENABLE_GEOPOLY',), ('ENABLE_JSON1',), ('ENABLE_RTREE',), ('ENABLE_STMTVTAB',), ('MAX_TRIGGER_DEPTH=100',), ('TEMP_STORE=1',), ('THREADSAFE=1',)]

    Queries now execute with errors, but also, without results -
    I am still getting a lack of results with the generated query. If I manually remove the JSON_QUOTE part of the query, it works.
    Example:

    SELECT base_extended_json.uid AS base_extended_json_uid, base_extended_json.data AS base_extended_json_data
    FROM base_extended_json
    WHERE JSON_QUOTE(JSON_EXTRACT(base_extended_json.data, ?)) = ?
    sqlalchemy.engine.base.Engine ('$."key2"', 'val2')

    Yields nothing. Nor does it yield results when I replace the placeholders and run it in DB Browser:

    SELECT base_extended_json.uid AS base_extended_json_uid, base_extended_json.data AS base_extended_json_data
    FROM base_extended_json
    WHERE JSON_QUOTE(JSON_EXTRACT(base_extended_json.data, '$.key2')) = 'val2'

    However, this does work:

    SELECT base_extended_json.uid AS base_extended_json_uid, base_extended_json.data AS base_extended_json_data
    FROM base_extended_json
    WHERE JSON_EXTRACT(base_extended_json.data, '$.key2') = 'val2'
  11. zzzeek commented on Jan 10, 2019

    @zzzeek
    Member

    does your original test case illustrate this? also you didnt state where you got this python.exe from, should you file an issue with bugs.python.org that their windows build has a broken sqlite in it and should be shipping all necessary dlls ?

  12. erichiller commented on Jan 11, 2019

    @erichiller
    Author

    No results with JSON_QUOTE but success without occurred with the correct DLL is what I meant. My python installation was off python.org ; normal Windows x64 installer. Agreed python should have a more fully featured windows. On your development environment does the query I posted (which uses JSON_QUOTE) work?

  13. zzzeek commented on Jan 11, 2019

    @zzzeek
    Member

    i get this, is that wrong?

    ********************************** Query test **********************************
    2019-01-11 12:58:30,450 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
    2019-01-11 12:58:30,451 INFO sqlalchemy.engine.base.Engine SELECT base_extended_grandchild.uid AS base_extended_grandchild_uid, base_extended_grandchild.data AS base_extended_grandchild_data, base_extended_child2.uid AS base_extended_child2_uid, base_extended_child2.data AS base_extended_child2_data 
    FROM base_extended_grandchild, base_extended_child2 
    WHERE base_extended_grandchild.uid = base_extended_child2.uid
    2019-01-11 12:58:30,451 INFO sqlalchemy.engine.base.Engine ()
    (     1634497) 0.555 | (     1634497) eric
    ******************************** json query ALL ********************************
    2019-01-11 12:58:30,453 INFO sqlalchemy.engine.base.Engine SELECT base_extended_json.uid AS base_extended_json_uid, base_extended_json.data AS base_extended_json_data 
    FROM base_extended_json
    2019-01-11 12:58:30,453 INFO sqlalchemy.engine.base.Engine ()
    [<__main__.BaseExtendedJson object at 0x7f3454c8ca90>]
    ********************************** json query **********************************
    2019-01-11 12:58:30,455 INFO sqlalchemy.engine.base.Engine SELECT base_extended_json.uid AS base_extended_json_uid, base_extended_json.data AS base_extended_json_data 
    FROM base_extended_json 
    WHERE CAST(JSON_QUOTE(JSON_EXTRACT(base_extended_json.data, ?)) AS VARCHAR) = ?
    2019-01-11 12:58:30,455 INFO sqlalchemy.engine.base.Engine ('$."key2"', 'value2')
    []
    
    
  14. zzzeek commented on Jan 11, 2019

    @zzzeek
    Member

    well the test case is wrong, it's asking for "value2" when it should be "val2". following the instrucrtions at https://docs.sqlalchemy.org/en/latest/core/type_basics.html#sqlalchemy.types.JSON, the correct comparison should be:

            _sql_session.query(BaseExtendedJson).filter(
                sqlalchemy.cast(BaseExtendedJson.data["key2"], String) == type_coerce('val2', JSON)).all()
            )
    
    

    returns a whole list of results

  15. zzzeek commented on Jan 11, 2019

    @zzzeek
    Member

    this works too:

            _sql_session.query(BaseExtendedJson).filter(
                BaseExtendedJson.data["key2"] == type_coerce('val2', JSON)).all()
            )
    
    
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

    bugdatatypessqlite

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions