You are here

function mongodb_next_id in MongoDB 7

Same name and namespace in other branches
  1. 6 mongodb.module \mongodb_next_id()

Return the next id in a sequence.

Parameters

string $name: The name of the sequence.

int $existing_id: The minimal value to be generated.

Return value

int The id.

Throws

\MongoConnectionException

1 call to mongodb_next_id()
mongodb_block_ui_add_block_form_submit in mongodb_block_ui/mongodb_block_ui.admin.inc
Save the new custom block.

File

./mongodb.module, line 361
Contains the main module connecting Drupal to MongoDB.

Code

function mongodb_next_id($name, $existing_id = 0) {

  // Atomically get the next id in the sequence.
  $mongo = mongodb();
  $cmd = array(
    'findandmodify' => mongodb_collection_name('sequence'),
    'query' => array(
      '_id' => $name,
    ),
    'update' => array(
      '$inc' => array(
        'value' => 1,
      ),
    ),
    'new' => TRUE,
  );

  // It's very likely that this is not necessary as command returns an array
  // not an exception. The increment will, however, will fix the problem of
  // the sequence not existing. Still, better safe than sorry.
  try {
    $sequence = $mongo
      ->command($cmd);
    $value = isset($sequence['value']['value']) ? $sequence['value']['value'] : 0;
  } catch (Exception $e) {
  }
  if (0 < $existing_id - $value + 1) {
    $cmd = array(
      'findandmodify' => mongodb_collection_name('sequence'),
      'query' => array(
        '_id' => $name,
      ),
      'update' => array(
        '$inc' => array(
          'value' => $existing_id - $value + 1,
        ),
      ),
      'upsert' => TRUE,
      'new' => TRUE,
    );
    $sequence = $mongo
      ->command($cmd);
    $value = isset($sequence['value']['value']) ? $sequence['value']['value'] : 0;
  }
  return $value;
}