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

Compare with Current View Page History

« Previous Version 9 Next »

ttps://home.simpleone.ru/record/sdlc_goal/159541824313375640

https://docs.google.com/spreadsheets/d/1dhiztB3hBmlEq2D1xFBrCE-tUGk9giKWgsmk6SSACAQ/edit#gid=614486133

What is REM?


To answer this question, we need to provide some theory first.

Thesis 1


In SimpleOne, you can handle with data which is represented as records in tables that have a specified attribute set. Records appear in tables and they have these attribute values given.

Thesis 2


Every table has its own data model stipulated by the business-logic. The data model is represented by the column set (their amount, types, links with another system objects, and so on). This data model can be extended with child table with the same attribute set as a parent one, and an individual attributes inaccessible from the parent table, as an addition.

Attributes extension curcuit diagram

Conclusion


To manage the commonalous entities (like ITSM Tasks), we can create a table with appropriate column set and extend from it for Incidents, Change Requests, Problems, and so on, creating respective tables that inherit attributes (columns) from a parent one and besides have their own attributes. For example, attribute overlap in there may be 70%, and unique attributes will be 30% of the total.

In this case, this model works fine (when we do not have many child tables, and the attribute overlap is high). But when the child table number increases, and the attribute overlap decreases, the management of this data model becomes a challenge. A Request Catalog can be taken as an example of such a table (a parent table for the catalog and a record in the table for every request template with specific attributes).

To deal with this issue, another concept has been created and implemented - Record Extended Model.

REM Concept


In this concept, extension concept can be applied for a specified table record giving some featured atrributes to it.

Physically, extension model are stored as records of the Models (sys_re_models) table, and they intended to collect specific attributes extending records. Attributes are stored as records of the Attributes (sys_re_attribute) table (extending the Columns (sys_db_column) table).

When a record extension model is applied to a record, it means that an auxiliary record set is created for this record containing information about specific attribute values. So the record has attributes inherited from a table, and in addition, it has attributes sourced from the extension model.


Configuring extension models


Generally, to configure your extension model, you need to:

  1. Create an extension model.
  2. Create attributes (and link it to the model).
  3. Configure RE client script if needed.

Creating models


To create a record extended model, please complete the steps below:

  1. Navigate to Record Extended Model → Models.
  2. Click New and fill in the fields.
  3. Click Save or Save and Exit to apply changes.

Record extended model form fields

FieldMandatoryDescription
NameYThe model name. 
TitleYThe model title. Can be specified in a language other than English.
DescriptionNThe model description. 
TableY

Reference to a table affected by the model.

Please note that you cannot specify a read-only table. To use such a table, please turn off this attribute first.

ActiveNSelect this checkbox to make the model active or inactive.
IconNReduced image intended for the model identification.
After insert scriptNSpecify a script that should be executed after a record is created. Develop it using JavaScript extended by the SimpleOne Server-Side API and Client-Side API methods.
Related lists
AttributeList of the RE attributes linked to this model.
Model client scriptList of the RE client scripts linked to this model.
Model form elementList of the RE model form element linked to this model.


Configuring attributes


To create an attribute, please complete the steps below:

  1. Navigate to Record Extended Model → Attributes.
  2. Click New and fill in the fields.
  3. Click Save or Save and Exit to apply changes.

Attribute form fields

FieldMandatoryDescription
RE modelYReference to a previously created model.
Column typeYSpecify a column type. 
TitleYAn attribute title. Can be specified in a language other than English. Latin, Cyrillic letters, [0..9] numbers and the underscore symbol ( _ ) are allowed.
Column nameYA column system name. Latin letters, [0..9] numbers and the underscore symbol ( _ ) are allowed.
Map to ColumnN

Specify a target field to map the attribute value after the record is created.


Существуют ситуации, когда мы хотим создать какую-то запись и не используем штатные механизмы создания записей, а используем только механизм создания атрибутов, моделей. Быстрая трансляция значения атрибутов в поля. Полезно, когда идет речь о дополнительной валидации.

CommentsNPut here some comments describing your attribute.
ActiveNSelect this checkbox to make the attribute active or inactive.
Read onlyNSelect this checkbox to make the field adding by this attribute read-only.
MandatoryNSelect this checkbox to make the field adding by this attribute mandatory.
Full text searchN
Display by refN
UniqueN
Type Specification tab
Max LengthN(For the columns that have a String or Text type) Specify a maximum value length for this column. The value length cannot exceed allowable length for the specified data type.
Default value tab
Default valueN

Specify a default value that will be populated to the field when creating a new record. This field may be specified by a Javascript scenario as well.

Use dynamic defaultN


To create a record extended model client script, please complete the steps below:

  1. Navigate to Record Extended Model → Model Client Scripts.
  2. Click New and fill in the fields.
  3. Click Save or Save and Exit to apply changes.

Record extended model client script form fields

FieldDescription
NameClient script name. This field is mandatory.
RE modelReference to a previously created model. This field is mandatory.
Type

The script type:

  • onLoad – it starts when the system displays the form for the first time before users will enter data. Generally, onLoad scripts perform manipulations on the client-side with the current form or set default record values;
  • onChange – it starts when the specified field in the form is changed;
  • onSubmit – this client-side script can cancel form submitting by returning false;
  • onCellEdit - this client-side script starts at the moment when some cell is to edit.
    • oldvalue - the old value for the cell that was edited;
    • newValue - the new value for the cell that was edited;
    • table - the table name of the cell being edited (for example, sys_db_table); 
    • sysId - the ID of the record relevant to the cell being edited;
    • callback - if this variable is equated to FALSE, then subsequent scripts will not run; otherwise, they will execute.
RE attributeReference to a previously created model attribute. This field is mandatory.
DescriptionClient script description.
ActiveSelect this checkbox to make the script active or inactive.
OrderClient script execution order. Scripts are executed in ascending order.
ScriptSpecify a client script. Develop it using JavaScript extended by the SimpleOne Client-Side API methods.

транскрибация записи



Порой, при работе в рамках одной таблицы, для расширенного сбора и последующей обработки информации, могут использоваться иные атрибуты, так называемые "переменные". Один из случаев, когда можно использовать такую функциональность, это когда в рамках одной таблицы, для разных записей нужны разные наборы атрибутов, а использование расширения таблиц, путем наследования, технологически неприемлемо (из-за большого количества специфичных полей в большом количестве наследуемых таблицах), а также влечет за собой увеличение трудозатрат на управление множеством специфических полей в наследуемых таблицах. Тогда необходимо использовать атрибуты расширенной модели записи.


Переменная записи это как бы поле, выглядит как поле, ведет себя как поле, но полем, т.е. объектом sys_db_column не является. Т.е. в “переменной” для определенной записи и в пользовательском интерфейсе, и в API можно задать значение, прочитать значение, изменить значение. На события, связанные с переменной и с ее содержимым, можно наложить необходимую для автоматизации бизнес-процесса логику. "Переменные" являются атомарным звеном и объединяются в модели записи или в коллекции атрибутов, и представляют собой расширенную модель записи. Коллекции могут включаться в разные модели записи. Модель записи определяется при создании записи путем выбора или предопределенного значения. 

Для целевой записи с определенной моделью записи можно задать значения переменных в виде ассоциированных с этой записью специальных записей, хранящих эти значения.



Первый тезис.

Наша система - это возможность управления данными, которые представлены в виде таблиц. Сами таблицы имеют определенный набор атрибутов. В этих таблицах появляются записи, у которых заданы значения этих атрибутов.

Второй тезис

Модель данных в той или иной таблице может быть расширена появлением дочерней таблицы, и у нас дочерняя таблица имеет в себе набор тех атрибутов, которые к ней пришли из родительской таблицы, и свой индивидуальный набор. Это наследование.

Если есть сущности, обладающие общностью, например, итсм таски, мы создаем соответствующую таблицу и от нее наследуем инциденты, реквесты и так далее. Получили, к примеру, 6 таблиц, у которых 70% атрибутов пересекается, и у каждой таблицы 30% свои атрибуты. В таких масштабах наследованием пользоваться удобно. Совсем другое дело, когда дочерних таблиц много.

Когда у нас есть какой-нибудь каталог запросов, в этом каталоге не 6 запросов, а 306) то наследование становится неудобным. И придумали еще один способ, как можно расширять модель данных. Причем это расширение будет справедливо для конкретной записи, а не в целом для набора записей в таблице. Что было сделано:

Мы сделали такую таблицу, в которой хранятся модели, эти модели могут применяться для какого-то типа записей для какой-то таблицы, и этой записи они могут добавить несколько специфичных атрибутов, которые описаны в этой модели. Получается, модель - это некий синоним шаблоона запроса.

Физически: есть табличка с этими модельками, к каждой модельке привязаны эти специфичные атрибуты, и есть запись, для которой эта модель может примениться. Применение модели означает, что когда мы создаем запись, мы: (1) задаем те значения, которые должны быть у этой записи, (2) и для этой записи мы создаем набор вспомогательных записей, в которых указано, что к этогй записи для специфичногог атрибута 1 такое-то значение, для атрибута 2 такое-то значение, и так далее. Получается: запись обладает атрибутами, которые есть у таблицы, и теми атрибутами и их значениями, на основании той модели с этой записью связанной. Для этой записи создается набор пар "атрибут : значение", набор связанных записей, которые указывают на эту запись, это указание на тот атрибут из этой модели и его значение, специфичное для этой записи. В данном случае у нас получается, что у этой записи нет колонок, но есть вспомогательные записи, которые содержат указания на атрибут и его значение. Но этот атрибут не является частью таблицы.

Допустим, есть запись типа "запрос" в таблице запросов, у всех записей в этой таблице есть общие поля типа "кто создал", "когда создал", "статус" и так далее. И это все является колонками таблицы. Мы говорим, что для этой записи хотим задавать такие параметры, как вкус, цвет, но эти вкус и цвет не являются колонками таблицы. Но в то же самое время для этой записи, которую мы создаем, где есть обычные поля, мы хотим еще чтобы были поля "вкус" и "цвет", которые мы выбрали. И эти вкус и цвет, они хранятся не как значения конкретной таблицы, а как вспомогательные записи, у этой записи есть указания, что это относится к этому запросу, какой атрибут мы характеризуем и его значение. Мы получаем вместо трех значений колонок три записи, в которых есть три параметра, которые как раз для запроса показывают какой вкус и цвет.

Дополнительные атрибуты можно подтягивать из других таблиц. Основной фокус работы этих расширенных атрибутов то, что они в целом копируют механику поведения и свойства штатных колонок, в том числе референс, чойс, лист, что угодно, в принципе могут подтягиваться в качестве значения ссылки на записи других таблиц.

Атрибут - это абстрактная сущность, похожая на обычную колонку таблицы, но ей не является по факту, но с точки зрения пользователя это как будто бы еще одно поле, которое ты заполняешь каким-то значением, но опять же оно хранится не как какое-то значение, а как отдельная запись в вспомогательной таблице.

Без модели, атрибут не имеет смысла, при создании атрибут связывается с моделью. Мы говорим, что у нас есть запрос, и он будет создан по такой-то модели. Это значит, что помимо штатных полей запроса мы еше запорлним вот эти вот атрибуты, которые пришли из модели.

Это полезно, когда мы оперируем большим количеством разнородных сущностей, которые должны обладать сходством. Простой пример: запросы. Там есть 10 базовых полей и куча отличающихся, и они созданы по сотне моделей. Плодить сто таблиц и этим управлять - это лишняя трата ресурсов. Гораздо проще натравить модельку с атрибутами, чем целую таблицу делать.

Этими атрибутами нужно управлять так же, как обычными полями. Потому что с точки зрения пользователя, он просто заполняет форму. 


  • No labels