mirror of
https://github.com/forcedotcom/afv-library.git
synced 2026-07-30 03:09:50 +08:00
2.0 KiB
2.0 KiB
Anonymous Apex Guide
Using anonymous Apex for complex data operations.
When to Use Anonymous Apex
- Complex data setup requiring Apex logic
- Testing triggers with specific data patterns
- One-time data migrations
- Debugging and troubleshooting
sf CLI Execution
From File
sf apex run --file setup-data.apex --target-org myorg
Interactive
sf apex run --target-org myorg
# Then type Apex code and press Ctrl+D
Common Patterns
Bulk Data Creation
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 500; i++) {
accounts.add(new Account(
Name = 'Test Account ' + i,
Industry = 'Technology'
));
}
insert accounts;
System.debug('Created ' + accounts.size() + ' accounts');
Data Transformation
List<Account> accounts = [
SELECT Id, Name, Industry
FROM Account
WHERE Name LIKE 'Old%'
];
for (Account acc : accounts) {
acc.Name = acc.Name.replace('Old', 'New');
}
update accounts;
Testing Trigger Logic
// Setup test data
Account acc = new Account(Name = 'Trigger Test');
insert acc;
// Force trigger to fire
acc.Industry = 'Technology';
update acc;
// Verify results
acc = [SELECT Id, Field__c FROM Account WHERE Id = :acc.Id];
System.debug('Result: ' + acc.Field__c);
Error Handling
try {
insert accounts;
} catch (DmlException e) {
System.debug('Error: ' + e.getMessage());
for (Integer i = 0; i < e.getNumDml(); i++) {
System.debug('Row ' + e.getDmlIndex(i) + ': ' + e.getDmlMessage(i));
}
}
Limits in Anonymous Apex
| Limit | Value |
|---|---|
| SOQL Queries | 100 |
| DML Rows | 10,000 |
| CPU Time | 10,000 ms |
| Heap Size | 6 MB |
Best Practices
- Test in sandbox first - Validate before production
- Add debug statements - Track progress
- Handle errors gracefully - Use try/catch
- Keep scripts idempotent - Safe to re-run