You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.3 KiB

3 years ago
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Andreas Fischer <bantu@owncloud.com>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Morris Jobke <hey@morrisjobke.de>
  8. * @author tbelau666 <thomas.belau@gmx.de>
  9. * @author Thomas Müller <thomas.mueller@tmit.eu>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OC\DB;
  27. use OCP\IConfig;
  28. /**
  29. * Various PostgreSQL specific helper functions.
  30. */
  31. class PgSqlTools {
  32. /** @var \OCP\IConfig */
  33. private $config;
  34. /**
  35. * @param \OCP\IConfig $config
  36. */
  37. public function __construct(IConfig $config) {
  38. $this->config = $config;
  39. }
  40. /**
  41. * @brief Resynchronizes all sequences of a database after using INSERTs
  42. * without leaving out the auto-incremented column.
  43. * @param \OC\DB\Connection $conn
  44. * @return null
  45. */
  46. public function resynchronizeDatabaseSequences(Connection $conn) {
  47. $filterExpression = '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
  48. $databaseName = $conn->getDatabase();
  49. $conn->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression);
  50. foreach ($conn->getSchemaManager()->listSequences() as $sequence) {
  51. $sequenceName = $sequence->getName();
  52. $sqlInfo = 'SELECT table_schema, table_name, column_name
  53. FROM information_schema.columns
  54. WHERE column_default = ? AND table_catalog = ?';
  55. $sequenceInfo = $conn->fetchAssoc($sqlInfo, [
  56. "nextval('$sequenceName'::regclass)",
  57. $databaseName
  58. ]);
  59. $tableName = $sequenceInfo['table_name'];
  60. $columnName = $sequenceInfo['column_name'];
  61. $sqlMaxId = "SELECT MAX($columnName) FROM $tableName";
  62. $sqlSetval = "SELECT setval('$sequenceName', ($sqlMaxId))";
  63. $conn->executeQuery($sqlSetval);
  64. }
  65. }
  66. }