TableGenerator.php 5.17 KB
Newer Older
1 2 3 4 5
<?php

namespace Doctrine\DBAL\Id;

use Doctrine\DBAL\Connection;
6 7
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\DriverManager;
8
use Doctrine\DBAL\FetchMode;
9
use Doctrine\DBAL\LockMode;
10
use Throwable;
11

12
use function array_change_key_case;
13 14
use function assert;
use function is_int;
15

Grégoire Paris's avatar
Grégoire Paris committed
16
use const CASE_LOWER;
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

/**
 * Table ID Generator for those poor languages that are missing sequences.
 *
 * WARNING: The Table Id Generator clones a second independent database
 * connection to work correctly. This means using the generator requests that
 * generate IDs will have two open database connections. This is necessary to
 * be safe from transaction failures in the main connection. Make sure to only
 * ever use one TableGenerator otherwise you end up with many connections.
 *
 * TableID Generator does not work with SQLite.
 *
 * The TableGenerator does not take care of creating the SQL Table itself. You
 * should look at the `TableGeneratorSchemaVisitor` to do this for you.
 * Otherwise the schema for a table looks like:
 *
 * CREATE sequences (
 *   sequence_name VARCHAR(255) NOT NULL,
35 36 37
 *   sequence_value INT NOT NULL DEFAULT 1,
 *   sequence_increment_by INT NOT NULL DEFAULT 1,
 *   PRIMARY KEY (sequence_name)
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
 * );
 *
 * Technically this generator works as follows:
 *
 * 1. Use a robust transaction serialization level.
 * 2. Open transaction
 * 3. Acquire a read lock on the table row (SELECT .. FOR UPDATE)
 * 4. Increment current value by one and write back to database
 * 5. Commit transaction
 *
 * If you are using a sequence_increment_by value that is larger than one the
 * ID Generator will keep incrementing values until it hits the incrementation
 * gap before issuing another query.
 *
 * If no row is present for a given sequence a new one will be created with the
 * default values 'value' = 1 and 'increment_by' = 1
 */
class TableGenerator
{
57
    /** @var Connection */
58 59
    private $conn;

60
    /** @var string */
61 62
    private $generatorTableName;

63
    /** @var mixed[][] */
64
    private $sequences = [];
65 66

    /**
67
     * @param string $generatorTableName
Benjamin Morel's avatar
Benjamin Morel committed
68
     *
69
     * @throws DBALException
70 71 72 73
     */
    public function __construct(Connection $conn, $generatorTableName = 'sequences')
    {
        $params = $conn->getParams();
74 75
        if ($params['driver'] === 'pdo_sqlite') {
            throw new DBALException('Cannot use TableGenerator with SQLite.');
76
        }
Grégoire Paris's avatar
Grégoire Paris committed
77

Sergei Morozov's avatar
Sergei Morozov committed
78 79
        $this->conn = DriverManager::getConnection($params, $conn->getConfiguration(), $conn->getEventManager());

80 81 82 83
        $this->generatorTableName = $generatorTableName;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
84 85
     * Generates the next unused value for the given sequence name.
     *
86
     * @param string $sequence
Benjamin Morel's avatar
Benjamin Morel committed
87
     *
88
     * @return int
89
     *
90
     * @throws DBALException
91
     */
92
    public function nextValue($sequence)
93
    {
94 95 96 97 98
        if (isset($this->sequences[$sequence])) {
            $value = $this->sequences[$sequence]['value'];
            $this->sequences[$sequence]['value']++;
            if ($this->sequences[$sequence]['value'] >= $this->sequences[$sequence]['max']) {
                unset($this->sequences[$sequence]);
99
            }
Benjamin Morel's avatar
Benjamin Morel committed
100

101 102 103 104 105 106 107
            return $value;
        }

        $this->conn->beginTransaction();

        try {
            $platform = $this->conn->getDatabasePlatform();
108 109 110
            $sql      = 'SELECT sequence_value, sequence_increment_by'
                . ' FROM ' . $platform->appendLockHint($this->generatorTableName, LockMode::PESSIMISTIC_WRITE)
                . ' WHERE sequence_name = ? ' . $platform->getWriteLockSQL();
111
            $stmt     = $this->conn->executeQuery($sql, [$sequence]);
112
            $row      = $stmt->fetch(FetchMode::ASSOCIATIVE);
113

114
            if ($row !== false) {
115 116
                $row = array_change_key_case($row, CASE_LOWER);

117 118 119
                $value = $row['sequence_value'];
                $value++;

120 121
                assert(is_int($value));

122
                if ($row['sequence_increment_by'] > 1) {
123
                    $this->sequences[$sequence] = [
124
                        'value' => $value,
125
                        'max' => $row['sequence_value'] + $row['sequence_increment_by'],
126
                    ];
127 128
                }

129 130 131
                $sql  = 'UPDATE ' . $this->generatorTableName . ' ' .
                       'SET sequence_value = sequence_value + sequence_increment_by ' .
                       'WHERE sequence_name = ? AND sequence_value = ?';
132
                $rows = $this->conn->executeUpdate($sql, [$sequence, $row['sequence_value']]);
133

134 135
                if ($rows !== 1) {
                    throw new DBALException('Race-condition detected while updating sequence. Aborting generation');
136 137 138 139
                }
            } else {
                $this->conn->insert(
                    $this->generatorTableName,
140
                    ['sequence_name' => $sequence, 'sequence_value' => 1, 'sequence_increment_by' => 1]
141 142 143 144 145
                );
                $value = 1;
            }

            $this->conn->commit();
146
        } catch (Throwable $e) {
147
            $this->conn->rollBack();
Grégoire Paris's avatar
Grégoire Paris committed
148

Sergei Morozov's avatar
Sergei Morozov committed
149 150 151 152 153
            throw new DBALException(
                'Error occurred while generating ID with TableGenerator, aborted generation: ' . $e->getMessage(),
                0,
                $e
            );
154 155 156 157 158
        }

        return $value;
    }
}