3 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15 * This software consists of voluntary contributions made by many individuals
16 * and is licensed under the MIT license. For more information, see
17 * <http://www.doctrine-project.org>.
20 namespace Doctrine\ORM\Id;
22 use Doctrine\ORM\EntityManager;
25 * Id generator that uses a single-row database table and a hi/lo algorithm.
28 * @author Benjamin Eberlei <kontakt@beberlei.de>
29 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
30 * @author Jonathan Wage <jonwage@gmail.com>
31 * @author Roman Borschel <roman@code-factory.org>
33 class TableGenerator extends AbstractIdGenerator
36 private $_sequenceName;
37 private $_allocationSize;
41 public function __construct($tableName, $sequenceName = 'default', $allocationSize = 10)
43 $this->_tableName = $tableName;
44 $this->_sequenceName = $sequenceName;
45 $this->_allocationSize = $allocationSize;
48 public function generate(EntityManager $em, $entity)
50 if ($this->_maxValue === null || $this->_nextValue == $this->_maxValue) {
51 // Allocate new values
52 $conn = $em->getConnection();
54 if ($conn->getTransactionNestingLevel() === 0) {
55 // use select for update
56 $sql = $conn->getDatabasePlatform()->getTableHiLoCurrentValSql($this->_tableName, $this->_sequenceName);
57 $currentLevel = $conn->fetchColumn($sql);
59 if ($currentLevel != null) {
60 $this->_nextValue = $currentLevel;
61 $this->_maxValue = $this->_nextValue + $this->_allocationSize;
63 $updateSql = $conn->getDatabasePlatform()->getTableHiLoUpdateNextValSql(
64 $this->_tableName, $this->_sequenceName, $this->_allocationSize
67 if ($conn->executeUpdate($updateSql, array(1 => $currentLevel, 2 => $currentLevel+1)) !== 1) {
68 // no affected rows, concurrency issue, throw exception
71 // no current level returned, TableGenerator seems to be broken, throw exception
74 // only table locks help here, implement this or throw exception?
75 // or do we want to work with table locks exclusively?
79 return $this->_nextValue++;