multitenant: skip tenants where all migrations are applied (#29522)
This commit is contained in:
parent
e9929d3b5b
commit
37f7dff960
|
@ -1,7 +1,9 @@
|
|||
import django
|
||||
from optparse import NO_DEFAULT
|
||||
|
||||
from django.apps import apps
|
||||
from django.core.management.commands.migrate import Command as MigrateCommand
|
||||
from django.db.migrations.loader import MigrationLoader
|
||||
from django.db.migrations.recorder import MigrationRecorder
|
||||
from django.db import connection
|
||||
from django.conf import settings
|
||||
|
@ -45,9 +47,39 @@ class MigrateSchemasCommand(SyncCommon):
|
|||
else:
|
||||
self.run_migrations(self.schema_name, settings.TENANT_APPS)
|
||||
else:
|
||||
app_labels = []
|
||||
for app in apps.get_app_configs():
|
||||
if app.name in settings.TENANT_APPS:
|
||||
app_labels.append(app.label)
|
||||
loader = MigrationLoader(connection)
|
||||
loader.load_disk()
|
||||
recorder = MigrationRecorder(connection)
|
||||
applied_public_migrations = set(
|
||||
[(app, migration) for app, migration
|
||||
in recorder.applied_migrations()
|
||||
if app in app_labels and
|
||||
(app, migration) in loader.disk_migrations])
|
||||
for tenant in TenantMiddleware.get_tenants():
|
||||
connection.set_schema(tenant.schema_name, include_public=False)
|
||||
applied_migrations = self.get_applied_migrations(app_labels)
|
||||
if options.get('fake'):
|
||||
# disregard applied migrations if --fake is given.
|
||||
applied_migrations = []
|
||||
if all([x in applied_migrations for x in applied_public_migrations]):
|
||||
if int(self.options.get('verbosity', 1)) >= 1:
|
||||
self._notice("=== Skipping migrations of schema %s" % tenant.schema_name)
|
||||
continue
|
||||
self.run_migrations(tenant.schema_name, settings.TENANT_APPS)
|
||||
|
||||
def get_applied_migrations(self, app_labels):
|
||||
applied_migrations = []
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute('SELECT app, name FROM django_migrations')
|
||||
for row in cursor.fetchall():
|
||||
applied_migrations.append(row)
|
||||
applied_migrations = [x for x in applied_migrations if x[0] in app_labels]
|
||||
return applied_migrations
|
||||
|
||||
def run_migrations(self, schema_name, included_apps):
|
||||
if int(self.options.get('verbosity', 1)) >= 1:
|
||||
self._notice("=== Running migrate for schema %s" % schema_name)
|
||||
|
|
Loading…
Reference in New Issue