pgsqltools.php 2.2 KB

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