mirror of
https://github.com/simonw/sqlite-utils.git
synced 2026-09-28 12:54:15 +02:00
Ability to create unique indexes, refs #14
This commit is contained in:
parent
1b6025e8ab
commit
e7ffbcdb36
3 changed files with 31 additions and 3 deletions
|
|
@ -388,6 +388,13 @@ By default the index will be named ``idx_{table-name}_{columns}`` - if you want
|
||||||
index_name="good_dogs_by_age"
|
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
|
Vacuum
|
||||||
======
|
======
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -236,16 +236,19 @@ class Table:
|
||||||
self.exists = True
|
self.exists = True
|
||||||
return self
|
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:
|
if index_name is None:
|
||||||
index_name = "idx_{}_{}".format(
|
index_name = "idx_{}_{}".format(
|
||||||
self.name.replace(" ", "_"), "_".join(columns)
|
self.name.replace(" ", "_"), "_".join(columns)
|
||||||
)
|
)
|
||||||
sql = """
|
sql = """
|
||||||
CREATE INDEX {index_name}
|
CREATE {unique}INDEX {index_name}
|
||||||
ON {table_name} ({columns});
|
ON {table_name} ({columns});
|
||||||
""".format(
|
""".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)
|
self.db.conn.execute(sql)
|
||||||
return self
|
return self
|
||||||
|
|
|
||||||
|
|
@ -170,6 +170,24 @@ def test_create_index(fresh_db, columns, index_name, expected_index):
|
||||||
assert expected_index == dogs.indexes[0]
|
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(
|
@pytest.mark.parametrize(
|
||||||
"data_structure",
|
"data_structure",
|
||||||
(
|
(
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue