🔍 Code Extractor

function update_review_comment_relationships

Maturity: 56

Migrates Neo4j ReviewComment nodes to use explicit parent/child relationships (PARENT_COMMENT and HAS_REPLY) based on existing parent_comment_uid properties.

File:
/tf/active/vicechatdev/CDocs single class/db/schema_manager.py
Lines:
741 - 800
Complexity:
moderate

Purpose

This function performs a database migration to update the ReviewComment graph structure in Neo4j. It identifies comments that have a parent_comment_uid property but lack the corresponding relationship edges, then creates bidirectional PARENT_COMMENT and HAS_REPLY relationships between child and parent comments. This is typically used during schema migrations to transition from property-based parent references to relationship-based graph structures.

Source Code

def update_review_comment_relationships(driver: Driver) -> Dict:
    """
    Update review comment relationships to use the new parent/child model.
    
    Args:
        driver: Neo4j driver instance
        
    Returns:
        Dict containing migration results
    """
    try:
        with driver.session() as session:
            # Check if any comments have parent_comment_uid but no relationship
            result = session.run(
                """
                MATCH (c:ReviewComment)
                WHERE exists(c.parent_comment_uid) AND c.parent_comment_uid IS NOT NULL
                AND NOT EXISTS((c)-[:PARENT_COMMENT]->(:ReviewComment))
                RETURN count(c) as count
                """
            )
            record = result.single()
            
            if not record or record["count"] == 0:
                return {
                    "success": True,
                    "message": "No comment relationships need updating",
                    "updated_count": 0
                }
            
            # Update comments with parent_comment_uid to have proper relationship
            update_query = """
            MATCH (c:ReviewComment)
            WHERE exists(c.parent_comment_uid) AND c.parent_comment_uid IS NOT NULL
            AND NOT EXISTS((c)-[:PARENT_COMMENT]->())
            
            MATCH (p:ReviewComment {UID: c.parent_comment_uid})
            
            CREATE (c)-[:PARENT_COMMENT]->(p)
            CREATE (p)-[:HAS_REPLY]->(c)
            
            RETURN count(c) as updated
            """
            
            result = session.run(update_query)
            record = result.single()
            
            return {
                "success": True,
                "message": f"Successfully updated {record['updated']} comment relationships",
                "updated_count": record["updated"]
            }
    except Exception as e:
        logger.error(f"Error updating comment relationships: {e}")
        logger.error(traceback.format_exc())
        return {
            "success": False,
            "message": f"Error: {str(e)}",
            "updated_count": 0
        }

Parameters

Name Type Default Kind
driver Driver - positional_or_keyword

Parameter Details

driver: A Neo4j Driver instance used to establish database connections and execute Cypher queries. Must be an active, authenticated driver connected to the target Neo4j database containing ReviewComment nodes.

Return Value

Type: Dict

Returns a dictionary with three keys: 'success' (bool indicating whether the migration completed without errors), 'message' (str describing the outcome or error details), and 'updated_count' (int representing the number of comment relationships successfully created). On success with no updates needed, updated_count is 0. On error, success is False and message contains the exception details.

Dependencies

  • neo4j
  • logging
  • traceback
  • typing
  • CDocs

Required Imports

from neo4j import Driver
from typing import Dict
import logging
import traceback

Usage Example

from neo4j import GraphDatabase
from typing import Dict
import logging

# Setup logger
logger = logging.getLogger(__name__)

# Create Neo4j driver
driver = GraphDatabase.driver(
    'bolt://localhost:7687',
    auth=('neo4j', 'password')
)

try:
    # Run the migration
    result = update_review_comment_relationships(driver)
    
    if result['success']:
        print(f"Migration successful: {result['message']}")
        print(f"Updated {result['updated_count']} relationships")
    else:
        print(f"Migration failed: {result['message']}")
finally:
    driver.close()

Best Practices

  • Always close the Neo4j driver after migration completes to free resources
  • Run this migration in a transaction-safe environment or during maintenance windows
  • Verify the migration results by checking the returned updated_count matches expectations
  • Ensure the logger is properly configured before calling this function to capture error details
  • Test the migration on a backup or staging database before running in production
  • The function is idempotent - it only creates relationships where they don't exist, so it's safe to run multiple times
  • Monitor the database for performance impact if migrating large numbers of comments
  • Ensure parent ReviewComment nodes exist before running to avoid orphaned references

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function migrate_review_assignments 78.3% similar

    Migrates legacy review data from direct REVIEWED_BY relationships to a new ReviewerAssignment node model in a Neo4j graph database.

    From: /tf/active/vicechatdev/CDocs single class/db/schema_manager.py
  • function migrate_approval_cycles 66.1% similar

    Migrates legacy Approval nodes and their related structures to the new ApprovalCycle model in a Neo4j graph database, creating ApprovalCycle nodes and ApproverAssignment nodes while maintaining relationships with DocumentVersion nodes.

    From: /tf/active/vicechatdev/CDocs/db/schema_manager.py
  • function migrate_approval_data 64.8% similar

    Migrates legacy single-step approval records in Neo4j to a new multi-step approval model by creating ApprovalStep nodes and Approver nodes with proper relationships.

    From: /tf/active/vicechatdev/CDocs/db/schema_manager.py
  • function migrate_approval_data_v1 64.0% similar

    Migrates legacy single-step approval records in Neo4j to a new multi-step approval model by creating ApprovalStep nodes and Approver nodes with proper relationships.

    From: /tf/active/vicechatdev/CDocs single class/db/schema_manager.py
  • function migrate_audit_events 62.1% similar

    Migrates orphaned AuditEvent nodes from CDocs nodes to an AuditTrail node in a Neo4j graph database by deleting old relationships and creating new ones.

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