Completed
Pull Request — master (#3212)
by Sergei
49:12 queued 45:02
created

TableGenerator::nextValue()   B

Complexity

Conditions 7
Paths 21

Size

Total Lines 59
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 8.3984

Importance

Changes 0
Metric Value
eloc 38
dl 0
loc 59
rs 8.3786
c 0
b 0
f 0
ccs 25
cts 36
cp 0.6944
cc 7
nc 21
nop 1
crap 8.3984

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
use Doctrine\DBAL\FetchMode;
25
use Doctrine\DBAL\LockMode;
26
use const CASE_LOWER;
27
use function array_change_key_case;
28
29
/**
30
 * Table ID Generator for those poor languages that are missing sequences.
31
 *
32
 * WARNING: The Table Id Generator clones a second independent database
33
 * connection to work correctly. This means using the generator requests that
34
 * generate IDs will have two open database connections. This is necessary to
35
 * be safe from transaction failures in the main connection. Make sure to only
36
 * ever use one TableGenerator otherwise you end up with many connections.
37
 *
38
 * TableID Generator does not work with SQLite.
39
 *
40
 * The TableGenerator does not take care of creating the SQL Table itself. You
41
 * should look at the `TableGeneratorSchemaVisitor` to do this for you.
42
 * Otherwise the schema for a table looks like:
43
 *
44
 * CREATE sequences (
45
 *   sequence_name VARCHAR(255) NOT NULL,
46
 *   sequence_value INT NOT NULL DEFAULT 1,
47
 *   sequence_increment_by INT NOT NULL DEFAULT 1,
48
 *   PRIMARY KEY (sequence_name)
49
 * );
50
 *
51
 * Technically this generator works as follows:
52
 *
53
 * 1. Use a robust transaction serialization level.
54
 * 2. Open transaction
55
 * 3. Acquire a read lock on the table row (SELECT .. FOR UPDATE)
56
 * 4. Increment current value by one and write back to database
57
 * 5. Commit transaction
58
 *
59
 * If you are using a sequence_increment_by value that is larger than one the
60
 * ID Generator will keep incrementing values until it hits the incrementation
61
 * gap before issuing another query.
62
 *
63
 * If no row is present for a given sequence a new one will be created with the
64
 * default values 'value' = 1 and 'increment_by' = 1
65
 *
66
 * @author Benjamin Eberlei <[email protected]>
67
 */
68
class TableGenerator
69
{
70
    /**
71
     * @var \Doctrine\DBAL\Connection
72
     */
73
    private $conn;
74
75
    /**
76
     * @var string
77
     */
78
    private $generatorTableName;
79
80
    /**
81
     * @var array
82
     */
83
    private $sequences = [];
84
85
    /**
86
     * @param \Doctrine\DBAL\Connection $conn
87
     * @param string                    $generatorTableName
88
     *
89
     * @throws \Doctrine\DBAL\DBALException
90
     */
91 36
    public function __construct(Connection $conn, $generatorTableName = 'sequences')
92
    {
93 36
        $params = $conn->getParams();
94 36
        if ($params['driver'] == 'pdo_sqlite') {
95
            throw new \Doctrine\DBAL\DBALException("Cannot use TableGenerator with SQLite.");
96
        }
97 36
        $this->conn = DriverManager::getConnection($params, $conn->getConfiguration(), $conn->getEventManager());
98 36
        $this->generatorTableName = $generatorTableName;
99 36
    }
100
101
    /**
102
     * Generates the next unused value for the given sequence name.
103
     *
104
     * @param string $sequenceName
105
     *
106
     * @return int
107
     *
108
     * @throws \Doctrine\DBAL\DBALException
109
     */
110 36
    public function nextValue($sequenceName)
111
    {
112 36
        if (isset($this->sequences[$sequenceName])) {
113
            $value = $this->sequences[$sequenceName]['value'];
114
            $this->sequences[$sequenceName]['value']++;
115
            if ($this->sequences[$sequenceName]['value'] >= $this->sequences[$sequenceName]['max']) {
116
                unset ($this->sequences[$sequenceName]);
117
            }
118
119
            return $value;
120
        }
121
122 36
        $this->conn->beginTransaction();
123
124
        try {
125 36
            $platform = $this->conn->getDatabasePlatform();
126
            $sql      = 'SELECT sequence_value, sequence_increment_by'
127 36
                . ' FROM ' . $platform->appendLockHint($this->generatorTableName, LockMode::PESSIMISTIC_WRITE)
128 36
                . ' WHERE sequence_name = ? ' . $platform->getWriteLockSQL();
129 36
            $stmt     = $this->conn->executeQuery($sql, [$sequenceName]);
130 36
            $row      = $stmt->fetch(FetchMode::ASSOCIATIVE);
131
132 36
            if ($row !== false) {
133 36
                $row = array_change_key_case($row, CASE_LOWER);
134
135 36
                $value = $row['sequence_value'];
136 36
                $value++;
137
138 36
                if ($row['sequence_increment_by'] > 1) {
139
                    $this->sequences[$sequenceName] = [
140
                        'value' => $value,
141
                        'max' => $row['sequence_value'] + $row['sequence_increment_by']
142
                    ];
143
                }
144
145 36
                $sql = "UPDATE " . $this->generatorTableName . " ".
146 36
                       "SET sequence_value = sequence_value + sequence_increment_by " .
147 36
                       "WHERE sequence_name = ? AND sequence_value = ?";
148 36
                $rows = $this->conn->executeUpdate($sql, [$sequenceName, $row['sequence_value']]);
149
150 36
                if ($rows != 1) {
151 36
                    throw new \Doctrine\DBAL\DBALException("Race-condition detected while updating sequence. Aborting generation");
152
                }
153
            } else {
154 18
                $this->conn->insert(
155 18
                    $this->generatorTableName,
156 18
                    ['sequence_name' => $sequenceName, 'sequence_value' => 1, 'sequence_increment_by' => 1]
157
                );
158 18
                $value = 1;
159
            }
160
161 36
            $this->conn->commit();
162
163
        } catch (\Exception $e) {
164
            $this->conn->rollBack();
165
            throw new \Doctrine\DBAL\DBALException("Error occurred while generating ID with TableGenerator, aborted generation: " . $e->getMessage(), 0, $e);
166
        }
167
168 36
        return $value;
169
    }
170
}
171