function DatabaseConnection_mysql::nextId

Overrides DatabaseConnection::nextId

File

includes/database/mysql/database.inc, line 488

Class

DatabaseConnection_mysql

Code

public function nextId($existing_id = 0) {
    $new_id = $this->query('INSERT INTO {sequences} () VALUES ()', array(), array(
        'return' => Database::RETURN_INSERT_ID,
    ));
    // This should only happen after an import or similar event.
    if ($existing_id >= $new_id) {
        // If we INSERT a value manually into the sequences table, on the next
        // INSERT, MySQL will generate a larger value. However, there is no way
        // of knowing whether this value already exists in the table. MySQL
        // provides an INSERT IGNORE which would work, but that can mask problems
        // other than duplicate keys. Instead, we use INSERT ... ON DUPLICATE KEY
        // UPDATE in such a way that the UPDATE does not do anything. This way,
        // duplicate keys do not generate errors but everything else does.
        $this->query('INSERT INTO {sequences} (value) VALUES (:value) ON DUPLICATE KEY UPDATE value = value', array(
            ':value' => $existing_id,
        ));
        $new_id = $this->query('INSERT INTO {sequences} () VALUES ()', array(), array(
            'return' => Database::RETURN_INSERT_ID,
        ));
    }
    $this->needsCleanup = TRUE;
    return $new_id;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.