3

is there an easy way to test if an object exists and isn't empty using simple salesforce? I have some code that is working to fetch records and I need to ensure that the objects I am getting from a file generated by someone else exist and are not empty.

Shenanigator
  • 1,036
  • 12
  • 45
  • Please share a snippet of code. – davejagoda Mar 20 '19 at 03:48
  • I actually don't have one as I wasn't able to determine from the simple salesforce module what I should expect to see back from it. Let me see if I can figure out some code and post it. – Shenanigator Mar 22 '19 at 15:20
  • Sounds good. Unless I am missing something, if a Salesforce object exists, it is by definition not empty (it will have at least an Id, and whatever fields are required). But show us the snippet and we'll try to help! – davejagoda Mar 22 '19 at 18:37
  • posted the code I ended up using. it works for objects that don't exist, but it doesn't deal with "empty" objects. That'll come later. – Shenanigator Mar 23 '19 at 01:54

2 Answers2

2

Assuming that "empty" object means an object with no records, I would suggest something like this:

def checkSalesforceObject(objName):
    try:
        getattr(sf,objName).metadata()
        a = len(sf.query_all('SELECT Id FROM {}'.format(objName))['records'])
        return {'IsObject':True,'Records':a}
    except:
        a = sys.exc_info()
        return {'IsObject':not("Resource {} Not Found".format(objName) in str(a[1])),'Records':None}

so checkSalesforceObject('Contact') would return something like {'IsObject': True, 'Records': 21}

and checkSalesforceObject('Contct') would return {'IsObject': False, 'Records': None}

If the nuance of an object existing vs. an object with no records isn't a concern, this function could be modified further to simply return true for any object that either doesn't exist OR has no records.

def objectInUse(objName):
    try:
        getattr(sf,objName).metadata()
        if len(sf.query('SELECT Id FROM {} LIMIT 1'.format(objName))['records']) == 0:
            return False
        else:
            return True
    except:
        a = sys.exc_info()
        if "Resource {} Not Found".format(objName) in str(a[1]):
            return False
Jwok
  • 646
  • 9
  • 23
0

Here is what I ended up doing, it doesn't deal with "empty" objects, but it does at least verify an object exists:

try :
    getattr(sf,nextObj).describe()
except (SalesforceGeneralError, SalesforceMoreThanOneRecord, SalesforceMalformedRequest, SalesforceExpiredSession, SalesforceRefusedRequest, SalesforceResourceNotFound) as e :
    print(e.content[0]['message'] +', writing next object and ending')
    updateNextObj(nextObj, s3NextObjDestination)
    sys.exit(1)
Shenanigator
  • 1,036
  • 12
  • 45