🔍 Code Extractor

function initialize_document_counters

Maturity: 57

Initializes document counters in Neo4j by analyzing existing ControlledDocument nodes and creating DocumentCounter nodes with values higher than the maximum existing document numbers for each department/type combination.

File:
/tf/active/vicechatdev/CDocs/db/schema_manager.py
Lines:
689 - 755
Complexity:
moderate

Purpose

This function ensures that document numbering sequences are properly initialized based on existing documents in the database. It prevents duplicate document numbers by setting counter values to one more than the highest existing document number for each unique department and document type combination. This is typically used during system initialization or migration to establish proper counter state.

Source Code

def initialize_document_counters(driver: Driver) -> bool:
    """
    Initialize document counters based on existing documents.
    This ensures counters start at values higher than existing documents.
    
    Args:
        driver: Neo4j driver instance
        
    Returns:
        Boolean indicating success
    """
    try:
        with driver.session() as session:
            # Find the CDocs node
            cdocs_result = session.run("MATCH (c:CDocs) RETURN c.UID AS uid LIMIT 1")
            cdocs_record = cdocs_result.single()
            
            if not cdocs_record:
                logger.warning("CDocs node not found, cannot initialize document counters")
                return False
                
            cdocs_uid = cdocs_record["uid"]
            
            # Get highest document number for each department/type combination
            result = session.run(
                """
                MATCH (d:ControlledDocument)
                WITH d.docType as docType, d.department as department, 
                     COUNT(d) as docCount, MAX(d.docNumber) as maxDocNum
                WHERE docCount > 0
                
                // Extract numeric part from doc number using regex
                WITH docType, department, maxDocNum,
                     CASE 
                        WHEN maxDocNum =~ '.*-(\\d+)$' 
                        THEN toInteger(
                            REDUCE(s = "", x IN split(maxDocNum, '-') | 
                                CASE WHEN x = last(split(maxDocNum, '-')) THEN x ELSE s END)
                        )
                        ELSE 1
                     END as maxNum
                
                MATCH (c:CDocs {UID: $cdocs_uid})
                MERGE (c)-[:HAS_COUNTER]->(counter:DocumentCounter {department: department, docType: docType})
                ON CREATE SET 
                    counter.UID = randomUUID(),
                    counter.value = maxNum + 1,
                    counter.currentYear = date().year,
                    counter.createdDate = datetime(),
                    counter.lastUpdated = datetime()
                    
                RETURN count(counter) as initialized
                """,
                {"cdocs_uid": cdocs_uid}
            )
            
            record = result.single()
            initialized = record["initialized"] if record else 0
            
            logger.info(f"Initialized {initialized} document counters from existing documents")
            return True
            
    except Exception as e:
        logger.error(f"Error initializing document counters: {e}")
        import traceback
        logger.error(traceback.format_exc())
        return False

Parameters

Name Type Default Kind
driver Driver - positional_or_keyword

Parameter Details

driver: A Neo4j Driver instance used to establish database connections. This should be an active, authenticated driver object capable of creating sessions to execute Cypher queries against the Neo4j database.

Return Value

Type: bool

Returns a boolean value: True if the counter initialization process completed successfully (even if zero counters were initialized), False if an error occurred (such as missing CDocs node or database connection issues).

Dependencies

  • neo4j
  • logging
  • uuid
  • typing
  • traceback

Required Imports

from neo4j import Driver
import logging
import traceback

Conditional/Optional Imports

These imports are only needed under specific conditions:

import traceback

Condition: only used in exception handling to log detailed error traces

Required (conditional)

Usage Example

from neo4j import GraphDatabase
import logging

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

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

try:
    # Initialize document counters
    success = initialize_document_counters(driver)
    
    if success:
        print('Document counters initialized successfully')
    else:
        print('Failed to initialize document counters')
finally:
    driver.close()

Best Practices

  • Ensure the CDocs node exists in the database before calling this function
  • Run this function during system initialization or after data migration to establish proper counter state
  • The function expects document numbers to end with a hyphen followed by digits (e.g., 'DOC-TYPE-123')
  • Always close the Neo4j driver after use to prevent connection leaks
  • Monitor the logger output to verify the number of counters initialized
  • This function uses MERGE to avoid creating duplicate counters, making it safe to run multiple times
  • The function sets counter values to maxNum + 1 to ensure new documents don't conflict with existing ones
  • Consider running this function in a transaction if coordinating with other database operations

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function initialize_schema 67.8% 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 generate_document_number 63.8% similar

    Generates unique, sequential document numbers for a given document type and department using persistent counters stored in Neo4j database.

    From: /tf/active/vicechatdev/CDocs/settings_prod.py
  • function get_next_document_number 61.3% similar

    Atomically retrieves and increments the next sequential document number for a specific document type and department combination from a Neo4j graph database.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function init_database 59.0% similar

    Initializes a Neo4j database with required schema constraints, creates an AuditTrail node, and migrates existing audit events.

    From: /tf/active/vicechatdev/CDocs/db/__init__.py
  • function _generate_document_number_fallback 58.6% similar

    Generates a fallback document number using in-memory counters when database access fails, creating unique identifiers based on document type, department, and year.

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