Repository navigation
indexes= argument for creating indexes along with a new table - #996
officialasishkumar wants to merge 2 commits into
Conversation
…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.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| ) | ||
| self.execute(sql) | ||
| # Roll back the new table if one of its indexes cannot be created | ||
| with self.atomic(): |
There was a problem hiding this comment.
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 👍 / 👎.
| f"Invalid index columns {invalid_columns} for table " | ||
| f"{name} with columns {list(table_columns)}" | ||
| ) | ||
| table.create_index(index_columns) |
There was a problem hiding this comment.
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.
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 theindexes=argument proposed in the issue: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 usualidx_{table}_{columns}names.Where it is accepted
db.create_table(),table.create(),insert(),insert_all(),upsert(),upsert_all()andlookup(), plus as a table default throughdb.table(name, indexes=...). Like the othercreate()settings it is stored intable._defaults(#655). The new parameter is added at the end of each signature, so existing positional calls are unaffected.Behaviour
ignore=True,if_not_exists=Trueandtransform=True(the same asforeign_keys=today).replace=Truecreates them on the new table.db.create_table()now runsCREATE TABLEand the index creation insidedb.atomic(), so if an index fails the new table is rolled back. Withreplace=Truethe old table is dropped inside the same transaction, so it is kept if that happens.table.create()already wrapped this call inatomic().InvalidColumns. Without that check SQLite treats an unknown quoted identifier as a string literal, socreate_index(["typo"])silently creates an index on a constant. I kept that check specific toindexes=rather than changingcreate_index()itself.lookup()now creates its unique index withfind_unique_name=True. Otherwise passingindexes=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.indexeshas also been added to the table configuration andlookup()parameter lists, and to the note about whattransform=Truedoes not apply.Tests
There are new tests in
tests/test_create.pyandtests/test_lookup.pycovering each method, compound and differently-cased columns, table defaults,_defaultspersistence, existing tables withignore/if_not_exists/transform/replace, and rollback on an invalid column for bothdb.create_table()andinsert(), including keeping the old table forreplace=True. All 17 fail onmainand pass with this change.Locally (Python 3.13, SQLite 3.54) the full suite passes (1647 passed, 17 skipped),
--sqlite-autocommitpasses for the affected modules, and so do black, flake8, mypy, pyright, ty, cog, codespell and asphinx-build -Wdocs build.