# QRY_Builder

**Class** · Group: `Query Infrastructure`

Learn it: [Fast Start - Selectors](/fast-start-selectors) and [Selectors guide](/selectors-guide)

<div class="apex-member apex-class">

```apex
global inherited sharing class QRY_Builder
```

Modern fluent query builder - the primary entry point for constructing and executing SOQL queries. Provides a clean, type-safe API for building queries with support for conditions, ordering, pagination, caching, and security enforcement. Design Principle: QRY_Builder passes the work to the existing query classes (QRY_Generator and QRY_Engine). This keeps older code working while giving new code a cleaner set of methods. 95% Use Case: Inline queries via QRY_Builder.selectFrom(...) 5% Use Case: Extend Builder for reusable custom selectors

**Example**

```apex
// Basic query
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .fields(new List<String>{'Name', 'Industry'})
    .condition(Account.Industry).equals('Technology')
    .toList();
```

```apex
// With caching
Account account = (Account)QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Id).equals(accountId)
    .withSystemMode()
    .withSharing()
    .withCache(300)
    .getFirst();
```

```apex
// Pagination
QRY_Builder.QueryPage result = QRY_Builder.selectFrom(Account.SObjectType)
    .condition(Account.Type).equals('Customer')
    .getPage(2, 25);
```

**See Also:** [IF_Queryable](/reference/apex/if-queryable), [QRY_Condition.DateLiteral](/reference/apex/qry-condition-dateliteral), [QRY_Function](/reference/apex/qry-function)

</div>

---

## Methods

| Method | Description |
|--------|-------------|
| global static void [clearMocks](#clearmocks)() | Clears all registered mocks and mock context classes for all SObjectTypes. |
| global static void [registerMockContextClass](#registermockcontextclass)([SObjectType](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_Schema_SObjectType.htm) sObjectType, [String](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_string.htm) contextClassName) | Registers a FormulaEval context class for an SObjectType, enabling smart mock filtering. |
| global static [QRY_Builder.Builder](/reference/apex/qry-builder-builder) [selectFrom](#selectfrom)([SObjectType](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_Schema_SObjectType.htm) sObjectType) | Entry point for inline queries. |
| global static void [setAggregateMock](#setaggregatemock)([SObjectType](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_Schema_SObjectType.htm) sObjectType, [List](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_list.htm)<[Map](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_map.htm)<[String](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_string.htm), [Object](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_System_Object.htm)>> rows) | Makes every aggregate query on this object type return these rows instead of reading the database, in your tests. |
| global static void [setMock](#setmock)([SObjectType](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_Schema_SObjectType.htm) sObjectType, [List](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_list.htm)<[SObject](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_sobject.htm)> mocks) | Registers mock records for a specific SObjectType during test execution. |
| global static void [setMockException](#setmockexception)([SObjectType](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_Schema_SObjectType.htm) sObjectType, [Exception](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_classes_exception_methods.htm) exceptionToThrow) | Registers an exception to be thrown when QRY_Builder is invoked for the specified SObjectType. |

### clearMocks

<div class="apex-member">

```apex
global static void clearMocks()
```

Clears all registered mocks and mock context classes for all SObjectTypes.

**Example**

```apex
QRY_Builder.clearMocks();
```

</div>

### registerMockContextClass

<div class="apex-member">

```apex
global static void registerMockContextClass(SObjectType sObjectType, String contextClassName)
```

Registers a FormulaEval context class for an SObjectType, enabling smart mock filtering.
When registered, mock queries against this SObjectType will evaluate WHERE conditions in memory
using the specified context class, returning only matching mock records.

Standard objects (Account, Contact, etc.) and Foobar__c are auto-detected and do not require
explicit registration. Use this method for custom objects that need mock filtering.

**Parameters**

| Parameter | Type | Description |
|-----------|------|-------------|
| `sObjectType` | [SObjectType](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_Schema_SObjectType.htm) | The SObjectType to register the context for |
| `contextClassName` | [String](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_string.htm) | The fully qualified class name of the FormulaEval context |

**Example**

```apex
QRY_Builder.registerMockContextClass(Invoice__c.SObjectType, 'InvoiceFormulaContext');
QRY_Builder.setMock(Invoice__c.SObjectType, mockInvoices);
// Queries against Invoice__c now filter mocks using InvoiceFormulaContext
```

</div>

### selectFrom

<div class="apex-member">

```apex
global static QRY_Builder.Builder selectFrom(SObjectType sObjectType)
```

Entry point for inline queries. Creates a new Builder instance for the specified SObject type.

**Parameters**

| Parameter | Type | Description |
|-----------|------|-------------|
| `sObjectType` | [SObjectType](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_Schema_SObjectType.htm) | The SObject type to query |

**Returns** [QRY_Builder.Builder](/reference/apex/qry-builder-builder) — Builder for fluent chaining

**Example**

```apex
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
    .fields(new List<String>{'Name', 'Industry'})
    .condition(Account.Industry).equals('Technology')
    .toList();
```

</div>

### setAggregateMock

<div class="apex-member">

```apex
global static void setAggregateMock(SObjectType sObjectType, List<Map<String, Object>> rows)
```

Makes every aggregate query on this object type return these rows instead of reading the database,
in your tests. Each map is one row: its keys are the aliases your code reads, its values what they hold. Pass
null to clear.

An aggregate query is one with count(field, alias), count(fieldName), countDistinct(), sum(), avg(), min(), max()
or groupBy(). The count() that ends a query and returns a number is not one: like toList(), it reads record mocks
set with setMock. Read the rows with toAggregateList() or getFirstAggregate(). The rows come back in the order you
gave them; only the query's limit is applied to them. Aliases are matched without regard to case. Rows set here
replace any set earlier for the type, as setMock replaces records; TST_Mock.registerAggregateRows adds to them
instead. clearMocks() removes them too.

**Parameters**

| Parameter | Type | Description |
|-----------|------|-------------|
| `sObjectType` | [SObjectType](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_Schema_SObjectType.htm) | The object type whose aggregate queries the rows answer. |
| `rows` | [List](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_list.htm) | The rows to return, in this order, or null to remove the rows set for the type. |

**Throws**

| Exception | Description |
|-----------|-------------|
| [IllegalArgumentException](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_classes_exception_methods.htm) | When sObjectType is null. |

**Example**

```apex
QRY_Builder.setAggregateMock(Account.SObjectType, new List<Map<String, Object>>
{
    new Map<String, Object> {'total' => 3, 'Industry' => 'Energy'}
});
QRY_Builder.AggregateRow row = QRY_Builder.selectFrom(Account.SObjectType)
    .count(Account.Id, 'total')
    .groupBy(Account.Industry)
    .getFirstAggregate();
Integer total = row.getInteger('total');
```

</div>

### setMock

<div class="apex-member">

```apex
global static void setMock(SObjectType sObjectType, List<SObject> mocks)
```

Registers mock records for a specific SObjectType during test execution.
When mocks are registered, queries will return these records instead of executing actual SOQL.

**Smart Mock Filtering:** WHERE conditions are evaluated in memory against mock records
using FormulaEval when a context class is available for the SObjectType. Standard objects
(Account, Contact, etc.) and Foobar__c are auto-detected. For custom objects, register
a context class via registerMockContextClass() to enable filtering.

When filtering is not possible (no context class, unsupported condition operators, or
relationship field traversals), all mocks are returned with only LIMIT and pagination applied.

**Parameters**

| Parameter | Type | Description |
|-----------|------|-------------|
| `sObjectType` | [SObjectType](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_Schema_SObjectType.htm) | The SObjectType to mock |
| `mocks` | [List](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_list.htm) | List of mock records to return for queries |

**Throws**

| Exception | Description |
|-----------|-------------|
| [IllegalArgumentException](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_classes_exception_methods.htm) | if mocks contain records of a different type than sObjectType |

**Example**

```apex
List<Account> mockAccounts = (List<Account>)TST_Builder.of(Account.SObjectType)
    .withOverride(Account.Name, 'Test Account')
    .withCount(5)
    .withoutInsertion(true)
    .buildList();
QRY_Builder.setMock(Account.SObjectType, mockAccounts);
```

</div>

### setMockException

<div class="apex-member">

```apex
global static void setMockException(SObjectType sObjectType, Exception exceptionToThrow)
```

Registers an exception to be thrown when QRY_Builder is invoked
for the specified SObjectType. Used for negative-path test coverage when a caller
needs to exercise a catch block around a SOQL call. Cleared by TST_Mock.clear()
and TST_Mock.clear(SObjectType).

**Parameters**

| Parameter | Type | Description |
|-----------|------|-------------|
| `sObjectType` | [SObjectType](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_Schema_SObjectType.htm) | The SObjectType for which queries should throw. |
| `exceptionToThrow` | [Exception](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_classes_exception_methods.htm) | The exception instance to throw. |

**Example**

```apex
QRY_Builder.setMockException(Account.SObjectType, new QueryException('Simulated SOQL failure'));
```

</div>

## Inner Classes

| Class | Description |
|-------|-------------|
| [AggregateRow](/reference/apex/qry-builder-aggregaterow) | Typed wrapper around AggregateResult for convenient value access. |
| [Builder](/reference/apex/qry-builder-builder) | Extensible query builder class. |
| [ConditionBuilder](/reference/apex/qry-builder-conditionbuilder) | Fluent builder for field-level conditions (WHERE and HAVING). |
| [DataCategoryBuilder](/reference/apex/qry-builder-datacategorybuilder) | Fluent builder for WITH DATA CATEGORY filters. |
| [QueryPage](/reference/apex/qry-builder-querypage) | Result container for paged queries, providing records and pagination metadata. |
| [Scope](/reference/apex/qry-builder-scope) | Enumeration of valid SOQL scope values for use with the USING SCOPE clause. |

---
