Skip to content

PHPLIB-547: Add helpers to list database and collection names #758

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions docs/reference/method/MongoDBClient-listDatabaseNames.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
====================================
MongoDB\\Client::listDatabaseNames()
====================================

.. versionadded:: 1.7

.. default-domain:: mongodb

.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol

Definition
----------

.. phpmethod:: MongoDB\\Client::listDatabaseNames()

Returns names for all databases on the server.

.. code-block:: php

function listDatabaseNames(array $options = []): Iterator

This method has the following parameters:

.. include:: /includes/apiargs/MongoDBClient-method-listDatabases-param.rst

The ``$options`` parameter supports the following options:

.. include:: /includes/apiargs/MongoDBClient-method-listDatabases-option.rst

Return Values
-------------

An :php:`Iterator <class.iterator.php>`, which provides the name of each
database on the server.

Errors/Exceptions
-----------------

.. include:: /includes/extracts/error-unexpectedvalueexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst

Example
-------

The following example lists all databases on the server:

.. code-block:: php

<?php

$client = new MongoDB\Client;

foreach ($client->listDatabaseNames() as $databaseName) {
var_dump($databaseName);
}

The output would then resemble::

string(5) "local"
string(4) "test"

See Also
--------

- :phpmethod:`MongoDB\\Database::listDatabases()`
- :manual:`listDatabases </reference/command/listDatabases>` command reference
in the MongoDB manual
- `Enumerating Databases
<https://github.com/mongodb/specifications/blob/master/source/enumerate-databases.rst>`_
specification
4 changes: 4 additions & 0 deletions docs/reference/method/MongoDBClient-listDatabases.txt
Original file line number Diff line number Diff line change
Expand Up @@ -80,5 +80,9 @@ The output would then resemble::
See Also
--------

- :phpmethod:`MongoDB\\Database::listDatabaseNames()`
- :manual:`listDatabases </reference/command/listDatabases>` command reference
in the MongoDB manual
- `Enumerating Databases
<https://github.com/mongodb/specifications/blob/master/source/enumerate-databases.rst>`_
specification
98 changes: 98 additions & 0 deletions docs/reference/method/MongoDBDatabase-listCollectionNames.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
========================================
MongoDB\\Database::listCollectionNames()
========================================

.. versionadded:: 1.7

.. default-domain:: mongodb

.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol

Definition
----------

.. phpmethod:: MongoDB\\Database::listCollectionNames()

Returns names for all collections in this database.

.. code-block:: php

function listCollectionNames(array $options = []): Iterator

This method has the following parameters:

.. include:: /includes/apiargs/MongoDBDatabase-method-listCollections-param.rst

The ``$options`` parameter supports the following options:

.. include:: /includes/apiargs/MongoDBDatabase-method-listCollections-option.rst

Return Values
-------------

An :php:`Iterator <class.iterator.php>`, which provides the name of each
collection in the database.

Example
-------

The following example lists all of the collections in the ``test`` database:

.. code-block:: php

<?php

$database = (new MongoDB\Client)->test;

foreach ($database->listCollectionNames() as $collectionName) {
var_dump($collectionName);
}

The output would then resemble::

string(11) "restaurants"
string(5) "users"
string(6) "restos"

The following example lists all collections whose name starts with ``"rest"``
in the ``test`` database:

.. code-block:: php

<?php

$database = (new MongoDB\Client)->test;

$collections = $database->listCollectionNames([
'filter' => [
'name' => new MongoDB\BSON\Regex('^rest.*'),
],
]);

foreach ($collections as $collectionName) {
var_dump($collectionName);
}

The output would then resemble::

string(11) "restaurants"
string(6) "restos"

.. note::

When enumerating collection names, a filter expression can only filter based
on a collection's name and type. No other fields are available.

See Also
--------

- :phpmethod:`MongoDB\\Database::listCollections()`
- :manual:`listCollections </reference/command/listCollections` command
reference in the MongoDB manual
- `Enumerating Collections
<https://github.com/mongodb/specifications/blob/master/source/enumerate-collections.rst>`_
specification
1 change: 1 addition & 0 deletions docs/reference/method/MongoDBDatabase-listCollections.txt
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ The output would then resemble::
See Also
--------

- :phpmethod:`MongoDB\\Database::listCollectionNames()`
- :manual:`listCollections </reference/command/listCollections` command
reference in the MongoDB manual
- `Enumerating Collections
Expand Down
18 changes: 18 additions & 0 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

namespace MongoDB;

use Iterator;
use Jean85\PrettyVersions;
use MongoDB\Driver\ClientEncryption;
use MongoDB\Driver\Exception\InvalidArgumentException as DriverInvalidArgumentException;
Expand All @@ -33,6 +34,7 @@
use MongoDB\Model\BSONDocument;
use MongoDB\Model\DatabaseInfoIterator;
use MongoDB\Operation\DropDatabase;
use MongoDB\Operation\ListDatabaseNames;
use MongoDB\Operation\ListDatabases;
use MongoDB\Operation\Watch;
use Throwable;
Expand Down Expand Up @@ -273,6 +275,22 @@ public function getWriteConcern()
return $this->writeConcern;
}

/**
* List database names.
*
* @see ListDatabaseNames::__construct() for supported options
* @throws UnexpectedValueException if the command response was malformed
* @throws InvalidArgumentException for parameter/option parsing errors
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function listDatabaseNames(array $options = []) : Iterator
{
$operation = new ListDatabaseNames($options);
$server = select_server($this->manager, $options);

return $operation->execute($server);
}

/**
* List databases.
*
Expand Down
139 changes: 139 additions & 0 deletions src/Command/ListCollections.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
<?php
/*
* Copyright 2020-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace MongoDB\Command;

use MongoDB\Driver\Command;
use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
use MongoDB\Driver\Server;
use MongoDB\Driver\Session;
use MongoDB\Exception\InvalidArgumentException;
use MongoDB\Model\CachingIterator;
use MongoDB\Operation\Executable;
use function is_array;
use function is_bool;
use function is_integer;
use function is_object;

/**
* Wrapper for the listCollections command.
*
* @internal
* @see http://docs.mongodb.org/manual/reference/command/listCollections/
*/
class ListCollections implements Executable
{
/** @var string */
private $databaseName;

/** @var array */
private $options;

/**
* Constructs a listCollections command.
*
* Supported options:
*
* * filter (document): Query by which to filter collections.
*
* * maxTimeMS (integer): The maximum amount of time to allow the query to
* run.
*
* * nameOnly (boolean): A flag to indicate whether the command should
* return just the collection/view names and type or return both the name
* and other information.
*
* * session (MongoDB\Driver\Session): Client session.
*
* Sessions are not supported for server versions < 3.6.
*
* @param string $databaseName Database name
* @param array $options Command options
* @throws InvalidArgumentException for parameter/option parsing errors
*/
public function __construct($databaseName, array $options = [])
{
if (isset($options['filter']) && ! is_array($options['filter']) && ! is_object($options['filter'])) {
throw InvalidArgumentException::invalidType('"filter" option', $options['filter'], 'array or object');
}

if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) {
throw InvalidArgumentException::invalidType('"maxTimeMS" option', $options['maxTimeMS'], 'integer');
}

if (isset($options['nameOnly']) && ! is_bool($options['nameOnly'])) {
throw InvalidArgumentException::invalidType('"nameOnly" option', $options['nameOnly'], 'boolean');
}

if (isset($options['session']) && ! $options['session'] instanceof Session) {
throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
}

$this->databaseName = (string) $databaseName;
$this->options = $options;
}

/**
* Execute the operation.
*
* @see Executable::execute()
* @param Server $server
* @return CachingIterator
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
*/
public function execute(Server $server)
{
$cmd = ['listCollections' => 1];

if (! empty($this->options['filter'])) {
$cmd['filter'] = (object) $this->options['filter'];
}

if (isset($this->options['maxTimeMS'])) {
$cmd['maxTimeMS'] = $this->options['maxTimeMS'];
}

if (isset($this->options['nameOnly'])) {
$cmd['nameOnly'] = $this->options['nameOnly'];
}

$cursor = $server->executeReadCommand($this->databaseName, new Command($cmd), $this->createOptions());
$cursor->setTypeMap(['root' => 'array', 'document' => 'array']);

return new CachingIterator($cursor);
}

/**
* Create options for executing the command.
*
* Note: read preference is intentionally omitted, as the spec requires that
* the command be executed on the primary.
*
* @see http://php.net/manual/en/mongodb-driver-server.executecommand.php
* @return array
*/
private function createOptions()
{
$options = [];

if (isset($this->options['session'])) {
$options['session'] = $this->options['session'];
}

return $options;
}
}
Loading