Skip to content

Support for generated columns #411

Open

Description

@eyeseast

This is a fairly new feature -- SQLite version 3.31.0 (2020-01-22) -- that I, admittedly, haven't gotten to work yet. But it looks incredibly useful: https://dgl.cx/2020/06/sqlite-json-support

I'm not sure if this is an option on add-column or a separate command like add-generated-column. Either way, it needs an argument to populate it. It could be something like this:

sqlite-utils add-column data.db table-name generated --as 'json_extract(data, "$.field")' --virtual

More here: https://www.sqlite.org/gencol.html

Activity

  1. added
    enhancement
    on Mar 11, 2022
  2. simonw commented on Mar 11, 2022

    @simonw
    Owner

    I like add-generated-column - feels very clear to me, and is a nice place for adding logic that checks if the DB version supports it or not and shows a useful error.

  3. simonw commented on Mar 11, 2022

    @simonw
    Owner

    The Python API could be:

    db[table_name].add_generated_column("field", str, "json_extract(data, '$.field')", stored=True)
  4. simonw commented on Mar 11, 2022

    @simonw
    Owner

    Just spotted this in https://www.sqlite.org/gencol.html

    The only functional difference is that one cannot add new STORED columns using the ALTER TABLE ADD COLUMN command. Only VIRTUAL columns can be added using ALTER TABLE.

    So to add stored columns to an existing table we would need to use the .transform() trick. Which implies that this should actually be a capability of the various .create() methods, since transform works by creating a new table with those and then copying across the old data.

    Here's where .transform() calls .create_table_sql() under the hood:

    sqls.append(
    self.db.create_table_sql(
    new_table_name,
    dict(new_column_pairs),
    pk=pk,
    not_null=create_table_not_null,
    defaults=create_table_defaults,
    foreign_keys=create_table_foreign_keys,
    column_order=column_order,
    ).strip()
    )

  5. simonw commented on Mar 11, 2022

    @simonw
    Owner

    Two new parameters to .create_table() and friends:

    • generated={...} - generated column definitions
    • generated_stored={...} generated stored column definitions

    These columns will be added at the end of the table, but you can use the column_order= parameter to apply a different order.

  6. simonw commented on Mar 11, 2022

    @simonw
    Owner

    I'm coming round to your suggestion to have this as extra arguments to sqlite-utils add-column now, especially since you also need to pass a column type.

    I'd like to come up with syntax for sqlite-utils create-table as well.

    https://sqlite-utils.datasette.io/en/stable/cli-reference.html#create-table

    Maybe extra --generated-stored colname expression (and --generated) options would work there.

  7. eyeseast commented on Mar 11, 2022

    @eyeseast
    ContributorAuthor

    Good call on adding this to create-table, especially for stored columns. Having the stored/virtual split might make this tricky to implement, but I haven't gone any farther than thinking about what the CLI looks like. I'm going to try making the SQL side work first and figure that'll tell me more about what it needs.

  8. simonw commented on Mar 11, 2022

    @simonw
    Owner

    I tried it out in Jupyter and it works as advertised:

    image

    Introspection is a bit weird: there doesn't seem to be a way to introspect generated columns outside of parsing the stored SQL schema for the columns at the moment! And the .columns method doesn't return them at all:

    @property
    def columns(self) -> List["Column"]:
    "List of :ref:`Columns <reference_db_other_column>` representing the columns in this table or view."
    if not self.exists():
    return []
    rows = self.db.execute("PRAGMA table_info([{}])".format(self.name)).fetchall()
    return [Column(*row) for row in rows]

    Here's why:

    >>> db.execute("PRAGMA table_info('t')").fetchall()
    [(0, 'body', 'TEXT', 0, None, 0)]
    >>> db.execute("PRAGMA table_xinfo('t')").fetchall()
    [(0, 'body', 'TEXT', 0, None, 0, 0), (1, 'd', 'INT', 0, None, 0, 2)]
    

    So table_xinfo() is needed to get back columns including generated columns: https://www.sqlite.org/pragma.html#pragma_table_xinfo

    PRAGMA *schema.*table_xinfo(table-name);

    This pragma returns one row for each column in the named table, including hidden columns in virtual tables. The output is the same as for PRAGMA table_info except that hidden columns are shown rather than being omitted.

  9. simonw commented on Mar 11, 2022

    @simonw
    Owner

    Trying to figure out what that extra field in table_info compared to table_xinfo is:

    >>> list(db.query("PRAGMA table_xinfo('t')"))
    [{'cid': 0,
      'name': 'body',
      'type': 'TEXT',
      'notnull': 0,
      'dflt_value': None,
      'pk': 0,
      'hidden': 0},
     {'cid': 1,
      'name': 'd',
      'type': 'INT',
      'notnull': 0,
      'dflt_value': None,
      'pk': 0,
      'hidden': 2}]
    ``
    Presumably `hidden` 0 v.s 2 v.s. other values has meaning.
    
  10. simonw commented on Nov 12, 2026

    @simonw
    Owner

    The .transform() method currently silently discards existing generated columns, which is bad!

  11. businessdeveloper69 commented on Nov 21, 2026

    @businessdeveloper69

    I tried the generated-column prototype at 770c0d8 with the items table from hacker-news-to-sqlite #6. On main, renaming title dropped the virtual permalink. The prototype kept the correct URL even when I renamed its input id.

    One regression I found is that an unrelated rename can change the results of a numeric filter when the generated column has no declared type.

    from sqlite_utils import Database
    
    db = Database(memory=True)
    db.execute("""create table events(payload text, note text,
        score as (json_extract(payload, '$.score')) stored)""")
    db.execute("""insert into events(payload) values ('{"score":2}'), ('{"score":10}')""")
    query = "select score from events where score >= 9"
    assert list(db.execute(query)) == [(10,)]
    db["events"].transform(rename={"note": "label"})
    assert list(db.execute(query)) == [(10,)]

    The final assertion gets []. The rebuilt schema declares score TEXT, so the values sort as '10', '2'. SQLite's native RENAME COLUMN preserves the empty declared type, integer values and the matching row. I got the same results for VIRTUAL and STORED columns on SQLite 3.45.1 and 3.53.1. An explicit score INTEGER AS (...) also preserved the result on the prototype. Codex prepared a patch against this prototype that preserves the original declared type through a rebuild. With the patch, the same query returned the expected row on both SQLite versions. The full suite passed on both, and the SQLite 3.23.1 compatibility run passed with the generated-column cases skipped.

    AI assisted.

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

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions