Skip to content

Request: SQLite json1 ext support #3850

Closed

Description

@sqlalchemy-bot

Migrated issue, originally created by Shengjing Zhu (@zhsj)

sqlalchemy.types.JSON only supports PostgreSQL and MySQL. But since SQLite 3.9, it has json support, https://sqlite.org/json1.html

I hope sqlalchemy can support json1 too.

Activity

  1. sqlalchemy-bot commented on Nov 11, 2016

    @sqlalchemy-bot
    CollaboratorAuthor

    Michael Bayer (@zzzeek) wrote:

    im not sure I have the resources to support a SQLIte JSON type directly right now as I generally do not support SQLite extensions. However, SQLAlchemy's type system is fully extensible so I will put up a recipe soon.

  2. sqlalchemy-bot commented on Nov 11, 2016

    @sqlalchemy-bot
    CollaboratorAuthor

    Michael Bayer (@zzzeek) wrote:

    hm, it seems those extensions come pre-installed, OK. it's just SQL functions so there's not much here.

  3. sqlalchemy-bot commented on Nov 11, 2016

    @sqlalchemy-bot
    CollaboratorAuthor

    Michael Bayer (@zzzeek) wrote:

    Here's a recipe. A real version of this feature would be sent as a PR that looks a lot like the MySQL JSON feature, as the syntax here seems to work mostly the same way, except I'm not sure MySQL's json_extract() reutrns non-JSON values the way this one does (maybe it does).

    from sqlalchemy import TypeDecorator, String, func
    from sqlalchemy.types import NullType
    import json
    
    
    class SQLiteJson(TypeDecorator):
        impl = String
    
        class Comparator(String.Comparator):
            def __getitem__(self, index):
                if isinstance(index, tuple):
                    index = "$%s" % (
                        "".join([
                            "[%s]" % elem if isinstance(elem, int)
                            else '."%s"' % elem for elem in index
                        ])
                    )
                elif isinstance(index, int):
                    index = "$[%s]" % index
                else:
                    index = '$."%s"' % index
    
                # json_extract does not appear to return JSON sub-elements
                # which is weird.
                return func.json_extract(self.expr, index, type_=NullType)
    
        comparator_factory = Comparator
    
        def process_bind_param(self, value, dialect):
            if value is not None:
                value = json.dumps(value)
            return value
    
        def process_result_value(self, value, dialect):
            if value is not None:
                value = json.loads(value)
            return value
    
    from sqlalchemy import create_engine, Table, MetaData, Column, Integer, select
    
    e = create_engine("sqlite://", echo='debug')
    
    m = MetaData()
    t = Table(
        't', m, Column('id', Integer, primary_key=True),
        Column('data', SQLiteJson)
    
    )
    m.create_all(e)
    
    with e.connect() as conn:
        conn.execute(
            t.insert(), data={"x": {"y": "two", "z": [1, 2, 3]}}
        )
    
        value = conn.scalar(
            select([t.c.data[('x', 'y')]]).where(t.c.data[('x', 'y')] == 'two')
        )
        print value
    
    
    
    
  4. sqlalchemy-bot commented on Nov 11, 2016

    @sqlalchemy-bot
    CollaboratorAuthor

    Changes by Michael Bayer (@zzzeek):

    • removed labels: low priority
  5. sqlalchemy-bot commented on Nov 11, 2016

    @sqlalchemy-bot
    CollaboratorAuthor

    Changes by Michael Bayer (@zzzeek):

    • set milestone to "1.x.xx"
  6. sqlalchemy-bot commented on Jun 4, 2017

    @sqlalchemy-bot
    CollaboratorAuthor

    Timothée Jeannin (@TimotheeJeannin) wrote:

    Would be very nice to have support for the JSON type in SQLite databases !

  7. sqlalchemy-bot commented on Nov 4, 2017

    @sqlalchemy-bot
    CollaboratorAuthor
  8. sqlalchemy-bot commented on Nov 6, 2017

    @sqlalchemy-bot
    CollaboratorAuthor

    Michael Bayer (@zzzeek) wrote:

    I don't have any plans to work on this alone so someone would need to work on adopting the above recipe into a patch that looks a lot like the MySQL feature.

  9. sqlalchemy-bot commented on Mar 12, 2018

    @sqlalchemy-bot
    CollaboratorAuthor

    Ilja Everilä (@everilae) wrote:

    For reasons perfectly unclear to me

    JSON_QUOTE(JSON_EXTRACT(...))
    

    would seem to produce somewhat the same behaviour as MySQL's JSON_EXTRACT has. No idea why, since a simple

    JSON_QUOTE('{"foo": "bar"}')
    

    does produce a JSON string containing escaped JSON, but for extracted text this does not happen:

    sqlite> create table data_table (data json);
    sqlite> insert into data_table values ('{"json": {"foo": "bar"}}')
       ...>                             , ('{"json": 1}')
       ...>                             , ('{"json": 1.2}')
       ...>                             , ('{"json": true}')
       ...>                             , ('{"json": false}')
       ...>                             , ('{"json": null}')
       ...>                             , ('{"json": "foobar"}')
       ...>                             , ('{"json": [1, 2, 3]}')
       ...>                             , ('{"json": ["foo", "bar"]}')
       ...>                             , ('{"json": [{"foo": "bar"}]}');
    sqlite> select json_quote(json_extract(data, '$.json')) from data_table;
    {"foo":"bar"}
    1
    1.2
    1
    0
    null
    "foobar"
    [1,2,3]
    ["foo","bar"]
    [{"foo":"bar"}]
    sqlite> select json_quote('{"foo": "bar"}');
    "{\"foo\": \"bar\"}"
    
    

    With that in place a very simple copy of the MySQL implementation passes the current JSON tests, though it incorrectly produces JSON null for missing keys.

  10. sqlalchemy-bot commented on Mar 12, 2018

    @sqlalchemy-bot
    CollaboratorAuthor

    Ilja Everilä (@everilae) wrote:

    Turns out this is documented in "3.3 VALUE arguments" (just managed to skip that part entirely first):

    However, if a value argument come directly from the result of another json1 function, then the argument is understood to be actual JSON and the complete JSON is inserted rather than a quoted string.

    and as such dependable.

  11. sqlalchemy-bot commented on Mar 15, 2018

    @sqlalchemy-bot
    CollaboratorAuthor
  12. sqlalchemy-bot commented on Mar 15, 2018

    @sqlalchemy-bot
    CollaboratorAuthor

    Changes by Michael Bayer (@zzzeek):

    • edited description
  13. sqlalchemy-bot commented on Mar 15, 2018

    @sqlalchemy-bot
    CollaboratorAuthor

    Changes by Michael Bayer (@zzzeek):

    • changed milestone from "1.x.xx" to "1.3"
  14. sqlalchemy-bot commented on Mar 16, 2018

    @sqlalchemy-bot
    CollaboratorAuthor
  15. sqlalchemy-bot commented on Mar 16, 2018

    @sqlalchemy-bot
    CollaboratorAuthor

    Michael Bayer (@zzzeek) wrote:

    well I just kicked the build follower which had crashed so lets see how the base test suite runs.

  16. sqlalchemy-bot commented on Mar 27, 2018

    @sqlalchemy-bot
    CollaboratorAuthor

    Michael Bayer (@zzzeek) wrote:

    Issue #4226 was marked as a duplicate of this issue.

  17. sqlalchemy-bot commented on Jul 10, 2018

    @sqlalchemy-bot
    CollaboratorAuthor

    Michael Bayer (@zzzeek) wrote:

    Sqlite json

    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: zzzeek/sqlalchemy#434

    → 62d5908

  18. sqlalchemy-bot commented on Jul 10, 2018

    @sqlalchemy-bot
    CollaboratorAuthor

    Changes by Michael Bayer (@zzzeek):

    • changed status to closed
  19. added this to the 1.3 milestone on Nov 27, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions