Initial sketch for index-foreign-keys, refs #33

This commit is contained in:
Simon Willison 2019-06-30 09:42:20 -07:00 committed by Simon Willison
commit f35e4e6662

View file

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