function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Cloud AtlasCloud Atlas 

Too many DML rows : 10001

Hello Team,

I am running into governor limits despite using database.batchable .
I am not being able to identify where the issue is.... Can some one just check my code and identify if possible ..
Any help is appreciated...
 
global class BatchToUpdatePageViews implements Database.Batchable<sObject>, Database.Stateful, Schedulable, Database.AllowsCallouts{

    private List<String> EMAIL_BATCH_RESULTS = new List<String>{System.Label.Email_List};  
    global  UrlIndividualMonthlyActivityServices.PageviewBatchResponse runningBatchResponse;
    private String query;
    private Integer queryYear;
    private Integer queryMonth;

    global BatchToUpdatePageViews(Integer year, Integer month){
        runningBatchResponse = new UrlIndividualMonthlyActivityServices.PageviewBatchResponse();

        // Validate user input, if request to run batch is not for todays date
        if(month != null && year != null && month >= 0 && month <= 12 && year > 1950){
            this.queryYear  = year;
            this.queryMonth = month;
        }
        else{
            Date yesterdaysDate = Date.today().addDays(-1);

            this.queryYear  = yesterdaysDate.year();
            this.queryMonth = yesterdaysDate.month();
        }

        this.query  = 'SELECT Id, GID__c ';
        this.query += 'FROM Monthly_Activity__c ';
        this.query += 'WHERE Year__c = ' + queryYear + ' ';
        this.query += 'AND Month__c = ' + queryMonth + ' ';
        this.query += 'AND GID__c <> null ';
        this.query += 'AND GID__c > 0 ';
    }

    global BatchToUpdatePageViews(){
        this(null, null);
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Monthly_Activity__c> currentBatchRecords){
        List<URL_Individual_Monthly_Activity__c> urlIndividualMonthlyActivities = [
            SELECT Id, GID__c, URL__c, Month__c, Year__c
            FROM URL_Individual_Monthly_Activity__c 
            WHERE Year__c =: queryYear
            AND Month__c =: queryMonth
            AND GID__c IN: Pluck.decimals('GID__c', currentBatchRecords)
        ];        

        if(urlIndividualMonthlyActivities.isEmpty()){
            return;
        }

        UrlIndividualMonthlyActivityServices.batchHandlerToUpdatePageviewCredits(
            runningBatchResponse,
            urlIndividualMonthlyActivities,
            queryYear,
            queryMonth
        );

        if(runningBatchResponse != null && !runningBatchResponse.getSuccessRecords().isEmpty()){
            List<Database.SaveResult> updateResults =
                Database.update(runningBatchResponse.getSuccessRecords(), false);

            for(Database.SaveResult updateResult : updateResults){
              if(!updateResult.isSuccess()){
                for(Database.Error err : updateResult.getErrors()){
                  runningBatchResponse.addDatabaseError(err.getMessage());
                }
              }
            }
        }

        runningBatchResponse.clearSuccessRecords();
    }

    global void execute(SchedulableContext SC){
        Database.executeBatch(new BatchToUpdatePageViews(), 2);
    }
    
    global void finish(Database.BatchableContext BC){
        AsyncApexJob apexBatchResult = [
            SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email
            FROM AsyncApexJob
            WHERE Id =: BC.getJobId()
        ];
    
        // Generate email body
        String emailBody = 'Apex Batch to Update Pageview Credits processed '
            + apexBatchResult.TotalJobItems + ' batches with '+ apexBatchResult.NumberOfErrors + ' failures.\n\n'
            + 'Database errors (if any): ' + JSON.serialize(runningBatchResponse.getDatabaseErrors()) + '\n';
        
        // Extract error string from batch response
        //emailBody += runningBatchResponse.generateErrorString();

        // Send email
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(EMAIL_BATCH_RESULTS);
        mail.setSenderDisplayName('About.com Experts - Batch Results');
        mail.setSubject('About.com - Batch to Update Page Views - status: ' + apexBatchResult.Status);
        mail.setPlainTextBody('Batch Process has completed\n\n' + emailBody);

        Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{mail});
    }
}

 
UC InnovationUC Innovation
Do you know if there's any DML statements happening in this function?

runningBatchResponse.addDatabaseError(err.getMessage());
Cloud AtlasCloud Atlas
@UCInnovation ... None.
Nishad KNishad K
Hi,

You cannot update more than 10000 records in a single transaction.

Governor limits count for each execution contexts (e.g. are reset between execution contexts).

As an example, consider a user that updates an account record, and a trigger is fired which invokes a method in a helper class. This method will have to operate within the governor limits for this transaction, which means that it cannot perform more SOQL queries than the current maximum, etc. Additionally, if the user performs the same operation almost at the same time (for instance by saving two different records in two different browser tabs), each transaction will be considered a separate execution context and will have its own governor limits (e.g. governor limits are not shared across transactions).