function execute_transaction
Executes a database transaction function within a Neo4j session, handling connection management and error logging automatically.
/tf/active/vicechatdev/CDocs/db/db_operations.py
691 - 710
moderate
Purpose
This function provides a wrapper for executing Neo4j database transactions with automatic session and driver management. It takes a transaction function as input, obtains a database driver, creates a session, and executes the function within a write transaction context. It handles exceptions by logging errors and re-raising them for upstream handling. This is useful for ensuring consistent transaction handling across the application and reducing boilerplate code for database operations.
Source Code
def execute_transaction(tx_function, *args, **kwargs) -> Any:
"""
Execute a function within a database transaction.
Args:
tx_function: Function that takes a transaction object as first parameter
*args: Additional positional arguments to pass to tx_function
**kwargs: Additional keyword arguments to pass to tx_function
Returns:
Result of the transaction function
"""
try:
driver = get_driver()
with driver.session() as session:
return session.execute_write(lambda tx: tx_function(tx, *args, **kwargs))
except Exception as e:
logger.error(f"Error executing transaction: {e}")
raise
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
tx_function |
- | - | positional_or_keyword |
*args |
- | - | var_positional |
**kwargs |
- | - | var_keyword |
Parameter Details
tx_function: A callable function that accepts a Neo4j Transaction object as its first parameter. This function contains the database operations to be executed within the transaction context. The transaction object provides methods like run() for executing Cypher queries.
*args: Variable length positional arguments that will be forwarded to tx_function after the transaction object. These allow passing additional data or parameters needed by the transaction function.
**kwargs: Variable length keyword arguments that will be forwarded to tx_function after the transaction object. These provide named parameters for more explicit function calls within the transaction.
Return Value
Type: Any
Returns the result of executing tx_function, which can be of Any type depending on what the transaction function returns. Common return types include Neo4j Record objects, lists of records, processed data structures, or None for operations that don't return data. The return value is passed through unchanged from the transaction function.
Dependencies
neo4jloggingtyping
Required Imports
from typing import Any
import logging
from neo4j import Driver
from CDocs.db import get_driver
Usage Example
from typing import Any
from neo4j import Transaction
from CDocs.db import get_driver
import logging
logger = logging.getLogger(__name__)
def execute_transaction(tx_function, *args, **kwargs) -> Any:
try:
driver = get_driver()
with driver.session() as session:
return session.execute_write(lambda tx: tx_function(tx, *args, **kwargs))
except Exception as e:
logger.error(f"Error executing transaction: {e}")
raise
# Define a transaction function
def create_user(tx: Transaction, name: str, email: str):
query = "CREATE (u:User {name: $name, email: $email}) RETURN u"
result = tx.run(query, name=name, email=email)
return result.single()[0]
# Execute the transaction
user = execute_transaction(create_user, "John Doe", "john@example.com")
print(f"Created user: {user}")
# Example with keyword arguments
def update_user(tx: Transaction, user_id: str, **properties):
query = "MATCH (u:User {id: $user_id}) SET u += $props RETURN u"
result = tx.run(query, user_id=user_id, props=properties)
return result.single()[0]
updated_user = execute_transaction(update_user, "123", age=30, city="New York")
Best Practices
- Always ensure tx_function accepts a Transaction object as its first parameter
- The transaction function should be idempotent when possible, as Neo4j may retry failed transactions
- Keep transactions short and focused to avoid locking issues and improve performance
- Handle specific Neo4j exceptions (ServiceUnavailable, ClientError) in calling code for better error recovery
- The function re-raises exceptions after logging, so ensure proper exception handling in calling code
- Use execute_write for write operations; consider creating a separate execute_read function for read-only operations to optimize performance
- Ensure get_driver() returns a properly configured Neo4j driver instance
- Configure logging appropriately to capture transaction errors for debugging
- Avoid long-running operations within transactions to prevent timeout issues
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function transaction 58.5% similar
-
function run_query_v2 47.7% similar
-
function run_query_v1 44.9% similar
-
function run_with_timeout 41.7% similar
-
function create_dbo_tnv 40.6% similar