apex.lang.performance.ncino.operationsinloops.avoidsoqlinloops.avoid-soql-in-loops

profile photo of semgrepsemgrep
Author
unknown
Download Count*

Database class methods, DML operations, SOQL queries, SOSL queries, Approval class methods, Email sending, async scheduling or queueing within loops can cause governor limit exceptions. Instead, try to batch up the data into a list and invoke the operation once on that list of data outside the loop.

Run Locally

Run in CI

Defintion

rules:
  - id: avoid-soql-in-loops
    min-version: 1.44.0
    severity: ERROR
    languages:
      - generic
    metadata:
      category: performance
      references:
        - https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm
      technology:
        - salesforce
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
    message: Database class methods, DML operations, SOQL queries, SOSL queries,
      Approval class methods, Email sending, async scheduling or queueing within
      loops can cause governor limit exceptions. Instead, try to batch up the
      data into a list and invoke the operation once on that list of data
      outside the loop.
    patterns:
      - pattern-either:
          - pattern-inside: |
              for (...) {
                ...
              }
          - pattern-inside: |
              while (...) {
                ...
              }
          - pattern-inside: |
              do {
                ...
              } while (...);
      - pattern: |
          $OBJECTS = [...SELECT...FROM...];

Examples

AvoidSoqlInLoops.cls

public class AvoidSoqlInLoops {
	public void SoqlInsideLoop() {
		for (Integer i = 0; i < 151; i++) {
			// ruleid: avoid-soql-in-loops
			List<Account> accounts = [SELECT Id FROM Account];
			// ruleid: avoid-soql-in-loops
			Account[] accounts = [SELECT Id FROM Account];
		}
	}

	public void SoqlInsideLoop2() {
		for (Account a : accounts) {
			// ruleid: avoid-soql-in-loops
			List<Account> accounts = [SELECT Id FROM Account];
			// ruleid: avoid-soql-in-loops
			Account[] accounts = [SELECT Id FROM Account];
		}
	}

	public void SoqlInsideLoop5() {
		while (someCondition) {
			// ruleid: avoid-soql-in-loops
			List<Account> accounts = [SELECT Id FROM Account];
			// ruleid: avoid-soql-in-loops
			Account[] accounts = [SELECT Id FROM Account];
		}
	}

	public void SoqlInsideLoop7() {
		do {
			// ruleid: avoid-soql-in-loops
			List<Account> accounts = [SELECT Id FROM Account];
			// ruleid: avoid-soql-in-loops
			Account[] accounts = [SELECT Id FROM Account];
		} while (someCondition);
	}
}