Skip to content

Commit 135db4c

Browse files
simonwclaude
andcommitted
extract() reuses an existing unique index on the lookup table
When table.extract() is pointed at a lookup table that already exists it always ran CREATE UNIQUE INDEX IF NOT EXISTS idx_<table>_<columns>, which only checks for an index of that name. A lookup table with a UNIQUE constraint, or a unique index under another name, ended up with a second, redundant unique index. extract() now skips creating the index if the lookup table already has a unique index covering exactly the extracted columns, in any order. Partial indexes, indexes on expressions and indexes with a collation other than BINARY do not count, since they do not enforce the same uniqueness. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1 parent 74c0b6c commit 135db4c

3 files changed

Lines changed: 123 additions & 1 deletion

File tree

‎docs/python-api.rst‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2229,6 +2229,10 @@ This produces a lookup table like so:
22292229
22302230
Rows where every extracted column is ``null`` are not extracted: no record is created for them in the lookup table and their foreign key column is left as ``null``. When extracting multiple columns, rows where at least one of the extracted columns has a value will be extracted as usual.
22312231
2232+
The lookup table is given a unique index on the extracted columns, called ``idx_Species_name_latin`` in this example.
2233+
2234+
If the lookup table already exists, the extracted values are matched against its existing rows and a new row is added for each value it does not have yet. It needs an ``id`` primary key and columns with the same names and types as the extracted columns. If it already has a unique index or ``UNIQUE`` constraint covering exactly those columns that index is used, otherwise one is added.
2235+
22322236
.. note::
22332237
In the CLI: :ref:`sqlite-utils extract <cli_extract>`
22342238

‎sqlite_utils/db.py‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2502,6 +2502,36 @@ def indexes(self) -> list[Index]:
25022502
indexes.append(Index(**row))
25032503
return indexes
25042504

2505+
def _has_unique_index_on(self, columns: Iterable[str]) -> bool:
2506+
"""
2507+
Does this table have a unique index covering exactly these columns,
2508+
in any order?
2509+
2510+
Only indexes that enforce uniqueness in the same way as one created
2511+
by ``create_index(columns, unique=True)`` count: not partial indexes,
2512+
indexes on expressions or indexes that use a collation other than
2513+
``BINARY``.
2514+
"""
2515+
wanted = sorted(columns)
2516+
candidates = {
2517+
index.name
2518+
for index in self.indexes
2519+
if index.unique and not index.partial and sorted(index.columns) == wanted
2520+
}
2521+
if not candidates:
2522+
return False
2523+
for xindex in self.xindexes:
2524+
if xindex.name not in candidates:
2525+
continue
2526+
key_columns = [column for column in xindex.columns if column.key]
2527+
if all(
2528+
column.name is not None
2529+
and (column.coll or "BINARY").upper() == "BINARY"
2530+
for column in key_columns
2531+
):
2532+
return True
2533+
return False
2534+
25052535
@property
25062536
def xindexes(self) -> list[XIndex]:
25072537
"List of indexes defined on this table using the more detailed ``XIndex`` format."
@@ -3337,7 +3367,13 @@ def extract(
33373367
strict=self.strict,
33383368
)
33393369
lookup_columns = [(rename.get(col) or col) for col in columns]
3340-
lookup_table.create_index(lookup_columns, unique=True, if_not_exists=True)
3370+
# INSERT OR IGNORE needs a unique index on these columns. An
3371+
# existing lookup table may have one already, under any name or
3372+
# as a UNIQUE constraint - if so it is reused
3373+
if not lookup_table._has_unique_index_on(lookup_columns):
3374+
lookup_table.create_index(
3375+
lookup_columns, unique=True, if_not_exists=True
3376+
)
33413377
# Rows where every extracted column is null are left alone - they
33423378
# get a null foreign key and no lookup table record, see #186
33433379
all_columns_are_null = " AND ".join(

‎tests/test_extract.py‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,88 @@ def test_reuse_lookup_table(fresh_db):
166166
]
167167

168168

169+
@pytest.mark.parametrize(
170+
"create_sql,expected_indexes",
171+
(
172+
# A UNIQUE constraint on the column
173+
(
174+
'CREATE TABLE "species" ("id" INTEGER PRIMARY KEY, "name" TEXT UNIQUE)',
175+
["sqlite_autoindex_species_1"],
176+
),
177+
# A unique index that is not called idx_species_name
178+
(
179+
'CREATE TABLE "species" ("id" INTEGER PRIMARY KEY, "name" TEXT);'
180+
'CREATE UNIQUE INDEX "species_by_name" ON "species" ("name")',
181+
["species_by_name"],
182+
),
183+
),
184+
)
185+
def test_extract_reuses_existing_unique_index(fresh_db, create_sql, expected_indexes):
186+
# extract() used to add idx_species_name beside an index like these
187+
fresh_db.executescript(create_sql)
188+
fresh_db.table("species").insert({"id": 1, "name": "Wolf"})
189+
fresh_db.table("sightings").insert_all(
190+
[{"id": 10, "species": "Wolf"}, {"id": 11, "species": "Fox"}], pk="id"
191+
)
192+
fresh_db.table("sightings").extract("species", rename={"species": "name"})
193+
assert [
194+
index.name for index in fresh_db.table("species").indexes
195+
] == expected_indexes
196+
assert list(fresh_db.table("species").rows) == [
197+
{"id": 1, "name": "Wolf"},
198+
{"id": 2, "name": "Fox"},
199+
]
200+
assert list(fresh_db.table("sightings").rows) == [
201+
{"id": 10, "species_id": 1},
202+
{"id": 11, "species_id": 2},
203+
]
204+
205+
206+
def test_extract_reuses_existing_unique_index_multiple_columns(fresh_db):
207+
# The index can list the columns in a different order
208+
fresh_db.executescript(
209+
'CREATE TABLE "species" ('
210+
'"id" INTEGER PRIMARY KEY, "common" TEXT, "latin" TEXT, '
211+
'UNIQUE ("latin", "common"))'
212+
)
213+
fresh_db.table("trees").insert(
214+
{"id": 1, "common": "Palm", "latin": "Arecaceae"}, pk="id"
215+
)
216+
fresh_db.table("trees").extract(["common", "latin"], table="species")
217+
assert [index.name for index in fresh_db.table("species").indexes] == [
218+
"sqlite_autoindex_species_1"
219+
]
220+
assert list(fresh_db.table("species").rows) == [
221+
{"id": 1, "common": "Palm", "latin": "Arecaceae"}
222+
]
223+
224+
225+
@pytest.mark.parametrize(
226+
"index_sql",
227+
(
228+
# Not unique
229+
'CREATE INDEX "other" ON "species" ("name")',
230+
# Does not cover every row
231+
'CREATE UNIQUE INDEX "other" ON "species" ("name") WHERE "name" != \'\'',
232+
# Treats Wolf and wolf as the same value
233+
'CREATE UNIQUE INDEX "other" ON "species" ("name" COLLATE NOCASE)',
234+
# On an expression, not the column
235+
'CREATE UNIQUE INDEX "other" ON "species" (lower("name"))',
236+
# Covers more than the extracted column
237+
'CREATE UNIQUE INDEX "other" ON "species" ("name", "id")',
238+
),
239+
)
240+
def test_extract_adds_index_if_existing_index_is_not_equivalent(fresh_db, index_sql):
241+
fresh_db.table("species").insert({"id": 1, "name": "Wolf"}, pk="id")
242+
fresh_db.execute(index_sql)
243+
fresh_db.table("sightings").insert({"id": 10, "species": "Fox"}, pk="id")
244+
fresh_db.table("sightings").extract("species", rename={"species": "name"})
245+
assert {index.name for index in fresh_db.table("species").indexes} == {
246+
"other",
247+
"idx_species_name",
248+
}
249+
250+
169251
def test_extract_error_on_incompatible_existing_lookup_table(fresh_db):
170252
fresh_db.table("species").insert({"id": 1})
171253
fresh_db.table("tree").insert({"name": "Tree 1", "common_name": "Palm"})

0 commit comments

Comments
 (0)