I have build an apex tool which analyzes managed Permission Sets, finds specific permissions and creates a custom Permission Set clone without those permissions.
In order to maintain the clones I am deleting all existing children (ObjectPermissions, FieldPermissions, SetupEntityAccess records) from the clone and re-create them from the original Permission Set.
Salesforce throws a DML Exception with following message:
System.DmlException Delete failed. First exception on row 61 with id 1100Y00000dQGnBQAW; first error: FIELD_INTEGRITY_EXCEPTION, Permission Read Namespace__Object1__c depends on permission(s): Read Namespace__Object2__c: 
I checked the Objects and they are in fact in a master detail relationship. Therefore deletion fails because I am deleting the read-access on the parent object before the read-access on the child object.
I am deleting straightforward without any additional checks since my expectation was that Salesforce would manage the order of deletion:
delete [SELECT Id FROM ObjectPermissions WHERE ParentId = :clone.Id];
- Does anyone know if this is a bug or intended behavior?
- How could I structure a "safe" delete by checking which objects are parents and which are children?