Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

This server class provides methods to operate database records.

SimpleRecord(tableName)


This method instantiates a SimpleRecord class object for a particular table.


Parameter(s):

NameTypeMandatoryDefault Value
tableNameStringN''

Example:

Code Block
languagejs
themeEclipse
titleSimpleRecord
linenumberstrue
const task = new SimpleRecord('task');
ss.info(task.getAttributes());
//Info: {"sys_id":"","parent_id":"","assigned_user":"","number":"","short_description":"","active":"",...}


addOrCondition(property, operatorOrValue, value)


This method appends a 2-or-3 parameter OR condition to an existing query. It works in conjunction with any of the addQuery() methods.


Parameter(s):

NameTypeMandatoryDefault Value
propertyStringYN
operatorOrValueInteger or String or Boolean (if this parameter is used as a value); String (if this parameter is used as an operator).NN
valueInteger or String or BooleanNNULL


Return:

TypeDescription
SimpleRecordThe query containing OR condition added to the SimpleRecord object.


Example:

Code Block
languagejs
themeEclipse
titleaddOrCondition
linenumberstrue
const task = new SimpleRecord('task');
task.addQuery('subject', 'like', 'not work').addOrCondition('description', 'like', 'not work');
task.query();
ss.info(task.getRowCount());
task.setMultipleValue('attention_required', '1');
// task.updateMultiple();


addQuery(property, operatorOrValue, value)


This method adds a condition to make a selection of records from the database. In this method, you can use any preferred operator from the Condition Operators list, specified either in lowercase or in uppercase.


Parameter(s):

NameTypeMandatoryDefault Value
propertyStringYN
operatorOrValueInteger or String or Boolean (if this parameter is used as a value); String (if this parameter is used as an operator).NN
valueInteger or StringNNULL


Return:

TypeDescription
SimpleRecordThe query condition added to the SimpleRecord object.


Example:

Code Block
languagejs
themeEclipse
titleaddQuery
linenumberstrue
const task = new SimpleRecord('task');
task.addQuery('active', '1'); // active is true
task.addQuery('subject', 'like', 'сеть');
task.addQuery('sys_created_at', '<', '2019-04-01 00:00:00');
task.query();
ss.info('Count: ' + task.getRowCount());


addEncodedQuery(condition)


This method adds encoded query and applies it to the current query method.


Parameter(s)

NameTypeMandatoryDefault Value
conditionStringYN


Return:

TypeDescription
VoidThis method does not return a value.


Example:

Code Block
languagejs
themeEclipse
titleaddEncodedQuery
linenumberstrue
const employee = new SimpleRecord('employee');
employee.addEncodedQuery('%28locked_out%21%3D0%29%5EmanagerISEMPTY');
employee.query();
employee.setMultipleValue('locked_out', '0');
employee.updateMultiple();

canCreate()


This method checks whether inserting new records in this table satisfies the Access Control Rule.

Also, you can use this method in your UI Actions to adjust its visibility more precisely.


Return:

TypeDescription
BooleanThe method returns TRUE if this operation is permitted; otherwise it returns FALSE.


Example:

Code Block
languagejs
themeEclipse
titlecanCreate
linenumberstrue
current.canCreate()

canDelete()


This method checks whether deleting records in this table satisfies the Access Control Rule.

Also, you can use this method in your UI Actions to adjust its visibility more precisely.


Return:

TypeDescription
BooleanThe method returns TRUE if this operation is permitted; otherwise it returns FALSE.


Example:

Code Block
languagejs
themeEclipse
titlecanDelete
linenumberstrue
current.canDelete()

canRead()


This method checks whether reading records in this table satisfies the Access Control Rule.

Also, you can use this method in your UI Actions to adjust its visibility more precisely.


Return:

TypeDescription
BooleanThe method returns TRUE if this operation is permitted; otherwise it returns FALSE.


Example:

Code Block
languagejs
themeEclipse
titlecanRead
linenumberstrue
current.canRead()


canUpdate()


This method checks whether updating records in this table satisfies the Access Control Rule.

Also, you can use this method in your UI Actions to adjust its visibility more precisely.


Return:

TypeDescription
BooleanThe method returns TRUE if this operation is permitted; otherwise it returns FALSE.


Example:

Code Block
languagejs
themeEclipse
titlecanUpdate
linenumberstrue
current.canUpdate()

deleteMultiple()


This method allows deleting multiple records in a query selection. Please note that attachments cannot be deleted using this method.

Note

Do not use this method on tables with dependencies. Always delete each record individually.


Return:

TypeDescription
BooleanThis method returns TRUE  if deleted successfully; otherwise returns false.


Example:

Code Block
languagejs
themeEclipse
titledeleteMultiple
linenumberstrue
const record = new SimpleRecord('sys_translation');
record.addQuery('value', 'like', 'network');
record.query();
ss.info(record.getRowCount());
// record.deleteMultiple();


deleteRecord()


This method deletes the current record.


Return:

TypeDescription
BooleanThis method returns TRUE if the record is deleted successfully; otherwise it returns FALSE.


Example:

Code Block
languagejs
themeEclipse
titledeleteRecord
linenumberstrue
const incident = new SimpleRecord('itsm_incident');
incident.get('155931135900000000');
incident.deleteRecord();


get(propertyOrValue, value)


This method loads an object from a database by the field value, or, in a specific case, by the sys_id.


Parameter(s):

NameTypeMandatoryDefault Value
propertyOrValue

String value of record ID or property name. If it is equal to the property name, then the second parameter 'value' is mandatory.

Note

Passing 'NULL' or an empty string as the propertyOrValue parameter value will cause an exception looking alike:

"Argument 1 passed to "get()" must not be empty".


YN
valueStringNNULL


Return:

TypeDescription
SimpleRecord objectThis method returns the SimpleRecord object from the table specified in the query.


Example:

Code Block
languagejs
themeEclipse
titleget
linenumberstrue
const service = new SimpleRecord('c_service');
service.get(current.getValue('service'));
if (!!service.sys_id) {
  const company = new SimpleRecord('org_company');
  company.get('link', service.customer_url);
  ss.eventQueue('notify.company.responsible', current, company.responsible.email);
}


Code Block
languagejs
themeEclipse
titleget using REM
linenumberstrue
let record = new SimpleRecord('task');
record.get('160638931615274614'); // Example record ID supposing to be extended with RE attributes 
// record.rem_attr - an object containing information about RE attributes
ss.info(record.rem_attr.description); // In there, we have called the RE attribute as a property

getAttributes()


This method returns an object with current record properties as keys and properties values as key values.


Return:

TypeDescription
ObjectThe array containing attributes.


Code Block
languagejs
themeEclipse
titlegetAttributes
linenumberstrue
if (!!table.name) {
  const record = new SimpleRecord(table.name);
  record.get(recordID);
  if (record.getAttributes()['display_name'] != undefined) {
    current.display_name = `Approval for ${record.display_name}`;
  } else {
    ss.error(`Field display_name in record ${recordID} of table ${table.name} not found. Display Name for approval did not created!`);
  }
}

getClassDisplayValue()


This method returns the table title. If the title is not set, then returns name.


Return:

TypeDescription
StringTitle or name.


Example:

Code Block
languagejs
themeEclipse
titlegetClassDisplayValue
linenumberstrue
email.setSubject(`New ${current.getClassDisplayValue()} - ${current.number} has been created`);

getConditionQuery()


This method returns current query condition.


Return:

TypeDescription
StringThe query condition.


Example:

Code Block
languagejs
themeEclipse
titlegetConditionQuery
linenumberstrue
const task = new SimpleRecord('task');
const condition = task.addQuery('state', '7');
condition.addOrCondition('priority', '<', '3');
condition.addEncodedQuery('active=1');
ss.info(task.getConditionQuery());
// Info: ((state=7)^OR(priority<3))^(active=1)

getDisplayValue(property)


This method returns the displayed field value (the display_by_ref field) or record value. For example, for the reference field the entity name will be returned, but not the ID.


Parameter(s):

NameTypeMandatoryDefault Value
PropertyStringNNULL


Return:

TypeDescription
StringA field or record value.


Example:

Code Block
languagejs
themeEclipse
titlegetDisplayValue
linenumberstrue
email.setBody(`Dear ${current.getDisplayValue('caller').match(/^(\w+)/g)}:

Your ${current.getClassDisplayValue()} - ${current.number} has been registered`);

getErrors()


If the record creating, updating or deleting fails, then this method will display error message.

Use this method for control purposes if there any validation errors within your scripts.

Warning

Some validation errors may not be displayed within the debug process, so it is highly recommended to use this method.

For example, errors in condition queries passed by methods like addEncodedQuery(condition) or similar methods can be displayed by calling this method.


Return:

TypeDescription
ArrayThe error value.


Example:

Code Block
languagejs
themeEclipse
titlegetErrors
linenumberstrue
const table = new SimpleRecord('sys_db_table');
table.get('name', 'task');
if (!table.deleteRecord()) {
  const errors = table.getErrors();
  ss.addErrorMessage(JSON.stringify(errors));
}


getLabel(property)


This method gets the field title.


Parameter(s):

NameTypeMandatoryDefault Value
propertyStringYN


Return:

TypeDescription
StringThe field name.


Example:

Code Block
languagejs
themeEclipse
titlegetLabel
linenumberstrue
ss.error(`Field "${current.getLabel('username')}" cannot be blank`);

getRowCount()


This method gets the amount of items in a row.


Returns:

TypeDescription
IntegerItems amount in a row specified.

Example:

Code Block
languagejs
themeEclipse
titlegetRowCount
linenumberstrue
const incident = new SimpleRecord('itsm_incident');
incident.query();
ss.addInfoMessage('Total incident count: ' + incident.getRowCount());


getTableName()


This method gets the current table name.


Return:

TypeDescription
StringThe current table name.


Example:

Code Block
languagejs
themeEclipse
titlegetTableName
linenumberstrue
const otherRecord = new SimpleRecord(current.getTableName());
otherRecord.addQuery('type', current.type);
otherRecord.addQuery('sys_id', '!=', current.sys_id);
otherRecord.selectAttributes('sys_id');
otherRecord.query();
if (otherRecord.getRowCount() > 0) {
  const messageLinks = [];
  while(otherRecord.next()) {
    messageLinks.push(
      `<a href=${ss.getProperty('simple.instance.uri')}/record/${current.getTableName()}/${otherRecord.sys_id}>${otherRecord.sys_id}</a>`);
    ;
  }
  ss.addErrorMessage(`There're some records with same type: ${messageLinks.join('\n')}`);  
}


getValue(property)


This method returns the value of the object property based on its name.

If the field is of the Reference or List types, then its sys_id value returns.

Note

To speed up the script execution, use this method to get values of the fields of the Reference type instead of Dot-walking.

As an example, it is preferable to use the current.getValue('reference_field') structure instead of current.reference_field.sys_id one.


Parameter(s):

NameTypeMandatoryDefault Value
propertyStringYN


Return:

TypeDescription
Mixed

The string value of the object property.


Code Block
languagejs
themeEclipse
titlegetValue
linenumberstrue
ss.importIncludeScript('customEmployeeAbsent');
if (!!customEmployeeAbsent(current.getValue('assigned_user'))) {
  ss.addErrorMessage(`User ${current.assigned_user.display_name} is not available`);
}

hasAttachment()


This method checks whether the record specified has an attachment or not.


Return:

TypeDescription
BooleanMethod returns TRUE if the record has an attachment; otherwise, it returns FALSE.


Example:

Code Block
languagejs
themeEclipse
titlehasAttachment
linenumberstrue
current.state == 'new' && current.hasAttachment()


initialize()


This method populates all active empty fields with their predefined default values.

It works only for new records that were never saved and cannot be called repeatedly.

This method is called automatically and implicitly at the first set operation (also known as "the setter").


Return:

TypeDescription
VoidThis method does not return a value.


Example:

Code Block
languagejs
themeEclipse
titleinitialize
linenumberstrue
const taskRecord = new SimpleRecord('task')
ss.info(Object.entries(taskRecord.getAttributes()).filter(item => !item.includes('')));
taskRecord.initialize();
ss.info(Object.entries(taskRecord.getAttributes()).filter(item => !item.includes('')));

insert()


This method uses the field values of the current record to insert a new one.


If the record is not inserted then method returns '0' (zero) and adds an informative error message which can be obtained with getErrors() method.


Return:

TypeDescription
Integer
  • If validation errors occurred and record was not updated, then method returns '0' and you can get a message containing list of errors.
  • As a normal case, a unique ID of the inserted record returns.


Example:

Code Block
languagejs
themeEclipse
titleinsert
linenumberstrue
const newTask = new SimpleRecord('task');
newTask.subject = `New task`;
const inserterTaskID = newTask.insert();
if (inserterTaskID != 0) {
  current.parent_id = inserterTaskID;
} else {
  ss.addErrorMessage('Errors: ' + JSON.stringify(newTask.getErrors()));
}

isTableVcsEnabled()


This method checks whether the VCS enabled attribute is enabled against the specified table or not. 


Return:

TypeDescription
BooleanMethod returns value of is_vcs_enabled property of record table.

Example:

Code Block
languagejs
themeEclipse
titleisTableVcsEnabled
linenumberstrue
const table = new SimpleRecord('sys_db_table');
ss.info(table.isTableVcsEnabled()); // true


matchesCondition(condition)


This method checks whether the current record meets the condition in the current state.


NameTypeMandatoryDefault Value
conditionStringN''


Return:

TypeDescription
VoidThis method does not return a value.


Code Block
languagejs
themeEclipse
titlematchesCondition
linenumberstrue
const task = new SimpleRecord('task');
task.description = 'dsc';
ss.info(task.matchesCondition('descriptionLIKEesc')); // false
task.description = 'desc';
ss.info(task.matchesCondition('descriptionLIKEesc')); // true

next()


If this is a new request, then this method returns the first record from the list; otherwise it returns FALSE, in the case if the record is unavailable.


Return:

Type
Record or Boolean


Example:

Code Block
languagejs
themeEclipse
titlenext
linenumberstrue
const incident = new SimpleRecord('itsm_incident');
incident.selectAttributes('sys_id');
incident.query();
while (incident.next()){
  ss.info(incident.sys_id);
}


orderBy(column)


This method sorts records in the ascending order.


Tip

Call this method several times to order by multiple columns.


Parameter(s):

NameTypeMandatoryDefault Value
columnStringYN


Return:

TypeDescription
VoidThis method does not return a value.


Example:

Code Block
languagejs
themeEclipse
titleorderBy
linenumberstrue
const firstComment= new SimpleRecord('sys_activities_stream_field');
firstComment.addQuery('element_id', current.sys_id);
firstComment.orderBy('sys_created_at'); // oldest record first
firstComment.setLimit(1); // very first message
firstComment.selectAttributes(['value', 'sys_created_by']);
firstComment.query();
if (firstComment.getRowCount() > 0) {
  firstComment.next();
  email.setBody(`First comment was added by ${firstComment.sys_created_by.display_name}
Comment: "${firstComment.value}"
`);
}


orderByDesc(column)


This method sorts the records in the descending order.


Parameter(s):

NameTypeMandatoryDefault Value
columnStringYN


Return:

TypeDescription
VoidThis method does not return a value.


Example:

Code Block
languagejs
themeEclipse
titleorderByDesc
linenumberstrue
const logMessagelastComment = new SimpleRecord('sys_logactivities_stream_field');
logMessage.addQuery('level', 'debug');
logMessage.addQuery('message', 'startswith', 'Missed values generation');
logMessage.lastComment.orderByDesc('sys_created_at');
logMessage // newest record first
lastComment.setLimit(1); // last messagecomment
logMessagelastComment.selectAttributes(['message'value', 'sys_created_by']);
logMessagelastComment.query();
if (logMessagelastComment.getRowCount() > 0) {
  logMessagelastComment.next();
  if (logMessage.message.match(/(?<=LastTable: )(.\w+)/g)) {
    lastTable = logMessage.message.match(/(?<=LastTable: )(.\w+)/g)[0];
  }email.setBody(`Last comment was added by ${lastComment.sys_created_by.display_name}
Comment: "${lastComment.value}"
`);
}

query()


This method applies query to the selection from a database, based on the $this→query. After this, it fills in the record set.


Return:

TypeDescription
VoidThis method does not return a value.


selectAttributes(attributes)


This method is intended to optimize database queries. Sometimes, it is necessary to obtain only several object fields, not the whole object. Therefore, this method was added.


Warning

Do not use this method when selecting records that can be updated after being selected. Otherwise, when updating, some of the record field values may be lost, or record updating will throw an exception looking like this:

Info

You can't save incomplete record.



NameTypeMandatoryDefault Value
attributesString or ArrayYN

Return:

TypeDescription
SimpleRecord objectThis method returns a SimpleRecord object containing attributes.

Example:

Code Block
languagejs
themeEclipse
titleselectAttributes (String or Array)
linenumberstrue
const record = new SimpleRecord('user');
record.selectAttributes('email');
record.query();
while (record.next()) {
  ss.info(record.email || 'null'); // not null
  ss.info(record.first_name || 'null'); // null
  ss.info(record.username || 'null'); // null
  // other fields are null
}


Example:

Code Block
languagejs
themeEclipse
titleselectAttributes (Array)
linenumberstrue
const record = new SimpleRecord('user');
record.selectAttributes(['email', 'first_name']);
record.query();
while (record.next()) {
  ss.info(record.email || 'null'); // not null
  ss.info(record.first_name || 'null'); // not null
  ss.info(record.username || 'null'); // null
  // other fields are null
}

setAbortAction(flag)


This method is used in business rules and sets a flag, indicating that the current operation (insert/update/delete) will be interrupted.


Note

Please note that the code will not be executed if it is typed after calling this method in the script body.


Parameter(s):

NameTypeMandatoryDefault Value
flagBooleanYN


Return:

TypeDescription
VoidThis method does not return a value.


Example:

Code Block
languagejs
themeEclipse
titlesetAbortAction
linenumberstrue
const now = new SimpleDateTime(); // now

if (now.before(new SimpleDateTime(current.appropriate_date))) {
  ss.addErrorMessage(`Can't be updated before ${new SimpleDateTime(current.appropriate_date)}.getDisplayValue()`);
  current.setAbortAction(true);
}

setLimit(maxNumRecords)


This method limits the number of records selected by SimpleRecord query methods.


Parameter(s):

NameTypeMandatoryDefault Value
maxNumRecordsIntegerYN


Return:

TypeDescription
VoidThis method does not return a value.


Example:

Code Block
languagejs
themeEclipse
titlesetLimit
linenumberstrue
const incident = new SimpleRecord('itsm_incident');
incident.orderByDesc('sys_created_at');
incident.setLimit(1);
incident.query(); // last created incident
if (incident.getRowCount() > 0) {
  incident.next();
  ss.info(`Last incident was created at ${incident.sys_created_at}`);
}


setMultipleValue(property,value)


This method sets the properties values for every entry in the current selection.


Parameter(s):

NameTypeMandatoryDefault Value
propertyStringYN
valueStringYN

Return:

TypeDescription
Void

This method does not return a value.


Code Block
languagejs
themeEclipse
titlesetMultipleValue
linenumberstrue
const task = new SimpleRecord('task');
task.addQuery('state', '7'); // Draft
task.query();
ss.info(task.getRowCount());
task.setMultipleValue('state', '2'); // Open
// task.updateMultiple();

setValue(property, value)


This method sets the value of the field in the current record.


Parameter(s):

NameTypeMandatoryDefault Value
propertyStringYN
valueStringYN


Return:

TypeDescription
VoidThis property does not return a value.


Example:

Code Block
languagejs
themeEclipse
titlesetValue
linenumberstrue
const task = new SimpleRecord('task');
task.setValue('subject', 'mail');
task.insert();


silentMode(enable)


This method is intended to update the record without executing any entities related to this record implementing the business logic, such as business rules, notifications, workflows, etc.


NameTypeMandatoryDefault Value
enableBooleanNtrue


TypeDescription
VoidThis property does not return a value.


Code Block
languagejs
themeEclipse
titlesilentMode
linenumberstrue
const task = new SimpleRecord('task');
task.addQuery('active', false);
task.addQuery('approval_state', 'isempty');
task.query();
ss.info(task.getRowCount());
task.silentMode();
task.setMultipleValue('approval_state', 'not_requested'); // set Default Value
//task.updateMultiple();

update()


This method updates a database record. If the record existed before, the changes are applied. If the record did not exist before, it is inserted.


Return:

TypeDescription
Integer
  • If validation errors occurred and record was not updated, then method returns '0' and you can get a message containing list of errors;
  • As a normal case, an ID of the updated (inserted) record returns.


Example:

Code Block
languagejs
themeEclipse
titleupdate
linenumberstrue
const incident = new SimpleRecord('itsm_incident');
incident.get(record_id);
if (incident.sys_id) {
  incident.subject += " (repair)";
  const updatedID = incident.update();
  if (updatedID == 0) {
    ss.debug(incident.getErrors());
  }
}


updateMultiple()


This method updates all the selection entries.

Return:

TypeDescription
Void or Integer
  • If validation errors occurred and record was not updated, then method returns '0' and you can get a message containing list of errors;
  • Normally, this method does not return a value.


Code Block
languagejs
themeEclipse
titleupdateMultiple
linenumberstrue
const task = new SimpleRecord('task');
task.addQuery('state', '0'); // Open
task.query();
ss.info(task.getRowCount());
task.setMultipleValue('state', '10'); // Canceled
// task.updateMultiple();


Table of Contents
absoluteUrltrue
printablefalse