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\FetchMode;
9
use Doctrine\DBAL\LockMode;
10
use Throwable;
11 12
use const CASE_LOWER;
use function array_change_key_case;
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

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

56
    /** @var string */
57 58
    private $generatorTableName;

59
    /** @var mixed[][] */
60
    private $sequences = [];
61 62

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

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

95 96 97 98 99 100 101
            return $value;
        }

        $this->conn->beginTransaction();

        try {
            $platform = $this->conn->getDatabasePlatform();
102 103 104 105 106
            $sql      = 'SELECT sequence_value, sequence_increment_by'
                . ' FROM ' . $platform->appendLockHint($this->generatorTableName, LockMode::PESSIMISTIC_WRITE)
                . ' WHERE sequence_name = ? ' . $platform->getWriteLockSQL();
            $stmt     = $this->conn->executeQuery($sql, [$sequenceName]);
            $row      = $stmt->fetch(FetchMode::ASSOCIATIVE);
107

108
            if ($row !== false) {
109 110
                $row = array_change_key_case($row, CASE_LOWER);

111 112 113 114
                $value = $row['sequence_value'];
                $value++;

                if ($row['sequence_increment_by'] > 1) {
115
                    $this->sequences[$sequenceName] = [
116
                        'value' => $value,
117
                        'max' => $row['sequence_value'] + $row['sequence_increment_by'],
118
                    ];
119 120
                }

121 122 123
                $sql  = 'UPDATE ' . $this->generatorTableName . ' ' .
                       'SET sequence_value = sequence_value + sequence_increment_by ' .
                       'WHERE sequence_name = ? AND sequence_value = ?';
124
                $rows = $this->conn->executeUpdate($sql, [$sequenceName, $row['sequence_value']]);
125

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

            $this->conn->commit();
138
        } catch (Throwable $e) {
139
            $this->conn->rollBack();
140
            throw new DBALException('Error occurred while generating ID with TableGenerator, aborted generation: ' . $e->getMessage(), 0, $e);
141 142 143 144 145
        }

        return $value;
    }
}