1
|
import django
|
2
|
from optparse import NO_DEFAULT
|
3
|
|
4
|
if django.VERSION >= (1, 7, 0):
|
5
|
from django.core.management.commands.migrate import Command as MigrateCommand
|
6
|
from django.db.migrations.recorder import MigrationRecorder
|
7
|
from django.db import connection
|
8
|
from django.conf import settings
|
9
|
|
10
|
from tenant_schemas.utils import get_public_schema_name
|
11
|
from entrouvert.djommon.multitenant.middleware import TenantMiddleware, TenantNotFound
|
12
|
from entrouvert.djommon.multitenant.management.commands import SyncCommon
|
13
|
|
14
|
|
15
|
class MigrateSchemasCommand(SyncCommon):
|
16
|
help = "Updates database schema. Manages both apps with migrations and those without."
|
17
|
|
18
|
def run_from_argv(self, argv):
|
19
|
"""
|
20
|
Changes the option_list to use the options from the wrapped command.
|
21
|
Adds schema parameter to specify which schema will be used when
|
22
|
executing the wrapped command.
|
23
|
"""
|
24
|
self.option_list += MigrateCommand.option_list
|
25
|
super(MigrateSchemasCommand, self).run_from_argv(argv)
|
26
|
|
27
|
def handle(self, *args, **options):
|
28
|
super(MigrateSchemasCommand, self).handle(*args, **options)
|
29
|
self.PUBLIC_SCHEMA_NAME = get_public_schema_name()
|
30
|
|
31
|
if self.sync_public and not self.schema_name:
|
32
|
self.schema_name = self.PUBLIC_SCHEMA_NAME
|
33
|
|
34
|
if self.sync_public:
|
35
|
self.run_migrations(self.schema_name, settings.SHARED_APPS)
|
36
|
if self.sync_tenant:
|
37
|
if self.schema_name and self.schema_name != self.PUBLIC_SCHEMA_NAME:
|
38
|
self.run_migrations(self.schema_name, settings.TENANT_APPS)
|
39
|
else:
|
40
|
all_tenants = TenantMiddleware.get_tenants()
|
41
|
for tenant in all_tenants:
|
42
|
self.run_migrations(tenant.schema_name, settings.TENANT_APPS)
|
43
|
|
44
|
def run_migrations(self, schema_name, included_apps):
|
45
|
self._notice("=== Running migrate for schema %s" % schema_name)
|
46
|
connection.set_schema(schema_name)
|
47
|
command = MigrateCommand()
|
48
|
|
49
|
defaults = {}
|
50
|
for opt in MigrateCommand.option_list:
|
51
|
if opt.dest in self.options:
|
52
|
defaults[opt.dest] = self.options[opt.dest]
|
53
|
elif opt.default is NO_DEFAULT:
|
54
|
defaults[opt.dest] = None
|
55
|
else:
|
56
|
defaults[opt.dest] = opt.default
|
57
|
|
58
|
command.execute(*self.args, **defaults)
|
59
|
connection.set_schema_to_public()
|
60
|
|
61
|
def _notice(self, output):
|
62
|
self.stdout.write(self.style.NOTICE(output))
|
63
|
|
64
|
|
65
|
if django.VERSION >= (1, 7, 0):
|
66
|
Command = MigrateSchemasCommand
|
67
|
else:
|
68
|
from .legacy.migrate_schemas import Command
|