Sub topic 13
Making seed scripts safe to run more than once
A seed script is idempotent when running it twice leaves the org in the same state as running it once. This chapter assumes you can run sf data import tree, sf data upsert bulk, and anonymous Apex, and that you know what an external ID field is.
Why repeat runs go wrong
Seed scripts get re-run often. You re-run them after a failed import, after a scratch org is rebuilt, and in CI on every push. Plain inserts create a second copy of every record each time. Duplicates then break tests that assume one "Seed Account" and make lookups ambiguous.
The three seeding tools behave differently on a second run:
| Tool | Second run behavior | Safe to repeat? |
|---|---|---|
| `sf data import tree` | Inserts every record again | No |
| `sf data upsert bulk` with `--external-id` | Updates matching rows, inserts new ones | Yes |
| Anonymous Apex with `insert` | Inserts again | No, unless you guard it |
Pattern 1: upsert on an external ID
An external ID is a custom field marked as External ID (and usually Unique) that holds a stable key from your seed file. Upsert looks up each row by that key. If a record exists, it is updated. If not, it is created.
sf data upsert bulk \
--sobject Account \
--file data/accounts.csv \
--external-id External_Id__c \
--target-org my-scratch \
--wait 10Run this twice and the org holds the same Accounts. Mark the field Unique so a bad file cannot create two rows with the same key.
Pattern 2: guard Apex with a query
For Apex, check for existing data before you insert. The better option is upsert on an external ID field, which does the check for you.
List<Account> existing = [
SELECT Id FROM Account WHERE Name = 'Seed Account' LIMIT 1
];
if (existing.isEmpty()) {
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;
} else {
System.debug('Seed data already present, skipping.');
}Guarding on a name works for a small script. Names are not unique in Salesforce, so a user who creates an Account with the same name will make the script skip seeding. An external ID is a stronger check.
Pattern 3: tree import only into a clean org
Tree import has no upsert mode. The usual approach is to import into a fresh scratch org, where nothing exists yet. If you must re-run it against an existing org, check first and skip the import.
#!/usr/bin/env bash
set -euo pipefail
ORG=my-scratch
COUNT=$(sf data query \
--query "SELECT COUNT() FROM Account WHERE Name = 'Seed Account'" \
--target-org "$ORG" \
--json | jq '.result.totalSize')
if [ "$COUNT" -eq 0 ]; then
sf data import tree --plan data/Account-Contact-plan.json --target-org "$ORG"
else
echo "Seed data already present, skipping import."
fiCommon mistakes
- Using
insertin Apex with no guard, which duplicates records on every run. - Forgetting the Unique setting on the external ID field, so duplicate keys slip in.
- Checking for existing data with a field users can edit, such as Name.
- Leaving half-loaded data after a failure, so the next run sees partial data and skips the rest. Check for the last record you load, or load in a single transaction where possible.
Exercise
You run sf data import tree --plan data/Account-Contact-plan.json twice against the same scratch org. What happens, and how would you change the workflow to make it safe?
Show answer
The second run inserts every Account and Contact again, so you end up with duplicates. Make it safe by importing only into a freshly created scratch org, by adding a query check that skips the import when seed data exists, or by switching to sf data upsert bulk with an external ID field.
Exercise
Why is an external ID field with the Unique setting a better idempotency key than the Account Name?
Show answer
Name is not unique and users can edit it, so a lookup on Name can match the wrong record or none at all. A unique external ID is a stable key that you control, and Salesforce rejects duplicate values.