function check_document_exists_by_doc_number
Queries a Neo4j database to check if a ControlledDocument exists with a specific document number and returns the document object if found.
/tf/active/vicechatdev/CDocs/FC_sync.py
110 - 138
simple
Purpose
This function provides a lookup mechanism to verify document existence in a Neo4j graph database by document number. It's used for validation before creating new documents, checking duplicates, or retrieving existing documents by their unique identifier. The function handles database errors gracefully and returns None if the document doesn't exist or if an error occurs.
Source Code
def check_document_exists_by_doc_number(doc_number: str) -> Optional[ControlledDocument]:
"""
Check if a document with the given document number exists in the Neo4j database.
Args:
doc_number: Document number to check
Returns:
ControlledDocument: Document object if found, None otherwise
"""
try:
result = db.run_query(
"""
MATCH (doc:ControlledDocument)
WHERE doc.docNumber = $doc_number
RETURN doc
LIMIT 1
""",
{"doc_number": doc_number}
)
if result and len(result) > 0:
doc = ControlledDocument(result[0]['doc'])
return doc
return None
except Exception as e:
logger.error(f"Error checking document existence by number: {e}")
return None
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
doc_number |
str | - | positional_or_keyword |
Parameter Details
doc_number: A string representing the unique document number to search for in the Neo4j database. This should match the 'docNumber' property of ControlledDocument nodes. Expected to be a non-empty string identifier.
Return Value
Type: Optional[ControlledDocument]
Returns an Optional[ControlledDocument] type. If a document with the matching document number is found, returns a ControlledDocument object instantiated from the database result. Returns None if no document is found, if the database query returns empty results, or if any exception occurs during the query execution.
Dependencies
loggingtypingCDocs.db.db_operationsCDocs.models.document
Required Imports
from typing import Optional
from CDocs.db import db_operations as db
from CDocs.models.document import ControlledDocument
import logging
Usage Example
from typing import Optional
from CDocs.db import db_operations as db
from CDocs.models.document import ControlledDocument
import logging
logger = logging.getLogger(__name__)
# Check if a document exists
doc_number = "DOC-2024-001"
document = check_document_exists_by_doc_number(doc_number)
if document:
print(f"Document found: {document.docNumber}")
# Access document properties
print(f"Document ID: {document.id}")
else:
print(f"No document found with number: {doc_number}")
# Proceed with creating new document
# Use in validation workflow
def create_new_document(doc_number: str, **kwargs):
existing_doc = check_document_exists_by_doc_number(doc_number)
if existing_doc:
raise ValueError(f"Document {doc_number} already exists")
# Create new document logic here
pass
Best Practices
- Always check if the returned value is None before accessing document properties to avoid AttributeError
- This function logs errors but doesn't raise exceptions, so check logs if None is returned unexpectedly
- The function uses LIMIT 1 in the query for performance optimization, assuming document numbers are unique
- Ensure the db_operations module's run_query method is properly initialized with Neo4j connection before calling this function
- Consider caching results if this function is called frequently with the same doc_number to reduce database load
- The function returns None on any exception, so it may mask database connectivity issues - monitor logs for errors
- Document numbers should be unique in the database schema; enforce this constraint at the database level
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function check_document_exists_by_uid 75.1% similar
-
function validate_document_number 74.0% similar
-
function generate_document_number 58.6% similar
-
function check_document_hash_exists 57.5% similar
-
function search_documents_v1 57.4% similar