🔍 Code Extractor

function close_driver

Maturity: 49

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

File:
/tf/active/vicechatdev/CDocs/db/__init__.py
Lines:
49 - 60
Complexity:
simple

Purpose

This function provides a clean shutdown mechanism for a Neo4j database driver connection. It ensures proper resource cleanup by closing the driver connection, logging the operation, and handling any exceptions that may occur during closure. The function manages a global _driver variable and guarantees it's set to None after closure attempts, preventing resource leaks and ensuring the application can safely terminate or reinitialize the connection.

Source Code

def close_driver() -> None:
    """Close the database driver if it exists."""
    global _driver
    
    if (_driver is not None):
        try:
            _driver.close()
            logger.info("Database connection closed")
        except Exception as e:
            logger.error(f"Error closing database connection: {e}")
        finally:
            _driver = None

Return Value

Type: None

Returns None. This function performs side effects (closing the driver and modifying the global _driver variable) but does not return any value.

Dependencies

  • logging
  • neo4j

Required Imports

import logging
from neo4j import Driver

Usage Example

import logging
from neo4j import GraphDatabase, Driver

# Setup logger
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

# Initialize global driver
_driver = None

def close_driver() -> None:
    """Close the database driver if it exists."""
    global _driver
    
    if (_driver is not None):
        try:
            _driver.close()
            logger.info("Database connection closed")
        except Exception as e:
            logger.error(f"Error closing database connection: {e}")
        finally:
            _driver = None

# Example usage
_driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))
# ... perform database operations ...
close_driver()  # Clean shutdown of database connection

Best Practices

  • Always call this function before application shutdown to ensure proper resource cleanup
  • This function should be called after all database operations are complete
  • The function is idempotent - it can be safely called multiple times without side effects
  • Ensure the global _driver variable is properly initialized before calling this function
  • Use this in conjunction with a context manager or try-finally block to guarantee cleanup
  • The function uses a finally block to ensure _driver is set to None even if closing fails
  • Consider calling this function in signal handlers or application exit hooks for graceful shutdown

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_driver 67.3% similar

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

    From: /tf/active/vicechatdev/CDocs/db/__init__.py
  • function init_connections 58.2% similar

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

    From: /tf/active/vicechatdev/offline_docstore_multi_vice.py
  • class Neo4jManager 50.3% similar

    A manager class that provides a high-level interface for interacting with Neo4j graph databases, handling connections, queries, node creation, and relationship management.

    From: /tf/active/vicechatdev/QA_updater/knowledge_store/neo4j_manager.py
  • function initialize_schema 49.8% 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 validate_schema 46.4% similar

    Validates that a Neo4j database schema contains all required constraints and node labels for a controlled document management system.

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