Adapter.php 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Jonny007-MKD <1-23-4-5@web.de>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Ole Ostergaard <ole.c.ostergaard@gmail.com>
  11. * @author Ole Ostergaard <ole.ostergaard@knime.com>
  12. * @author Robin Appelman <robin@icewind.nl>
  13. *
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. namespace OC\DB;
  30. use Doctrine\DBAL\Exception;
  31. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  32. use OC\DB\Exceptions\DbalException;
  33. /**
  34. * This handles the way we use to write queries, into something that can be
  35. * handled by the database abstraction layer.
  36. */
  37. class Adapter {
  38. /**
  39. * @var \OC\DB\Connection $conn
  40. */
  41. protected $conn;
  42. public function __construct($conn) {
  43. $this->conn = $conn;
  44. }
  45. /**
  46. * @param string $table name
  47. *
  48. * @return int id of last insert statement
  49. * @throws Exception
  50. */
  51. public function lastInsertId($table) {
  52. return (int) $this->conn->realLastInsertId($table);
  53. }
  54. /**
  55. * @param string $statement that needs to be changed so the db can handle it
  56. * @return string changed statement
  57. */
  58. public function fixupStatement($statement) {
  59. return $statement;
  60. }
  61. /**
  62. * Create an exclusive read+write lock on a table
  63. *
  64. * @param string $tableName
  65. * @throws Exception
  66. * @since 9.1.0
  67. */
  68. public function lockTable($tableName) {
  69. $this->conn->beginTransaction();
  70. $this->conn->executeUpdate('LOCK TABLE `' .$tableName . '` IN EXCLUSIVE MODE');
  71. }
  72. /**
  73. * Release a previous acquired lock again
  74. *
  75. * @throws Exception
  76. * @since 9.1.0
  77. */
  78. public function unlockTable() {
  79. $this->conn->commit();
  80. }
  81. /**
  82. * Insert a row if the matching row does not exists. To accomplish proper race condition avoidance
  83. * it is needed that there is also a unique constraint on the values. Then this method will
  84. * catch the exception and return 0.
  85. *
  86. * @param string $table The table name (will replace *PREFIX* with the actual prefix)
  87. * @param array $input data that should be inserted into the table (column name => value)
  88. * @param array|null $compare List of values that should be checked for "if not exists"
  89. * If this is null or an empty array, all keys of $input will be compared
  90. * Please note: text fields (clob) must not be used in the compare array
  91. * @return int number of inserted rows
  92. * @throws Exception
  93. * @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
  94. */
  95. public function insertIfNotExist($table, $input, array $compare = null) {
  96. if (empty($compare)) {
  97. $compare = array_keys($input);
  98. }
  99. $query = 'INSERT INTO `' .$table . '` (`'
  100. . implode('`,`', array_keys($input)) . '`) SELECT '
  101. . str_repeat('?,', count($input) - 1).'? ' // Is there a prettier alternative?
  102. . 'FROM `' . $table . '` WHERE ';
  103. $inserts = array_values($input);
  104. foreach ($compare as $key) {
  105. $query .= '`' . $key . '`';
  106. if (is_null($input[$key])) {
  107. $query .= ' IS NULL AND ';
  108. } else {
  109. $inserts[] = $input[$key];
  110. $query .= ' = ? AND ';
  111. }
  112. }
  113. $query = substr($query, 0, -5);
  114. $query .= ' HAVING COUNT(*) = 0';
  115. try {
  116. return $this->conn->executeUpdate($query, $inserts);
  117. } catch (UniqueConstraintViolationException $e) {
  118. // if this is thrown then a concurrent insert happened between the insert and the sub-select in the insert, that should have avoided it
  119. // it's fine to ignore this then
  120. //
  121. // more discussions about this can be found at https://github.com/nextcloud/server/pull/12315
  122. return 0;
  123. }
  124. }
  125. /**
  126. * @throws \OCP\DB\Exception
  127. */
  128. public function insertIgnoreConflict(string $table, array $values) : int {
  129. try {
  130. $builder = $this->conn->getQueryBuilder();
  131. $builder->insert($table);
  132. foreach ($values as $key => $value) {
  133. $builder->setValue($key, $builder->createNamedParameter($value));
  134. }
  135. return $builder->executeStatement();
  136. } catch (DbalException $e) {
  137. if ($e->getReason() === \OCP\DB\Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
  138. return 0;
  139. }
  140. throw $e;
  141. }
  142. }
  143. }