|
| 1 | +public class QueryGenerator { |
| 2 | + |
| 3 | + private Schema.FieldSet fieldSet; |
| 4 | + private SObjectType sobjectType; |
| 5 | + private Schema.DescribeSObjectResult sobjectResult; |
| 6 | + private Set<String> queryFields; |
| 7 | + |
| 8 | + public QueryGenerator(Schema.DescribeSObjectResult sobjectResult) { |
| 9 | + this(sobjectResult, null); |
| 10 | + } |
| 11 | + |
| 12 | + public QueryGenerator(Schema.FieldSet fieldSet) { |
| 13 | + this(null, fieldSet); |
| 14 | + } |
| 15 | + |
| 16 | + private QueryGenerator(Schema.DescribeSObjectResult sobjectResult, Schema.FieldSet fieldSet) { |
| 17 | + this.fieldSet = fieldSet; |
| 18 | + this.sobjectResult = sobjectResult; |
| 19 | + |
| 20 | + this.sobjectType = fieldSet != null ? fieldSet.getSObjectType() : sobjectResult.getSobjectType(); |
| 21 | + this.queryFields = new Set<String>{'Id'}; |
| 22 | + |
| 23 | + if(this.fieldSet == null) this.parseSObjectFields(); |
| 24 | + else this.parseFieldSetMembers(); |
| 25 | + } |
| 26 | + |
| 27 | + public String buildQuery() { |
| 28 | + return this.buildQuery(''); |
| 29 | + } |
| 30 | + |
| 31 | + public String buildQuery(String whereClause) { |
| 32 | + String query = |
| 33 | + 'SELECT ' + String.join(new List<String>(this.queryFields), ', ') |
| 34 | + + ' FROM ' + this.sobjectType; |
| 35 | + |
| 36 | + if(!String.isEmpty(whereClause)) query = query + whereClause; |
| 37 | + |
| 38 | + return query; |
| 39 | + } |
| 40 | + |
| 41 | + public void parseSObjectFields() { |
| 42 | + for(Schema.SObjectField sobjectField : this.sobjectResult.fields.getMap().values()) { |
| 43 | + this.queryFields.add(sobjectField.getDescribe().getName()); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + private void parseFieldSetMembers() { |
| 48 | + if(this.fieldSet == null) return; |
| 49 | + |
| 50 | + for(Schema.FieldSetMember field : this.fieldSet.getFields()) this.queryFields.add(field.getFieldPath()); |
| 51 | + } |
| 52 | + |
| 53 | +} |
0 commit comments