Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 34 additions & 3 deletions docs/python-api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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:

Expand Down Expand Up @@ -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:

Expand Down Expand Up @@ -1027,6 +1027,36 @@ Here's an example that uses these features:
.. note::
In the CLI: :ref:`sqlite-utils insert --not-null and --default <cli_defaults_not_null>`

.. _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() <python_api_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() <python_api_create_index>` to add an index to an existing table.

.. _python_api_rename_table:

Renaming a table
Expand Down Expand Up @@ -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:

Expand Down
98 changes: 76 additions & 22 deletions sqlite_utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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():

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 👍 / 👎.

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)

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 👍 / 👎.

return self.table(
name,
pk=pk,
Expand All @@ -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:
Expand Down Expand Up @@ -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.
Expand All @@ -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 = {
Expand All @@ -2331,6 +2363,7 @@ def __init__(
"conversions": conversions or {},
"columns": columns,
"strict": strict,
"indexes": indexes,
}

def __repr__(self) -> str:
Expand Down Expand Up @@ -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.
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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():
Expand All @@ -2636,6 +2674,7 @@ def create(
ignore=ignore,
transform=transform,
strict=cast(bool, strict),
indexes=indexes,
)
return self

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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],
Expand All @@ -4828,6 +4870,7 @@ def insert(
conversions=conversions,
columns=columns,
strict=strict,
indexes=indexes,
)

def insert_all(
Expand 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
Expand All @@ -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"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -5240,6 +5287,7 @@ def upsert(
conversions=conversions,
columns=columns,
strict=strict,
indexes=indexes,
)

def upsert_all(
Expand 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.
Expand All @@ -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":
Expand All @@ -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.
Expand Down Expand Up @@ -5366,6 +5417,7 @@ def lookup(
conversions=conversions,
columns=columns,
strict=strict,
indexes=indexes,
).last_pk
else:
pk = self.insert(
Expand All @@ -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(
Expand Down
Loading