extracts= accepts tuple as well as list

This commit is contained in:
Simon Willison 2019-07-23 18:53:39 +02:00
commit afad1f70d0
2 changed files with 21 additions and 10 deletions

View file

@ -1033,6 +1033,6 @@ def _hash(record):
def resolve_extracts(extracts): def resolve_extracts(extracts):
if extracts is None: if extracts is None:
extracts = {} extracts = {}
if isinstance(extracts, list): if isinstance(extracts, (list, tuple)):
extracts = {item: item for item in extracts} extracts = {item: item for item in extracts}
return extracts return extracts

View file

@ -2,9 +2,16 @@ from sqlite_utils.db import Index
import pytest import pytest
@pytest.mark.parametrize(
"kwargs,expected_table",
[
(dict(extracts={"species_id": "Species"}), "Species"),
(dict(extracts=["species_id"]), "species_id"),
(dict(extracts=("species_id",)), "species_id"),
],
)
@pytest.mark.parametrize("use_table_factory", [True, False]) @pytest.mark.parametrize("use_table_factory", [True, False])
def test_extracts(fresh_db, use_table_factory): def test_extracts(fresh_db, kwargs, expected_table, use_table_factory):
kwargs = dict(extracts={"species_id": "Species"})
table_kwargs = {} table_kwargs = {}
insert_kwargs = {} insert_kwargs = {}
if use_table_factory: if use_table_factory:
@ -21,29 +28,33 @@ def test_extracts(fresh_db, use_table_factory):
**insert_kwargs **insert_kwargs
) )
# Should now have two tables: Trees and Species # Should now have two tables: Trees and Species
assert {"Species", "Trees"} == set(fresh_db.table_names()) assert {expected_table, "Trees"} == set(fresh_db.table_names())
assert ( assert (
"CREATE TABLE [Species] (\n [id] INTEGER PRIMARY KEY,\n [value] TEXT\n)" "CREATE TABLE [{}] (\n [id] INTEGER PRIMARY KEY,\n [value] TEXT\n)".format(
== fresh_db["Species"].schema expected_table
)
== fresh_db[expected_table].schema
) )
assert ( assert (
"CREATE TABLE [Trees] (\n [id] INTEGER,\n [species_id] INTEGER REFERENCES [Species]([id])\n)" "CREATE TABLE [Trees] (\n [id] INTEGER,\n [species_id] INTEGER REFERENCES [{}]([id])\n)".format(
expected_table
)
== fresh_db["Trees"].schema == fresh_db["Trees"].schema
) )
# Should have unique index on Species # Should have unique index on Species
assert [ assert [
Index( Index(
seq=0, seq=0,
name="idx_Species_value", name="idx_{}_value".format(expected_table),
unique=1, unique=1,
origin="c", origin="c",
partial=0, partial=0,
columns=["value"], columns=["value"],
) )
] == fresh_db["Species"].indexes ] == fresh_db[expected_table].indexes
# Finally, check the rows # Finally, check the rows
assert [{"id": 1, "value": "Oak"}, {"id": 2, "value": "Palm"}] == list( assert [{"id": 1, "value": "Oak"}, {"id": 2, "value": "Palm"}] == list(
fresh_db["Species"].rows fresh_db[expected_table].rows
) )
assert [ assert [
{"id": 1, "species_id": 1}, {"id": 1, "species_id": 1},