cardamom
cardamom

Reputation: 7441

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?

Upvotes: 1

Views: 2721

Answers (2)

Joe Cheng
Joe Cheng

Reputation: 9564

You can also use Salesforce bulk api via simple_salesforce to delete records in Salesforce.

Step 1: Create a CSV file with the record IDs you're going to delete

Step 2:

For Bulk API v2:

sf.bulk2.Contact.delete(csv_file='/path/to/your/csv', batch_size=5)

For Bulk API v1:

contacts_to_delete = []
with open('/path/to/your/csv', 'r') as f:
    for line in f:
        contacts_to_delete.append({'Id': line.replace('"', '').strip()})
sf.bulk.Contact.delete(contacts_to_delete, batch_size=5, use_serial=True)

Simply change the file path, and other parameters as you need.

Step 3: Monitor the batch job:

In Salesforce UI: go to Setup -> Environments -> Jobs -> "Bulk Data Load Jobs". You'll find the job submitted and monitor the status.

Keep in mind that the number of batches can be executed every 24 hours are limited. Set the batch size and the amount of data to be processed properly to avoid the impact of the daily business.

Upvotes: 0

David Reed
David Reed

Reputation: 2759

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>];"},
)

Upvotes: 6

Related Questions