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

namespace Doctrine\DBAL\Id;

use Doctrine\DBAL\Connection;
6
use Doctrine\DBAL\DBALException;
7
use Doctrine\DBAL\Driver;
8
use Doctrine\DBAL\DriverManager;
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
     */
    public function __construct(Connection $conn, $generatorTableName = 'sequences')
    {
73
        if ($conn->getDriver() instanceof Driver\PDOSqlite\Driver) {
74
            throw new DBALException('Cannot use TableGenerator with SQLite.');
75
        }
Grégoire Paris's avatar
Grégoire Paris committed
76

77 78 79 80 81 82
        $this->conn = DriverManager::getConnection(
            $conn->getParams(),
            $conn->getConfiguration(),
            $conn->getEventManager()
        );

83 84 85 86
        $this->generatorTableName = $generatorTableName;
    }

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

104 105 106 107 108 109 110
            return $value;
        }

        $this->conn->beginTransaction();

        try {
            $platform = $this->conn->getDatabasePlatform();
111 112 113
            $sql      = 'SELECT sequence_value, sequence_increment_by'
                . ' FROM ' . $platform->appendLockHint($this->generatorTableName, LockMode::PESSIMISTIC_WRITE)
                . ' WHERE sequence_name = ? ' . $platform->getWriteLockSQL();
114
            $row      = $this->conn->fetchAssociative($sql, [$sequenceName]);
115

116
            if ($row !== false) {
117 118
                $row = array_change_key_case($row, CASE_LOWER);

119 120 121
                $value = $row['sequence_value'];
                $value++;

122 123
                assert(is_int($value));

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

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

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

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

151
            throw new DBALException('Error occurred while generating ID with TableGenerator, aborted generation: ' . $e->getMessage(), 0, $e);
152 153 154 155 156
        }

        return $value;
    }
}