3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Db\TableGateway\Feature
;
12 use Zend\Db\Sql\Insert
;
13 use Zend\Db\Adapter\Driver\ResultInterface
;
14 use Zend\Db\Adapter\Driver\StatementInterface
;
16 class SequenceFeature
extends AbstractFeature
21 protected $primaryKeyField;
26 protected $sequenceName;
31 protected $sequenceValue;
35 * @param string $primaryKeyField
36 * @param string $sequenceName
38 public function __construct($primaryKeyField, $sequenceName)
40 $this->primaryKeyField
= $primaryKeyField;
41 $this->sequenceName
= $sequenceName;
45 * @param Insert $insert
47 public function preInsert(Insert
$insert)
49 $columns = $insert->getRawState('columns');
50 $values = $insert->getRawState('values');
51 $key = array_search($this->primaryKeyField
, $columns);
53 $this->sequenceValue
= $values[$key];
57 $this->sequenceValue
= $this->nextSequenceId();
58 if ($this->sequenceValue
=== null) {
62 $insert->values(array($this->primaryKeyField
=> $this->sequenceValue
), Insert
::VALUES_MERGE
);
66 public function postInsert(StatementInterface
$statement, ResultInterface
$result)
68 if ($this->sequenceValue
!== null) {
69 $this->tableGateway
->lastInsertValue
= $this->sequenceValue
;
74 * Generate a new value from the specified sequence in the database, and return it.
77 public function nextSequenceId()
79 $platform = $this->tableGateway
->adapter
->getPlatform();
80 $platformName = $platform->getName();
82 switch ($platformName) {
84 $sql = 'SELECT ' . $platform->quoteIdentifier($this->sequenceName
) . '.NEXTVAL FROM dual';
87 $sql = 'SELECT NEXTVAL(\'' . $this->sequenceName
. '\')';
93 $statement = $this->tableGateway
->adapter
->createStatement();
94 $statement->prepare($sql);
95 $result = $statement->execute();
96 $sequence = $result->current();
97 unset($statement, $result);
98 return $sequence['nextval'];
102 * Return the most recent value from the specified sequence in the database.
105 public function lastSequenceId()
107 $platform = $this->tableGateway
->adapter
->getPlatform();
108 $platformName = $platform->getName();
110 switch ($platformName) {
112 $sql = 'SELECT ' . $platform->quoteIdentifier($this->sequenceName
) . '.CURRVAL FROM dual';
115 $sql = 'SELECT CURRVAL(\'' . $this->sequenceName
. '\')';
121 $statement = $this->tableGateway
->adapter
->createStatement();
122 $statement->prepare($sql);
123 $result = $statement->execute();
124 $sequence = $result->current();
125 unset($statement, $result);
126 return $sequence['currval'];