function close_driver
Safely closes a global database driver connection and sets it to None, with error handling and logging.
/tf/active/vicechatdev/CDocs/db/__init__.py
49 - 60
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
loggingneo4j
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function get_driver 67.3% similar
-
function init_connections 58.2% similar
-
class Neo4jManager 50.3% similar
-
function initialize_schema 49.8% similar
-
function validate_schema 46.4% similar