Repository navigation
Sqlite json - #434
Sqlite json#434everilae wants to merge 7 commits into
Conversation
Provide a minimal implementation that is able to produce tables having a JSON column and insert/select Python values that are serialized/deserialized to JSON strings.
The JSON path implementation of MySQL and SQLite seem very much alike, so copied the path formatting over. Perhaps these could be unified?
It'd seem that wrapping JSON_EXTRACT in JSON_QUOTE produces a bit saner behaviour, or in other words all returned values are JSON text, compared to INTEGER/REAL for numeric values, SQL NULL for JSON null, SQL text for JSON text and SQL text containing JSON for JSON objects and arrays.
zzzeek
left a comment
There was a problem hiding this comment.
looks great, I'd like to get the test support working (e.g. load the extension) before pulling into gerrit.
| not config.db.dialect._is_mariadb, | ||
| "postgresql >= 9.3" | ||
| "postgresql >= 9.3", | ||
| "sqlite >= 3.9" |
There was a problem hiding this comment.
this also requires that the JSON extension is loaded, right? do we need to do that somewhere? (take a look in lib/sqlalchemy/testing/provision.py)
There was a problem hiding this comment.
It does and to be honest I've not researched much if and how many distributions of SQLite have it statically compiled in wrt. having to load it during run-time. The version of Ubuntu I'm using comes with an SQLite that has it baked in, I think. I guess one should check if it's already there and if not, attempt to load it. On the other hand loading extensions is disabled entirely by default, in which case it may be impossible, and perhaps the tests should just be skipped?
Using PRAGMA compile_options one can check if JSON1 has been enabled in the amalgamation:
>>> ('ENABLE_JSON1',) in c.execute('pragma compile_options').fetchall()
True
|
|
||
| SQLite supports JSON as of version 3.9 through its JSON1_ extension. Note | ||
| that JSON1_ is a `loadable extension <https://www.sqlite.org/loadext.html>`_ | ||
| and as such may not be available, or may require run-time loading. |
There was a problem hiding this comment.
"may" require, what is the expectation with the sqlite3 library that is delivered with standard Python version? when would it not be required?
There was a problem hiding this comment.
That sentence is based on personal experience; as mentioned in the previous comment, the version of Ubuntu I'm using came with an SQLite package that had it without having to jump through any hoops. Something I must look into.
A quick look into CPython reveals that at least Mac/BuildScript/build-installer.py enables JSON1. Not sure about other environments. Does Python rely on system's libsqlite in general?
There was a problem hiding this comment.
well I've got a plain vanilla Python 3 on fedora linux and it seems to be there:
from sqlalchemy import create_engine
e = create_engine("sqlite://", echo="debug")
print(e.scalar("""select json(' { "this" : "is", "a": [ "test" ] } ') """))
print(e.scalar("""select json_array(1,2,'3',4)"""))
2018-03-15 10:10:27,098 INFO sqlalchemy.engine.base.Engine select json(' { "this" : "is", "a": [ "test" ] } ')
2018-03-15 10:10:27,098 INFO sqlalchemy.engine.base.Engine ()
2018-03-15 10:10:27,099 DEBUG sqlalchemy.engine.base.Engine Col ('json(\' { "this" : "is", "a":',)
2018-03-15 10:10:27,099 DEBUG sqlalchemy.engine.base.Engine Row ('{"this":"is","a":["test"]}',)
{"this":"is","a":["test"]}
2018-03-15 10:10:27,099 INFO sqlalchemy.engine.base.Engine select json_array(1,2,'3',4)
2018-03-15 10:10:27,099 INFO sqlalchemy.engine.base.Engine ()
2018-03-15 10:10:27,099 DEBUG sqlalchemy.engine.base.Engine Col ("json_array(1,2,'3',4)",)
2018-03-15 10:10:27,100 DEBUG sqlalchemy.engine.base.Engine Row ('[1,2,"3",4]',)
[1,2,"3",4]
seems promising
There was a problem hiding this comment.
it's supported at build time with the -DSQLITE_ENABLE_JSON flag on sqlite, so this is a bundled extension. on fedora 27 it's there. I have a rhel 7.4 host here they seem to just be on the older sqlite. it's there on my CI server so I think we just don't worry about it, I'll maybe update the doc above to reflect that it's a build flag that most distros should already be setting.
| """ | ||
|
|
||
|
|
||
| # TODO: MySQL and SQLite seem to share the same JSON path syntax, maybe unify? |
There was a problem hiding this comment.
I'd leave this non-unified for the first iteration.
| # NUMERIC storage class, which will blow up deserialization. | ||
| # As an alternative this could be for example JSONTEXT or some | ||
| # such, which would allow reflection to recognize JSON columns, | ||
| # and would ensure TEXT affinity. |
There was a problem hiding this comment.
ugh. it seems like this should be JSONTEXT, we would never want numeric affinity. however, numeric affinity doesn't take place if there's text within the column in any case? can you illustrate the deserialization failing with numeric affinity? are there similar json/ sqlite types in django we can emulate?
There was a problem hiding this comment.
In [3]: engine = create_engine('sqlite:///')
In [4]: metadata = MetaData(bind=engine)
In [5]: t = Table('test', metadata,
...: Column('id', Integer, primary_key=True),
...: Column('data', JSON))
...:
In [6]: metadata.create_all()
In [7]: t.insert().values(data={'foo': 'bar'}).execute()
Out[7]: <sqlalchemy.engine.result.ResultProxy at 0x7fc191f7bf60>
In [8]: t.select().execute().fetchall()
Out[8]: [(1, {'foo': 'bar'})]
In [9]: t.insert().values(data=123).execute()
Out[9]: <sqlalchemy.engine.result.ResultProxy at 0x7fc191f93ba8>
In [10]: t.select().execute().fetchall()
Out[10]: ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
...
TypeError: the JSON object must be str, bytes or bytearray, not 'int'
Indexing works, though:
In [12]: engine.execute(select([t.c.data['foo']])).fetchall()
Out[12]: [('bar',), (None,)]
In the end I also highly doubt that storing plain numbers in a JSON column is common. But it might happen, I guess. Will have to check, if Django has something similar and has solved it.
|
Dear contributor - This pull request is being moved to Gerrit, at https://gerrit.sqlalchemy.org/#/c/zzzeek/sqlalchemy/+/706, where it may be tested and reviewed more closely. As such, the pull request itself is being marked "closed" or "declined", however your contribution is merely being moved to our central review system. Please register at https://gerrit.sqlalchemy.org#/register/ to send and receive comments regarding this item. |
Added support for SQLite's json functionality via the new SQLite implementation for :class:`.sqltypes.JSON`, :class:`.sqlite.JSON`. The name used for the type is ``JSON``, following an example found at SQLite's own documentation. Pull request courtesy Ilja Everilä. Fixes: #3850 Change-Id: I3d2714fb8655343a99d13dc751b16b93d05d7dda Pull-request: #434
This is a skeleton implementation of JSON type for SQLite. There are some open issues, but the usual functionality is there.
Issues:
JSONtypename, which has numeric affinity, not text. This is an issue, if a numeric JSON value is stored, as SQLite will use some numeric storage class, which will trip deserialization.