Completed
Push — 2.10.x ( 61a6b9...f20ba1 )
by Grégoire
13:37 queued 11s
created

TableGenerator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 97
Duplicated Lines 0 %

Test Coverage

Coverage 55.17%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
eloc 47
dl 0
loc 97
ccs 32
cts 58
cp 0.5517
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B nextValue() 0 61 7
A __construct() 0 9 2
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 function array_change_key_case;
12
use function assert;
13
use function is_int;
14
use const CASE_LOWER;
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
76 46
        $this->conn               = DriverManager::getConnection($params, $conn->getConfiguration(), $conn->getEventManager());
77 46
        $this->generatorTableName = $generatorTableName;
78 46
    }
79
80
    /**
81
     * Generates the next unused value for the given sequence name.
82
     *
83
     * @param string $sequenceName
84
     *
85
     * @return int
86
     *
87
     * @throws DBALException
88
     */
89 46
    public function nextValue($sequenceName)
90
    {
91 46
        if (isset($this->sequences[$sequenceName])) {
92
            $value = $this->sequences[$sequenceName]['value'];
93
            $this->sequences[$sequenceName]['value']++;
94
            if ($this->sequences[$sequenceName]['value'] >= $this->sequences[$sequenceName]['max']) {
95
                unset($this->sequences[$sequenceName]);
96
            }
97
98
            return $value;
99
        }
100
101 46
        $this->conn->beginTransaction();
102
103
        try {
104 46
            $platform = $this->conn->getDatabasePlatform();
105
            $sql      = 'SELECT sequence_value, sequence_increment_by'
106 46
                . ' FROM ' . $platform->appendLockHint($this->generatorTableName, LockMode::PESSIMISTIC_WRITE)
107 46
                . ' WHERE sequence_name = ? ' . $platform->getWriteLockSQL();
108 46
            $stmt     = $this->conn->executeQuery($sql, [$sequenceName]);
109 46
            $row      = $stmt->fetch(FetchMode::ASSOCIATIVE);
110
111 46
            if ($row !== false) {
112 46
                $row = array_change_key_case($row, CASE_LOWER);
113
114 46
                $value = $row['sequence_value'];
115 46
                $value++;
116
117 46
                assert(is_int($value));
118
119 46
                if ($row['sequence_increment_by'] > 1) {
120
                    $this->sequences[$sequenceName] = [
121
                        'value' => $value,
122
                        'max' => $row['sequence_value'] + $row['sequence_increment_by'],
123
                    ];
124
                }
125
126 46
                $sql  = 'UPDATE ' . $this->generatorTableName . ' ' .
127 46
                       'SET sequence_value = sequence_value + sequence_increment_by ' .
128 46
                       'WHERE sequence_name = ? AND sequence_value = ?';
129 46
                $rows = $this->conn->executeUpdate($sql, [$sequenceName, $row['sequence_value']]);
130
131 46
                if ($rows !== 1) {
132 46
                    throw new DBALException('Race-condition detected while updating sequence. Aborting generation');
133
                }
134
            } else {
135 45
                $this->conn->insert(
136 45
                    $this->generatorTableName,
137 45
                    ['sequence_name' => $sequenceName, 'sequence_value' => 1, 'sequence_increment_by' => 1]
138
                );
139 45
                $value = 1;
140
            }
141
142 46
            $this->conn->commit();
143
        } catch (Throwable $e) {
144
            $this->conn->rollBack();
145
146
            throw new DBALException('Error occurred while generating ID with TableGenerator, aborted generation: ' . $e->getMessage(), 0, $e);
147
        }
148
149 46
        return $value;
150
    }
151
}
152