Adapter.php 3.9 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. * @param string $tableName
  43. * @throws Exception
  44. * @since 9.1.0
  45. */
  46. public function lockTable($tableName) {
  47. $this->conn->beginTransaction();
  48. $this->conn->executeUpdate('LOCK TABLE `' .$tableName . '` IN EXCLUSIVE MODE');
  49. }
  50. /**
  51. * Release a previous acquired lock again
  52. *
  53. * @throws Exception
  54. * @since 9.1.0
  55. */
  56. public function unlockTable() {
  57. $this->conn->commit();
  58. }
  59. /**
  60. * Insert a row if the matching row does not exists. To accomplish proper race condition avoidance
  61. * it is needed that there is also a unique constraint on the values. Then this method will
  62. * catch the exception and return 0.
  63. *
  64. * @param string $table The table name (will replace *PREFIX* with the actual prefix)
  65. * @param array $input data that should be inserted into the table (column name => value)
  66. * @param array|null $compare List of values that should be checked for "if not exists"
  67. * If this is null or an empty array, all keys of $input will be compared
  68. * Please note: text fields (clob) must not be used in the compare array
  69. * @return int number of inserted rows
  70. * @throws Exception
  71. * @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
  72. */
  73. public function insertIfNotExist($table, $input, ?array $compare = null) {
  74. if (empty($compare)) {
  75. $compare = array_keys($input);
  76. }
  77. $query = 'INSERT INTO `' .$table . '` (`'
  78. . implode('`,`', array_keys($input)) . '`) SELECT '
  79. . str_repeat('?,', count($input) - 1).'? ' // Is there a prettier alternative?
  80. . 'FROM `' . $table . '` WHERE ';
  81. $inserts = array_values($input);
  82. foreach ($compare as $key) {
  83. $query .= '`' . $key . '`';
  84. if (is_null($input[$key])) {
  85. $query .= ' IS NULL AND ';
  86. } else {
  87. $inserts[] = $input[$key];
  88. $query .= ' = ? AND ';
  89. }
  90. }
  91. $query = substr($query, 0, -5);
  92. $query .= ' HAVING COUNT(*) = 0';
  93. try {
  94. return $this->conn->executeUpdate($query, $inserts);
  95. } catch (UniqueConstraintViolationException $e) {
  96. // if this is thrown then a concurrent insert happened between the insert and the sub-select in the insert, that should have avoided it
  97. // it's fine to ignore this then
  98. //
  99. // more discussions about this can be found at https://github.com/nextcloud/server/pull/12315
  100. return 0;
  101. }
  102. }
  103. /**
  104. * @throws \OCP\DB\Exception
  105. */
  106. public function insertIgnoreConflict(string $table, array $values) : int {
  107. try {
  108. $builder = $this->conn->getQueryBuilder();
  109. $builder->insert($table);
  110. foreach ($values as $key => $value) {
  111. $builder->setValue($key, $builder->createNamedParameter($value));
  112. }
  113. return $builder->executeStatement();
  114. } catch (DbalException $e) {
  115. if ($e->getReason() === \OCP\DB\Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
  116. return 0;
  117. }
  118. throw $e;
  119. }
  120. }
  121. }