You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 156 Next »

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
tableNameStringYN

Example:

SimpleRecord
const task = new SimpleRecord('task');
task.get('162494866118348768');


addOrCondition(property, operator, 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. In this method, you can use any preferred operator from the Condition Operators list, specified either in lowercase or in uppercase. Please notice that you need to use system name of the operator in your scripts.


Parameter(s):

NameTypeMandatoryDefault Value
propertyStringYN
operatorString (refer to the Condition Operators article for more information)NN
valueInteger or String or Boolean or ArrayYN


Return:

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


Example:

addOrCondition
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', true);
// task.updateMultiple();

addQuery(property, operator, 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. Please notice that you need to use system name of the operator in your scripts.


Parameter(s):

NameTypeMandatoryDefault Value
propertyStringYN
operatorString (refer to the Condition Operators article for more information)NN
valueInteger or String or Boolean or ArrayYN


Return:

TypeDescription
SimpleRecordThe query condition added to the SimpleRecord object.


Example:

addQuery
const task = new SimpleRecord('task');
task.addQuery('active', true);
task.addQuery('subject', 'like', 'email');
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:

addEncodedQuery
const employee = new SimpleRecord('employee');
employee.addEncodedQuery('%28locked_out%21%3D0%29%5EmanagerISEMPTY');
employee.query();
employee.setMultipleValue('locked_out', false);
// 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:

canCreate
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:

canDelete
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:

canRead
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:

canUpdate
current.canUpdate();

deleteMultiple()


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

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:

deleteMultiple
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:

deleteRecord
const incident = new SimpleRecord('itsm_incident');
incident.get('155931135900000000');
if (incident.sys_id) {
  const wasDeleted = incident.deleteRecord();
  if (wasDeleted) {
    ss.info('Incident ' + incident.sys_id + ' was deleted');
  } else {
    ss.error('Errors: ' + incident.getErrors());
  }
}

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.

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:

get
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.responsible', current, company.responsible.email);
}
get using REM
const 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.
getAttributes
const userRecord = ss.getUser();
ss.info(userRecord.getAttributes());
// Info: {"sys_id":"155931135900000001","sys_created_at":"2019-09-30 00:00:00","sys_updated_at":"2021-06-28...

getClassDisplayValue()


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


Return:

TypeDescription
StringTitle or name.


Example:

getClassDisplayValue
const taskTitle = current.getClassDisplayValue();
email.setSubject('New ' + taskTitle + ' has been created');

getConditionQuery()


This method returns current query condition.

Return:

TypeDescription
StringThe query condition.

Example:

getConditionQuery
const task = new SimpleRecord('task');
const condition = task.addQuery('state', '7');
condition.addOrCondition('priority', '<', '3');
ss.info('Condition before query: ' + task.getConditionQuery());
task.query();
ss.info('Condition after query: ' + task.getConditionQuery());
// Info: Condition before query: (state=7)^OR(priority<3)
// Info: Condition after query:

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:

getDisplayValue
const companyName = current.getDisplayValue('company');
email.setSubject('New employee at "' + companyName + '" company');

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.

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:

getErrors
const record = new SimpleRecord('user');
const newUserID = record.insert();
if (newUserID == 0) {
  ss.info(record.getErrors());
}
// Info: ["The \"\"First Name\" [first_name]\" field is mandatory. (record id: )",...

getLabel(property)


This method gets the field title.


Parameter(s):

NameTypeMandatoryDefault Value
propertyStringYN


Return:

TypeDescription
StringThe field name.


Example:

getLabel
const current = ss.getUser();
const fieldLabel = current.getLabel('username');
ss.addErrorMessage('Field "' +  fieldLabel + '" cannot be blank');
// Field "Login" cannot be blank

getRowCount()


This method gets the amount of items in a row.

Returns:

TypeDescription
IntegerItems amount in a row specified.

Example:

getRowCount
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:

getTableName
const current = ss.getUser();
ss.info('/list/' + current.getTableName());
// Info: /list/user

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.

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.


getValue
const current = ss.getUser();
const user = new SimpleRecord('user');
user.addQuery('timezone_id', current.getValue('timezone_id'));
user.query();
ss.info('Same timezone for: ' + user.getRowCount() + ' users');
// Info: Same timezone for: 36 users

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:

hasAttachment
const hasAttach = current.hasAttachment();
if (!hasAttach) {
  ss.addErrorMessage('File should be attached');
  current.setAbortAction(true);
}

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:

initialize
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('')));
// Info: []
// Info: [["active",1],["state",7],["opened_at","2021-06-29 10:06:38"],...

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:

insert
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:

isTableVcsEnabled
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
BooleanThis method returns 'true' if the record meets the condition specified; otherwise; it returns 'false'.
matchesCondition
const task = new SimpleRecord('task');
task.description = 'emaik';
ss.info(task.matchesCondition('descriptionLIKEemail')); // false
task.description = 'email';
ss.info(task.matchesCondition('descriptionLIKEemail')); // 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:

next
const user = new SimpleRecord('user');
user.setLimit(1);
user.query();
user.next();
ss.info(user.sys_id);
// Info: 100000000000000000

orderBy(column)


This method sorts records in the ascending order.

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:

orderBy
const firstLog = new SimpleRecord('sys_log');
firstLog.orderBy('sys_created_at'); // oldest record first
firstLog.addQuery('message', 'like', 'Connection');
firstLog.setLimit(1);
firstLog.selectAttributes(['message', 'sys_created_at']);
firstLog.query();
firstLog.next();
ss.info('[' + firstLog.sys_created_at + ']: ' + firstLog.message);
// Info: [2021-06-03 06:34:02]: IMAP IMAP (Default): Connection error: ...

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:

orderByDesc
const lastComment = new SimpleRecord('sys_activities_stream_field');
lastComment.orderByDesc('sys_created_at'); // newest record first
lastComment.setLimit(1);
lastComment.selectAttributes(['value', 'sys_created_by']);
lastComment.query();
lastComment.next();
ss.info(lastComment.sys_created_by.display_name + ': ' + lastComment.value);
// Info: Admin null: test

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.

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:

You can't save incomplete record.


NameTypeMandatoryDefault Value
attributesString or ArrayYN

It is allowed to pass a single attribute name as a string. But if you need to pass more than one attribute names, please use Array type (as shown in code example below).


Return:

TypeDescription
SimpleRecord objectThis method returns a SimpleRecord object containing attributes.

Example:

selectAttributes (String)
const record = new SimpleRecord('user');
record.selectAttributes('email');
record.query();
record.next();
ss.info(record.getAttributes());
// Info: {"email":"john.doe@email.com","sys_id":"162423321917274937"}


Example:

selectAttributes (Array)
const record = new SimpleRecord('user');
record.selectAttributes(['email', 'username']);
record.query();
record.next();
ss.info(record.getAttributes());
// Info: {"email":"john.doe@email.com","username":"john.doe","sys_id":"162423321917274937"}

setAbortAction(flag)


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


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:

setAbortAction
const NOW = new SimpleDateTime();
const appropriateDatetime = new SimpleDateTime(current.appropriate_date);

if (NOW.before(appropriateDatetime)) {
  ss.addErrorMessage("Can't be updated before " + appropriateDatetime.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:

setLimit
const record = new SimpleRecord('user');
record.setLimit(1);
record.query();
ss.info(record.getRowCount());
// Info: 1

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.

setMultipleValue
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:

setValue
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.
silentMode
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:

update
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.
updateMultiple
const task = new SimpleRecord('task');
task.addQuery('state', '0'); // Open
task.query();
ss.info(task.getRowCount());
task.setMultipleValue('state', '10'); // Canceled
// task.updateMultiple();


  • No labels