function get_or_create_audit_trail_uid
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.
/tf/active/vicechatdev/CDocs/utils/audit_trail.py
965 - 1001
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
uuiddatetimeloggingtypingjsonCDocsCDocs.dbCDocs.configCDocs.db.schema_managerCDocs.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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function ensure_audit_trail_exists 83.2% similar
-
function get_document_audit_trail 63.5% similar
-
function migrate_audit_events 62.8% similar
-
function log_event 60.1% similar
-
function create_node_with_uid 59.4% similar