🔍 Code Extractor

function get_document_v5

Maturity: 47

Retrieves all versions of a controlled document from a Neo4j graph database, including metadata about which version is current.

File:
/tf/active/vicechatdev/CDocs/db/db_operations.py
Lines:
981 - 1051
Complexity:
moderate

Purpose

This function queries a Neo4j database to fetch all versions associated with a specific controlled document identified by its UID. It returns a list of version dictionaries with normalized field names (both camelCase and snake_case) and marks which version is the current one. The function handles errors gracefully and returns an empty list if no versions are found or if an error occurs.

Source Code

def get_document_versions_from_db(document_uid):
    """
    Get all versions for a document from the database.
    
    Parameters
    ----------
    document_uid : str
        Document UID
        
    Returns
    -------
    list
        List of version dictionaries
    """
    try:
        #logger.info(f"Getting versions for document {document_uid}")
        
        # Query for versions
        query = """
        MATCH (d:ControlledDocument)-[:HAS_VERSION]->(v:DocumentVersion)
        WHERE d.UID = $doc_uid
        OPTIONAL MATCH (d)-[:CURRENT_VERSION]->(cv:DocumentVersion)
        RETURN v as version, 
               (CASE WHEN v.UID = cv.UID THEN true ELSE false END) as is_current
        ORDER BY v.versionNumber DESC
        """
        
        params = {"doc_uid": document_uid}
        
        result = run_query(query, params)
        
        if not result:
            logger.warning(f"No versions found for document {document_uid}")
            return []
            
        # Process results
        versions = []
        for record in result:
            version_data = record.get("version")
            is_current = record.get("is_current", False)
            
            if version_data:
                # Make a copy of the version data
                version = dict(version_data)
                
                # Add additional properties
                version["is_current"] = is_current
                
                # Ensure key fields exist with consistent names
                if "versionNumber" in version and "version_number" not in version:
                    version["version_number"] = version["versionNumber"]
                    
                if "createdDate" in version and "created_date" not in version:
                    version["created_date"] = version["createdDate"]
                    
                if "creatorName" in version and "created_by_name" not in version:
                    version["created_by_name"] = version["creatorName"]
                    
                if "fileName" in version and "file_name" not in version:
                    version["file_name"] = version["fileName"]
                
                versions.append(version)
                
        #logger.info(f"Found {len(versions)} versions for document {document_uid}")
        return versions
        
    except Exception as e:
        logger.error(f"Error getting document versions from DB: {e}")
        import traceback
        logger.error(traceback.format_exc())
        return []

Parameters

Name Type Default Kind
document_uid - - positional_or_keyword

Parameter Details

document_uid: String identifier (UID) of the controlled document whose versions should be retrieved. This should be a valid UID that exists in the Neo4j database as a ControlledDocument node property.

Return Value

Returns a list of dictionaries, where each dictionary represents a document version. Each version dictionary contains properties from the DocumentVersion node (like UID, versionNumber/version_number, createdDate/created_date, creatorName/created_by_name, fileName/file_name) and an additional 'is_current' boolean field indicating if that version is the current version. Returns an empty list if no versions are found or if an error occurs. The list is sorted by version number in descending order (newest first).

Dependencies

  • neo4j
  • logging
  • typing
  • datetime
  • traceback
  • CDocs.db
  • CDocs.db.schema_manager

Required Imports

import logging
from neo4j import Driver, Session, Transaction, Record
from neo4j.exceptions import ServiceUnavailable, ClientError
from CDocs.db import get_driver
from CDocs.db.schema_manager import NodeLabels, RelTypes

Conditional/Optional Imports

These imports are only needed under specific conditions:

import traceback

Condition: imported inside exception handler for detailed error logging

Required (conditional)

Usage Example

# Assuming Neo4j connection is configured and run_query function exists
import logging
from CDocs.db import get_driver

# Setup logger
logger = logging.getLogger(__name__)

# Get versions for a specific document
document_uid = "doc-12345-abcde"
versions = get_document_versions_from_db(document_uid)

if versions:
    print(f"Found {len(versions)} versions")
    for version in versions:
        version_num = version.get('version_number', 'Unknown')
        is_current = version.get('is_current', False)
        created_date = version.get('created_date', 'Unknown')
        print(f"Version {version_num} - Current: {is_current} - Created: {created_date}")
else:
    print("No versions found or error occurred")

Best Practices

  • Always check if the returned list is empty before processing versions
  • The function returns both camelCase and snake_case field names for compatibility - use the naming convention that matches your codebase
  • The function handles exceptions internally and logs errors, but returns an empty list on failure - implement additional error handling if needed
  • Ensure the run_query function is properly implemented and handles Neo4j connection management
  • The is_current flag is computed in the query and added to each version dictionary for easy identification of the current version
  • Results are sorted by version number in descending order, so the first item in the list is typically the newest version
  • The function depends on a module-level logger object - ensure logging is configured before calling this function

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_document_v6 87.3% similar

    Retrieves all versions of a document from the database given its unique identifier (UID).

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function get_document_v2 80.6% similar

    Retrieves detailed information about a specific document version by its UID, including associated document context and version status.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function get_document_v1 76.6% similar

    Retrieves comprehensive details of a controlled document by its UID, including optional version history, review cycles, and approval workflows.

    From: /tf/active/vicechatdev/CDocs/controllers/document_controller.py
  • function get_document_with_relationships 75.9% similar

    Retrieves a complete document from Neo4j graph database along with all its related entities including versions, reviews, approvals, and authors.

    From: /tf/active/vicechatdev/CDocs/db/db_operations.py
  • function get_document 75.6% similar

    Retrieves comprehensive details of a controlled document by its UID, with optional inclusion of version history, review cycles, and approval cycles.

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