Skip to content

Commit

Permalink
feat: defer the database connection to when it's needed
Browse files Browse the repository at this point in the history
  • Loading branch information
masci committed May 28, 2024
1 parent 257f992 commit 7b6752d
Showing 1 changed file with 16 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -81,22 +81,28 @@ def __init__(
msg = f'Invalid collection name: "{collection_name}". It can only contain letters, numbers, -, or _.'
raise ValueError(msg)

resolved_connection_string = mongo_connection_string.resolve_value()
self.resolved_connection_string = mongo_connection_string.resolve_value()
self.mongo_connection_string = mongo_connection_string

self.database_name = database_name
self.collection_name = collection_name
self.vector_search_index = vector_search_index
self._connection: Optional[MongoClient] = None

@property
def connection(self) -> MongoClient:
if self._connection is None:
self._connection = MongoClient(
self.resolved_connection_string, driver=DriverInfo(name="MongoDBAtlasHaystackIntegration")
)
database = self.connection[self.database_name]

if self.collection_name not in database.list_collection_names():
msg = f"Collection '{self.collection_name}' does not exist in database '{self.database_name}'."
raise ValueError(msg)
self.collection = database[self.collection_name]

self.connection: MongoClient = MongoClient(
resolved_connection_string, driver=DriverInfo(name="MongoDBAtlasHaystackIntegration")
)
database = self.connection[self.database_name]

if collection_name not in database.list_collection_names():
msg = f"Collection '{collection_name}' does not exist in database '{database_name}'."
raise ValueError(msg)
self.collection = database[self.collection_name]
return self._connection

def to_dict(self) -> Dict[str, Any]:
"""
Expand Down

0 comments on commit 7b6752d

Please sign in to comment.