to support Django 1.7 migrations, see also the add_introspection_rules
        section at bottom of this file for South + earlier Django versions
357925
def deconstruct(self):
        
        name, path, args, kwargs = super(
            ExclusiveBooleanField, self).deconstruct()
        if self._on_fields:
            kwargs['on'] = self._on_fields
        return name, path, args, kwargs
887012
def create(resource_path, previous_version=None, package='perch.migrations'):
    """"""
    pkg, obj = resource_path.rsplit('.', 1)
    module = importlib.import_module(pkg)
    resource = getattr(module, obj)
    version = uuid4().hex
    target_module = importlib.import_module(package)
    target_dir = os.path.dirname(target_module.__file__)
    target_file = os.path.join(target_dir, resource.resource_type + '_' + version + '.py')

    with open(target_file, 'w') as f:
        f.write(MIGRATION_TEMPLATE.format(
            resource_path=resource_path,
            resource_type=resource.resource_type,
            version=version,
            previous_version=previous_version or '',
        ))

    return target_file
1324912
def add_url_rule(self, rule, endpoint=None, view_func=None,
                     provide_automatic_options=None, register_with_babel=False,
                     **options):
        
        if self.unchained.babel_bundle and register_with_babel:
            self.unchained.babel_bundle.add_url_rule(
                self, rule, endpoint=endpoint, view_func=view_func,
                provide_automatic_options=provide_automatic_options, **options)
        return super().add_url_rule(rule, endpoint, view_func,
                                    provide_automatic_options, **options)
924650
def migrate1():
    ""

    initial = [
    "create table Chill (version integer);",
    "insert into Chill (version) values (1);",
    "alter table SelectSQL rename to Query;",
    "alter table Node add column template integer references Template (id) on delete set null;",
    "alter table Node add column query integer references Query (id) on delete set null;"
    ]


    cleanup = [
    "drop table SelectSQL_Node;",
    "drop table Template_Node;"
    ]

    c = db.cursor()
    try:
        c.execute("select version from Chill limit 1;")
    except sqlite3.DatabaseError as err:
        pass
    result = c.fetchone()
    if result:
        version = result[0]
        if version == 1:
            current_app.logger.warn("Migration from version 0 to 1 is not needed.")
        else:
            current_app.logger.warn("Migration from version 0 to {0} is not supported.".format(version))
        return

    try:
        for query in initial:
            c.execute(query)
    except sqlite3.DatabaseError as err:
        current_app.logger.error("DatabaseError: %s", err)

    try:
        c.execute(fetch_query_string('select_all_nodes.sql'))
    except sqlite3.DatabaseError as err:
        current_app.logger.error("DatabaseError: %s", err)
    result = c.fetchall()
    if result:
        (result, col_names) = rowify(result, c.description)
        for kw in result:

            try:
                c.execute("""
                update Node set template = (
                select t.id from Template as t
                join Template_Node as tn on ( tn.template_id = t.id )
                join Node as n on ( n.id = tn.node_id )
                where n.id is :node_id
                group by t.id)
                where id is :node_id;
                """, {'node_id':kw['id']})
            except sqlite3.DatabaseError as err:
                current_app.logger.error("DatabaseError: %s", err)

            try:
                c.execute("""
                update Node set query = (
                select s.id from Query as s
                join SelectSQL_Node as sn on ( sn.selectsql_id = s.id )
                join Node as n on ( n.id = sn.node_id )
                where n.id is :node_id
                group by s.id)
                where id is :node_id;
                """, {'node_id':kw['id']})
            except sqlite3.DatabaseError as err:
                current_app.logger.error("DatabaseError: %s", err)
    try:
        for query in cleanup:
            c.execute(query)
    except sqlite3.DatabaseError as err:
        current_app.logger.error("DatabaseError: %s", err)

    db.commit()
759878
public function migrateGarpModels() {
        $modelDir = APPLICATION_PATH . '/modules/default/Model';
        $dirIterator = new DirectoryIterator($modelDir);
        foreach ($dirIterator as $finfo) {
            if ($finfo->isDot()) {
                continue;
            }
            $this->_modifyModelFile($finfo);
        }

        $this->_updateCropTemplateRefs();
        return true;
    }
653800
def __create_translation_migration(self):
        
        migrations_dir = os.path.join(self.BASE_DIR, self.app_name + "/migrations/")
        dependency_migration = os.path.basename(max(glob.iglob(migrations_dir + '*.py'), key=os.path.getctime)).replace(
            ".py", "")
        """
        If there's no migration before this, which is unlikely to happen, then create a migration without dependencies
        """
        if "__init__" in dependency_migration:
            dependency_migration = ""
        """ Make an empty migration """
        call_command('makemigrations', self.app_name, "--empty")
        """ Get last migration name and edit it, adding the new code """
        last_migration_file = max(glob.iglob(migrations_dir + '*.py'), key=os.path.getctime)
        new_lines = self.__create_translation_lines()
        translation_type_lines = self.__create_translation_type_lines()
        if len(dependency_migration) > 0:
            dependency_string = "('%(app_name)s', '%(dependency)s')," % {'app_name': self.app_name,
                                                                         'dependency': dependency_migration}
        else:
            dependency_string = ""
        try:
            if len(new_lines) > 0:
                with open(last_migration_file, 'w+') as file:
                    file.write(self.migration_string % {
                        'django_version': django.get_version(),
                        'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                        'translation_strings': "\n".join(new_lines),
                        'tags_to_remove': ", ".join('"{0}"'.format(tag) for tag in self.updated_translations),
                        'dependency_string': dependency_string,
                        'app_name': 'translation_server',
                        'translation_type_strings': "\n".join(translation_type_lines),
                        'translation_types_to_remove': ", ".join(
                            '"{0}"'.format(tag) for tag in self.updated_translation_types),
                    })
            else:
                os.remove(last_migration_file)
                self.stdout.write(self.style.NOTICE("There was no new translations to make migrations"))
                return
        except Exception as error:
            os.remove(last_migration_file)
            raise error
        else:
            self.__update_translation()
            self.stdout.write(self.style.SUCCESS("Translation migration file create successfully"))
            return
1073377
def _add_backend(self, backend):
        
        md_type = backend.verbose_name
        base = backend().get_model(self)
        # TODO: Rename this field
        new_md_attrs = {'_metadata': self.metadata, '__module__': __name__ }

        new_md_meta = {}
        new_md_meta['verbose_name'] = '%s (%s)' % (self.verbose_name, md_type)
        new_md_meta['verbose_name_plural'] = '%s (%s)' % (self.verbose_name_plural, md_type)
        new_md_meta['unique_together'] = base._meta.unique_together
        new_md_attrs['Meta'] = type("Meta", (), new_md_meta)
        new_md_attrs['_metadata_type'] = backend.name
        model = type("%s%s"%(self.name,"".join(md_type.split())), (base, self.MetadataBaseModel), new_md_attrs.copy())
        self.models[backend.name] = model
        # This is a little dangerous, but because we set __module__ to __name__, the model needs tobe accessible here
        globals()[model.__name__] = model
608660
def _migrate_subresource(subresource, parent, migrations):
    
    for key, doc in getattr(parent, subresource.parent_key, {}).items():
        for migration in migrations['migrations']:
            instance = migration(subresource(id=key, **doc))
            parent._resource['doc_version'] = unicode(migration.version)

            instance = _migrate_subresources(
                instance,
                migrations['subresources']
            )

        doc = instance._resource
        doc.pop('id', None)
        doc.pop(instance.resource_type + '_id', None)

        getattr(parent, subresource.parent_key)[key] = doc

    return parent
655014
def transition(field, source='*', target=None, on_error=None, conditions=[], permission=None, custom={}):
    
    def inner_transition(func):
        wrapper_installed, fsm_meta = True, getattr(func, '_django_fsm', None)
        if not fsm_meta:
            wrapper_installed = False
            fsm_meta = FSMMeta(field=field, method=func)
            setattr(func, '_django_fsm', fsm_meta)

        if isinstance(source, (list, tuple, set)):
            for state in source:
                func._django_fsm.add_transition(func, state, target, on_error, conditions, permission, custom)
        else:
            func._django_fsm.add_transition(func, source, target, on_error, conditions, permission, custom)

        @wraps(func)
        def _change_state(instance, *args, **kwargs):
            return fsm_meta.field.change_state(instance, func, *args, **kwargs)

        if not wrapper_installed:
            return _change_state

        return func

    return inner_transition
958289
def _write_migration(self, creator, name, table, create, path):
        
        file_ = os.path.basename(creator.create(name, path, table, create))

        return file_
1118794
public function help()
	{
		$this
			->output
			->addOverview(
				'Run a migration. This includes searching for migration files,
				depending on the options provided.'
			)
			->addTasks($this)
			->addArgument(
				'-d: direction [up|down]',
				'If not specified, defaults to "up".',
				'Example: -d=up or -d=down'
			)
			->addArgument(
				'-r: document root',
				'Specify the document root through which the the application
				will search for migrations directories. The primary use case
				for this is specifying an alternate directory for testing.
				By default, it will use the PATH_CORE constant for
				the document root.',
				'Example: -r=/www/myhub/unittests/migrations'
			)
			->addArgument(
				'-e: extension',
				'Explicity give the extension on which the migration should be run.
				This could be one of "com_componentname", "mod_modulename",
				or "plg_plugingroup_pluginname". This option is required
				when using the force (--force) option and the log only option (-m).',
				'Example: -e=com_courses, -e=plg_members_dashboard'
			)
			->addArgument(
				'-a: list all',
				'List all will display all migrations found, not just those needing
				to be run. This allows you to see the files that need to be run in the
				context of the other files that have already been run. This differs from
				the prior -i argument which was needed because, by default, only new
				files were considered for a run. Now, all files needing to be run are
				included by default, irrespective of whether or not they are dated after
				the last run migration.'
			)
			->addArgument(
				'-i: ignore dates',
				'DEPRECATED: Now functions as if the -a option were given.
				Using this option will scan for and run all migrations that haven\'t
				previously been run, irrespective of the date of the migration.
				This differs from the default behavior in that normally, only files
				dated after the last run date will be eligable to be included in the
				migration. This option also differs from force mode (--force) in that it
				will find all migrations, but only run those that haven\'t been run
				before (whereas --force will run them irrespective of whether or not it
				thinks they\'ve already been run). You do not have to use -e with this
				option. This option is necessary when needing to run migrations that
				have been skipped for one reason or another.'
			)
			->addArgument(
				'-f: full run',
				'By default, using the migration command without any options will run
				in dry-run mode (meaning no changes will actually be made), displaying
				the migrations that would be run, were the command to be fully executed.
				Use the "-f" (full run) option to do the full migration run.'
			)
			->addArgument(
				'-m: log only',
				'Using this option, a migration will run as normal, and log entries
				will be created, but the SQL itself will not be run. As a general
				precaution, this should not be run without the extension option (-e).
				The primary use case for this option would be marking a migration
				as run in the event that it had already been run (manually), yet
				not logged in the database.'
			)
			->addArgument(
				'--file: run a provided filed',
				'Provide the filename to be run. This and only this file will be run.
				This will automatically place the migration in (-i) mode, ignoring dates.
				It will not, however, force it to be run, if a log entry for this file
				and direction already exists. Use the (--force) option to override this
				behavior or run the opposite direction first.',
				'Example: --file=Migration20130101000000ComMigrations.php'
			)
			->addArgument(
				'--force: force mode',
				'This option should be used carefully. It will run a migration,
				even if it thinks it has already been run. When using this option,
				you must also give a specific extension using the (-e) option.'
			)
			->addArgument(
				'--email: send email',
				'Specify an email address to receive the output of this run. If no
				files are executed during the migration, an email will not be sent.',
				'Example: --email=sampleuser@hubzero.org'
			);
	}
1336888
def create_migration_template(name):
    
    assert name, 'Name of the migration can not be empty.'
    from . import migrations

    # Find next number
    #
    package = migrations
    prefix = package.__name__ + '.'
    all_versions = []
    for importer, modname, ispkg in pkgutil.iter_modules(package.__path__, prefix):
        version = int(modname.split('.')[-1].split('_')[0])
        all_versions.append(version)

    next_number = max(all_versions) + 1

    # Generate next migration name
    #
    next_migration_name = '{}_{}.py'.format(next_number, name)
    migration_fullname = os.path.join(package.__path__[0], next_migration_name)

    # Write next migration file content.
    #
    with open(migration_fullname, 'w') as f:
        f.write(MIGRATION_TEMPLATE)
    return migration_fullname
637293
def _add_version_info(func):
		
		pattern = r'v(?P<source>\d+)_to_(?P<target>\d+)$'
		match = re.match(pattern, func.__name__)
		if not match:
			raise ValueError("migration function name must match " + pattern)
		func.source, func.target = map(int, match.groups())
1120391
def create_migrations_and_models
      src = "#{@gem_path}/lib/modules/migrations"
      dest = "#{@target_dir}/db/migrate"
      copy_files(src,dest,AUTH_MIGRATE)
      if @module_name == "oauth"
        copy_files(src,dest,OAUTH_MIGRATE)
      end
      src_path = "#{@gem_path}/lib/modules/models"
      dest_path = "#{@target_dir}/app/models"   
      copy_files(src_path,dest_path,AUTH_MODELS)
      if @module_name == "oauth"
        copy_files(src_path,dest_path,OAUTH_MODELS)
      end
    end
1169952
def check_migrations_applied(app_configs, **kwargs):
    
    from django.db.migrations.loader import MigrationLoader
    errors = []

    # Load migrations from disk/DB
    try:
        loader = MigrationLoader(connection, ignore_no_migrations=True)
    except (ImproperlyConfigured, ProgrammingError, OperationalError):
        msg = "Can't connect to database to check migrations"
        return [checks.Info(msg, id=health.INFO_CANT_CHECK_MIGRATIONS)]

    if app_configs:
        app_labels = [app.label for app in app_configs]
    else:
        app_labels = loader.migrated_apps

    for node, migration in loader.graph.nodes.items():
        if migration.app_label not in app_labels:
            continue
        if node not in loader.applied_migrations:
            msg = 'Unapplied migration {}'.format(migration)
            # NB: This *must* be a Warning, not an Error, because Errors
            # prevent migrations from being run.
            errors.append(checks.Warning(msg,
                                         id=health.WARNING_UNAPPLIED_MIGRATION))

    return errors
640091
protected void migrateProcessInstance(MigratingProcessInstance migratingProcessInstance) {
    MigratingActivityInstance rootActivityInstance = migratingProcessInstance.getRootInstance();

    MigratingProcessElementInstanceTopDownWalker walker = new MigratingProcessElementInstanceTopDownWalker(rootActivityInstance);

    walker.addPreVisitor(
        new MigratingActivityInstanceVisitor(
            executionBuilder.isSkipCustomListeners(),
            executionBuilder.isSkipIoMappings()));
    walker.addPreVisitor(new MigrationCompensationInstanceVisitor());

    walker.walkUntil();
  }
1215280
def create_new_migration_record(self):
        
        migration_record = self.migration_model(
            name=self.name,
            version=self.latest_migration)
        self.session.add(migration_record)
        self.session.commit()