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

Compare with Current View Page History

« Previous Version 140 Next »

This server class provides methods to operate with database records.

SimpleRecord(tableName)


Instantiates a SimpleRecord class object for the table specified.


Parameter(s):

NameTypeMandatoryDefault Value
tableNameStringN''

Example:

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

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

addQuery(property, operatorOrValue, value)


This method adds a condition for the selection 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:

addQuery
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)


Adds encoded query to other queries already created.


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', '0');
employee.updateMultiple();

canCreate()


This method determines if the Access Control Rules permit inserting new records in this table.

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 determines if the Access Control Rules permit deleting records in this table.

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 determines if the Access Control Rules permit reading records in this table.

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 determines if the Access Control Rules permit updating records in this table.

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 that meet the query condition. It does not allow deleting attachments.

Do not use it 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(recordId)


This method deletes the current record.


Parameter(s):

NameTypeMandatoryDefault Value
recordIdIntegerN-1


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');
incident.deleteRecord();

get(propertyOrValue, value)


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


Parameter(s):

NameTypeMandatoryDefault Value
propertyOrValueString value of record ID or property name. If equals to property name, second param 'value' is mandatory.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.company.responsible', current, company.responsible.email);
}

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

getClassDisplayValue
email.setSubject(`New ${current.getClassDisplayValue()} - ${current.number} 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');
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:

getDisplayValue
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 will fail, then this method will display error message.

Return:

TypeDescription
ArrayThe error value.

Example:

getErrors
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 returns the field title.


Parameter(s):

NameTypeMandatoryDefault Value
propertyStringYN


Return:

TypeDescription
StringThe field name.


Example:

getLabel
ss.error(`Field "${current.getLabel('username')}" cannot be blank`);

getRowCount()


This method gets an amount of the 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 returns the current table name.


Return:

TypeDescription
StringThe current table name.


Example:

getTableName
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.

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

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

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

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('')));

insert()


This method inserts a new record using the field values set for the current record.

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 table specified 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 being in the current state.


NameTypeMandatoryDefault Value
conditionStringN''

Return:

TypeDescription
VoidThis method does not return a value.
matchesCondition
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:

next
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.

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 firstComment= new SimpleRecord('sys_activities_stream_field');
firstComment.addQuery('element_id', current.sys_id);
firstComment.orderBy('sys_created_at');
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:

orderByDesc
const logMessage = new SimpleRecord('sys_log');
logMessage.addQuery('level', 'debug');
logMessage.addQuery('message', 'startswith', 'Missed values generation');
logMessage.orderByDesc('sys_created_at');
logMessage.setLimit(1); // last message
logMessage.selectAttributes(['message']);
logMessage.query();
if (logMessage.getRowCount() > 0) {
  logMessage.next();
  if (logMessage.message.match(/(?<=LastTable: )(.\w+)/g)) {
    lastTable = logMessage.message.match(/(?<=LastTable: )(.\w+)/g)[0];
  }
}

query()


This method runs a query against the selection from the 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

Return:

TypeDescription
SimpleRecord objectThis method returns a SimpleRecord object containing attributes.

Example:

selectAttributes (String or Array)
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:

selectAttributes (Array)
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 sets a flag, indicating that will be current operation (insert/update/delete) interrupted. It is used in business rules.

Please keep in mind: the code being typed after calling this method in the script body will not be executed.


Parameter(s):

NameTypeMandatoryDefault Value
flagBooleanYN


Return:

TypeDescription
VoidThis method does not return a value.


Example:

setAbortAction
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)


Sets a limit for a number of records are fetched by SimpleRecord query.


Parameter(s):

NameTypeMandatoryDefault Value
maxNumRecordsIntegerYN


Return:

TypeDescription
VoidThis method does not return a value.


Example:

setLimit
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.

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
enableBooleanYN
TypeDescription
VoidThis property does not return a value.
silentMode
const task = new SimpleRecord('task');
task.query();
task.silentMode();
task.update();

update()


This method updates a database record. If the record does not exist, 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;
  • As a normal case, this method does not returns 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