Skip to content

Commit 28d5377

Browse files
committed
PHPLIB-547: Implement listDatabaseNames helper
1 parent bcfdbc4 commit 28d5377

11 files changed

+467
-82
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
====================================
2+
MongoDB\\Client::listDatabaseNames()
3+
====================================
4+
5+
.. versionadded:: 1.7
6+
7+
.. default-domain:: mongodb
8+
9+
.. contents:: On this page
10+
:local:
11+
:backlinks: none
12+
:depth: 1
13+
:class: singlecol
14+
15+
Definition
16+
----------
17+
18+
.. phpmethod:: MongoDB\\Client::listDatabaseNames()
19+
20+
Returns names for all databases on the server.
21+
22+
.. code-block:: php
23+
24+
function listDatabaseNames(array $options = []): Iterator
25+
26+
This method has the following parameters:
27+
28+
.. include:: /includes/apiargs/MongoDBClient-method-listDatabases-param.rst
29+
30+
The ``$options`` parameter supports the following options:
31+
32+
.. include:: /includes/apiargs/MongoDBClient-method-listDatabases-option.rst
33+
34+
Return Values
35+
-------------
36+
37+
An :php:`Iterator <class.iterator.php>`, which provides the name of each
38+
database on the server.
39+
40+
Errors/Exceptions
41+
-----------------
42+
43+
.. include:: /includes/extracts/error-unexpectedvalueexception.rst
44+
.. include:: /includes/extracts/error-invalidargumentexception.rst
45+
.. include:: /includes/extracts/error-driver-runtimeexception.rst
46+
47+
Example
48+
-------
49+
50+
The following example lists all databases on the server:
51+
52+
.. code-block:: php
53+
54+
<?php
55+
56+
$client = new MongoDB\Client;
57+
58+
foreach ($client->listDatabaseNames() as $databaseName) {
59+
var_dump($databaseName);
60+
}
61+
62+
The output would then resemble::
63+
64+
string(5) "local"
65+
string(4) "test"
66+
67+
See Also
68+
--------
69+
70+
- :phpmethod:`MongoDB\\Database::listDatabases()`
71+
- :manual:`listDatabases </reference/command/listDatabases>` command reference
72+
in the MongoDB manual
73+
- `Enumerating Databases
74+
<https://github.com/mongodb/specifications/blob/master/source/enumerate-databases.rst>`_
75+
specification

docs/reference/method/MongoDBClient-listDatabases.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,5 +80,9 @@ The output would then resemble::
8080
See Also
8181
--------
8282

83+
- :phpmethod:`MongoDB\\Database::listDatabaseNames()`
8384
- :manual:`listDatabases </reference/command/listDatabases>` command reference
8485
in the MongoDB manual
86+
- `Enumerating Databases
87+
<https://github.com/mongodb/specifications/blob/master/source/enumerate-databases.rst>`_
88+
specification

src/Client.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
namespace MongoDB;
1919

20+
use Iterator;
2021
use Jean85\PrettyVersions;
2122
use MongoDB\Driver\ClientEncryption;
2223
use MongoDB\Driver\Exception\InvalidArgumentException as DriverInvalidArgumentException;
@@ -33,6 +34,7 @@
3334
use MongoDB\Model\BSONDocument;
3435
use MongoDB\Model\DatabaseInfoIterator;
3536
use MongoDB\Operation\DropDatabase;
37+
use MongoDB\Operation\ListDatabaseNames;
3638
use MongoDB\Operation\ListDatabases;
3739
use MongoDB\Operation\Watch;
3840
use Throwable;
@@ -273,6 +275,22 @@ public function getWriteConcern()
273275
return $this->writeConcern;
274276
}
275277

278+
/**
279+
* List database names.
280+
*
281+
* @see ListDatabaseNames::__construct() for supported options
282+
* @throws UnexpectedValueException if the command response was malformed
283+
* @throws InvalidArgumentException for parameter/option parsing errors
284+
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
285+
*/
286+
public function listDatabaseNames(array $options = []) : Iterator
287+
{
288+
$operation = new ListDatabaseNames($options);
289+
$server = select_server($this->manager, $options);
290+
291+
return $operation->execute($server);
292+
}
293+
276294
/**
277295
* List databases.
278296
*

src/Command/ListDatabases.php

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
<?php
2+
/*
3+
* Copyright 2020-present MongoDB, Inc.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
namespace MongoDB\Command;
19+
20+
use MongoDB\Driver\Command;
21+
use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
22+
use MongoDB\Driver\Server;
23+
use MongoDB\Driver\Session;
24+
use MongoDB\Exception\InvalidArgumentException;
25+
use MongoDB\Exception\UnexpectedValueException;
26+
use MongoDB\Operation\Executable;
27+
use function current;
28+
use function is_array;
29+
use function is_bool;
30+
use function is_integer;
31+
use function is_object;
32+
33+
/**
34+
* Wrapper for the ListDatabases command.
35+
*
36+
* @internal
37+
* @see http://docs.mongodb.org/manual/reference/command/listDatabases/
38+
*/
39+
class ListDatabases implements Executable
40+
{
41+
/** @var array */
42+
private $options;
43+
44+
/**
45+
* Constructs a listDatabases command.
46+
*
47+
* Supported options:
48+
*
49+
* * authorizedDatabases (boolean): Determines which databases are returned
50+
* based on the user privileges.
51+
*
52+
* For servers < 4.0.5, this option is ignored.
53+
*
54+
* * filter (document): Query by which to filter databases.
55+
*
56+
* For servers < 3.6, this option is ignored.
57+
*
58+
* * maxTimeMS (integer): The maximum amount of time to allow the query to
59+
* run.
60+
*
61+
* * nameOnly (boolean): A flag to indicate whether the command should
62+
* return just the database names, or return both database names and size
63+
* information.
64+
*
65+
* * session (MongoDB\Driver\Session): Client session.
66+
*
67+
* Sessions are not supported for server versions < 3.6.
68+
*
69+
* @param array $options Command options
70+
* @throws InvalidArgumentException for parameter/option parsing errors
71+
*/
72+
public function __construct(array $options = [])
73+
{
74+
if (isset($options['authorizedDatabases']) && ! is_bool($options['authorizedDatabases'])) {
75+
throw InvalidArgumentException::invalidType('"authorizedDatabases" option', $options['authorizedDatabases'], 'boolean');
76+
}
77+
78+
if (isset($options['filter']) && ! is_array($options['filter']) && ! is_object($options['filter'])) {
79+
throw InvalidArgumentException::invalidType('"filter" option', $options['filter'], ['array', 'object']);
80+
}
81+
82+
if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) {
83+
throw InvalidArgumentException::invalidType('"maxTimeMS" option', $options['maxTimeMS'], 'integer');
84+
}
85+
86+
if (isset($options['nameOnly']) && ! is_bool($options['nameOnly'])) {
87+
throw InvalidArgumentException::invalidType('"nameOnly" option', $options['nameOnly'], 'boolean');
88+
}
89+
90+
if (isset($options['session']) && ! $options['session'] instanceof Session) {
91+
throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
92+
}
93+
94+
$this->options = $options;
95+
}
96+
97+
/**
98+
* Execute the operation.
99+
*
100+
* @see Executable::execute()
101+
* @param Server $server
102+
* @return array An array of database info structures
103+
* @throws UnexpectedValueException if the command response was malformed
104+
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
105+
*/
106+
public function execute(Server $server)
107+
{
108+
$cmd = ['listDatabases' => 1];
109+
110+
if (isset($this->options['authorizedDatabases'])) {
111+
$cmd['authorizedDatabases'] = $this->options['authorizedDatabases'];
112+
}
113+
114+
if (! empty($this->options['filter'])) {
115+
$cmd['filter'] = (object) $this->options['filter'];
116+
}
117+
118+
if (isset($this->options['maxTimeMS'])) {
119+
$cmd['maxTimeMS'] = $this->options['maxTimeMS'];
120+
}
121+
122+
if (isset($this->options['nameOnly'])) {
123+
$cmd['nameOnly'] = $this->options['nameOnly'];
124+
}
125+
126+
$cursor = $server->executeReadCommand('admin', new Command($cmd), $this->createOptions());
127+
$cursor->setTypeMap(['root' => 'array', 'document' => 'array']);
128+
$result = current($cursor->toArray());
129+
130+
if (! isset($result['databases']) || ! is_array($result['databases'])) {
131+
throw new UnexpectedValueException('listDatabases command did not return a "databases" array');
132+
}
133+
134+
return $result['databases'];
135+
}
136+
137+
/**
138+
* Create options for executing the command.
139+
*
140+
* Note: read preference is intentionally omitted, as the spec requires that
141+
* the command be executed on the primary.
142+
*
143+
* @see http://php.net/manual/en/mongodb-driver-server.executecommand.php
144+
* @return array
145+
*/
146+
private function createOptions()
147+
{
148+
$options = [];
149+
150+
if (isset($this->options['session'])) {
151+
$options['session'] = $this->options['session'];
152+
}
153+
154+
return $options;
155+
}
156+
}

src/Operation/ListDatabaseNames.php

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
<?php
2+
/*
3+
* Copyright 2020-present MongoDB, Inc.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
namespace MongoDB\Operation;
19+
20+
use ArrayIterator;
21+
use Iterator;
22+
use MongoDB\Command\ListDatabases as ListDatabasesCommand;
23+
use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
24+
use MongoDB\Driver\Server;
25+
use MongoDB\Exception\InvalidArgumentException;
26+
use MongoDB\Exception\UnexpectedValueException;
27+
use function array_column;
28+
29+
/**
30+
* Operation for the ListDatabases command, returning only database names.
31+
*
32+
* @api
33+
* @see \MongoDB\Client::listDatabaseNames()
34+
* @see http://docs.mongodb.org/manual/reference/command/ListDatabases/
35+
*/
36+
class ListDatabaseNames implements Executable
37+
{
38+
/** @var ListDatabasesCommand */
39+
private $listDatabases;
40+
41+
/**
42+
* Constructs a listDatabases command.
43+
*
44+
* Supported options:
45+
*
46+
* * authorizedDatabases (boolean): Determines which databases are returned
47+
* based on the user privileges.
48+
*
49+
* For servers < 4.0.5, this option is ignored.
50+
*
51+
* * filter (document): Query by which to filter databases.
52+
*
53+
* For servers < 3.6, this option is ignored.
54+
*
55+
* * maxTimeMS (integer): The maximum amount of time to allow the query to
56+
* run.
57+
*
58+
* * session (MongoDB\Driver\Session): Client session.
59+
*
60+
* Sessions are not supported for server versions < 3.6.
61+
*
62+
* @param array $options Command options
63+
* @throws InvalidArgumentException for parameter/option parsing errors
64+
*/
65+
public function __construct(array $options = [])
66+
{
67+
$this->listDatabases = new ListDatabasesCommand(['nameOnly' => true] + $options);
68+
}
69+
70+
/**
71+
* Execute the operation.
72+
*
73+
* @see Executable::execute()
74+
* @param Server $server
75+
* @return Iterator
76+
* @throws UnexpectedValueException if the command response was malformed
77+
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
78+
*/
79+
public function execute(Server $server) : Iterator
80+
{
81+
$result = $this->listDatabases->execute($server);
82+
83+
return new ArrayIterator(array_column($result, 'name'));
84+
}
85+
}

0 commit comments

Comments
 (0)