1
0

PgSqlTools.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\DB;
  8. use Doctrine\DBAL\Schema\AbstractAsset;
  9. use OCP\IConfig;
  10. use function preg_match;
  11. use function preg_quote;
  12. /**
  13. * Various PostgreSQL specific helper functions.
  14. */
  15. class PgSqlTools {
  16. /** @var \OCP\IConfig */
  17. private $config;
  18. /**
  19. * @param \OCP\IConfig $config
  20. */
  21. public function __construct(IConfig $config) {
  22. $this->config = $config;
  23. }
  24. /**
  25. * @brief Resynchronizes all sequences of a database after using INSERTs
  26. * without leaving out the auto-incremented column.
  27. * @param \OC\DB\Connection $conn
  28. * @return null
  29. */
  30. public function resynchronizeDatabaseSequences(Connection $conn) {
  31. $databaseName = $conn->getDatabase();
  32. $conn->getConfiguration()->setSchemaAssetsFilter(function ($asset) {
  33. /** @var string|AbstractAsset $asset */
  34. $filterExpression = '/^' . preg_quote($this->config->getSystemValueString('dbtableprefix', 'oc_')) . '/';
  35. if ($asset instanceof AbstractAsset) {
  36. return preg_match($filterExpression, $asset->getName()) !== false;
  37. }
  38. return preg_match($filterExpression, $asset) !== false;
  39. });
  40. foreach ($conn->getSchemaManager()->listSequences() as $sequence) {
  41. $sequenceName = $sequence->getName();
  42. $sqlInfo = 'SELECT table_schema, table_name, column_name
  43. FROM information_schema.columns
  44. WHERE column_default = ? AND table_catalog = ?';
  45. $result = $conn->executeQuery($sqlInfo, [
  46. "nextval('$sequenceName'::regclass)",
  47. $databaseName
  48. ]);
  49. $sequenceInfo = $result->fetchAssociative();
  50. $result->free();
  51. /** @var string $tableName */
  52. $tableName = $sequenceInfo['table_name'];
  53. /** @var string $columnName */
  54. $columnName = $sequenceInfo['column_name'];
  55. $sqlMaxId = "SELECT MAX($columnName) FROM $tableName";
  56. $sqlSetval = "SELECT setval('$sequenceName', ($sqlMaxId))";
  57. $conn->executeQuery($sqlSetval);
  58. }
  59. }
  60. }