PgSqlTools.php 2.2 KB

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