Passed
Pull Request — 2.11.x (#3971)
by Grégoire
03:18
created

TableGenerator::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.2109

Importance

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