Executing migration

@throws MongobeeException exception
541192
public void execute() throws MongobeeException {
    if (!isEnabled()) {
      logger.info("Mongobee is disabled. Exiting.");
      return;
    }

    validateConfig();

    if (this.mongoClient != null) {
      dao.connectMongoDb(this.mongoClient, dbName);
    } else {
      dao.connectMongoDb(this.mongoClientURI, dbName);
    }

    if (!dao.acquireProcessLock()) {
      logger.info("Mongobee did not acquire process lock. Exiting.");
      return;
    }

    logger.info("Mongobee acquired process lock, starting the data migration sequence..");

    try {
      executeMigration();
    } finally {
      logger.info("Mongobee is releasing process lock.");
      dao.releaseProcessLock();
    }

    logger.info("Mongobee has finished his job.");
  }
511797
public function run(Migration $migration, $executeQueries = false, $forcedRollback = false)
    {
        $this->migration = $migration;

        try {
            $this->playQueries($executeQueries);
            if ($forcedRollback) {
                $this->playRollbackQueries($executeQueries);
            }
        } catch (Exception $e) {
            $this->playRollbackQueries($executeQueries);

            throw $e;
        }
    }
1296622
public function create() {
        $migration = $this->getMessages();
        if (!$migration) {
            $this->db()->insert($this->table, array('migration' => get_class($this), 'state' => false));
        } else {
            throw new \Exception('Migration ' .  get_class($this) . ' already created');
        }
    }
106350
private function executeMigrations()
    {
        if ($this->migrator->needsToRun()) {
            $latestVersion = $this->migrator->migrate();
            $this->logger->info('Migrate all migrations up to version ' . $latestVersion . '.');
        }
    }
425562
public function run(): void
    {
        $continents = json_decode(file_get_contents(__DIR__ . '/../../resources/json/continents.json'), true);

        foreach ($continents as $continent) {

            $this->connection->beginTransaction();

            try {
                $translations = $continent['translations'];
                array_forget($continent, 'translations');

                $continentRecord = $this->continentRepository->updateOrCreate(['id' => $continent['id']], $continent);
                $continentRecord->updateTranslations($translations);

                $this->connection->commit();

            } catch (\Exception $e) {
                $this->connection->rollBack();
                dd($e);
            }
        }
    }
818076
@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
	    try {
			final ResourcesAggregator aggr = this.createResourcesAggregator();
			
			final File fullOutputDirectory = new File(baseOutputDirectory, skinOutputDirectory);
			this.doAggregation(aggr, skinConfigurationFile, fullOutputDirectory);
		} catch (AggregationException e) {
			throw new MojoExecutionException("aggregation failed", e);
		} catch (IOException e) {
			throw new MojoExecutionException("IOException occurred", e);
		}
	}
758964
void migrateProfile(Node oldUserNode) throws Exception
   {
      UserProfile userProfile = new UserProfileImpl(oldUserNode.getName());

      Node attrNode = null;
      try
      {
         attrNode = oldUserNode.getNode(JCROrganizationServiceImpl.JOS_PROFILE + "/" + MigrationTool.JOS_ATTRIBUTES);
      }
      catch (PathNotFoundException e)
      {
         return;
      }
      PropertyIterator props = attrNode.getProperties();

      while (props.hasNext())
      {
         Property prop = props.nextProperty();

         // ignore system properties
         if (!(prop.getName()).startsWith("jcr:") && !(prop.getName()).startsWith("exo:")
            && !(prop.getName()).startsWith("jos:"))
         {
            userProfile.setAttribute(prop.getName(), prop.getString());
         }
      }

      if (findUserProfileByName(userProfile.getUserName()) != null)
      {
         removeUserProfile(userProfile.getUserName(), false);
      }

      saveUserProfile(userProfile, false);
   }
1218949
public function migrate()
	{
		// Set our group arg & call migration
		$this->arguments->setOpt('group', $this->group->get('cn'));
		\App::get('client')->call('migration', 'run', $this->arguments, $this->output);
	}
1238385
public function execute( )
    {
        $this->doAction( self::ON_BEFORE_MIGRATE_CMD_EXECUTE_ACTION );
        
        if ( NULL === $this->migrator )
        {
            throw new MigrationException( 'You must set the migrator before executing this command.' );
        }
        
        $verbose   = self::getOption( $this, 'verbose' )->value;
        
        $direction = self::getOption( $this, 'direction' )->value;
        $levels    = self::getOption( $this, 'levels' )->value;
        
        $this->migrator->verbose = $verbose;
        
        switch( $direction )
        {
            case 'up':
                $this->migrator->migrateUp( $levels );
                break;
            
            case 'down':
                $this->migrator->migrateDown( $levels );
                break;
            
            default:
                // do nothing
                break;
        }
        
        $this->doAction( self::ON_AFTER_MIGRATE_CMD_EXECUTE_ACTION );
    }
1187239
public function runMigrations()
	{
		$migrations = Model::where('status', 'pending');

		if ($migrations->get()->size() > 0) {
			foreach($migrations->get()->all() as $migration) {
				$this->runSingleMigration($migration);
			}
		}
	}
499124
def execute(self, i, o):
        
        super(StatusCommand, self).execute(i, o)

        database = i.get_option('database')
        repository = DatabaseMigrationRepository(self._resolver, 'migrations')

        migrator = Migrator(repository, self._resolver)

        if not migrator.repository_exists():
            return o.writeln('<error>No migrations found</error>')

        self._prepare_database(migrator, database, i, o)

        path = i.get_option('path')

        if path is None:
            path = self._get_migration_path()

        ran = migrator.get_repository().get_ran()

        migrations = []
        for migration in migrator._get_migration_files(path):
            if migration in ran:
                migrations.append(['<fg=cyan>%s</>' % migration, '<info>Yes</info>'])
            else:
                migrations.append(['<fg=cyan>%s</>' % migration, '<fg=red>No</>'])

        if migrations:
            table = self.get_helper('table')
            table.set_headers(['Migration', 'Ran?'])
            table.set_rows(migrations)
            table.render(o)
        else:
            return o.writeln('<error>No migrations found</error>')

        for note in migrator.get_notes():
            o.writeln(note)
536348
def apply_migration(self, migration, **kwargs):
        '''
        
        '''
        cprint("\nAttempting to run %s" % migration, "cyan")
        # First check if the migration has already been applied
        exists = Migration.select().where(Migration.name == migration).limit(1).first()
        if exists and self.direction == 'up':
            cprint("This migration has already been run on this server", "red")
            if not self.force or self.fake:
                return False
            else:
                cprint("Force running this migration again", "yellow")

        # Load the module
        module_name = "%s.%s" % (self.module_name, migration)
        try:
            module = importlib.import_module(module_name)
            if not hasattr(module, self.direction):
                raise MigrationException("%s doesn't have %s migration defined" %
                    (migration, self.direction)
                )
            # Actually execute the direction method
            # Note that this doesn't actually run the migrations in the DB yet.
            # This merely collects the steps in the migration, so that if needed
            # we can just fake it and print out the SQL query as well.
            getattr(module, self.direction)(self)
            # Print out each migration and execute it
            for op in self.operations:
                self.execute_operation(op)

            if not self.fake:
                # If successful, create the entry in our log
                if self.direction == 'up' and not exists:
                    Migration.create(name=migration)
                elif self.direction == 'down' and exists:
                    exists.delete_instance()

            cprint("Done", "green")

        except ImportError:
            raise MigrationException("%s migration not found" % migration)
867621
def execute_migrations(self, show_traceback=True):
        
        all_migrations = get_pending_migrations(self.path, self.databases)
        
        if not len(all_migrations):
            sys.stdout.write("There are no migrations to apply.\n")
        
        for db, migrations in all_migrations.iteritems():
            connection = connections[db]
            
            # init connection
            cursor = connection.cursor()
            cursor.close()
                        
            for migration in migrations:
                migration_path = self._get_migration_path(db, migration)
                
                with Transactional():
                    sys.stdout.write(
                        "Executing migration %r on %r...." %
                        (migration, db)
                    )
                    created_models = self._execute_migration(
                        db,
                        migration_path,
                        show_traceback=show_traceback
                    )

                    emit_post_sync_signal(
                        created_models=created_models,
                        verbosity=self.verbosity,
                        interactive=self.interactive,
                        db=db,
                    )
            
            if self.load_initial_data:
                sys.stdout.write(
                    "Running loaddata for initial_data fixtures on %r.\n" % db
                )
                call_command(
                    "loaddata",
                    "initial_data",
                    verbosity=self.verbosity,
                    database=db,
                )
227957
def execute(self, conn, migration_url="", migration_input="", create_by="", migration_request_id="", oldest= False, transaction=False):
        
        sql = self.sql
        binds = {}
	if migration_request_id:
	    sql += " WHERE MR.MIGRATION_REQUEST_ID=:migration_request_id"
	    binds['migration_request_id']=migration_request_id
        elif oldest:
            #FIXME: Need to write the sql.YG
            #current_date = dbsUtils().getTime()
            #we require waiting time for 
            #retry_count=0 is 1 minutes
            #retry_count=1 is 2 minutes
            #retyr_count=2 is 4 minutes

            sql += """
                       WHERE MR.MIGRATION_STATUS=0 
                       or (MR.migration_status=3 and MR.retry_count=0 and MR.last_modification_date <= :current_date-60)    
                       or (MR.migration_status=3 and MR.retry_count=1 and MR.last_modification_date <= :current_date-120)  
                       or (MR.migration_status=3 and MR.retry_count=2 and MR.last_modification_date <= :current_date-240)
                       ORDER BY MR.creation_date
                   """ 
            binds['current_date'] = dbsUtils().getTime()
            #print "time= " + str(binds['current_date'])
        else:    
	    if  migration_url or migration_input or create_by:
		sql += " WHERE "
	    if migration_url:
		sql += " MR.MIGRATION_URL=:migration_url"
		binds['migration_url']=migration_url
	    if  migration_input:
		if migration_url:
		    sql += " AND "
		op = ("=", "like")["%" in migration_input]
		sql += " MR.MIGRATION_INPUT %s :migration_input" % op
		binds['migration_input']=migration_input
	    if create_by:
		if  migration_url or migration_input:
		    sql += " AND "
		sql += " MR.CREATE_BY=:create_by" %create_by
		binds['create_by']=create_by
	cursors = self.dbi.processData(sql, binds, conn, transaction, returnCursor=True)
        result = []
        for c in cursors:
            result.extend(self.formatCursor(c, size=100))
        return result
836664
private function migrate()
    {
        $action = $this->arg->getParameter('action');

        if (!is_null($action)) {
            $this->throwFailsCommand('This action is not allow!', 'help migration');
        }

        $this->command->call(
            'migrate',
            'migration',
            null
        );
    }
662241
private void init() throws Exception {
        this.useCertAuth = (((Boolean) props.get(USE_CERTIFICATE_AUTHENTICATION)) == null) ? false : (Boolean) props.get(USE_CERTIFICATE_AUTHENTICATION);

        ClassLoader loader = libraryRef.getServiceWithException().getClassLoader();

        // Lazy initialization for version 2.x of the Mongo Java driver.

        boolean sslEnabled = (((Boolean) props.get(SSL_ENABLED)) == null) ? false : (Boolean) props.get(SSL_ENABLED);

        assertLibrary(loader, sslEnabled);
        assertValidSSLConfig();

        // Initialize List<ServerAddress>
        List<Object> serverAddresses = new LinkedList<Object>();
        Constructor<?> ServerAddress_constructor = loader.loadClass("com.mongodb.ServerAddress").getConstructor(String.class, int.class);
        String[] hosts = (String[]) props.get(HOST_NAMES);
        int[] ports = (int[]) props.get(PORTS);
        int numServerAddresses = hosts.length;
        if (hosts.length != ports.length) {
            IllegalArgumentException failure = ignoreWarnOrFail(null, IllegalArgumentException.class, "CWKKD0011.hosts.ports.mismatch",
                                                                MONGO, id, hosts.length, ports.length);
            if (failure == null) // tolerate the error and keep going
                numServerAddresses = hosts.length < ports.length ? hosts.length : ports.length;
            else
                throw failure;
        }

        //Initialise URI. Only used when constructing mongo with the default SSL turned on.
        StringBuilder uriBuilder = new StringBuilder();
        uriBuilder.append("mongodb://");
        for (int i = 0; i < numServerAddresses; i++) {
            serverAddresses.add(ServerAddress_constructor.newInstance(hosts[i], ports[i]));
            //Add server addresses to URI
            uriBuilder.append(hosts[i] + ":" + ports[i]);
            if (i != numServerAddresses - 1) {
                uriBuilder.append(",");
            }
        }

        // Initialize MongoOptions
        Class<?> MongoClientOptions = loader.loadClass("com.mongodb.MongoClientOptions");
        Class<?> MongoClientOptions_Builder = loader.loadClass("com.mongodb.MongoClientOptions$Builder");

        Object optionsBuilder = MongoClientOptions_Builder.newInstance();
        for (Map.Entry<String, Object> prop : props.entrySet()) {
            String name = prop.getKey();
            Object value = prop.getValue();
            if (value != null && name.indexOf('.') < 0 && !NOT_MONGO_CLIENT_OPTIONS.contains(name))
                set(MongoClientOptions_Builder, optionsBuilder, name, value);
        }

        String value = (String) props.get(READ_PREFERENCE);
        if (value != null) {
            setReadPreference(MongoClientOptions_Builder, optionsBuilder, value);
        }
        value = (String) props.get(WRITE_CONCERN);
        if (value != null) {
            setWriteConcern(MongoClientOptions_Builder, optionsBuilder, value);
        }

        //SSL setup
        boolean sslRefExists = props.containsKey(SSL_REF);
        Properties sslProperties = null;
        if (sslEnabled) {
            Map<String, Object> connectionInfo = getConnectionInfo();
            setSocketFactory(MongoClientOptions_Builder, optionsBuilder, connectionInfo);
            sslProperties = sslHelper.getSSLProperties(sslConfigurationRef.getService(), connectionInfo, this);
        }
        // Initialize the Mongo instance
        Class<?> MongoClient = loader.loadClass(com_mongodb_MongoClient);
        Class<?> MongoClientURI = loader.loadClass("com.mongodb.MongoClientURI");
        if (sslEnabled && !sslRefExists && !useCertAuth) {
            // TODO check if this is still needed as we are setting the socket factory above
            uriBuilder.append("/?ssl=true");
            String uri = uriBuilder.toString();
            Constructor<?> MongoClientURI_constructor = MongoClientURI.getConstructor(String.class, MongoClientOptions_Builder);
            Object uriObject = MongoClientURI_constructor.newInstance(uri, optionsBuilder);
            Constructor<?> MongoClient_constructor = MongoClient.getConstructor(MongoClientURI);
            mongoClient = MongoClient_constructor.newInstance(uriObject);

        } else if (sslEnabled && useCertAuth) {
            // get the name from the certificate and handle exceptions / null
            String certificateDN = getCerticateSubject(keyStoreServiceRef, sslProperties);

            // Create an x509 credential calling the MongoCredential class reflectively passing the DN
            Class<?> MongoCredential = loader.loadClass("com.mongodb.MongoCredential");
            Method MongoCredential_createCertificate = MongoCredential.getMethod("createMongoX509Credential", String.class);
            Object credential = MongoCredential_createCertificate.invoke(null, certificateDN);

            // create a client authenticated using this credential
            Constructor<?> MongoClient_constructor = MongoClient.getConstructor(List.class, List.class, MongoClientOptions);
            Object mongoClientOptions = MongoClientOptions_Builder.getMethod("build").invoke(optionsBuilder);
            mongoClient = MongoClient_constructor.newInstance(serverAddresses, Arrays.asList(credential), mongoClientOptions);
        } else {
            Constructor<?> MongoClient_constructor = MongoClient.getConstructor(List.class, MongoClientOptions);
            Object mongoClientOptions = MongoClientOptions_Builder.getMethod("build").invoke(optionsBuilder);
            mongoClient = MongoClient_constructor.newInstance(serverAddresses, mongoClientOptions);
        }

        // Methods that we need each each time a DB instance is created
        MongoClient_getDB = MongoClient.getMethod("getDB", String.class);
        Class<?> DB = loader.loadClass("com.mongodb.DB");
        DB_authenticate = DB.getMethod("authenticate", String.class, char[].class);
        DB_isAuthenticated = DB.getMethod("isAuthenticated");
    }
1311245
protected function runMigration(object $migration, string $method, ?int $batch = null): void
	{
		$migrationInstance = $this->resolve($migration);

		$migrationWrapper = $this->buildMigrationWrapper($migration, $migrationInstance, $method, $batch);

		if($migrationInstance->useTransaction())
		{
			$migrationInstance->getConnection()->transaction(function() use ($migrationWrapper): void
			{
				$migrationWrapper();
			});

			return;
		}

		$migrationWrapper();
	}