TableGenerator.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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 Connection $conn
  77. * @param string $generatorTableName
  78. */
  79. public function __construct(Connection $conn, $generatorTableName = 'sequences')
  80. {
  81. $params = $conn->getParams();
  82. if ($params['driver'] == 'pdo_sqlite') {
  83. throw new \Doctrine\DBAL\DBALException("Cannot use TableGenerator with SQLite.");
  84. }
  85. $this->conn = DriverManager::getConnection($params, $conn->getConfiguration(), $conn->getEventManager());
  86. $this->generatorTableName = $generatorTableName;
  87. }
  88. /**
  89. * Generate the next unused value for the given sequence name
  90. *
  91. * @param string
  92. * @return int
  93. */
  94. public function nextValue($sequenceName)
  95. {
  96. if (isset($this->sequences[$sequenceName])) {
  97. $value = $this->sequences[$sequenceName]['value'];
  98. $this->sequences[$sequenceName]['value']++;
  99. if ($this->sequences[$sequenceName]['value'] >= $this->sequences[$sequenceName]['max']) {
  100. unset ($this->sequences[$sequenceName]);
  101. }
  102. return $value;
  103. }
  104. $this->conn->beginTransaction();
  105. try {
  106. $platform = $this->conn->getDatabasePlatform();
  107. $sql = "SELECT sequence_value, sequence_increment_by " .
  108. "FROM " . $platform->appendLockHint($this->generatorTableName, \Doctrine\DBAL\LockMode::PESSIMISTIC_WRITE) . " " .
  109. "WHERE sequence_name = ? " . $platform->getWriteLockSQL();
  110. $stmt = $this->conn->executeQuery($sql, array($sequenceName));
  111. if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  112. $row = array_change_key_case($row, CASE_LOWER);
  113. $value = $row['sequence_value'];
  114. $value++;
  115. if ($row['sequence_increment_by'] > 1) {
  116. $this->sequences[$sequenceName] = array(
  117. 'value' => $value,
  118. 'max' => $row['sequence_value'] + $row['sequence_increment_by']
  119. );
  120. }
  121. $sql = "UPDATE " . $this->generatorTableName . " ".
  122. "SET sequence_value = sequence_value + sequence_increment_by " .
  123. "WHERE sequence_name = ? AND sequence_value = ?";
  124. $rows = $this->conn->executeUpdate($sql, array($sequenceName, $row['sequence_value']));
  125. if ($rows != 1) {
  126. throw new \Doctrine\DBAL\DBALException("Race-condition detected while updating sequence. Aborting generation");
  127. }
  128. } else {
  129. $this->conn->insert(
  130. $this->generatorTableName,
  131. array('sequence_name' => $sequenceName, 'sequence_value' => 1, 'sequence_increment_by' => 1)
  132. );
  133. $value = 1;
  134. }
  135. $this->conn->commit();
  136. } catch(\Exception $e) {
  137. $this->conn->rollback();
  138. throw new \Doctrine\DBAL\DBALException("Error occured while generating ID with TableGenerator, aborted generation: " . $e->getMessage(), 0, $e);
  139. }
  140. return $value;
  141. }
  142. }