TableGenerator.php 5.08 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\LockMode;
9
use Throwable;
10

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

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

/**
 * 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,
34 35 36
 *   sequence_value INT NOT NULL DEFAULT 1,
 *   sequence_increment_by INT NOT NULL DEFAULT 1,
 *   PRIMARY KEY (sequence_name)
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
 * );
 *
 * 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
{
56
    /** @var Connection */
57 58
    private $conn;

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

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

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

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

    /**
Benjamin Morel's avatar
Benjamin Morel committed
82 83 84 85
     * Generates the next unused value for the given sequence name.
     *
     * @param string $sequenceName
     *
86
     * @return int
87
     *
88
     * @throws DBALException
89 90 91 92 93 94 95
     */
    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']) {
96
                unset($this->sequences[$sequenceName]);
97
            }
Benjamin Morel's avatar
Benjamin Morel committed
98

99 100 101 102 103 104 105
            return $value;
        }

        $this->conn->beginTransaction();

        try {
            $platform = $this->conn->getDatabasePlatform();
106 107 108
            $sql      = 'SELECT sequence_value, sequence_increment_by'
                . ' FROM ' . $platform->appendLockHint($this->generatorTableName, LockMode::PESSIMISTIC_WRITE)
                . ' WHERE sequence_name = ? ' . $platform->getWriteLockSQL();
109
            $row      = $this->conn->fetchAssociative($sql, [$sequenceName]);
110

111
            if ($row !== false) {
112 113
                $row = array_change_key_case($row, CASE_LOWER);

114 115 116
                $value = $row['sequence_value'];
                $value++;

117 118
                assert(is_int($value));

119
                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 127 128
                $sql  = 'UPDATE ' . $this->generatorTableName . ' ' .
                       'SET sequence_value = sequence_value + sequence_increment_by ' .
                       'WHERE sequence_name = ? AND sequence_value = ?';
129
                $rows = $this->conn->executeUpdate($sql, [$sequenceName, $row['sequence_value']]);
130

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

            $this->conn->commit();
143
        } catch (Throwable $e) {
144
            $this->conn->rollBack();
Grégoire Paris's avatar
Grégoire Paris committed
145

146
            throw new DBALException('Error occurred while generating ID with TableGenerator, aborted generation: ' . $e->getMessage(), 0, $e);
147 148 149 150 151
        }

        return $value;
    }
}