diff --git a/docs/python-api.rst b/docs/python-api.rst index 78f73f2cc..5d0a1cb3d 100644 --- a/docs/python-api.rst +++ b/docs/python-api.rst @@ -785,7 +785,7 @@ You can directly create a new table without inserting any data into it using the The first argument here is a dictionary specifying the columns you would like to create. Each column is paired with a Python type indicating the type of column. See :ref:`python_api_add_column` for full details on how these types work. -This method takes optional arguments ``pk=``, ``column_order=``, ``foreign_keys=``, ``not_null=set()`` and ``defaults=dict()`` - explained below. +This method takes optional arguments ``pk=``, ``column_order=``, ``foreign_keys=``, ``not_null=set()``, ``defaults=dict()`` and ``indexes=`` - explained below. A ``sqlite_utils.utils.sqlite3.OperationalError`` will be raised if a table of that name already exists. @@ -817,7 +817,7 @@ The ``transform=True`` option will update the table schema if any of the followi - The order of the columns, defined using ``column_order=`` - The ``not_null=`` or ``defaults=`` arguments -Changes to ``foreign_keys=`` are not currently detected and applied by ``transform=True``. +Changes to ``foreign_keys=`` and ``indexes=`` are not currently detected and applied by ``transform=True``. You can pass ``strict=True`` to create a table in ``STRICT`` mode: @@ -979,7 +979,7 @@ You can set default values for these methods by accessing the table through the # Now you can call .insert() like so: table.insert({"id": 1, "name": "Tracy", "score": 5}) -The configuration options that can be specified in this way are ``pk``, ``foreign_keys``, ``column_order``, ``not_null``, ``defaults``, ``batch_size``, ``hash_id``, ``hash_id_columns``, ``alter``, ``ignore``, ``replace``, ``extracts``, ``conversions``, ``columns``, ``strict``. These are all documented below. +The configuration options that can be specified in this way are ``pk``, ``foreign_keys``, ``column_order``, ``not_null``, ``defaults``, ``batch_size``, ``hash_id``, ``hash_id_columns``, ``alter``, ``ignore``, ``replace``, ``extracts``, ``conversions``, ``columns``, ``strict``, ``indexes``. These are all documented below. .. _python_api_defaults_not_null: @@ -1027,6 +1027,36 @@ Here's an example that uses these features: .. note:: In the CLI: :ref:`sqlite-utils insert --not-null and --default ` +.. _python_api_create_table_indexes: + +Creating indexes along with a table +----------------------------------- + +The methods that can cause a table to be created also take an optional ``indexes=`` argument, listing indexes that should be created at the same time as the table. These indexes are only created if the table does not exist yet, so you can pass the same argument every time code like this runs in a loop: + +.. code-block:: python + + db.table("dogs").insert( + {"name": "Cleo", "species": "Mutt", "hobbies": "Raiding picnics"}, + indexes=[("name", "species"), "hobbies"], + ) + +Each item in the list is either a column name, for an index on that column, or a tuple of column names, for a compound index across those columns. The example above creates two indexes called ``idx_dogs_name_species`` and ``idx_dogs_hobbies``, named in the same way as indexes created by :ref:`table.create_index() `. + +The methods that take this argument are: + +* ``db.create_table(...)`` +* ``table.create(...)`` +* ``table.insert(...)`` +* ``table.insert_all(...)`` +* ``table.upsert(...)`` +* ``table.upsert_all(...)`` +* ``table.lookup(...)`` + +A ``sqlite_utils.db.InvalidColumns`` exception will be raised if an index refers to a column that the new table does not have. If an index cannot be created, the table is not created either, and any existing table that ``replace=True`` would have dropped is kept. + +Tables that already exist are left unchanged, including when ``.create()`` is called with ``ignore=True``, ``if_not_exists=True`` or ``transform=True``. Use :ref:`table.create_index() ` to add an index to an existing table. + .. _python_api_rename_table: Renaming a table @@ -1388,6 +1418,7 @@ The first time this is called the record will be created for ``name="Palm"``. An - ``conversions`` - ``columns`` - ``strict`` +- ``indexes`` .. _python_api_extracts: diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index e85ac52a9..2a018898b 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -345,6 +345,9 @@ class TransformError(Exception): PrimaryKey = str | tuple[str, ...] | list[str] +# Each index is a column name, or an iterable of column names for a compound index +IndexesType = Iterable[str | Iterable[str]] + class Default: pass @@ -1726,6 +1729,7 @@ def create_table( ignore: bool = False, transform: bool = False, strict: bool = False, + indexes: IndexesType | None = None, ) -> "Table": """ Create a table with the specified name and the specified ``{column_name: type}`` columns. @@ -1747,14 +1751,12 @@ def create_table( :param ignore: Silently do nothing if table already exists :param transform: If table already exists transform it to fit the specified schema :param strict: Apply STRICT mode to table + :param indexes: Indexes to create if this creates the table, see :ref:`python_api_create_table_indexes` """ # Transform table to match the new definition if table already exists: - if self[name].exists(): - if ignore: - return self.table(name) - elif replace: - self[name].drop() - if transform and self[name].exists(): + if self[name].exists() and ignore: + return self.table(name) + if transform and not replace and self[name].exists(): table = self.table(name) should_transform = False # First add missing columns and figure out columns to drop @@ -1821,21 +1823,48 @@ def create_table( pk=pk, ) return table - sql = self.create_table_sql( - name=name, - columns=columns, - pk=pk, - foreign_keys=foreign_keys, - column_order=column_order, - not_null=not_null, - defaults=defaults, - hash_id=hash_id, - hash_id_columns=hash_id_columns, - extracts=extracts, - if_not_exists=if_not_exists, - strict=strict, - ) - self.execute(sql) + # A single transaction, so if the table or one of its indexes cannot be + # created nothing is changed - not even the drop for replace=True + with self.atomic(): + if replace and self[name].exists(): + self[name].drop() + # Indexes are only created along with the table - so not when + # if_not_exists=True finds that the table already exists + new_indexes = ( + [] if indexes is None or self[name].exists() else list(indexes) + ) + sql = self.create_table_sql( + name=name, + columns=columns, + pk=pk, + foreign_keys=foreign_keys, + column_order=column_order, + not_null=not_null, + defaults=defaults, + hash_id=hash_id, + hash_id_columns=hash_id_columns, + extracts=extracts, + if_not_exists=if_not_exists, + strict=strict, + ) + self.execute(sql) + if new_indexes: + table = self.table(name) + table_columns = table.columns_dict + for index in new_indexes: + index_columns = [index] if isinstance(index, str) else list(index) + # SQLite would index an unknown "column" as a string literal + invalid_columns = [ + column + for column in index_columns + if resolve_casing(column, table_columns) not in table_columns + ] + if invalid_columns: + raise InvalidColumns( + f"Invalid index columns {invalid_columns} for table " + f"{name} with columns {list(table_columns)}" + ) + table.create_index(index_columns) return self.table( name, pk=pk, @@ -1845,6 +1874,7 @@ def create_table( defaults=defaults, hash_id=hash_id, hash_id_columns=hash_id_columns, + indexes=indexes, ) def rename_table(self, name: str, new_name: str) -> None: @@ -2287,6 +2317,7 @@ class Table(Queryable): :param conversions: Dictionary of column names and conversion functions :param columns: Dictionary of column names to column types :param strict: If True, apply STRICT mode to table + :param indexes: List of indexes to create along with the table """ #: The ``rowid`` of the last inserted, updated or selected row. @@ -2313,6 +2344,7 @@ def __init__( conversions: dict | None = None, columns: dict[str, Any] | None = None, strict: bool = False, + indexes: IndexesType | None = None, ): super().__init__(db, name) self._defaults = { @@ -2331,6 +2363,7 @@ def __init__( "conversions": conversions or {}, "columns": columns, "strict": strict, + "indexes": indexes, } def __repr__(self) -> str: @@ -2565,6 +2598,7 @@ def create( ignore: bool = False, transform: bool = False, strict: bool | Default | None = DEFAULT, + indexes: IndexesType | Default | None = DEFAULT, ) -> "Table": """ Create a table with the specified columns. @@ -2585,6 +2619,7 @@ def create( :param ignore: Silently do nothing if table already exists :param transform: If table already exists transform it to fit the specified schema :param strict: Apply STRICT mode to table + :param indexes: Indexes to create if this creates the table, see :ref:`python_api_create_table_indexes` """ # Resolve defaults from _defaults (issue #655) pk = self.value_or_default("pk", pk) @@ -2596,6 +2631,7 @@ def create( hash_id_columns = self.value_or_default("hash_id_columns", hash_id_columns) extracts = self.value_or_default("extracts", extracts) strict = self.value_or_default("strict", strict) + indexes = self.value_or_default("indexes", indexes) # Store configuration in _defaults for subsequent operations (issue #655) # Don't store pk if hash_id is set, since pk is derived from hash_id in that case @@ -2617,6 +2653,8 @@ def create( self._defaults["extracts"] = extracts if strict: self._defaults["strict"] = strict + if indexes is not None: + self._defaults["indexes"] = indexes columns = {name: value for (name, value) in columns.items()} with self.db.atomic(): @@ -2636,6 +2674,7 @@ def create( ignore=ignore, transform=transform, strict=cast(bool, strict), + indexes=indexes, ) return self @@ -4778,6 +4817,7 @@ def insert( conversions: dict[str, str] | Default | None = DEFAULT, columns: dict[str, Any] | Default | None = DEFAULT, strict: bool | Default | None = DEFAULT, + indexes: IndexesType | Default | None = DEFAULT, ) -> "Table": """ Insert a single record into the table. The table will be created with a schema that matches @@ -4811,6 +4851,8 @@ def insert( :param columns: Dictionary over-riding the detected types used for the columns, for example ``{"age": int, "weight": float}``. :param strict: Boolean, apply STRICT mode if creating the table. + :param indexes: List of indexes to create if creating the table, each one a column name + or a tuple of column names. See :ref:`python_api_create_table_indexes`. """ return self.insert_all( [record], @@ -4828,6 +4870,7 @@ def insert( conversions=conversions, columns=columns, strict=strict, + indexes=indexes, ) def insert_all( @@ -4851,6 +4894,7 @@ def insert_all( upsert: bool = False, analyze: bool = False, strict: bool | Default | None = DEFAULT, + indexes: IndexesType | Default | None = DEFAULT, ) -> "Table": """ Like ``.insert()`` but takes a list of records and ensures that the table @@ -4873,6 +4917,7 @@ def insert_all( conversions = self.value_or_default("conversions", conversions) or {} columns = self.value_or_default("columns", columns) strict = self.value_or_default("strict", strict) + indexes = self.value_or_default("indexes", indexes) if hash_id_columns and hash_id is None: hash_id = "id" @@ -5020,6 +5065,7 @@ def insert_all( hash_id_columns=hash_id_columns, extracts=extracts, strict=strict, + indexes=indexes, ) if list_mode: # In list mode, columns are already known @@ -5219,6 +5265,7 @@ def upsert( conversions: dict[str, str] | Default | None = DEFAULT, columns: dict[str, Any] | Default | None = DEFAULT, strict: bool | Default | None = DEFAULT, + indexes: IndexesType | Default | None = DEFAULT, ) -> "Table": """ Like ``.insert()`` but performs an ``UPSERT``, where records are inserted if they do @@ -5240,6 +5287,7 @@ def upsert( conversions=conversions, columns=columns, strict=strict, + indexes=indexes, ) def upsert_all( @@ -5259,6 +5307,7 @@ def upsert_all( columns: dict[str, Any] | Default | None = DEFAULT, analyze: bool = False, strict: bool | Default | None = DEFAULT, + indexes: IndexesType | Default | None = DEFAULT, ) -> "Table": """ Like ``.upsert()`` but can be applied to a list of records. @@ -5280,6 +5329,7 @@ def upsert_all( upsert=True, analyze=analyze, strict=strict, + indexes=indexes, ) def add_missing_columns(self, records: Iterable[dict[str, Any]]) -> "Table": @@ -5303,6 +5353,7 @@ def lookup( conversions: dict[str, str] | None = None, columns: dict[str, Any] | None = None, strict: bool | None = False, + indexes: IndexesType | None = None, ): """ Create or populate a lookup table with the specified values. @@ -5366,6 +5417,7 @@ def lookup( conversions=conversions, columns=columns, strict=strict, + indexes=indexes, ).last_pk else: pk = self.insert( @@ -5379,8 +5431,10 @@ def lookup( conversions=conversions, columns=columns, strict=strict, + indexes=indexes, ).last_pk - self.create_index(lookup_values.keys(), unique=True) + # find_unique_name=True in case indexes= already used the default name + self.create_index(lookup_values.keys(), unique=True, find_unique_name=True) return pk def m2m( diff --git a/tests/test_create.py b/tests/test_create.py index fcd9eee34..e51ec9136 100644 --- a/tests/test_create.py +++ b/tests/test_create.py @@ -1586,6 +1586,112 @@ def test_create_transform_keyword_literal_defaults_unchanged(fresh_db): assert not any(sql.startswith("CREATE TABLE") for sql, _ in traces) +def _index_columns(table): + return {index.name: index.columns for index in table.indexes} + + +@pytest.mark.parametrize( + "method_name", ("insert", "insert_all", "upsert", "upsert_all", "create") +) +def test_indexes_created_with_table(fresh_db, method_name): + table = fresh_db.table("dogs") + method = getattr(table, method_name) + + def records(record): + return [record] if method_name.endswith("_all") else record + + if method_name == "create": + first = {"id": int, "name": str, "species": str, "hobbies": str} + else: + first = records({"id": 1, "name": "Cleo", "species": "Mutt", "hobbies": "Fun"}) + method(first, pk="id", indexes=[("name", "species"), "hobbies"]) + expected = { + "idx_dogs_name_species": ["name", "species"], + "idx_dogs_hobbies": ["hobbies"], + } + assert _index_columns(table) == expected + # Indexes are only created if the table is being created + if method_name != "create": + method( + records( + {"id": 2, "name": "Pancakes", "species": "Corgi", "hobbies": "Naps"} + ), + indexes=["species"], + ) + assert table.count == 2 + assert _index_columns(table) == expected + + +def test_create_table_indexes(fresh_db): + table = fresh_db.create_table( + "dogs", + {"id": int, "name": str, "age": int}, + pk="id", + # Iterators and differently cased column names work too + indexes=["NAME", iter(["name", "age"])], + ) + assert _index_columns(table) == { + "idx_dogs_NAME": ["name"], + "idx_dogs_name_age": ["name", "age"], + } + + +@pytest.mark.parametrize( + "kwargs,expected_indexes", + ( + ({"ignore": True}, {}), + ({"if_not_exists": True}, {}), + ({"transform": True}, {}), + ({"replace": True}, {"idx_dogs_name": ["name"]}), + ), +) +def test_create_indexes_table_already_exists(fresh_db, kwargs, expected_indexes): + fresh_db.table("dogs").create({"id": int, "name": str}, pk="id") + # The extra column means transform=True has to transform the table + fresh_db.table("dogs").create( + {"id": int, "name": str, "age": int}, pk="id", indexes=["name"], **kwargs + ) + assert _index_columns(fresh_db.table("dogs")) == expected_indexes + + +@pytest.mark.parametrize("use_create_table", (True, False)) +def test_create_indexes_invalid_column(fresh_db, use_create_table): + indexes = ["name", ("id", "nope")] + with pytest.raises(InvalidColumns) as ex: + if use_create_table: + fresh_db.create_table("dogs", {"id": int, "name": str}, indexes=indexes) + else: + fresh_db.table("dogs").insert({"id": 1, "name": "Cleo"}, indexes=indexes) + assert ex.value.args == ( + "Invalid index columns ['nope'] for table dogs with columns ['id', 'name']", + ) + # The table is rolled back along with any indexes created before the error + assert not fresh_db.table("dogs").exists() + + +def test_create_indexes_invalid_column_replace_keeps_table(fresh_db): + dogs = fresh_db.table("dogs") + dogs.insert({"id": 1, "name": "Cleo"}, pk="id") + with pytest.raises(InvalidColumns): + fresh_db.create_table( + "dogs", {"id": int, "name": str}, pk="id", replace=True, indexes=["nope"] + ) + # The table dropped by replace=True is restored + assert list(dogs.rows) == [{"id": 1, "name": "Cleo"}] + + +def test_indexes_table_configuration(fresh_db): + table = fresh_db.table("dogs", pk="id", indexes=["name"]) + table.insert({"id": 1, "name": "Cleo"}) + assert _index_columns(table) == {"idx_dogs_name": ["name"]} + + +def test_indexes_persist_after_create_655(fresh_db): + table = fresh_db.table("dogs") + table.create({"id": int, "name": str}, pk="id", indexes=["name"]) + assert table._defaults["indexes"] == ["name"] + + def test_rename_table(fresh_db): fresh_db.table("t").insert({"foo": "bar"}) assert ["t"] == fresh_db.table_names() diff --git a/tests/test_lookup.py b/tests/test_lookup.py index f96cfefaf..2b199bff3 100644 --- a/tests/test_lookup.py +++ b/tests/test_lookup.py @@ -154,6 +154,28 @@ def test_lookup_with_extra_insert_parameters(fresh_db): ] +def test_lookup_new_table_indexes(fresh_db): + items = fresh_db.table("items") + first_id = items.lookup({"_item_id": "a"}, {"_version": 1}, indexes=["_version"]) + second_id = items.lookup({"_item_id": "b"}, {"_version": 2}, indexes=["_version"]) + assert first_id != second_id + assert {index.name: (index.columns, index.unique) for index in items.indexes} == { + "idx_items__item_id": (["_item_id"], 1), + "idx_items__version": (["_version"], 0), + } + + +def test_lookup_new_table_indexes_on_lookup_columns(fresh_db): + # The unique index lookup() creates must not clash with indexes= + species = fresh_db.table("species") + palm_id = species.lookup({"name": "Palm"}, indexes=["name"]) + assert species.lookup({"name": "Palm"}, indexes=["name"]) == palm_id + assert {index.name: (index.columns, index.unique) for index in species.indexes} == { + "idx_species_name": (["name"], 0), + "idx_species_name_2": (["name"], 1), + } + + @pytest.mark.parametrize("strict", (False, True)) def test_lookup_new_table_strict(fresh_db, strict): fresh_db.table("species").lookup({"name": "Palm"}, strict=strict)