Method that aggregates all needed migration operations in needed order.
@throws RepositoryException
485802
void migrate() throws RepositoryException
   {
      try
      {
         LOG.info("Migration started.");

         moveOldStructure();
         service.createStructure();

         //Migration order is important due to removal of nodes.
         migrateGroups();
         migrateMembershipTypes();
         migrateUsers();
         migrateProfiles();
         migrateMemberships();

         removeOldStructure();

         LOG.info("Migration completed.");
      }
      catch (Exception e)//NOSONAR
      {
         throw new RepositoryException("Migration failed", e);
      }
   }
610361
private void migrateGroups() throws Exception
   {
      Session session = service.getStorageSession();
      try
      {
         if (session.itemExists(groupsStorageOld))
         {
            NodeIterator iterator = ((ExtendedNode)session.getItem(groupsStorageOld)).getNodesLazily();
            GroupHandlerImpl gh = ((GroupHandlerImpl)service.getGroupHandler());
            while (iterator.hasNext())
            {
               Node oldGroupNode = iterator.nextNode();
               gh.migrateGroup(oldGroupNode);
               migrateGroups(oldGroupNode);
            }
         }
      }
      finally
      {
         session.logout();
      }
   }
247697
function () {
                /*  determine parameters  */
                var params = $cs.params("migrate", arguments, {
                    comps:     { pos: "...", req: true    },
                    sync:      {             def: false   },
                    completed: {             def: $cs.nop }
                });

                /*  iterate over all components to migrate  */
                var n = 0;
                var parent = this;
                _cs.foreach(params.comps, function (comp) {
                    if (params.sync) {
                        /*  migrate synchronously  */
                        var state_old = comp.state();
                        comp.state({ state: "created", sync: true });
                        comp.detach();
                        comp.attach(parent);
                        comp.state(state_old);
                    }
                    else {
                        /*  migrate asynchronously  */
                        (function (comp, state_old) {
                            comp.state({ state: "created", sync: false, callback: function (/* state_new */) {
                                this.detach();
                                this.attach(parent);
                                this.state({ state: state_old, sync: false, callback: function (/* state_old */) {
                                    n--;
                                    if (n === 0)
                                        params.completed.call(null);
                                }});
                            }});
                        })(comp, comp.state());
                        n++;
                    }
                });
            }
233335
private void migrate() throws SQLException {
		QueryVO pk = helper.selectAll("pkList",
			ObjectBuilder.<String, Object>map().put("tables", tables).get());
		List<TablePkFkVO> tablePkFkVOs = pk.toBeans(TablePkFkVO.class);

		logger.info("TablePkFkVO size = {}", tablePkFkVOs.size());

		for (TablePkFkVO table : tablePkFkVOs) {
			QueryVO fk = helper.selectAll("fkList",
				ObjectBuilder.<String, Object>map().put("table", table.getName()).get());
			table.setReferencedBy(fk.toBeans(RefConsVO.class));
		}

		logger.info("TablePkFkVO size = {}", tablePkFkVOs.size());

		for (TablePkFkVO tablePkFkVO : tablePkFkVOs) {
			migrateTable(tablePkFkVO);
		}
	}
1193692
@Override
    public Operation prepareReplicationOperation(PartitionReplicationEvent event) {
        if (event.getReplicaIndex() > 1) {
            return null;
        }

        List<XATransactionDTO> migrationData = new ArrayList<XATransactionDTO>();
        InternalPartitionService partitionService = nodeEngine.getPartitionService();
        for (Map.Entry<SerializableXID, List<XATransaction>> entry : transactions.entrySet()) {
            SerializableXID xid = entry.getKey();
            int partitionId = partitionService.getPartitionId(xid);
            List<XATransaction> xaTransactionList = entry.getValue();
            for (XATransaction xaTransaction : xaTransactionList) {
                if (partitionId == event.getPartitionId()) {
                    migrationData.add(new XATransactionDTO(xaTransaction));
                }
            }
        }
        if (migrationData.isEmpty()) {
            return null;
        } else {
            return new XaReplicationOperation(migrationData, event.getPartitionId(), event.getReplicaIndex());
        }
    }
385432
public function 
    {

        $count = $this->count();

        foreach ($this->migrations as $i => $mig) {
            if ($this->preCallback) {
                $callback = $this->preCallback;
                $callback($mig->getVersion(), $i, $count);
            }

            if ($this->direction == 'up') {
                $mig->up();
            } elseif ($this->direction == 'down') {
                $mig->down();
            }

            if ($this->postCallback) {
                $callback = $this->postCallback;
                $callback($mig->getVersion(), $i, $count);
            }
        }
    }
514892
private void commitSource() {
        int partitionId = getPartitionId();
        InternalPartitionServiceImpl partitionService = getService();
        PartitionReplicaManager replicaManager = partitionService.getReplicaManager();

        ILogger logger = getLogger();

        int sourceNewReplicaIndex = migrationInfo.getSourceNewReplicaIndex();
        if (sourceNewReplicaIndex < 0) {
            clearPartitionReplicaVersions(partitionId);
            if (logger.isFinestEnabled()) {
                logger.finest("Replica versions are cleared in source after migration. partitionId=" + partitionId);
            }
        } else if (migrationInfo.getSourceCurrentReplicaIndex() != sourceNewReplicaIndex && sourceNewReplicaIndex > 1) {
            for (ServiceNamespace namespace : replicaManager.getNamespaces(partitionId)) {
                long[] versions = updatePartitionReplicaVersions(replicaManager, partitionId,
                                                                 namespace, sourceNewReplicaIndex - 1);
                if (logger.isFinestEnabled()) {
                    logger.finest("Replica versions are set after SHIFT DOWN migration. partitionId="
                            + partitionId + " namespace: " + namespace + " replica versions=" + Arrays.toString(versions));
                }
            }
        }
    }
130610
public void captureOrderings(OrderingList<?> ordering) {
        try {
            if (ordering != null) {
                for (OrderedProperty<?> orderedProperty : ordering) {
                    ChainedProperty<?> chained = orderedProperty.getChainedProperty();
                    if (!chained.isDerived()) {
                        mRootJoinNode.addJoin(mRepository, chained, mAliasGenerator);
                    }
                }
            }
        } catch (RepositoryException e) {
            throw new UndeclaredThrowableException(e);
        }
    }
582664
public void processMigration(Migration dbMigration, DdlWrite write) throws IOException {
        DdlHandler handler = handler();
        handler.generateProlog(write);
        List<ChangeSet> changeSets = dbMigration.getChangeSet();
        for (ChangeSet changeSet : changeSets) {
            if (isApply(changeSet)) {
                handler.generate(write, changeSet);
            }
        }
        handler.generateEpilog(write);

        writePlatformDdl(write);
    }
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;
        }
    }
890944
private void removeOldStructure() throws RepositoryException
   {
      ExtendedSession session = (ExtendedSession)service.getStorageSession();
      try
      {
         if (session.itemExists(storagePathOld))
         {
            NodeIterator usersIter = ((ExtendedNode)session.getItem(usersStorageOld)).getNodesLazily();
            while (usersIter.hasNext())
            {
               Node currentUser = usersIter.nextNode();
               currentUser.remove();
               session.save();
            }

            NodeIterator groupsIter = ((ExtendedNode)session.getItem(groupsStorageOld)).getNodesLazily();
            while (groupsIter.hasNext())
            {
               Node currentGroup = groupsIter.nextNode();
               currentGroup.remove();
               session.save();
            }

            NodeIterator membershipTypesIter =
               ((ExtendedNode)session.getItem(membershipTypesStorageOld)).getNodesLazily();
            while (membershipTypesIter.hasNext())
            {
               Node currentMembershipType = membershipTypesIter.nextNode();
               currentMembershipType.remove();
               session.save();
            }

            session.getItem(storagePathOld).remove();
            session.save();
         }
      }
      finally
      {
         session.logout();
      }
   }
45613
@Override
    public <E extends Exception> void add(Iteration<? extends Statement, E> statements, Resource... contexts) throws RepositoryException, E {
        while(statements.hasNext()){
            Statement st = statements.next();
            add(st.getSubject(), st.getPredicate(), st.getObject(), mergeResource(st.getContext(), contexts));
        }
    }
178943
protected void readMigrations() {
        final List<MigrationResource> resources = findMigrationResource();

        // sort into version order before applying
        Collections.sort(resources);

        for (MigrationResource migrationResource : resources) {
            logger.debug("read {}", migrationResource);
            model.apply(migrationResource.read(), migrationResource.getVersion());
        }

        // remember the last version
        if (!resources.isEmpty()) {
            lastVersion = resources.get(resources.size() - 1).getVersion();
        }
    }
253113
void executeBeforeMigrations() throws Exception {
        PartitionMigrationEvent event = getMigrationEvent();

        Throwable t = null;
        for (MigrationAwareService service : getMigrationAwareServices()) {
            // we need to make sure all beforeMigration() methods are executed
            try {
                service.beforeMigration(event);
            } catch (Throwable e) {
                getLogger().warning("Error while executing beforeMigration()", e);
                t = e;
            }
        }
        if (t != null) {
            throw ExceptionUtil.rethrow(t);
        }
    }
1317991
public function executeAll()
    {
        $repository = $this->repository;

        $entity = $this->entity;

        $prepare = $repository->prepareQuery($entity->getQuery(), $entity->getRecordClass());

        $measure = str_replace("\n", " ", $prepare->queryString);
        $hash = sha1($measure . microtime());

        startMeasure('Executing ' . $measure);
        $execute = $repository->executePrepared($prepare);
        stopMeasure('Executing ' . $measure);

        if (!$execute) {
            return new Collection();
        }

        $results = $repository->fetchAllPrepared($prepare);

        if (!$results) {
            return new Collection();
        }

        $collection = new Collection($results);
        if ($entity->getQuery()->isCounted()) {
            startMeasure('Counting ' . $hash);
            $prepareCount = $repository->prepareSQL('SELECT FOUND_ROWS()');
            $repository->executePrepared($prepareCount);
            $collection->setTotal($prepareCount->fetch(PDO::FETCH_COLUMN));
            $entity->count(false);
            stopMeasure('Counting ' . $hash);
        }

        startMeasure('Setting original ' . $hash);
        $collection->setEntity($entity)->setSaved()->setOriginalFromData();
        stopMeasure('Setting original ' . $hash);

        startMeasure('Filling relations ' . $hash);
        $filled = $entity->fillCollectionWithRelations($collection);
        stopMeasure('Filling relations ' . $hash);

        return $filled;
    }
1359865
protected function prepareExecute()
    {
        // Prepare migration path
        $packageName = $this->getOption('p');

        /** @var AbstractPackage $package */
        $package = $this->console->getPackage($packageName);

        if ($package) {
            $dir = $package->getDir() . '/Migration';
        } else {
            $dir = $this->getOption('d');
        }

        $dir = $dir ?: $this->console->get('path.migrations');

        $this->console->set('migration.dir', $dir);

        // DB log
        $this->console->database->setDebug(true);

        $this->console->database->setMonitor(
            new CallbackMonitor(function ($query) {
                $this->console->triggerEvent('onMigrationAfterQuery', ['query' => $query]);
            })
        );
    }
227969
public function applyToCollection(Builder $aggregationBuilder, string $resourceClass, string $operationName = null, array &$context = [])
    {
        if (!$this->pagination->isEnabled($resourceClass, $operationName, $context)) {
            return;
        }

        $context = $this->addCountToContext(clone $aggregationBuilder, $context);

        [, $offset, $limit] = $this->pagination->getPagination($resourceClass, $operationName, $context);

        $manager = $this->managerRegistry->getManagerForClass($resourceClass);
        if (!$manager instanceof DocumentManager) {
            throw new RuntimeException(sprintf('The manager for "%s" must be an instance of "%s".', $resourceClass, DocumentManager::class));
        }

        $repository = $manager->getRepository($resourceClass);
        if (!$repository instanceof DocumentRepository) {
            throw new RuntimeException(sprintf('The repository for "%s" must be an instance of "%s".', $resourceClass, DocumentRepository::class));
        }

        $resultsAggregationBuilder = $repository->createAggregationBuilder()->skip($offset);
        if ($limit > 0) {
            $resultsAggregationBuilder->limit($limit);
        } else {
            // Results have to be 0 but MongoDB does not support a limit equal to 0.
            $resultsAggregationBuilder->match()->field(Paginator::LIMIT_ZERO_MARKER_FIELD)->equals(Paginator::LIMIT_ZERO_MARKER);
        }

        $aggregationBuilder
            ->facet()
            ->field('results')->pipeline(
                $resultsAggregationBuilder
            )
            ->field('count')->pipeline(
                $repository->createAggregationBuilder()
                    ->count('count')
            );
    }