Rajout de doctrine/orm
[zf2.biz/galerie.git] / vendor / doctrine / dbal / lib / Doctrine / DBAL / Id / TableGenerator.php
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
20 namespace Doctrine\DBAL\Id;
21
22 use Doctrine\DBAL\DriverManager;
23 use Doctrine\DBAL\Connection;
24
25 /**
26  * Table ID Generator for those poor languages that are missing sequences.
27  *
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.
33  *
34  * TableID Generator does not work with SQLite.
35  *
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:
39  *
40  * CREATE sequences (
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)
45  * );
46  *
47  * Technically this generator works as follows:
48  *
49  * 1. Use a robust transaction serialization level.
50  * 2. Open transaction
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
54  *
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.
58  *
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
61  *
62  * @author Benjamin Eberlei <kontakt@beberlei.de>
63  */
64 class TableGenerator
65 {
66     /**
67      * @var \Doctrine\DBAL\Connection
68      */
69     private $conn;
70
71     /**
72      * @var string
73      */
74     private $generatorTableName;
75
76     /**
77      * @var array
78      */
79     private $sequences = array();
80
81     /**
82      * @param Connection $conn
83      * @param string $generatorTableName
84      */
85     public function __construct(Connection $conn, $generatorTableName = 'sequences')
86     {
87         $params = $conn->getParams();
88         if ($params['driver'] == 'pdo_sqlite') {
89             throw new \Doctrine\DBAL\DBALException("Cannot use TableGenerator with SQLite.");
90         }
91         $this->conn = DriverManager::getConnection($params, $conn->getConfiguration(), $conn->getEventManager());
92         $this->generatorTableName = $generatorTableName;
93     }
94
95     /**
96      * Generate the next unused value for the given sequence name
97      *
98      * @param string
99      * @return int
100      */
101     public function nextValue($sequenceName)
102     {
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]);
108             }
109             return $value;
110         }
111
112         $this->conn->beginTransaction();
113
114         try {
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));
120
121             if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
122                 $row = array_change_key_case($row, CASE_LOWER);
123
124                 $value = $row['sequence_value'];
125                 $value++;
126
127                 if ($row['sequence_increment_by'] > 1) {
128                     $this->sequences[$sequenceName] = array(
129                         'value' => $value,
130                         'max' => $row['sequence_value'] + $row['sequence_increment_by']
131                     );
132                 }
133
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']));
138
139                 if ($rows != 1) {
140                     throw new \Doctrine\DBAL\DBALException("Race-condition detected while updating sequence. Aborting generation");
141                 }
142             } else {
143                 $this->conn->insert(
144                     $this->generatorTableName,
145                     array('sequence_name' => $sequenceName, 'sequence_value' => 1, 'sequence_increment_by' => 1)
146                 );
147                 $value = 1;
148             }
149
150             $this->conn->commit();
151
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);
155         }
156
157         return $value;
158     }
159 }
160