Validating Arbitrary GlideRecord Queries in scripts [ ServiceNow]

Andy LordAndy Lord
2 min read

One thing I often find myself doing is writing wrapper functions around GlideRecord to connect the application and the data model to the GlideRecord in a constant and reusable way.

These wrapper functions (or ‘convenience’ functions) often take some parameters and pass them to various combinations of GlideRecord.addQuery and GlideRecord.addEncodedQuery.

It is especially important, when writing library functions, to validate the function arguments and particularly catch invalid queries before execution.

ServiceNow by default discards the invalid part of a query - eg incorrect field name - but runs the rest of it. It does quietly log an exception in the background, but it still runs the code. This can be catastrophic!

There is a setting so the query will return no rows - glide.invalid_query.returns_no_rows - but this is a global optional setting that is disabled by default, and still does not clearly flag that there is a problem.

I had previously used calls to GlideRecord.isValidField() and GlideRecord.isValidEncodedQuery() to validate incoming query components. But this can add some complexity to the code.

Here is a neat way to validate any query combination just before execution, combining getEncodedQuery() and isValidEncodedQuery(): (note isValidEncodedQuery() is currently documented under the Scoped GlideRecord but also available to Global )

let any_gr = new GlideRecord('some_table');

...
any_gr.addQuery('field1',...);
any_gr.addQuery('field2',...);
any_gr.addEncodedQuery('encodedQuery3');
...

let query = any_gr.getEncodedQuery();
if (!any_gr.isValidEncodedQuery(query)) {
   throw new Error('Invalid query '+query);
}
any_gr.query();

Or as a convenience function:

// Execulte query safely - use if query "provenance" cannot be guaranteed etc..
function querySafe(/** {GlideRecord} */ any_gr) {
   let query = any_gr.getEncodedQuery();
   if (!any_gr.isValidEncodedQuery(query)) {
      throw new Error('Invalid query '+query+' on '+any_gr.getTableName());
   }
   any_gr.query();
}

querySafe(any_gr);

In an ideal world, trying to add the invalid query should trigger an exception at the point of adding, but I suspect this would fail platform regression testing in some weird and wonderful way.

0
Subscribe to my newsletter

Read articles from Andy Lord directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Andy Lord
Andy Lord