Generate a diff changelog from differences between actual database state and doctrine metadata.

@param LiquibaseOutput|LiquibaseOutputOptions|null $output
@param array|null $metadata
@return \DOMDocument|mixed
@throws \Doctrine\ORM\ORMException
196416
public function diffChangeLog($output = null, $metadata = null)
    {
        $output = $this->sanitizeOutputParameter($output);
        $metadata = $this->sanitizeMetadatas($metadata);

        $sm = $this->em->getConnection()->getSchemaManager();

        $fromSchema = $sm->createSchema();
        $this->removeLiquibaseTables($fromSchema);
        $toSchema = $this->getSchemaFromMetadata($metadata);

        $comparator = new Comparator();
        $schemaDiff = $comparator->compare($fromSchema, $toSchema);

        return $this->diffChangeLogFromSchemaDiff($schemaDiff, $output);
    }
147514
public function getTableMigration($output, $new, $old)
    {
        if (!empty($this->options['foreign_keys'])) {
            $output[] = $this->getSetUniqueChecks(0);
            $output[] = $this->getSetForeignKeyCheck(0);
        }

        $output = $this->getTableMigrationNewDatabase($output, $new, $old);
        $output = $this->getTableMigrationNewTables($output, $new, $old);

        if (!empty($this->options['foreign_keys'])) {
            $lines = $this->getForeignKeysMigrations($new, $old);
            $output = $this->appendLines($output, $lines);
        }

        $output = $this->getTableMigrationOldTables($output, $new, $old);

        if (!empty($this->options['foreign_keys'])) {
            $output[] = $this->getSetForeignKeyCheck(1);
            $output[] = $this->getSetUniqueChecks(1);
        }

        return $output;
    }
149766
function diff( $old, $new )
    {
        $datatype = $this->dataType();
        $result = $datatype->diff( $old, $new );
        return $result;
    }
790866
protected function outputDiffTable(array $change_list)
    {
        $header = [
            $this->trans('commands.config.diff.table.headers.collection'),
            $this->trans('commands.config.diff.table.headers.config-name'),
            $this->trans('commands.config.diff.table.headers.operation'),
        ];
        $rows = [];
        foreach ($change_list as $collection => $changes) {
            foreach ($changes as $operation => $configs) {
                foreach ($configs as $config) {
                    $rows[] = [
                        $collection,
                        $config,
                        sprintf(self::$operationColours[$operation], $operation),
                    ];
                }
            }
        }
        $this->getIo()->table($header, $rows);
    }
1068969
protected function getMetadata(InputInterface $input, OutputInterface $output, $displayStatus)
    {
        $manager = new DisconnectedMetadataFactory($this->getContainer()->get('doctrine'));
        try {
            $bundle = $this->getContainer()->get("kernel")->getBundle($input->getArgument('name'));
            if ($displayStatus) {
                $output->writeln(sprintf('Generating entities for bundle "<info>%s</info>"', $bundle->getName()));
            }
            $metadata = $manager->getBundleMetadata($bundle);
        } catch (\InvalidArgumentException $e) {
            $name = strtr($input->getArgument('name'), '/', '\\');

            if (false !== $pos = strpos($name, ':')) {
                $name = $this->getContainer()->get('doctrine')
                        ->getAliasNamespace(substr($name, 0, $pos)).'\\'.substr($name, $pos + 1);
            }

            if (class_exists($name)) {
                if ($displayStatus) {
                    $output->writeln(sprintf('Generating entity "<info>%s</info>"', $name));
                }
                $metadata = $manager->getClassMetadata($name, $input->getOption('path'));
            } else {
                if ($displayStatus) {
                    $output->writeln(sprintf('Generating entities for namespace "<info>%s</info>"', $name));
                }
                $metadata = $manager->getNamespaceMetadata($name, $input->getOption('path'));
            }
        }

        return $metadata;
    }
212191
protected function get_other_values(renderer_base $output) {

        $othervalues = [
            'currentversion' => null,
            'draftversions' => [],
            'archivedversions' => [],
        ];

        foreach ($this->related['versions'] as $exporter) {
            $data = $exporter->export($output);

            if ($data->id == $this->data->currentversionid) {
                $othervalues['currentversion'] = $data;

            } else if ($data->archived) {
                $othervalues['archivedversions'][] = $data;

            } else {
                $othervalues['draftversions'][] = $data;
            }
        }

        return $othervalues;
    }
506396
public function doMigrate(OutputInterface $output)
	{
		assert($this->_dispatcher);
		assert($this->_container);

		$this->_clearStatProperties();
		$call = self::$_call;

		$callPhpScript = function($event, $hash, $key, $script, $arguments) use ($call) {
			try
			{
				$errorReporting = error_reporting(E_ALL | E_STRICT);

				if (!$this->_evalCheckSyntax($script))
				{
					/** @noinspection PhpUndefinedMethodInspection */
					$message = sprintf(self::ERROR_WRONG_PHP_SYNTAX, $event->getMigrationName());
					/** @noinspection PhpUndefinedMethodInspection */
					throw new ErrorException($message, 0, E_PARSE, 'action N'.$event->getStep(), 0);
				}

				set_error_handler(function($severity, $message, $file = null, $line = null) {
					if (error_reporting() & $severity)
					{
						throw new ErrorException($message, 0, $severity, $file, $line);
					}
				}, E_ALL | E_STRICT);

				/** @var \Moro\Migration\Event\OnAskMigrationApply $event */
				$service = $this->_container->offsetGet($event->getServiceName());
				return $call($this->_container, $service, $arguments, trim($script), $hash, $this->getValidationKey().$key);
			}
			catch (Exception $exception)
			{
				/** @noinspection PhpUndefinedMethodInspection */
				$event->setException($exception);
				return -1;
			}
			finally
			{
				/** @noinspection PhpUndefinedVariableInspection */
				error_reporting($errorReporting);
				restore_error_handler();
			}
		};

		$this->_dispatcher->dispatch(self::EVENT_INIT_SERVICE, OnInitService::create()->setOutput($output));

		try
		{
			$this->notify(self::STATE_FIRED);

			$modulesAndFiles = $this->_findModulesAndMigrationFiles();
			$migrations      = $this->_parseMigrationFiles($modulesAndFiles);

			$this->notify(self::STATE_FIND_MIGRATIONS);

			$actions         = $this->_askMigrationList($modulesAndFiles, $migrations);
			$actions         = $this->_sortMigrationsList($actions);

			$this->notify(self::STATE_MIGRATIONS_ASKED);

			if (empty($this->_statErrors))
			{
				$actions[0] && $this->_askMigrationRollback($actions[0], $callPhpScript);
				$actions[1] && $this->_askMigrationsApply($actions[1], $modulesAndFiles, $callPhpScript);
			}

			$this->notify(self::STATE_COMPLETE);
		}
		catch (Exception $exception)
		{
			$this->_printError($exception);
			$this->notify(self::STATE_COMPLETE);
		}
		finally
		{
			$this->_stateMigrationName = null;
			$this->_state = self::STATE_INITIALIZED;

			$this->_dispatcher->dispatch(self::EVENT_FREE_SERVICE, OnFreeService::create());
		}
	}
471066
private function logChange($contentType, $contentId, $newContent = null, $oldContent = null, $comment = null)
    {
        $type = $oldContent ? 'Update' : 'Insert';

        $this->loggerChange->info(
            $type . ' record',
            [
                'action'      => strtoupper($type),
                'contenttype' => $contentType,
                'id'          => $contentId,
                'new'         => $newContent ? $newContent->toArray() : null,
                'old'         => $oldContent ? $oldContent->toArray() : null,
                'comment'     => $comment,
            ]
        );
    }
12249
protected function executeSchemaCommand(InputInterface $input, OutputInterface $output,
		SchemaTool $schemaTool, array $metadata, SymfonyStyle $ui)
	{
		$merger = new MetadataMerger();
		$metadata = $merger->merge($metadata);

		return parent::executeSchemaCommand($input, $output, $schemaTool, $metadata, $ui);
	}
383482
protected function getTableMigrationNewTables($output, $new, $old)
    {
        if (empty($new['tables'])) {
            return $output;
        }
        foreach ($new['tables'] as $tableName => $table) {
            if ($tableName === $this->options['default_migration_table']) {
                continue;
            }

            if (!isset($old['tables'][$tableName])) {
                // create the table
                $table['has_table_variable'] = true;
                $output = $this->getCreateTable($output, $table, $tableName);
            }

            $output = $this->getTableMigrationNewTablesColumns($output, $table, $tableName, $new, $old);
            $output = $this->getTableMigrationOldTablesColumns($output, $tableName, $new, $old);
            $output = $this->getTableMigrationIndexes($output, $table, $tableName, $new, $old);
        }

        return $output;
    }
192705
protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Get the current version or generate a new one if the user has confirm that this is required
        try {
            $currentVersion = Context::get('version-persister')->getCurrentVersion();
        } catch (\Liip\RMT\Exception\NoReleaseFoundException $e) {
            if (Context::get('information-collector')->getValueFor('confirm-first') == false) {
                throw $e;
            }
            $currentVersion = Context::get('version-generator')->getInitialVersion();
        }
        Context::getInstance()->setParameter('current-version', $currentVersion);

        // Generate and save the new version number
        $newVersion = Context::get('version-generator')->generateNextVersion(
            Context::getParam('current-version')
        );
        Context::getInstance()->setParameter('new-version', $newVersion);

        $this->executeActionListIfExist('pre-release-actions');

        $this->getOutput()->writeSmallTitle('Release process');
        $this->getOutput()->indent();

        $this->getOutput()->writeln("A new version named [<yellow>$newVersion</yellow>] is going to be released");
        Context::get('version-persister')->save($newVersion);
        $this->getOutput()->writeln('Release: <green>Success</green>');

        $this->getOutput()->unIndent();

        $this->executeActionListIfExist('post-release-actions');
    }
1014757
static function databaseVersion( $withRelease = true )
    {
        $db = eZDB::instance();
        $rows = $db->arrayQuery( "SELECT value as version FROM ezsite_data WHERE name='ezpublish-version'" );
        $version = false;
        if ( count( $rows ) > 0 )
        {
            $version = $rows[0]['version'];
            if ( $withRelease )
            {
                $release = eZPublishSDK::databaseRelease();
                $version .= '-' . $release;
            }
        }
        return $version;
    }
80308
protected function serialize($input, ClassMetadata $metadata)
    {
        $output = [];
        foreach ($metadata->getFieldMappings() as $field) {
            $fieldObj = $this->em->getFieldManager()->get($field['fieldtype'], $field);
            $type = $fieldObj->getStorageType();
            $key = $field['fieldname'];

            // Hack … remove soon
            if (!isset($input[$key])) {
                continue;
            }
            if (Json::test($input[$key])) {
                $input[$key] = Json::parse($input[$key]);
            }
            $output[$key] = $type->convertToDatabaseValue($input[$key], $this->getPlatform());
        }

        return $output;
    }
1196208
protected function getTableMigrationNewTablesColumns($output, $table, $tableName, $new, $old)
    {
        if (empty($table['columns'])) {
            return $output;
        }
        $hasTableVariable = !empty($table['has_table_variable']);
        $alternatePrimaryKeys = $this->getAlternatePrimaryKeys($table);
        $opened = false;

        foreach ($table['columns'] as $columnName => $columnData) {
            if (!isset($old['tables'][$tableName]['columns'][$columnName])) {
                $opened = true;

                if (!$hasTableVariable) {
                    $output[] = sprintf("%s\$table = \$this->table(\"%s\");", $this->ind2, $tableName);
                    $hasTableVariable = true;
                }

                if ($columnName == 'id') {
                    $output[] = $this->getColumnCreateId($new, $tableName, $columnName);
                } else {
                    if (!empty($alternatePrimaryKeys)) {
                        $output[] = $this->getColumnCreateAddNoUpdate($new, $tableName, $columnName);
                    } else {
                        $output[] = $this->getColumnCreateAdd($new, $tableName, $columnName);
                    }
                }
            } else {
                if ($this->neq($new, $old, ['tables', $tableName, 'columns', $columnName])) {
                    $output[] = $this->getColumnUpdate($new, $tableName, $columnName);
                }
            }
        }
        if ($opened) {
            $output[] = sprintf("%s\$table->save();", $this->ind2);
        }

        return $output;
    }
1069682
private function createDatabase(
        OutputInterface $output,
        Connection $tmpConnection,
        string $name,
        bool $shouldNotCreateDatabase
    ): int {
        try {
            if ($shouldNotCreateDatabase) {
                $output->writeln(sprintf('<info>Database <comment>%s</comment> already exists.</info>', $name));
            } else {
                $tmpConnection->getSchemaManager()->createDatabase($name);
                $output->writeln(sprintf('<info>Created database <comment>%s</comment>', $name));
            }

            return 0;
        } catch (\Exception $e) {
            $output->writeln(sprintf('<error>Could not create database <comment>%s</comment></error>', $name));
            $output->writeln(sprintf('<error>%s</error>', $e->getMessage()));

            return 1;
        }
    }
711610
protected function showDebugger(array $output)
    {
        $output['queries'] = $this->connection->getQueryLog();
        $output['input']   = $this->request->all();

        return $output;
    }
339077
public function diffChangeLogFromSchemaDiff(SchemaDiff $schemaDiff, $output = null)
    {
        $output = $this->sanitizeOutputParameter($output);

        $output->started($this->em);

        foreach ($schemaDiff->newNamespaces as $newNamespace) {
            $output->createSchema($newNamespace);
        }

        foreach ($schemaDiff->orphanedForeignKeys as $orphanedForeignKey) {
            $output->dropForeignKey($orphanedForeignKey, $orphanedForeignKey->getLocalTable());
        }

        foreach ($schemaDiff->changedSequences as $sequence) {
            $output->alterSequence($sequence);
        }

        foreach ($schemaDiff->removedSequences as $sequence) {
            $output->dropSequence($sequence);
        }

        foreach ($schemaDiff->newSequences as $sequence) {
            $output->createSequence($sequence);
        }

        foreach ($schemaDiff->newTables as $table) {
            $output->createTable($table);
            
            foreach ($table->getForeignKeys() as $foreignKey) {
                $output->createForeignKey($foreignKey, $table);
            }
        }

        foreach ($schemaDiff->removedTables as $table) {
            $output->dropTable($table);
        }

        foreach ($schemaDiff->changedTables as $tableDiff) {
            $output->alterTable($tableDiff);
        }

        $output->terminated();

        return $output->getResult();
    }