You are here

public function Logger::ensureCappedCollection in MongoDB 8.2

Ensure a collection is capped with the proper size.

@todo support sharded clusters: convertToCapped does not support them.

Parameters

string $name: The collection name.

int $size: The collection size cap.

Return value

\MongoDB\Collection The collection, usable for additional commands like index creation.

Throws

\MongoDB\Exception\InvalidArgumentException

\MongoDB\Exception\UnsupportedException

\MongoDB\Exception\UnexpectedValueException

\MongoDB\Driver\Exception\RuntimeException

Note that MongoDB 4.2 still misses a proper exists() command, which is the reason for the weird try/catch logic.

See also

https://docs.mongodb.com/manual/reference/command/convertToCapped

https://jira.mongodb.org/browse/SERVER-1938

1 call to Logger::ensureCappedCollection()
Logger::ensureSchema in modules/mongodb_watchdog/src/Logger.php
Ensure indexes are set on the collections and tracker collection is capped.

File

modules/mongodb_watchdog/src/Logger.php, line 449

Class

Logger
Class Logger is a PSR/3 Logger using a MongoDB data store.

Namespace

Drupal\mongodb_watchdog

Code

public function ensureCappedCollection(string $name, int $size) : Collection {
  if ($size === 0) {
    $this->messenger
      ->addError($this
      ->t('Abnormal size 0 ensuring capped collection, defaulting.'));
    $size = 100000;
  }
  $collection = $this
    ->ensureCollection($name);
  $stats = $this->database
    ->command([
    'collStats' => $name,
  ], static::LEGACY_TYPE_MAP)
    ->toArray()[0];
  if (!empty($stats['capped'])) {
    return $collection;
  }
  $command = [
    'convertToCapped' => $name,
    'size' => $size,
  ];
  $this->database
    ->command($command);
  $this->messenger
    ->addStatus($this
    ->t('@name converted to capped collection size @size.', [
    '@name' => $name,
    '@size' => $size,
  ]));
  return $collection;
}