Whatever message this page gives is out now! Go check it out!

WriteDump

Last update:
May 18, 2026

Description

A function equivalent to the <cfdump> tag which can be used in <cfscript>.

Parameters

Same as <cfdump> tag.

Category

Function syntax

WriteDump (var, output, format, abort, label, metainfo, top, show, hide, keys, expand, showUDFs);

See also

History

ColdFusion 11: Parameters passed to this function needs to be in a comma-separated format.
ColdFusion 9: Added this function.

Usage

You can call this function providing arguments as name-value pair or as positional arguments .For positional notations, the sequence must be followed exactly in the same manner as provided in the syntax. If you do not provide one of the parameters, use an empty string instead. This does not apply to Boolean values for which you must provide proper values even if you have to skip them.

Example 1

 
<cfscript>
    myArr=listToArray("The,Quick,Brown,Fox,Jumps,Over,The,Lazy,Dog")
    writeDump(var="#myArr#",format="text")
</cfscript>
Output
array

1) The

2) Quick

3) Brown

4) Fox

5) Jumps

6) Over

7) The

8) Lazy

9) Dog
Example 2
 
<cfscript>
    myArr=listToArray("The,Quick,Brown,Fox,Jumps,Over,The,Lazy,Dog")
    writeDump(var="#myArr#",output="browser",format="text",label="WriteDump example")
</cfscript>
Output
WriteDump example - array

1) The

2) Quick

3) Brown

4) Fox

5) Jumps

6) Over

7) The

8) Lazy

9) Dog
Example 3
 
<cfscript> 
 filename = "log.txt"; 
 try { 
  result = FileOpen(expandpath(filename)); 
  WriteDump(result); 
 } 
 catch(Expression exception) { 
 WriteOutput("<p>An Expression exception was thrown.</p>"); 
 WriteOutput("<p>#exception.message#</p>"); 
 WriteLog(type="Error", file="myapp.log", text="[exception.type] #exception.message#"); 
 } 
</cfscript>
Output
An Expression exception was thrown.
File or directory /shared/cffiddle/cffiddle/c85fa036-5a93-423a-b748-4f0852e91d64/b0faac60-e774-4e5c-aff0-ce794e966d29/log.txt does not exist.

Real-world uses of the WriteDump function

Application development and debugging

Development teams building complex ColdFusion applications need comprehensive debugging capabilities to inspect variables, data structures, and application state during development and testing phases. Manual variable inspection through WriteOutput is time-intensive and incomplete. Complex data structures (structs, arrays, queries) are difficult to visualize and debug. Use WriteDump to instantly visualize any ColdFusion variable with complete structure details, data types, and nested relationships for rapid debugging.
<cfscript>
    // Sample user profile data from registration form
    userProfile = {
        "id": 12345,
        "personalInfo": {
            "firstName": "John",
            "lastName": "Doe", 
            "email": "john.doe@company.com",
            "phone": "+1-555-0123"
        },
        "preferences": {
            "theme": "dark",
            "language": "en-US",
            "notifications": {
                "email": true,
                "sms": false,
                "push": true
            },
            "privacy": {
                "profileVisible": true,
                "shareData": false
            }
        },
        "permissions": ["read", "write", "comment"],
        "accountStatus": "active",
        "lastLogin": Now(),
        "loginHistory": [
            {"date": "2024-10-15", "ip": "192.168.1.100", "success": true},
            {"date": "2024-10-14", "ip": "192.168.1.101", "success": true},
            {"date": "2024-10-13", "ip": "192.168.1.102", "success": false}
        ]
    };
    
    // Sample e-commerce shopping cart
    shoppingCart = {
        "cartId": "CART-2024-001",
        "customerId": 98765,
        "sessionId": "SESS-ABC123",
        "items": [
            {
                "productId": "PROD-001",
                "name": "Laptop Pro 15""",
                "category": "Electronics",
                "price": 1299.99,
                "quantity": 1,
                "options": {
                    "color": "Silver",
                    "storage": "512GB SSD",
                    "warranty": "2 years"
                }
            },
            {
                "productId": "PROD-002", 
                "name": "Wireless Mouse",
                "category": "Accessories",
                "price": 49.99,
                "quantity": 2,
                "options": {
                    "color": "Black",
                    "connectivity": "Bluetooth"
                }
            }
        ],
        "pricing": {
            "subtotal": 1399.97,
            "tax": 119.00,
            "shipping": 19.99,
            "discount": -50.00,
            "total": 1488.96
        },
        "shipping": {
            "method": "Standard",
            "estimatedDays": 5,
            "address": {
                "street": "123 Main St",
                "city": "Anytown", 
                "state": "CA",
                "zip": "12345",
                "country": "USA"
            }
        },
        "createdAt": DateAdd("d", -2, Now()),
        "updatedAt": Now()
    };
    
    // Sample API response data
    apiResponse = {
        "status": "success",
        "statusCode": 200,
        "message": "Data retrieved successfully",
        "data": {
            "employees": [
                {"id": 1, "name": "Alice Johnson", "department": "Engineering", "salary": 95000},
                {"id": 2, "name": "Bob Smith", "department": "Marketing", "salary": 78000},
                {"id": 3, "name": "Carol Davis", "department": "Sales", "salary": 82000}
            ],
            "metadata": {
                "totalRecords": 150,
                "page": 1,
                "pageSize": 10,
                "totalPages": 15
            }
        },
        "executionTime": "0.045s",
        "timestamp": Now(),
        "serverInfo": {
            "version": "1.2.3",
            "environment": "development"
        }
    };
</cfscript>

<cfoutput>
<h2>🔍 Development Debugging Examples</h2>

<div style="background: ##f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0;">
    <h3>🔧 WriteDump Implementation:</h3>
    <div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
        WriteDump(var=userProfile, format="html", label="User Debug");<br>
        WriteDump(var=shoppingCart, top="2", expand="false");
    </div>
    
    <h3>👤 User Profile Structure Analysis:</h3>
    <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##28a745;">
        <h4 style="margin-top: 0; color: ##28a745;">Complete User Profile Inspection</h4>
        <p><strong>Purpose:</strong> Analyze user registration data structure and nested preferences</p>
        
        <cfscript>
            // Full structure dump with custom label
            WriteDump(var=userProfile, format="html", label="User Profile Debug Analysis", expand="false");
        </cfscript>
        
        <div style="background: ##e8f5e8; padding: 10px; border-radius: 3px; margin-top: 10px;">
            <strong>✅ Debug Benefits:</strong>
            <ul style="margin: 5px 0; padding-left: 20px;">
                <li>Verify nested preference structure</li>
                <li>Inspect login history array format</li> 
                <li>Validate permission assignments</li>
                <li>Check data type consistency</li>
            </ul>
        </div>
    </div>
    
    <h3>🛒 Shopping Cart Development Analysis:</h3>
    <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##17a2b8;">
        <h4 style="margin-top: 0; color: ##17a2b8;">E-Commerce Cart Structure Debugging</h4>
        <p><strong>Purpose:</strong> Debug complex shopping cart calculations and item configurations</p>
        
        <cfscript>
            // Limited depth dump for large structures
            WriteDump(var=shoppingCart, format="html", label="Shopping Cart Debug", top="2");
        </cfscript>
        
        <div style="background: ##e8f4f8; padding: 10px; border-radius: 3px; margin-top: 10px;">
            <strong>🎯 Development Focus Areas:</strong>
            <ul style="margin: 5px 0; padding-left: 20px;">
                <li>Pricing calculation accuracy</li>
                <li>Product option handling</li>
                <li>Shipping address validation</li>
                <li>Cart state persistence</li>
            </ul>
        </div>
    </div>
    
    <h3>📊 API Response Structure Inspection:</h3>
    <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##fd7e14;">
        <h4 style="margin-top: 0; color: ##fd7e14;">API Development & Testing</h4>
        <p><strong>Purpose:</strong> Verify API response structure and data integrity</p>
        
        <cfscript>
            // Selective property display for API responses
            WriteDump(var=apiResponse, format="html", label="API Response Debug", 
                     show="status,statusCode,data,executionTime");
        </cfscript>
        
        <div style="background: ##fff3cd; padding: 10px; border-radius: 3px; margin-top: 10px;">
            <strong>🔍 API Validation Points:</strong>
            <ul style="margin: 5px 0; padding-left: 20px;">
                <li>Response status and codes</li>
                <li>Data structure consistency</li>
                <li>Pagination metadata accuracy</li>
                <li>Performance timing validation</li>
            </ul>
        </div>
    </div>
    
    <h3>🛠️ Development Workflow Integration:</h3>
    
    <cfscript>
        // Conditional debugging based on environment
        if (IsDefined("application") AND StructKeyExists(application, "environment") AND application.environment == "development") {
            debugMode = true;
        } else {
            debugMode = false;
        }
    </cfscript>
    
    <div style="background: ##d4edda; padding: 15px; border-radius: 5px; margin: 15px 0;">
        <h4>⚙️ Environment-Specific Debugging:</h4>
        <div style="background: white; padding: 12px; border-radius: 3px; font-family: monospace; font-size: 0.9em;">
            // Conditional debugging for development only<br>
            if (IsDefined("application") AND StructKeyExists(application, "environment") AND application.environment == "development") {<br>
            &nbsp;&nbsp;&nbsp;&nbsp;WriteDump(var=userProfile, format="html", label="Dev Debug");<br>
            &nbsp;&nbsp;&nbsp;&nbsp;WriteDump(var=shoppingCart, top="3", label="Cart Analysis");<br>
            }
        </div>
        
        <cfif debugMode>
            <div style="background: ##28a745; color: white; padding: 8px; border-radius: 3px; margin-top: 8px;">
                <strong>🔧 Development Mode Active:</strong> Full debugging enabled
            </div>
        <cfelse>
            <div style="background: ##6c757d; color: white; padding: 8px; border-radius: 3px; margin-top: 8px;">
                <strong>🚫 Production Mode:</strong> Debugging disabled for performance
            </div>
        </cfif>
    </div>
    
    <h3>📝 Console Debugging for Server-Side Analysis:</h3>
    <div style="background: ##f8d7da; padding: 15px; border-radius: 5px; margin: 15px 0;">
        <h4>🖥️ Server Console Output:</h4>
        <div style="background: white; padding: 12px; border-radius: 3px; font-family: monospace; font-size: 0.9em;">
            // Server-side debugging to console<br>
            WriteDump(var=apiResponse, output="console", format="text", label="API Console Debug");<br>
            WriteDump(var=userProfile.permissions, output="console", label="User Permissions");
        </div>
        
        <cfscript>
            // Execute console debugging
            WriteDump(var=apiResponse.data.metadata, output="console", format="text", 
                     label="API Metadata Console Debug");
            WriteDump(var=userProfile.preferences, output="console", label="User Preferences Console");
        </cfscript>
        
        <div style="background: ##dc3545; color: white; padding: 8px; border-radius: 3px; margin-top: 8px;">
            <strong>📟 Console Output:</strong> Check ColdFusion server console for detailed variable dumps
        </div>
    </div>
    
    <h3>🎯 Selective Property Debugging:</h3>
    <div style="background: ##e8f4f8; padding: 15px; border-radius: 5px; margin: 15px 0;">
        <h4>🔍 Focused Debugging Examples:</h4>
        
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin: 15px 0;">
            <div style="background: white; padding: 10px; border-radius: 3px;">
                <h5>👤 User Permissions Only</h5>
                <div style="background: ##f8f9fa; padding: 8px; border-radius: 3px; font-family: monospace; font-size: 0.85em;">
                    WriteDump(var=userProfile, show="permissions");
                </div>
                <cfscript>
                    WriteDump(var=userProfile, format="html", show="permissions", label="User Permissions Only");
                </cfscript>
            </div>
            
            <div style="background: white; padding: 10px; border-radius: 3px;">
                <h5>💰 Cart Pricing Only</h5>
                <div style="background: ##f8f9fa; padding: 8px; border-radius: 3px; font-family: monospace; font-size: 0.85em;">
                    WriteDump(var=shoppingCart, show="pricing");
                </div>
                <cfscript>
                    WriteDump(var=shoppingCart, format="html", show="pricing", label="Cart Pricing Debug");
                </cfscript>
            </div>
        </div>
    </div>
    
    <h3>📈 Development Performance Metrics:</h3>
    
    <cfscript>
        // Calculate debug information
        totalUserFields = StructCount(userProfile) + StructCount(userProfile.personalInfo) + StructCount(userProfile.preferences);
        totalCartItems = ArrayLen(shoppingCart.items);
        totalApiRecords = apiResponse.data.metadata.totalRecords;
        
        developmentStats = {
            "debuggingEnabled": debugMode,
            "userComplexity": totalUserFields & " nested fields",
            "cartItems": totalCartItems & " products", 
            "apiRecords": totalApiRecords & " total records",
            "debuggingTime": "&lt;1ms per dump"
        };
    </cfscript>
    
    <div style="background: ##e8f5e8; padding: 15px; border-radius: 5px;">
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px;">
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##28a745;">#totalUserFields#</h3>
                <p style="margin: 5px 0 0 0;">User Data Fields</p>
            </div>
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##17a2b8;">#totalCartItems#</h3>
                <p style="margin: 5px 0 0 0;">Cart Products</p>
            </div>
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##fd7e14;">#totalApiRecords#</h3>
                <p style="margin: 5px 0 0 0;">API Records</p>
            </div>
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##6f42c1;">&lt;1ms</h3>
                <p style="margin: 5px 0 0 0;">Debug Time</p>
            </div>
        </div>
    </div>
    
    <h3>🔄 Real-World Development Scenarios:</h3>
    
    <div style="background: ##f0f8ff; padding: 15px; border-radius: 5px;">
        <h4>💻 Common Development Debugging Patterns:</h4>
        
        <cfscript>
            debuggingScenarios = [
                "User Registration: Verify form data structure and validation",
                "Shopping Cart: Debug pricing calculations and item modifications",
                "API Integration: Inspect request/response data transformation",
                "Session Management: Analyze user state and permission changes",
                "Database Queries: Examine query results and data relationships",
                "Error Handling: Capture exception details and application context"
            ];
            
            scenariosList = ArrayToList(debuggingScenarios, " • ");
        </cfscript>
        
        <div style="background: white; padding: 12px; border-radius: 3px; margin: 8px 0; line-height: 1.6;">
            <span style="font-size: 0.9em;">#scenariosList#</span>
        </div>
        
        <h4>⚡ Development Best Practices:</h4>
        <ul style="font-size: 0.9em; margin: 10px 0;">
            <li><strong>Environment Control:</strong> Use conditional debugging for development only</li>
            <li><strong>Selective Display:</strong> Focus on specific properties with show/hide parameters</li>
            <li><strong>Performance Awareness:</strong> Limit depth for large structures with top parameter</li>
            <li><strong>Console Logging:</strong> Use console output for server-side analysis</li>
            <li><strong>Labeling:</strong> Always use descriptive labels for debugging context</li>
        </ul>
    </div>
</div>

</cfoutput>

Production error logging and diagnostics

Production ColdFusion applications require comprehensive error logging and diagnostic capabilities for rapid incident resolution and system monitoring without impacting user experience. Standard error logging lacks detailed context about application state. Manual log parsing is time-consuming and incomplete. Production issues take 4-6 hours to diagnose due to insufficient diagnostic information. Use WriteDump to capture detailed application state, variable contents, and error context in production logs for comprehensive incident analysis.
<cfscript>
    // Sample error context for production logging
    errorContext = {
        "errorId": "ERROR-2024-10-15-001",
        "severity": "HIGH",
        "errorType": "Database Connection Failed",
        "errorMessage": "Unable to connect to primary database server after 3 retry attempts",
        "timestamp": Now(),
        "duration": "00:00:15",
        "affectedUsers": 47,
        "requestInfo": {
            "url": "https://app.company.com/api/users/search",
            "method": "POST",
            "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
            "referrer": "https://app.company.com/dashboard",
            "clientIP": "192.168.1.150"
        },
        "userSession": {
            "userId": 12345,
            "sessionId": "SESS-2024-10-15-001",
            "loginTime": DateAdd("h", -2, Now()),
            "userRole": "admin",
            "permissions": ["read", "write", "admin"]
        },
        "systemState": {
            "serverName": "APP-SERVER-01",
            "memoryUsage": "2.8GB of 4GB",
            "cpuLoad": "78%",
            "diskSpace": "85% full",
            "activeConnections": 95,
            "maxConnections": 100
        },
        "stackTrace": [
            "at DatabaseService.connect() line 45",
            "at UserController.searchUsers() line 123",
            "at APIHandler.processRequest() line 67"
        ],
        "retryAttempts": 3,
        "lastSuccessfulOperation": DateAdd("m", -5, Now())
    };
    
    // Sample sensitive session data that needs secure logging
    sessionData = {
        "userId": 12345,
        "username": "john.doe",
        "email": "john.doe@company.com",
        "fullName": "John Doe",
        "password": "hashed_password_value",  // Should be hidden
        "creditCardLast4": "1234",            // Should be hidden
        "ssn": "XXX-XX-1234",                // Should be hidden
        "apiKeys": {
            "salesforce": "sk_live_abc123",   // Should be hidden
            "stripe": "pk_test_xyz789"        // Should be hidden
        },
        "preferences": {
            "theme": "dark",
            "language": "en-US",
            "notifications": true
        },
        "permissions": ["read", "write", "export"],
        "lastActivity": Now(),
        "sessionTimeout": DateAdd("m", 30, Now()),
        "loginAttempts": 0,
        "accountStatus": "active"
    };
    
    // Sample exception details
    exceptionDetails = {
        "exceptionType": "coldfusion.sql.DataSource",
        "message": "Connection verification failed for data source 'enterprise_db'",
        "detail": "java.sql.SQLException: No suitable driver found for jdbc:mysql://db-server:3306/enterprise",
        "errorCode": "08001",
        "sqlState": "Connection Exception",
        "nativeErrorCode": 0,
        "occurred": Now(),
        "queryExecuted": "SELECT u.id, u.name FROM users u WHERE u.status = 'active' AND u.department IN (?, ?)",
        "queryParameters": ["IT", "Engineering"],
        "affectedQuery": "getUsersByDepartment",
        "connectionPool": {
            "name": "enterprise_db",
            "maxConnections": 50,
            "activeConnections": 0,
            "idleConnections": 0,
            "failedConnections": 8
        }
    };
</cfscript>

<cfoutput>
<h2>🚨 Production Error Logging Examples</h2>

<div style="background: ##f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0;">
    <h3>🔧 WriteDump Implementation:</h3>
    <div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
        WriteDump(var=errorContext, format="html", label="Error Log");<br>
        WriteDump(var=sessionData, hide="password,ssn,apiKeys");
    </div>
    
    <h3>📝 Error Context Display:</h3>
    <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##dc3545;">
        <h4 style="margin-top: 0; color: ##dc3545;">🚨 Production Error Context Capture</h4>
        <p><strong>Purpose:</strong> Display complete error context for immediate incident analysis and troubleshooting</p>
        
        <cfscript>
            // Display error context (instead of logging to file)
            WriteDump(var=errorContext, format="html", 
                     label="Production Error - " & errorContext.errorId);
        </cfscript>
        
        <div style="background: ##f8d7da; padding: 10px; border-radius: 3px; margin-top: 10px;">
            <strong>📁 Log File Benefits:</strong>
            <ul style="margin: 5px 0; padding-left: 20px;">
                <li>Persistent error records for historical analysis</li>
                <li>Detailed context capture for debugging</li>
                <li>Automated incident trending and reporting</li>
                <li>Integration with monitoring and alerting systems</li>
            </ul>
        </div>
    </div>
    
    <h3>🖥️ Console Logging for Immediate Analysis:</h3>
    <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##fd7e14;">
        <h4 style="margin-top: 0; color: ##fd7e14;">⚡ Real-Time Error Monitoring</h4>
        <p><strong>Purpose:</strong> Immediate error visibility for production support teams</p>
        
        <cfscript>
            // Console output for immediate monitoring
            WriteDump(var=errorContext, output="console", format="text", 
                     label="PRODUCTION ALERT - " & errorContext.errorType,
                     show="errorType,severity,affectedUsers,systemState");
        </cfscript>
        
        <div style="background: ##fff3cd; padding: 10px; border-radius: 3px; margin-top: 10px;">
            <strong>📟 Console Monitoring Advantages:</strong>
            <ul style="margin: 5px 0; padding-left: 20px;">
                <li>Immediate visibility for support teams</li>
                <li>Real-time system health monitoring</li>
                <li>Quick identification of critical issues</li>
                <li>No browser dependency for server monitoring</li>
            </ul>
        </div>
    </div>
    
    <h3>🔐 Secure Session Data Logging:</h3>
    <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##28a745;">
        <h4 style="margin-top: 0; color: ##28a745;">🛡️ Privacy-Protected Diagnostics</h4>
        <p><strong>Purpose:</strong> Capture user session context while protecting sensitive information</p>
        
        <cfscript>
            // Secure session logging with sensitive data hidden
            WriteDump(var=sessionData, format="html", 
                     label="Secure Session Diagnostics",
                     hide="password,creditCardLast4,ssn,apiKeys");
        </cfscript>
        
        <div style="background: ##d4edda; padding: 10px; border-radius: 3px; margin-top: 10px;">
            <strong>🔒 Security Benefits:</strong>
            <ul style="margin: 5px 0; padding-left: 20px;">
                <li>Complete session context without exposing sensitive data</li>
                <li>GDPR and privacy compliance in error logging</li>
                <li>Safe diagnostic information for support teams</li>
                <li>Comprehensive user state analysis for troubleshooting</li>
            </ul>
        </div>
    </div>
    
    <h3>⚠️ Exception Details Analysis:</h3>
    <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##6f42c1;">
        <h4 style="margin-top: 0; color: ##6f42c1;">🔍 Database Exception Diagnostics</h4>
        <p><strong>Purpose:</strong> Comprehensive database error analysis for rapid resolution</p>
        
        <cfscript>
            // Detailed exception analysis
            WriteDump(var=exceptionDetails, format="html", label="Database Exception Analysis", 
                     show="exceptionType,message,errorCode,connectionPool,queryExecuted");
        </cfscript>
        
        <div style="background: ##e8e6ff; padding: 10px; border-radius: 3px; margin-top: 10px;">
            <strong>🎯 Exception Analysis Benefits:</strong>
            <ul style="margin: 5px 0; padding-left: 20px;">
                <li>Complete error context including SQL details</li>
                <li>Connection pool status for capacity planning</li>
                <li>Query parameter inspection for debugging</li>
                <li>Root cause identification for faster resolution</li>
            </ul>
        </div>
    </div>
    
    <h3>🛠️ Production Error Handling Workflow:</h3>
    
    <div style="background: ##e8f4f8; padding: 15px; border-radius: 5px; margin: 15px 0;">
        <h4>🔄 Complete Error Handling Pattern:</h4>
        <div style="background: white; padding: 12px; border-radius: 3px; font-family: monospace; font-size: 0.85em;">
            try {<br>
            &nbsp;&nbsp;&nbsp;&nbsp;// Business logic execution<br>
            &nbsp;&nbsp;&nbsp;&nbsp;result = performDatabaseOperation();<br>
            }<br>
            catch (database e) {<br>
            &nbsp;&nbsp;&nbsp;&nbsp;// Capture complete error context<br>
            &nbsp;&nbsp;&nbsp;&nbsp;errorData = {<br>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"exception": e,<br>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"userContext": sessionData,<br>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"systemContext": errorContext,<br>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"timestamp": Now()<br>
            &nbsp;&nbsp;&nbsp;&nbsp;};<br>
            &nbsp;&nbsp;&nbsp;&nbsp;<br>
            &nbsp;&nbsp;&nbsp;&nbsp;// Display error for immediate analysis<br>
            &nbsp;&nbsp;&nbsp;&nbsp;WriteDump(var=errorData, format="html", label="Error Details");<br>
            &nbsp;&nbsp;&nbsp;&nbsp;<br>
            &nbsp;&nbsp;&nbsp;&nbsp;// Alert monitoring console<br>
            &nbsp;&nbsp;&nbsp;&nbsp;WriteDump(var=errorData, output="console", format="text",<br>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;show="exception.message,systemContext.severity");<br>
            &nbsp;&nbsp;&nbsp;&nbsp;<br>
            &nbsp;&nbsp;&nbsp;&nbsp;// Secure user notification (hide sensitive data)<br>
            &nbsp;&nbsp;&nbsp;&nbsp;WriteDump(var=errorData, format="html", hide="userContext.password,userContext.apiKeys");<br>
            }
        </div>
    </div>
    
    <h3>📊 Error Severity Classification:</h3>
    
    <cfscript>
        // Error severity examples
        errorSeverityExamples = [
            {
                "level": "CRITICAL",
                "description": "System unavailable - affects all users",
                "examples": ["Database server down", "Application crashes", "Security breaches"],
                "response": "Immediate escalation and resolution"
            },
            {
                "level": "HIGH", 
                "description": "Major functionality impacted - affects many users",
                "examples": ["Payment processing failures", "Login system issues", "Data corruption"],
                "response": "2-hour response SLA"
            },
            {
                "level": "MEDIUM",
                "description": "Feature degradation - affects some users",
                "examples": ["Report generation delays", "Email notifications failing", "UI display issues"],
                "response": "Next business day resolution"
            },
            {
                "level": "LOW",
                "description": "Minor issues - minimal user impact",
                "examples": ["Cosmetic problems", "Non-critical validation errors", "Documentation updates"],
                "response": "Scheduled maintenance window"
            }
        ];
    </cfscript>
    
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 15px; margin: 20px 0;">
        <cfloop array="#errorSeverityExamples#" index="severity">
            <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid 
                <cfif severity.level EQ 'CRITICAL'>##dc3545<cfelseif severity.level EQ 'HIGH'>##fd7e14<cfelseif severity.level EQ 'MEDIUM'>##ffc107<cfelse>##28a745</cfif>;">
                <h5 style="margin-top: 0; color: <cfif severity.level EQ 'CRITICAL'>##dc3545<cfelseif severity.level EQ 'HIGH'>##fd7e14<cfelseif severity.level EQ 'MEDIUM'>##ffc107<cfelse>##28a745</cfif>;">
                    #severity.level# Severity
                </h5>
                <p style="font-size: 0.9em; margin: 5px 0;">#severity.description#</p>
                <div style="background: ##f8f9fa; padding: 8px; border-radius: 3px; font-size: 0.85em;">
                    <strong>Examples:</strong> #ArrayToList(severity.examples, ", ")#
                </div>
                <div style="background: ##e9ecef; padding: 6px; border-radius: 3px; font-size: 0.8em; margin-top: 5px;">
                    <strong>SLA:</strong> #severity.response#
                </div>
            </div>
        </cfloop>
    </div>
    
    <h3>📈 Production Error Metrics:</h3>
    
    <cfscript>
        // Calculate error statistics
        totalErrors = 1;  // Current error being logged
        criticalErrors = 0;
        highErrors = 1;
        mediumErrors = 0;
        lowErrors = 0;
        
        // System impact metrics
        impactMetrics = {
            "usersAffected": errorContext.affectedUsers,
            "systemLoad": Val(Left(errorContext.systemState.cpuLoad, Len(errorContext.systemState.cpuLoad)-1)),
            "memoryUsage": "70%",
            "responseTime": "2.3s increased"
        };
    </cfscript>
    
    <div style="background: ##f8d7da; padding: 15px; border-radius: 5px;">
        <h4>📊 Current Error Impact Dashboard:</h4>
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px;">
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##dc3545;">#impactMetrics.usersAffected#</h3>
                <p style="margin: 5px 0 0 0;">Users Affected</p>
            </div>
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##fd7e14;">#impactMetrics.systemLoad#%</h3>
                <p style="margin: 5px 0 0 0;">CPU Load</p>
            </div>
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##ffc107;">#impactMetrics.memoryUsage#</h3>
                <p style="margin: 5px 0 0 0;">Memory Usage</p>
            </div>
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##28a745;">15s</h3>
                <p style="margin: 5px 0 0 0;">Error Duration</p>
            </div>
        </div>
    </div>
    
    <h3>🔄 Automated Error Response:</h3>
    
    <div style="background: ##f0f8ff; padding: 15px; border-radius: 5px;">
        <h4>🤖 Intelligent Error Handling System:</h4>
        
        <cfscript>
            automatedResponses = [
                "Automatic failover to backup database server",
                "Load balancer redirects traffic to healthy servers", 
                "Cache warming prevents subsequent database load",
                "Alert notifications sent to on-call support team",
                "User-friendly error pages displayed to end users",
                "Retry mechanisms attempt automatic recovery"
            ];
            
            responseList = ArrayToList(automatedResponses, " • ");
        </cfscript>
        
        <div style="background: white; padding: 12px; border-radius: 3px; margin: 8px 0; line-height: 1.6;">
            <span style="font-size: 0.9em;">#responseList#</span>
        </div>
        
        <h4>📋 Error Resolution Checklist:</h4>
        <ul style="font-size: 0.9em; margin: 10px 0;">
            <li><strong>Immediate:</strong> Assess user impact and system availability</li>
            <li><strong>5 minutes:</strong> Implement temporary workarounds if available</li>
            <li><strong>15 minutes:</strong> Identify root cause using error dump analysis</li>
            <li><strong>1 hour:</strong> Deploy permanent fix and verify resolution</li>
            <li><strong>Post-incident:</strong> Update monitoring and prevention measures</li>
        </ul>
    </div>
</div>

</cfoutput>

API development and integration testing

Development teams creating REST APIs and integrating with external services need comprehensive request/response inspection and data validation capabilities for reliable service delivery. API request/response debugging requires manual inspection of complex JSON structures. Integration testing lacks visibility into data transformation processes. Use WriteDump to inspect API payloads, validate data transformations, and capture integration points for comprehensive API testing and debugging.
<cfscript>
    // Sample API request payload
    apiRequest = {
        "endpoint": "/api/v1/users",
        "method": "POST",
        "headers": {
            "Content-Type": "application/json",
            "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
            "X-API-Version": "1.0",
            "X-Request-ID": "REQ-2024-10-15-001",
            "User-Agent": "Mobile-App/2.1.0 iOS/17.0"
        },
        "payload": {
            "user": {
                "firstName": "Jane",
                "lastName": "Smith", 
                "email": "jane.smith@company.com",
                "phone": "+1-555-0123",
                "department": "Engineering"
            },
            "preferences": {
                "notifications": true,
                "theme": "dark",
                "language": "en-US"
            },
            "permissions": ["read", "write", "deploy"]
        },
        "metadata": {
            "clientIP": "192.168.1.150",
            "timestamp": Now(),
            "requestSize": "1.2KB"
        }
    };
    
    // Sample API response data
    apiResponse = {
        "status": "success",
        "statusCode": 201,
        "message": "User created successfully",
        "data": {
            "userId": 67890,
            "username": "jane.smith",
            "createdAt": Now(),
            "profileComplete": 75,
            "nextSteps": [
                "Complete profile information",
                "Set up two-factor authentication", 
                "Join team channels"
            ],
            "accountDetails": {
                "tier": "professional",
                "trialEndsAt": DateAdd("d", 30, Now()),
                "features": ["api-access", "advanced-reporting", "priority-support"]
            }
        },
        "metadata": {
            "processingTime": "0.234s",
            "apiVersion": "1.0",
            "serverId": "API-SERVER-02",
            "requestId": "REQ-2024-10-15-001",
            "rateLimitRemaining": 4975
        },
        "links": {
            "self": "/api/v1/users/67890",
            "profile": "/api/v1/users/67890/profile", 
            "permissions": "/api/v1/users/67890/permissions",
            "avatar": "/api/v1/users/67890/avatar"
        }
    };
    
    // Data transformation example
    transformationData = {
        "input": {
            "name": "Jane Smith",
            "contact": "jane.smith@company.com",
            "dept": "Engineering",
            "role": "senior_dev"
        },
        "output": {
            "fullName": "Jane Smith",
            "emailAddress": "jane.smith@company.com",
            "departmentName": "Engineering",
            "jobTitle": "Senior Developer",
            "displayName": "Jane S.",
            "initials": "JS"
        },
        "transformations": [
            {"field": "name", "operation": "splitName", "result": "success"},
            {"field": "contact", "operation": "validateEmail", "result": "valid"},
            {"field": "dept", "operation": "expandDepartment", "result": "Engineering"},
            {"field": "role", "operation": "formatTitle", "result": "Senior Developer"}
        ],
        "validationResults": {
            "isValid": true,
            "errors": [],
            "warnings": ["Phone number not provided"]
        }
    };
</cfscript>

<cfoutput>
<h2>🌐 API Development & Testing Examples</h2>

<div style="background: ##f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0;">
    <h3>🔧 WriteDump Implementation:</h3>
    <div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
        WriteDump(var=apiRequest, format="text", label="API Request");<br>
        WriteDump(var=apiResponse, top="3", expand="false");
    </div>
    
    <h3>📥 API Request Analysis:</h3>
    <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##28a745;">
        <h4 style="margin-top: 0; color: ##28a745;">📨 Incoming Request Inspection</h4>
        <p><strong>Purpose:</strong> Validate request structure, headers, and payload for API security and correctness</p>
        
        <cfscript>
            // Analyze incoming API request with selective display
            WriteDump(var=apiRequest, format="html", label="API Request Analysis", 
                     show="method,headers,payload");
        </cfscript>
        
        <div style="background: ##d4edda; padding: 10px; border-radius: 3px; margin-top: 10px;">
            <strong>✅ Request Validation Benefits:</strong>
            <ul style="margin: 5px 0; padding-left: 20px;">
                <li>Verify required headers and authentication tokens</li>
                <li>Inspect payload structure for schema compliance</li>
                <li>Validate content types and API version compatibility</li>
                <li>Security analysis of request metadata and client information</li>
            </ul>
        </div>
    </div>
    
    <h3>📤 API Response Validation:</h3>
    <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##17a2b8;">
        <h4 style="margin-top: 0; color: ##17a2b8;">📋 Response Structure Verification</h4>
        <p><strong>Purpose:</strong> Ensure API responses meet schema requirements and include all necessary data</p>
        
        <cfscript>
            // Validate API response structure with limited depth
            WriteDump(var=apiResponse, format="html", label="API Response Validation", 
                     top="2", expand="false");
        </cfscript>
        
        <div style="background: ##cce5f4; padding: 10px; border-radius: 3px; margin-top: 10px;">
            <strong>🎯 Response Validation Points:</strong>
            <ul style="margin: 5px 0; padding-left: 20px;">
                <li>Status codes and success/error message consistency</li>
                <li>Data structure completeness and type validation</li>
                <li>Metadata accuracy including timing and versioning</li>
                <li>HATEOAS links for RESTful API compliance</li>
            </ul>
        </div>
    </div>
    
    <h3>🔄 Data Transformation Testing:</h3>
    <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##fd7e14;">
        <h4 style="margin-top: 0; color: ##fd7e14;">⚡ Input/Output Data Processing</h4>
        <p><strong>Purpose:</strong> Verify data transformation logic and business rule application</p>
        
        <cfscript>
            // Verify data transformation results
            WriteDump(var=transformationData, format="html", label="Data Transformation Analysis");
        </cfscript>
        
        <div style="background: ##fff3cd; padding: 10px; border-radius: 3px; margin-top: 10px;">
            <strong>🔍 Transformation Verification:</strong>
            <ul style="margin: 5px 0; padding-left: 20px;">
                <li>Input data normalization and cleansing verification</li>
                <li>Business rule application and field mapping accuracy</li>
                <li>Data validation results and error handling</li>
                <li>Output format compliance with downstream systems</li>
            </ul>
        </div>
    </div>
    
    <h3>🧪 API Testing Workflows:</h3>
    
    <div style="background: ##e8f4f8; padding: 15px; border-radius: 5px; margin: 15px 0;">
        <h4>🔬 Comprehensive API Testing Pattern:</h4>
        <div style="background: white; padding: 12px; border-radius: 3px; font-family: monospace; font-size: 0.85em;">
            function testAPIEndpoint(endpoint, testData) {<br>
            &nbsp;&nbsp;&nbsp;&nbsp;// Log request for analysis<br>
            &nbsp;&nbsp;&nbsp;&nbsp;WriteDump(var=testData, format="text", label="Test Request",<br>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;output=ExpandPath("./logs/api_tests.log"));<br>
            &nbsp;&nbsp;&nbsp;&nbsp;<br>
            &nbsp;&nbsp;&nbsp;&nbsp;// Execute API call<br>
            &nbsp;&nbsp;&nbsp;&nbsp;response = httpPost(endpoint, testData);<br>
            &nbsp;&nbsp;&nbsp;&nbsp;<br>
            &nbsp;&nbsp;&nbsp;&nbsp;// Validate response structure<br>
            &nbsp;&nbsp;&nbsp;&nbsp;WriteDump(var=response, format="html", label="API Response", top="3");<br>
            &nbsp;&nbsp;&nbsp;&nbsp;<br>
            &nbsp;&nbsp;&nbsp;&nbsp;// Console output for automated testing<br>
            &nbsp;&nbsp;&nbsp;&nbsp;WriteDump(var=response, output="console", <br>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;show="status,statusCode,data", format="text");<br>
            &nbsp;&nbsp;&nbsp;&nbsp;<br>
            &nbsp;&nbsp;&nbsp;&nbsp;return response;<br>
            }
        </div>
    </div>
    
    <h3>📊 API Request/Response Metrics:</h3>
    
    <cfscript>
        // Calculate API metrics
        requestHeaders = StructCount(apiRequest.headers);
        responseFields = StructCount(apiResponse);
        transformationSteps = ArrayLen(transformationData.transformations);
        processingTime = Val(Left(apiResponse.metadata.processingTime, Len(apiResponse.metadata.processingTime)-1));
        
        apiMetrics = {
            "requestComplexity": requestHeaders & " headers",
            "responseSize": responseFields & " fields",
            "transformationSteps": transformationSteps,
            "processingTime": processingTime & "ms",
            "rateLimitUsed": (5000 - apiResponse.metadata.rateLimitRemaining) & "/5000"
        };
    </cfscript>
    
    <div style="background: ##f0f8ff; padding: 15px; border-radius: 5px;">
        <h4>📈 API Performance Dashboard:</h4>
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px;">
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##28a745;">#requestHeaders#</h3>
                <p style="margin: 5px 0 0 0;">Request Headers</p>
            </div>
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##17a2b8;">#responseFields#</h3>
                <p style="margin: 5px 0 0 0;">Response Fields</p>
            </div>
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##fd7e14;">#transformationSteps#</h3>
                <p style="margin: 5px 0 0 0;">Transform Steps</p>
            </div>
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##6f42c1;">234ms</h3>
                <p style="margin: 5px 0 0 0;">Response Time</p>
            </div>
        </div>
    </div>
    
    <h3>🔧 Selective API Data Inspection:</h3>
    
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin: 20px 0;">
        <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##6f42c1;">
            <h4 style="margin-top: 0; color: ##6f42c1;">🔒 Headers & Auth Only</h4>
            <div style="background: ##f8f9fa; padding: 10px; border-radius: 3px; font-family: monospace; font-size: 0.85em;">
                WriteDump(var=apiRequest, show="headers");
            </div>
            <cfscript>
                WriteDump(var=apiRequest, format="html", show="headers", label="Request Headers Analysis");
            </cfscript>
        </div>
        
        <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##dc3545;">
            <h4 style="margin-top: 0; color: ##dc3545;">⚡ Performance Metrics Only</h4>
            <div style="background: ##f8f9fa; padding: 10px; border-radius: 3px; font-family: monospace; font-size: 0.85em;">
                WriteDump(var=apiResponse, show="metadata");
            </div>
            <cfscript>
                WriteDump(var=apiResponse, format="html", show="metadata", label="Performance Metrics");
            </cfscript>
        </div>
    </div>
    
    <h3>📝 API Documentation Generation:</h3>
    
    <div style="background: ##d4edda; padding: 15px; border-radius: 5px; margin: 15px 0;">
        <h4>📖 Automated API Documentation:</h4>
        <div style="background: white; padding: 12px; border-radius: 3px; font-family: monospace; font-size: 0.85em;">
            // Generate API documentation from live examples<br>
            apiDocumentation = {<br>
            &nbsp;&nbsp;&nbsp;&nbsp;"endpoint": apiRequest.endpoint,<br>
            &nbsp;&nbsp;&nbsp;&nbsp;"method": apiRequest.method,<br>
            &nbsp;&nbsp;&nbsp;&nbsp;"sampleRequest": apiRequest,<br>
            &nbsp;&nbsp;&nbsp;&nbsp;"sampleResponse": apiResponse,<br>
            &nbsp;&nbsp;&nbsp;&nbsp;"lastUpdated": Now()<br>
            };<br>
            <br>
            WriteDump(var=apiDocumentation, format="text", <br>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;output=ExpandPath("./docs/api_documentation.txt"));
        </div>
        
        <div style="background: ##28a745; color: white; padding: 8px; border-radius: 3px; margin-top: 8px;">
            <strong>📚 Documentation Benefits:</strong> Living API documentation generated from actual request/response examples
        </div>
    </div>
    
    <h3>🚀 Integration Testing Scenarios:</h3>
    
    <div style="background: ##f8f9fa; padding: 15px; border-radius: 5px;">
        <cfscript>
            integrationScenarios = [
                "Authentication: Verify token validation and authorization levels",
                "Data Validation: Test input sanitization and business rule enforcement",
                "Error Handling: Validate error responses and status code accuracy",
                "Performance: Monitor response times and resource utilization",
                "Versioning: Test backward compatibility and API version handling",
                "Rate Limiting: Verify throttling and quota enforcement"
            ];
            
            scenariosList = ArrayToList(integrationScenarios, " • ");
        </cfscript>
        
        <h4>🧪 Common API Testing Scenarios:</h4>
        <div style="background: white; padding: 12px; border-radius: 3px; margin: 8px 0; line-height: 1.6;">
            <span style="font-size: 0.9em;">#scenariosList#</span>
        </div>
        
        <h4>⚡ API Development Best Practices:</h4>
        <ul style="font-size: 0.9em; margin: 10px 0;">
            <li><strong>Request Logging:</strong> Capture all incoming requests for analysis and debugging</li>
            <li><strong>Response Validation:</strong> Verify output structure matches API schema specifications</li>
            <li><strong>Performance Monitoring:</strong> Track response times and identify bottlenecks</li>
            <li><strong>Security Testing:</strong> Validate authentication, authorization, and input sanitization</li>
            <li><strong>Error Scenarios:</strong> Test edge cases and error handling pathways</li>
        </ul>
    </div>
</div>

</cfoutput>

Database query analysis and performance tuning

Database administrators and developers need detailed query result inspection and performance analysis capabilities to optimize database interactions and ensure efficient data retrieval. Complex query results are difficult to analyze manually. Query performance bottlenecks are hard to identify without detailed result inspection. Database optimization takes weeks due to limited visibility into query execution. Use WriteDump to analyze query structures, inspect result sets, and capture query metadata for comprehensive database performance analysis.
<cfscript>
    // Create sample employee query for analysis
    employeeQuery = QueryNew("id,name,department,salary,hire_date,status,performance_rating", 
                            "integer,varchar,varchar,decimal,date,varchar,decimal");
    
    QueryAddRow(employeeQuery, [
        {id: 1, name: "John Doe", department: "IT", salary: 75000, hire_date: CreateDate(2020, 3, 15), status: "Active", performance_rating: 4.2},
        {id: 2, name: "Jane Smith", department: "HR", salary: 68000, hire_date: CreateDate(2019, 8, 22), status: "Active", performance_rating: 4.7},
        {id: 3, name: "Bob Johnson", department: "Finance", salary: 82000, hire_date: CreateDate(2021, 1, 10), status: "Active", performance_rating: 4.0},
        {id: 4, name: "Alice Brown", department: "IT", salary: 79000, hire_date: CreateDate(2020, 11, 5), status: "Inactive", performance_rating: 3.8},
        {id: 5, name: "Charlie Wilson", department: "Marketing", salary: 71000, hire_date: CreateDate(2022, 6, 18), status: "Active", performance_rating: 4.5}
    ]);
    
    // Sample sales data query
    salesQuery = QueryNew("order_id,customer_id,product_name,quantity,unit_price,total_amount,order_date,region", 
                         "integer,integer,varchar,integer,decimal,decimal,date,varchar");
                         
    QueryAddRow(salesQuery, [
        {order_id: 1001, customer_id: 501, product_name: "Laptop Pro", quantity: 2, unit_price: 1299.99, total_amount: 2599.98, order_date: CreateDate(2024, 10, 1), region: "North"},
        {order_id: 1002, customer_id: 502, product_name: "Wireless Mouse", quantity: 5, unit_price: 49.99, total_amount: 249.95, order_date: CreateDate(2024, 10, 2), region: "South"},
        {order_id: 1003, customer_id: 503, product_name: "Monitor 4K", quantity: 1, unit_price: 599.99, total_amount: 599.99, order_date: CreateDate(2024, 10, 3), region: "East"},
        {order_id: 1004, customer_id: 504, product_name: "Keyboard", quantity: 3, unit_price: 129.99, total_amount: 389.97, order_date: CreateDate(2024, 10, 4), region: "West"},
        {order_id: 1005, customer_id: 505, product_name: "Headphones", quantity: 1, unit_price: 199.99, total_amount: 199.99, order_date: CreateDate(2024, 10, 5), region: "North"}
    ]);
    
    // Query performance metadata
    queryMetadata = {
        "queryName": "getEmployeesByDepartment",
        "executionTime": "0.025s",
        "recordCount": employeeQuery.recordCount,
        "columnList": employeeQuery.columnList,
        "sqlStatement": "SELECT id, name, department, salary, hire_date, status, performance_rating FROM employees WHERE status = 'Active' AND department IN ('IT', 'HR', 'Marketing') ORDER BY performance_rating DESC",
        "parameters": ["Active", "IT", "HR", "Marketing"],
        "indexesUsed": ["idx_status", "idx_department", "idx_performance"],
        "executionPlan": {
            "cost": "0.15",
            "estimatedRows": 150,
            "actualRows": employeeQuery.recordCount,
            "operations": ["Index Seek", "Filter", "Sort"]
        },
        "connectionInfo": {
            "dataSource": "enterprise_db",
            "server": "DB-SERVER-01", 
            "poolUsage": "3 of 50 connections"
        }
    };
    
    // Performance comparison data
    performanceComparison = {
        "optimization": "Added composite index on (status, department, performance_rating)",
        "before": {
            "executionTime": "1.250s",
            "cpuUsage": "25%",
            "memoryUsage": "45MB",
            "recordsScanned": 50000,
            "indexSeeks": 0,
            "tableScan": true
        },
        "after": {
            "executionTime": "0.025s", 
            "cpuUsage": "3%",
            "memoryUsage": "8MB",
            "recordsScanned": 150,
            "indexSeeks": 3,
            "tableScan": false
        },
        "improvements": {
            "speedIncrease": "98%",
            "cpuReduction": "88%",
            "memoryReduction": "82%",
            "scanReduction": "99.7%"
        }
    };
</cfscript>

<cfoutput>
<h2>🔍 Database Query Analysis Examples</h2>

<div style="background: ##f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0;">
    <h3>🔧 WriteDump Implementation:</h3>
    <div style="background: white; padding: 15px; border-radius: 3px; font-family: monospace; font-size: 1.1em;">
        WriteDump(var=queryResult, show="recordCount,columnList");<br>
        WriteDump(var=queryResult, format="text", top="5");
    </div>
    
    <h3>📊 Query Structure Analysis:</h3>
    <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##28a745;">
        <h4 style="margin-top: 0; color: ##28a745;">👥 Employee Query Metadata</h4>
        <p><strong>Purpose:</strong> Analyze query structure, column types, and record count for optimization</p>
        
        <cfscript>
            // Analyze query structure and metadata
            WriteDump(var=employeeQuery, format="html", label="Employee Query Structure", 
                     show="recordCount,columnList");
        </cfscript>
        
        <div style="background: ##d4edda; padding: 10px; border-radius: 3px; margin-top: 10px;">
            <strong>📋 Query Metadata Benefits:</strong>
            <ul style="margin: 5px 0; padding-left: 20px;">
                <li>Record count verification for result set size analysis</li>
                <li>Column list inspection for data structure validation</li>
                <li>Data type verification for application compatibility</li>
                <li>Result set size assessment for performance planning</li>
            </ul>
        </div>
    </div>
    
    <h3>💰 Sales Data Sample Analysis:</h3>
    <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##17a2b8;">
        <h4 style="margin-top: 0; color: ##17a2b8;">🛒 Sales Query Data Preview</h4>
        <p><strong>Purpose:</strong> Inspect sample data for accuracy and completeness verification</p>
        
        <cfscript>
            // Show first 3 records for data verification
            WriteDump(var=salesQuery, format="html", label="Sales Data Sample", top="3");
        </cfscript>
        
        <div style="background: ##cce5f4; padding: 10px; border-radius: 3px; margin-top: 10px;">
            <strong>🎯 Data Sampling Benefits:</strong>
            <ul style="margin: 5px 0; padding-left: 20px;">
                <li>Quick verification of data accuracy and format</li>
                <li>Detection of data quality issues and anomalies</li>
                <li>Validation of calculated fields and business logic</li>
                <li>Performance testing with representative sample data</li>
            </ul>
        </div>
    </div>
    
    <h3>⚡ Query Performance Metadata:</h3>
    <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##fd7e14;">
        <h4 style="margin-top: 0; color: ##fd7e14;">📈 Execution Performance Analysis</h4>
        <p><strong>Purpose:</strong> Comprehensive performance metrics for query optimization decisions</p>
        
        <cfscript>
            // Display comprehensive query performance data
            WriteDump(var=queryMetadata, format="html", label="Query Performance Analysis");
        </cfscript>
        
        <div style="background: ##fff3cd; padding: 10px; border-radius: 3px; margin-top: 10px;">
            <strong>⚡ Performance Analysis Features:</strong>
            <ul style="margin: 5px 0; padding-left: 20px;">
                <li>Execution time tracking for performance benchmarking</li>
                <li>Index usage analysis for optimization opportunities</li>
                <li>Connection pool monitoring for resource management</li>
                <li>Execution plan review for query tuning insights</li>
            </ul>
        </div>
    </div>
    
    <h3>📊 Performance Optimization Results:</h3>
    <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##6f42c1;">
        <h4 style="margin-top: 0; color: ##6f42c1;">🚀 Before/After Optimization Comparison</h4>
        <p><strong>Purpose:</strong> Track optimization results and demonstrate performance improvements</p>
        
        <cfscript>
            // Track performance improvements
            WriteDump(var=performanceComparison, format="html", label="Query Optimization Results");
        </cfscript>
        
        <div style="background: ##e8e6ff; padding: 10px; border-radius: 3px; margin-top: 10px;">
            <strong>🎯 Optimization Impact:</strong>
            <ul style="margin: 5px 0; padding-left: 20px;">
                <li>98% speed improvement through proper indexing</li>
                <li>88% CPU reduction for better resource utilization</li>
                <li>82% memory savings for higher concurrent capacity</li>
                <li>99.7% reduction in records scanned for efficiency</li>
            </ul>
        </div>
    </div>
    
    <h3>🔬 Database Analysis Workflow:</h3>
    
    <div style="background: ##e8f4f8; padding: 15px; border-radius: 5px; margin: 15px 0;">
        <h4>📋 Complete Query Analysis Process:</h4>
        <div style="background: white; padding: 12px; border-radius: 3px; font-family: monospace; font-size: 0.85em;">
            function analyzeQuery(queryResult, queryName) {<br>
            &nbsp;&nbsp;&nbsp;&nbsp;// Log query metadata to file<br>
            &nbsp;&nbsp;&nbsp;&nbsp;WriteDump(var=queryResult, format="text", <br>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;show="recordCount,columnList,executionTime",<br>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;output=ExpandPath("./logs/query_analysis.log"));<br>
            &nbsp;&nbsp;&nbsp;&nbsp;<br>
            &nbsp;&nbsp;&nbsp;&nbsp;// Display sample data for verification<br>
            &nbsp;&nbsp;&nbsp;&nbsp;WriteDump(var=queryResult, format="html", top="5", label=queryName);<br>
            &nbsp;&nbsp;&nbsp;&nbsp;<br>
            &nbsp;&nbsp;&nbsp;&nbsp;// Performance monitoring alerts<br>
            &nbsp;&nbsp;&nbsp;&nbsp;if (queryResult.recordCount GT 1000) {<br>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WriteDump(var="LARGE_RESULT_SET", output="console", <br>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;label="Performance Alert");<br>
            &nbsp;&nbsp;&nbsp;&nbsp;}<br>
            }
        </div>
    </div>
    
    <h3>📈 Query Performance Dashboard:</h3>
    
    <cfscript>
        // Calculate query statistics
        totalEmployees = employeeQuery.recordCount;
        totalSalesOrders = salesQuery.recordCount;
        avgSalary = 0;
        totalSalesAmount = 0;
        
        // Calculate average salary
        for (row = 1; row LTE employeeQuery.recordCount; row++) {
            avgSalary += employeeQuery.salary[row];
        }
        avgSalary = avgSalary / employeeQuery.recordCount;
        
        // Calculate total sales
        for (row = 1; row LTE salesQuery.recordCount; row++) {
            totalSalesAmount += salesQuery.total_amount[row];
        }
        
        queryStats = {
            "employeeRecords": totalEmployees,
            "salesRecords": totalSalesOrders,
            "avgSalary": NumberFormat(avgSalary, "999,999"),
            "totalSales": NumberFormat(totalSalesAmount, "999,999.99"),
            "queryTime": "25ms"
        };
    </cfscript>
    
    <div style="background: ##f0f8ff; padding: 15px; border-radius: 5px;">
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px;">
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##28a745;">#totalEmployees#</h3>
                <p style="margin: 5px 0 0 0;">Employee Records</p>
            </div>
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##17a2b8;">#totalSalesOrders#</h3>
                <p style="margin: 5px 0 0 0;">Sales Orders</p>
            </div>
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##fd7e14;">$#NumberFormat(avgSalary, "999,999")#</h3>
                <p style="margin: 5px 0 0 0;">Avg Salary</p>
            </div>
            <div style="background: white; padding: 15px; border-radius: 5px; text-align: center;">
                <h3 style="margin: 0; color: ##6f42c1;">25ms</h3>
                <p style="margin: 5px 0 0 0;">Query Time</p>
            </div>
        </div>
    </div>
    
    <h3>🎯 Selective Query Data Inspection:</h3>
    
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin: 20px 0;">
        <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##28a745;">
            <h4 style="margin-top: 0; color: ##28a745;">💼 Employee Performance Focus</h4>
            <div style="background: ##f8f9fa; padding: 10px; border-radius: 3px; font-family: monospace; font-size: 0.85em;">
                WriteDump(var=employeeQuery, show="name,performance_rating");
            </div>
            <cfscript>
                WriteDump(var=employeeQuery, format="html", show="name,performance_rating", 
                         label="Performance Analysis");
            </cfscript>
        </div>
        
        <div style="background: white; padding: 15px; border-radius: 5px; border-left: 4px solid ##17a2b8;">
            <h4 style="margin-top: 0; color: ##17a2b8;">💰 Sales Revenue Focus</h4>
            <div style="background: ##f8f9fa; padding: 10px; border-radius: 3px; font-family: monospace; font-size: 0.85em;">
                WriteDump(var=salesQuery, show="product_name,total_amount,region");
            </div>
            <cfscript>
                WriteDump(var=salesQuery, format="html", show="product_name,total_amount,region", 
                         label="Revenue Analysis");
            </cfscript>
        </div>
    </div>
    
    <h3>📝 Query Optimization Recommendations:</h3>
    
    <div style="background: ##d4edda; padding: 15px; border-radius: 5px;">
        <cfscript>
            optimizationTips = [
                "Index Analysis: Create composite indexes on frequently filtered columns",
                "Query Structure: Use WHERE clauses before JOIN operations for efficiency",
                "Data Types: Ensure proper data types to avoid implicit conversions",
                "Result Limiting: Use TOP/LIMIT clauses to reduce result set size",
                "Connection Pooling: Monitor and optimize connection pool settings",
                "Statistics Updates: Keep database statistics current for optimal execution plans"
            ];
            
            tipsList = ArrayToList(optimizationTips, " • ");
        </cfscript>
        
        <h4>⚡ Database Optimization Best Practices:</h4>
        <div style="background: white; padding: 12px; border-radius: 3px; margin: 8px 0; line-height: 1.6;">
            <span style="font-size: 0.9em;">#tipsList#</span>
        </div>
        
        <h4>🔍 Query Analysis Checklist:</h4>
        <ul style="font-size: 0.9em; margin: 10px 0;">
            <li><strong>Execution Plan:</strong> Review query execution plans for optimization opportunities</li>
            <li><strong>Index Usage:</strong> Verify appropriate indexes are being utilized effectively</li>
            <li><strong>Resource Consumption:</strong> Monitor CPU, memory, and I/O usage patterns</li>
            <li><strong>Result Set Size:</strong> Validate result sets are appropriately sized for application needs</li>
            <li><strong>Performance Trends:</strong> Track query performance over time for degradation detection</li>
        </ul>
    </div>
</div>

</cfoutput>

Share this page

Was this page helpful?
We're glad. Tell us how this page helped.
We're sorry. Can you tell us what didn't work for you?
Thank you for your feedback. Your response will help improve this page.

On this page