Skip to content

Commit d2bebc4

Browse files
committed
PHPLIB-547: Implement listDatabaseNames helper
1 parent 8ff5758 commit d2bebc4

11 files changed

+462
-82
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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 = []): Generator
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+
A generator containing the name of each database on the server.
38+
39+
Errors/Exceptions
40+
-----------------
41+
42+
.. include:: /includes/extracts/error-unexpectedvalueexception.rst
43+
.. include:: /includes/extracts/error-invalidargumentexception.rst
44+
.. include:: /includes/extracts/error-driver-runtimeexception.rst
45+
46+
Example
47+
-------
48+
49+
The following example lists all databases on the server:
50+
51+
.. code-block:: php
52+
53+
<?php
54+
55+
$client = new MongoDB\Client;
56+
57+
foreach ($client->listDatabaseNames() as $databaseName) {
58+
var_dump($databaseName);
59+
}
60+
61+
The output would then resemble::
62+
63+
string(5) "local"
64+
string(4) "test"
65+
66+
See Also
67+
--------
68+
69+
- :phpmethod:`MongoDB\\Database::listDatabases()`
70+
- :manual:`listDatabases </reference/command/listDatabases>` command reference
71+
in the MongoDB manual
72+
- `Enumerating Databases
73+
<https://github.com/mongodb/specifications/blob/master/source/enumerate-databases.rst>`_
74+
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: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
namespace MongoDB;
1919

20+
use Generator;
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,24 @@ public function getWriteConcern()
273275
return $this->writeConcern;
274276
}
275277

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

src/Command/ListDatabases.php

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
<?php
2+
/*
3+
* Copyright 2015-2017 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 array_column;
28+
use function current;
29+
use function is_array;
30+
use function is_bool;
31+
use function is_integer;
32+
use function is_object;
33+
34+
/**
35+
* Wrapper for the ListDatabases command.
36+
*
37+
* @internal
38+
* @see http://docs.mongodb.org/manual/reference/command/listDatabases/
39+
*/
40+
class ListDatabases implements Executable
41+
{
42+
/** @var array */
43+
private $options;
44+
45+
/**
46+
* Constructs a listDatabases command.
47+
*
48+
* Supported options:
49+
*
50+
* * authorizedDatabases (boolean): Determines which databases are returned
51+
* based on the user privileges.
52+
*
53+
* For servers < 4.0.5, this option is ignored.
54+
*
55+
* * filter (document): Query by which to filter databases.
56+
*
57+
* For servers < 3.6, this option is ignored.
58+
*
59+
* * maxTimeMS (integer): The maximum amount of time to allow the query to
60+
* run.
61+
*
62+
* * session (MongoDB\Driver\Session): Client session.
63+
*
64+
* Sessions are not supported for server versions < 3.6.
65+
*
66+
* @param array $options Command options
67+
* @throws InvalidArgumentException for parameter/option parsing errors
68+
*/
69+
public function __construct(array $options = [])
70+
{
71+
if (isset($options['authorizedDatabases']) && ! is_bool($options['authorizedDatabases'])) {
72+
throw InvalidArgumentException::invalidType('"authorizedDatabases" option', $options['authorizedDatabases'], 'boolean');
73+
}
74+
75+
if (isset($options['filter']) && ! is_array($options['filter']) && ! is_object($options['filter'])) {
76+
throw InvalidArgumentException::invalidType('"filter" option', $options['filter'], ['array', 'object']);
77+
}
78+
79+
if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) {
80+
throw InvalidArgumentException::invalidType('"maxTimeMS" option', $options['maxTimeMS'], 'integer');
81+
}
82+
83+
if (isset($options['nameOnly']) && ! is_bool($options['nameOnly'])) {
84+
throw InvalidArgumentException::invalidType('"nameOnly" option', $options['nameOnly'], 'boolean');
85+
}
86+
87+
if (isset($options['session']) && ! $options['session'] instanceof Session) {
88+
throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
89+
}
90+
91+
$this->options = $options;
92+
}
93+
94+
/**
95+
* Execute the operation.
96+
*
97+
* @see Executable::execute()
98+
* @param Server $server
99+
* @return array An array of database names or an array of database info structures, depending on the nameOnly option
100+
* @throws UnexpectedValueException if the command response was malformed
101+
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
102+
*/
103+
public function execute(Server $server)
104+
{
105+
$cmd = ['listDatabases' => 1];
106+
107+
if (isset($this->options['authorizedDatabases'])) {
108+
$cmd['authorizedDatabases'] = $this->options['authorizedDatabases'];
109+
}
110+
111+
if (! empty($this->options['filter'])) {
112+
$cmd['filter'] = (object) $this->options['filter'];
113+
}
114+
115+
if (isset($this->options['maxTimeMS'])) {
116+
$cmd['maxTimeMS'] = $this->options['maxTimeMS'];
117+
}
118+
119+
if (isset($this->options['nameOnly'])) {
120+
$cmd['nameOnly'] = $this->options['nameOnly'];
121+
}
122+
123+
$cursor = $server->executeReadCommand('admin', new Command($cmd), $this->createOptions());
124+
$cursor->setTypeMap(['root' => 'array', 'document' => 'array']);
125+
$result = current($cursor->toArray());
126+
127+
if (! isset($result['databases']) || ! is_array($result['databases'])) {
128+
throw new UnexpectedValueException('listDatabases command did not return a "databases" array');
129+
}
130+
131+
// Using array_column here emulates nameOnly behavior for servers that don't support it and ensures a consistent return type
132+
return $this->options['nameOnly'] ?? false ? array_column($result['databases'], 'name') : $result['databases'];
133+
}
134+
135+
/**
136+
* Create options for executing the command.
137+
*
138+
* Note: read preference is intentionally omitted, as the spec requires that
139+
* the command be executed on the primary.
140+
*
141+
* @see http://php.net/manual/en/mongodb-driver-server.executecommand.php
142+
* @return array
143+
*/
144+
private function createOptions()
145+
{
146+
$options = [];
147+
148+
if (isset($this->options['session'])) {
149+
$options['session'] = $this->options['session'];
150+
}
151+
152+
return $options;
153+
}
154+
}

src/Operation/ListDatabaseNames.php

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
<?php
2+
/*
3+
* Copyright 2015-2017 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 Generator;
21+
use MongoDB\Command\ListDatabases as ListDatabasesCommand;
22+
use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
23+
use MongoDB\Driver\Server;
24+
use MongoDB\Exception\InvalidArgumentException;
25+
use MongoDB\Exception\UnexpectedValueException;
26+
27+
/**
28+
* Operation for the ListDatabases command, returning only database names.
29+
*
30+
* @api
31+
* @see \MongoDB\Client::listDatabaseNames()
32+
* @see http://docs.mongodb.org/manual/reference/command/ListDatabases/
33+
*/
34+
class ListDatabaseNames implements Executable
35+
{
36+
/** @var ListDatabasesCommand */
37+
private $listDatabases;
38+
39+
/**
40+
* Constructs a listDatabases command.
41+
*
42+
* Supported options:
43+
*
44+
* * authorizedDatabases (boolean): Determines which databases are returned
45+
* based on the user privileges.
46+
*
47+
* For servers < 4.0.5, this option is ignored.
48+
*
49+
* * filter (document): Query by which to filter databases.
50+
*
51+
* For servers < 3.6, this option is ignored.
52+
*
53+
* * maxTimeMS (integer): The maximum amount of time to allow the query to
54+
* run.
55+
*
56+
* * session (MongoDB\Driver\Session): Client session.
57+
*
58+
* Sessions are not supported for server versions < 3.6.
59+
*
60+
* @param array $options Command options
61+
* @throws InvalidArgumentException for parameter/option parsing errors
62+
*/
63+
public function __construct(array $options = [])
64+
{
65+
$this->listDatabases = new ListDatabasesCommand(['nameOnly' => true] + $options);
66+
}
67+
68+
/**
69+
* Execute the operation.
70+
*
71+
* @see Executable::execute()
72+
* @param Server $server
73+
* @return Generator
74+
* @throws UnexpectedValueException if the command response was malformed
75+
* @throws DriverRuntimeException for other driver errors (e.g. connection errors)
76+
*/
77+
public function execute(Server $server)
78+
{
79+
yield from $this->listDatabases->execute($server);
80+
}
81+
}

0 commit comments

Comments
 (0)