Failed Conditions
Push — master ( 656579...2742cd )
by Marco
11:55
created

TableGenerator::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.4285
ccs 0
cts 8
cp 0
cc 2
eloc 5
nc 2
nop 2
crap 6
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 (sequence_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 <[email protected]>
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 = [];
80
81
    /**
82
     * @param \Doctrine\DBAL\Connection $conn
83
     * @param string                    $generatorTableName
84
     *
85
     * @throws \Doctrine\DBAL\DBALException
86
     */
87
    public function __construct(Connection $conn, $generatorTableName = 'sequences')
88
    {
89
        $params = $conn->getParams();
90
        if ($params['driver'] == 'pdo_sqlite') {
91
            throw new \Doctrine\DBAL\DBALException("Cannot use TableGenerator with SQLite.");
92
        }
93
        $this->conn = DriverManager::getConnection($params, $conn->getConfiguration(), $conn->getEventManager());
94
        $this->generatorTableName = $generatorTableName;
95
    }
96
97
    /**
98
     * Generates the next unused value for the given sequence name.
99
     *
100
     * @param string $sequenceName
101
     *
102
     * @return integer
103
     *
104
     * @throws \Doctrine\DBAL\DBALException
105
     */
106
    public function nextValue($sequenceName)
107
    {
108
        if (isset($this->sequences[$sequenceName])) {
109
            $value = $this->sequences[$sequenceName]['value'];
110
            $this->sequences[$sequenceName]['value']++;
111
            if ($this->sequences[$sequenceName]['value'] >= $this->sequences[$sequenceName]['max']) {
112
                unset ($this->sequences[$sequenceName]);
113
            }
114
115
            return $value;
116
        }
117
118
        $this->conn->beginTransaction();
119
120
        try {
121
            $platform = $this->conn->getDatabasePlatform();
122
            $sql = "SELECT sequence_value, sequence_increment_by " .
123
                   "FROM " . $platform->appendLockHint($this->generatorTableName, \Doctrine\DBAL\LockMode::PESSIMISTIC_WRITE) . " " .
124
                   "WHERE sequence_name = ? " . $platform->getWriteLockSQL();
125
            $stmt = $this->conn->executeQuery($sql, [$sequenceName]);
126
127
            if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
128
                $row = array_change_key_case($row, CASE_LOWER);
129
130
                $value = $row['sequence_value'];
131
                $value++;
132
133
                if ($row['sequence_increment_by'] > 1) {
134
                    $this->sequences[$sequenceName] = [
135
                        'value' => $value,
136
                        'max' => $row['sequence_value'] + $row['sequence_increment_by']
137
                    ];
138
                }
139
140
                $sql = "UPDATE " . $this->generatorTableName . " ".
141
                       "SET sequence_value = sequence_value + sequence_increment_by " .
142
                       "WHERE sequence_name = ? AND sequence_value = ?";
143
                $rows = $this->conn->executeUpdate($sql, [$sequenceName, $row['sequence_value']]);
144
145
                if ($rows != 1) {
146
                    throw new \Doctrine\DBAL\DBALException("Race-condition detected while updating sequence. Aborting generation");
147
                }
148
            } else {
149
                $this->conn->insert(
150
                    $this->generatorTableName,
151
                    ['sequence_name' => $sequenceName, 'sequence_value' => 1, 'sequence_increment_by' => 1]
152
                );
153
                $value = 1;
154
            }
155
156
            $this->conn->commit();
157
158
        } catch (\Exception $e) {
159
            $this->conn->rollBack();
160
            throw new \Doctrine\DBAL\DBALException("Error occurred while generating ID with TableGenerator, aborted generation: " . $e->getMessage(), 0, $e);
161
        }
162
163
        return $value;
164
    }
165
}
166