diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index b1e31685b4..29e79b78ae 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -420,6 +420,16 @@ parameters: count: 1 path: src/bundle/Core/Command/UpdateTimestampsToUTCCommand.php + - + message: "#^Cannot cast Doctrine\\\\DBAL\\\\ForwardCompatibility\\\\Result\\|int\\|string to int\\.$#" + count: 1 + path: src/bundle/Core/Command/VirtualFieldDuplicateFixCommand.php + + - + message: "#^Method Ibexa\\\\Bundle\\\\Core\\\\Command\\\\VirtualFieldDuplicateFixCommand\\:\\:getDuplicatedAttributesBatch\\(\\) should return array\\ but returns array\\\\>\\.$#" + count: 1 + path: src/bundle/Core/Command/VirtualFieldDuplicateFixCommand.php + - message: "#^Method Ibexa\\\\Bundle\\\\Core\\\\Converter\\\\ContentParamConverter\\:\\:getSupportedClass\\(\\) has no return type specified\\.$#" count: 1 @@ -10885,11 +10895,6 @@ parameters: count: 1 path: src/lib/IO/IOMetadataHandler/LegacyDFSCluster.php - - - message: "#^Cannot call method rowCount\\(\\) on Doctrine\\\\DBAL\\\\ForwardCompatibility\\\\Result\\|int\\|string\\.$#" - count: 3 - path: src/lib/IO/IOMetadataHandler/LegacyDFSCluster.php - - message: "#^Method Ibexa\\\\Core\\\\IO\\\\IOMetadataHandler\\\\LegacyDFSCluster\\:\\:delete\\(\\) has no return type specified\\.$#" count: 1 diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 54acab26b1..a8e4451c5c 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -9,7 +9,7 @@ parameters: treatPhpDocTypesAsCertain: false ignoreErrors: - - message: "#^Cannot call method (fetchOne|fetchColumn|fetchAllAssociative|fetchAssociative|fetchAllKeyValue|fetchFirstColumn)\\(\\) on Doctrine\\\\DBAL\\\\ForwardCompatibility\\\\Result\\|int\\|string\\.$#" + message: "#^Cannot call method (fetchOne|fetchColumn|fetchAllAssociative|fetchAssociative|fetchAllKeyValue|fetchFirstColumn|rowCount)\\(\\) on Doctrine\\\\DBAL\\\\ForwardCompatibility\\\\Result\\|int\\|string\\.$#" paths: - src/* - tests/* diff --git a/src/bundle/Core/Command/VirtualFieldDuplicateFixCommand.php b/src/bundle/Core/Command/VirtualFieldDuplicateFixCommand.php new file mode 100644 index 0000000000..4ca0cedadc --- /dev/null +++ b/src/bundle/Core/Command/VirtualFieldDuplicateFixCommand.php @@ -0,0 +1,263 @@ +connection = $connection; + } + + public function configure(): void + { + $this->addOption( + 'batch-size', + 'b', + InputOption::VALUE_REQUIRED, + 'Number of attributes affected per iteration', + self::DEFAULT_BATCH_SIZE + ); + + $this->addOption( + 'max-iterations', + 'i', + InputOption::VALUE_REQUIRED, + 'Max iterations count (default or -1: unlimited)', + self::MAX_ITERATIONS_UNLIMITED + ); + + $this->addOption( + 'sleep', + 's', + InputOption::VALUE_REQUIRED, + 'Wait between iterations, in milliseconds', + self::DEFAULT_SLEEP + ); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $style = new SymfonyStyle($input, $output); + $stopwatch = new Stopwatch(true); + $stopwatch->start('total', 'command'); + + $batchSize = (int)$input->getOption('batch-size'); + if ($batchSize === 0) { + $style->warning('Batch size is set to 0. Nothing to do.'); + + return Command::INVALID; + } + + $maxIterations = (int)$input->getOption('max-iterations'); + if ($maxIterations === 0) { + $style->warning('Max iterations is set to 0. Nothing to do.'); + + return Command::INVALID; + } + + $sleep = (int)$input->getOption('sleep'); + + $totalCount = $this->getDuplicatedAttributeTotalCount($style, $stopwatch); + + if ($totalCount === 0) { + $style->success('Database is clean of attribute duplicates. Nothing to do.'); + + return Command::SUCCESS; + } + + if ($input->isInteractive()) { + $confirmation = $this->askForConfirmation($style); + if (!$confirmation) { + $style->info('Confirmation rejected. Terminating.'); + + return Command::FAILURE; + } + } + + $iteration = 1; + $totalDeleted = 0; + do { + $deleted = 0; + $stopwatch->start('iteration', 'sql'); + + $attributes = $this->getDuplicatedAttributesBatch($batchSize); + foreach ($attributes as $attribute) { + $attributeIds = $this->getDuplicatedAttributeIds($attribute); + + if (!empty($attributeIds)) { + $iterationDeleted = $this->deleteAttributes($attributeIds); + + $deleted += $iterationDeleted; + $totalDeleted += $iterationDeleted; + } + } + + $style->info( + sprintf( + 'Iteration %d: Removed %d duplicate database rows (total removed this execution: %d). [Debug %s]', + $iteration, + $deleted, + $totalDeleted, + $stopwatch->stop('iteration') + ) + ); + + if ($maxIterations !== self::MAX_ITERATIONS_UNLIMITED && ++$iteration > $maxIterations) { + $style->warning('Max iterations count reached. Terminating.'); + + return self::SUCCESS; + } + + // Wait, if needed, before moving to next iteration + usleep($sleep * 1000); + } while ($batchSize === count($attributes)); + + $style->success(sprintf( + 'Operation successful. Removed total of %d duplicate database rows. [Debug %s]', + $totalDeleted, + $stopwatch->stop('total') + )); + + return Command::SUCCESS; + } + + private function getDuplicatedAttributeTotalCount( + SymfonyStyle $style, + Stopwatch $stopwatch + ): int { + $stopwatch->start('total_count', 'sql'); + $query = $this->connection->createQueryBuilder() + ->select('COUNT(a.id) as instances') + ->groupBy('version', 'contentclassattribute_id', 'contentobject_id', 'language_id') + ->from('ezcontentobject_attribute', 'a') + ->having('instances > 1'); + + $count = (int) $query->execute()->rowCount(); + + if ($count > 0) { + $style->warning( + sprintf( + 'Found %d of affected attributes. [Debug: %s]', + $count, + $stopwatch->stop('total_count') + ) + ); + } + + return $count; + } + + /** + * @phpstan-return array + */ + private function getDuplicatedAttributesBatch(int $batchSize): array + { + $query = $this->connection->createQueryBuilder(); + + $query + ->select('version', 'contentclassattribute_id', 'contentobject_id', 'language_id') + ->groupBy('version', 'contentclassattribute_id', 'contentobject_id', 'language_id') + ->from('ezcontentobject_attribute') + ->having('COUNT(id) > 1') + ->setFirstResult(0) + ->setMaxResults($batchSize); + + return $query->execute()->fetchAllAssociative(); + } + + /** + * @phpstan-param array{ + * version: int, + * contentclassattribute_id: int, + * contentobject_id: int, + * language_id: int + * } $attribute + * + * @return int[] + */ + private function getDuplicatedAttributeIds(array $attribute): array + { + $query = $this->connection->createQueryBuilder(); + + $query + ->select('id') + ->from('ezcontentobject_attribute') + ->andWhere('version = :version') + ->andWhere('contentclassattribute_id = :contentclassattribute_id') + ->andWhere('contentobject_id = :contentobject_id') + ->andWhere('language_id = :language_id') + ->orderBy('id', 'ASC') + // Keep the original attribute row, the very first one + ->setFirstResult(1); + + $query->setParameters($attribute); + $result = $query->execute()->fetchFirstColumn(); + + return array_map('intval', $result); + } + + private function askForConfirmation(SymfonyStyle $style): bool + { + $style->warning('Operation is irreversible.'); + + return $style->askQuestion( + new ConfirmationQuestion( + 'Proceed with deletion?', + false + ) + ); + } + + /** + * @param int[] $ids + * + * @throws \Doctrine\DBAL\Exception + */ + private function deleteAttributes(array $ids): int + { + $query = $this->connection->createQueryBuilder(); + + $query + ->delete('ezcontentobject_attribute') + ->andWhere($query->expr()->in('id', array_map('strval', $ids))); + + return (int)$query->execute(); + } +} diff --git a/src/bundle/Core/Resources/config/commands.yml b/src/bundle/Core/Resources/config/commands.yml index bd92d66a04..e8b077d0cf 100644 --- a/src/bundle/Core/Resources/config/commands.yml +++ b/src/bundle/Core/Resources/config/commands.yml @@ -66,6 +66,14 @@ services: autowire: true autoconfigure: true + Ibexa\Bundle\Core\Command\VirtualFieldDuplicateFixCommand: + autowire: true + autoconfigure: true + arguments: + $connection: '@ibexa.persistence.connection' + tags: + - { name: console.command } + # Dedicated services for commands Ibexa\Bundle\Core\Command\Indexer\ContentIdList\ContentTypeInputGeneratorStrategy: autowire: true