Using "gr" in Scripts can result in variables getting clobbered by other scopes


Description

When writing server-side scripts (Script Includes, Business Rules, etc.) the use of "gr" when not included in a function or other limited scope construct, it can get 'corrupted' during script execution.

Release or Environment

All

Cause

The following example demonstrates the behavior, when run in Scripts Background

var gr = new GlideRecord("sys_user_grmember");
gr.addQuery("user=02c1f2c71b774450371adb9edc4bcb33");
gr.query();
gs.print("There are " + gr.getRowCount() + " records for user=02c1f2c71b774450371adb9edc4bcb33");
while(gr.next()){
    gs.print("Found record for " + gr.user.getDisplayValue() + " and group: " + gr.group.getDisplayValue() + ".");
    gr.deleteRecord();
}

In the above example the user value is the sys_id of a user with three records in the sys_usr_grmember table. The output shows 3 records were found, but execution stop after deleting one record. and this example deal with the Contextual Security: Role Management plugin being active, and that contains platform logic to re-allocate roles.

Resolution

The use of "gr" is subject to 'scope creep' as OOB or other scripts define that object. Wrap script logic in a function and call the function to prevent scope creep.  The following example will result in the deletion of each record meeting the query condition.

 

deleteGroups();

function deleteGroups() {
    var gr = new GlideRecord("sys_user_grmember");
    gr.addQuery("user=02c1f2c71b774450371adb9edc4bcb33");
    gr.query();
    gs.print("There are " + gr.getRowCount() + " records for user=02c1f2c71b774450371adb9edc4bcb33");
    while(gr.next()){
        gs.print("Found record for " + gr.user.getDisplayValue() + " and group: " + gr.group.getDisplayValue() + ".");
        gr.deleteRecord();
    }
}