🔍 Code Extractor

function get_or_create_audit_trail_uid

Maturity: 53

Retrieves the UID of an existing AuditTrail node from a Neo4j database, or creates a new AuditTrail node with a generated UID if one doesn't exist.

File:
/tf/active/vicechatdev/CDocs/utils/audit_trail.py
Lines:
965 - 1001
Complexity:
moderate

Purpose

This function ensures that an AuditTrail node exists in the Neo4j database for tracking audit events. It implements a get-or-create pattern to maintain a singleton AuditTrail node. The function first queries for an existing AuditTrail node, returns its UID if found, or creates a new one with a UUID and timestamp if not found. It includes error handling that falls back to generating a new UID even if database operations fail.

Source Code

def get_or_create_audit_trail_uid() -> str:
    """
    Get the UID of the AuditTrail node, creating it if it doesn't exist.
    
    Returns:
        str: UID of the AuditTrail node
    """
    try:
        # Check if audit trail exists
        result = db.run_query(
            """
            MATCH (t:AuditTrail)
            RETURN t.UID as uid
            LIMIT 1
            """
        )
        
        # If we found an existing audit trail node, return its UID
        if result and len(result) > 0 and 'uid' in result[0]:
            return result[0]['uid']
        
        # No audit trail found, create a new one
        audit_trail_uid = str(uuid.uuid4())
        
        # Create the audit trail node
        db.create_node(NodeLabels.AUDIT_TRAIL, {
            "UID": audit_trail_uid,
            "createdDate": datetime.now()
        })
        
        logger.info(f"Created new AuditTrail node with UID {audit_trail_uid}")
        return audit_trail_uid
        
    except Exception as e:
        logger.error(f"Error getting or creating audit trail: {e}")
        # Fallback to generating a new UID, even though the node creation might have failed
        return str(uuid.uuid4())

Return Value

Type: str

Returns a string containing the UID (Unique Identifier) of the AuditTrail node. This will be either the UID of an existing AuditTrail node found in the database, or a newly generated UUID v4 string if a new node was created or if an error occurred during database operations.

Dependencies

  • uuid
  • datetime
  • logging
  • typing
  • json
  • CDocs
  • CDocs.db
  • CDocs.config
  • CDocs.db.schema_manager
  • CDocs.models.user_extensions

Required Imports

import uuid
from datetime import datetime
import logging
from CDocs import db
from CDocs.db.schema_manager import NodeLabels

Usage Example

import logging
import uuid
from datetime import datetime
from CDocs import db
from CDocs.db.schema_manager import NodeLabels

# Ensure logger is configured
logger = logging.getLogger(__name__)

# Get or create the audit trail UID
audit_trail_uid = get_or_create_audit_trail_uid()
print(f"AuditTrail UID: {audit_trail_uid}")

# Use the UID for subsequent audit operations
# For example, linking audit events to this trail
db.create_relationship(
    audit_event_uid,
    audit_trail_uid,
    'BELONGS_TO_TRAIL'
)

Best Practices

  • This function assumes a singleton pattern for AuditTrail nodes - only one should exist in the database
  • The function includes error handling that returns a UUID even on failure, which may lead to orphaned audit data if the database operation fails
  • Ensure the database connection is established before calling this function
  • The logger instance must be defined in the module scope before calling this function
  • Consider wrapping calls to this function in a try-except block for additional error handling in production environments
  • The function uses LIMIT 1 in the query, assuming only one AuditTrail node should exist
  • If multiple AuditTrail nodes exist in the database, only the first one found will be returned
  • The createdDate property is set using datetime.now() which uses the server's local timezone

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function ensure_audit_trail_exists 83.2% similar

    Ensures a singleton AuditTrail node exists in a Neo4j database, creating it if necessary, and returns its unique identifier.

    From: /tf/active/vicechatdev/CDocs/db/schema_manager.py
  • function get_document_audit_trail 63.5% similar

    Retrieves the complete audit trail for a controlled document from a Neo4j graph database, including timestamps, user actions, and event details.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function migrate_audit_events 62.8% 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
  • function log_event 60.1% similar

    Creates and persists an audit trail event in a Neo4j graph database, linking it to users, resources, and an audit trail node with comprehensive event metadata.

    From: /tf/active/vicechatdev/CDocs/utils/audit_trail.py
  • function create_node_with_uid 59.4% similar

    Creates a new node in a Neo4j graph database with a specified UID, label, and properties, automatically adding a creation timestamp if not provided.

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