TableGenerator.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the MIT license. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\DBAL\Id;
  20. use Doctrine\DBAL\DriverManager;
  21. use Doctrine\DBAL\Connection;
  22. /**
  23. * Table ID Generator for those poor languages that are missing sequences.
  24. *
  25. * WARNING: The Table Id Generator clones a second independent database
  26. * connection to work correctly. This means using the generator requests that
  27. * generate IDs will have two open database connections. This is necessary to
  28. * be safe from transaction failures in the main connection. Make sure to only
  29. * ever use one TableGenerator otherwise you end up with many connections.
  30. *
  31. * TableID Generator does not work with SQLite.
  32. *
  33. * The TableGenerator does not take care of creating the SQL Table itself. You
  34. * should look at the `TableGeneratorSchemaVisitor` to do this for you.
  35. * Otherwise the schema for a table looks like:
  36. *
  37. * CREATE sequences (
  38. * sequence_name VARCHAR(255) NOT NULL,
  39. * sequence_value INT NOT NULL DEFAULT '1',
  40. * sequence_increment_by INT NOT NULL DEFAULT '1',
  41. * PRIMARY KEY (table_name)
  42. * );
  43. *
  44. * Technically this generator works as follows:
  45. *
  46. * 1. Use a robust transaction serialization level.
  47. * 2. Open transaction
  48. * 3. Acquire a read lock on the table row (SELECT .. FOR UPDATE)
  49. * 4. Increment current value by one and write back to database
  50. * 5. Commit transaction
  51. *
  52. * If you are using a sequence_increment_by value that is larger than one the
  53. * ID Generator will keep incrementing values until it hits the incrementation
  54. * gap before issuing another query.
  55. *
  56. * If no row is present for a given sequence a new one will be created with the
  57. * default values 'value' = 1 and 'increment_by' = 1
  58. *
  59. * @author Benjamin Eberlei <kontakt@beberlei.de>
  60. */
  61. class TableGenerator
  62. {
  63. /**
  64. * @var \Doctrine\DBAL\Connection
  65. */
  66. private $conn;
  67. /**
  68. * @var string
  69. */
  70. private $generatorTableName;
  71. /**
  72. * @var array
  73. */
  74. private $sequences = array();
  75. /**
  76. * @param \Doctrine\DBAL\Connection $conn
  77. * @param string $generatorTableName
  78. *
  79. * @throws \Doctrine\DBAL\DBALException
  80. */
  81. public function __construct(Connection $conn, $generatorTableName = 'sequences')
  82. {
  83. $params = $conn->getParams();
  84. if ($params['driver'] == 'pdo_sqlite') {
  85. throw new \Doctrine\DBAL\DBALException("Cannot use TableGenerator with SQLite.");
  86. }
  87. $this->conn = DriverManager::getConnection($params, $conn->getConfiguration(), $conn->getEventManager());
  88. $this->generatorTableName = $generatorTableName;
  89. }
  90. /**
  91. * Generates the next unused value for the given sequence name.
  92. *
  93. * @param string $sequenceName
  94. *
  95. * @return integer
  96. *
  97. * @throws \Doctrine\DBAL\DBALException
  98. */
  99. public function nextValue($sequenceName)
  100. {
  101. if (isset($this->sequences[$sequenceName])) {
  102. $value = $this->sequences[$sequenceName]['value'];
  103. $this->sequences[$sequenceName]['value']++;
  104. if ($this->sequences[$sequenceName]['value'] >= $this->sequences[$sequenceName]['max']) {
  105. unset ($this->sequences[$sequenceName]);
  106. }
  107. return $value;
  108. }
  109. $this->conn->beginTransaction();
  110. try {
  111. $platform = $this->conn->getDatabasePlatform();
  112. $sql = "SELECT sequence_value, sequence_increment_by " .
  113. "FROM " . $platform->appendLockHint($this->generatorTableName, \Doctrine\DBAL\LockMode::PESSIMISTIC_WRITE) . " " .
  114. "WHERE sequence_name = ? " . $platform->getWriteLockSQL();
  115. $stmt = $this->conn->executeQuery($sql, array($sequenceName));
  116. if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  117. $row = array_change_key_case($row, CASE_LOWER);
  118. $value = $row['sequence_value'];
  119. $value++;
  120. if ($row['sequence_increment_by'] > 1) {
  121. $this->sequences[$sequenceName] = array(
  122. 'value' => $value,
  123. 'max' => $row['sequence_value'] + $row['sequence_increment_by']
  124. );
  125. }
  126. $sql = "UPDATE " . $this->generatorTableName . " ".
  127. "SET sequence_value = sequence_value + sequence_increment_by " .
  128. "WHERE sequence_name = ? AND sequence_value = ?";
  129. $rows = $this->conn->executeUpdate($sql, array($sequenceName, $row['sequence_value']));
  130. if ($rows != 1) {
  131. throw new \Doctrine\DBAL\DBALException("Race-condition detected while updating sequence. Aborting generation");
  132. }
  133. } else {
  134. $this->conn->insert(
  135. $this->generatorTableName,
  136. array('sequence_name' => $sequenceName, 'sequence_value' => 1, 'sequence_increment_by' => 1)
  137. );
  138. $value = 1;
  139. }
  140. $this->conn->commit();
  141. } catch(\Exception $e) {
  142. $this->conn->rollback();
  143. throw new \Doctrine\DBAL\DBALException("Error occurred while generating ID with TableGenerator, aborted generation: " . $e->getMessage(), 0, $e);
  144. }
  145. return $value;
  146. }
  147. }