function test_connection
Tests the database connection by executing a simple query and validating the result.
/tf/active/vicechatdev/CDocs/db/db_operations.py
964 - 979
simple
Purpose
This function verifies that the database connection is working properly by running a minimal test query ('RETURN 1 as test') and checking if the expected result is returned. It's typically used for health checks, initialization validation, or troubleshooting database connectivity issues. The function handles exceptions gracefully and logs errors when connection tests fail.
Source Code
def test_connection():
"""
Test the database connection.
Returns
-------
bool
True if connection is successful, False otherwise
"""
try:
# Simple query to test connection
result = run_query("RETURN 1 as test")
return result and 'test' in result[0] and result[0]['test'] == 1
except Exception as e:
logger.error(f"Database connection test failed: {str(e)}")
return False
Return Value
Returns a boolean value: True if the database connection is successful and the test query returns the expected result (a record with 'test' key equal to 1), False if the connection fails, the query fails, or any exception occurs during the test.
Dependencies
loggingneo4jCDocs.dbCDocs.db.schema_manager
Required Imports
import logging
from CDocs.db import get_driver
Usage Example
import logging
from CDocs.db import get_driver
# Setup logger
logger = logging.getLogger(__name__)
# Assume run_query function exists
def run_query(query, parameters=None):
driver = get_driver()
with driver.session() as session:
result = session.run(query, parameters or {})
return [record.data() for record in result]
# Test the connection
if test_connection():
print("Database connection successful")
else:
print("Database connection failed")
Best Practices
- Ensure the 'logger' object is properly initialized before calling this function
- The 'run_query' function must be defined or imported in the same module
- This function should be called during application startup or as part of health check endpoints
- Use this function before performing critical database operations to ensure connectivity
- The function catches all exceptions, so check logs for detailed error information if it returns False
- Consider calling this function periodically in long-running applications to monitor database connectivity
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function test_connection_string 57.3% similar
-
function test_odbc_driver 56.5% similar
-
function test_filecloud_connection_v1 54.2% similar
-
function test_filecloud_connection 53.9% similar
-
function test_sharepoint_connection 53.8% similar