mirror of
https://github.com/simonw/sqlite-utils.git
synced 2026-09-20 07:24:23 +02:00
DescIndex(column) for descending index columns, refs #260
This commit is contained in:
parent
b2302875c9
commit
c374d7ef04
3 changed files with 37 additions and 1 deletions
|
|
@ -1866,6 +1866,17 @@ By default the index will be named ``idx_{table-name}_{columns}`` - if you want
|
|||
index_name="good_dogs_by_age"
|
||||
)
|
||||
|
||||
To create an index in descending order for a column, wrap the column name in ``db.DescIndex()`` like this:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from sqlite_utils.db import DescIndex
|
||||
|
||||
db["dogs"].create_index(
|
||||
["is_good_dog", DescIndex("age")],
|
||||
index_name="good_dogs_by_age"
|
||||
)
|
||||
|
||||
You can create a unique index by passing ``unique=True``:
|
||||
|
||||
.. code-block:: python
|
||||
|
|
|
|||
|
|
@ -144,6 +144,10 @@ class InvalidColumns(Exception):
|
|||
pass
|
||||
|
||||
|
||||
class DescIndex(str):
|
||||
pass
|
||||
|
||||
|
||||
_COUNTS_TABLE_CREATE_SQL = """
|
||||
CREATE TABLE IF NOT EXISTS [{}](
|
||||
[table] TEXT PRIMARY KEY,
|
||||
|
|
@ -1156,6 +1160,13 @@ class Table(Queryable):
|
|||
index_name = "idx_{}_{}".format(
|
||||
self.name.replace(" ", "_"), "_".join(columns)
|
||||
)
|
||||
columns_sql = []
|
||||
for column in columns:
|
||||
if isinstance(column, DescIndex):
|
||||
fmt = "[{}] desc"
|
||||
else:
|
||||
fmt = "[{}]"
|
||||
columns_sql.append(fmt.format(column))
|
||||
sql = (
|
||||
textwrap.dedent(
|
||||
"""
|
||||
|
|
@ -1167,7 +1178,7 @@ class Table(Queryable):
|
|||
.format(
|
||||
index_name=index_name,
|
||||
table_name=self.name,
|
||||
columns=", ".join("[{}]".format(c) for c in columns),
|
||||
columns=", ".join(columns_sql),
|
||||
unique="UNIQUE " if unique else "",
|
||||
if_not_exists="IF NOT EXISTS " if if_not_exists else "",
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
from sqlite_utils.db import (
|
||||
Index,
|
||||
Database,
|
||||
DescIndex,
|
||||
ForeignKey,
|
||||
AlterError,
|
||||
NoObviousTable,
|
||||
|
|
@ -739,6 +740,19 @@ def test_create_index_if_not_exists(fresh_db):
|
|||
dogs.create_index(["name"], if_not_exists=True)
|
||||
|
||||
|
||||
def test_create_index_desc(fresh_db):
|
||||
dogs = fresh_db["dogs"]
|
||||
dogs.insert({"name": "Cleo", "twitter": "cleopaws", "age": 3, "is good dog": True})
|
||||
assert [] == dogs.indexes
|
||||
dogs.create_index([DescIndex("age"), "name"])
|
||||
sql = fresh_db.execute(
|
||||
"select sql from sqlite_master where name='idx_dogs_age_name'"
|
||||
).fetchone()[0]
|
||||
assert sql == (
|
||||
"CREATE INDEX [idx_dogs_age_name]\n" " ON [dogs] ([age] desc, [name])"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"data_structure",
|
||||
(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue