Ability to add descending order indexes (#262)

* DescIndex(column) for descending index columns, refs #260
* Ability to add desc indexes using CLI, closes #260
This commit is contained in:
Simon Willison 2021-05-28 22:01:38 -07:00 committed by GitHub
commit 51d01da30d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 69 additions and 4 deletions

View file

@ -5,7 +5,7 @@ from datetime import datetime
import hashlib
import pathlib
import sqlite_utils
from sqlite_utils.db import AlterError
from sqlite_utils.db import AlterError, DescIndex
import textwrap
import io
import itertools
@ -450,11 +450,21 @@ def index_foreign_keys(path, load_extension):
)
@load_extension_option
def create_index(path, table, column, name, unique, if_not_exists, load_extension):
"Add an index to the specified table covering the specified columns"
"""
Add an index to the specified table covering the specified columns.
Use "sqlite-utils create-index mydb -- -column" to specify descending
order for a column.
"""
db = sqlite_utils.Database(path)
_load_extensions(db, load_extension)
# Treat -prefix as descending for columns
columns = []
for col in column:
if col.startswith("-"):
col = DescIndex(col[1:])
columns.append(col)
db[table].create_index(
column, index_name=name, unique=unique, if_not_exists=if_not_exists
columns, index_name=name, unique=unique, if_not_exists=if_not_exists
)

View file

@ -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 "",
)