Search code examples
python-3.xsimple-salesforce

Python 3 Simple Salesforce Testing to see if an object exists and contains data


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.


Solution

  • 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