pythonsalesforcesimple-salesforce

Delete a table row from salesforce table with simple-salesforce


I have managed to query tables, pull schemas and add a row to a (custom) table but cannot work out how to delete that row again through the API. The following will list the row I want to get rid of:

import config
from simple_salesforce import Salesforce

sf = Salesforce(password=config.PASSWORD, 
                username=config.EMAIL_SANDBOX, 
                organizationId='',
                domain='test')

sf.query("SELECT Id FROM MyTable__c where id = 'a0D2R067009YpAeWAK'")

Have tried all kinds of things from around the web for too long now, the most likely one looked like this:

sf.query("delete [SELECT Id FROM MyTable__c where id = 'a0D2R067009YpAeWAK']")

as described here, but it unfortunately it raises:

SalesforceMalformedRequest: Malformed request https://eu20.salesforce.com/services/data/v38.0/query/?q=delete+%5BSELECT+Id+FROM+MyTable__c+where+id+%3D+%27a0D2R067009YpAeWAK%27%5D. Response content: [{'message': 'unexpected token: delete', 'errorCode': 'MALFORMED_QUERY'}]

Have tried variants on this with basically the same result. Any ideas how to get it to work?


Solution

  • To delete a record in simple_salesforce, you have to call a method on the connection attribute corresponding to the sObject. SOQL queries are read-only and can never update or delete data, although Anonymous Apex can.

    There's an example in the simple_salesforce documentation:

    sf.Contact.delete('003e0000003GuNXAA0')
    

    If you want to do it through Anonymous Apex, you can use the restful() method to hit the Tooling API, but this is not the "right" way to do a simple delete operation and will be slower.

    sf.restful(
        "tooling/executeAnonymous",
        {"anonymousBody": "delete [SELECT Id FROM Contact WHERE <condition>];"},
    )