From f35e4e6662abeb8fae05408d315bd9b526943870 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Sun, 30 Jun 2019 09:42:20 -0700 Subject: [PATCH] Initial sketch for index-foreign-keys, refs #33 --- sqlite_utils/cli.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index 0df540a..ea7d193 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -217,6 +217,31 @@ def add_foreign_key(path, table, column, other_table, other_column): raise click.ClickException(e) + +@cli.command(name="index-foreign-keys") +@click.argument( + "path", + type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False), + required=True, +) +def index_foreign_keys(path): + """ + Ensure every foreign key column has an index on it. + """ + db = sqlite_utils.Database(path) + for table_name in db.table_names(): + table = db[table_name] + existing_indexes = { + i.columns[0] for i in table.indexes if len(i.columns) == 1 + } + for fk in table.foreign_keys: + if fk.column not in existing_indexes: + print("Creating index on {}.{}".format( + table_name, fk.column + )) + table.create_index([fk.column]) + + @cli.command(name="create-index") @click.argument( "path",