From 9a8c6fa0205635a008515549df2f04aa89f86cc5 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Fri, 28 May 2021 21:50:24 -0700 Subject: [PATCH] Ability to add desc indexes using CLI, closes #260 --- docs/cli.rst | 8 ++++++++ sqlite_utils/cli.py | 16 +++++++++++++--- tests/test_cli.py | 11 +++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/docs/cli.rst b/docs/cli.rst index b314b2d..e5ffcfc 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -1033,6 +1033,14 @@ Use the ``--unique`` option to create a unique index. Use ``--if-not-exists`` to avoid attempting to create the index if one with that name already exists. +To add an index on a column in descending order, prefix the column with a hyphen. Since this can be confused for a command-line option you need to construct that like this:: + + $ sqlite-utils create-index mydb.db mytable -- col1 -col2 col3 + +This will create an index on that table on ``(col1, col2 desc, col3)``. + +If your column names are already prefixed with a hyphen you'll need to manually execute a ``CREATE INDEX`` SQL statement to add indexes to them rather than using this tool. + .. _cli_fts: Configuring full-text search diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index 960d34c..52de64a 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -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 ) diff --git a/tests/test_cli.py b/tests/test_cli.py index 2e982dd..17ce27d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -208,6 +208,17 @@ def test_create_index(db_path): ) +def test_create_index_desc(db_path): + db = Database(db_path) + assert [] == db["Gosh"].indexes + result = CliRunner().invoke(cli.cli, ["create-index", db_path, "Gosh", "--", "-c1"]) + assert result.exit_code == 0 + assert ( + db.execute("select sql from sqlite_master where type='index'").fetchone()[0] + == "CREATE INDEX [idx_Gosh_c1]\n ON [Gosh] ([c1] desc)" + ) + + @pytest.mark.parametrize( "col_name,col_type,expected_schema", (