Working with databases
System databases. User databases.
Required:
iRidi Server
Documentation updated 01.01.2024
A database (DB) is a logical object containing tables and indexes.
iRidi has the following database types:
- System;
- User.
Before working with a database, you must configure tags to write to it.
This can be configured only in a server project.
System database
The system database is created with the server project and stores incoming tag data.
Only queries and reading are supported.
The system database contains several tables:
- FLOAT_TAG_HISTORY (contains the ID, TAG_ID, DATETIME, QUALITY, VALUE fields)
- INTEGER_TAG_HISTORY (contains the ID, TAG_ID, DATETIME, QUALITY, VALUE fields)
- QUALITY_LIST (contains the ID, NAME fields)
- STRING_TAG_HISTORY (contains the ID, TAG_ID, DATETIME, QUALITY, VALUE fields)
- TAGS_PASSPORT (contains the TAG_ID, TAG_TYPE, NAME, STATUS fields)
- TAG_STATUSES (contains the ID, NAME fields)
- TAG_TYPES_LIST (contains the ID, NAME, TABLE_NAME fields)
Location
You can locate the database file through the web server. Open the web server page in a browser and sign in to your account. The main page displays tabs for working with the server. The first row on the Database tab shows the database file location.

Automatic system database cleanup
If persistent storage is running out on the device running iRidi Server, you can use automatic system database cleanup.
Automatic system database cleanup is available on the server starting with v.1.3.55. The cleanup function has the following database fill levels:
- Normal - normal level [0-80%],
- Warning - a warning is issued [80-90%],
- Cleaning - database cleanup starts [90-95%],
- Overflow - the database is full; writing to all database tables stops [95-100%].
The database size limit is set to 300 MB.
Reaching each level and the start and end of database cleanup are recorded in the server log.
System database cleanup strategy:
- Cleaning - feedback channel value records are deleted:
- as entire files,
- from oldest to newest,
- across all feedback channels fairly (if a channel occupies more space than others, more of its files are deleted accordingly),
- until the Normal fill level is reached (at the boundary with Warning).
- Overflow :
- the database switches to Readonly,
- the same operations are performed as for Cleaning,
- if storage is successfully freed to at least below the Overflow level, the database leaves Readonly.
- If the server is started for the first time and its documents do not contain the old IridiumStorage.db database, automatic cleanup is enabled by default and the database is immediately saved in *.csv format. Otherwise, you must activate automatic database cleanup manually (see instructions .
- If you want to disable automatic database cleanup for any reason, contact our technical support: support@iridi.com.
Activating automatic system database cleanup
After updating your server to version 1.3.55, you can enable automatic system database cleanup.
To activate it:
-
Open the iRidi Server application web interface: http://192.168.1.254:8888/ (specify your device's address).
-
Open SYSTEM > Database .
-
In the Database cleanup section, click Activate cleanup .

- In the warning dialog, click ACTIVATE CLEANUP to activate automatic database cleanup, or click CANCEL to cancel.

After automatic system database cleanup is activated, writing to the old file stops and starts again in another format (*.csv). The old data is therefore unavailable to iRidi Server, but the old database file remains on the system. If you no longer need this data or have already copied it elsewhere, you can delete it (see the instructions below).
Moving and deleting the old database
If iRidi Server is running on Windows :
-
Open the system database folder (default: C:\Users\Documents\iRidium pro documents\Server\Database).
-
Copy the 'IridiumStorage.db elsewhere on the disk, or delete the file if you no longer need the old data.
If iRidi Server is running on Linux :
-
Install and start WinSCP.
-
Click the "Новое подключение" (new connection) tab and configure:
- "Протокол передачи" (file protocol) : SCP
- "Имя хоста" (host name) :
- "Порт" (port) : 22
- "Имя пользователя" (user name) : login
- "Пароль" (password) : password
- Select "Войти" (sign in) .

-
Open the iRidi Server system database folder (usually /var/lib/iRidi Server/DataBase/, or alternatively /root/iRidi Server/DataBase/)
-
Copy the IridiumStorage.db file to the required folder on your computer, or delete it from the iRidi Server system database folder if you no longer need the old data.
Configuring data storage in the database
Create a feedback for the device and, in its settings, select Store In DB .
Store In DB - specifies the data type for storing incoming values: *None - tag values are not written to the database; *Signed 32 bit - tag values are written as integers; *Float 64bit - tag values are written as decimal numbers; *String UTF8 - tag values are written as UTF8-encoded strings. After selecting the data type, you can define the save strategy: *Deadband - if the tag value is less than the number set in the "Deadband" field, the value is not written to the database. This strategy works only for numbers; *Interval - values are written at a time interval. You can select an interval from the list or set your own. To do this, select "Custom" in the "Interval" field and enter your time and unit.
With Deadband = 0, every tag change is recorded, regardless of the amount of change. In this mode, the database grows very quickly.

Working with the database through JavaScript
These methods work only with old *.db database files (created by the server before version XXX). They do not work with the new *.csv type.
Create a script with queries that log data matching specific conditions. You need to learn SQL to work with queries. Common database scenarios are described below.
var sql = IR.GetDatabase(); // присвоение переменной sql свойства системной базы.
Querying the database:
Assign the result of the sql database's Request method to the examp variable. Write the query body in single quotes inside parentheses.
var examp = sql.Request('SELECT ...');
Logging data from the database:
IR.Log(examp.Columns); // выводит в лог количество полей (столбцов) в запросе
IR.Log(examp.Rows); // выводит в лог количество записей (строк) в запросе
IR.Log(examp.GetRowValue(0,0)); //выводит в лог значение ячейки в строке с индексами (строка, столбец);
IR.Log(examp.GetColumnName(0)); //выводит имя поля, у которого индекс соответствует числу в скобках.
Example: select information from the database about tags with a value <1500.
var i;
var j;
IR.AddListener(IR.EVENT_START,0,function()
{
var sql = IR.GetDatabase(); // присвоили переменной sql свойства системной базы.
var examp = sql.Request('SELECT DISTINCT(ID), VALUE, TAG_ID FROM FLOAT_TAG_HISTORY WHERE VALUE<1500'); // присвоение переменной examp свойства Request базы sql. В скобках и одинарных кавычках пишется тело запроса.
for (i=0;i<examp.Columns;i++) //организовали цикл для вывода значений
for (j=0;j<examp.Rows;j++)
{
IR.Log(examp.GetRowValue(i,j); //выводим в лог значения полей
};
});
User database
A user database is created by the integrator. Its structure can be fully defined.
To create one, perform the following steps in the script editor:
- Create a variable to hold the database properties.
var mybase= new SQL();
- mybase - variable,
- new SQL() - creates a database object in iRidi JS.
- Create a database file for further use.
mybase.Open('Example.db');
Open - opens the database file. If the file does not exist, it is created in the application's documents folder, for example C:\Users\UserName\Documents\iRidium mobile 3\Settings\ Server\Database'Example.db' - the database name with its extension.
For fast, correct database writes, you must use logical commands.
mybase.Execute("BEGIN");
...
// Операции с базой;
...
mybase.Execute("COMMIT");
mybase.Close();
Execute - performs an operation on the database, "BEGIN" - starts writing to the database. "COMMIT" - ends writing to the database. Close() - closes the database.
- Create a table. This table will be empty.
mybase.Execute('CREATE TABLE Info(ID int, Value double, Name string)');
CREATE TABLE - creates a table named Info. ID, Value, Name are the table field names, containing int, double, string values respectively. You can change the field names, but you must specify each field's type.
- Writing to a table.
mybase.Execute('INSERT INTO Info(ID, Value, Name) VALUES(1,2.5,"sunny day")');
INSERT INTO writes to the Info table, specifically to the ID, Value, Name fields. VALUES - the values to write to the fields. The ID field receives the number 1, the Value field receives the number 2.5, and the Name field receives the text "sunny day".
The number of values in parentheses after VALUES must equal the number of fields declared in parentheses after INSERT INTO ().
There are some specifics to writing values to table fields. For example, use this syntax to write text:
VALUES("Iridium", "Mobile"); (Текст пишется в двойных кавычках).
To write a number, use this format:
VALUES( 1, 2.5, 36.788); (Число пишется без кавычек, десятичное число пишется с точкой)
To write the value of a variable, use:
// var CV = "Hello!"; (Объявленные ранее переменные)
// var V = 1.25;
...
VALUES("'+CV+'",'+V+');
First enter a single quote, then a plus sign, the variable itself, another plus sign, and another single quote.
- Deleting a table and adding fields.
Method for deleting a table:
mybase.Execute('DROP TABLE Testing');
Adding a field to an existing table.
mybase.Execute('ALTER TABLE Testing DROP COLUMN New_column');
Automatic user database cleanup
Coming in a future release.
Enabling automatic database cleanup in the server web interface does not delete user database data. Instead, the database is automatically vacuumed (VACUUM), which reduces its overall size.
-
Data vacuuming works only on server v.XXX and later.
-
Vacuuming can cause the system to hang, potentially for a long time if the database is too large. It can also cause a Linux system restart if iRidi Server was started with a watchdog.
-
To delete some outdated user database data and reduce its size further, you can use script listeners to monitor the database fill level.
Example script:
//Listener for NORMAL level
IR.AddListener(IR.EVENT_USER_DB_FILL_LEVEL_NORMAL, 0, function(name){
IR.Log(name + ": NORMAL FILL LEVEL EVENT");
});
//Listener for WARNING level
IR.AddListener(IR.EVENT_USER_DB_FILL_LEVEL_WARNING, 0, function(name){
IR.Log(name + ": WARNING FILL LEVEL EVENT");
});
//Listener for CLEANING level
IR.AddListener(IR.EVENT_USER_DB_FILL_LEVEL_CLEANING, 0, function(name){
IR.Log(name + ": CLEANING FILL LEVEL EVENT");
});
//Listener for OVERFLOW level
IR.AddListener(IR.EVENT_USER_DB_FILL_LEVEL_OVERFLOW, 0, function(name){
IR.Log(name + ": OVERFLOW FILL LEVEL EVENT");
if(EndsWith(name, "MyBase.db"))
{
IR.Log("My own cleaning...");
mybase.Open('MyBase.db', true);
mybase.Execute('DELETE FROM Info WHERE ID < 1000');
mybase.Close();
IR.Log("End my own cleaning.");
}
});
//Function for determining the name of the desired user database
function EndsWith(str, stringPart){
if(str !== undefined && stringPart !== undefined) {
var wordIndex = str.lastIndexOf(stringPart);
var result = str.substring(wordIndex, str.length);
if(result === stringPart){
return true;
} else {
return false;
}
}
}
Creating queries
These methods work only with old *.db database files (created by the server before version XXX). They do not work with the new *.csv type.
Common database scenarios are described below. In the iRidi script editor, you can write queries that log data matching specific conditions. You need to learn SQL to work with queries.
var mybase= new SQL(); // присвоили переменной sql свойства системной базы.
To query a database, perform the following operation:
var this_request = mybase.Request('SELECT ...'); // присвоение переменной this_request свойства Request базы mybase. В скобках и одинарных кавычках пишется тело запроса.
Logging.
// выводит в лог количество полей (столбцов) в запросе
IR.Log(this_request.Columns);
// выводит в лог количество записей (строк) в запросе
IR.Log(this_request.Rows);
//выводит в лог значение ячейки в строке с индексами (строка, столбец);
IR.Log(this_request.GetRowValue(0,0));
//выводит имя поля, у которого индекс соответствует числу в скобках.
IR.Log(this_request.GetColumnName(0));
Example: select information from the database about tags with a value <10.
function request()
{
//Открытие базы. Если такой базы нет, то она будет создана автоматически
mybase.Open('Example.db');
//Начало работы с базой
mybase.Execute("BEGIN");
// Создание переменной и присвоение ей метода запроса Request
var this_request = mybase.Request('SELECT * FROM Info WHERE Value<10');
//выводит имя поля, у которого индекс соответствует числу в скобках.
IR.Log(this_request.GetColumnName(0)+ '\t'+ this_request.GetColumnName(1)+ '\t'+ this_request.GetColumnName(2));
for (i=0;i<this_request.Rows;i++)
//вывод в лог значений полей
IR.Log(this_request.GetRowValue(0,i)+ '\t'+ this_request.GetRowValue(1,i)+ '\t'+ this_request.GetRowValue(2,i));
//Конец работы с базой
mybase.Execute("COMMIT");
//Закрытие базы
mybase.Close();
}