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 Serializable, Doctrine\ORM\EntityManager;
25 * Represents an ID generator that uses a database sequence.
28 * @author Roman Borschel <roman@code-factory.org>
30 class SequenceGenerator extends AbstractIdGenerator implements Serializable
32 private $_allocationSize;
33 private $_sequenceName;
34 private $_nextValue = 0;
35 private $_maxValue = null;
38 * Initializes a new sequence generator.
40 * @param \Doctrine\ORM\EntityManager $em The EntityManager to use.
41 * @param string $sequenceName The name of the sequence.
42 * @param integer $allocationSize The allocation size of the sequence.
44 public function __construct($sequenceName, $allocationSize)
46 $this->_sequenceName = $sequenceName;
47 $this->_allocationSize = $allocationSize;
51 * Generates an ID for the given entity.
53 * @param object $entity
54 * @return integer|float The generated value.
57 public function generate(EntityManager $em, $entity)
59 if ($this->_maxValue === null || $this->_nextValue == $this->_maxValue) {
60 // Allocate new values
61 $conn = $em->getConnection();
62 $sql = $conn->getDatabasePlatform()->getSequenceNextValSQL($this->_sequenceName);
64 $this->_nextValue = (int)$conn->fetchColumn($sql);
65 $this->_maxValue = $this->_nextValue + $this->_allocationSize;
68 return $this->_nextValue++;
72 * Gets the maximum value of the currently allocated bag of values.
74 * @return integer|float
76 public function getCurrentMaxValue()
78 return $this->_maxValue;
82 * Gets the next value that will be returned by generate().
84 * @return integer|float
86 public function getNextValue()
88 return $this->_nextValue;
91 public function serialize()
93 return serialize(array(
94 'allocationSize' => $this->_allocationSize,
95 'sequenceName' => $this->_sequenceName
99 public function unserialize($serialized)
101 $array = unserialize($serialized);
103 $this->_sequenceName = $array['sequenceName'];
104 $this->_allocationSize = $array['allocationSize'];