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
;
26 * Represents an ID generator that uses a database sequence.
29 * @author Roman Borschel <roman@code-factory.org>
31 class SequenceGenerator
extends AbstractIdGenerator
implements Serializable
34 * The allocation size of the sequence.
38 private $_allocationSize;
41 * The name of the sequence.
45 private $_sequenceName;
50 private $_nextValue = 0;
55 private $_maxValue = null;
58 * Initializes a new sequence generator.
60 * @param string $sequenceName The name of the sequence.
61 * @param integer $allocationSize The allocation size of the sequence.
63 public function __construct($sequenceName, $allocationSize)
65 $this->_sequenceName
= $sequenceName;
66 $this->_allocationSize
= $allocationSize;
72 public function generate(EntityManager
$em, $entity)
74 if ($this->_maxValue
=== null ||
$this->_nextValue
== $this->_maxValue
) {
75 // Allocate new values
76 $conn = $em->getConnection();
77 $sql = $conn->getDatabasePlatform()->getSequenceNextValSQL($this->_sequenceName
);
79 // Using `query` to force usage of the master server in MasterSlaveConnection
80 $this->_nextValue
= (int) $conn->query($sql)->fetchColumn();
81 $this->_maxValue
= $this->_nextValue +
$this->_allocationSize
;
84 return $this->_nextValue++
;
88 * Gets the maximum value of the currently allocated bag of values.
90 * @return integer|null
92 public function getCurrentMaxValue()
94 return $this->_maxValue
;
98 * Gets the next value that will be returned by generate().
102 public function getNextValue()
104 return $this->_nextValue
;
110 public function serialize()
114 'allocationSize' => $this->_allocationSize
,
115 'sequenceName' => $this->_sequenceName
121 * @param string $serialized
125 public function unserialize($serialized)
127 $array = unserialize($serialized);
129 $this->_sequenceName
= $array['sequenceName'];
130 $this->_allocationSize
= $array['allocationSize'];