salesforce-migration-deep-dive
Execute Salesforce data migrations using Bulk API, Data Loader, and ETL patterns. Use when migrating data to/from Salesforce, performing org-to-org migrations, or re-platforming CRM data into Salesforce. Trigger with phrases like "migrate to salesforce", "salesforce data migration", "salesforce import data", "salesforce ETL", "CRM migration to salesforce".
What this skill does
# Salesforce Migration Deep Dive
## Overview
Comprehensive guide for migrating data to/from Salesforce: ETL patterns using Bulk API 2.0, data mapping between CRM schemas, record relationship preservation, and validation.
## Prerequisites
- Source and target Salesforce orgs (or external CRM)
- jsforce with Bulk API 2.0 access
- Understanding of sObject relationships and External IDs
- Staging sandbox for dry runs
## Migration Types
| Type | Complexity | Duration | Tool |
|------|-----------|----------|------|
| CSV import (< 50K records) | Low | Hours | Data Import Wizard / Bulk API |
| CRM-to-Salesforce | Medium | Weeks | Custom ETL with jsforce |
| Org-to-org migration | Medium | Weeks | SFDX + Bulk API |
| Full re-platform | High | Months | Custom ETL + change management |
## Instructions
### Step 1: Data Assessment
```typescript
const conn = await getConnection();
// Count records per object
const objectCounts = await Promise.all(
['Account', 'Contact', 'Lead', 'Opportunity', 'Case'].map(async (obj) => {
const result = await conn.query(`SELECT COUNT(Id) total FROM ${obj}`);
return { object: obj, count: result.records[0].total };
})
);
console.table(objectCounts);
// Account: 15,234
// Contact: 45,678
// Lead: 23,456
// Opportunity: 8,901
// Case: 67,890
// Check data storage limits
const limits = await conn.request('/services/data/v59.0/limits/');
console.log(`Data storage: ${limits.DataStorageMB.Max - limits.DataStorageMB.Remaining}/${limits.DataStorageMB.Max} MB`);
```
### Step 2: Schema Mapping
```typescript
// Map source fields to Salesforce sObject fields
interface FieldMapping {
source: string;
target: string;
transform?: (value: any) => any;
required: boolean;
}
const accountMappings: FieldMapping[] = [
{ source: 'company_name', target: 'Name', required: true },
{ source: 'industry_code', target: 'Industry', required: false,
transform: (code) => INDUSTRY_MAP[code] || 'Other' },
{ source: 'annual_rev', target: 'AnnualRevenue', required: false,
transform: (v) => typeof v === 'string' ? parseFloat(v.replace(/[$,]/g, '')) : v },
{ source: 'website_url', target: 'Website', required: false },
{ source: 'employee_count', target: 'NumberOfEmployees', required: false },
{ source: 'external_id', target: 'External_ID__c', required: true },
];
function transformRecord(
source: Record<string, any>,
mappings: FieldMapping[]
): Record<string, any> {
const target: Record<string, any> = {};
for (const mapping of mappings) {
let value = source[mapping.source];
if (value === undefined || value === null) {
if (mapping.required) throw new Error(`Missing required field: ${mapping.source}`);
continue;
}
if (mapping.transform) value = mapping.transform(value);
target[mapping.target] = value;
}
return target;
}
```
### Step 3: Migration Order (Respecting Relationships)
```
Migration order matters! Parent objects must be loaded before children.
1. Account (no dependencies)
2. Contact (depends on Account via AccountId)
3. Opportunity (depends on Account via AccountId)
4. OpportunityContactRole (depends on Opportunity + Contact)
5. Case (depends on Account + Contact)
6. Task / Event (depends on Contact via WhoId, Account via WhatId)
Use External IDs to resolve relationships without knowing Salesforce IDs:
- Create External_ID__c on Account, Contact, Opportunity
- Use external ID references in child records
```
### Step 4: Bulk Migration with External ID Relationships
```typescript
import { getConnection } from './salesforce/connection';
import fs from 'fs';
const conn = await getConnection();
// Step 4a: Load Accounts first
const accountCsv = `Name,Industry,External_ID__c
Acme Corp,Technology,EXT-ACME-001
Globex Inc,Manufacturing,EXT-GLOBEX-002
Initech LLC,Consulting,EXT-INITECH-003`;
const accountResults = await conn.bulk2.loadAndWaitForResults({
object: 'Account',
operation: 'upsert',
externalIdFieldName: 'External_ID__c',
input: accountCsv,
});
console.log(`Accounts: ${accountResults.successfulResults.length} success, ${accountResults.failedResults.length} failed`);
// Step 4b: Load Contacts with Account relationship via External ID
const contactCsv = `FirstName,LastName,Email,Account.External_ID__c,External_ID__c
Jane,Smith,[email protected],EXT-ACME-001,EXT-CONTACT-001
John,Doe,[email protected],EXT-GLOBEX-002,EXT-CONTACT-002`;
const contactResults = await conn.bulk2.loadAndWaitForResults({
object: 'Contact',
operation: 'upsert',
externalIdFieldName: 'External_ID__c',
input: contactCsv,
});
// Account.External_ID__c resolves to the correct AccountId automatically!
```
### Step 5: Validation
```typescript
async function validateMigration(
sourceCount: number,
objectType: string
): Promise<{ passed: boolean; details: string }> {
const conn = await getConnection();
// Count migrated records
const result = await conn.query(
`SELECT COUNT(Id) total FROM ${objectType} WHERE External_ID__c != null`
);
const targetCount = result.records[0].total;
// Check for orphaned relationships
let orphans = 0;
if (objectType === 'Contact') {
const orphanResult = await conn.query(
`SELECT COUNT(Id) total FROM Contact WHERE AccountId = null AND External_ID__c != null`
);
orphans = orphanResult.records[0].total;
}
const passed = targetCount === sourceCount && orphans === 0;
return {
passed,
details: `Source: ${sourceCount}, Target: ${targetCount}, Orphans: ${orphans}`,
};
}
```
### Step 6: Rollback Plan
```typescript
// Delete migrated records using External ID marker
async function rollbackMigration(objectType: string): Promise<void> {
const conn = await getConnection();
// Query all migrated records (identified by External_ID__c)
const records = await conn.query(
`SELECT Id FROM ${objectType} WHERE External_ID__c != null`
);
// Delete in reverse order (children first)
const ids = records.records.map((r: any) => r.Id);
for (let i = 0; i < ids.length; i += 200) {
const batch = ids.slice(i, i + 200);
await conn.sobject(objectType).destroy(batch);
}
console.log(`Rolled back ${ids.length} ${objectType} records`);
}
```
## Output
- Data assessment with record counts and storage usage
- Field mapping layer transforming source to Salesforce schema
- Bulk API migration respecting parent-child relationships
- External ID-based relationship resolution (no hardcoded IDs)
- Validation and rollback procedures
## Error Handling
| Error | Cause | Solution |
|-------|-------|----------|
| `DUPLICATE_VALUE` on External_ID__c | Re-running migration | Use upsert instead of insert |
| `INVALID_CROSS_REFERENCE_KEY` | Parent record not found | Verify parent loaded first, check External ID values |
| `STORAGE_LIMIT_EXCEEDED` | Org storage full | Delete test data or upgrade storage |
| Bulk job timeout | Very large dataset | Split into smaller jobs (< 100M records) |
| Field mapping errors | Source schema mismatch | Validate transform functions with sample data first |
## Resources
- [Bulk API 2.0](https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/bulk_api_2_0.htm)
- [External ID Fields](https://help.salesforce.com/s/articleView?id=sf.fields_about_external_ids.htm)
- [Data Import Best Practices](https://help.salesforce.com/s/articleView?id=sf.importing_data.htm)
- [Salesforce Data Loader](https://developer.salesforce.com/docs/atlas.en-us.dataLoader.meta/dataLoader/)
## Next Steps
For advanced troubleshooting, see `salesforce-advanced-troubleshooting`.
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.