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