dschibster / sfdx-batch-orchestrator

A Package for organizing Batch Jobs and their Schedules via a record-based Scheduling Configuration, including dependencies and ad-hoc runs.
https://dschibster.github.io/sfdx-batch-orchestrator/
Other
10 stars 2 forks source link

MIXED_DML_OPERATION #20

Closed gluch closed 3 months ago

gluch commented 1 year ago

BatchJobLogger throws an error with the "logLegacy" method.

System.DmlException: Failed to save batch job log: Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): Batch_Job_Log__c, original object: User: []

The error comes from: Class.BatchJobLogger.logLegacy: line 183, column 1

This actually happened while running one of our test-classes. Is there anything we can do here?

dschibster commented 1 year ago

Hi! Thanks for using Batch Orchestrator. :) First of all: is that a Batch Class that is processing Users? Usually, mixed DML can be handled by switching Context by designating a separate User to perform the Insert of Users, before / after the rest of the Objects is inserted.

fentes commented 1 year ago

Hey the (test) class is used to (de)activate users at a specific date, So the class itself is just performing DML on User object. But after that, the orchestrator is logging the results which led to the issue. I assume that the logs are inserted synchronously after the job finished. It it somehow possible to inserting the logs by publishing an event (like nebula does)?

dschibster commented 1 year ago

Hah, I needed a second to recognize it's Georg! The Name I read in the Email was way less clear than the user name here :D Good to see you on here. Yes, that can be done by using Enhanced Logging: https://dschibster.github.io/sfdx-batch-orchestrator/logging/ It's important to mark the Checkbox "Enhanced Logging" on the Batch Apex Job Record to true, too.

gluch commented 1 year ago

Hi there :)

Usually we would mark the "Enhanced Logging" checkbox, but this is a test class which is failing and it is pointing us to BatchJobLogger.cls (method: logLegacy).

According to Salesforce it is possible to isolate DML operations on different sObject with the @future annotation. This prevents the mixed DML error at least on our Sandbox.

I wonder if this change does not screw up anything:

image

Again, with the above change our test class is working fine.

dschibster commented 1 year ago

I might enable this as a separate method in the future because I would need to test the full implications of it. But good to know. Thanks for the input and best wishes from Japan!

dschibster commented 3 months ago

Problem here solved, and after some thinking and coming back to this package I do not plan to support logLegacy more in the future (I would like everyone to switch to enhanced logging at some point :)), so I will close this issue