Exports counts of unapplied migrations.

    This is meant to be called during app startup, ideally by
    django_prometheus.apps.AppConfig.
177064
def ExportMigrations():
    

    # Import MigrationExecutor lazily. MigrationExecutor checks at
    # import time that the apps are ready, and they are not when
    # django_prometheus is imported. ExportMigrations() should be
    # called in AppConfig.ready(), which signals that all apps are
    # ready.
    from django.db.migrations.executor import MigrationExecutor

    if 'default' in connections and (
            type(connections['default']) == DatabaseWrapper):
        # This is the case where DATABASES = {} in the configuration,
        # i.e. the user is not using any databases. Django "helpfully"
        # adds a dummy database and then throws when you try to
        # actually use it. So we don't do anything, because trying to
        # export stats would crash the app on startup.
        return
    for alias in connections.databases:
        executor = MigrationExecutor(connections[alias])
        ExportMigrationsForDatabase(alias, executor)
1214341
def get_all_migrations(path, databases=None):
    
    # database: [(number, full_path)]
    possible_migrations = defaultdict(list)
    
    try:
        in_directory = sorted(get_file_list(path))
    except OSError:
        import traceback
        print "An error occurred while reading migrations from %r:" % path
        traceback.print_exc()
        return {}
    
    # Iterate through our results and discover which migrations are
    # actually runnable
    for full_path in in_directory:
        child_path, script = os.path.split(full_path)
        name, ext = os.path.splitext(script)
        
        # the database component is default if this is in the root directory
        # is <directory> if in a subdirectory
        if path == child_path:
            db = DEFAULT_DB_ALIAS
        else:
            db = os.path.split(child_path)[-1]
        
        # filter by database if set
        if databases and db not in databases:
            continue
        
        match = MIGRATION_NAME_RE.match(name)
        if match is None:
            raise MigrationError("Invalid migration file prefix %r "
                                 "(must begin with a number)" % name)
        
        number = int(match.group(1))
        if ext in [".sql", ".py"]:
            possible_migrations[db].append((number, full_path))
    
    return possible_migrations
1183903
protected function alreadyExecutedMigrations()
    {
        $results = $this->db->query(
            'SELECT * FROM `app_migrations`',
            DbAdapter::QUERY_MODE_EXECUTE
        );

        return (array) iterator_to_array($results, true);
    }
1357982
def show_status(self):
        """"""
        if not self.check_directory():
            return

        migrations = self.get_unregistered_migrations()
        if migrations:
            logger.info('Unregistered migrations:')
            for migration in migrations:
                logger.info(migration.filename)
        else:
            logger.info(self.NO_MIGRATIONS_MSG)
670112
function (tryReload, options) {                                        // 139
  tryReload = tryReload || function () {};                                                 // 140
  options = options || {};                                                                 // 141
                                                                                           // 142
  var migrationData = {};                                                                  // 143
  var remaining = _.clone(providers);                                                      // 144
  var allReady = true;                                                                     // 145
  while (remaining.length) {                                                               // 146
    var p = remaining.shift();                                                             // 147
    var status = p.callback(tryReload, options);                                           // 148
    if (!status[0])                                                                        // 149
      allReady = false;                                                                    // 150
    if (status.length > 1 && p.name)                                                       // 151
      migrationData[p.name] = status[1];                                                   // 152
  };                                                                                       // 153
  if (allReady || options.immediateMigration)                                              // 154
    return migrationData;                                                                  // 155
  else                                                                                     // 156
    return null;                                                                           // 157
}
85755
def run_migrations_online():
    
    app_conf = dci_config.generate_conf()
    connectable = dci_config.get_engine(app_conf)
    with connectable.connect() as connection:
        context.configure(
            connection=connection,
            target_metadata=target_metadata,
        )

        with context.begin_transaction():
            context.run_migrations()
1187239
public function runMigrations()
	{
		$migrations = Model::where('status', 'pending');

		if ($migrations->get()->size() > 0) {
			foreach($migrations->get()->all() as $migration) {
				$this->runSingleMigration($migration);
			}
		}
	}
972181
def __apply(self, migration=None, run_all=False):
        
        out = StringIO()
        trace = None

        migrate_kwargs = {
            'interactive': False,
            'stdout': out,
            'database': self._database_name,
        }
        if migration is not None:
            migrate_kwargs.update({
                'app_label': migration[0],
                'migration_name': migration[1],
            })
        elif not run_all:
            raise ValueError('Either a migration must be provided or "run_all" must be True')

        start = self._timer()
        try:
            call_command("migrate", **migrate_kwargs)
        except Exception:
            trace = ''.join(traceback.format_exception(*sys.exc_info()))
        finally:
            end = self._timer()
            successes, failure = self._parse_migrate_output(out.getvalue())

            self._migration_state.append({
                'database': self._database_name,
                'migration': 'all' if run_all else (migration[0], migration[1]),
                'duration': end - start,
                'output': _remove_escape_characters(out.getvalue()),
                'succeeded_migrations': successes,        # [(app, migration), ...]
                'failed_migration': failure,              # (app, migration)
                'traceback': trace,
                'succeeded': failure is None and trace is None,
            })

        if failure is not None:
            raise CommandError("Migration failed for app '{}' - migration '{}'.\n".format(*failure))
        elif trace is not None:
            raise CommandError("Migrations failed unexpectedly. See self.state['traceback'] for details.")
827854
def _pretend_to_run(self, migration, method):
        
        self._note("")
        names = []
        for query in self._get_queries(migration, method):
            name = migration.__class__.__name__
            bindings = None

            if isinstance(query, tuple):
                query, bindings = query

            query = highlight(query, SqlLexer(), CommandFormatter()).strip()

            if bindings:
                query = (query, bindings)

            if name not in names:
                self._note("[<info>{}</info>]".format(name))
                names.append(name)

            self._note(query)
953527
private function exportMigrations()
	{
		$databaseFolder = base_path( 'database/migrations/vendor/' . $this->currentStructure['vendor'] . '/' . $this->currentStructure['module'] . '/' );
		if( ! file_exists( $databaseFolder ) ) {
			return $this->line( 'no migrations to move' );
		}
		$this->moveFilesToResources( $databaseFolder );
	}
627220
def make_migrations(schema=None):
    """"""

    entrypoints = {}
    old = {}

    def apply_migrations(migrations, new_model):
        """Apply migration data to compile an up to date model"""

        def get_path(raw_path):
            """Get local path of schema definition"""

            print("RAW PATH:", raw_path, type(raw_path))
            path = []
            for item in raw_path.split("["):
                print(item)
                item = item.rstrip("]")
                item = item.replace('"', '')
                item = item.replace("'", '')
                try:
                    item = int(item)
                except ValueError:
                    pass
                path.append(item)
            path.remove('root')
            print("PATH:", path)
            return path

        def apply_entry(changetype, change, result):
            """Upgrade with a single migration"""

            def apply_removes(removes, result):
                """Delete removed fields"""

                for remove in removes:
                    path = get_path(remove)
                    amount = dpath.util.delete(result, path)
                    assert amount == 1
                return result

            def apply_additions(additions, result):
                """Add newly added fields"""

                for addition in additions:
                    path = get_path(addition)
                    entry = additions[addition]
                    hfoslog('Adding:', entry, 'at', path)
                    dpath.util.new(result, path, entry)
                return result

            if changetype == 'type_changes':
                hfoslog('Creating new object')
                result = change['root']['new_value']
                return result

            if changetype == 'dictionary_item_added':
                hfoslog('Adding items')
                result = apply_additions(change, result)
            elif changetype == 'dictionary_item_removed':
                hfoslog('Removing items')
                result = apply_removes(change, result)
            elif changetype == 'values_changed':
                hfoslog("Changing items' types")
                for item in change:
                    path = get_path(item)
                    hfoslog('Changing', path, 'from',
                            change[item]['old_value'], ' to',
                            change[item]['new_value'])
                    assert dpath.util.get(result, path) == change[item][
                        'old_value']
                    amount = dpath.util.set(result, path, change[item][
                        'new_value'])
                    assert amount == 1

            return result

        def get_renames(migrations):
            """Check migrations for renamed fields"""

            hfoslog('Checking for rename operations:')
            pprint(migrations)
            for entry in migrations:

                added = entry.get('dictionary_item_added', None)
                removed = entry.get('dictionary_item_removed', None)

            renames = []

            if added and removed:
                for addition in added:
                    path = get_path(addition)
                    for removal in removed:
                        removed_path = get_path(removal)
                        if path[:-1] == removed_path[:-1]:
                            hfoslog('Possible rename detected:', removal, '->',
                                    addition)
                            renames.append((removed_path, path))
            return renames

        result = {}
        for no, migration in enumerate(migrations):
            hfoslog('Migrating', no)
            hfoslog('Migration:', migration, lvl=debug)
            renamed = get_renames(migrations)

            for entry in migration:
                result = apply_entry(entry, migration[entry], result)

        pprint(result)
        return result

    def write_migration(schema, counter, path, previous, current):
        """Write out complete migration data"""

        filename = "%s_%04i.json" % (schema, counter)
        migration = DeepDiff(previous, current, verbose_level=2).json
        if migration == "{}":
            hfoslog('Nothing changed - no new migration data.', lvl=warn)
            return

        print('Writing migration: ', os.path.join(path, filename))
        pprint(migration)

        with open(os.path.join(path, filename), 'w') as f:
            f.write(migration)

    for schema_entrypoint in iter_entry_points(group='hfos.schemata',
                                               name=None):
        try:
            hfoslog("Schemata found: ", schema_entrypoint.name, lvl=debug,
                    emitter='DB')
            if schema is not None and schema_entrypoint.name != schema:
                continue

            entrypoints[schema_entrypoint.name] = schema_entrypoint
            pprint(schema_entrypoint.dist.location)
            schema_top = schema_entrypoint.dist.location
            schema_migrations = schema_entrypoint.module_name.replace(
                'schemata', 'migrations').replace('.', '/')
            path = os.path.join(schema_top, schema_migrations)
            new_model = schema_entrypoint.load()['schema']

            migrations = []

            try:
                for file in sorted(os.listdir(path)):
                    if not file.endswith('.json'):
                        continue
                    fullpath = os.path.join(path, file)
                    hfoslog('Importing migration', fullpath)
                    with open(fullpath, 'r') as f:
                        migration = DeepDiff.from_json(f.read())
                    migrations.append(migration)
                    hfoslog('Successfully imported')

                if len(migrations) == 0:
                    raise ImportError
                pprint(migrations)
                model = apply_migrations(migrations, new_model)
                write_migration(schema, len(migrations) + 1, path, model,
                                new_model)
            except ImportError as e:
                hfoslog('No previous migrations for', schema, e,
                        type(e), exc=True)

            if len(migrations) == 0:
                write_migration(schema, 1, path, None, new_model)

        except (ImportError, DistributionNotFound) as e:
            hfoslog("Problematic schema: ", e, type(e),
                    schema_entrypoint.name, exc=True, lvl=warn,
                    emitter='SCHEMATA')

    hfoslog("Found schemata: ", sorted(entrypoints.keys()), lvl=debug,
            emitter='SCHEMATA')

    pprint(entrypoints)

    def make_single_migration(old, new):
        pass
961983
def not_implemented(self, context, **response_kwargs):
        '''
        
        '''
        if settings.DEBUG:
            raise NotImplementedError(_('This export type ({})is not yet supported.'.format(self.format)))
        raise Http404
1215551
def ListMigrationsToProcess(migrations_root,
                            current_migration_number
                           ):
  """"""
  migrations = []
  for m in os.listdir(migrations_root):
    if (current_migration_number is None or
        _MigrationFilenameToInt(m) > current_migration_number):
      migrations.append(m)

  return sorted(migrations, key=_MigrationFilenameToInt)
464571
function (latestMigrationFile) {
        return function (err, files) {
            if (err) {
                throw err;
            }
            files = _getApplicableMigrations(files, latestMigrationFile);

            var filesRemaining = files.length;
            var parsedMigrations = {};
            console.log('* Number of migration scripts to apply:', filesRemaining);
            if (filesRemaining === 0) {
//                me.client; // TODO : what is this ?
            }

            for (var file in files) {
                if (files.hasOwnProperty(file)) {

                    var filename = files[file];
                    var filepath = _config.migrationFolder + '/' + filename;
                    var parser = new migrationParser(filepath, me.client);
                    parser.on('ready', function () {
                        filesRemaining--;
                        parsedMigrations[basename(this.file)] = this;
                        if (filesRemaining === 0) {
                            var orderedMigrations = _orderMigrations(files, parsedMigrations);

                            // Here is where the migration really takes place
                            me.changelog.apply(orderedMigrations, direction);
                        }
                    });
                }
            }
        }
    }
328434
def dry_run(self):
        
        if self.database_current_migration is None:
            self.printer(
                    u'~> Woulda initialized: %s\n' % self.name_for_printing())
            return u'inited'

        migrations_to_run = self.migrations_to_run()
        if migrations_to_run:
            self.printer(
                u'~> Woulda updated %s:\n' % self.name_for_printing())

            for migration_number, migration_func in migrations_to_run():
                self.printer(
                    u'   + Would update %s, "%s"\n' % (
                        migration_number, migration_func.func_name))

            return u'migrated'
689238
def create_migration(initial=False):
    """"""

    settings = DjangoSettings()
    if 'south' not in (name.lower() for name in settings.INSTALLED_APPS):
        print("Temporarily adding 'south' into INSTALLED_APPS.")
        settings.INSTALLED_APPS.append('south')

    kwargs = dict(initial=True) if initial else dict(auto=True)
    run_django_cmd('schemamigration', package['name'], **kwargs)
780183
def monkey_patch_migration_template(self, app, fixture_path):
        
        self._MIGRATION_TEMPLATE = writer.MIGRATION_TEMPLATE
        module_split = app.module.__name__.split('.')

        if len(module_split) == 1:
            module_import = "import %s\n" % module_split[0]
        else:
            module_import = "from %s import %s\n" % (
                '.'.join(module_split[:-1]),
                module_split[-1:][0],
            )

        writer.MIGRATION_TEMPLATE = writer.MIGRATION_TEMPLATE\
            .replace(
                '%(imports)s',
                "%(imports)s" + "\nfrom django_migration_fixture import fixture\n%s" % module_import
            )\
            .replace(
                '%(operations)s', 
                "        migrations.RunPython(**fixture(%s, ['%s'])),\n" % (
                    app.label,
                    os.path.basename(fixture_path)
                ) + "%(operations)s\n" 
            )