Skip to content

fix(#249): Duplicate index for ForeignKeyField added to existing table - #250

Open
jpsca wants to merge 1 commit into
klen:developfrom
jpsca:develop
Open

fix(#249): Duplicate index for ForeignKeyField added to existing table#250
jpsca wants to merge 1 commit into
klen:developfrom
jpsca:develop

Conversation

@jpsca

@jpsca jpsca commented May 8, 2026

Copy link
Copy Markdown

Fixes #249

Summary

When Router.create(..., auto=...) detects a ForeignKeyField that has been added to a pre-existing table, the generated migration contains both:

migrator.add_fields(..., fk=pw.ForeignKeyField(...)), which (correctly) creates the FK column and its implicit index, because ForeignKeyField defaults to index=True.

migrator.add_index(table, fk_name, unique=False), a redundant call that tries to create the same index a second time.

Running the migration on a fresh DB fails with peewee.OperationalError: index <table>_<fk>_id already exists

The bug only manifests when the FK is added to an existing model. New models generated through create_model don't trigger it (the index is implicit in the CREATE TABLE).

Root cause

In peewee_migrate/auto.py, diff_model runs the field diff and the index diff independently, with no
coordination:

# auto.py:146-151
def diff_model(model, source, **opts):
    ...
    return [*diff_model_fields(model, source, **opts), *diff_model_indexes(model, source)]

diff_model_fields (line 154) sees cover in fields_to_add and emits add_fields(... ForeignKeyField ...).
When applied, peewee's standard field-creation path produces the FK column and its index (because ForeignKeyField.__init__ sets index=True by default).

diff_model_indexes (line 187) independently compares model._meta.fields_to_index() against source._meta.fields_to_index(). The FK's auto-index is in the new set but not the old, so it lands in indexes_to_add (line 204) and emits add_index(...) - duplicating what add_fields will already do.

Because diff_model_indexes has no knowledge of which fields are being newly added in this same migration, it can't tell that those fields' indexes are "free" (created as a side effect of add_fields).

cc/ @klen

@jpsca
jpsca requested a review from klen as a code owner May 8, 2026 23:19
@jpsca jpsca changed the title fix(#249): Duplicate index for FK added to existing table fix(#249): Duplicate index for ForeignKeyField added to existing table May 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug report: Autogenerator emits duplicate add_index for ForeignKeyField added to existing table

1 participant