function get_driver
Singleton function that initializes and returns a Neo4j database driver instance with connection verification.
/tf/active/vicechatdev/CDocs/db/__init__.py
18 - 47
moderate
Purpose
This function provides a centralized way to obtain a Neo4j driver instance for database operations. It implements a singleton pattern using a global variable to ensure only one driver instance exists throughout the application lifecycle. The function handles driver initialization, authentication, connection verification, and error logging. It's designed to be called whenever database access is needed, automatically creating the connection on first use.
Source Code
def get_driver() -> Driver:
"""
Get a Neo4j driver instance.
Returns:
Neo4j driver instance
"""
global _driver
if _driver is None:
# Initialize driver
try:
from CDocs.config import settings
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=UserWarning)
uri = settings.DB_URI
auth = (settings.DB_USER, settings.DB_PASSWORD)
logger.info(f"Initializing database connection to {uri}")
_driver = GraphDatabase.driver(uri, auth=auth)
# Verify connectivity
_driver.verify_connectivity()
logger.info("Database connection established successfully")
except Exception as e:
logger.error(f"Error initializing database connection: {e}")
raise
return _driver
Return Value
Type: Driver
Returns a Neo4j Driver instance that can be used to create sessions and execute database queries. The driver is configured with the URI and authentication credentials from the application settings. The same driver instance is returned on subsequent calls (singleton pattern).
Dependencies
neo4jCDocs
Required Imports
from neo4j import GraphDatabase
from neo4j import Driver
import warnings
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
from CDocs.config import settings
Condition: imported lazily inside the function when driver is first initialized
Required (conditional)Usage Example
# Ensure global driver variable exists
_driver = None
logger = logging.getLogger(__name__)
# Get driver instance
driver = get_driver()
# Use driver to create a session and run queries
with driver.session() as session:
result = session.run("MATCH (n) RETURN count(n) as count")
count = result.single()['count']
print(f"Total nodes: {count}")
# Subsequent calls return the same driver instance
driver2 = get_driver()
assert driver is driver2 # True - same instance
Best Practices
- This function uses a global variable '_driver' which must be declared in the module scope before calling the function
- The function implements lazy initialization - the driver is only created on first call
- Connection verification is performed automatically to ensure the database is accessible
- UserWarnings are suppressed during initialization to avoid cluttering logs
- Always handle potential exceptions when calling this function, as it may raise errors during connection
- The driver should be closed properly when the application shuts down using driver.close()
- This is a singleton pattern - the same driver instance is reused across the application
- Ensure CDocs.config.settings is properly configured with valid database credentials before calling
- The function logs connection status at INFO level and errors at ERROR level
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function init_connections 70.5% similar
-
function close_driver 67.3% similar
-
function initialize_schema 57.2% similar
-
function get_manual_relationship_manager 51.9% similar
-
function ensure_audit_trail_exists 51.8% similar