Sub topic 13
Making seed scripts safe to run more than once
A seed script is idempotent if running it twice leaves the org in the same state as running it once. This chapter shows why the commands from earlier chapters are not idempotent by default, and how to make a seeding workflow safe to repeat.
This chapter assumes you can run sf data import tree and sf data upsert bulk, you know what an external ID field is, and you can read basic Apex and shell scripts.
Why repetition happens
Seed scripts run more often than you plan for:
- A developer reruns the setup script after a failed deploy.
- CI retries a job that timed out.
- A teammate runs the script against an org that already has data.
- A sandbox refresh script runs again after a partial failure.
If every run adds new rows, you get duplicate Accounts, test assertions that match the wrong record, and unique-rule or duplicate-rule errors on the second run. Idempotency removes that class of problem.
What is and is not idempotent
| Approach | Safe to rerun? | Why |
|---|---|---|
| `sf data import tree` | No | Every run inserts new records. Nothing matches against existing rows. |
| Anonymous Apex with `insert` | No | Each run creates new records. |
| `sf data upsert bulk` with `--external-id` | Yes | Rows that match the external ID are updated. Others are inserted. |
| Apex `upsert` with an external ID field | Yes | Same matching rule as the bulk command. |
| Delete seed records, then load | Yes | The load always starts from a known empty state. |
| Recreate the scratch org | Yes | There is no previous state. |
The first two rows are the ones that bite. Tree import is convenient for the first load, but it has no way to say "update this record if it exists".
Strategy 1: Upsert on an external ID
An external ID is a custom field marked as an External ID. If you also mark it Unique, Salesforce rejects two records with the same value. Seed data should use a recognizable prefix such as SEED- so you can find and clean it later.
Assume Account.External_Id__c and Contact.External_Id__c exist in your project metadata. Both are Text fields with External ID and Unique selected. Deploy them before loading data.
Here is data/accounts.csv:
External_Id__c,Name,Industry
SEED-ACC-001,Seed Account One,Technology
SEED-ACC-002,Seed Account Two,TechnologyHere is data/contacts.csv. The Account.External_Id__c column links each Contact to its parent without needing the parent's Salesforce ID:
External_Id__c,FirstName,LastName,Email,Account.External_Id__c
SEED-CON-001,Ada,Lovelace,[email protected],SEED-ACC-001
SEED-CON-002,Grace,Hopper,[email protected],SEED-ACC-001
SEED-CON-003,Alan,Turing,[email protected],SEED-ACC-002Load the parent first, then the child:
sf data upsert bulk \
--sobject Account \
--file data/accounts.csv \
--external-id External_Id__c \
--target-org my-scratch \
--wait 10
sf data upsert bulk \
--sobject Contact \
--file data/contacts.csv \
--external-id External_Id__c \
--target-org my-scratch \
--wait 10Run both commands twice. The second run reports updated records and creates no new ones.
This approach removes the need for the referenceId and @ references that tree import uses. The external ID plays the role of a stable key that exists before and after the load.
Strategy 2: Upsert in Apex
Apex seed scripts can be idempotent too. Use upsert with the external ID field and set parent links through the external ID instead of a queried Salesforce ID:
List<Account> accounts = new List<Account>{
new Account(External_Id__c = 'SEED-ACC-001', Name = 'Seed Account One', Industry = 'Technology'),
new Account(External_Id__c = 'SEED-ACC-002', Name = 'Seed Account Two', Industry = 'Technology')
};
upsert accounts Account.External_Id__c;
List<Contact> contacts = new List<Contact>{
new Contact(
External_Id__c = 'SEED-CON-001',
FirstName = 'Ada',
LastName = 'Lovelace',
Account = new Account(External_Id__c = 'SEED-ACC-001')
),
new Contact(
External_Id__c = 'SEED-CON-002',
FirstName = 'Grace',
LastName = 'Hopper',
Account = new Account(External_Id__c = 'SEED-ACC-001')
)
};
upsert contacts Contact.External_Id__c;Save this as scripts/apex/seed-idempotent.apex and run it with sf apex run --file scripts/apex/seed-idempotent.apex --target-org my-scratch. The Account = new Account(External_Id__c = ...) expression is a foreign key reference. Salesforce resolves it to the real Account at save time.
Anonymous Apex is also subject to governor limits, such as the 10,000 DML row limit per transaction. For more than a few thousand rows, use the bulk command instead.
Strategy 3: Reset, then load
Some data cannot carry an external ID. Examples are records created by managed packages, or objects where you cannot add custom fields. For these, delete the previous seed data and load it again.
Marking seed rows with a prefix makes the cleanup query precise:
delete [SELECT Id FROM Account WHERE External_Id__c LIKE 'SEED-%'];Deleting an Account also deletes its child Contacts and moves its other related records to the Recycle Bin. Two things to watch for:
- A delete can fail if other records depend on the ones you remove, or if a trigger or validation rule blocks it. Check the output of every run.
- Never write a cleanup query without a filter that identifies seed rows. An unfiltered
delete [SELECT Id FROM Account]in a sandbox with real-looking data is destructive.
Strategy 4: Guard with a check
You can also skip seeding if the data is already present. This suits tree imports, where you cannot make the import itself idempotent:
#!/usr/bin/env bash
set -euo pipefail
ORG="${1:-my-scratch}"
count=$(sf data query \
--query "SELECT COUNT() FROM Account WHERE Name LIKE 'Seed%'" \
--target-org "$ORG" \
--json | jq '.result.totalSize')
if [ "$count" -gt 0 ]; then
echo "Seed data already present ($count accounts). Skipping import."
exit 0
fi
sf data import tree --plan data/Account-Contact-plan.json --target-org "$ORG"
echo "Seed data imported."This script needs jq installed. A guard has one weakness. It tests for any seed data, not for complete seed data. If the first import failed halfway, the guard sees the partial data and skips. Pair a guard with a reset when you need a guaranteed full dataset.
Choosing a strategy
For scratch orgs, the simplest idempotent strategy is often to throw the org away and create a new one. That costs a few minutes but removes every hidden-state problem. Use upsert when you want fast iteration on an existing org.
Edge cases
- Order matters. Upsert parents before children. If a child references a parent external ID that does not exist yet, the row fails.
- Case sensitivity. Unique external IDs can be case-insensitive by default.
seed-acc-001andSEED-ACC-001may collide. Pick one casing and keep it in all files. - Partial success. Bulk upsert can succeed for some rows and fail for others. A rerun fixes the failed rows without touching the rest, which is a real advantage of upsert. Read the job result after every run.
- Changed values. Upsert overwrites fields you include in the file. If a developer edited a seed record by hand, the next run replaces those edits. This is usually the point.
- Removed rows. Upsert never deletes. If you remove a row from the CSV, the old record stays in the org. Use a reset when the file shrinks.
- Non-production safety. Check that
--target-orgis a scratch org or sandbox before any delete step. Passing an alias to a script is easier to get wrong than it looks.
Putting it together
A repeatable setup script combines these pieces: deploy metadata, load parents, load children, check results. Each step can run again without harm:
#!/usr/bin/env bash
set -euo pipefail
ORG="${1:?Usage: seed.sh <org-alias>}"
sf project deploy start --target-org "$ORG"
sf data upsert bulk --sobject Account --file data/accounts.csv \
--external-id External_Id__c --target-org "$ORG" --wait 10
sf data upsert bulk --sobject Contact --file data/contacts.csv \
--external-id External_Id__c --target-org "$ORG" --wait 10
echo "Seeding complete for $ORG"set -euo pipefail stops the script at the first failing command, so a failed Account load never leads to a Contact load that references missing parents. A later chapter covers running this script in CI.
Exercise
A teammate runs sf data import tree --plan data/Account-Contact-plan.json against the same scratch org three times and finds 30 Accounts instead of 10. Give two ways to change the workflow so that repeated runs leave 10 Accounts, and name one limitation of each.
Show answer
Option 1: add a unique External ID field to Account and Contact, convert the data to CSV, and load with sf data upsert bulk --external-id External_Id__c. Limitation: upsert never deletes, so rows removed from the file stay in the org, and records without an external ID value are not matched. Option 2: delete the seed records (filtered by a marker such as an External_Id__c prefix or a seed name) before each tree import, or guard the import with a count query. Limitation: a delete can be blocked by dependent records or validation rules, and a guard cannot detect a partially completed earlier import.