ioBroker / ioBroker.sql

Store history data in SQL Database: MySQL, PostgreSQL or SQLite
MIT License
45 stars 25 forks source link
history history-adapter iobroker mssql mysql postgresql sqlite storage-provider

Logo

ioBroker.sql

Number of Installations Number of Installations NPM version Downloads Tests

NPM

This adapter saves state history into SQL DB.

Supports PostgreSQL, mysql, Microsoft SQL Server and sqlite. You can leave port 0 if the default port is desired.

This adapter uses Sentry libraries to automatically report exceptions and code errors to the developers. For more details and for information how to disable the error reporting see Sentry-Plugin Documentation! Sentry reporting is used starting with js-controller 3.0.

Settings

Connection Settings

Default Settings

Most of these values can be pre-defined in the instance settings and are then pre-filled or used for the datapoint.

Database installation tips

MS-SQL:

Use localhost\instance for the host and check TCP/IP connections enabled. https://msdn.microsoft.com/en-us/library/bb909712(v=vs.90).aspx

SQLite:

is "file"-DB and cannot manage too many events. If you have a big amount of data, use the real DB, like PostgreSQL and co.

SQLite DB must not be installed extra. It is just a file on disk, but to install it you require build tools on your system. For linux, just write:

sudo apt-get install build-essential

For windows:

c:\>npm install --global --production windows-build-tools

and then reinstall the adapter, e.g:

cd /opt/iobroker
iobroker stop sql
npm install iobroker.sql --production
iobroker start sql

MySQL:

You can install mysql on linux systems as following:

apt-get install mysql-server mysql-client

mysql -u root -p

CREATE USER 'iobroker'@'%' IDENTIFIED BY 'iobroker';
GRANT ALL PRIVILEGES ON * . * TO 'iobroker'@'%';
FLUSH PRIVILEGES;

If required, edit /etc/mysql/my.cnf to set bind to IP-Address for remote connecting.

Warning: iobroker user is "admin". If required give limited rights to iobroker user.

On the "windows" it can be easily installed via installer: https://dev.mysql.com/downloads/installer/.

Pay attention to the authentication method. The new encryption algorithm in MySQL 8.0 is not yet supported by node.js and you must select legacy authentication method.

Windows

Structure of the DBs

The default Database name is iobroker, but it can be changed in the configuration.

Sources

This table is a list of adapter's instances, that wrote the entries. (state.from)

DB Name in query
MS-SQL iobroker.dbo.sources
MySQL iobroker.sources
PostgreSQL sources
SQLite sources

Structure:

Field Type Description
id INTEGER NOT NULL PRIMARY KEY IDENTITY(1,1) unique ID
name varchar(255) / TEXT instance of adapter, that wrote the entry

Note: MS-SQL uses varchar(255), and others use TEXT

Data points

This table is a list of data points. (IDs)

DB Name in query
MS-SQL iobroker.dbo.datapoints
MySQL iobroker.datapoints
PostgreSQL datapoints
SQLite datapoints

Structure:

Field Type Description
id INTEGER NOT NULL PRIMARY KEY IDENTITY(1,1) unique ID
name varchar(255) / TEXT ID of variable, e.g. hm-rpc.0.JEQ283747.1.STATE
type INTEGER 0 - number, 1 - string, 2 - boolean

Note: MS-SQL uses varchar(255), and others use TEXT

Numbers

Values for states with type "number". ts means "time series".

DB Name in query
MS-SQL iobroker.dbo.ts_number
MySQL iobroker.ts_number
PostgreSQL ts_number
SQLite ts_number

Structure:

Field Type Description
id INTEGER ID of state from "Data points" table
ts BIGINT / INTEGER Time in ms till epoch. Can be converted to time with "new Date(ts)"
val REAL Value
ack BIT/BOOLEAN Is acknowledged: 0 - not ack, 1 - ack
_from INTEGER ID of source from "Sources" table
q INTEGER Quality as number. You can find description here

Note: MS-SQL uses BIT, and others use BOOLEAN. SQLite uses for ts INTEGER and all others BIGINT.

The user can define additional to type number the functionality of counters. For this purpose, the following table is created: DB Name in the query
MS-SQL iobroker.dbo.ts_counter
MySQL iobroker.ts_counter
PostgreSQL ts_counter
SQLite ts_counter

Structure:

Field Type Description
id INTEGER ID of state from "Data points" table
ts BIGINT / INTEGER Time in ms till epoch. Can be converted to time with "new Date(ts)"
val REAL Value

This table stores the values when the counter was exchanged and the value does not increase, but failed to zero or lower value.

Strings

Values for states with type string.

DB Name in query
MS-SQL iobroker.dbo.ts_string
MySQL iobroker.ts_string
PostgreSQL ts_string
SQLite ts_string

Structure:

Field Type Description
id INTEGER ID of state from "Data points" table
ts BIGINT Time in ms till epoch. Can be converted to time with "new Date(ts)"
val TEXT Value
ack BIT/BOOLEAN Is acknowledged: 0 - not ack, 1 - ack
_from INTEGER ID of source from "Sources" table
q INTEGER Quality as number. You can find description here

Note: MS-SQL uses BIT, and others use BOOLEAN. SQLite uses for ts INTEGER and all others BIGINT.

Booleans

Values for states with type boolean.

DB Name in query
MS-SQL iobroker.dbo.ts_bool
MySQL iobroker.ts_bool
PostgreSQL ts_bool
SQLite ts_bool

Structure:

Field Type Description
id INTEGER ID of state from "Data points" table
ts BIGINT Time in ms till epoch. Can be converted to time with "new Date(ts)"
val BIT/BOOLEAN Value
ack BIT/BOOLEAN Is acknowledged: 0 - not ack, 1 - ack
_from INTEGER ID of source from "Sources" table
q INTEGER Quality as number. You can find description here

Note: MS-SQL uses BIT, and others use BOOLEAN. SQLite uses for ts INTEGER and all others BIGINT.

Access values from Javascript adapter

The sorted values can be accessed from Javascript adapter.

Possible options:

The first and last points will be calculated for aggregations, except aggregation none. If you manually request some aggregation, you should ignore first and last values, because they are calculated from values outside of a period.

Get counter

User can ask the value of some counter (type=number, counter=true) for a specific period.

var now = Date.now();
// get consumption value for last 30 days
sendTo('sql.0', 'getCounter', {
    id: 'system.adapter.admin.0.memRss',
    options: {
        start:      now - 3600000 * 24 * 30,
        end:        now,
    }
}, result => {
    console.log(`In last 30 days the consumption was ${result.result} kWh`);    
});

If the counter-device is replaced, it will be calculated too.

Custom queries

The user can execute custom queries on tables from javascript adapter:

sendTo('sql.0', 'query', 'SELECT * FROM datapoints', function (result) {
    if (result.error) {
        console.error(result.error);
    } else {
        // show result
         console.log('Rows: ' + JSON.stringify(result.result));
    }
});

Or get entries for the last hour for ID=system.adapter.admin.0.memRss

sendTo('sql.0', 'query', 'SELECT id FROM datapoints WHERE name="system.adapter.admin.0.memRss"', function (result) {
    if (result.error) {
        console.error(result.error);
    } else {
        // show result
        console.log('Rows: ' + JSON.stringify(result.result));
        var now = new Date();
        now.setHours(-1);
        sendTo('sql.0', 'query', 'SELECT * FROM ts_number WHERE ts >= ' + now.getTime() + ' AND id=' + result.result[0].id, function (result) {
            console.log('Rows: ' + JSON.stringify(result.result));
        });
    }
});

Note:

Depending on the database, the database name or database name + schema must be inserted before the table name - see boxes above under 'Structure of the DBs'.

Example if your database is called 'iobroker':

DB Name in query
MS-SQL SELECT * FROM iobroker.dbo.datapoints ...
MySQL SELECT * FROM iobroker.datapoints ...

storeState

If you want to write other data into the InfluxDB/SQL you can use the build in system function storeState. This function can also be used to convert data from other History adapters like History or SQL.

A successful response does not mean that the data is really written out to the disk. It just means that they were processed.

The given ids are not checked against the ioBroker database and do not need to be set up or enabled there. If own IDs are used without settings, then the "rules" parameter is not supported and will result in an error. The default "Maximal number of stored in RAM values" is used for such IDs.

The Message can have one of the following three formats:

sendTo('history.0', 'storeState', [
    id: 'mbus.0.counter.xxx',
    state: {ts: 1589458809352, val: 123, ack: false, from: 'system.adapter.whatever.0', ...}
], result => console.log('added'));
sendTo('history.0', 'storeState', {
    id: 'mbus.0.counter.xxx',
    state: [
      {ts: 1589458809352, val: 123, ack: false, from: 'system.adapter.whatever.0', ...}, 
      {ts: 1589458809353, val: 123, ack: false, from: 'system.adapter.whatever.0', ...}
    ]
}, result => console.log('added'));
sendTo('history.0', 'storeState', [
    {id: 'mbus.0.counter.xxx', state: {ts: 1589458809352, val: 123, ack: false, from: 'system.adapter.whatever.0', ...}}, 
    {id: 'mbus.0.counter.yyy', state: {ts: 1589458809353, val: 123, ack: false, from: 'system.adapter.whatever.0', ...}}
], result => console.log('added'));

Additionally, you can add attribute rules: true in a message to activate all rules, like counter, changesOnly, de-bounce and so on.

In case of errors, an array with all single error messages is returned and also a successCount to see how many entries were stored successfully.

delete state

If you want to delete entry from the Database, you can use the build in system function delete:

sendTo('sql.0', 'delete', [
    {id: 'mbus.0.counter.xxx', state: {ts: 1589458809352}, 
    {id: 'mbus.0.counter.yyy', state: {ts: 1589458809353}
], result => console.log('deleted'));

To delete ALL history data for some data point, execute:

sendTo('sql.0', 'deleteAll', [
    {id: 'mbus.0.counter.xxx'} 
    {id: 'mbus.0.counter.yyy'}
], result => console.log('deleted'));

To delete history data for some data point and for some range, execute:

sendTo('sql.0', 'deleteRange', [
    {id: 'mbus.0.counter.xxx', start: '2019-01-01T00:00:00.000Z', end: '2019-12-31T23:59:59.999'}, 
    {id: 'mbus.0.counter.yyy', start: 1589458809352, end: 1589458809353}
], result => console.log('deleted'));

Time could be ms since epoch or ans string, that could be converted by javascript Date object.

Values will be deleted including defined limits. ts >= start AND ts <= end

change state

If you want to change entry's value, quality or acknowledge flag in the database, you can use the build in system function update:

sendTo('sql.0', 'update', [
    {id: 'mbus.0.counter.xxx', state: {ts: 1589458809352, val: 15, ack: true, q: 0}, 
    {id: 'mbus.0.counter.yyy', state: {ts: 1589458809353, val: 16, ack: true, q: 0}
], result => console.log('deleted'));

ts is mandatory. At least one other flag must be included in a state object.

Be careful with counters. The counters in DB will not be reset, and you must handle it yourself.

History Logging Management via Javascript

The adapter supports enabling and disabling of history logging via JavaScript and also retrieving the list of enabled data points with their settings.

enable

The message requires having the "id" of the data point. Additionally, optional "options" to define the data point specific settings:

sendTo('sql.0', 'enableHistory', {
    id: 'system.adapter.sql.0.memRss',
    options: {
        changesOnly:  true,
        debounce:     0,
        retention:    31536000,
        maxLength:    3,
        changesMinDelta: 0.5,
        aliasId: ''
    }
}, function (result) {
    if (result.error) {
        console.log(result.error);
    }
    if (result.success) {
        //successful enabled
    }
});

disable

The message requires having the "id" of the data point.

sendTo('sql.0', 'disableHistory', {
    id: 'system.adapter.sql.0.memRss',
}, function (result) {
    if (result.error) {
        console.log(result.error);
    }
    if (result.success) {
        // successful enabled
    }
});

get List

The message has no parameters.

sendTo('sql.0', 'getEnabledDPs', {}, function (result) {
    //result is object like:
    {
        "system.adapter.sql.0.memRss": {
            "changesOnly":true,
            "debounce":0,
            "retention":31536000,
            "maxLength":3,
            "changesMinDelta":0.5,
            "enabled":true,
            "changesRelogInterval":0,
            "aliasId": ""
        }
        ...
    }
});

Changelog

3.0.1 (2024-06-13)

3.0.0 (2023-09-13)

2.2.0 (2022-09-19)

2.1.8 (2022-08-13)

2.1.7 (2022-06-30)

2.1.6 (2022-06-27)

2.1.5 (2022-06-27)

2.1.3 (2022-06-12)

2.1.2 (2022-06-08)

2.1.1 (2022-05-30)

2.1.0 (2022-05-27)

2.0.2 (2022-05-11)

2.0.0 (2022-05-11)

1.16.2 (2022-02-16)

1.16.1 (2021-12-19)

1.16.0 (2021-12-14)

1.15.7 (2021-04-28)

1.15.6 (2021-04-19)

1.15.5 (2021-01-22)

1.15.4 (2021-01-17)

1.15.3 (2020-08-29)

1.15.2 (2020-07-26)

1.15.1 (2020-07-20)

1.15.0 (2020-07-19)

BREAKING This version only accepts Node.js 10.x+ (because sqlite3 was upgraded)

1.14.2 (2020-06-23)

1.14.1 (2020-06-17)

1.14.0 (2020-05-20)

1.13.1 (2020-05-20)

1.12.6 (2020-05-08)

1.12.5 (2020-05-05)

1.12.4 (2020-05-04)

1.12.3 (2020-04-30)

1.12.2 (2020-04-30)

1.12.1 (2020-04-26)

1.12.0 (2020-04-23)

1.11.1 (2020-04-19)

1.10.1 (2020-04-12)

1.9.5 (2019-05-15)

1.9.4 (2019-02-24)

1.9.0 (2018-06-19)

1.8.0 (2018-04-29)

1.7.4 (2018-04-15)

1.7.3 (2018-03-28)

1.7.2 (2018-03-24)

1.7.1 (2018-02-10)

1.6.9 (2018-02-07)

1.6.7 (2018-01-31)

1.6.2 (2018-01-30)

1.6.0 (2018-01-14)

1.5.8 (2017-10-05)

1.5.7 (2017-08-10)

1.5.6 (2017-08-02)

1.5.4 (2017-06-12)

1.5.3 (2017-04-07)

1.5.0 (2017-03-02)

1.4.6 (2017-02-25)

1.4.5 (2017-02-18)

1.4.3 (2017-02-11)

1.4.2 (2017-01-16)

1.4.1

1.4.0 (2016-12-02)

1.3.4 (2016-11)

1.3.3 (2016-11)

1.3.2 (2016-11-21)

1.3.0 (2016-10-29)

1.2.1 (2016-08-30)

1.2.0 (2016-08-30)

1.0.10 (2016-08-27)

1.0.10 (2016-07-31)

1.0.9 (2016-06-14)

1.0.7 (2016-05-31)

1.0.6 (2016-05-30)

1.0.5 (2016-05-29)

1.0.4 (2016-05-29)

1.0.3 (2016-05-28)

1.0.2 (2016-05-24)

1.0.1 (2016-05-24)

1.0.0 (2016-05-20)

0.3.3 (2016-05-18)

0.3.2 (2016-05-13)

0.3.1 (2016-05-12)

0.3.0 (2016-05-08)

0.2.0 (2016-04-30)

0.1.4 (2016-04-25)

0.1.3 (2016-03-08)

0.1.2 (2015-12-22)

0.1.1 (2015-12-19)

0.1.0 (2015-12-14)

0.0.3 (2015-12-06)

0.0.2 (2015-12-06)

0.0.1 (2015-11-19)

License

The MIT License (MIT)

Copyright (c) 2015-2024 bluefox dogafox@gmail.com, Apollon77

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.