Sub topic 2
Plan files and reference IDs: keeping relationships intact
Assume you know Salesforce objects, lookup relationships, JSON, CSV, Apex, and the sf CLI. This chapter shows how to load related records without hard-coding Salesforce IDs.
Plan files and reference IDs
A tree export stores records in JSON files and creates a plan file. The plan controls import order and reference handling. Parent records must be imported before child records.
[
{
"sobject": "Account",
"saveRefs": true,
"resolveRefs": false,
"files": ["Accounts.json"]
},
{
"sobject": "Contact",
"saveRefs": false,
"resolveRefs": true,
"files": ["Contacts.json"]
}
]A record gets a local referenceId. A child record points to that reference with an @ prefix. Salesforce resolves the reference to the newly created parent ID.
{
"records": [
{
"attributes": {
"type": "Contact",
"referenceId": "ContactRef1"
},
"FirstName": "Ada",
"LastName": "Lovelace",
"Email": "[email protected]",
"AccountId": "@AccountRef1"
}
]
}The corresponding Account record must use referenceId AccountRef1.
flowchart TD
A[Import Accounts] --> B[Save AccountRef1]
B --> C[Import Contacts]
C --> D[Resolve @AccountRef1]Importing the dataset into a scratch org
Deploy metadata before importing data. Otherwise, objects or custom fields in the dataset may not exist.
sf org create scratch \
--definition-file config/project-scratch-def.json \
--alias my-scratch \
--set-default \
--duration-days 7
sf project deploy start --target-org my-scratch
sf data import tree \
--plan data/Account-Contact-plan.json \
--target-org my-scratchSeeding with an Apex anonymous script
Apex is useful when the data needs logic, loops, or calculated values.
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;Run it with:
sf apex run --file scripts/apex/seed.apex --target-org my-scratchExternal IDs and upsert for repeatable loads
For repeatable data loads, add a unique external ID field such as External_Id__c. An upsert updates a matching record and inserts one when no match exists.
sf data upsert bulk \
--sobject Account \
--file data/accounts.csv \
--external-id External_Id__c \
--target-org my-scratch \
--wait 10Loading larger datasets with bulk commands
Tree import is convenient for small related datasets. Bulk commands are better for larger flat files. Split large loads by dependency order: Accounts first, then Contacts. Validate required fields, picklist values, permissions, and automation before loading thousands of rows.
Exercise
Why must Accounts appear before Contacts in the plan?
Show answer
Contacts contain AccountId references, so the parent Accounts must exist before those references can be resolved.