function DB_mysql::nextId in Flickr API 5
Returns the next free id in a sequence
DB_mysql::createSequence(), DB_mysql::dropSequence()
Parameters
string $seq_name name of the sequence:
boolean $ondemand when true, the seqence is automatically: created if it does not exist
Return value
int the next id number in the sequence. A DB_Error object on failure.
Overrides DB_common::nextId
See also
DB_common::nextID(), DB_common::getSequenceName(),
File
- phpFlickr/
PEAR/ DB/ mysql.php, line 580
Class
- DB_mysql
- The methods PEAR DB uses to interact with PHP's mysql extension for interacting with MySQL databases
Code
function nextId($seq_name, $ondemand = true) {
$seqname = $this
->getSequenceName($seq_name);
do {
$repeat = 0;
$this
->pushErrorHandling(PEAR_ERROR_RETURN);
$result = $this
->query("UPDATE {$seqname} " . 'SET id=LAST_INSERT_ID(id+1)');
$this
->popErrorHandling();
if ($result === DB_OK) {
// COMMON CASE
$id = @mysql_insert_id($this->connection);
if ($id != 0) {
return $id;
}
// EMPTY SEQ TABLE
// Sequence table must be empty for some reason, so fill
// it and return 1 and obtain a user-level lock
$result = $this
->getOne("SELECT GET_LOCK('{$seqname}_lock',10)");
if (DB::isError($result)) {
return $this
->raiseError($result);
}
if ($result == 0) {
// Failed to get the lock
return $this
->mysqlRaiseError(DB_ERROR_NOT_LOCKED);
}
// add the default value
$result = $this
->query("REPLACE INTO {$seqname} (id) VALUES (0)");
if (DB::isError($result)) {
return $this
->raiseError($result);
}
// Release the lock
$result = $this
->getOne('SELECT RELEASE_LOCK(' . "'{$seqname}_lock')");
if (DB::isError($result)) {
return $this
->raiseError($result);
}
// We know what the result will be, so no need to try again
return 1;
}
elseif ($ondemand && DB::isError($result) && $result
->getCode() == DB_ERROR_NOSUCHTABLE) {
// ONDEMAND TABLE CREATION
$result = $this
->createSequence($seq_name);
if (DB::isError($result)) {
return $this
->raiseError($result);
}
else {
$repeat = 1;
}
}
elseif (DB::isError($result) && $result
->getCode() == DB_ERROR_ALREADY_EXISTS) {
// BACKWARDS COMPAT
// see _BCsequence() comment
$result = $this
->_BCsequence($seqname);
if (DB::isError($result)) {
return $this
->raiseError($result);
}
$repeat = 1;
}
} while ($repeat);
return $this
->raiseError($result);
}