I am trying to create custom sequence generator. after searching a lot I found the following methods
- Save counter method
public function sequence( $id )
{
$model = CustomSequence::model()->findByPk( id ); // where id => primary key in table CustomSequence
$model->saveCounter(array('counter' => 1 ) ); //increments the field counter in table CustomSequence by 1
echo $model->counter; //prints the incremented value
}
I wrote the above code in an action and called it simultaneously using CURL different shell.
$ for i in `seq 1 1000`; do curl "localhost/test/index.php/controller/sequence/id/1"; done
The issue is I got duplicate values in two terminals. Then I enclosed the above inside transaction. That issue still persisted.
- The other way is to use separate tables for each sequence.
Eg:
CREATE TABLE IF NOT EXISTS `seq_1` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=<my_custom_start_number> ;
To get a value from counter "get the last inserted id" after running the query
INSERT INTO `seq_1` VALUES ()
Your thoughts please.