Forked from johncasimiro/Mimic SQL select * statement in SOQL using Apex
Last active
August 29, 2015 14:07
-
-
Save arufian/f3231cbda7bf87b7d4fe to your computer and use it in GitHub Desktop.
My version of "Select All Mimic2 in SOQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
global with sharing class CommonClass { | |
global List<Object> selectAllFromTable(String objectName, String whereCondition, String order, String limit1){ | |
String query = selectAllQuery(objectName, whereCondition); | |
query += ' ORDER BY '+order+' LIMIT '+limit1; | |
try { | |
return database.query(query); | |
} catch (QueryException e){ | |
//perform exception handling | |
System.debug('failed to selectAllFromTable'); | |
System.debug('query: '+query+', tableName: '+objectName); | |
return NULL; | |
} | |
} | |
global List<Object> selectAllFromTable(String objectName, String whereCondition, String order){ | |
String query = selectAllQuery(objectName, whereCondition); | |
query += ' ORDER BY '+order; | |
try { | |
return database.query(query); | |
} catch (QueryException e){ | |
//perform exception handling | |
System.debug('failed to selectAllFromTable'); | |
System.debug('query: '+query+', tableName: '+objectName); | |
return NULL; | |
} | |
} | |
global List<Object> selectAllFromTable(String objectName, String whereCondition){ | |
String query = selectAllQuery(objectName, whereCondition); | |
try { | |
return database.query(query); | |
} catch (QueryException e){ | |
//perform exception handling | |
System.debug('failed to selectAllFromTable'); | |
System.debug('query: '+query+', tableName: '+objectName); | |
return NULL; | |
} | |
} | |
private String selectAllQuery(String objectName, String whereCondition){ | |
/* | |
* @description: A code snippet that mimics the popular Select * SQL syntax in force.com's Apex language. | |
*/ | |
// Initialize setup variables | |
String query = 'SELECT'; | |
Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap(); | |
// Grab the fields from the describe method and append them to the queryString one by one. | |
for(String s : objectFields.keySet()) { | |
query += ' ' + s + ', '; | |
} | |
// Strip off the last comma if it exists. | |
if (query.subString(query.Length()-1,query.Length()) == ','){ | |
query = query.subString(0,query.Length()-1); | |
} | |
// Add FROM statement | |
query += ' FROM ' + objectName; | |
// Add on a WHERE/ORDER/LIMIT statement as needed | |
query += ' WHERE '+whereCondition; // modify as needed | |
return query; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment