Ejemplo n.º 1
0
def run_migrations(args, options, executor_codename, schema_name, tenant_type='',
                   allow_atomic=True, idx=None, count=None):
    from django.core.management import color
    from django.core.management.base import OutputWrapper
    from django.db import connections
    style = color.color_style()

    def style_func(msg):
        percent_str = ''
        if idx is not None and count is not None and count > 0:
            percent_str = '%d/%d (%s%%) ' % (idx + 1, count, int(100 * (idx + 1) / count))

        message = '[%s%s:%s] %s' % (
            percent_str,
            style.NOTICE(executor_codename),
            style.NOTICE(schema_name),
            msg
        )
        signal_message = '[%s%s:%s] %s' % (
            percent_str,
            executor_codename,
            schema_name,
            msg
        )
        schema_migrate_message.send(run_migrations, message=signal_message)
        return message

    connection = connections[options.get('database', get_tenant_database_alias())]
    connection.set_schema(schema_name, tenant_type=tenant_type)

    # ensure that django_migrations table is created in the schema before migrations run, otherwise the migration
    # table in the public schema gets picked and no migrations are applied
    migration_recorder = MigrationRecorder(connection)
    migration_recorder.ensure_schema()

    stdout = OutputWrapper(sys.stdout)
    stdout.style_func = style_func
    stderr = OutputWrapper(sys.stderr)
    stderr.style_func = style_func
    if int(options.get('verbosity', 1)) >= 1:
        stdout.write(style.NOTICE("=== Starting migration"))
    MigrateCommand(stdout=stdout, stderr=stderr).execute(*args, **options)

    try:
        transaction.commit()
        connection.close()
        connection.connection = None
    except transaction.TransactionManagementError:
        if not allow_atomic:
            raise

        # We are in atomic transaction, don't close connections
        pass

    connection.set_schema_to_public()
    schema_migrated.send(run_migrations, schema_name=schema_name)
Ejemplo n.º 2
0
    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        command = MigrateCommand()

        skip_checks_action = parser._option_string_actions.pop(
            '--skip-checks', None)
        if skip_checks_action:
            parser._remove_action(skip_checks_action)

        command.add_arguments(parser)
Ejemplo n.º 3
0
    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)

        if not schema_exists(schema_name):
            raise MigrationSchemaMissing(
                'Schema "{}" does not exist'.format(schema_name))

        connection.set_schema(schema_name)
        command = MigrateCommand()
        command.execute(*self.args, **self.options)
        connection.set_schema_to_public()
Ejemplo n.º 4
0
    def seed_default(self):
        migrator = MigrateCommand()
        migrator.stdout = self.stdout
        migrator.handle(database="default",
                        verbosity=1,
                        noinput=True,
                        app_label=None,
                        migration_name=None)

        if not Shop.objects.exists():
            Shop.objects.create(name="Wintergear",
                                identifier="wintergear",
                                status=ShopStatus.ENABLED)
            try:
                tax_class = TaxClass.objects.create(identifier="default",
                                                    tax_rate=0)
            except:
                tax_class = TaxClass.objects.create(identifier="default")

            PaymentMethod.objects.create(identifier="default",
                                         name="Invoice",
                                         tax_class=tax_class)
            PaymentMethod.objects.create(identifier="bank_xfer",
                                         name="Bank Transfer",
                                         tax_class=tax_class)
            PaymentMethod.objects.create(identifier="cash",
                                         name="Cash (Pickup Only)",
                                         tax_class=tax_class)
            ShippingMethod.objects.create(identifier="default",
                                          name="Post Parcel",
                                          tax_class=tax_class)
            ShippingMethod.objects.create(identifier="pickup",
                                          name="Pickup at Helsinki Store",
                                          tax_class=tax_class)
            create_default_order_statuses()
            get_default_supplier()
            ProductType.objects.create(identifier="default")
            SalesUnit.objects.create(identifier="pcs",
                                     short_name="pcs",
                                     name="pieces")
            print("Seeded basic shop information")
        if not User.objects.filter(is_superuser=True).exists():
            User.objects.create_superuser(
                username="******",
                email="*****@*****.**",
                password="******",
            )
            print("Superuser created: admin / admin")
Ejemplo n.º 5
0
    def run_migrations(self, schema_name, included_apps):
        self._notice("=== Running migrate for schema %s" % schema_name)
        connection.set_schema(schema_name)
        command = MigrateCommand()

        defaults = {}
        for opt in MigrateCommand.option_list:
            if opt.dest in self.options:
                defaults[opt.dest] = self.options[opt.dest]
            elif opt.default is NO_DEFAULT:
                defaults[opt.dest] = None
            else:
                defaults[opt.dest] = opt.default

        command.execute(*self.args, **defaults)
        connection.set_schema_to_public()
Ejemplo n.º 6
0
def run_migrations(args,
                   options,
                   executor_codename,
                   schema_name,
                   allow_atomic=True,
                   idx=None,
                   count=None):
    from django.core.management import color
    from django.core.management.base import OutputWrapper
    from django.db import connections

    style = color.color_style()

    def style_func(msg):
        percent_str = ''
        if idx is not None and count is not None and count > 0:
            percent_str = '%d/%d (%s%%) ' % (idx + 1, count,
                                             int(100 * (idx + 1) / count))
        return '[%s%s:%s] %s' % (percent_str, style.NOTICE(executor_codename),
                                 style.NOTICE(schema_name), msg)

    include_public = True if (options.get('shared')
                              or schema_name == 'public') else False
    connection = connections[get_tenant_database_alias()]
    connection.set_schema(schema_name, include_public=include_public)

    stdout = OutputWrapper(sys.stdout)
    stdout.style_func = style_func
    stderr = OutputWrapper(sys.stderr)
    stderr.style_func = style_func
    if int(options.get('verbosity', 1)) >= 1:
        stdout.write(style.NOTICE("=== Starting migration"))
    MigrateCommand(stdout=stdout, stderr=stderr).execute(*args, **options)

    try:
        transaction.commit()
        connection.close()
        connection.connection = None
    except transaction.TransactionManagementError:
        if not allow_atomic:
            raise

        # We are in atomic transaction, don't close connections
        pass

    connection.set_schema_to_public()
Ejemplo n.º 7
0
def run_migrations(args,
                   options,
                   executor_codename,
                   schema_name,
                   allow_atomic=True):
    from django.core.management import color
    from django.core.management.base import OutputWrapper
    from django.db import connections

    PUBLIC_SCHEMA_NAME = get_public_schema_name()

    options['database'] = settings.TENANT_DATABASE
    if schema_name == PUBLIC_SCHEMA_NAME:
        options['database'] = DEFAULT_DB_ALIAS

    style = color.color_style()

    def style_func(msg):
        return '[%s:%s:%s] %s' % (options['database'],
                                  style.NOTICE(executor_codename),
                                  style.NOTICE(schema_name), msg)

    connections[options['database']].set_schema(schema_name)

    stdout = OutputWrapper(sys.stdout)
    stdout.style_func = style_func
    stderr = OutputWrapper(sys.stderr)
    stderr.style_func = style_func
    if int(options.get('verbosity', 1)) >= 1:
        stdout.write(style.NOTICE("=== Starting migration"))
    MigrateCommand(stdout=stdout, stderr=stderr).execute(*args, **options)

    try:
        transaction.commit()
        connections[options['database']].close()
        connections[options['database']].connection = None
    except transaction.TransactionManagementError:
        if not allow_atomic:
            raise

        # We are in atomic transaction, don't close connections
        pass
Ejemplo n.º 8
0
    def handle(self, *args, **kwargs):
        migrate = MigrateCommand()

        options = {
            'app_label': None,
            'migration_name': None,
            'interactive': True,
            'fake': False,
            'fake_initial': False,
            'run_syncdb': False,
            'plan': False,
        }
        options.update(kwargs)

        for database in settings.DATABASES:
            options['database'] = database
            if options['verbosity'] >= 1:
                self.stdout.write(self.style.MIGRATE_HEADING('Database:'))
                self.stdout.write('  ' + database)
            migrate.handle(*args, **options)
            if options['verbosity'] >= 1:
                self.stdout.write('')
Ejemplo n.º 9
0
def run_migrations(args,
                   options,
                   executor_codename,
                   schema_name,
                   allow_atomic=True):
    from django.core.management import color
    from django.core.management.base import OutputWrapper
    from django.db import connection

    style = color.color_style()

    def style_func(msg):
        return '[%s:%s] %s' % (style.NOTICE(executor_codename),
                               style.NOTICE(schema_name), msg)

    stdout = OutputWrapper(sys.stdout)
    stdout.style_func = style_func
    stderr = OutputWrapper(sys.stderr)
    stderr.style_func = style_func
    if int(options.get('verbosity', 1)) >= 1:
        stdout.write(
            style.NOTICE("=== Running migrate for schema %s" % schema_name))

    connection.set_schema(schema_name)
    MigrateCommand(stdout=stdout, stderr=stderr).execute(*args, **options)

    try:
        transaction.commit()
        connection.close()
        connection.connection = None
    except transaction.TransactionManagementError:
        if not allow_atomic:
            raise

        # We are in atomic transaction, don't close connections
        pass

    connection.set_schema_to_public()
Ejemplo n.º 10
0
    def run_migrations(self, schema_name, included_apps):
        self._notice("=== Running migrate for schema %s" % schema_name)
        connection.set_schema(schema_name, include_public=False)
        apps.app_configs = OrderedDict()
        apps.clear_cache()
        apps.set_installed_apps(included_apps)

        command = MigrateCommand()

        defaults = {}
        for opt in MigrateCommand.option_list:
            if opt.dest in self.options:
                defaults[opt.dest] = self.options[opt.dest]
            elif opt.default is NO_DEFAULT:
                defaults[opt.dest] = None
            else:
                defaults[opt.dest] = opt.default

        command.execute(*self.args, **defaults)

        connection.set_schema('public', include_public=True)
        apps.app_configs = OrderedDict()
        apps.clear_cache()
        apps.set_installed_apps(settings.SHARED_APPS)
 def add_arguments(self, parser):
     super(MigrateSchemasCommand, self).add_arguments(parser)
     command = MigrateCommand()
     command.add_arguments(parser)
Ejemplo n.º 12
0
def migrate(params=None):
    command = MigrateCommand()
    parser = command.create_parser('manage.py', 'migrate')
    options = parser.parse_args(params or [])
    cmd_options = vars(options)
    return command.execute(**cmd_options)