Using Salesforce Big Object and Batch Apex, we can archive the records regularly.
1. Make a note of your Object Fields for the Big Object creation.
2. Create a Big Object with similar Object Fields.
3. Create the following Batch Apex.
global class EmployeeBackup Implements Database.Batchable <sObject> {
global Database.queryLocator start(
Database.BatchableContext bc
) {
String strSOQL = 'SELECT Id, CreatedDate, Age__c, ';
strSOQL += 'CreatedById, Employee_Number__c, ';
strSOQL += 'LastModifiedById, LastModifiedDate, ';
strSOQL += 'Name__c, OwnerId ';
strSOQL += 'FROM Employee_Detail__c ';
strSOQL += 'WHERE Is_Active__c = false';
return Database.getQueryLocator(
strSOQL
);
}
global void execute(
Database.BatchableContext bc,
List < Employee_Detail__c > listEmployees
) {
List < Employee_Backup__b > listEmpBackups =
new List < Employee_Backup__b >();
for (
Employee_Detail__c objEmp : listEmployees
) {
Employee_Backup__b objBackup = new Employee_Backup__b();
objBackup.Age__c = objEmp.Age__c;
objBackup.Created_By_Id__c = objEmp.CreatedById;
objBackup.Created_Date__c = objEmp.CreatedDate;
objBackup.Employee_Number__c = objEmp.Employee_Number__c;
objBackup.Last_Modified_By_Id__c = objEmp.LastModifiedById;
objBackup.Last_Modified_Date__c = objEmp.LastModifiedDate;
objBackup.Name__c = objEmp.Name__c;
objBackup.Owner_Id__c = objEmp.OwnerId;
listEmpBackups.add( objBackup );
}
if ( !Test.isRunningTest() ) {
Database.insertImmediate(
listEmpBackups
);
}
delete listEmployees;
}
global void finish(
Database.BatchableContext bc
) {
}
}
4. You can create a Scheduler Call to schedule the Batch Class regularly.
5. Use the following resources to Execute the Batch Class, Query the Big Object or to clear the Big Object Data.
To execute the Batch Class:
EmployeeBackup objEmpBackup =
new EmployeeBackup();
Database.executeBatch(
objEmpBackup
);
Big Object SOQL:
SELECT Id, Age__c, Created_By_Id__c, Created_Date__c,
Employee_Number__c, Last_Modified_By_Id__c,
Last_Modified_Date__c, Owner_Id__c
FROM Employee_Backup__b
To clear data in Big Object:
List < Employee_Backup__b > listEmpBackups = [
SELECT Employee_Number__c
FROM Employee_Backup__b
];
Database.deleteImmediate(
listEmpBackups
);
Test Class for the Batch:
@isTest private class EmployeeBackupTest {
@TestSetup
static void setupData() {
Employee_Detail__c objEmp = new Employee_Detail__c();
objEmp.Age__c = 80;
objEmp.Employee_Number__c = 'Testing123';
objEmp.Name__c = 'Test Employee';
objEmp.Is_Active__c = false;
insert objEmp;
}
static testMethod void testBatch() {
Test.startTest();
EmployeeBackup objEmpBackup =
new EmployeeBackup();
Database.executeBatch(
objEmpBackup
);
Test.stopTest();
}
}