You are here

public function Connection::nextId in Drupal driver for SQL Server and SQL Azure 3.0.x

Same name and namespace in other branches
  1. 8.2 drivers/lib/Drupal/Driver/Database/sqlsrv/Connection.php \Drupal\Driver\Database\sqlsrv\Connection::nextId()
  2. 8 drivers/lib/Drupal/Driver/Database/sqlsrv/Connection.php \Drupal\Driver\Database\sqlsrv\Connection::nextId()

Retrieves a unique ID from a given sequence.

Use this function if for some reason you can't use a serial field. For example, MySQL has no ways of reading of the current value of a sequence and PostgreSQL can not advance the sequence to be larger than a given value. Or sometimes you just need a unique integer.

Parameters

$existing_id: (optional) After a database import, it might be that the sequences table is behind, so by passing in the maximum existing ID, it can be assured that we never issue the same ID.

Return value

An integer number larger than any number returned by earlier calls and also larger than the $existing_id if one was passed in.

Overrides Connection::nextId

File

drivers/lib/Drupal/Driver/Database/sqlsrv/Connection.php, line 242

Class

Connection
Sqlsvr implementation of \Drupal\Core\Database\Connection.

Namespace

Drupal\Driver\Database\sqlsrv

Code

public function nextId($existing = 0) {

  // If an exiting value is passed, for its insertion into the sequence table.
  if ($existing > 0) {
    try {
      $sql = 'SET IDENTITY_INSERT {sequences} ON;';
      $sql .= ' INSERT INTO {sequences} (value) VALUES(:existing);';
      $sql .= ' SET IDENTITY_INSERT {sequences} OFF';
      $this
        ->queryDirect($sql, [
        ':existing' => $existing,
      ]);
    } catch (\Exception $e) {

      // Doesn't matter if this fails, it just means that this value is
      // already present in the table.
    }
  }

  // Refactored to use OUTPUT because under high concurrency LAST_INSERTED_ID
  // does not work properly.
  return $this
    ->queryDirect('INSERT INTO {sequences} OUTPUT (Inserted.[value]) DEFAULT VALUES')
    ->fetchField();
}