DatabaseHasMissingPrimaryKeys.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\Settings\SetupChecks;
  8. use OC\DB\Connection;
  9. use OC\DB\MissingPrimaryKeyInformation;
  10. use OC\DB\SchemaWrapper;
  11. use OCP\DB\Events\AddMissingPrimaryKeyEvent;
  12. use OCP\EventDispatcher\IEventDispatcher;
  13. use OCP\IL10N;
  14. use OCP\SetupCheck\ISetupCheck;
  15. use OCP\SetupCheck\SetupResult;
  16. class DatabaseHasMissingPrimaryKeys implements ISetupCheck {
  17. public function __construct(
  18. private IL10N $l10n,
  19. private Connection $connection,
  20. private IEventDispatcher $dispatcher,
  21. ) {
  22. }
  23. public function getCategory(): string {
  24. return 'database';
  25. }
  26. public function getName(): string {
  27. return $this->l10n->t('Database missing primary keys');
  28. }
  29. private function getMissingPrimaryKeys(): array {
  30. $primaryKeyInfo = new MissingPrimaryKeyInformation();
  31. // Dispatch event so apps can also hint for pending primary key updates if needed
  32. $event = new AddMissingPrimaryKeyEvent();
  33. $this->dispatcher->dispatchTyped($event);
  34. $missingPrimaryKeys = $event->getMissingPrimaryKeys();
  35. if (!empty($missingPrimaryKeys)) {
  36. $schema = new SchemaWrapper($this->connection);
  37. foreach ($missingPrimaryKeys as $missingPrimaryKey) {
  38. if ($schema->hasTable($missingPrimaryKey['tableName'])) {
  39. $table = $schema->getTable($missingPrimaryKey['tableName']);
  40. if ($table->getPrimaryKey() === null) {
  41. $primaryKeyInfo->addHintForMissingPrimaryKey($missingPrimaryKey['tableName']);
  42. }
  43. }
  44. }
  45. }
  46. return $primaryKeyInfo->getListOfMissingPrimaryKeys();
  47. }
  48. public function run(): SetupResult {
  49. $missingPrimaryKeys = $this->getMissingPrimaryKeys();
  50. if (empty($missingPrimaryKeys)) {
  51. return SetupResult::success('None');
  52. } else {
  53. $list = '';
  54. foreach ($missingPrimaryKeys as $missingPrimaryKey) {
  55. $list .= "\n".$this->l10n->t('Missing primary key on table "%s".', [$missingPrimaryKey['tableName']]);
  56. }
  57. return SetupResult::warning(
  58. $this->l10n->t('The database is missing some primary keys. Due to the fact that adding primary keys on big tables could take some time they were not added automatically. By running "occ db:add-missing-primary-keys" those missing primary keys could be added manually while the instance keeps running.').$list
  59. );
  60. }
  61. }
  62. }