2
votes

Was trying to figure out a way to get simple salesforce to just give me all the field names in a list. I want to create soql query that pretty much does the same thing as a Select * does in sql.

for obj in objects:

fields = [x["name"] for x in sf[obj].describe()["fields"]]

thanks

3
Are you sure that you really need to select all fields? This is usually considered as a bad practice and can affect performance (and in the case of Salesforce, it can lead to the reaching limits).Gleb
Im wanting to select all the fields for each Sobject because we want to create a data lake with all the fields.oharr

3 Answers

2
votes

A list of field names in an object can be achieved as follow:

def getObjectFields(obj):
    fields = getattr(sf,obj).describe()['fields']
    flist = [i['name'] for i in fields]
    return flist

getObjectFields('Contact')

Your query to get the effect of SELECT * would then look something like this:

sf.query_all('SELECT {} FROM Contact LIMIT 10'.format(','.join(getObjectFields('Contact'))))

On a related note:

In case it is helpful, a dictionary of label/name pairs can be achieved as follows:

def getObjectFieldsDict(obj):
    fields = getattr(sf,obj).describe()['fields']
    fdict = {}
    for i in fields:
        fdict[i['label']] = i['name']
    return fdict

getObjectFieldsDict('Contact')

I find this can be useful for figuring out the names of fields with labels that do not follow the standard format (i.e. "My Favorite Website" field label for "Favorite_Website__c" field name)

0
votes

This method will return a query string with all fields for the object passed in. Well all the fields the user has access to.

 public static string getFullObjectQuery(String sObjectName){
Schema.SObjectType convertType = Schema.getGlobalDescribe().get(sObjectName);
Map<String,Schema.sObjectField> fieldMap = convertType.getDescribe().Fields.getMap();
Set<String> fields = fieldMap.keySet();
String Query = 'SELECT ';
for(String field: fields){
  Schema.DescribeFieldResult dfr = fieldMap.get(field).getDescribe();
  if(dfr.isAccessible()){
    Query += field + ',';
  }
}
Query = query.SubString(0,Query.length() - 1);
Query += ' FROM ' + sObjectName;

return Query;
}
0
votes
#!/usr/bin/env python3

import argparse
import os
import simple_salesforce

parser = argparse.ArgumentParser()
parser.add_argument('--sandbox', action='store_true',
                    help='Use a sandbox')
parser.add_argument('sfobject', nargs='+', action='store',
                    help=('Salesforce object to query (e.g. Contact)'))
args = parser.parse_args()

sf = simple_salesforce.Salesforce(
    username       = os.getenv('USERNAME'),
    password       = os.getenv('PASSWORD'),
    security_token = os.getenv('SECURITY_TOKEN'),
    sandbox        = args.sandbox)

for sfobject in args.sfobject:
    print(sfobject)
    fields = [x['name'] for x in getattr(sf, sfobject).describe()['fields']]
    print(fields)