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.
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>.
20 namespace Doctrine\DBAL\Id;
22 use Doctrine\DBAL\DriverManager;
23 use Doctrine\DBAL\Connection;
26 * Table ID Generator for those poor languages that are missing sequences.
28 * WARNING: The Table Id Generator clones a second independent database
29 * connection to work correctly. This means using the generator requests that
30 * generate IDs will have two open database connections. This is necessary to
31 * be safe from transaction failures in the main connection. Make sure to only
32 * ever use one TableGenerator otherwise you end up with many connections.
34 * TableID Generator does not work with SQLite.
36 * The TableGenerator does not take care of creating the SQL Table itself. You
37 * should look at the `TableGeneratorSchemaVisitor` to do this for you.
38 * Otherwise the schema for a table looks like:
41 * sequence_name VARCHAR(255) NOT NULL,
42 * sequence_value INT NOT NULL DEFAULT '1',
43 * sequence_increment_by INT NOT NULL DEFAULT '1',
44 * PRIMARY KEY (table_name)
47 * Technically this generator works as follows:
49 * 1. Use a robust transaction serialization level.
51 * 3. Acquire a read lock on the table row (SELECT .. FOR UPDATE)
52 * 4. Increment current value by one and write back to database
53 * 5. Commit transaction
55 * If you are using a sequence_increment_by value that is larger than one the
56 * ID Generator will keep incrementing values until it hits the incrementation
57 * gap before issuing another query.
59 * If no row is present for a given sequence a new one will be created with the
60 * default values 'value' = 1 and 'increment_by' = 1
62 * @author Benjamin Eberlei <kontakt@beberlei.de>
67 * @var \Doctrine\DBAL\Connection
74 private $generatorTableName;
79 private $sequences = array();
82 * @param Connection $conn
83 * @param string $generatorTableName
85 public function __construct(Connection $conn, $generatorTableName = 'sequences')
87 $params = $conn->getParams();
88 if ($params['driver'] == 'pdo_sqlite') {
89 throw new \Doctrine\DBAL\DBALException("Cannot use TableGenerator with SQLite.");
91 $this->conn = DriverManager::getConnection($params, $conn->getConfiguration(), $conn->getEventManager());
92 $this->generatorTableName = $generatorTableName;
96 * Generate the next unused value for the given sequence name
101 public function nextValue($sequenceName)
103 if (isset($this->sequences[$sequenceName])) {
104 $value = $this->sequences[$sequenceName]['value'];
105 $this->sequences[$sequenceName]['value']++;
106 if ($this->sequences[$sequenceName]['value'] >= $this->sequences[$sequenceName]['max']) {
107 unset ($this->sequences[$sequenceName]);
112 $this->conn->beginTransaction();
115 $platform = $this->conn->getDatabasePlatform();
116 $sql = "SELECT sequence_value, sequence_increment_by " .
117 "FROM " . $platform->appendLockHint($this->generatorTableName, \Doctrine\DBAL\LockMode::PESSIMISTIC_WRITE) . " " .
118 "WHERE sequence_name = ? " . $platform->getWriteLockSQL();
119 $stmt = $this->conn->executeQuery($sql, array($sequenceName));
121 if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
122 $row = array_change_key_case($row, CASE_LOWER);
124 $value = $row['sequence_value'];
127 if ($row['sequence_increment_by'] > 1) {
128 $this->sequences[$sequenceName] = array(
130 'max' => $row['sequence_value'] + $row['sequence_increment_by']
134 $sql = "UPDATE " . $this->generatorTableName . " ".
135 "SET sequence_value = sequence_value + sequence_increment_by " .
136 "WHERE sequence_name = ? AND sequence_value = ?";
137 $rows = $this->conn->executeUpdate($sql, array($sequenceName, $row['sequence_value']));
140 throw new \Doctrine\DBAL\DBALException("Race-condition detected while updating sequence. Aborting generation");
144 $this->generatorTableName,
145 array('sequence_name' => $sequenceName, 'sequence_value' => 1, 'sequence_increment_by' => 1)
150 $this->conn->commit();
152 } catch(\Exception $e) {
153 $this->conn->rollback();
154 throw new \Doctrine\DBAL\DBALException("Error occured while generating ID with TableGenerator, aborted generation: " . $e->getMessage(), 0, $e);