Skip to content

indexes= argument for creating indexes along with a new table - #996

Open
officialasishkumar wants to merge 2 commits into
simonw:mainfrom
officialasishkumar:create-indexes-349
Open

officialasishkumar wants to merge 2 commits into
simonw:mainfrom
officialasishkumar:create-indexes-349

Conversation

@officialasishkumar

@officialasishkumar officialasishkumar commented Dec 4, 2026 •

Copy link
Copy Markdown

Closes #349

Code that creates a table on demand, for example by calling .insert() or .lookup() in a loop, had no way to add indexes only when the table was first created. This adds the indexes= argument proposed in the issue:

db["dogs"].insert(
    {"name": "Cleo", "species": "Mutt", "hobbies": "Raiding picnics"},
    indexes=[("name", "species"), "hobbies"],
)

Each item is a column name, or a tuple of column names for a compound index. The indexes are created with table.create_index(), so they get the usual idx_{table}_{columns} names.

Where it is accepted

db.create_table(), table.create(), insert(), insert_all(), upsert(), upsert_all() and lookup(), plus as a table default through db.table(name, indexes=...). Like the other create() settings it is stored in table._defaults (#655). The new parameter is added at the end of each signature, so existing positional calls are unaffected.

Behaviour

  • Indexes are only created when the call creates the table. Existing tables are left alone, including for ignore=True, if_not_exists=True and transform=True (the same as foreign_keys= today). replace=True creates them on the new table.
  • db.create_table() now runs CREATE TABLE and the index creation inside db.atomic(), so if an index fails the new table is rolled back. With replace=True the old table is dropped inside the same transaction, so it is kept if that happens. table.create() already wrapped this call in atomic().
  • Index columns are checked against the new table first, and an unknown column raises InvalidColumns. Without that check SQLite treats an unknown quoted identifier as a string literal, so create_index(["typo"]) silently creates an index on a constant. I kept that check specific to indexes= rather than changing create_index() itself.
  • lookup() now creates its unique index with find_unique_name=True. Otherwise passing indexes= naming the lookup columns would fail with "index already exists" after the row had been inserted.

Docs

There's a new "Creating indexes along with a table" section in docs/python-api.rst. indexes has also been added to the table configuration and lookup() parameter lists, and to the note about what transform=True does not apply.

Tests

There are new tests in tests/test_create.py and tests/test_lookup.py covering each method, compound and differently-cased columns, table defaults, _defaults persistence, existing tables with ignore/if_not_exists/transform/replace, and rollback on an invalid column for both db.create_table() and insert(), including keeping the old table for replace=True. All 17 fail on main and pass with this change.

Locally (Python 3.13, SQLite 3.54) the full suite passes (1647 passed, 17 skipped), --sqlite-autocommit passes for the affected modules, and so do black, flake8, mypy, pyright, ty, cog, codespell and a sphinx-build -W docs build.

…imonw#349

Code that creates a table on demand, for example by calling .insert() or
.lookup() inside a loop, had no way to add indexes only when the table
was first created, short of running CREATE INDEX IF NOT EXISTS every
time around the loop.

The methods that can create a table now take indexes=, following the
syntax proposed in the issue - a list where each item is a column name
or a tuple of column names for a compound index:

    db["dogs"].insert(
        {"name": "Cleo", "species": "Mutt", "hobbies": "Raiding picnics"},
        indexes=[("name", "species"), "hobbies"],
    )

It is accepted by db.create_table(), table.create(), insert(),
insert_all(), upsert(), upsert_all() and lookup(), and as a table
default through db.table(name, indexes=...). Like the other create()
settings it is stored in table._defaults (simonw#655).

The indexes are created with table.create_index(), so they get the usual
idx_{table}_{columns} names, and only when the call creates the table.
Existing tables are left alone, including for ignore=True,
if_not_exists=True and transform=True.

db.create_table() now runs CREATE TABLE and the index creation inside
db.atomic(), so a failing index rolls back the new table. Index columns
are checked against the new table first and an unknown column raises
InvalidColumns. Without that check SQLite treats an unknown quoted
identifier as a string literal and silently creates an index on a
constant.

lookup() creates its unique index with find_unique_name=True, so passing
indexes= that names the lookup columns does not fail with "index already
exists" after the row has been inserted.

Documented in a new "Creating indexes along with a table" section of the
Python API docs.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-04T20:52:51.753199Z 607450b PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 607450b355

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread sqlite_utils/db.py
)
self.execute(sql)
# Roll back the new table if one of its indexes cannot be created
with self.atomic():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the existing table when index creation fails

When callers invoke Database.create_table(..., replace=True, indexes=[...]) on an existing table and an index names a missing column, the earlier drop() runs before this transaction; validation then raises and this block rolls back only the new table, leaving the original data gone. Move the replace/drop into the same transaction so a bad index cannot turn a failed replacement into data loss.

Useful? React with 👍 / 👎.

Comment thread sqlite_utils/db.py
f"Invalid index columns {invalid_columns} for table "
f"{name} with columns {list(table_columns)}"
)
table.create_index(index_columns)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require a unique index before skipping lookup's constraint

When a table is first created via insert(..., indexes=["name"]) and later used with lookup({"name": ...}), this creates a non-unique index on name. The existing-table branch in lookup() treats any same-column index as satisfying its uniqueness check without checking Index.unique, so it skips creating the unique index and other inserts can persist duplicate lookup keys despite .lookup()'s guarantee. Require a matching unique index before skipping its creation.

Useful? React with 👍 / 👎.

db.create_table() dropped the existing table for replace=True before
opening the transaction that creates the new table and its indexes, so
an invalid indexes= column raised InvalidColumns after the old table and
its rows were already gone.

The drop now happens inside that same transaction, so a failure while
creating the table or one of its indexes rolls the drop back as well.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A way of creating indexes on newly created tables

1 participant