I am building a package where I use child-to-parent query to get the data, and I allow users to select fields and relationships they want. This may lead to problems like this, or in my case when I try to select [SELECT CreatedBy.AboutMe FROM AccountFeed]
.
I want to prevent this from happening and forbid users to select polymorphic relationships.
My current approach to detect such relationship is following
static Boolean isPolymorphic(DescribeFieldResult fd) {
return fd.getReferenceTo().size() > 1
}
which fails to detect fields like AccountFeed.CreatedById
, AccountFeed.RelatedRecordId
, AccountFeed.InsertedById
or SocialPost.ParentId
as polymorphic and which leads to errors like No such column as 'AboutMe' on Entity Name
.
Another way would be just to run the query and check if it fails like following
static Boolean isPolymorphic(DescribeFieldResult fd) {
try {
List<SObject> records = Database.query('SELECT ' + fd.getRelationshipName() + '.AboutMe FROM AccountFeed');
return false;
} catch (System.QueryException e) {
return true;
}
}
however, this way looks too ugly.
Is there an effective way to detect polymorphic fields to prevent users to select them?