Certainly! Below is a TypeScript implementation that takes an array of IDs, splits them into batches of 2000, and constructs a SOQL query for each batch. Each query is stored with its corresponding batch number.
/**
* Generates batched SOQL queries for given Opportunity IDs.
* Each query selects specific fields from Opportunity where Id is in the batch.
*/
type BatchedQueries = {
[batchNumber: number]: string;
};
/**
* Escapes single quotes in a string for SOQL queries.
* @param id - The ID string to escape.
* @returns The escaped ID string.
*/
const escapeSingleQuotes = (id: string): string => {
return id.replace(/'/g, "\\'");
};
/**
* Splits an array into chunks of specified size.
* @param array - The array to split.
* @param chunkSize - The maximum size of each chunk.
* @returns An array of chunks.
*/
const chunkArray = <T>(array: T[], chunkSize: number): T[][] => {
const chunks: T[][] = [];
for (let i = 0; i < array.length; i += chunkSize) {
chunks.push(array.slice(i, i + chunkSize));
}
return chunks;
};
/**
* Creates batched SOQL queries based on the provided Opportunity IDs.
* @param ids - An array of Opportunity ID strings.
* @returns An object where each key is the batch number and the value is the corresponding SOQL query.
*/
const createBatchedQueries = (ids: string[]): BatchedQueries => {
const BATCH_SIZE = 2000;
const batchedQueries: BatchedQueries = {};
// Define the SELECT clause
const selectClause = `
SELECT
APNAWSAccountId__c,
APN_Did_AWS_Support_Partner_on_Oppty__c,
APN_FailedConvertUpdateId__c,
APN_Opportunity_Id__c,
APN_Opportunity_Identifier__c,
ASIN_2__c,
AccountId,
ActivityMetricId,
Amarna_Managed_Opportunity_Id__c,
Business_Validation_Duration_Percent__c,
Business_Validation_Duration__c,
Business_Validation_Flag__c,
CampaignId,
Confidence_to_Close_this_Year__c,
ConnectionReceivedId,
ConnectionSentId,
ContactId,
ContractId,
Count_of_AWS_Account_IDs__c,
CreatedById,
Customer_Tax_VAT_ID__c,
Days_in_Business_Validation__c,
Days_in_Technical_Validation__c,
Discount_Approval_Id__c,
Elemental_Opportunity_ID__c,
Engaged_Paid_Subs__c,
Forecasted_Paid_Subs__c,
Id,
LastAmountChangedHistoryId,
LastCloseDateChangedHistoryId,
LastModifiedById,
Legacy_Id__c,
Opportunity_Override_Amount__c,
Override_RCS__c,
OwnerId,
PSM_ProServe_Account_Id__c,
PSM_Proserve_Associate_Project_Id__c,
PSM_Proserve_Group_Id__c,
PSM_Proserve_Practice_Id__c,
PSM_Proserve_Primary_Project_Id__c,
PSM_Proserve_Rate_Card_Set_Id__c,
PSM_Proserve_Region_Id__c,
PartnerAccountId,
Partner_SAP_Win_Id__c,
Prepaid_Amount__c,
Pricebook2Id,
Priority_Customer_Override_PCO_Reason__c,
Priority_Customer_Override_PCO__c,
ProServe_Opportunity_ID__c,
RecordTypeId,
Reseller_AWS_Account_ID__c,
SPMS_ID__c,
SyncedQuoteId,
Tech_Valid_Set_Date_Diff_Expected__c,
Tech_Validation_Set_Date_Diff_Indicator__c,
Technical_Validation_Duration_Percent__c,
Technical_Validation_Duration__c,
Technical_Validation_Set_Date__c,
Territory2Id,
Time_Difference_Tech__c,
X18_Character_Account_ID__c,
X18_Character_Oppty_ID__c
FROM Opportunity`;
// Split IDs into batches
const batches = chunkArray(ids, BATCH_SIZE);
batches.forEach((batch, index) => {
const batchNumber = index + 1;
// Escape single quotes in IDs
const escapedIds = batch.map(id => `'${escapeSingleQuotes(id)}'`);
const whereClause = `WHERE Id IN (${escapedIds.join(', ')})`;
// Combine clauses to form the full query
const query = `${selectClause}\n${whereClause}`;
// Save the query with its batch number
batchedQueries[batchNumber] = query;
});
return batchedQueries;
};
// Example Usage
const opportunityIds: string[] = [
'Id1',
'Id2',
'Id3',
// ... more IDs
];
// Generate batched queries
const queries = createBatchedQueries(opportunityIds);
// Output the queries
for (const [batch, query] of Object.entries(queries)) {
console.log(`Batch ${batch}:\n${query}\n`);
}
Explanation:
-
Type Definition:
BatchedQueries: An object type where each key is a batch number (starting from 1) and the value is the corresponding SOQL query string.
-
Utility Functions:
escapeSingleQuotes: Ensures that any single quotes within the IDs are properly escaped to prevent SOQL injection or syntax errors.
chunkArray: Splits the input array into smaller arrays (chunks) of a specified size (BATCH_SIZE).
-
createBatchedQueries Function:
- Parameters: Accepts an array of Opportunity ID strings.
- Process:
- Defines the
SELECT clause as provided.
- Splits the IDs into batches of 2000 using the
chunkArray function.
- Iterates over each batch, escapes the IDs, and constructs the
WHERE clause.
- Combines the
SELECT and WHERE clauses to form the complete SOQL query.
- Stores each query in the
batchedQueries object with an incremented batch number.
- Return: An object containing all the batched queries.
-
Example Usage:
- Demonstrates how to use the
createBatchedQueries function with a sample array of Opportunity IDs.
- Iterates over the resulting queries and logs them to the console with their corresponding batch numbers.
Notes:
- Batch Size: The batch size is set to 2000 as per the requirement. Adjust
BATCH_SIZE if needed.
- Performance: For very large ID arrays, consider processing batches asynchronously or integrating with a queue system, especially if you plan to execute these queries against a Salesforce instance or similar service.
- Error Handling: Depending on the use case, you might want to add error handling to manage scenarios like empty ID arrays or invalid ID formats.
Feel free to integrate this code into your project and modify it as needed based on your specific requirements!