Sub topic 7
Seeding with an Apex Anonymous Script
This chapter shows how to create seed data by running Apex code through the Salesforce CLI. It assumes you know basic Apex syntax (loops, collections, DML), have a Salesforce DX project, and have the sf CLI authorized to a scratch org or sandbox. It also assumes you have deployed the project metadata, so the objects and fields your script uses already exist.
When Apex is the right tool
Tree import and bulk upsert load data that already exists as files. An Apex script builds the data in code. That fits several situations:
- You need records that are generated by logic, such as five contacts per account with numbered names.
- You need to call existing Apex, for example a factory class or a service that sets up related records.
- You need to set up data that is awkward to express in JSON, such as users, permission set assignments, or records that depend on triggers and flows running.
- You want the seed data to be reviewed in version control as readable code instead of exported JSON.
The trade-off is that Apex runs under governor limits and executes your triggers, flows, and validation rules. Files loaded through the Bulk API avoid some of that overhead. For a few hundred records, Apex is fine. For tens of thousands, use a bulk load.
What an anonymous script is
Anonymous Apex is code that runs once without being saved as a class in the org. You can run it from a file with the CLI. There is no class declaration, no method wrapper, and no access modifier. Statements execute from top to bottom.
Here is the script from the topic plan. Save it as scripts/apex/seed.apex:
Account acct = new Account(Name = 'Seed Account', Industry = 'Technology');
insert acct;
List<Contact> contacts = new List<Contact>();
for (Integer i = 1; i <= 5; i++) {
contacts.add(new Contact(
FirstName = 'Seed',
LastName = 'Contact ' + i,
AccountId = acct.Id
));
}
insert contacts;The script follows the dependency order from the data design chapter. The parent Account is inserted first, so acct.Id is populated by the time the Contacts reference it. The five Contacts go into a list and are inserted with one DML statement, not five. This pattern keeps you far from the limit of 150 DML statements per transaction.
Running the script
Run the file against a target org:
sf apex run --file scripts/apex/seed.apex --target-org my-scratchIf you have set a default org, --target-org is optional. The command compiles the file, executes it, and prints the result, including any debug log output. If compilation fails, nothing runs. If a runtime exception occurs, the transaction rolls back and no records from that script remain.
That rollback is useful. An anonymous script runs as one transaction, so it either creates all its records or none of them. You never end up with an Account but no Contacts because of a failure halfway through.
The execution flow
Writing a script you can debug
Seed scripts fail for ordinary reasons: a required field is missing, a validation rule rejects a value, or a trigger throws. Two habits make these failures easier to diagnose.
First, use Database.insert with allOrNone set to false when you want to see every failure at once, not just the first:
List<Contact> contacts = new List<Contact>();
for (Integer i = 1; i <= 5; i++) {
contacts.add(new Contact(LastName = 'Contact ' + i));
}
List<Database.SaveResult> results = Database.insert(contacts, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error err : results[i].getErrors()) {
System.debug(LoggingLevel.ERROR,
'Row ' + i + ' failed: ' + err.getStatusCode() + ' ' + err.getMessage());
}
}
}With allOrNone set to false, valid records are saved even when others fail. That is helpful while you are debugging, but it breaks the all-or-nothing guarantee. For the finished script, plain insert is usually the better choice, because a partial dataset is harder to reason about than a failed run.
Second, print what you created. A System.debug line with the count and the parent ID helps you confirm the result in the log output.
Making the script repeatable
Running seed.apex twice creates two accounts named "Seed Account" and ten contacts. This chapter does not cover full idempotency, which a later chapter treats in detail. Still, a small change makes the script safe to rerun: look for the record first, or use upsert with an external ID field.
Account acct = new Account(
External_Id__c = 'SEED-ACCT-001',
Name = 'Seed Account',
Industry = 'Technology'
);
upsert acct External_Id__c;This assumes Account has a custom text field External_Id__c marked as an external ID, which you must deploy first. On the first run, upsert creates the record. On later runs, it finds the existing record with the same external ID and updates it. The acct.Id value is set in both cases, so the Contact-creating code below it still works.
You can also reference a parent by external ID without querying for its Salesforce ID, using a reference object:
Account parentRef = new Account(External_Id__c = 'SEED-ACCT-001');
Contact c = new Contact(
External_Id__c = 'SEED-CON-001',
LastName = 'Lovelace',
Account = parentRef
);
upsert c External_Id__c;This assumes Contact also has an External_Id__c field. Setting the Account relationship field to an object that has only an external ID tells Salesforce to resolve the parent during the DML operation.
Organizing larger scripts
An anonymous script cannot define a top-level class, and long scripts become hard to read. Two approaches keep things manageable.
- Split by purpose. Keep
scripts/apex/seed-accounts.apexandscripts/apex/seed-users.apexas separate files and run them in order from a setup script. - Move reusable logic into a class in your project, such as
TestDataFactory, and have the script call it. The class is deployed with your metadata, and the script becomes a short list of calls.
Anonymous scripts can declare local helper methods only inside classes you deploy, so helper logic belongs in a class. The script itself stays a plain sequence of statements.
Limits and edge cases
Anonymous Apex runs in a single synchronous transaction, so the usual synchronous governor limits apply. The ones that matter most for seeding:
| Limit | Synchronous value | What it means for seeding |
|---|---|---|
| DML statements | 150 | Insert lists, not single records in a loop |
| DML rows | 10,000 | A single script cannot insert more than 10,000 rows |
| SOQL queries | 100 | Query once outside loops |
| CPU time | 10,000 ms | Heavy logic or many triggers can exhaust it |
Other points to watch:
- Automation fires. Triggers, flows, and duplicate rules run on your inserts. A trigger that sends email or calls out can break or slow a seed run. Use test-aware guards in your own code, or deactivate noisy automation in scratch orgs.
- Record ownership. Records are owned by the user who runs the script. Use
--target-orgwith the user you want as the owner, or setOwnerIdexplicitly. - Mixed DML. Inserting setup objects (such as
User) and non-setup objects (such asAccount) in the same transaction raises a mixed DML error. Split them into separate scripts. - Sandbox use. The same script works in a sandbox. Check the target org alias first, because the command runs against whichever org you name and will happily add records to the wrong one.
- Volume. If you hit the DML row or CPU limits, move to a bulk load, as described in the bulk loading chapter.
Choosing between Apex and tree import
| Question | Prefer Apex | Prefer tree import |
|---|---|---|
| Is the data generated by rules or loops? | Yes | No |
| Is the data a snapshot of real records? | No | Yes |
| Does it need users or permission assignments? | Yes | No |
| Do you want to avoid triggers and flows firing? | Hard to do | Also fires, but easier to review as data |
| Is the volume above a few thousand rows? | No | Better still, use bulk |
Exercise
A seed script inserts one Account and then five Contacts in a single run. The fourth Contact fails a validation rule, and the script uses plain insert contacts; on the list. What is in the org after the run, and what change would let the other four Contacts save while you see the failure?
Show answer
Nothing is saved. Plain insert on a list is all-or-nothing, the unhandled exception ends the transaction, and the Account insert is rolled back along with the Contacts. To let the four valid Contacts save, use Database.insert(contacts, false) and loop over the returned Database.SaveResult list, logging the errors for failed rows. The Account would then be saved as well, since the script no longer throws.
Exercise
You run sf apex run --file scripts/apex/seed.apex twice. Why do you get duplicate Accounts, and what two pieces do you need to prevent that?
Show answer
The script uses insert, which always creates new records. To make it repeatable, add a custom external ID field to Account (deployed to the org first) and change the DML to upsert acct External_Id__c; with a fixed value such as 'SEED-ACCT-001' set in the record.