Failed Conditions
Push — drop-deprecated ( d77510...d983c4 )
by Michael
40:59 queued 38:23
created

TableGenerator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 93
Duplicated Lines 0 %

Test Coverage

Coverage 72.09%

Importance

Changes 0
Metric Value
wmc 9
eloc 46
dl 0
loc 93
ccs 31
cts 43
cp 0.7209
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B nextValue() 0 58 7
A __construct() 0 8 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Id;
6
7
use Doctrine\DBAL\Connection;
8
use Doctrine\DBAL\DBALException;
9
use Doctrine\DBAL\DriverManager;
10
use Doctrine\DBAL\FetchMode;
11
use Doctrine\DBAL\LockMode;
12
use Throwable;
13
use const CASE_LOWER;
14
use function array_change_key_case;
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
                if ($row['sequence_increment_by'] > 1) {
117
                    $this->sequences[$sequenceName] = [
118
                        'value' => $value,
119
                        'max' => $row['sequence_value'] + $row['sequence_increment_by'],
120
                    ];
121
                }
122
123 46
                $sql  = 'UPDATE ' . $this->generatorTableName . ' ' .
124 46
                       'SET sequence_value = sequence_value + sequence_increment_by ' .
125 46
                       'WHERE sequence_name = ? AND sequence_value = ?';
126 46
                $rows = $this->conn->executeUpdate($sql, [$sequenceName, $row['sequence_value']]);
127
128 46
                if ($rows !== 1) {
129 46
                    throw new DBALException('Race-condition detected while updating sequence. Aborting generation');
130
                }
131
            } else {
132 46
                $this->conn->insert(
133 46
                    $this->generatorTableName,
134 46
                    ['sequence_name' => $sequenceName, 'sequence_value' => 1, 'sequence_increment_by' => 1]
135
                );
136 46
                $value = 1;
137
            }
138
139 46
            $this->conn->commit();
140
        } catch (Throwable $e) {
141
            $this->conn->rollBack();
142
            throw new DBALException('Error occurred while generating ID with TableGenerator, aborted generation: ' . $e->getMessage(), 0, $e);
143
        }
144
145 46
        return $value;
146
    }
147
}
148