AdapterPgSql.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. class AdapterPgSql extends Adapter {
  9. protected $compatModePre9_5 = null;
  10. public function lastInsertId($table) {
  11. $result = $this->conn->executeQuery('SELECT lastval()');
  12. $val = $result->fetchOne();
  13. $result->free();
  14. return (int)$val;
  15. }
  16. public const UNIX_TIMESTAMP_REPLACEMENT = 'cast(extract(epoch from current_timestamp) as integer)';
  17. public function fixupStatement($statement) {
  18. $statement = str_replace('`', '"', $statement);
  19. $statement = str_ireplace('UNIX_TIMESTAMP()', self::UNIX_TIMESTAMP_REPLACEMENT, $statement);
  20. return $statement;
  21. }
  22. public function insertIgnoreConflict(string $table, array $values) : int {
  23. if ($this->isPre9_5CompatMode() === true) {
  24. return parent::insertIgnoreConflict($table, $values);
  25. }
  26. // "upsert" is only available since PgSQL 9.5, but the generic way
  27. // would leave error logs in the DB.
  28. $builder = $this->conn->getQueryBuilder();
  29. $builder->insert($table);
  30. foreach ($values as $key => $value) {
  31. $builder->setValue($key, $builder->createNamedParameter($value));
  32. }
  33. $queryString = $builder->getSQL() . ' ON CONFLICT DO NOTHING';
  34. return $this->conn->executeUpdate($queryString, $builder->getParameters(), $builder->getParameterTypes());
  35. }
  36. protected function isPre9_5CompatMode(): bool {
  37. if ($this->compatModePre9_5 !== null) {
  38. return $this->compatModePre9_5;
  39. }
  40. $result = $this->conn->executeQuery('SHOW SERVER_VERSION');
  41. $version = $result->fetchOne();
  42. $result->free();
  43. $this->compatModePre9_5 = version_compare($version, '9.5', '<');
  44. return $this->compatModePre9_5;
  45. }
  46. }