Skip to content

Commit

Permalink
Allow to override the database name when connecting
Browse files Browse the repository at this point in the history
This is particularly useful when you connect with an URI that you can't
change (e.g. given by a cloud provider) and that doesn't specify a default
database, or when you have one specified but still want to use another one.
  • Loading branch information
ramnes committed Nov 25, 2022
1 parent 66c70a4 commit 08d09a4
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
4 changes: 2 additions & 2 deletions mongo_thingy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,13 @@ def count(cls, filter=None, *args, **kwargs):
return cls.count_documents(filter=filter, *args, **kwargs)

@classmethod
def connect(cls, *args, client_cls=None, **kwargs):
def connect(cls, *args, client_cls=None, database_name=None, **kwargs):
if not client_cls:
client_cls = cls._client_cls

cls._client = client_cls(*args, **kwargs)
try:
cls._database = cls._client.get_database()
cls._database = cls._client.get_database(database_name)
except (ConfigurationError, TypeError):
cls._database = cls._client["test"]

Expand Down
7 changes: 7 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,13 @@ def test_connect_disconnect(thingy_cls, client_cls):
disconnect()
assert thingy_cls._client is None

connect(client_cls=client_cls, database_name="database")
assert isinstance(thingy_cls.client, client_cls)
assert thingy_cls._database.name == "database"

disconnect()
assert thingy_cls._client is None

thingy_cls._client_cls = client_cls
connect()
assert isinstance(thingy_cls.client, client_cls)
Expand Down

0 comments on commit 08d09a4

Please sign in to comment.