🔍 Code Extractor

function get_driver

Maturity: 54

Singleton function that initializes and returns a Neo4j database driver instance with connection verification.

File:
/tf/active/vicechatdev/CDocs/db/__init__.py
Lines:
18 - 47
Complexity:
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

  • neo4j
  • CDocs

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function init_connections 70.5% similar

    Initializes and returns a Neo4j database session and driver connection using configuration settings.

    From: /tf/active/vicechatdev/offline_docstore_multi_vice.py
  • function close_driver 67.3% similar

    Safely closes a global database driver connection and sets it to None, with error handling and logging.

    From: /tf/active/vicechatdev/CDocs/db/__init__.py
  • function initialize_schema 57.2% similar

    Initializes the Neo4j database schema by creating required constraints, indexes, root nodes, audit trails, and migrating existing data structures to current schema versions.

    From: /tf/active/vicechatdev/CDocs/db/schema_manager.py
  • function get_manual_relationship_manager 51.9% similar

    Returns a singleton instance of the ManualRelationshipManager class, creating it on first access using lazy initialization.

    From: /tf/active/vicechatdev/full_smartstat/manual_relationships.py
  • function ensure_audit_trail_exists 51.8% similar

    Ensures a singleton AuditTrail node exists in a Neo4j database, creating it if necessary, and returns its unique identifier.

    From: /tf/active/vicechatdev/CDocs/db/schema_manager.py
← Back to Browse