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