From e7ffbcdb364810213b0697c9bcab064efb1dd469 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Sun, 24 Feb 2019 10:41:51 -0800 Subject: [PATCH] Ability to create unique indexes, refs #14 --- docs/python-api.rst | 7 +++++++ sqlite_utils/db.py | 9 ++++++--- tests/test_create.py | 18 ++++++++++++++++++ 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/docs/python-api.rst b/docs/python-api.rst index 1da1c84..57857c6 100644 --- a/docs/python-api.rst +++ b/docs/python-api.rst @@ -388,6 +388,13 @@ By default the index will be named ``idx_{table-name}_{columns}`` - if you want index_name="good_dogs_by_age" ) +You can create a unique index by passing ``unique=True``:: + +.. code-block:: python + + dogs.create_index(["name"], unique=True) + + Vacuum ====== diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index f645ebb..adcd934 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -236,16 +236,19 @@ class Table: self.exists = True return self - def create_index(self, columns, index_name=None): + def create_index(self, columns, index_name=None, unique=False): if index_name is None: index_name = "idx_{}_{}".format( self.name.replace(" ", "_"), "_".join(columns) ) sql = """ - CREATE INDEX {index_name} + CREATE {unique}INDEX {index_name} ON {table_name} ({columns}); """.format( - index_name=index_name, table_name=self.name, columns=", ".join(columns) + index_name=index_name, + table_name=self.name, + columns=", ".join(columns), + unique="UNIQUE " if unique else "", ) self.db.conn.execute(sql) return self diff --git a/tests/test_create.py b/tests/test_create.py index 9886874..16b52e2 100644 --- a/tests/test_create.py +++ b/tests/test_create.py @@ -170,6 +170,24 @@ def test_create_index(fresh_db, columns, index_name, expected_index): assert expected_index == dogs.indexes[0] +def test_create_index_unique(fresh_db): + dogs = fresh_db["dogs"] + dogs.insert({"name": "Cleo", "twitter": "cleopaws", "age": 3, "is_good_dog": True}) + assert [] == dogs.indexes + dogs.create_index(["name"], unique=True) + assert ( + Index( + seq=0, + name="idx_dogs_name", + unique=1, + origin="c", + partial=0, + columns=["name"], + ) + == dogs.indexes[0] + ) + + @pytest.mark.parametrize( "data_structure", (