🔍 Code Extractor

function update_schema

Maturity: 61

Updates a Neo4j database schema to match a specific version by running base schema initialization and applying version-specific migrations sequentially.

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

Purpose

This function manages database schema migrations for a Neo4j database, allowing the system to upgrade from older schema versions to newer ones. It first initializes the base schema, then conditionally applies version-specific migrations (approval data migration for v1.1.0+, reviewer assignment migration for v1.2.0+) based on the target version. This enables safe, incremental schema upgrades during application updates.

Source Code

def update_schema(driver: Driver, version: str) -> bool:
    """
    Update schema to match a specific version.
    This allows for schema migrations when upgrading.
    
    Args:
        driver: Neo4j driver instance
        version: Target schema version
        
    Returns:
        Boolean indicating success of update
    """
    logger.info(f"Updating schema to version {version}")
    
    try:
        # Run standard schema initialization
        if not initialize_schema(driver):
            logger.error("Failed to initialize base schema")
            return False
            
        # Version-specific migrations
        if version >= "1.1.0":
            # Migrate to multi-step approval model
            migrate_approval_data(driver)
            
        if version >= "1.2.0":
            # Migrate to reviewer assignment model
            migrate_review_assignments(driver)
            
        return True
    except Exception as e:
        logger.error(f"Error updating schema to version {version}: {e}")
        logger.error(traceback.format_exc())
        return False

Parameters

Name Type Default Kind
driver Driver - positional_or_keyword
version str - positional_or_keyword

Parameter Details

driver: A Neo4j Driver instance that provides the connection to the Neo4j database. This driver is used to execute schema initialization and migration queries. Must be a valid, connected Neo4j driver object.

version: A string representing the target schema version to migrate to (e.g., '1.1.0', '1.2.0'). The function uses string comparison to determine which migrations to apply. Expected format is semantic versioning (major.minor.patch).

Return Value

Type: bool

Returns a boolean value indicating the success or failure of the schema update operation. Returns True if the base schema initialization succeeds and all applicable version-specific migrations complete without errors. Returns False if the base schema initialization fails or if any exception occurs during the migration process.

Dependencies

  • neo4j
  • logging
  • traceback
  • typing
  • datetime
  • uuid
  • CDocs

Required Imports

import logging
import traceback
from neo4j import Driver
from CDocs import guard_execution
from CDocs import db

Usage Example

from neo4j import GraphDatabase
import logging

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

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

try:
    # Update schema to version 1.2.0
    target_version = '1.2.0'
    success = update_schema(driver, target_version)
    
    if success:
        print(f'Schema successfully updated to version {target_version}')
    else:
        print('Schema update failed')
finally:
    driver.close()

Best Practices

  • Always backup the Neo4j database before running schema migrations
  • Ensure the Neo4j driver is properly connected and authenticated before calling this function
  • Use semantic versioning format for the version parameter (e.g., '1.2.0')
  • Monitor logs during migration as the function logs detailed information about the migration process
  • Handle the boolean return value to determine if the migration succeeded before proceeding with application logic
  • Test migrations on a non-production database first to verify they work correctly
  • Be aware that version comparisons use string comparison (>=), which may not work correctly for all version formats
  • Ensure that helper functions (initialize_schema, migrate_approval_data, migrate_review_assignments) are properly implemented and available
  • The function applies migrations cumulatively, so migrating to version 1.2.0 will also apply 1.1.0 migrations

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function update_schema_v1 97.0% similar

    Updates a Neo4j database schema to match a specific version, enabling schema migrations during system upgrades.

    From: /tf/active/vicechatdev/CDocs/db/schema_manager.py
  • function update_database_version 78.8% similar

    Updates the database schema version in a Neo4j graph database by setting the version property on a CDocs node and recording the update timestamp.

    From: /tf/active/vicechatdev/CDocs single class/db/schema_manager.py
  • function initialize_schema 72.2% 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 initialize_schema_v1 71.8% similar

    Initializes a Neo4j database schema by creating constraints, indexes, a root CDocs node, audit trail, and migrating approval data and workflow types.

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

    Validates that a Neo4j database schema is correctly configured by checking for required constraints, node labels, and indexes.

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