You are here

public function Connection::nextId in Drupal driver for SQL Server and SQL Azure 8.2

Same name in this branch
  1. 8.2 drivers/lib/Drupal/Driver/Database/sqlsrv/Connection.php \Drupal\Driver\Database\sqlsrv\Connection::nextId()
  2. 8.2 drivers/lib/Drupal/Driver/Database/sqlsrv/PDO/Connection.php \Drupal\Driver\Database\sqlsrv\PDO\Connection::nextId()

Generate a sequence

Parameters

int $existing: The sequence value must be greater than this value.

string $name: Name of the sequence.

Return value

mixed

Throws

\Exception

File

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

Class

Connection

Namespace

Drupal\Driver\Database\sqlsrv\PDO

Code

public function nextId($min = 0, $name = 'default') {

  // To deal with crappy upstream code.
  if (empty($min)) {
    $min = 0;
  }
  if (!is_numeric($min)) {
    throw new \InvalidArgumentException("Minimum id value must be an integer: {$min}");
  }

  // The sequence name must be unique for this installation.
  $sequence_name = 'seq_' . $name;
  try {
    $next_id = $this
      ->query_execute("SELECT NEXT VALUE FOR {$sequence_name}")
      ->fetchField();
  } catch (\Exception $e) {

    // Create the sequence starting at $min + 2,
    // because $min + 1 is already being used in this request.
    $start = $min + 2;

    // The "first id" is the same as the minimum possible
    // value, because the minimum for MSSQL is inclusive, while
    // this function's definition $min is exclusive (must
    // be greater.
    $next_id = $min + 1;
    $this
      ->query_execute("CREATE SEQUENCE {$sequence_name} START WITH {$start} INCREMENT BY 1 MINVALUE {$next_id}");
  }

  // If the retrieve id is smaller or equal to de existent,
  // restart the sequence to the provided number.
  if ($next_id <= $min) {
    $min++;
    $this
      ->query_execute("ALTER SEQUENCE {$sequence_name} RESTART WITH {$min}");
    $next_id = $this
      ->query_execute("SELECT NEXT VALUE FOR {$sequence_name}")
      ->fetchColumn();
  }
  return $next_id;
}