https://github.com/jsmithdev/aggregateiterator
https://github.com/jsmithdev/aggregateiterator
Last synced: 5 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/jsmithdev/aggregateiterator
- Owner: jsmithdev
- Created: 2024-07-24T21:18:34.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2024-07-24T21:18:35.000Z (almost 2 years ago)
- Last Synced: 2025-03-25T09:51:22.610Z (about 1 year ago)
- Language: Apex
- Size: 5.86 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Aggregate Iterator
This aggregate iterator allows you to iterate over a collection of Aggregate Results.
For example, in a batch class. See the usage example below.
## Installation
To add to your project, cd to your sf/sfdx project and run:
```bash
npx sfmm add jsmithdev AggregateIterator
```
## Usage
```java
public with sharing class AggregateBatchExample implements Database.Batchable {
public Iterable start(Database.BatchableContext bc){
return new CustomIterable();
}
public void execute(Database.BatchableContext bc, List scope) {
logicExample(scope);
}
public void finish(Database.BatchableContext bc) {
System.debug('AggregateBatchExample finished');
}
public with sharing class CustomIterable implements Iterable {
public Iterator iterator(){
String query = queryExample();
return new AggregateIterator(
Database.query(query)
);
}
}
private static String queryExample() {
return ''+
'SELECT Account.ParentId '+
'FROM Opportunity '+
'GROUP BY Account.ParentId'+
'';
}
private static void logicExample(List ars) {
/*
In this example we are getting Opp Account ParentIds to show
every Parent Account's Expected Revenue for all it's opportunities.
We could make a field on account to store the expected revenue from opps but
this is more to show how to break down the aggregate result from the iterator.
*/
List accIds = new List();
for(AggregateResult ar : ars) {
accIds.add((Id)ar.get('ParentId'));
}
System.debug('Parent Account Size: '+accIds.size());
for(Opportunity opp : [
SELECT ExpectedRevenue, Account.ParentId
FROM Opportunity
WHERE Account.ParentId IN: accIds
ORDER BY Account.ParentId, ExpectedRevenue DESC
]) {
System.debug(Account.ParentId +': '+ opp.ExpectedRevenue);
}
}
}
```