Repository navigation
indexes= argument for creating indexes along with a new table
#996
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a table is first created via Useful? React with 👍 / 👎. |
||
| 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( | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When callers invoke
Database.create_table(..., replace=True, indexes=[...])on an existing table and an index names a missing column, the earlierdrop()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 👍 / 👎.