grzmol/vibe-force/sf-fflib-selector-layer

Claude Code and agent skill by grzmol/vibe-force

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Deep coverage of the fflib selector layer - extending fflib_SObjectSelector, getSObjectType/getSObjectFieldList/getOrderBy, the constructor flag and DataAccess.USER_MODE matrix, selectSObjectsById and queryLocatorById, the full fflib_QueryFactory fluent API (selectField, setCondition, addOrdering, setLimit, setOffset, subselectQuery, toSOQL, deepClone), parent field traversal and child subselects via configureQueryFactoryFields and addQueryFactorySubselect, FLS and CRUD enforcement old versus WITH USER_MODE, dynamic filters without SOQL injection using Database.queryWithBinds, QueryLocator selectors for Batch Apex, and selector anti-patterns. Use it when writing or reviewing any class extending fflib_SObjectSelector, when a selector query must add a filter, a child subselect, a field set, or a parent field, when fflib_QueryFactory.InvalidFieldException or NonReferenceFieldException or InvalidSubqueryRelationshipException appears, or when deciding how a selector enforces field-level security.

Install

npx vskill@latest install grzmol/vibe-force/sf-fflib-selector-layer

SKILL.md

The same SKILL.md was published earlier as grzmol/vibe-force/sf-fflib-selector-layer.

fflib Selector Layer

Every signature below was read this session from apex-enterprise-patterns/fflib-apex-common @ master commit dab5977: sfdx-source/apex-common/main/classes/fflib_SObjectSelector.cls, fflib_QueryFactory.cls, fflib_ISObjectSelector.cls, fflib_SecurityUtils.cls, fflib_SObjectDescribe.cls. Selector examples follow fflib-apex-common-samplecode @ master commit 4657d63. Items marked [unverified] were not read from source.

When to use

TaskWhere
New selector class for an SObjectpattern 1 + references/selector-recipes.md
Add a filtered query methodpattern 4
Add a child subselect or parent fieldspattern 5 + recipes 4-6
Field sets in a querypattern 3
FLS/CRUD posture decisionpattern 6 + references/selector-security.md
Dynamic/optional filters from user inputpattern 7
Batch Apex start() methodpattern 8
Aggregate or COUNT() querypattern 9
Reviewing a selectorreferences/selector-antipatterns.md
fflib_QueryFactory method lookupreferences/query-factory-api.md
Registering the selector, factory wiringskill sf-fflib-foundations
Mocking a selector in a testskill sf-fflib-testing

Quick reference: constructor matrix

Read from the five fflib_SObjectSelector constructors and the field initialisers.

ConstructorincludeFieldSetFieldsenforceCRUDenforceFLSsortSelectFieldsDataAccess
fflib_SObjectSelector()falsetruefalsetrueLEGACY
(Boolean includeFieldSetFields)argtruefalsetrueLEGACY
(Boolean, DataAccess)argfalsefalse`false`arg
(Boolean, Boolean enforceCRUD, Boolean enforceFLS) (deprecated)argargargtrueLEGACY
(Boolean, Boolean, Boolean, Boolean sortSelectFields) (deprecated)argargargargLEGACY

The (Boolean, DataAccess) constructor is the modern one and it also turns select-field sorting off - your generated SOQL will list fields in Set<String> iteration order, not alphabetically. Tests that assert on a SOQL string must account for that.

setDataAccess(DataAccess access) mutates a live selector and, for any value other than LEGACY, forces ignoreCRUD() and m_enforceFLS = false: legacy checks and native modes are mutually exclusive by construction.

Fluent mutatorEffect
includeFieldSetFields()m_includeFieldSetFields = true
ignoreCRUD()m_enforceCRUD = false
enforceFLS() (deprecated)m_enforceFLS = true
unsortedSelectFields()m_sortSelectFields = false
setDataAccess(DataAccess)sets mode, disables legacy CRUD/FLS when not LEGACY

All five return fflib_SObjectSelector, so they chain but do not return your subclass type - assign before casting.

Core patterns

1. Selector anatomy
apex
public inherited sharing class AccountsSelector extends fflib_SObjectSelector
implements IAccountsSelector
{
public static IAccountsSelector newInstance() {
return (IAccountsSelector) Application.Selector.newInstance(Account.SObjectType);
}
public AccountsSelector() {
super(false, fflib_SObjectSelector.DataAccess.USER_MODE);
}
public Schema.SObjectType getSObjectType() {
return Account.SObjectType;
}
public List<Schema.SObjectField> getSObjectFieldList() {
return new List<Schema.SObjectField> {
Account.Id,
Account.Name,
Account.AccountNumber,
Account.LastInvoiceDate__c
};
}
public List<Account> selectById(Set<Id> idSet) {
return (List<Account>) selectSObjectsById(idSet);
}
}
apex
public interface IAccountsSelector extends fflib_ISObjectSelector {
List<Account> selectById(Set<Id> idSet);
}

Required members: getSObjectType() and getSObjectFieldList() are abstract on the base class. Optional overrides: getSObjectFieldSetList() (returns null by default) and getOrderBy().

getOrderBy() default, computed once and cached in m_orderBy: the object's Name field if it exists and is not encrypted, else CreatedDate, else Id. Override it to return a comma-delimited clause; configureQueryFactory splits on ,, then on space, recognises ASC/DESC and detects NULLS LAST case-insensitively:

apex
public override String getOrderBy() {
return 'LastInvoiceDate__c DESC NULLS LAST, Name ASC';
}
2. The two base query methods
apex
// SELECT <fields> FROM Account WHERE id in :idSet ORDER BY <getOrderBy()> [WITH USER_MODE]
public virtual List<SObject> selectSObjectsById(Set<Id> idSet) // Database.query
public virtual Database.QueryLocator queryLocatorById(Set<Id> idSet) // Database.getQueryLocator

Both call protected String buildQuerySObjectById(), which is literally newQueryFactory().setCondition('id in :idSet').toSOQL(). The bind :idSet resolves against the local scope of the method that calls Database.query, which is why the parameter is named idSet. If you re-use `buildQuerySObjectById()` from your own method, the local variable must also be named `idSet` or the query throws an unbound-variable QueryException.

getSObjectName() returns the API name via the cached fflib_SObjectDescribe. sObjectType() and getSObjectType2() are public aliases of the abstract getSObjectType() and exist so mock registration can read the type (see skill sf-fflib-foundations).

3. Field sets
apex
public ProductsSelector(Boolean includeFieldSetFields) {
super(includeFieldSetFields, fflib_SObjectSelector.DataAccess.USER_MODE);
}
public override List<Schema.FieldSet> getSObjectFieldSetList() {
return new List<Schema.FieldSet> { SObjectType.Product2.FieldSets.OpportunityDiscount };
}

Field set fields are added only when both m_includeFieldSetFields is true and getSObjectFieldSetList() is non-null (configureQueryFactory). selectFieldSet throws fflib_QueryFactory.InvalidFieldSetException if the field set belongs to another SObject, and with allowCrossObject = false it rejects any member whose getFieldPath() contains a dot.

Multi-currency: configureQueryFactory appends CurrencyIsoCode automatically when UserInfo.isMultiCurrencyOrganization() and the SObject has the field. You do not list it.

4. Custom query methods
apex
public List<Account> selectByNameAndRating(Set<String> names, String rating) {
return (List<Account>) Database.query(
newQueryFactory()
.setCondition('Name IN :names AND Rating = :rating')
.setLimit(200)
.toSOQL());
}

Rules that keep custom methods honest:

RuleReason
Return a concrete List<Account>, never List<SObject>callers should not cast
Start from newQueryFactory(), never a raw new fflib_QueryFactory(...)you lose the field list, order by and security posture
Name locals exactly as the bind tokens in setConditionDatabase.query binds from local scope
Guard empty input: if (idSet.isEmpty()) { return new List<Account>(); }saves a SOQL statement against the 100 limit
One SOQL per method, never inside a loopskill sf-governor-limits
Selective filters on indexed fieldsskill sf-soql-sosl-optimization

newQueryFactory(false) omits the selector's own field list, which is how you build a narrow projection query (the samplecode's selectOpportunityInfo does exactly this).

5. Parent fields and child subselects
apex
public List<Opportunity> selectByIdWithProducts(Set<Id> idSet) {
fflib_QueryFactory oppFactory = newQueryFactory();
// Child subselect: (SELECT ... FROM OpportunityLineItems)
fflib_QueryFactory lineFactory =
new OpportunityLineItemsSelector()
.addQueryFactorySubselect(oppFactory, 'OpportunityLineItems');
// Parent fields on the child, contributed by other selectors' field lists
new PricebookEntriesSelector().configureQueryFactoryFields(lineFactory, 'PricebookEntry');
new ProductsSelector().configureQueryFactoryFields(lineFactory, 'PricebookEntry.Product2');
return (List<Opportunity>) Database.query(
oppFactory.setCondition('id in :idSet').toSOQL());
}
MethodEffect
addQueryFactorySubselect(parent)uses the deprecated subselectQuery(SObjectType) overload; logs a WARN debug
addQueryFactorySubselect(parent, 'RelationshipName')preferred; resolves the ChildRelationship by name
addQueryFactorySubselect(parent, name, Boolean includeSelectorFields)subselect with a hand-picked field list
configureQueryFactoryFields(qf, 'PricebookEntry')adds this selector's field list prefixed with the relationship path, plus CurrencyIsoCode in MC orgs

Ad-hoc parent traversal without another selector is just selectField('Account.Owner.Name'): fflib_QueryFactory.getFieldPath walks each segment through fflib_SObjectDescribe, substitutes getRelationshipName(), and throws NonReferenceFieldException when a mid-path segment is not a lookup or master-detail field. For polymorphic lookups (Lead.Owner -> Group|User) pass the intended type: selectField('Owner.Name', User.SObjectType).

Subselects go one level deep; the source comment states this explicitly and the child factory is created through a private constructor that carries the ChildRelationship. subselectQuery(String) throws InvalidSubqueryRelationshipException for an unknown relationship name. A subselect never emits WITH USER_MODE - toSOQL() only appends the mode clause when relationship == null.

6. Security posture
PostureConstructorWhat is enforcedGenerated SOQL
Modern (default choice)super(false, DataAccess.USER_MODE)object + field read permission by the platform... WITH USER_MODE
Explicit elevationsuper(false, DataAccess.SYSTEM_MODE)nothing; documents intent... WITH SYSTEM_MODE
Legacy assertionssuper(false, true, true)fflib_SecurityUtils describe checks per field, throws FlsException/CrudExceptionno mode clause
Nonesuper()CRUD read only (enforceCRUD defaults true)no mode clause

API version boundary, from the Apex Developer Guide "Apex Security and Sharing Model" versioned behavior changes: at 67.0 and later Apex runs in user context by default (object permissions and FLS enforced unless you opt into system mode), WITH SECURITY_ENFORCED is not allowed in an Apex SOQL SELECT, and a class with no sharing declaration behaves as with sharing. That does not make the selector setting redundant: fflib_QueryFactory.toSOQL() emits a mode clause only for USER_MODE/SYSTEM_MODE, so a LEGACY selector on a pre-67.0-versioned class still runs in system context. Pin the posture explicitly with DataAccess, and never write WITH SECURITY_ENFORCED except in a comment describing legacy code.

Never mixed: setDataAccess disables the legacy flags. Record-level sharing is not a selector setting - fflib_SObjectSelector is declared with sharing, so selectSObjectsById and queryLocatorById enforce sharing, while a query you issue from your own subclass method runs under your subclass's sharing declaration. Declare inherited sharing on selectors unless you have a reason not to. Full matrix, before/after code and proving tests: references/selector-security.md and skill sf-security-model.

7. Dynamic filters without SOQL injection
apex
public List<Account> search(String nameFragment, Set<String> ratings, Integer maxRows) {
fflib_QueryFactory qf = newQueryFactory();

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 90 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/grzmol/vibe-force/sf-fflib-selector-layer/badge)](https://verified-skill.com/skills/grzmol/vibe-force/sf-fflib-selector-layer)

Something wrong with this skill or its page? Tell us.