Versions Compared

Key

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

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:

Code Block
languagejs
themeEclipse
titleSimpleRecord
linenumberstrue
let sysNumber = '';
sysNumber += subject.match(/[A-Z]+\d+/g);
if (!!sysNumber) {
  const task = new SimpleRecord('task');
  task.get('number', sysNumber);
  if (!!task.sys_id) {
    task.state = '10'; // Cancelled  
    task.update();
  }
}


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();
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 String or BooleanNNULL


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

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


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


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


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


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

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

Also, do not use it combined with the setLimit() method when working with large tables.

Do not use the deleteMultiple() method on the tables with the currency fields. Always delete each record individually. Also, do not use this method with the chooseWindow() or setLimit() methods when working with large tables.


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

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

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);
}

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');
task.selectAttributes('sys_id');
task.next();
ss.info(task.getConditionQuery()); // Info: ((state=7)^OR(priority<3))^(active=1)
ss.info(task.getRowCount());


getDisplayValue(property)


This method returns displayed field or record value (the display_by_ref field). 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 will fail, then this method will display error message.

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();
  errors.forEach(error => {
    ss.addErrorMessage(error);
  }JSON,stringify(errors));
}


getLabel(property)


This method returns the field title.


Parameter(s):

NameTypeMandatoryDefault Value
propertyStringYN


Return:

TypeDescription
StringThe field title.


Example:

Code Block
languagejs
themeEclipse
titlegetLabel
linenumberstrue
const incident = new SimpleRecord('itsm_incident');
incident.get('150000000000000001');
ss.info(incident.getLabel('caller'))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:

Code Block
languagejs
themeEclipse
titlegetRowCount
linenumberstrue
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:

Code Block
languagejs
themeEclipse
titlegetTableName
linenumberstrue
const incidentotherRecord = new SimpleRecord('itsm_incident'(current.getTableName());
ssotherRecord.info(incident.getTableName()); // itsm_incident

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.

Parameter(s):

NameTypeMandatoryDefault ValuePropertyStringYN

Return:

TypeDescriptionMixed

The string value of the object property.

Code Block
languagejs
themeEclipse
titlegetValue
linenumberstrue
const task = new SimpleRecord('task');
task.get('150000000000000001');
ss.info(task.getValue('assigned_user')); // 150000000534521234

hasAttachment()

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

Return:

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

Example:

Code Block
languagejs
themeEclipse
titlehasAttachment
linenumberstrue
const task = new SimpleRecord('task');
task.get('157531598110402540');
ss.info(task.hasAttachment()); // false

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").
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.

Parameter(s):

NameTypeMandatoryDefault Value
PropertyStringYN


Return:

TypeDescription
VoidThis method does not return a value.

Example:

Mixed

The string value of the object property.


Code Block
languagejs
themeEclipse
titleinitializegetValue
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 inserts a new record using the field values set for the current record.

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 notIf 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.
  • BooleanMethod returns TRUE if the record has an attachment; otherwise, it returns FALSE
    As a normal case, a unique ID of the inserted record returns
    .


    Example:

    Code Block
    languagejs
    themeEclipse
    titleinserthasAttachment
    linenumberstrue
    const incident current.state == 'new SimpleRecord('itsm_incident');
    incident.insert();
    isTableVcsEnabled
    ' && 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"). 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.
    VoidThis method does not return a value.


    ExampleExample:

    Code Block
    languagejs
    themeEclipse
    titleisTableVcsEnabledinitialize
    linenumberstrue
    const tabletaskRecord = new SimpleRecord('sys_db_tabletask');
    ss.info(Object.entries(tabletaskRecord.isTableVcsEnabledgetAttributes()); // true

    matchesCondition(condition)

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

    NameTypeMandatoryDefault ValueconditionStringN''

    Return:

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

    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 table specified or not. 


    Return:

    TypeDescription
    BooleanMethod returns value of is_vcs_enabled property of record table.
    Code Block
    languagejs
    themeEclipse
    titlematchesCondition
    linenumberstrue
    const task = new SimpleRecord('task');
    rec.description = 'dsc';
    ss.info(rec.matchesCondition('descriptionLIKEesc')); // false
    rec.description = 'desc';
    ss.info(rec.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:

    TypeRecord or Boolean

    Example:

    Code Block
    languagejs
    themeEclipse
    titlenextisTableVcsEnabled
    linenumberstrue
    const incidenttable = new SimpleRecord('itsm_incident');
    incident.selectAttributes('sys_idsys_db_table');
    incidentss.query();
    while (incident.nextinfo(table.isTableVcsEnabled()){
    ;  ss.info(incident.sys_id);
    }
    orderBy(column
    // true


    matchesCondition(condition)


    This method

    sorts records

    checks whether the current record meets the condition being in the

    ascending order

    current state.

    Tip

    Call this method several times to order by multiple columns.

    Parameter(s):


    NameTypeMandatoryDefault Value
    conditionStringN''
    NameTypeMandatoryDefault ValuecolumnStringYN


    Return:

    TypeDescription
    VoidThis method does not return a value.

    Example:


    Code Block
    languagejs
    themeEclipse
    titleorderBymatchesCondition
    linenumberstrue
    const incidenttask = new SimpleRecord('itsm_incidenttask');
    incident.orderBy('sys_created_at');
    incident.query();

    orderByDesc(column)

    This method sorts the records in the descending order.

    Parameter(s):

    NameTypeMandatoryDefault ValuecolumnStringYN

    Return:

    TypeDescriptionVoidThis method does not return a value.
    rec.description = 'dsc';
    ss.info(rec.matchesCondition('descriptionLIKEesc')); // false
    rec.description = 'desc';
    ss.info(rec.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
    titleorderByDescnext
    linenumberstrue
    const incident = new SimpleRecord('itsm_incident');
    incident.orderByDesc('sys_updated_at');
    incident.query(););
    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');
    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 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.


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


    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))) {
      current.setAbortAction(true);
      ss.addErrorMessage(`Can't be updated before ${new SimpleDateTime(current.appropriate_date)}.getDisplayValue()`);
    }

    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:

    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
    enableBooleanYN


    TypeDescription
    VoidThis property does not return a value.


    Code Block
    languagejs
    themeEclipse
    titlesilentMode
    linenumberstrue
    const task = new SimpleRecord('task');
    task.query();
    task.next();
    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:

    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;
    • As a normal case, this method does not returns 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