grzmol/vibe-force/sf-fflib-selector-layer
Claude Code and agent skill by grzmol/vibe-force
- community
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-layerSKILL.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
| Task | Where | |
|---|---|---|
| New selector class for an SObject | pattern 1 + references/selector-recipes.md | |
| Add a filtered query method | pattern 4 | |
| Add a child subselect or parent fields | pattern 5 + recipes 4-6 | |
| Field sets in a query | pattern 3 | |
| FLS/CRUD posture decision | pattern 6 + references/selector-security.md | |
| Dynamic/optional filters from user input | pattern 7 | |
| Batch Apex start() method | pattern 8 | |
| Aggregate or COUNT() query | pattern 9 | |
| Reviewing a selector | references/selector-antipatterns.md | |
fflib_QueryFactory method lookup | references/query-factory-api.md | |
| Registering the selector, factory wiring | skill sf-fflib-foundations | |
| Mocking a selector in a test | skill sf-fflib-testing |
Quick reference: constructor matrix
Read from the five fflib_SObjectSelector constructors and the field initialisers.
| Constructor | includeFieldSetFields | enforceCRUD | enforceFLS | sortSelectFields | DataAccess | |
|---|---|---|---|---|---|---|
fflib_SObjectSelector() | false | true | false | true | LEGACY | |
(Boolean includeFieldSetFields) | arg | true | false | true | LEGACY | |
(Boolean, DataAccess) | arg | false | false | `false` | arg | |
(Boolean, Boolean enforceCRUD, Boolean enforceFLS) (deprecated) | arg | arg | arg | true | LEGACY | |
(Boolean, Boolean, Boolean, Boolean sortSelectFields) (deprecated) | arg | arg | arg | arg | LEGACY |
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 mutator | Effect | |
|---|---|---|
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
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:
2. The two base query methods
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
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
Rules that keep custom methods honest:
| Rule | Reason | |
|---|---|---|
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 setCondition | Database.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 loop | skill sf-governor-limits | |
| Selective filters on indexed fields | skill 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
| Method | Effect | |
|---|---|---|
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
| Posture | Constructor | What is enforced | Generated SOQL | |
|---|---|---|---|---|
| Modern (default choice) | super(false, DataAccess.USER_MODE) | object + field read permission by the platform | ... WITH USER_MODE | |
| Explicit elevation | super(false, DataAccess.SYSTEM_MODE) | nothing; documents intent | ... WITH SYSTEM_MODE | |
| Legacy assertions | super(false, true, true) | fflib_SecurityUtils describe checks per field, throws FlsException/CrudException | no mode clause | |
| None | super() | 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
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
- SKILL.md in the repositoryCheckingskills/sf-fflib-selector-layer/SKILL.md
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
[](https://verified-skill.com/skills/grzmol/vibe-force/sf-fflib-selector-layer)