Opened 9 years ago

Closed 9 years ago

#26117 closed Bug (fixed)

Add database routers support to initial migration detection

Reported by: Scott Sexton Owned by: Scott Sexton
Component: Migrations Version: 1.9
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: yes
Easy pickings: no UI/UX: no

Description

In the case where you have an app that defines a routers.py to associate certain models with a different database, the initial migration for that app cannot be faked with --fake-initial. Because some of the models exist in a different database than the one Django is currently migrating, it will ignore the fake and try to apply the migration anyway, giving you an OperationalError that one of the tables already exists.

The documentation reveals the location of the bug: "For an initial migration that creates one or more tables (CreateModel operation), Django checks that all of those tables already exist in the database and fake-applies the migration if so." But does it check the right database for those tables? No.

The bug occurs occurs in django.db.migrations.executor.py in the detect_soft_applied method. It simply compares all models it finds to a list of tables for the current db existing_table_names = self.connection.introspection.table_names(self.connection.cursor()), however, if a certain model exists in a different DB as defined in the app's routers.py, this check will always fail.

Instead, this method should probably consider the return value of the allow_migrate() method in the app's routers.py before trying to confirm whether that model should exist in the current db.

Change History (5)

comment:1 by Tim Graham, 9 years ago

Summary: Apps with a routers.py file using multiple databases may not use --fake-initialAdd database routers support to initial migration detection
Triage Stage: UnreviewedAccepted

Thanks for the detailed report. Feel free to offer a patch if you are able.

comment:2 by Scott Sexton, 9 years ago

Owner: changed from nobody to Scott Sexton
Status: newassigned

I'll submit a pull request this weekend.

comment:3 by Tim Graham, 9 years ago

Has patch: set

comment:4 by Tim Graham, 9 years ago

Patch needs improvement: set

Comments for improvement on the pull request.

comment:5 by Tim Graham <timograham@…>, 9 years ago

Resolution: fixed
Status: assignedclosed

In fc584f0:

Fixed #26117 -- Consulted database routers in initial migration detection.

Thanks Simon Charette for help.

Note: See TracTickets for help on using tickets.
Back to Top