Adapter.php 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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\Exception;
  9. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  10. use OC\DB\Exceptions\DbalException;
  11. /**
  12. * This handles the way we use to write queries, into something that can be
  13. * handled by the database abstraction layer.
  14. */
  15. class Adapter {
  16. /**
  17. * @var \OC\DB\Connection $conn
  18. */
  19. protected $conn;
  20. public function __construct($conn) {
  21. $this->conn = $conn;
  22. }
  23. /**
  24. * @param string $table name
  25. *
  26. * @return int id of last insert statement
  27. * @throws Exception
  28. */
  29. public function lastInsertId($table) {
  30. return (int)$this->conn->realLastInsertId($table);
  31. }
  32. /**
  33. * @param string $statement that needs to be changed so the db can handle it
  34. * @return string changed statement
  35. */
  36. public function fixupStatement($statement) {
  37. return $statement;
  38. }
  39. /**
  40. * Create an exclusive read+write lock on a table
  41. *
  42. * @throws Exception
  43. * @since 9.1.0
  44. */
  45. public function lockTable(string $tableName) {
  46. $this->conn->beginTransaction();
  47. $this->conn->executeUpdate('LOCK TABLE `' . $tableName . '` IN EXCLUSIVE MODE');
  48. }
  49. /**
  50. * Release a previous acquired lock again
  51. *
  52. * @throws Exception
  53. * @since 9.1.0
  54. */
  55. public function unlockTable() {
  56. $this->conn->commit();
  57. }
  58. /**
  59. * Insert a row if the matching row does not exists. To accomplish proper race condition avoidance
  60. * it is needed that there is also a unique constraint on the values. Then this method will
  61. * catch the exception and return 0.
  62. *
  63. * @param string $table The table name (will replace *PREFIX* with the actual prefix)
  64. * @param array $input data that should be inserted into the table (column name => value)
  65. * @param array|null $compare List of values that should be checked for "if not exists"
  66. * If this is null or an empty array, all keys of $input will be compared
  67. * Please note: text fields (clob) must not be used in the compare array
  68. * @return int number of inserted rows
  69. * @throws Exception
  70. * @deprecated 15.0.0 - use unique index and "try { $db->insert() } catch (UniqueConstraintViolationException $e) {}" instead, because it is more reliable and does not have the risk for deadlocks - see https://github.com/nextcloud/server/pull/12371
  71. */
  72. public function insertIfNotExist($table, $input, ?array $compare = null) {
  73. $compare = $compare ?: array_keys($input);
  74. // Prepare column names and generate placeholders
  75. $columns = '`' . implode('`,`', array_keys($input)) . '`';
  76. $placeholders = implode(', ', array_fill(0, count($input), '?'));
  77. $query = 'INSERT INTO `' . $table . '` (' . $columns . ') '
  78. . 'SELECT ' . $placeholders . ' '
  79. . 'FROM `' . $table . '` WHERE ';
  80. $inserts = array_values($input);
  81. foreach ($compare as $key) {
  82. $query .= '`' . $key . '`';
  83. if (is_null($input[$key])) {
  84. $query .= ' IS NULL AND ';
  85. } else {
  86. $inserts[] = $input[$key];
  87. $query .= ' = ? AND ';
  88. }
  89. }
  90. $query = substr($query, 0, -5);
  91. $query .= ' HAVING COUNT(*) = 0';
  92. try {
  93. return $this->conn->executeUpdate($query, $inserts);
  94. } catch (UniqueConstraintViolationException $e) {
  95. // This exception indicates a concurrent insert happened between
  96. // the insert and the sub-select in the insert, which is safe to ignore.
  97. // More details: https://github.com/nextcloud/server/pull/12315
  98. return 0;
  99. }
  100. }
  101. /**
  102. * @throws \OCP\DB\Exception
  103. */
  104. public function insertIgnoreConflict(string $table, array $values) : int {
  105. try {
  106. $builder = $this->conn->getQueryBuilder();
  107. $builder->insert($table);
  108. foreach ($values as $key => $value) {
  109. $builder->setValue($key, $builder->createNamedParameter($value));
  110. }
  111. return $builder->executeStatement();
  112. } catch (DbalException $e) {
  113. if ($e->getReason() === \OCP\DB\Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
  114. return 0;
  115. }
  116. throw $e;
  117. }
  118. }
  119. }