simonw / sqlite-utils

Python CLI utility and library for manipulating SQLite databases
https://sqlite-utils.datasette.io
Apache License 2.0
1.58k stars 106 forks source link

Allow mytable.create_index() to ignore an already existing index #627

Open tobych opened 2 months ago

tobych commented 2 months ago

While I'm working on a migration, I like to keep my code idempotent.

I love that most operations offer an ignore argument.

I'd like one for create_index() too.

I can submit a PR but I'd like some discussion first.

Meanwhile I'm using this motif:

from contextlib import suppress

from sqlite_utils.db import OperationalError

with suppress(OperationalError):
    mytable.create_index({'mycolumn'}, unique=True)

I could instead check to see whether the index already exists, but that's not Pythonic.

I should be checking the error message there really. More fine-grained exception classes would help here, so I could do this:

with suppress(IndexAlreadyExists):
    mytable.create_index({'mycolumn'}, unique=True)

Where IndexAlreadyExists is a subclass of OperationalError. Separate issue though.