🔍 Code Extractor

function test_connection

Maturity: 44

Tests the database connection by executing a simple query and validating the result.

File:
/tf/active/vicechatdev/CDocs/db/db_operations.py
Lines:
964 - 979
Complexity:
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

  • logging
  • neo4j
  • CDocs.db
  • CDocs.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

    Tests the format and creation of a SQL Server connection string using SQLAlchemy with ODBC Driver 18, without establishing an actual database connection.

    From: /tf/active/vicechatdev/full_smartstat/test_odbc.py
  • function test_odbc_driver 56.5% similar

    Tests the availability of ODBC drivers on the system, specifically checking for SQL Server drivers and returning a boolean indicating whether SQL Server drivers are found.

    From: /tf/active/vicechatdev/full_smartstat/test_odbc.py
  • function test_filecloud_connection_v1 54.2% similar

    Tests the connection to a FileCloud server by attempting to instantiate a FileCloudClient with credentials from configuration.

    From: /tf/active/vicechatdev/SPFCsync/test_connections.py
  • function test_filecloud_connection 53.9% similar

    Tests the connection to a FileCloud server by establishing a client connection and performing a document search operation to verify functionality.

    From: /tf/active/vicechatdev/contract_validity_analyzer/test_implementation.py
  • function test_sharepoint_connection 53.8% similar

    Tests the connection to a SharePoint site by attempting to instantiate a SharePointClient with Azure credentials and configuration settings.

    From: /tf/active/vicechatdev/SPFCsync/test_connections.py
← Back to Browse