Tuesday, January 22, 2013

Build a dynamic SOQL query string

This post is one of my promises to myself this year to build reusable components. I will try to post a few here. But whenever i write a code, Good design pattern is to make it as reusable as possible.

This Apex method basically returns the dynamic soql query string when you feed the list of field api names, object name , conditions and limit .
[Edit] This works only for soql and does not do aggregate functions or polymorphic soql or sosl

/* Return dynamic soql query string
     Inputs list of field api names
     Object name
     list of Condition strings eg 'name=\'test\'' , 'noofemployees=0'
     limit string eg '50000'*/
     */ ----------------------------------------------------
     usage
     list<string> fieldname = new list<string>();
     fieldname.add('id');
     fieldname.add('name');
     list<string> conditions = new list<string>();
     conditions.add('name=\'test\'');
   
     eg1:dynamicSoqlString(fieldname,'account',null,null)
     eg2:dynamicSoqlString(fieldname,'account',null,'2')  
     eg3:dynamicSoqlString(fieldname,'account',conditions,'2');
     */
     

     public static string dynamicSoqlString(List<string> apiNames,string objectname, list<string> conditions, string limitcount){
        if(objectname == null || apinames.size()==0){
            return null;
        }
        string soqlstring ='select ';
        for(integer counter =0;counter<apinames.size();counter++){
            if(counter!=0){
                soqlstring+=',';
            }
            soqlstring+=apinames[counter];
        }
        soqlstring += ' from '+ objectname;
        if(conditions != null && !conditions.isempty()){
            soqlstring+=' where ';
            for(integer counter =0;counter<conditions.size();counter++){
                if(counter!=0){
                    soqlstring+=' and ';
                }
                soqlstring+=conditions[counter];
            }
        }
        if(limitcount != null && limitcount !=''){
            soqlstring+=' limit '+limitcount;
        }
        return soqlstring;
    }