iobroker.sql 3.0.1 → 4.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +142 -428
- package/admin/i18n/de/translations.json +1 -1
- package/admin/i18n/en/translations.json +1 -1
- package/admin/i18n/es/translations.json +12 -12
- package/admin/i18n/fr/translations.json +1 -1
- package/admin/i18n/it/translations.json +1 -1
- package/admin/i18n/nl/translations.json +1 -1
- package/admin/i18n/pt/translations.json +1 -1
- package/admin/i18n/ru/translations.json +1 -1
- package/admin/jsonConfig.json +423 -321
- package/admin/words.js +12 -12
- package/build/lib/aggregate.js +1484 -0
- package/build/lib/aggregate.js.map +1 -0
- package/build/lib/connection-factory.js +7 -0
- package/build/lib/connection-factory.js.map +1 -0
- package/build/lib/mssql-client.js +67 -0
- package/build/lib/mssql-client.js.map +1 -0
- package/build/lib/mssql.js +267 -0
- package/build/lib/mssql.js.map +1 -0
- package/build/lib/mysql-client.js +61 -0
- package/build/lib/mysql-client.js.map +1 -0
- package/build/lib/mysql.js +245 -0
- package/build/lib/mysql.js.map +1 -0
- package/build/lib/postgresql-client.js +56 -0
- package/build/lib/postgresql-client.js.map +1 -0
- package/build/lib/postgresql.js +241 -0
- package/build/lib/postgresql.js.map +1 -0
- package/build/lib/sql-client-pool.js +369 -0
- package/build/lib/sql-client-pool.js.map +1 -0
- package/build/lib/sql-client.js +110 -0
- package/build/lib/sql-client.js.map +1 -0
- package/build/lib/sqlite.js +244 -0
- package/build/lib/sqlite.js.map +1 -0
- package/build/lib/sqlite3-client.js +68 -0
- package/build/lib/sqlite3-client.js.map +1 -0
- package/build/main.js +3624 -0
- package/build/main.js.map +1 -0
- package/docker-compose.yaml +57 -0
- package/io-package.json +54 -31
- package/package.json +28 -20
- package/admin/.gitignore +0 -0
- package/lib/aggregate.js +0 -1000
- package/lib/mssql-client.js +0 -61
- package/lib/mssql.js +0 -278
- package/lib/mysql-client.js +0 -62
- package/lib/mysql.js +0 -263
- package/lib/postgresql-client.js +0 -202
- package/lib/postgresql.js +0 -260
- package/lib/sqlite.js +0 -260
- package/lib/tools.js +0 -99
- package/main.js +0 -3469
package/build/main.js
ADDED
|
@@ -0,0 +1,3624 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.SqlAdapter = void 0;
|
|
37
|
+
const adapter_core_1 = require("@iobroker/adapter-core"); // Get common adapter utils
|
|
38
|
+
const aggregate_1 = require("./lib/aggregate");
|
|
39
|
+
const node_fs_1 = require("node:fs");
|
|
40
|
+
const node_path_1 = require("node:path");
|
|
41
|
+
const MSSQL = __importStar(require("./lib/mssql"));
|
|
42
|
+
const MySQL = __importStar(require("./lib/mysql"));
|
|
43
|
+
const PostgreSQL = __importStar(require("./lib/postgresql"));
|
|
44
|
+
const SQLite = __importStar(require("./lib/sqlite"));
|
|
45
|
+
const mssql_client_1 = require("./lib/mssql-client");
|
|
46
|
+
const mysql_client_1 = require("./lib/mysql-client");
|
|
47
|
+
const postgresql_client_1 = require("./lib/postgresql-client");
|
|
48
|
+
const sqlite3_client_1 = require("./lib/sqlite3-client");
|
|
49
|
+
const SQLFuncs = {
|
|
50
|
+
mssql: {
|
|
51
|
+
init: MSSQL.init,
|
|
52
|
+
destroy: MSSQL.destroy,
|
|
53
|
+
getFirstTs: MSSQL.getFirstTs,
|
|
54
|
+
insert: MSSQL.insert,
|
|
55
|
+
retention: MSSQL.retention,
|
|
56
|
+
getIdSelect: MSSQL.getIdSelect,
|
|
57
|
+
getIdInsert: MSSQL.getIdInsert,
|
|
58
|
+
getIdUpdate: MSSQL.getIdUpdate,
|
|
59
|
+
getFromSelect: MSSQL.getFromSelect,
|
|
60
|
+
getFromInsert: MSSQL.getFromInsert,
|
|
61
|
+
getCounterDiff: MSSQL.getCounterDiff,
|
|
62
|
+
getHistory: MSSQL.getHistory,
|
|
63
|
+
deleteFromTable: MSSQL.deleteFromTable,
|
|
64
|
+
update: MSSQL.update,
|
|
65
|
+
},
|
|
66
|
+
mysql: {
|
|
67
|
+
init: MySQL.init,
|
|
68
|
+
destroy: MySQL.destroy,
|
|
69
|
+
getFirstTs: MySQL.getFirstTs,
|
|
70
|
+
insert: MySQL.insert,
|
|
71
|
+
retention: MySQL.retention,
|
|
72
|
+
getIdSelect: MySQL.getIdSelect,
|
|
73
|
+
getIdInsert: MySQL.getIdInsert,
|
|
74
|
+
getIdUpdate: MySQL.getIdUpdate,
|
|
75
|
+
getFromSelect: MySQL.getFromSelect,
|
|
76
|
+
getFromInsert: MySQL.getFromInsert,
|
|
77
|
+
getCounterDiff: MySQL.getCounterDiff,
|
|
78
|
+
getHistory: MySQL.getHistory,
|
|
79
|
+
deleteFromTable: MySQL.deleteFromTable,
|
|
80
|
+
update: MySQL.update,
|
|
81
|
+
},
|
|
82
|
+
postgresql: {
|
|
83
|
+
init: PostgreSQL.init,
|
|
84
|
+
destroy: PostgreSQL.destroy,
|
|
85
|
+
getFirstTs: PostgreSQL.getFirstTs,
|
|
86
|
+
insert: PostgreSQL.insert,
|
|
87
|
+
retention: PostgreSQL.retention,
|
|
88
|
+
getIdSelect: PostgreSQL.getIdSelect,
|
|
89
|
+
getIdInsert: PostgreSQL.getIdInsert,
|
|
90
|
+
getIdUpdate: PostgreSQL.getIdUpdate,
|
|
91
|
+
getFromSelect: PostgreSQL.getFromSelect,
|
|
92
|
+
getFromInsert: PostgreSQL.getFromInsert,
|
|
93
|
+
getCounterDiff: PostgreSQL.getCounterDiff,
|
|
94
|
+
getHistory: PostgreSQL.getHistory,
|
|
95
|
+
deleteFromTable: PostgreSQL.deleteFromTable,
|
|
96
|
+
update: PostgreSQL.update,
|
|
97
|
+
},
|
|
98
|
+
sqlite: {
|
|
99
|
+
init: SQLite.init,
|
|
100
|
+
destroy: SQLite.destroy,
|
|
101
|
+
getFirstTs: SQLite.getFirstTs,
|
|
102
|
+
insert: SQLite.insert,
|
|
103
|
+
retention: SQLite.retention,
|
|
104
|
+
getIdSelect: SQLite.getIdSelect,
|
|
105
|
+
getIdInsert: SQLite.getIdInsert,
|
|
106
|
+
getIdUpdate: SQLite.getIdUpdate,
|
|
107
|
+
getFromSelect: SQLite.getFromSelect,
|
|
108
|
+
getFromInsert: SQLite.getFromInsert,
|
|
109
|
+
getCounterDiff: SQLite.getCounterDiff,
|
|
110
|
+
getHistory: SQLite.getHistory,
|
|
111
|
+
deleteFromTable: SQLite.deleteFromTable,
|
|
112
|
+
update: SQLite.update,
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
const clients = {
|
|
116
|
+
postgresql: { multiRequests: true },
|
|
117
|
+
mysql: { multiRequests: true },
|
|
118
|
+
sqlite: { multiRequests: false },
|
|
119
|
+
mssql: { multiRequests: true },
|
|
120
|
+
};
|
|
121
|
+
const types = {
|
|
122
|
+
number: 0,
|
|
123
|
+
string: 1,
|
|
124
|
+
boolean: 2,
|
|
125
|
+
object: 1,
|
|
126
|
+
};
|
|
127
|
+
const dbNames = ['ts_number', 'ts_string', 'ts_bool'];
|
|
128
|
+
const storageTypes = ['Number', 'String', 'Boolean'];
|
|
129
|
+
function isEqual(a, b) {
|
|
130
|
+
//console.log('Compare ' + JSON.stringify(a) + ' with ' + JSON.stringify(b));
|
|
131
|
+
// Create arrays of property names
|
|
132
|
+
if (a === null || a === undefined || b === null || b === undefined) {
|
|
133
|
+
return a === b;
|
|
134
|
+
}
|
|
135
|
+
const aProps = Object.getOwnPropertyNames(a);
|
|
136
|
+
const bProps = Object.getOwnPropertyNames(b);
|
|
137
|
+
// If the number of properties is different,
|
|
138
|
+
// objects are not equivalent
|
|
139
|
+
if (aProps.length !== bProps.length) {
|
|
140
|
+
//console.log('num props different: ' + JSON.stringify(aProps) + ' / ' + JSON.stringify(bProps));
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
for (let i = 0; i < aProps.length; i++) {
|
|
144
|
+
const propName = aProps[i];
|
|
145
|
+
if (typeof a[propName] !== typeof b[propName]) {
|
|
146
|
+
//console.log('type props ' + propName + ' different');
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
else if (typeof a[propName] === 'object') {
|
|
150
|
+
if (!isEqual(a[propName], b[propName])) {
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
// If values of same property are not equal,
|
|
156
|
+
// objects are not equivalent
|
|
157
|
+
if (a[propName] !== b[propName]) {
|
|
158
|
+
//console.log('props ' + propName + ' different');
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
// If we made it this far, objects
|
|
164
|
+
// are considered equivalent
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
const MAX_TASKS = 100;
|
|
168
|
+
function sortByTs(a, b) {
|
|
169
|
+
const aTs = a.ts;
|
|
170
|
+
const bTs = b.ts;
|
|
171
|
+
return aTs < bTs ? -1 : aTs > bTs ? 1 : 0;
|
|
172
|
+
}
|
|
173
|
+
class SqlAdapter extends adapter_core_1.Adapter {
|
|
174
|
+
sqlDPs = {};
|
|
175
|
+
from = {};
|
|
176
|
+
tasks = [];
|
|
177
|
+
tasksReadType = [];
|
|
178
|
+
tasksStart = [];
|
|
179
|
+
isFromRunning = {};
|
|
180
|
+
aliasMap = {};
|
|
181
|
+
finished = false;
|
|
182
|
+
sqlConnected = null;
|
|
183
|
+
multiRequests = true;
|
|
184
|
+
subscribeAll = false;
|
|
185
|
+
clientPool = null;
|
|
186
|
+
reconnectTimeout = null;
|
|
187
|
+
testConnectTimeout = null;
|
|
188
|
+
dpOverviewTimeout = null;
|
|
189
|
+
bufferChecker = null;
|
|
190
|
+
activeConnections = 0;
|
|
191
|
+
poolBorrowGuard = []; // required until https://github.com/intellinote/sql-client/issues/7 is fixed
|
|
192
|
+
logConnectionUsage = true;
|
|
193
|
+
postgresDbCreated = false;
|
|
194
|
+
lockTasks = false;
|
|
195
|
+
sqlFuncs = null;
|
|
196
|
+
constructor(options = {}) {
|
|
197
|
+
super({
|
|
198
|
+
...options,
|
|
199
|
+
name: 'sql',
|
|
200
|
+
ready: () => this.main(),
|
|
201
|
+
message: (obj) => this.processMessage(obj),
|
|
202
|
+
stateChange: (id, state) => {
|
|
203
|
+
id = this.aliasMap[id] || id;
|
|
204
|
+
this.pushHistory(id, state);
|
|
205
|
+
},
|
|
206
|
+
objectChange: (id, obj) => {
|
|
207
|
+
let tmpState;
|
|
208
|
+
const now = Date.now();
|
|
209
|
+
const formerAliasId = this.aliasMap[id] || id;
|
|
210
|
+
if (obj?.common?.custom?.[this.namespace] &&
|
|
211
|
+
typeof obj.common.custom[this.namespace] === 'object' &&
|
|
212
|
+
obj.common.custom[this.namespace].enabled) {
|
|
213
|
+
const realId = id;
|
|
214
|
+
let checkForRemove = true;
|
|
215
|
+
if (obj.common.custom?.[this.namespace]?.aliasId) {
|
|
216
|
+
if (obj.common.custom[this.namespace].aliasId !== id) {
|
|
217
|
+
this.aliasMap[id] = obj.common.custom[this.namespace].aliasId;
|
|
218
|
+
this.log.debug(`Registered Alias: ${id} --> ${this.aliasMap[id]}`);
|
|
219
|
+
id = this.aliasMap[id];
|
|
220
|
+
checkForRemove = false;
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
this.log.warn(`Ignoring Alias-ID because identical to ID for ${id}`);
|
|
224
|
+
obj.common.custom[this.namespace].aliasId = '';
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
if (checkForRemove && this.aliasMap[id]) {
|
|
228
|
+
this.log.debug(`Removed Alias: ${id} !-> ${this.aliasMap[id]}`);
|
|
229
|
+
delete this.aliasMap[id];
|
|
230
|
+
}
|
|
231
|
+
if (!this.sqlDPs[formerAliasId]?.config && !this.subscribeAll) {
|
|
232
|
+
// un-subscribe
|
|
233
|
+
for (const _id in this.sqlDPs) {
|
|
234
|
+
if (Object.prototype.hasOwnProperty.call(this.sqlDPs, _id) &&
|
|
235
|
+
Object.prototype.hasOwnProperty.call(this.sqlDPs, this.sqlDPs[_id].realId)) {
|
|
236
|
+
this.unsubscribeForeignStates(this.sqlDPs[_id].realId);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
this.subscribeAll = true;
|
|
240
|
+
this.subscribeForeignStates('*');
|
|
241
|
+
}
|
|
242
|
+
if (this.sqlDPs[id] && this.sqlDPs[id].index === undefined) {
|
|
243
|
+
this.getId(id, this.sqlDPs[id].dbType, () => this.reInit(id, realId, formerAliasId, obj));
|
|
244
|
+
}
|
|
245
|
+
else {
|
|
246
|
+
this.reInit(id, realId, formerAliasId, obj);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
if (this.aliasMap[id]) {
|
|
251
|
+
this.log.debug(`Removed Alias: ${id} !-> ${this.aliasMap[id]}`);
|
|
252
|
+
delete this.aliasMap[id];
|
|
253
|
+
}
|
|
254
|
+
const sqlDP = this.sqlDPs[id];
|
|
255
|
+
id = formerAliasId;
|
|
256
|
+
if (sqlDP?.config) {
|
|
257
|
+
this.log.info(`disabled logging of ${id}`);
|
|
258
|
+
if (sqlDP.relogTimeout) {
|
|
259
|
+
clearTimeout(sqlDP.relogTimeout);
|
|
260
|
+
sqlDP.relogTimeout = null;
|
|
261
|
+
}
|
|
262
|
+
if (sqlDP.timeout) {
|
|
263
|
+
clearTimeout(sqlDP.timeout);
|
|
264
|
+
sqlDP.timeout = null;
|
|
265
|
+
}
|
|
266
|
+
if (sqlDP.state) {
|
|
267
|
+
tmpState = { ...sqlDP.state };
|
|
268
|
+
}
|
|
269
|
+
const state = sqlDP.state ? tmpState || null : null;
|
|
270
|
+
if (sqlDP.config) {
|
|
271
|
+
sqlDP.config.enabled = false;
|
|
272
|
+
if (sqlDP.skipped && !sqlDP.config.disableSkippedValueLogging) {
|
|
273
|
+
this.pushValueIntoDB(id, sqlDP.skipped, false, true);
|
|
274
|
+
sqlDP.skipped = null;
|
|
275
|
+
}
|
|
276
|
+
if (this.config.writeNulls) {
|
|
277
|
+
const nullValue = {
|
|
278
|
+
val: null,
|
|
279
|
+
ts: now,
|
|
280
|
+
lc: now,
|
|
281
|
+
q: 0x40,
|
|
282
|
+
from: `system.adapter.${this.namespace}`,
|
|
283
|
+
ack: true,
|
|
284
|
+
};
|
|
285
|
+
if (sqlDP.config.changesOnly && state && state.val !== null) {
|
|
286
|
+
((_id, _state, _nullValue) => {
|
|
287
|
+
_state.ts = now;
|
|
288
|
+
_state.from = `system.adapter.${this.namespace}`;
|
|
289
|
+
nullValue.ts += 4;
|
|
290
|
+
nullValue.lc += 4; // because of MS SQL
|
|
291
|
+
this.log.debug(`Write 1/2 "${_state.val}" _id: ${_id}`);
|
|
292
|
+
this.pushValueIntoDB(_id, _state, false, true, () => {
|
|
293
|
+
// terminate values with null to indicate adapter stop. timestamp + 1
|
|
294
|
+
this.log.debug(`Write 2/2 "null" _id: ${_id}`);
|
|
295
|
+
this.pushValueIntoDB(_id, _nullValue, false, false, () => delete this.sqlDPs[id]);
|
|
296
|
+
});
|
|
297
|
+
})(id, state, nullValue);
|
|
298
|
+
}
|
|
299
|
+
else {
|
|
300
|
+
// terminate values with null to indicate adapter stop. timestamp + 1
|
|
301
|
+
this.log.debug(`Write 0 NULL _id: ${id}`);
|
|
302
|
+
this.pushValueIntoDB(id, nullValue, false, false, () => delete this.sqlDPs[id]);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
else {
|
|
306
|
+
this.storeCached(id, () => delete this.sqlDPs[id]);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
else {
|
|
310
|
+
delete this.sqlDPs[id];
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
},
|
|
315
|
+
unload: (callback) => {
|
|
316
|
+
void this.finish(callback);
|
|
317
|
+
},
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
borrowClientFromPool(callback) {
|
|
321
|
+
if (!this.clientPool) {
|
|
322
|
+
this.setConnected(false);
|
|
323
|
+
return callback(new Error('No database connection'));
|
|
324
|
+
}
|
|
325
|
+
this.setConnected(true);
|
|
326
|
+
if (this.activeConnections >= this.config.maxConnections) {
|
|
327
|
+
if (this.logConnectionUsage) {
|
|
328
|
+
this.log.debug(`Borrow connection not possible: ${this.activeConnections} >= Max - Store for Later`);
|
|
329
|
+
}
|
|
330
|
+
this.poolBorrowGuard.push(callback);
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
this.activeConnections++;
|
|
334
|
+
if (this.logConnectionUsage) {
|
|
335
|
+
this.log.debug(`Borrow connection from pool: ${this.activeConnections} now`);
|
|
336
|
+
}
|
|
337
|
+
this.clientPool.borrow((err, client) => {
|
|
338
|
+
if (!err && client) {
|
|
339
|
+
// make sure we always have at least one error listener to prevent crashes
|
|
340
|
+
if (client.on && client.listenerCount && !client.listenerCount('error')) {
|
|
341
|
+
client.on('error', (err) => this.log.warn(`SQL client error: ${err}`));
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
else if (!client) {
|
|
345
|
+
this.activeConnections--;
|
|
346
|
+
}
|
|
347
|
+
callback(err, client);
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
returnClientToPool(client) {
|
|
351
|
+
if (client) {
|
|
352
|
+
this.activeConnections--;
|
|
353
|
+
}
|
|
354
|
+
if (this.logConnectionUsage) {
|
|
355
|
+
this.log.debug(`Return connection to pool: ${this.activeConnections} now`);
|
|
356
|
+
}
|
|
357
|
+
if (this.clientPool && client) {
|
|
358
|
+
if (this.poolBorrowGuard.length) {
|
|
359
|
+
this.activeConnections++;
|
|
360
|
+
if (this.logConnectionUsage) {
|
|
361
|
+
this.log.debug(`Borrow returned connection directly: ${this.activeConnections} now`);
|
|
362
|
+
}
|
|
363
|
+
const callback = this.poolBorrowGuard.shift();
|
|
364
|
+
callback(null, client);
|
|
365
|
+
}
|
|
366
|
+
else {
|
|
367
|
+
try {
|
|
368
|
+
this.clientPool.return(client);
|
|
369
|
+
}
|
|
370
|
+
catch {
|
|
371
|
+
// Ignore
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
normalizeCustomConfig(customConfig) {
|
|
377
|
+
// maxLength
|
|
378
|
+
if (!customConfig.maxLength && customConfig.maxLength !== '0' && customConfig.maxLength !== 0) {
|
|
379
|
+
customConfig.maxLength = this.config.maxLength || 0;
|
|
380
|
+
}
|
|
381
|
+
else {
|
|
382
|
+
customConfig.maxLength = parseInt(customConfig.maxLength, 10);
|
|
383
|
+
}
|
|
384
|
+
// retention
|
|
385
|
+
if (customConfig.retention || customConfig.retention === 0) {
|
|
386
|
+
customConfig.retention = parseInt(customConfig.retention, 10) || 0;
|
|
387
|
+
}
|
|
388
|
+
else {
|
|
389
|
+
customConfig.retention = this.config.retention;
|
|
390
|
+
}
|
|
391
|
+
if (customConfig.retention === -1) {
|
|
392
|
+
// customRetentionDuration
|
|
393
|
+
if (customConfig.customRetentionDuration !== undefined &&
|
|
394
|
+
customConfig.customRetentionDuration !== null &&
|
|
395
|
+
customConfig.customRetentionDuration !== '') {
|
|
396
|
+
customConfig.customRetentionDuration =
|
|
397
|
+
parseInt(customConfig.customRetentionDuration, 10) || 0;
|
|
398
|
+
}
|
|
399
|
+
else {
|
|
400
|
+
customConfig.customRetentionDuration = this.config.customRetentionDuration;
|
|
401
|
+
}
|
|
402
|
+
customConfig.retention = customConfig.customRetentionDuration * 24 * 60 * 60;
|
|
403
|
+
}
|
|
404
|
+
// debounceTime and debounce compatibility handling
|
|
405
|
+
if (!customConfig.blockTime && customConfig.blockTime !== '0' && customConfig.blockTime !== 0) {
|
|
406
|
+
if (!customConfig.debounce && customConfig.debounce !== '0' && customConfig.debounce !== 0) {
|
|
407
|
+
customConfig.blockTime = this.config.blockTime || 0;
|
|
408
|
+
}
|
|
409
|
+
else {
|
|
410
|
+
customConfig.blockTime = parseInt(customConfig.debounce, 10) || 0;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
else {
|
|
414
|
+
customConfig.blockTime = parseInt(customConfig.blockTime, 10) || 0;
|
|
415
|
+
}
|
|
416
|
+
if (!customConfig.debounceTime && customConfig.debounceTime !== '0' && customConfig.debounceTime !== 0) {
|
|
417
|
+
customConfig.debounceTime = this.config.debounceTime || 0;
|
|
418
|
+
}
|
|
419
|
+
else {
|
|
420
|
+
customConfig.debounceTime = parseInt(customConfig.debounceTime, 10) || 0;
|
|
421
|
+
}
|
|
422
|
+
// changesOnly
|
|
423
|
+
customConfig.changesOnly = customConfig.changesOnly === true || customConfig.changesOnly === 'true';
|
|
424
|
+
// ignoreZero
|
|
425
|
+
customConfig.ignoreZero = customConfig.ignoreZero === true || customConfig.ignoreZero === 'true';
|
|
426
|
+
// round
|
|
427
|
+
if (customConfig.round !== null && customConfig.round !== undefined && customConfig.round !== '') {
|
|
428
|
+
customConfig.round = parseInt(customConfig.round, 10);
|
|
429
|
+
if (!isFinite(customConfig.round) || customConfig.round < 0) {
|
|
430
|
+
customConfig.round = this.config.round;
|
|
431
|
+
}
|
|
432
|
+
else {
|
|
433
|
+
customConfig.round = Math.pow(10, parseInt(customConfig.round, 10));
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
else {
|
|
437
|
+
customConfig.round = this.config.round;
|
|
438
|
+
}
|
|
439
|
+
// ignoreAboveNumber
|
|
440
|
+
if (customConfig.ignoreAboveNumber !== undefined &&
|
|
441
|
+
customConfig.ignoreAboveNumber !== null &&
|
|
442
|
+
customConfig.ignoreAboveNumber !== '') {
|
|
443
|
+
customConfig.ignoreAboveNumber = parseFloat(customConfig.ignoreAboveNumber) || null;
|
|
444
|
+
}
|
|
445
|
+
// ignoreBelowNumber incl. ignoreBelowZero compatibility handling
|
|
446
|
+
if (customConfig.ignoreBelowNumber !== undefined &&
|
|
447
|
+
customConfig.ignoreBelowNumber !== null &&
|
|
448
|
+
customConfig.ignoreBelowNumber !== '') {
|
|
449
|
+
customConfig.ignoreBelowNumber = parseFloat(customConfig.ignoreBelowNumber) || null;
|
|
450
|
+
}
|
|
451
|
+
else if (customConfig.ignoreBelowZero === 'true' || customConfig.ignoreBelowZero === true) {
|
|
452
|
+
customConfig.ignoreBelowNumber = 0;
|
|
453
|
+
}
|
|
454
|
+
// disableSkippedValueLogging
|
|
455
|
+
if (customConfig.disableSkippedValueLogging !== undefined &&
|
|
456
|
+
customConfig.disableSkippedValueLogging !== null &&
|
|
457
|
+
customConfig.disableSkippedValueLogging !== '') {
|
|
458
|
+
customConfig.disableSkippedValueLogging =
|
|
459
|
+
customConfig.disableSkippedValueLogging === 'true' || customConfig.disableSkippedValueLogging === true;
|
|
460
|
+
}
|
|
461
|
+
else {
|
|
462
|
+
customConfig.disableSkippedValueLogging = this.config.disableSkippedValueLogging;
|
|
463
|
+
}
|
|
464
|
+
// enableDebugLogs
|
|
465
|
+
if (customConfig.enableDebugLogs !== undefined &&
|
|
466
|
+
customConfig.enableDebugLogs !== null &&
|
|
467
|
+
customConfig.enableDebugLogs !== '') {
|
|
468
|
+
customConfig.enableDebugLogs =
|
|
469
|
+
customConfig.enableDebugLogs === 'true' || customConfig.enableDebugLogs === true;
|
|
470
|
+
}
|
|
471
|
+
else {
|
|
472
|
+
customConfig.enableDebugLogs = this.config.enableDebugLogs;
|
|
473
|
+
}
|
|
474
|
+
// changesRelogInterval
|
|
475
|
+
if (customConfig.changesRelogInterval || customConfig.changesRelogInterval === 0) {
|
|
476
|
+
customConfig.changesRelogInterval = parseInt(customConfig.changesRelogInterval, 10) || 0;
|
|
477
|
+
}
|
|
478
|
+
else {
|
|
479
|
+
customConfig.changesRelogInterval = this.config.changesRelogInterval;
|
|
480
|
+
}
|
|
481
|
+
// changesMinDelta
|
|
482
|
+
if (customConfig.changesMinDelta || customConfig.changesMinDelta === 0) {
|
|
483
|
+
customConfig.changesMinDelta = parseFloat(customConfig.changesMinDelta.toString().replace(/,/g, '.')) || 0;
|
|
484
|
+
}
|
|
485
|
+
else {
|
|
486
|
+
customConfig.changesMinDelta = this.config.changesMinDelta;
|
|
487
|
+
}
|
|
488
|
+
// storageType
|
|
489
|
+
if (!customConfig.storageType) {
|
|
490
|
+
customConfig.storageType = false;
|
|
491
|
+
}
|
|
492
|
+
// add one day if retention is too small
|
|
493
|
+
if (customConfig.retention && customConfig.retention <= 604800) {
|
|
494
|
+
customConfig.retention += 86400;
|
|
495
|
+
}
|
|
496
|
+
return customConfig;
|
|
497
|
+
}
|
|
498
|
+
reInit(id, realId, formerAliasId, obj) {
|
|
499
|
+
const customConfig = this.normalizeCustomConfig(obj.common.custom?.[this.namespace]);
|
|
500
|
+
if (this.sqlDPs[formerAliasId]?.config && isEqual(customConfig, this.sqlDPs[formerAliasId].config)) {
|
|
501
|
+
if (obj.common.custom?.[this.namespace].enableDebugLogs) {
|
|
502
|
+
this.log.debug(`Object ${id} unchanged. Ignore`);
|
|
503
|
+
}
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
// relogTimeout
|
|
507
|
+
if (this.sqlDPs[formerAliasId] && this.sqlDPs[formerAliasId].relogTimeout) {
|
|
508
|
+
clearTimeout(this.sqlDPs[formerAliasId].relogTimeout);
|
|
509
|
+
this.sqlDPs[formerAliasId].relogTimeout = null;
|
|
510
|
+
}
|
|
511
|
+
const writeNull = !this.sqlDPs[id]?.config;
|
|
512
|
+
this.sqlDPs[id] = {
|
|
513
|
+
config: customConfig,
|
|
514
|
+
state: this.sqlDPs[id]?.state || null,
|
|
515
|
+
list: this.sqlDPs[id]?.list || [],
|
|
516
|
+
inFlight: this.sqlDPs[id]?.inFlight || {},
|
|
517
|
+
timeout: this.sqlDPs[id]?.timeout || null,
|
|
518
|
+
ts: this.sqlDPs[id]?.ts || null,
|
|
519
|
+
lastLogTime: 0,
|
|
520
|
+
relogTimeout: null,
|
|
521
|
+
realId: realId,
|
|
522
|
+
lastCheck: this.sqlDPs[id]?.lastCheck || Date.now() - Math.floor(Math.random() * 21600000 /* 6 hours */), // randomize lastCheck to avoid all datapoints to be checked at same timepoint
|
|
523
|
+
};
|
|
524
|
+
// changesRelogInterval
|
|
525
|
+
if (this.sqlDPs[id].config.changesOnly && this.sqlDPs[id].config.changesRelogInterval > 0) {
|
|
526
|
+
this.sqlDPs[id].relogTimeout = setTimeout((_id) => this.reLogHelper(_id), this.sqlDPs[id].config.changesRelogInterval * 500 * (1 + Math.random()), id);
|
|
527
|
+
}
|
|
528
|
+
if (writeNull && this.config.writeNulls) {
|
|
529
|
+
this.writeNulls(id);
|
|
530
|
+
}
|
|
531
|
+
this.log.info(`enabled logging of ${id}, Alias=${id !== realId}, WriteNulls=${writeNull}`);
|
|
532
|
+
}
|
|
533
|
+
setConnected(isConnected) {
|
|
534
|
+
if (this.sqlConnected !== isConnected) {
|
|
535
|
+
this.sqlConnected = isConnected;
|
|
536
|
+
void this.setState('info.connection', this.sqlConnected, true);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
connect(callback) {
|
|
540
|
+
if (this.reconnectTimeout) {
|
|
541
|
+
clearTimeout(this.reconnectTimeout);
|
|
542
|
+
this.reconnectTimeout = null;
|
|
543
|
+
}
|
|
544
|
+
if (!this.clientPool) {
|
|
545
|
+
this.setConnected(false);
|
|
546
|
+
let sqLiteOptions;
|
|
547
|
+
let msSQLOptions;
|
|
548
|
+
let mySQLOptions;
|
|
549
|
+
let postgreSQLOptions;
|
|
550
|
+
const poolOptions = {
|
|
551
|
+
max_idle: this.config.dbtype === 'sqlite' ? 1 : 2,
|
|
552
|
+
};
|
|
553
|
+
if (this.config.maxConnections) {
|
|
554
|
+
poolOptions.max_active = this.config.maxConnections + 1; // we use our own Pool limiter logic, so let library have one more to not block us too early
|
|
555
|
+
poolOptions.max_wait = 10000; // hard code for now
|
|
556
|
+
poolOptions.when_exhausted = 'block';
|
|
557
|
+
}
|
|
558
|
+
if (!this.config.dbtype) {
|
|
559
|
+
return this.log.error('DB Type is not defined!');
|
|
560
|
+
}
|
|
561
|
+
if (!clients[this.config.dbtype]) {
|
|
562
|
+
return this.log.error(`Unknown type "${this.config.dbtype}"`);
|
|
563
|
+
}
|
|
564
|
+
if (this.config.dbtype === 'postgresql') {
|
|
565
|
+
postgreSQLOptions = {
|
|
566
|
+
host: this.config.host,
|
|
567
|
+
user: this.config.user || '',
|
|
568
|
+
password: this.config.password || '',
|
|
569
|
+
port: this.config.port || undefined,
|
|
570
|
+
database: 'postgres',
|
|
571
|
+
ssl: this.config.encrypt
|
|
572
|
+
? {
|
|
573
|
+
rejectUnauthorized: !!this.config.rejectUnauthorized,
|
|
574
|
+
}
|
|
575
|
+
: undefined,
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
else if (this.config.dbtype === 'mssql') {
|
|
579
|
+
msSQLOptions = {
|
|
580
|
+
server: this.config.host, // needed for MSSQL
|
|
581
|
+
user: this.config.user || '',
|
|
582
|
+
password: this.config.password || '',
|
|
583
|
+
port: this.config.port || undefined,
|
|
584
|
+
options: {
|
|
585
|
+
encrypt: !!this.config.encrypt,
|
|
586
|
+
trustServerCertificate: !this.config.rejectUnauthorized,
|
|
587
|
+
},
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
else if (this.config.dbtype === 'mysql') {
|
|
591
|
+
mySQLOptions = {
|
|
592
|
+
host: this.config.host, // needed for PostgreSQL , MySQL
|
|
593
|
+
user: this.config.user || '',
|
|
594
|
+
password: this.config.password || '',
|
|
595
|
+
port: this.config.port || undefined,
|
|
596
|
+
ssl: this.config.encrypt
|
|
597
|
+
? {
|
|
598
|
+
rejectUnauthorized: !!this.config.rejectUnauthorized,
|
|
599
|
+
}
|
|
600
|
+
: undefined,
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
else if (this.config.dbtype === 'sqlite') {
|
|
604
|
+
sqLiteOptions = { fileName: this.getSqlLiteDir(this.config.fileName) };
|
|
605
|
+
}
|
|
606
|
+
if (this.config.dbtype === 'postgresql' && !this.postgresDbCreated && postgreSQLOptions) {
|
|
607
|
+
// special solution for postgres. Connect first to Db "postgres", create new DB "iobroker" and then connect to "iobroker" DB.
|
|
608
|
+
// connect first to DB postgres and create iobroker DB
|
|
609
|
+
this.log.info(`Postgres connection options: ${JSON.stringify(postgreSQLOptions).replace(postgreSQLOptions.password || '******', '****')}`);
|
|
610
|
+
const _client = new postgresql_client_1.PostgreSQLClient(postgreSQLOptions);
|
|
611
|
+
_client.on?.('error', (err) => this.log.warn(`SQL client error: ${err}`));
|
|
612
|
+
return _client.connect((err) => {
|
|
613
|
+
if (err) {
|
|
614
|
+
this.log.error(err.toString());
|
|
615
|
+
if (this.reconnectTimeout) {
|
|
616
|
+
clearTimeout(this.reconnectTimeout);
|
|
617
|
+
}
|
|
618
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
619
|
+
this.reconnectTimeout = null;
|
|
620
|
+
this.connect(callback);
|
|
621
|
+
}, 30000);
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
if (this.config.doNotCreateDatabase) {
|
|
625
|
+
_client.disconnect();
|
|
626
|
+
this.postgresDbCreated = true;
|
|
627
|
+
this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
|
|
628
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
629
|
+
this.reconnectTimeout = null;
|
|
630
|
+
this.connect(callback);
|
|
631
|
+
}, 100);
|
|
632
|
+
}
|
|
633
|
+
else {
|
|
634
|
+
_client.execute(`CREATE DATABASE ${this.config.dbname};`, (err) => {
|
|
635
|
+
_client.disconnect();
|
|
636
|
+
const typedError = err;
|
|
637
|
+
if (typedError && typedError.code !== '42P04') {
|
|
638
|
+
// if error not about yet exists
|
|
639
|
+
this.postgresDbCreated = false;
|
|
640
|
+
this.log.error(JSON.stringify(typedError));
|
|
641
|
+
this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
|
|
642
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
643
|
+
this.reconnectTimeout = null;
|
|
644
|
+
this.connect(callback);
|
|
645
|
+
}, 30000);
|
|
646
|
+
}
|
|
647
|
+
else {
|
|
648
|
+
// remember that DB is created
|
|
649
|
+
this.postgresDbCreated = true;
|
|
650
|
+
this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
|
|
651
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
652
|
+
this.reconnectTimeout = null;
|
|
653
|
+
this.connect(callback);
|
|
654
|
+
}, 100);
|
|
655
|
+
}
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
});
|
|
659
|
+
}
|
|
660
|
+
if (this.config.dbtype === 'postgresql' && postgreSQLOptions) {
|
|
661
|
+
postgreSQLOptions.database = this.config.dbname;
|
|
662
|
+
}
|
|
663
|
+
try {
|
|
664
|
+
if (this.config.dbtype === 'mssql' && msSQLOptions) {
|
|
665
|
+
this.clientPool = new mssql_client_1.MSSQLClientPool(poolOptions, msSQLOptions);
|
|
666
|
+
}
|
|
667
|
+
else if (this.config.dbtype === 'mysql' && mySQLOptions) {
|
|
668
|
+
this.clientPool = new mysql_client_1.MySQL2ClientPool(poolOptions, mySQLOptions);
|
|
669
|
+
}
|
|
670
|
+
else if (this.config.dbtype === 'sqlite' && sqLiteOptions) {
|
|
671
|
+
this.clientPool = new sqlite3_client_1.SQLite3ClientPool(poolOptions, sqLiteOptions);
|
|
672
|
+
}
|
|
673
|
+
else if (this.config.dbtype === 'postgresql' && postgreSQLOptions) {
|
|
674
|
+
this.clientPool = new postgresql_client_1.PostgreSQLClientPool(poolOptions, postgreSQLOptions);
|
|
675
|
+
}
|
|
676
|
+
else {
|
|
677
|
+
throw new Error('DB connection options not defined');
|
|
678
|
+
}
|
|
679
|
+
return this.clientPool.open(poolOptions, (err) => {
|
|
680
|
+
this.activeConnections = 0;
|
|
681
|
+
if (err) {
|
|
682
|
+
this.clientPool = null;
|
|
683
|
+
this.setConnected(false);
|
|
684
|
+
// JSON.stringify(Error) is "{}" and would swallow the message
|
|
685
|
+
this.log.error(err.message || err.toString());
|
|
686
|
+
this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
|
|
687
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
688
|
+
this.reconnectTimeout = null;
|
|
689
|
+
this.connect(callback);
|
|
690
|
+
}, 30000);
|
|
691
|
+
}
|
|
692
|
+
else {
|
|
693
|
+
if (this.reconnectTimeout) {
|
|
694
|
+
clearTimeout(this.reconnectTimeout);
|
|
695
|
+
}
|
|
696
|
+
setImmediate(() => this.connect(callback));
|
|
697
|
+
}
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
catch (ex) {
|
|
701
|
+
this.log.error(ex.toString());
|
|
702
|
+
this.log.error(ex.stack);
|
|
703
|
+
this.clientPool = null;
|
|
704
|
+
this.activeConnections = 0;
|
|
705
|
+
this.setConnected(false);
|
|
706
|
+
this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
|
|
707
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
708
|
+
this.reconnectTimeout = null;
|
|
709
|
+
this.connect(callback);
|
|
710
|
+
}, 30000);
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
this.allScripts(this.sqlFuncs.init(this.config.dbname, this.config.doNotCreateDatabase), 0, err => {
|
|
715
|
+
if (err) {
|
|
716
|
+
//this.log.error(err);
|
|
717
|
+
this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
|
|
718
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
719
|
+
this.reconnectTimeout = null;
|
|
720
|
+
this.connect(callback);
|
|
721
|
+
}, 30000);
|
|
722
|
+
}
|
|
723
|
+
else {
|
|
724
|
+
this.log.info(`Connected to ${this.config.dbtype}`);
|
|
725
|
+
// read all DB IDs and all FROM ids
|
|
726
|
+
this.getAllIds(() => this.getAllFroms(callback));
|
|
727
|
+
}
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
// Find sqlite data directory
|
|
731
|
+
getSqlLiteDir(fileName) {
|
|
732
|
+
fileName ||= 'sqlite.db';
|
|
733
|
+
fileName = fileName.replace(/\\/g, '/');
|
|
734
|
+
if (fileName[0] === '/' || fileName.match(/^\w:\//)) {
|
|
735
|
+
return fileName;
|
|
736
|
+
}
|
|
737
|
+
// normally /opt/iobroker/node_modules/iobroker.js-controller
|
|
738
|
+
// but can be /example/ioBroker.js-controller
|
|
739
|
+
const config = (0, node_path_1.join)((0, adapter_core_1.getAbsoluteDefaultDataDir)(), 'sqlite');
|
|
740
|
+
// create sqlite directory
|
|
741
|
+
if (!(0, node_fs_1.existsSync)(config)) {
|
|
742
|
+
(0, node_fs_1.mkdirSync)(config);
|
|
743
|
+
}
|
|
744
|
+
return (0, node_path_1.normalize)((0, node_path_1.join)(config, fileName));
|
|
745
|
+
}
|
|
746
|
+
async testConnection(msg) {
|
|
747
|
+
if (!msg?.message?.config) {
|
|
748
|
+
if (msg.callback) {
|
|
749
|
+
this.sendTo(msg.from, msg.command, { error: 'invalid config' }, msg.callback);
|
|
750
|
+
}
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
let sqLiteOptions;
|
|
754
|
+
let msSQLOptions;
|
|
755
|
+
let mySQLOptions;
|
|
756
|
+
let postgreSQLOptions;
|
|
757
|
+
const config = msg.message.config;
|
|
758
|
+
config.port = parseInt(config.port, 10) || 0;
|
|
759
|
+
if (config.dockerMysql?.enabled) {
|
|
760
|
+
// The container is started by the docker plugin; only align the connection settings
|
|
761
|
+
this.applyDockerMysqlConfig(config);
|
|
762
|
+
}
|
|
763
|
+
if (config.dbtype === 'postgresql') {
|
|
764
|
+
postgreSQLOptions = {
|
|
765
|
+
host: config.host,
|
|
766
|
+
user: config.user || '',
|
|
767
|
+
password: config.password || '',
|
|
768
|
+
port: config.port || undefined,
|
|
769
|
+
database: 'postgres',
|
|
770
|
+
ssl: config.encrypt
|
|
771
|
+
? {
|
|
772
|
+
rejectUnauthorized: !!config.rejectUnauthorized,
|
|
773
|
+
}
|
|
774
|
+
: undefined,
|
|
775
|
+
};
|
|
776
|
+
}
|
|
777
|
+
else if (config.dbtype === 'mssql') {
|
|
778
|
+
msSQLOptions = {
|
|
779
|
+
server: config.host, // needed for MSSQL
|
|
780
|
+
user: config.user || '',
|
|
781
|
+
password: config.password || '',
|
|
782
|
+
port: config.port || undefined,
|
|
783
|
+
options: {
|
|
784
|
+
encrypt: !!config.encrypt,
|
|
785
|
+
trustServerCertificate: !config.rejectUnauthorized,
|
|
786
|
+
},
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
else if (config.dbtype === 'mysql') {
|
|
790
|
+
mySQLOptions = {
|
|
791
|
+
host: config.host, // needed for PostgreSQL , MySQL
|
|
792
|
+
user: config.user || '',
|
|
793
|
+
password: config.password || '',
|
|
794
|
+
port: config.port || undefined,
|
|
795
|
+
ssl: config.encrypt
|
|
796
|
+
? {
|
|
797
|
+
rejectUnauthorized: !!config.rejectUnauthorized,
|
|
798
|
+
}
|
|
799
|
+
: undefined,
|
|
800
|
+
};
|
|
801
|
+
}
|
|
802
|
+
else if (config.dbtype === 'sqlite') {
|
|
803
|
+
sqLiteOptions = { fileName: this.getSqlLiteDir(config.fileName) };
|
|
804
|
+
}
|
|
805
|
+
try {
|
|
806
|
+
let client;
|
|
807
|
+
if (config.dbtype === 'postgresql' && postgreSQLOptions) {
|
|
808
|
+
client = new postgresql_client_1.PostgreSQLClient(postgreSQLOptions);
|
|
809
|
+
}
|
|
810
|
+
else if (config.dbtype === 'mssql' && msSQLOptions) {
|
|
811
|
+
client = new mssql_client_1.MSSQLClient(msSQLOptions);
|
|
812
|
+
}
|
|
813
|
+
else if (config.dbtype === 'mysql' && mySQLOptions) {
|
|
814
|
+
client = new mysql_client_1.MySQL2Client(mySQLOptions);
|
|
815
|
+
}
|
|
816
|
+
else if (config.dbtype === 'sqlite' && sqLiteOptions) {
|
|
817
|
+
client = new sqlite3_client_1.SQLite3Client(sqLiteOptions);
|
|
818
|
+
}
|
|
819
|
+
else {
|
|
820
|
+
this.sendTo(msg.from, msg.command, { error: 'Unknown DB type' }, msg.callback);
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
client.on?.('error', (err) => this.log.warn(`SQL client error: ${err}`));
|
|
824
|
+
this.testConnectTimeout = setTimeout(() => {
|
|
825
|
+
this.testConnectTimeout = null;
|
|
826
|
+
this.sendTo(msg.from, msg.command, { error: 'connect timeout' }, msg.callback);
|
|
827
|
+
}, 5000);
|
|
828
|
+
const err = await new Promise(resolve => client.connect((err) => {
|
|
829
|
+
if (err) {
|
|
830
|
+
if (this.testConnectTimeout) {
|
|
831
|
+
clearTimeout(this.testConnectTimeout);
|
|
832
|
+
this.testConnectTimeout = null;
|
|
833
|
+
}
|
|
834
|
+
this.sendTo(msg.from, msg.command, { error: `${err.code} ${err.toString()}` }, msg.callback);
|
|
835
|
+
return;
|
|
836
|
+
}
|
|
837
|
+
client.execute('SELECT 2 + 3 AS x', (err /* , rows, fields */) => {
|
|
838
|
+
client.disconnect();
|
|
839
|
+
resolve(err);
|
|
840
|
+
});
|
|
841
|
+
}));
|
|
842
|
+
if (this.testConnectTimeout) {
|
|
843
|
+
clearTimeout(this.testConnectTimeout);
|
|
844
|
+
this.testConnectTimeout = null;
|
|
845
|
+
this.sendTo(msg.from, msg.command, { error: err?.toString() || null }, msg.callback);
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
catch (ex) {
|
|
850
|
+
if (this.testConnectTimeout) {
|
|
851
|
+
clearTimeout(this.testConnectTimeout);
|
|
852
|
+
this.testConnectTimeout = null;
|
|
853
|
+
}
|
|
854
|
+
this.sendTo(msg.from, msg.command, { error: ex.toString() }, msg.callback);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
destroyDB(msg) {
|
|
858
|
+
try {
|
|
859
|
+
this.allScripts(this.sqlFuncs.destroy(this.config.dbname), 0, err => {
|
|
860
|
+
if (err) {
|
|
861
|
+
this.log.error(err.toString());
|
|
862
|
+
this.sendTo(msg.from, msg.command, { error: err.toString() }, msg.callback);
|
|
863
|
+
}
|
|
864
|
+
else {
|
|
865
|
+
this.sendTo(msg.from, msg.command, { error: null, result: 'deleted' }, msg.callback);
|
|
866
|
+
// restart adapter
|
|
867
|
+
setTimeout(() => this.getForeignObject(`system.adapter.${this.namespace}`, (err, obj) => {
|
|
868
|
+
if (!err && obj) {
|
|
869
|
+
void this.setForeignObject(obj._id, obj);
|
|
870
|
+
}
|
|
871
|
+
else {
|
|
872
|
+
this.log.error(`Cannot read object "system.adapter.${this.namespace}": ${err || 'Config does not exist'}`);
|
|
873
|
+
this.stop ? void this.stop() : void this.terminate();
|
|
874
|
+
}
|
|
875
|
+
}), 2000);
|
|
876
|
+
}
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
catch (ex) {
|
|
880
|
+
return this.sendTo(msg.from, msg.command, { error: ex.toString() }, msg.callback);
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
_userQuery(msg, callback) {
|
|
884
|
+
try {
|
|
885
|
+
if (typeof msg.message !== 'string' || !msg.message.length) {
|
|
886
|
+
throw new Error('No query provided');
|
|
887
|
+
}
|
|
888
|
+
this.log.debug(msg.message);
|
|
889
|
+
this.borrowClientFromPool((err, client) => {
|
|
890
|
+
if (err || !client) {
|
|
891
|
+
this.sendTo(msg.from, msg.command, { error: err?.toString() || 'No client' }, msg.callback);
|
|
892
|
+
this.returnClientToPool(client);
|
|
893
|
+
callback?.();
|
|
894
|
+
}
|
|
895
|
+
else {
|
|
896
|
+
client.execute(msg.message, (err, rows /* , fields */) => {
|
|
897
|
+
this.returnClientToPool(client);
|
|
898
|
+
//convert ts for postgresql and ms sqlserver
|
|
899
|
+
if (!err && rows?.[0] && typeof rows[0].ts === 'string') {
|
|
900
|
+
for (let i = 0; i < rows.length; i++) {
|
|
901
|
+
rows[i].ts = parseInt(rows[i].ts, 10);
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
this.sendTo(msg.from, msg.command, { error: err ? err.toString() : null, result: rows }, msg.callback);
|
|
905
|
+
callback?.();
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
catch (err) {
|
|
911
|
+
this.sendTo(msg.from, msg.command, { error: err.toString() }, msg.callback);
|
|
912
|
+
callback?.();
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
// execute custom query
|
|
916
|
+
query(msg) {
|
|
917
|
+
if (!this.multiRequests) {
|
|
918
|
+
if (this.tasks.length > MAX_TASKS) {
|
|
919
|
+
const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
|
|
920
|
+
this.log.error(error);
|
|
921
|
+
this.sendTo(msg.from, msg.command, { error }, msg.callback);
|
|
922
|
+
}
|
|
923
|
+
else {
|
|
924
|
+
this.tasks.push({ operation: 'userQuery', msg });
|
|
925
|
+
if (this.tasks.length === 1) {
|
|
926
|
+
this.processTasks();
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
else {
|
|
931
|
+
this._userQuery(msg);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
// one script
|
|
935
|
+
oneScript(script, cb) {
|
|
936
|
+
try {
|
|
937
|
+
this.borrowClientFromPool((err, client) => {
|
|
938
|
+
if (err || !client) {
|
|
939
|
+
this.clientPool?.close();
|
|
940
|
+
this.activeConnections = 0;
|
|
941
|
+
this.clientPool = null;
|
|
942
|
+
this.setConnected(false);
|
|
943
|
+
this.log.error(err?.toString() || 'No database connection');
|
|
944
|
+
return cb?.(err || new Error('No database connection'));
|
|
945
|
+
}
|
|
946
|
+
this.log.debug(script);
|
|
947
|
+
client.execute(script, (err) => {
|
|
948
|
+
this.log.debug(`Response: ${JSON.stringify(err)}`);
|
|
949
|
+
if (err) {
|
|
950
|
+
const typedError = err;
|
|
951
|
+
// Database 'iobroker' already exists. Choose a different database name.
|
|
952
|
+
if (typedError.number === 1801 ||
|
|
953
|
+
// There is already an object named 'sources' in the database.
|
|
954
|
+
typedError.number === 2714) {
|
|
955
|
+
// do nothing
|
|
956
|
+
err = null;
|
|
957
|
+
}
|
|
958
|
+
else if (typedError.message?.match(/^SQLITE_ERROR: table [\w_]+ already exists$/)) {
|
|
959
|
+
// do nothing
|
|
960
|
+
err = null;
|
|
961
|
+
}
|
|
962
|
+
else if (typedError.errno == 1007 || typedError.errno == 1050) {
|
|
963
|
+
// if a database exists or table exists,
|
|
964
|
+
// do nothing
|
|
965
|
+
err = null;
|
|
966
|
+
}
|
|
967
|
+
else if (typedError.code === '42P04') {
|
|
968
|
+
// if a database exists or table exists,
|
|
969
|
+
// do nothing
|
|
970
|
+
err = null;
|
|
971
|
+
}
|
|
972
|
+
else if (typedError.code === '42P07') {
|
|
973
|
+
const match = script.match(/CREATE\s+TABLE\s+(\w*)\s+\(/);
|
|
974
|
+
if (match) {
|
|
975
|
+
this.log.debug(`OK. Table "${match[1]}" yet exists`);
|
|
976
|
+
err = null;
|
|
977
|
+
}
|
|
978
|
+
else {
|
|
979
|
+
this.log.error(script);
|
|
980
|
+
this.log.error(err.toString());
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
else if (script.startsWith('CREATE INDEX')) {
|
|
984
|
+
this.log.info('Ignore Error on Create index. You might want to create the index yourself!');
|
|
985
|
+
this.log.info(script);
|
|
986
|
+
this.log.info(`${typedError.code}: ${err}`);
|
|
987
|
+
err = null;
|
|
988
|
+
}
|
|
989
|
+
else {
|
|
990
|
+
this.log.error(script);
|
|
991
|
+
this.log.error(err.toString());
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
this.returnClientToPool(client);
|
|
995
|
+
cb?.(err);
|
|
996
|
+
});
|
|
997
|
+
});
|
|
998
|
+
}
|
|
999
|
+
catch (ex) {
|
|
1000
|
+
this.log.error(ex);
|
|
1001
|
+
cb?.(ex);
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
// all scripts
|
|
1005
|
+
allScripts(scripts, index, cb) {
|
|
1006
|
+
index ||= 0;
|
|
1007
|
+
if (scripts && index < scripts.length) {
|
|
1008
|
+
this.oneScript(scripts[index], err => {
|
|
1009
|
+
if (err) {
|
|
1010
|
+
cb?.(err);
|
|
1011
|
+
}
|
|
1012
|
+
else {
|
|
1013
|
+
this.allScripts(scripts, index + 1, cb);
|
|
1014
|
+
}
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
else {
|
|
1018
|
+
cb?.();
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
finish(callback) {
|
|
1022
|
+
let count = 0;
|
|
1023
|
+
const now = Date.now();
|
|
1024
|
+
const allFinished = () => {
|
|
1025
|
+
if (this.clientPool) {
|
|
1026
|
+
this.clientPool.close();
|
|
1027
|
+
this.activeConnections = 0;
|
|
1028
|
+
this.clientPool = null;
|
|
1029
|
+
this.setConnected(false);
|
|
1030
|
+
}
|
|
1031
|
+
if (typeof this.finished === 'object') {
|
|
1032
|
+
setTimeout((cb) => {
|
|
1033
|
+
for (let f = 0; f < cb.length; f++) {
|
|
1034
|
+
typeof cb[f] === 'function' && cb[f]();
|
|
1035
|
+
}
|
|
1036
|
+
}, 500, this.finished);
|
|
1037
|
+
this.finished = true;
|
|
1038
|
+
}
|
|
1039
|
+
};
|
|
1040
|
+
const finishId = (id) => {
|
|
1041
|
+
if (!this.sqlDPs[id]) {
|
|
1042
|
+
return;
|
|
1043
|
+
}
|
|
1044
|
+
if (this.sqlDPs[id].relogTimeout) {
|
|
1045
|
+
clearTimeout(this.sqlDPs[id].relogTimeout);
|
|
1046
|
+
this.sqlDPs[id].relogTimeout = null;
|
|
1047
|
+
}
|
|
1048
|
+
if (this.sqlDPs[id].timeout) {
|
|
1049
|
+
clearTimeout(this.sqlDPs[id].timeout);
|
|
1050
|
+
this.sqlDPs[id].timeout = null;
|
|
1051
|
+
}
|
|
1052
|
+
const state = this.sqlDPs[id].state ? { ...this.sqlDPs[id].state } : null;
|
|
1053
|
+
if (this.sqlDPs[id].skipped &&
|
|
1054
|
+
!(this.sqlDPs[id].config && this.sqlDPs[id].config.disableSkippedValueLogging)) {
|
|
1055
|
+
count++;
|
|
1056
|
+
this.pushValueIntoDB(id, this.sqlDPs[id].skipped, false, true, () => {
|
|
1057
|
+
if (!--count) {
|
|
1058
|
+
this.pushValuesIntoDB(id, this.sqlDPs[id].list, () => {
|
|
1059
|
+
allFinished();
|
|
1060
|
+
});
|
|
1061
|
+
}
|
|
1062
|
+
});
|
|
1063
|
+
this.sqlDPs[id].skipped = null;
|
|
1064
|
+
}
|
|
1065
|
+
const nullValue = {
|
|
1066
|
+
ack: true,
|
|
1067
|
+
val: null,
|
|
1068
|
+
ts: now,
|
|
1069
|
+
lc: now,
|
|
1070
|
+
q: 0x40,
|
|
1071
|
+
from: `system.adapter.${this.namespace}`,
|
|
1072
|
+
};
|
|
1073
|
+
if (this.sqlDPs[id].config && this.config.writeNulls) {
|
|
1074
|
+
if (this.sqlDPs[id].config.changesOnly && state && state.val !== null) {
|
|
1075
|
+
count++;
|
|
1076
|
+
((_id, _state, _nullValue) => {
|
|
1077
|
+
_state.ts = now;
|
|
1078
|
+
_state.from = `system.adapter.${this.namespace}`;
|
|
1079
|
+
nullValue.ts += 4;
|
|
1080
|
+
nullValue.lc += 4; // because of MS SQL
|
|
1081
|
+
this.log.debug(`Write 1/2 "${_state.val}" _id: ${_id}`);
|
|
1082
|
+
this.pushValueIntoDB(_id, _state, false, true, () => {
|
|
1083
|
+
// terminate values with null to indicate adapter stop. timestamp + 1
|
|
1084
|
+
this.log.debug(`Write 2/2 "null" _id: ${_id}`);
|
|
1085
|
+
this.pushValueIntoDB(_id, _nullValue, false, true, () => {
|
|
1086
|
+
if (!--count) {
|
|
1087
|
+
this.pushValuesIntoDB(id, this.sqlDPs[id].list, () => {
|
|
1088
|
+
allFinished();
|
|
1089
|
+
});
|
|
1090
|
+
}
|
|
1091
|
+
});
|
|
1092
|
+
});
|
|
1093
|
+
})(id, state, nullValue);
|
|
1094
|
+
}
|
|
1095
|
+
else {
|
|
1096
|
+
// terminate values with null to indicate adapter stop. timestamp + 1
|
|
1097
|
+
count++;
|
|
1098
|
+
this.log.debug(`Write 0 NULL _id: ${id}`);
|
|
1099
|
+
this.pushValueIntoDB(id, nullValue, false, true, () => {
|
|
1100
|
+
if (!--count) {
|
|
1101
|
+
this.pushValuesIntoDB(id, this.sqlDPs[id].list, () => {
|
|
1102
|
+
allFinished();
|
|
1103
|
+
});
|
|
1104
|
+
}
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
if (!this.subscribeAll) {
|
|
1110
|
+
for (const _id in this.sqlDPs) {
|
|
1111
|
+
if (Object.prototype.hasOwnProperty.call(this.sqlDPs, _id) &&
|
|
1112
|
+
Object.prototype.hasOwnProperty.call(this.sqlDPs, this.sqlDPs[_id].realId)) {
|
|
1113
|
+
this.unsubscribeForeignStates(this.sqlDPs[_id].realId);
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
else {
|
|
1118
|
+
this.subscribeAll = false;
|
|
1119
|
+
this.unsubscribeForeignStates('*');
|
|
1120
|
+
}
|
|
1121
|
+
if (this.reconnectTimeout) {
|
|
1122
|
+
clearTimeout(this.reconnectTimeout);
|
|
1123
|
+
this.reconnectTimeout = null;
|
|
1124
|
+
}
|
|
1125
|
+
if (this.testConnectTimeout) {
|
|
1126
|
+
clearTimeout(this.testConnectTimeout);
|
|
1127
|
+
this.testConnectTimeout = null;
|
|
1128
|
+
}
|
|
1129
|
+
if (this.dpOverviewTimeout) {
|
|
1130
|
+
clearTimeout(this.dpOverviewTimeout);
|
|
1131
|
+
this.dpOverviewTimeout = null;
|
|
1132
|
+
}
|
|
1133
|
+
if (this.bufferChecker) {
|
|
1134
|
+
clearInterval(this.bufferChecker);
|
|
1135
|
+
this.bufferChecker = null;
|
|
1136
|
+
}
|
|
1137
|
+
if (this.finished) {
|
|
1138
|
+
if (callback) {
|
|
1139
|
+
if (this.finished === true) {
|
|
1140
|
+
callback();
|
|
1141
|
+
}
|
|
1142
|
+
else {
|
|
1143
|
+
this.finished.push(callback);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
return;
|
|
1147
|
+
}
|
|
1148
|
+
this.finished = [callback];
|
|
1149
|
+
let dpcount = 0;
|
|
1150
|
+
let delay = 0;
|
|
1151
|
+
for (const id in this.sqlDPs) {
|
|
1152
|
+
if (!Object.prototype.hasOwnProperty.call(this.sqlDPs, id)) {
|
|
1153
|
+
continue;
|
|
1154
|
+
}
|
|
1155
|
+
dpcount++;
|
|
1156
|
+
delay += dpcount % 50 === 0 ? 1000 : 0;
|
|
1157
|
+
setTimeout(finishId, delay, id);
|
|
1158
|
+
}
|
|
1159
|
+
if (!dpcount && callback) {
|
|
1160
|
+
if (this.clientPool) {
|
|
1161
|
+
this.clientPool.close();
|
|
1162
|
+
this.activeConnections = 0;
|
|
1163
|
+
this.clientPool = null;
|
|
1164
|
+
this.setConnected(false);
|
|
1165
|
+
}
|
|
1166
|
+
callback();
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
processMessage(msg) {
|
|
1170
|
+
if (msg.command === 'features') {
|
|
1171
|
+
this.sendTo(msg.from, msg.command, { supportedFeatures: ['update', 'delete', 'deleteRange', 'deleteAll', 'storeState'] }, msg.callback);
|
|
1172
|
+
}
|
|
1173
|
+
else if (msg.command === 'getHistory') {
|
|
1174
|
+
this.getHistorySql(msg);
|
|
1175
|
+
}
|
|
1176
|
+
else if (msg.command === 'getCounter') {
|
|
1177
|
+
this.getCounterDiff(msg);
|
|
1178
|
+
}
|
|
1179
|
+
else if (msg.command === 'test') {
|
|
1180
|
+
void this.testConnection(msg);
|
|
1181
|
+
}
|
|
1182
|
+
else if (msg.command === 'destroy') {
|
|
1183
|
+
this.destroyDB(msg);
|
|
1184
|
+
}
|
|
1185
|
+
else if (msg.command === 'query') {
|
|
1186
|
+
this.query(msg);
|
|
1187
|
+
}
|
|
1188
|
+
else if (msg.command === 'update') {
|
|
1189
|
+
this.updateState(msg);
|
|
1190
|
+
}
|
|
1191
|
+
else if (msg.command === 'delete') {
|
|
1192
|
+
this.deleteHistoryEntry(msg);
|
|
1193
|
+
}
|
|
1194
|
+
else if (msg.command === 'deleteAll') {
|
|
1195
|
+
this.deleteStateAll(msg);
|
|
1196
|
+
}
|
|
1197
|
+
else if (msg.command === 'deleteRange') {
|
|
1198
|
+
this.deleteHistoryEntry(msg);
|
|
1199
|
+
}
|
|
1200
|
+
else if (msg.command === 'storeState') {
|
|
1201
|
+
this.storeState(msg).catch(e => this.log.error(`Cannot store state: ${e}`));
|
|
1202
|
+
}
|
|
1203
|
+
else if (msg.command === 'getDpOverview') {
|
|
1204
|
+
this.getDpOverview(msg);
|
|
1205
|
+
}
|
|
1206
|
+
else if (msg.command === 'enableHistory') {
|
|
1207
|
+
this.enableHistory(msg);
|
|
1208
|
+
}
|
|
1209
|
+
else if (msg.command === 'disableHistory') {
|
|
1210
|
+
this.disableHistory(msg);
|
|
1211
|
+
}
|
|
1212
|
+
else if (msg.command === 'getEnabledDPs') {
|
|
1213
|
+
this.getEnabledDPs(msg);
|
|
1214
|
+
}
|
|
1215
|
+
else if (msg.command === 'stopInstance') {
|
|
1216
|
+
this.finish(() => {
|
|
1217
|
+
if (msg.callback) {
|
|
1218
|
+
this.sendTo(msg.from, msg.command, 'stopped', msg.callback);
|
|
1219
|
+
setTimeout(() => (this.stop ? this.stop() : this.terminate?.()), 200);
|
|
1220
|
+
}
|
|
1221
|
+
});
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
processStartValues(callback) {
|
|
1225
|
+
if (this.tasksStart?.length) {
|
|
1226
|
+
const task = this.tasksStart.shift();
|
|
1227
|
+
const sqlDP = this.sqlDPs[task.id];
|
|
1228
|
+
if (sqlDP.config.changesOnly) {
|
|
1229
|
+
void this.getForeignState(sqlDP.realId, (err, state) => {
|
|
1230
|
+
const now = task.now || Date.now();
|
|
1231
|
+
this.pushHistory(task.id, {
|
|
1232
|
+
val: null,
|
|
1233
|
+
ts: state ? now - 4 : now, // 4 is because of MS SQL
|
|
1234
|
+
lc: state ? now - 4 : now, // 4 is because of MS SQL
|
|
1235
|
+
ack: true,
|
|
1236
|
+
q: 0x40,
|
|
1237
|
+
from: `system.adapter.${this.namespace}`,
|
|
1238
|
+
});
|
|
1239
|
+
if (state) {
|
|
1240
|
+
state.ts = now;
|
|
1241
|
+
state.lc = now;
|
|
1242
|
+
state.from = `system.adapter.${this.namespace}`;
|
|
1243
|
+
this.pushHistory(task.id, state);
|
|
1244
|
+
}
|
|
1245
|
+
setImmediate(() => this.processStartValues());
|
|
1246
|
+
});
|
|
1247
|
+
}
|
|
1248
|
+
else {
|
|
1249
|
+
const now = Date.now();
|
|
1250
|
+
this.pushHistory(task.id, {
|
|
1251
|
+
val: null,
|
|
1252
|
+
ts: task.now || now,
|
|
1253
|
+
lc: task.now || now,
|
|
1254
|
+
ack: true,
|
|
1255
|
+
q: 0x40,
|
|
1256
|
+
from: `system.adapter.${this.namespace}`,
|
|
1257
|
+
});
|
|
1258
|
+
setImmediate(() => this.processStartValues());
|
|
1259
|
+
}
|
|
1260
|
+
if (sqlDP.config?.changesOnly && sqlDP.config.changesRelogInterval > 0) {
|
|
1261
|
+
if (sqlDP.relogTimeout) {
|
|
1262
|
+
clearTimeout(sqlDP.relogTimeout);
|
|
1263
|
+
}
|
|
1264
|
+
sqlDP.relogTimeout = setTimeout((id) => this.reLogHelper(id), sqlDP.config.changesRelogInterval * 500 * Math.random() + sqlDP.config.changesRelogInterval * 500, task.id);
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
else {
|
|
1268
|
+
callback && callback();
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
writeNulls(id, now) {
|
|
1272
|
+
if (!id) {
|
|
1273
|
+
now = Date.now();
|
|
1274
|
+
Object.keys(this.sqlDPs)
|
|
1275
|
+
.filter(_id => this.sqlDPs[_id] && this.sqlDPs[_id].config)
|
|
1276
|
+
.forEach(_id => this.writeNulls(_id, now));
|
|
1277
|
+
}
|
|
1278
|
+
else {
|
|
1279
|
+
now ||= Date.now();
|
|
1280
|
+
this.tasksStart.push({ id, now });
|
|
1281
|
+
if (this.tasksStart.length === 1 && this.sqlConnected) {
|
|
1282
|
+
this.processStartValues();
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
pushHistory(id, state, timerRelog) {
|
|
1287
|
+
timerRelog ||= false;
|
|
1288
|
+
// Push into DB
|
|
1289
|
+
if (this.sqlDPs[id]) {
|
|
1290
|
+
const settings = this.sqlDPs[id].config;
|
|
1291
|
+
if (!settings || !state) {
|
|
1292
|
+
return;
|
|
1293
|
+
}
|
|
1294
|
+
if (state && state.val === undefined) {
|
|
1295
|
+
return this.log.warn(`state value undefined received for ${id} which is not allowed. Ignoring.`);
|
|
1296
|
+
}
|
|
1297
|
+
if (typeof state.val === 'string' && settings.storageType !== 'String') {
|
|
1298
|
+
if (isFinite(state.val)) {
|
|
1299
|
+
state.val = parseFloat(state.val);
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
if (settings.enableDebugLogs) {
|
|
1303
|
+
this.log.debug(`new value received for ${id} (storageType ${settings.storageType}), new-value=${state.val}, ts=${state.ts}, relog=${timerRelog}`);
|
|
1304
|
+
}
|
|
1305
|
+
let ignoreDebounce = false;
|
|
1306
|
+
if (!timerRelog) {
|
|
1307
|
+
const valueUnstable = !!this.sqlDPs[id].timeout;
|
|
1308
|
+
// When a debounce timer runs and the value is the same as the last one, ignore it
|
|
1309
|
+
if (this.sqlDPs[id].timeout && state.ts !== state.lc) {
|
|
1310
|
+
settings.enableDebugLogs &&
|
|
1311
|
+
this.log.debug(`value not changed debounce ${id}, value=${state.val}, ts=${state.ts}, debounce timer keeps running`);
|
|
1312
|
+
return;
|
|
1313
|
+
}
|
|
1314
|
+
else if (this.sqlDPs[id].timeout) {
|
|
1315
|
+
// if value changed, clear timer
|
|
1316
|
+
settings.enableDebugLogs &&
|
|
1317
|
+
this.log.debug(`value changed during debounce time ${id}, value=${state.val}, ts=${state.ts}, debounce timer restarted`);
|
|
1318
|
+
clearTimeout(this.sqlDPs[id].timeout);
|
|
1319
|
+
this.sqlDPs[id].timeout = null;
|
|
1320
|
+
}
|
|
1321
|
+
if (!valueUnstable &&
|
|
1322
|
+
settings.blockTime &&
|
|
1323
|
+
this.sqlDPs[id].state &&
|
|
1324
|
+
this.sqlDPs[id].state.ts + settings.blockTime > state.ts) {
|
|
1325
|
+
// Keep the blocked value for reLogHelper. It is deliberately NOT put into "skipped":
|
|
1326
|
+
// that channel is flushed as soon as the next value passes, which would write blocked
|
|
1327
|
+
// values after all and undermine blockTime, documented as "no further value is stored"
|
|
1328
|
+
// during the window. Here it only replaces the stale value the relog timer would
|
|
1329
|
+
// otherwise repeat - a PV inverter dropping from 500 W to 0 W and then staying there
|
|
1330
|
+
// used to be relogged as 500 W for hours (issue #273).
|
|
1331
|
+
this.sqlDPs[id].blocked = state;
|
|
1332
|
+
settings.enableDebugLogs &&
|
|
1333
|
+
this.log.debug(`value ignored blockTime ${id}, value=${state.val}, ts=${state.ts}, lastState.ts=${this.sqlDPs[id].state.ts}, blockTime=${settings.blockTime}`);
|
|
1334
|
+
return;
|
|
1335
|
+
}
|
|
1336
|
+
if (settings.ignoreZero && (state.val === undefined || state.val === null || state.val === 0)) {
|
|
1337
|
+
if (settings.enableDebugLogs) {
|
|
1338
|
+
this.log.debug(`value ignore because zero or null ${id}, new-value=${state.val}, ts=${state.ts}`);
|
|
1339
|
+
}
|
|
1340
|
+
return;
|
|
1341
|
+
}
|
|
1342
|
+
if (typeof settings.ignoreBelowNumber === 'number' &&
|
|
1343
|
+
typeof state.val === 'number' &&
|
|
1344
|
+
state.val < settings.ignoreBelowNumber) {
|
|
1345
|
+
if (settings.enableDebugLogs) {
|
|
1346
|
+
this.log.debug(`value ignored because below ${settings.ignoreBelowNumber} for ${id}, new-value=${state.val}, ts=${state.ts}`);
|
|
1347
|
+
}
|
|
1348
|
+
return;
|
|
1349
|
+
}
|
|
1350
|
+
if (typeof settings.ignoreAboveNumber === 'number' &&
|
|
1351
|
+
typeof state.val === 'number' &&
|
|
1352
|
+
state.val > settings.ignoreAboveNumber) {
|
|
1353
|
+
if (settings.enableDebugLogs) {
|
|
1354
|
+
this.log.debug(`value ignored because above ${settings.ignoreAboveNumber} for ${id}, new-value=${state.val}, ts=${state.ts}`);
|
|
1355
|
+
}
|
|
1356
|
+
return;
|
|
1357
|
+
}
|
|
1358
|
+
if (this.sqlDPs[id].state && settings.changesOnly) {
|
|
1359
|
+
if (!settings.changesRelogInterval) {
|
|
1360
|
+
if ((this.sqlDPs[id].state.val !== null || state.val === null) && state.ts !== state.lc) {
|
|
1361
|
+
// remember new timestamp
|
|
1362
|
+
if (!valueUnstable && !settings.disableSkippedValueLogging) {
|
|
1363
|
+
this.sqlDPs[id].skipped = state;
|
|
1364
|
+
}
|
|
1365
|
+
settings.enableDebugLogs &&
|
|
1366
|
+
this.log.debug(`value not changed ${id}, last-value=${this.sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
|
|
1367
|
+
return;
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
else if (this.sqlDPs[id].lastLogTime) {
|
|
1371
|
+
if ((this.sqlDPs[id].state.val !== null || state.val === null) &&
|
|
1372
|
+
state.ts !== state.lc &&
|
|
1373
|
+
Math.abs(this.sqlDPs[id].lastLogTime - state.ts) < settings.changesRelogInterval * 1000) {
|
|
1374
|
+
// remember new timestamp
|
|
1375
|
+
if (!valueUnstable && !settings.disableSkippedValueLogging) {
|
|
1376
|
+
this.sqlDPs[id].skipped = state;
|
|
1377
|
+
}
|
|
1378
|
+
settings.enableDebugLogs &&
|
|
1379
|
+
this.log.debug(`value not changed ${id}, last-value=${this.sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
|
|
1380
|
+
return;
|
|
1381
|
+
}
|
|
1382
|
+
if (state.ts !== state.lc) {
|
|
1383
|
+
settings.enableDebugLogs &&
|
|
1384
|
+
this.log.debug(`value-not-changed-relog ${id}, value=${state.val}, lastLogTime=${this.sqlDPs[id].lastLogTime}, ts=${state.ts}`);
|
|
1385
|
+
ignoreDebounce = true;
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
if (typeof state.val === 'number') {
|
|
1389
|
+
if (this.sqlDPs[id].state.val !== null &&
|
|
1390
|
+
settings.changesMinDelta &&
|
|
1391
|
+
Math.abs(this.sqlDPs[id].state.val - state.val) < settings.changesMinDelta) {
|
|
1392
|
+
if (!valueUnstable && !settings.disableSkippedValueLogging) {
|
|
1393
|
+
this.sqlDPs[id].skipped = state;
|
|
1394
|
+
}
|
|
1395
|
+
if (settings.enableDebugLogs) {
|
|
1396
|
+
this.log.debug(`Min-Delta not reached ${id}, last-value=${this.sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
|
|
1397
|
+
}
|
|
1398
|
+
return;
|
|
1399
|
+
}
|
|
1400
|
+
if (settings.changesMinDelta && settings.enableDebugLogs) {
|
|
1401
|
+
this.log.debug(`Min-Delta reached ${id}, last-value=${this.sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
else if (settings.enableDebugLogs) {
|
|
1405
|
+
this.log.debug(`Min-Delta ignored because no number ${id}, last-value=${this.sqlDPs[id].state.val}, new-value=${state.val}, ts=${state.ts}`);
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
if (settings.counter && this.sqlDPs[id].state) {
|
|
1410
|
+
if (this.sqlDPs[id].type !== types.number) {
|
|
1411
|
+
this.log.error('Counter must have type "number"!');
|
|
1412
|
+
}
|
|
1413
|
+
else if (state.val === null ||
|
|
1414
|
+
this.sqlDPs[id].state.val === null ||
|
|
1415
|
+
state.val < this.sqlDPs[id].state.val) {
|
|
1416
|
+
// if the actual value is less then last seen counter, store both values
|
|
1417
|
+
this.pushValueIntoDB(id, this.sqlDPs[id].state, true);
|
|
1418
|
+
this.pushValueIntoDB(id, state, true);
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
if (this.sqlDPs[id].relogTimeout) {
|
|
1422
|
+
clearTimeout(this.sqlDPs[id].relogTimeout);
|
|
1423
|
+
this.sqlDPs[id].relogTimeout = null;
|
|
1424
|
+
}
|
|
1425
|
+
if (timerRelog) {
|
|
1426
|
+
state = { ...state };
|
|
1427
|
+
state.ts = Date.now();
|
|
1428
|
+
state.from = `system.adapter.${this.namespace}`;
|
|
1429
|
+
settings.enableDebugLogs &&
|
|
1430
|
+
this.log.debug(`timed-relog ${id}, value=${state.val}, lastLogTime=${this.sqlDPs[id].lastLogTime}, ts=${state.ts}`);
|
|
1431
|
+
ignoreDebounce = true;
|
|
1432
|
+
}
|
|
1433
|
+
else {
|
|
1434
|
+
if (settings.changesOnly && this.sqlDPs[id].skipped) {
|
|
1435
|
+
settings.enableDebugLogs &&
|
|
1436
|
+
this.log.debug(`Skipped value logged ${id}, value=${this.sqlDPs[id].skipped.val}, ts=${this.sqlDPs[id].skipped.ts}`);
|
|
1437
|
+
this.pushHelper(id, this.sqlDPs[id].skipped);
|
|
1438
|
+
this.sqlDPs[id].skipped = null;
|
|
1439
|
+
}
|
|
1440
|
+
if (this.sqlDPs[id].state &&
|
|
1441
|
+
((this.sqlDPs[id].state.val === null && state.val !== null) ||
|
|
1442
|
+
(this.sqlDPs[id].state.val !== null && state.val === null))) {
|
|
1443
|
+
ignoreDebounce = true;
|
|
1444
|
+
}
|
|
1445
|
+
else if (!this.sqlDPs[id].state && state.val === null) {
|
|
1446
|
+
ignoreDebounce = true;
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
if (settings.debounceTime && !ignoreDebounce && !timerRelog) {
|
|
1450
|
+
// Discard changes in the debounce time to store last stable value
|
|
1451
|
+
this.sqlDPs[id].timeout && clearTimeout(this.sqlDPs[id].timeout);
|
|
1452
|
+
this.sqlDPs[id].timeout = setTimeout((id, state) => {
|
|
1453
|
+
if (!this.sqlDPs[id]) {
|
|
1454
|
+
return;
|
|
1455
|
+
}
|
|
1456
|
+
this.sqlDPs[id].timeout = null;
|
|
1457
|
+
this.sqlDPs[id].state = state;
|
|
1458
|
+
// a newer value was logged, so any value dropped by blockTime before is obsolete
|
|
1459
|
+
this.sqlDPs[id].blocked = null;
|
|
1460
|
+
this.sqlDPs[id].lastLogTime = state.ts;
|
|
1461
|
+
if (settings.enableDebugLogs) {
|
|
1462
|
+
this.log.debug(`Value logged ${id}, value=${this.sqlDPs[id].state.val}, ts=${this.sqlDPs[id].state.ts}`);
|
|
1463
|
+
}
|
|
1464
|
+
this.pushHelper(id);
|
|
1465
|
+
if (settings.changesOnly && settings.changesRelogInterval > 0) {
|
|
1466
|
+
this.sqlDPs[id].relogTimeout = setTimeout((_id) => this.reLogHelper(_id), settings.changesRelogInterval * 1000, id);
|
|
1467
|
+
}
|
|
1468
|
+
}, settings.debounceTime, id, state);
|
|
1469
|
+
}
|
|
1470
|
+
else {
|
|
1471
|
+
if (!timerRelog) {
|
|
1472
|
+
this.sqlDPs[id].state = state;
|
|
1473
|
+
// a newer value was logged, so any value dropped by blockTime before is obsolete
|
|
1474
|
+
this.sqlDPs[id].blocked = null;
|
|
1475
|
+
}
|
|
1476
|
+
this.sqlDPs[id].lastLogTime = state.ts;
|
|
1477
|
+
if (settings.enableDebugLogs) {
|
|
1478
|
+
this.log.debug(`Value logged ${id}, value=${this.sqlDPs[id].state?.val}, ts=${this.sqlDPs[id].state?.ts}`);
|
|
1479
|
+
}
|
|
1480
|
+
this.pushHelper(id, state);
|
|
1481
|
+
if (settings.changesOnly && settings.changesRelogInterval > 0) {
|
|
1482
|
+
this.sqlDPs[id].relogTimeout = setTimeout((_id) => this.reLogHelper(_id), settings.changesRelogInterval * 1000, id);
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
reLogHelper(_id) {
|
|
1488
|
+
if (!this.sqlDPs[_id]) {
|
|
1489
|
+
this.log.info(`non-existing id ${_id}`);
|
|
1490
|
+
}
|
|
1491
|
+
else {
|
|
1492
|
+
this.sqlDPs[_id].relogTimeout = null;
|
|
1493
|
+
if (this.sqlDPs[_id].skipped) {
|
|
1494
|
+
this.pushHistory(_id, this.sqlDPs[_id].skipped, true);
|
|
1495
|
+
}
|
|
1496
|
+
else if (this.sqlDPs[_id].blocked) {
|
|
1497
|
+
// a value dropped by blockTime is newer than the last logged one, so relog that
|
|
1498
|
+
// instead of repeating a value the datapoint has long left behind (issue #273)
|
|
1499
|
+
this.pushHistory(_id, this.sqlDPs[_id].blocked, true);
|
|
1500
|
+
}
|
|
1501
|
+
else if (this.sqlDPs[_id].state) {
|
|
1502
|
+
this.pushHistory(_id, this.sqlDPs[_id].state, true);
|
|
1503
|
+
}
|
|
1504
|
+
else {
|
|
1505
|
+
void this.getForeignState(this.sqlDPs[_id].realId, (err, state) => {
|
|
1506
|
+
if (err) {
|
|
1507
|
+
this.log.info(`init timed Relog: can not get State for ${_id} : ${err}`);
|
|
1508
|
+
}
|
|
1509
|
+
else if (!state) {
|
|
1510
|
+
this.log.info(`init timed Relog: disable relog because state not set so far for ${_id}: ${JSON.stringify(state)}`);
|
|
1511
|
+
}
|
|
1512
|
+
else {
|
|
1513
|
+
this.log.debug(`init timed Relog: getState ${_id}: Value=${state.val}, ack=${state.ack}, ts=${state.ts}, lc=${state.lc}`);
|
|
1514
|
+
this.sqlDPs[_id].state = state;
|
|
1515
|
+
this.pushHistory(_id, this.sqlDPs[_id].state, true);
|
|
1516
|
+
}
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
pushHelper(_id, state, cb) {
|
|
1522
|
+
if (!this.sqlDPs[_id] || (!this.sqlDPs[_id].state && !state)) {
|
|
1523
|
+
return;
|
|
1524
|
+
}
|
|
1525
|
+
state ||= this.sqlDPs[_id].state;
|
|
1526
|
+
const _settings = this.sqlDPs[_id].config || {};
|
|
1527
|
+
let val = state.val;
|
|
1528
|
+
if (val !== null && (typeof val === 'object' || typeof val === 'undefined')) {
|
|
1529
|
+
val = JSON.stringify(val);
|
|
1530
|
+
}
|
|
1531
|
+
if (val !== null && val !== undefined) {
|
|
1532
|
+
if (_settings.enableDebugLogs) {
|
|
1533
|
+
this.log.debug(`Datatype ${_id}: Currently: ${typeof val}, StorageType: ${_settings.storageType}`);
|
|
1534
|
+
}
|
|
1535
|
+
if (typeof val === 'string' && _settings.storageType !== 'String') {
|
|
1536
|
+
_settings.enableDebugLogs && this.log.debug(`Do Automatic Datatype conversion for ${_id}`);
|
|
1537
|
+
if (isFinite(val)) {
|
|
1538
|
+
val = parseFloat(val);
|
|
1539
|
+
}
|
|
1540
|
+
else if (val === 'true') {
|
|
1541
|
+
val = true;
|
|
1542
|
+
}
|
|
1543
|
+
else if (val === 'false') {
|
|
1544
|
+
val = false;
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
if (_settings.storageType === 'String' && typeof val !== 'string') {
|
|
1548
|
+
val = val.toString();
|
|
1549
|
+
}
|
|
1550
|
+
else if (_settings.storageType === 'Number' && typeof val !== 'number') {
|
|
1551
|
+
if (typeof val === 'boolean') {
|
|
1552
|
+
val = val ? 1 : 0;
|
|
1553
|
+
}
|
|
1554
|
+
else {
|
|
1555
|
+
return this.log.info(`Do not store value "${val}" for ${_id} because no number`);
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
else if (_settings.storageType === 'Boolean' && typeof val !== 'boolean') {
|
|
1559
|
+
val = !!val;
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
else {
|
|
1563
|
+
_settings.enableDebugLogs && this.log.debug(`Datatype ${_id}: Currently: null`);
|
|
1564
|
+
}
|
|
1565
|
+
state.val = val;
|
|
1566
|
+
this.pushValueIntoDB(_id, state, false, false, cb);
|
|
1567
|
+
}
|
|
1568
|
+
getAllIds(cb) {
|
|
1569
|
+
const query = this.sqlFuncs.getIdSelect(this.config.dbname);
|
|
1570
|
+
this.log.debug(query);
|
|
1571
|
+
this.borrowClientFromPool((err, client) => {
|
|
1572
|
+
if (err || !client) {
|
|
1573
|
+
this.returnClientToPool(client);
|
|
1574
|
+
return cb?.(err || new Error('No client'));
|
|
1575
|
+
}
|
|
1576
|
+
client.execute(query, (err, rows) => {
|
|
1577
|
+
this.returnClientToPool(client);
|
|
1578
|
+
if (err) {
|
|
1579
|
+
this.log.error(`Cannot select ${query}: ${err}`);
|
|
1580
|
+
return cb?.(err);
|
|
1581
|
+
}
|
|
1582
|
+
if (rows?.length) {
|
|
1583
|
+
let id;
|
|
1584
|
+
for (let r = 0; r < rows.length; r++) {
|
|
1585
|
+
id = rows[r].name;
|
|
1586
|
+
this.sqlDPs[id] ||= {};
|
|
1587
|
+
this.sqlDPs[id].index = rows[r].id;
|
|
1588
|
+
if (rows[r].type !== null) {
|
|
1589
|
+
this.sqlDPs[id].dbType = rows[r].type;
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
cb?.();
|
|
1594
|
+
});
|
|
1595
|
+
});
|
|
1596
|
+
}
|
|
1597
|
+
getAllFroms(cb) {
|
|
1598
|
+
const query = this.sqlFuncs.getFromSelect(this.config.dbname);
|
|
1599
|
+
this.log.debug(query);
|
|
1600
|
+
this.borrowClientFromPool((err, client) => {
|
|
1601
|
+
if (err || !client) {
|
|
1602
|
+
this.returnClientToPool(client);
|
|
1603
|
+
return cb?.(err || new Error('No client'));
|
|
1604
|
+
}
|
|
1605
|
+
client.execute(query, (err, rows /* , fields */) => {
|
|
1606
|
+
this.returnClientToPool(client);
|
|
1607
|
+
if (err) {
|
|
1608
|
+
this.log.error(`Cannot select ${query}: ${err}`);
|
|
1609
|
+
return cb?.(err);
|
|
1610
|
+
}
|
|
1611
|
+
if (rows?.length) {
|
|
1612
|
+
for (let r = 0; r < rows.length; r++) {
|
|
1613
|
+
this.from[rows[r].name] = rows[r].id;
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
cb?.();
|
|
1617
|
+
});
|
|
1618
|
+
});
|
|
1619
|
+
}
|
|
1620
|
+
_checkRetention(query, cb) {
|
|
1621
|
+
this.log.debug(query);
|
|
1622
|
+
this.borrowClientFromPool((err, client) => {
|
|
1623
|
+
if (err || !client) {
|
|
1624
|
+
this.returnClientToPool(client);
|
|
1625
|
+
this.log.error(err?.toString() || 'No client');
|
|
1626
|
+
cb?.();
|
|
1627
|
+
}
|
|
1628
|
+
else {
|
|
1629
|
+
client.execute(query, (err) => {
|
|
1630
|
+
this.returnClientToPool(client);
|
|
1631
|
+
if (err) {
|
|
1632
|
+
this.log.warn(`Retention: Cannot delete ${query}: ${err}`);
|
|
1633
|
+
}
|
|
1634
|
+
cb?.();
|
|
1635
|
+
});
|
|
1636
|
+
}
|
|
1637
|
+
});
|
|
1638
|
+
}
|
|
1639
|
+
checkRetention(id) {
|
|
1640
|
+
if (this.sqlDPs[id]?.config?.retention) {
|
|
1641
|
+
const dt = Date.now();
|
|
1642
|
+
// check every 6 hours
|
|
1643
|
+
if (!this.sqlDPs[id].lastCheck || dt - this.sqlDPs[id].lastCheck >= 21600000 /* 6 hours */) {
|
|
1644
|
+
this.sqlDPs[id].lastCheck = dt;
|
|
1645
|
+
if (!dbNames[this.sqlDPs[id].type]) {
|
|
1646
|
+
this.log.error(`No type ${this.sqlDPs[id].type} found for ${id}. Retention is not possible.`);
|
|
1647
|
+
}
|
|
1648
|
+
else {
|
|
1649
|
+
const query = this.sqlFuncs.retention(this.config.dbname, this.sqlDPs[id].index, dbNames[this.sqlDPs[id].type], this.sqlDPs[id].config.retention);
|
|
1650
|
+
if (!this.multiRequests) {
|
|
1651
|
+
if (this.tasks.length > MAX_TASKS) {
|
|
1652
|
+
return this.log.error(`Cannot queue new requests, because more than ${MAX_TASKS}`);
|
|
1653
|
+
}
|
|
1654
|
+
const start = this.tasks.length === 1;
|
|
1655
|
+
this.tasks.push({ operation: 'delete', query });
|
|
1656
|
+
// delete counters too
|
|
1657
|
+
if (this.sqlDPs[id] && this.sqlDPs[id].type === 0) {
|
|
1658
|
+
// 0 === number
|
|
1659
|
+
const query = this.sqlFuncs.retention(this.config.dbname, this.sqlDPs[id].index, 'ts_counter', this.sqlDPs[id].config.retention);
|
|
1660
|
+
this.tasks.push({ operation: 'delete', query });
|
|
1661
|
+
}
|
|
1662
|
+
start && this.processTasks();
|
|
1663
|
+
}
|
|
1664
|
+
else {
|
|
1665
|
+
this._checkRetention(query, () => {
|
|
1666
|
+
// delete counters too
|
|
1667
|
+
if (this.sqlDPs[id] && this.sqlDPs[id].type === 0) {
|
|
1668
|
+
// 0 === number
|
|
1669
|
+
const query = this.sqlFuncs.retention(this.config.dbname, this.sqlDPs[id].index, 'ts_counter', this.sqlDPs[id].config.retention);
|
|
1670
|
+
this._checkRetention(query);
|
|
1671
|
+
}
|
|
1672
|
+
});
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
/**
|
|
1679
|
+
* Write one batch of values.
|
|
1680
|
+
*
|
|
1681
|
+
* `sqlFuncs.insert()` chunks at 500 rows per statement and emits one statement per table, so a batch
|
|
1682
|
+
* can be more than one query. They must be sent one by one: no driver here is configured for
|
|
1683
|
+
* multi-statement batches (mysql2 needs `multipleStatements`, node-sqlite3's run() takes a single
|
|
1684
|
+
* statement), and enabling that would only widen the injection surface of the `query` message.
|
|
1685
|
+
* All statements share one borrowed connection, and the first failure aborts the rest - same as the
|
|
1686
|
+
* single concatenated query did before.
|
|
1687
|
+
*/
|
|
1688
|
+
_insertValuesIntoDB(queries, id, cb) {
|
|
1689
|
+
this.borrowClientFromPool((err, client) => {
|
|
1690
|
+
if (err || !client) {
|
|
1691
|
+
this.returnClientToPool(client);
|
|
1692
|
+
this.log.error(err?.toString() || 'No client');
|
|
1693
|
+
cb?.(); // BF asked (2021.12.14): may be return here err?
|
|
1694
|
+
return;
|
|
1695
|
+
}
|
|
1696
|
+
const next = (i) => {
|
|
1697
|
+
if (i >= queries.length) {
|
|
1698
|
+
this.returnClientToPool(client);
|
|
1699
|
+
this.checkRetention(id);
|
|
1700
|
+
cb?.(); // BF asked (2021.12.14): may be return here err?
|
|
1701
|
+
return;
|
|
1702
|
+
}
|
|
1703
|
+
this.log.debug(queries[i]);
|
|
1704
|
+
client.execute(queries[i], (err /* , rows, fields */) => {
|
|
1705
|
+
if (err) {
|
|
1706
|
+
this.returnClientToPool(client);
|
|
1707
|
+
this.log.error(`Cannot insert ${queries[i]}: ${err} (id: ${id})`);
|
|
1708
|
+
cb?.(); // BF asked (2021.12.14): may be return here err?
|
|
1709
|
+
return;
|
|
1710
|
+
}
|
|
1711
|
+
next(i + 1);
|
|
1712
|
+
});
|
|
1713
|
+
};
|
|
1714
|
+
next(0);
|
|
1715
|
+
});
|
|
1716
|
+
}
|
|
1717
|
+
_executeQuery(query, id, cb) {
|
|
1718
|
+
this.log.debug(query);
|
|
1719
|
+
this.borrowClientFromPool((err, client) => {
|
|
1720
|
+
if (err || !client) {
|
|
1721
|
+
this.returnClientToPool(client);
|
|
1722
|
+
this.log.error(err?.toString() || 'No client');
|
|
1723
|
+
cb?.();
|
|
1724
|
+
}
|
|
1725
|
+
else {
|
|
1726
|
+
client.execute(query, (err) => {
|
|
1727
|
+
this.returnClientToPool(client);
|
|
1728
|
+
if (err) {
|
|
1729
|
+
this.log.error(`Cannot query ${query}: ${err} (id: ${id})`);
|
|
1730
|
+
}
|
|
1731
|
+
cb?.();
|
|
1732
|
+
});
|
|
1733
|
+
}
|
|
1734
|
+
});
|
|
1735
|
+
}
|
|
1736
|
+
processReadTypes() {
|
|
1737
|
+
if (this.tasksReadType?.length) {
|
|
1738
|
+
const task = this.tasksReadType[0];
|
|
1739
|
+
if (!this.sqlDPs[task.id]) {
|
|
1740
|
+
this.log.warn(`Ignore type lookup for ${task.id} because not enabled anymore`);
|
|
1741
|
+
task.cb?.(new Error(`Ignore type lookup for ${task.id} because not enabled anymore`));
|
|
1742
|
+
task.cb = null;
|
|
1743
|
+
setImmediate(() => {
|
|
1744
|
+
this.tasksReadType.shift();
|
|
1745
|
+
this.processReadTypes();
|
|
1746
|
+
});
|
|
1747
|
+
return;
|
|
1748
|
+
}
|
|
1749
|
+
const sqlDP = this.sqlDPs[task.id];
|
|
1750
|
+
this.log.debug(`Type set in Def for ${task.id}: ${this.sqlDPs[task.id].config && this.sqlDPs[task.id].config.storageType}`);
|
|
1751
|
+
if (sqlDP.config?.storageType) {
|
|
1752
|
+
sqlDP.type = types[sqlDP.config.storageType.toLowerCase()];
|
|
1753
|
+
this.log.debug(`Type (from Def) for ${task.id}: ${sqlDP.type}`);
|
|
1754
|
+
this.processVerifyTypes(task);
|
|
1755
|
+
}
|
|
1756
|
+
else if (sqlDP.dbType !== undefined) {
|
|
1757
|
+
sqlDP.type = sqlDP.dbType;
|
|
1758
|
+
if (sqlDP.config) {
|
|
1759
|
+
sqlDP.config.storageType = storageTypes[sqlDP.type];
|
|
1760
|
+
}
|
|
1761
|
+
this.log.debug(`Type (from DB-Type) for ${task.id}: ${sqlDP.type}`);
|
|
1762
|
+
this.processVerifyTypes(task);
|
|
1763
|
+
}
|
|
1764
|
+
else {
|
|
1765
|
+
void this.getForeignObject(sqlDP.realId, (err, obj) => {
|
|
1766
|
+
if (err) {
|
|
1767
|
+
this.log.warn(`Error while get Object for Def for ${sqlDP.realId}: ${err}`);
|
|
1768
|
+
}
|
|
1769
|
+
if (!sqlDP) {
|
|
1770
|
+
this.log.warn(`Ignore type lookup for ${task.id} because not enabled anymore`);
|
|
1771
|
+
task.cb?.(new Error(`Ignore type lookup for ${task.id} because not enabled anymore`));
|
|
1772
|
+
task.cb = null;
|
|
1773
|
+
return setImmediate(() => {
|
|
1774
|
+
this.tasksReadType.shift();
|
|
1775
|
+
this.processReadTypes();
|
|
1776
|
+
});
|
|
1777
|
+
}
|
|
1778
|
+
else if (obj?.common?.type && types[obj.common.type.toLowerCase()] !== undefined) {
|
|
1779
|
+
// read type from object
|
|
1780
|
+
this.log.debug(`${obj.common.type.toLowerCase()} / ${types[obj.common.type.toLowerCase()]} / ${JSON.stringify(obj.common)}`);
|
|
1781
|
+
sqlDP.type = types[obj.common.type.toLowerCase()];
|
|
1782
|
+
if (sqlDP.config) {
|
|
1783
|
+
sqlDP.config.storageType = storageTypes[sqlDP.type];
|
|
1784
|
+
}
|
|
1785
|
+
this.log.debug(`Type (from Obj) for ${task.id}: ${sqlDP.type}`);
|
|
1786
|
+
this.processVerifyTypes(task);
|
|
1787
|
+
}
|
|
1788
|
+
else if (sqlDP.type === undefined) {
|
|
1789
|
+
void this.getForeignState(sqlDP.realId, (err, state) => {
|
|
1790
|
+
if (!this.sqlDPs[task.id]) {
|
|
1791
|
+
this.log.warn(`Ignore type lookup for ${task.id} because not enabled anymore`);
|
|
1792
|
+
task.cb?.(new Error(`Ignore type lookup for ${task.id} because not enabled anymore`));
|
|
1793
|
+
task.cb = null;
|
|
1794
|
+
return setImmediate(() => {
|
|
1795
|
+
this.tasksReadType.shift();
|
|
1796
|
+
this.processReadTypes();
|
|
1797
|
+
});
|
|
1798
|
+
}
|
|
1799
|
+
if (err && task.state) {
|
|
1800
|
+
this.log.warn(`Fallback to type of current state value because no other valid type found`);
|
|
1801
|
+
state = task.state;
|
|
1802
|
+
}
|
|
1803
|
+
if (state &&
|
|
1804
|
+
state.val !== null &&
|
|
1805
|
+
state.val !== undefined &&
|
|
1806
|
+
types[typeof state.val] !== undefined) {
|
|
1807
|
+
this.sqlDPs[task.id].type = types[typeof state.val];
|
|
1808
|
+
if (this.sqlDPs[task.id].config) {
|
|
1809
|
+
this.sqlDPs[task.id].config.storageType = storageTypes[this.sqlDPs[task.id].type];
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
else {
|
|
1813
|
+
this.log.warn(`Store data for ${task.id} as string because no other valid type found (${state ? typeof state.val : 'state not existing'})`);
|
|
1814
|
+
this.sqlDPs[task.id].type = 1; // string
|
|
1815
|
+
}
|
|
1816
|
+
this.log.debug(`Type (from State) for ${task.id}: ${this.sqlDPs[task.id].type}`);
|
|
1817
|
+
this.processVerifyTypes(task);
|
|
1818
|
+
});
|
|
1819
|
+
}
|
|
1820
|
+
else {
|
|
1821
|
+
// all OK
|
|
1822
|
+
task.cb?.();
|
|
1823
|
+
task.cb = null;
|
|
1824
|
+
this.tasksReadType.shift();
|
|
1825
|
+
this.processReadTypes();
|
|
1826
|
+
}
|
|
1827
|
+
});
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
}
|
|
1831
|
+
processVerifyTypes(task) {
|
|
1832
|
+
if (this.sqlDPs[task.id].index !== undefined &&
|
|
1833
|
+
this.sqlDPs[task.id].type !== undefined &&
|
|
1834
|
+
this.sqlDPs[task.id].type !== this.sqlDPs[task.id].dbType) {
|
|
1835
|
+
this.sqlDPs[task.id].dbType = this.sqlDPs[task.id].type;
|
|
1836
|
+
const query = this.sqlFuncs.getIdUpdate(this.config.dbname, this.sqlDPs[task.id].index, this.sqlDPs[task.id].type);
|
|
1837
|
+
this.log.debug(query);
|
|
1838
|
+
return this.borrowClientFromPool((err, client) => {
|
|
1839
|
+
if (err || !client) {
|
|
1840
|
+
this.returnClientToPool(client);
|
|
1841
|
+
this.processVerifyTypes(task);
|
|
1842
|
+
return;
|
|
1843
|
+
}
|
|
1844
|
+
client.execute(query, err => {
|
|
1845
|
+
this.returnClientToPool(client);
|
|
1846
|
+
if (err) {
|
|
1847
|
+
this.log.error(`error updating history config for ${task.id} to pin datatype: ${query}: ${err}`);
|
|
1848
|
+
}
|
|
1849
|
+
else {
|
|
1850
|
+
this.log.info(`changed history configuration to pin detected datatype for ${task.id}`);
|
|
1851
|
+
}
|
|
1852
|
+
this.processVerifyTypes(task);
|
|
1853
|
+
});
|
|
1854
|
+
});
|
|
1855
|
+
}
|
|
1856
|
+
task.cb?.();
|
|
1857
|
+
task.cb = null;
|
|
1858
|
+
setTimeout(() => {
|
|
1859
|
+
this.tasksReadType.shift();
|
|
1860
|
+
this.processReadTypes();
|
|
1861
|
+
}, 50);
|
|
1862
|
+
}
|
|
1863
|
+
prepareTaskReadDbId(id, state, isCounter, cb) {
|
|
1864
|
+
if (!this.sqlDPs[id]) {
|
|
1865
|
+
cb?.(new Error(`${id} not active any more`));
|
|
1866
|
+
return;
|
|
1867
|
+
}
|
|
1868
|
+
const type = this.sqlDPs[id].type;
|
|
1869
|
+
if (type === undefined) {
|
|
1870
|
+
// Can not happen anymore
|
|
1871
|
+
let warn;
|
|
1872
|
+
if (state.val === null) {
|
|
1873
|
+
warn = `Ignore null value for ${id} because no type defined till now.`;
|
|
1874
|
+
}
|
|
1875
|
+
else {
|
|
1876
|
+
warn = `Cannot store values of type "${typeof state.val}" for ${id}`;
|
|
1877
|
+
}
|
|
1878
|
+
this.log.warn(warn);
|
|
1879
|
+
cb?.(new Error(warn));
|
|
1880
|
+
return;
|
|
1881
|
+
}
|
|
1882
|
+
let tmpState;
|
|
1883
|
+
// get SQL id of state
|
|
1884
|
+
if (this.sqlDPs[id].index === undefined) {
|
|
1885
|
+
this.sqlDPs[id].isRunning ||= [];
|
|
1886
|
+
tmpState = { ...state };
|
|
1887
|
+
this.sqlDPs[id].isRunning.push({ id, state: tmpState, cb, isCounter });
|
|
1888
|
+
if (this.sqlDPs[id].isRunning.length === 1) {
|
|
1889
|
+
// read or create in DB
|
|
1890
|
+
return this.getId(id, type, (err, _id) => {
|
|
1891
|
+
this.log.debug(`prepareTaskCheckTypeAndDbId getId Result - isRunning length = ${this.sqlDPs[id].isRunning ? this.sqlDPs[id].isRunning.length : 'none'}`);
|
|
1892
|
+
if (err) {
|
|
1893
|
+
this.log.warn(`Cannot get index of "${_id}": ${err}`);
|
|
1894
|
+
this.sqlDPs[_id].isRunning?.forEach(r => r.cb?.(new Error(`Cannot get index of "${r.id}": ${err}`)));
|
|
1895
|
+
}
|
|
1896
|
+
else {
|
|
1897
|
+
this.sqlDPs[_id].isRunning?.forEach(r => r.cb?.());
|
|
1898
|
+
}
|
|
1899
|
+
this.sqlDPs[_id].isRunning = undefined;
|
|
1900
|
+
});
|
|
1901
|
+
}
|
|
1902
|
+
return;
|
|
1903
|
+
}
|
|
1904
|
+
// get from
|
|
1905
|
+
if (!isCounter && state.from && !this.from[state.from]) {
|
|
1906
|
+
this.isFromRunning[state.from] ||= [];
|
|
1907
|
+
tmpState = { ...state };
|
|
1908
|
+
const isFromRunning = this.isFromRunning[state.from];
|
|
1909
|
+
isFromRunning.push({ id, state: tmpState, cb });
|
|
1910
|
+
if (isFromRunning.length === 1) {
|
|
1911
|
+
// read or create in DB
|
|
1912
|
+
return this.getFrom(state.from, (err, from) => {
|
|
1913
|
+
this.log.debug(`prepareTaskCheckTypeAndDbId getFrom ${from} Result - isRunning length = ${this.isFromRunning[from] ? this.isFromRunning[from].length : 'none'}`);
|
|
1914
|
+
if (err) {
|
|
1915
|
+
this.log.warn(`Cannot get "from" for "${from}": ${err}`);
|
|
1916
|
+
this.isFromRunning[from]?.forEach(f => f.cb?.(new Error(`Cannot get "from" for "${from}": ${err}`)));
|
|
1917
|
+
}
|
|
1918
|
+
else {
|
|
1919
|
+
this.isFromRunning[from]?.forEach(f => f.cb?.());
|
|
1920
|
+
}
|
|
1921
|
+
this.isFromRunning[from] = null;
|
|
1922
|
+
});
|
|
1923
|
+
}
|
|
1924
|
+
return;
|
|
1925
|
+
}
|
|
1926
|
+
if (state.ts) {
|
|
1927
|
+
state.ts = parseInt(state.ts, 10);
|
|
1928
|
+
}
|
|
1929
|
+
try {
|
|
1930
|
+
if (state.val !== null && typeof state.val === 'object') {
|
|
1931
|
+
state.val = JSON.stringify(state.val);
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
catch {
|
|
1935
|
+
const error = `Cannot convert the object value "${id}"`;
|
|
1936
|
+
this.log.error(error);
|
|
1937
|
+
cb?.(new Error(error));
|
|
1938
|
+
return;
|
|
1939
|
+
}
|
|
1940
|
+
cb?.();
|
|
1941
|
+
}
|
|
1942
|
+
prepareTaskCheckTypeAndDbId(id, state, isCounter, cb) {
|
|
1943
|
+
// check if we know about this ID
|
|
1944
|
+
if (!this.sqlDPs[id]) {
|
|
1945
|
+
if (cb) {
|
|
1946
|
+
setImmediate(() => cb(new Error(`Unknown ID: ${id}`)));
|
|
1947
|
+
}
|
|
1948
|
+
return;
|
|
1949
|
+
}
|
|
1950
|
+
// Check SQL connection
|
|
1951
|
+
if (!this.clientPool) {
|
|
1952
|
+
this.log.warn('No Connection to database');
|
|
1953
|
+
if (cb) {
|
|
1954
|
+
setImmediate(() => cb(new Error('No Connection to database')));
|
|
1955
|
+
}
|
|
1956
|
+
return;
|
|
1957
|
+
}
|
|
1958
|
+
this.log.debug(`prepareTaskCheckTypeAndDbId CALLED for ${id}`);
|
|
1959
|
+
// read type of value
|
|
1960
|
+
if (this.sqlDPs[id].type !== undefined) {
|
|
1961
|
+
this.prepareTaskReadDbId(id, state, isCounter, cb);
|
|
1962
|
+
}
|
|
1963
|
+
else {
|
|
1964
|
+
// read type from DB
|
|
1965
|
+
this.tasksReadType.push({
|
|
1966
|
+
id,
|
|
1967
|
+
state,
|
|
1968
|
+
cb: err => {
|
|
1969
|
+
if (err) {
|
|
1970
|
+
cb?.(err);
|
|
1971
|
+
}
|
|
1972
|
+
else {
|
|
1973
|
+
this.prepareTaskReadDbId(id, state, isCounter, cb);
|
|
1974
|
+
}
|
|
1975
|
+
},
|
|
1976
|
+
});
|
|
1977
|
+
if (this.tasksReadType.length === 1) {
|
|
1978
|
+
this.processReadTypes();
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
pushValueIntoDB(id, state, isCounter, storeInCacheOnly, cb) {
|
|
1983
|
+
if (!this.sqlDPs[id] || !state) {
|
|
1984
|
+
return cb?.();
|
|
1985
|
+
}
|
|
1986
|
+
this.log.debug(`pushValueIntoDB called for ${id} (type: ${this.sqlDPs[id].type}, ID: ${this.sqlDPs[id].index}) and state: ${JSON.stringify(state)}`);
|
|
1987
|
+
this.prepareTaskCheckTypeAndDbId(id, state, isCounter, (err) => {
|
|
1988
|
+
if (!this.sqlDPs[id]) {
|
|
1989
|
+
return cb?.();
|
|
1990
|
+
}
|
|
1991
|
+
this.log.debug(`pushValueIntoDB-prepareTaskCheckTypeAndDbId RESULT for ${id} (type: ${this.sqlDPs[id].type}, ID: ${this.sqlDPs[id].index}) and state: ${JSON.stringify(state)}: ${err}`);
|
|
1992
|
+
if (err) {
|
|
1993
|
+
return cb?.(err);
|
|
1994
|
+
}
|
|
1995
|
+
const type = this.sqlDPs[id].type;
|
|
1996
|
+
// increase timestamp if last is the same
|
|
1997
|
+
if (!isCounter && this.sqlDPs[id].ts && state.ts === this.sqlDPs[id].ts) {
|
|
1998
|
+
state.ts++;
|
|
1999
|
+
}
|
|
2000
|
+
// remember last timestamp
|
|
2001
|
+
this.sqlDPs[id].ts = state.ts;
|
|
2002
|
+
// if it was not deleted in this time
|
|
2003
|
+
this.sqlDPs[id].list ||= [];
|
|
2004
|
+
this.sqlDPs[id].list.push({
|
|
2005
|
+
state,
|
|
2006
|
+
from: state.from ? this.from[state.from] : 0,
|
|
2007
|
+
table: isCounter ? 'ts_counter' : dbNames[type],
|
|
2008
|
+
});
|
|
2009
|
+
const _settings = this.sqlDPs[id].config || {};
|
|
2010
|
+
const maxLength = _settings.maxLength !== undefined ? _settings.maxLength : this.config.maxLength || 0;
|
|
2011
|
+
if ((cb || (_settings && this.sqlDPs[id].list.length > maxLength)) && !storeInCacheOnly) {
|
|
2012
|
+
this.storeCached(id, cb);
|
|
2013
|
+
}
|
|
2014
|
+
else if (cb && storeInCacheOnly) {
|
|
2015
|
+
setImmediate(cb);
|
|
2016
|
+
}
|
|
2017
|
+
});
|
|
2018
|
+
}
|
|
2019
|
+
storeCached(onlyId, cb) {
|
|
2020
|
+
let count = 0;
|
|
2021
|
+
for (const id in this.sqlDPs) {
|
|
2022
|
+
if (!Object.prototype.hasOwnProperty.call(this.sqlDPs, id) || (onlyId !== undefined && onlyId !== id)) {
|
|
2023
|
+
continue;
|
|
2024
|
+
}
|
|
2025
|
+
const _settings = this.sqlDPs[id].config || {};
|
|
2026
|
+
if (_settings && this.sqlDPs[id]?.list?.length) {
|
|
2027
|
+
if (_settings.enableDebugLogs) {
|
|
2028
|
+
this.log.debug(`inserting ${this.sqlDPs[id].list.length} entries from ${id} to DB`);
|
|
2029
|
+
}
|
|
2030
|
+
const inFlightId = `${id}_${Date.now()}_${Math.random()}`;
|
|
2031
|
+
this.sqlDPs[id].inFlight ||= {};
|
|
2032
|
+
this.sqlDPs[id].inFlight[inFlightId] = this.sqlDPs[id].list;
|
|
2033
|
+
this.sqlDPs[id].list = [];
|
|
2034
|
+
count++;
|
|
2035
|
+
this.pushValuesIntoDB(id, this.sqlDPs[id].inFlight[inFlightId], (err) => {
|
|
2036
|
+
if (this.sqlDPs[id]?.inFlight?.[inFlightId]) {
|
|
2037
|
+
delete this.sqlDPs[id].inFlight[inFlightId];
|
|
2038
|
+
}
|
|
2039
|
+
if (!--count && cb) {
|
|
2040
|
+
cb?.(err);
|
|
2041
|
+
cb = null;
|
|
2042
|
+
}
|
|
2043
|
+
});
|
|
2044
|
+
if (onlyId !== undefined) {
|
|
2045
|
+
break;
|
|
2046
|
+
}
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
if (!count && cb) {
|
|
2050
|
+
cb();
|
|
2051
|
+
}
|
|
2052
|
+
}
|
|
2053
|
+
pushValuesIntoDB(id, list, cb) {
|
|
2054
|
+
if (!list.length) {
|
|
2055
|
+
if (cb) {
|
|
2056
|
+
setImmediate(() => cb());
|
|
2057
|
+
}
|
|
2058
|
+
return;
|
|
2059
|
+
}
|
|
2060
|
+
if (!this.multiRequests) {
|
|
2061
|
+
if (this.tasks.length > MAX_TASKS) {
|
|
2062
|
+
const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
|
|
2063
|
+
this.log.error(error);
|
|
2064
|
+
cb?.(new Error(error));
|
|
2065
|
+
}
|
|
2066
|
+
else {
|
|
2067
|
+
this.tasks.push({ operation: 'insert', index: this.sqlDPs[id].index, list, id, callback: cb });
|
|
2068
|
+
this.tasks.length === 1 && this.processTasks();
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
else {
|
|
2072
|
+
const queries = this.sqlFuncs.insert(this.config.dbname, this.sqlDPs[id].index, list);
|
|
2073
|
+
this._insertValuesIntoDB(queries, id, cb);
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
2076
|
+
processTasks() {
|
|
2077
|
+
if (this.lockTasks) {
|
|
2078
|
+
return this.log.debug('Tries to execute task, but last one not finished!');
|
|
2079
|
+
}
|
|
2080
|
+
this.lockTasks = true;
|
|
2081
|
+
if (this.tasks.length) {
|
|
2082
|
+
if (this.tasks[0].operation === 'query') {
|
|
2083
|
+
const taskQuery = this.tasks[0];
|
|
2084
|
+
this._executeQuery(taskQuery.query, this.tasks[0].id, () => {
|
|
2085
|
+
taskQuery.callback?.();
|
|
2086
|
+
this.tasks.shift();
|
|
2087
|
+
this.lockTasks = false;
|
|
2088
|
+
if (this.tasks.length) {
|
|
2089
|
+
setTimeout(() => this.processTasks(), this.config.requestInterval);
|
|
2090
|
+
}
|
|
2091
|
+
});
|
|
2092
|
+
}
|
|
2093
|
+
else if (this.tasks[0].operation === 'insert') {
|
|
2094
|
+
const taskInsert = this.tasks[0];
|
|
2095
|
+
const callbacks = [];
|
|
2096
|
+
if (taskInsert.callback) {
|
|
2097
|
+
callbacks.push(taskInsert.callback);
|
|
2098
|
+
}
|
|
2099
|
+
for (let i = 1; i < this.tasks.length; i++) {
|
|
2100
|
+
if (this.tasks[i].operation === 'insert') {
|
|
2101
|
+
const _taskInsert = this.tasks[i];
|
|
2102
|
+
if (taskInsert.index === _taskInsert.index) {
|
|
2103
|
+
taskInsert.list = taskInsert.list.concat(_taskInsert.list);
|
|
2104
|
+
if (_taskInsert.callback) {
|
|
2105
|
+
callbacks.push(_taskInsert.callback);
|
|
2106
|
+
}
|
|
2107
|
+
this.tasks.splice(i, 1);
|
|
2108
|
+
i--;
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
const queries = this.sqlFuncs.insert(this.config.dbname, this.tasks[0].index, this.tasks[0].list);
|
|
2113
|
+
this._insertValuesIntoDB(queries, this.tasks[0].id, () => {
|
|
2114
|
+
callbacks.forEach(cb => cb());
|
|
2115
|
+
this.tasks.shift();
|
|
2116
|
+
this.lockTasks = false;
|
|
2117
|
+
if (this.tasks.length) {
|
|
2118
|
+
setTimeout(() => this.processTasks(), this.config.requestInterval);
|
|
2119
|
+
}
|
|
2120
|
+
});
|
|
2121
|
+
}
|
|
2122
|
+
else if (this.tasks[0].operation === 'select') {
|
|
2123
|
+
const taskSelect = this.tasks[0];
|
|
2124
|
+
this.#getDataFromDB(taskSelect.query, taskSelect.options, (err, rows) => {
|
|
2125
|
+
taskSelect.callback?.(err, rows);
|
|
2126
|
+
this.tasks.shift();
|
|
2127
|
+
this.lockTasks = false;
|
|
2128
|
+
if (this.tasks.length) {
|
|
2129
|
+
setTimeout(() => this.processTasks(), this.config.requestInterval);
|
|
2130
|
+
}
|
|
2131
|
+
});
|
|
2132
|
+
}
|
|
2133
|
+
else if (this.tasks[0].operation === 'userQuery') {
|
|
2134
|
+
const taskUserQuery = this.tasks[0];
|
|
2135
|
+
this._userQuery(taskUserQuery.msg, () => {
|
|
2136
|
+
this.tasks.shift();
|
|
2137
|
+
this.lockTasks = false;
|
|
2138
|
+
if (this.tasks.length) {
|
|
2139
|
+
setTimeout(() => this.processTasks(), this.config.requestInterval);
|
|
2140
|
+
}
|
|
2141
|
+
});
|
|
2142
|
+
}
|
|
2143
|
+
else if (this.tasks[0].operation === 'delete') {
|
|
2144
|
+
const taskDelete = this.tasks[0];
|
|
2145
|
+
this._checkRetention(taskDelete.query, () => {
|
|
2146
|
+
this.tasks.shift();
|
|
2147
|
+
this.lockTasks = false;
|
|
2148
|
+
if (this.tasks.length) {
|
|
2149
|
+
setTimeout(() => this.processTasks(), this.config.requestInterval);
|
|
2150
|
+
}
|
|
2151
|
+
});
|
|
2152
|
+
}
|
|
2153
|
+
else {
|
|
2154
|
+
this.log.error(`unknown task: ${this.tasks[0].operation}`);
|
|
2155
|
+
this.tasks[0].callback?.('Unknown task');
|
|
2156
|
+
this.tasks.shift();
|
|
2157
|
+
this.lockTasks = false;
|
|
2158
|
+
if (this.tasks.length) {
|
|
2159
|
+
setTimeout(() => this.processTasks(), this.config.requestInterval);
|
|
2160
|
+
}
|
|
2161
|
+
}
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
// may be it is required to cache all the data in memory
|
|
2165
|
+
getId(id, type, cb) {
|
|
2166
|
+
let query = this.sqlFuncs.getIdSelect(this.config.dbname, id);
|
|
2167
|
+
this.log.debug(query);
|
|
2168
|
+
this.borrowClientFromPool((err, client) => {
|
|
2169
|
+
if (err || !client) {
|
|
2170
|
+
this.returnClientToPool(client);
|
|
2171
|
+
cb?.(err || new Error('No client'), id);
|
|
2172
|
+
return;
|
|
2173
|
+
}
|
|
2174
|
+
client.execute(query, (err, rows /* , fields */) => {
|
|
2175
|
+
if (!this.sqlDPs[id]) {
|
|
2176
|
+
this.returnClientToPool(client);
|
|
2177
|
+
cb?.(new Error(`ID ${id} no longer active`), id);
|
|
2178
|
+
return;
|
|
2179
|
+
}
|
|
2180
|
+
if (err) {
|
|
2181
|
+
this.returnClientToPool(client);
|
|
2182
|
+
this.log.error(`Cannot select ${query}: ${err}`);
|
|
2183
|
+
cb?.(err, id);
|
|
2184
|
+
return;
|
|
2185
|
+
}
|
|
2186
|
+
if (!rows?.length) {
|
|
2187
|
+
if (type !== null && type !== undefined) {
|
|
2188
|
+
// insert
|
|
2189
|
+
query = this.sqlFuncs.getIdInsert(this.config.dbname, id, type);
|
|
2190
|
+
this.log.debug(query);
|
|
2191
|
+
client.execute(query, (err /* , rows, fields */) => {
|
|
2192
|
+
if (err) {
|
|
2193
|
+
this.returnClientToPool(client);
|
|
2194
|
+
this.log.error(`Cannot insert ${query}: ${err}`);
|
|
2195
|
+
cb?.(err, id);
|
|
2196
|
+
}
|
|
2197
|
+
else {
|
|
2198
|
+
query = this.sqlFuncs.getIdSelect(this.config.dbname, id);
|
|
2199
|
+
this.log.debug(query);
|
|
2200
|
+
client.execute(query, (err, rows /* , fields */) => {
|
|
2201
|
+
this.returnClientToPool(client);
|
|
2202
|
+
if (err) {
|
|
2203
|
+
this.log.error(`Cannot select ${query}: ${err}`);
|
|
2204
|
+
cb?.(err, id);
|
|
2205
|
+
}
|
|
2206
|
+
else if (rows?.[0]) {
|
|
2207
|
+
this.sqlDPs[id].index = rows[0].id;
|
|
2208
|
+
this.sqlDPs[id].type = rows[0].type;
|
|
2209
|
+
cb?.(null, id);
|
|
2210
|
+
}
|
|
2211
|
+
else {
|
|
2212
|
+
this.log.error(`No result for select ${query}: after insert`);
|
|
2213
|
+
cb?.(new Error(`No result for select ${query}: after insert`), id);
|
|
2214
|
+
}
|
|
2215
|
+
});
|
|
2216
|
+
}
|
|
2217
|
+
});
|
|
2218
|
+
}
|
|
2219
|
+
else {
|
|
2220
|
+
this.returnClientToPool(client);
|
|
2221
|
+
cb?.(new Error('id not found'), id);
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2224
|
+
else {
|
|
2225
|
+
this.sqlDPs[id].index = rows[0].id;
|
|
2226
|
+
if (rows[0].type === null || typeof rows[0].type !== 'number') {
|
|
2227
|
+
this.sqlDPs[id].type = type === null ? 1 : type; // default string
|
|
2228
|
+
const query = this.sqlFuncs.getIdUpdate(this.config.dbname, this.sqlDPs[id].index, this.sqlDPs[id].type);
|
|
2229
|
+
this.log.debug(query);
|
|
2230
|
+
client.execute(query, err => {
|
|
2231
|
+
this.returnClientToPool(client);
|
|
2232
|
+
if (err) {
|
|
2233
|
+
this.log.error(`error updating history config for ${id} to pin datatype: ${query}: ${err}`);
|
|
2234
|
+
}
|
|
2235
|
+
else {
|
|
2236
|
+
this.log.info(`changed history configuration to pin detected datatype for ${id}`);
|
|
2237
|
+
}
|
|
2238
|
+
cb?.(null, id);
|
|
2239
|
+
});
|
|
2240
|
+
}
|
|
2241
|
+
else {
|
|
2242
|
+
this.returnClientToPool(client);
|
|
2243
|
+
this.sqlDPs[id].type = rows[0].type;
|
|
2244
|
+
cb?.(null, id);
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
});
|
|
2248
|
+
});
|
|
2249
|
+
}
|
|
2250
|
+
// may be it is required to cache all the data in memory
|
|
2251
|
+
getFrom(_from, cb) {
|
|
2252
|
+
// const sources = (this.config.dbtype !== 'postgresql' ? (this.config.dbname + '.') : '') + 'sources';
|
|
2253
|
+
let query = this.sqlFuncs.getFromSelect(this.config.dbname, _from);
|
|
2254
|
+
this.log.debug(query);
|
|
2255
|
+
this.borrowClientFromPool((err, client) => {
|
|
2256
|
+
if (err || !client) {
|
|
2257
|
+
this.returnClientToPool(client);
|
|
2258
|
+
return cb?.(err || new Error('No client'), _from);
|
|
2259
|
+
}
|
|
2260
|
+
client.execute(query, (err, rows /* , fields */) => {
|
|
2261
|
+
if (err) {
|
|
2262
|
+
this.returnClientToPool(client);
|
|
2263
|
+
this.log.error(`Cannot select ${query}: ${err}`);
|
|
2264
|
+
return cb?.(err, _from);
|
|
2265
|
+
}
|
|
2266
|
+
if (!rows?.length) {
|
|
2267
|
+
// insert
|
|
2268
|
+
query = this.sqlFuncs.getFromInsert(this.config.dbname, _from);
|
|
2269
|
+
this.log.debug(query);
|
|
2270
|
+
client.execute(query, err => {
|
|
2271
|
+
if (err) {
|
|
2272
|
+
this.returnClientToPool(client);
|
|
2273
|
+
this.log.error(`Cannot insert ${query}: ${err}`);
|
|
2274
|
+
return cb?.(err, _from);
|
|
2275
|
+
}
|
|
2276
|
+
query = this.sqlFuncs.getFromSelect(this.config.dbname, _from);
|
|
2277
|
+
this.log.debug(query);
|
|
2278
|
+
client.execute(query, (err, rows /* , fields */) => {
|
|
2279
|
+
this.returnClientToPool(client);
|
|
2280
|
+
if (err || !rows?.length) {
|
|
2281
|
+
this.log.error(`Cannot select ${query}: ${err}`);
|
|
2282
|
+
return cb?.(err, _from);
|
|
2283
|
+
}
|
|
2284
|
+
this.from[_from] = rows[0].id;
|
|
2285
|
+
cb?.(null, _from);
|
|
2286
|
+
});
|
|
2287
|
+
});
|
|
2288
|
+
}
|
|
2289
|
+
else {
|
|
2290
|
+
this.returnClientToPool(client);
|
|
2291
|
+
this.from[_from] = rows[0].id;
|
|
2292
|
+
cb?.(null, _from);
|
|
2293
|
+
}
|
|
2294
|
+
});
|
|
2295
|
+
});
|
|
2296
|
+
}
|
|
2297
|
+
getOneCachedData(id, options, cache) {
|
|
2298
|
+
if (this.sqlDPs[id]) {
|
|
2299
|
+
let anyInflight = false;
|
|
2300
|
+
let res = [];
|
|
2301
|
+
for (const inFlightId in this.sqlDPs[id].inFlight) {
|
|
2302
|
+
this.log.debug(`getOneCachedData: add ${this.sqlDPs[id].inFlight[inFlightId].length} inFlight datapoints for ${options.id}`);
|
|
2303
|
+
res = res.concat(this.sqlDPs[id].inFlight[inFlightId]);
|
|
2304
|
+
anyInflight ||= !!this.sqlDPs[id].inFlight[inFlightId].length;
|
|
2305
|
+
}
|
|
2306
|
+
res = res.concat(this.sqlDPs[id].list);
|
|
2307
|
+
// todo can be optimized
|
|
2308
|
+
if (res) {
|
|
2309
|
+
let iProblemCount = 0;
|
|
2310
|
+
let vLast = null;
|
|
2311
|
+
for (let i = res.length - 1; i >= 0; i--) {
|
|
2312
|
+
if (!res[i] || !res[i].state) {
|
|
2313
|
+
iProblemCount++;
|
|
2314
|
+
continue;
|
|
2315
|
+
}
|
|
2316
|
+
if (options.start && res[i].state.ts < options.start) {
|
|
2317
|
+
// add one before start
|
|
2318
|
+
cache.unshift({ ...res[i].state });
|
|
2319
|
+
break;
|
|
2320
|
+
}
|
|
2321
|
+
else if (res[i].state.ts > options.end) {
|
|
2322
|
+
// add one after end
|
|
2323
|
+
vLast = res[i].state;
|
|
2324
|
+
continue;
|
|
2325
|
+
}
|
|
2326
|
+
if (vLast) {
|
|
2327
|
+
cache.unshift({ ...vLast });
|
|
2328
|
+
vLast = null;
|
|
2329
|
+
}
|
|
2330
|
+
cache.unshift({ ...res[i].state });
|
|
2331
|
+
if (options.returnNewestEntries &&
|
|
2332
|
+
options.count &&
|
|
2333
|
+
cache.length >= options.count &&
|
|
2334
|
+
(options.aggregate === 'onchange' || !options.aggregate || options.aggregate === 'none')) {
|
|
2335
|
+
break;
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
if (iProblemCount) {
|
|
2339
|
+
this.log.warn(`getOneCachedData: got null states ${iProblemCount} times for ${options.id}`);
|
|
2340
|
+
}
|
|
2341
|
+
this.log.debug(`getOneCachedData: got ${res.length} datapoints for ${options.id}`);
|
|
2342
|
+
return anyInflight;
|
|
2343
|
+
}
|
|
2344
|
+
this.log.debug(`getOneCachedData: datapoints for ${options.id} do not yet exist`);
|
|
2345
|
+
}
|
|
2346
|
+
return false;
|
|
2347
|
+
}
|
|
2348
|
+
getCachedData(options, callback) {
|
|
2349
|
+
const cache = [];
|
|
2350
|
+
let anyInflight = false;
|
|
2351
|
+
if (options.id) {
|
|
2352
|
+
anyInflight = this.getOneCachedData(options.id, options, cache);
|
|
2353
|
+
}
|
|
2354
|
+
else {
|
|
2355
|
+
for (const id in this.sqlDPs) {
|
|
2356
|
+
if (Object.prototype.hasOwnProperty.call(this.sqlDPs, id)) {
|
|
2357
|
+
anyInflight ||= this.getOneCachedData(id, options, cache);
|
|
2358
|
+
}
|
|
2359
|
+
}
|
|
2360
|
+
}
|
|
2361
|
+
let earliestTs = null;
|
|
2362
|
+
for (let c = 0; c < cache.length; c++) {
|
|
2363
|
+
if (typeof cache[c].ts === 'string') {
|
|
2364
|
+
cache[c].ts = parseInt(cache[c].ts, 10);
|
|
2365
|
+
}
|
|
2366
|
+
if (this.common?.loglevel === 'debug') {
|
|
2367
|
+
cache[c].date = new Date(cache[c].ts);
|
|
2368
|
+
}
|
|
2369
|
+
if (options.ack) {
|
|
2370
|
+
cache[c].ack = !!cache[c].ack;
|
|
2371
|
+
}
|
|
2372
|
+
if (typeof cache[c].val === 'number' && isFinite(cache[c].val) && options.round) {
|
|
2373
|
+
cache[c].val = Math.round(cache[c].val * options.round) / options.round;
|
|
2374
|
+
}
|
|
2375
|
+
if (options.id && this.sqlDPs[options.id] && this.sqlDPs[options.id].type === 2) {
|
|
2376
|
+
// 2 === boolean
|
|
2377
|
+
cache[c].val = !!cache[c].val;
|
|
2378
|
+
}
|
|
2379
|
+
if (options.addId && !cache[c].id && options.id) {
|
|
2380
|
+
cache[c].id = options.id;
|
|
2381
|
+
}
|
|
2382
|
+
if (earliestTs === null || cache[c].ts < earliestTs) {
|
|
2383
|
+
earliestTs = cache[c].ts;
|
|
2384
|
+
}
|
|
2385
|
+
}
|
|
2386
|
+
// options.length = cache.length;
|
|
2387
|
+
callback(cache, !!options.returnNewestEntries && !!options.count && cache.length >= options.count, anyInflight, earliestTs);
|
|
2388
|
+
}
|
|
2389
|
+
#getDataFromDB(query, options, callback) {
|
|
2390
|
+
this.log.debug(query);
|
|
2391
|
+
this.borrowClientFromPool((err, client) => {
|
|
2392
|
+
if (err || !client) {
|
|
2393
|
+
this.returnClientToPool(client);
|
|
2394
|
+
callback?.(err || new Error('No client'));
|
|
2395
|
+
return;
|
|
2396
|
+
}
|
|
2397
|
+
client.execute(query, (err, rows /* , fields */) => {
|
|
2398
|
+
this.returnClientToPool(client);
|
|
2399
|
+
if (!err && rows) {
|
|
2400
|
+
for (let c = 0; c < rows.length; c++) {
|
|
2401
|
+
if (typeof rows[c].ts === 'string') {
|
|
2402
|
+
rows[c].ts = parseInt(rows[c].ts, 10);
|
|
2403
|
+
}
|
|
2404
|
+
if (this.common?.loglevel === 'debug') {
|
|
2405
|
+
rows[c].date = new Date(rows[c].ts);
|
|
2406
|
+
}
|
|
2407
|
+
if (options.ack) {
|
|
2408
|
+
rows[c].ack = !!rows[c].ack;
|
|
2409
|
+
}
|
|
2410
|
+
if (typeof rows[c].val === 'number' && isFinite(rows[c].val) && options.round) {
|
|
2411
|
+
rows[c].val = Math.round(rows[c].val * options.round) / options.round;
|
|
2412
|
+
}
|
|
2413
|
+
if (options.id && this.sqlDPs[options.id] && this.sqlDPs[options.id].type === 2) {
|
|
2414
|
+
// 2 === boolean
|
|
2415
|
+
rows[c].val = !!rows[c].val;
|
|
2416
|
+
}
|
|
2417
|
+
if (options.addId && !rows[c].id && options.id) {
|
|
2418
|
+
rows[c].id = options.id;
|
|
2419
|
+
}
|
|
2420
|
+
}
|
|
2421
|
+
}
|
|
2422
|
+
callback?.(err, rows);
|
|
2423
|
+
});
|
|
2424
|
+
});
|
|
2425
|
+
}
|
|
2426
|
+
getDataFromDB(table, options, callback) {
|
|
2427
|
+
const query = this.sqlFuncs.getHistory(this.config.dbname, table, options);
|
|
2428
|
+
this.log.debug(query);
|
|
2429
|
+
if (!this.multiRequests) {
|
|
2430
|
+
if (this.tasks.length > MAX_TASKS) {
|
|
2431
|
+
this.log.error(`Cannot queue new requests, because more than ${MAX_TASKS}`);
|
|
2432
|
+
callback?.(new Error(`Cannot queue new requests, because more than ${MAX_TASKS}`));
|
|
2433
|
+
}
|
|
2434
|
+
else {
|
|
2435
|
+
this.tasks.push({ operation: 'select', query, options, callback });
|
|
2436
|
+
if (this.tasks.length === 1) {
|
|
2437
|
+
this.processTasks();
|
|
2438
|
+
}
|
|
2439
|
+
}
|
|
2440
|
+
}
|
|
2441
|
+
else {
|
|
2442
|
+
this.#getDataFromDB(query, options, callback);
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
getCounterDataFromDB(options, callback) {
|
|
2446
|
+
const query = this.sqlFuncs.getCounterDiff(this.config.dbname, options);
|
|
2447
|
+
this.log.debug(query);
|
|
2448
|
+
if (!this.multiRequests) {
|
|
2449
|
+
if (this.tasks.length > MAX_TASKS) {
|
|
2450
|
+
const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
|
|
2451
|
+
this.log.error(error);
|
|
2452
|
+
callback?.(new Error(error));
|
|
2453
|
+
}
|
|
2454
|
+
else {
|
|
2455
|
+
this.tasks.push({ operation: 'select', query, options, callback });
|
|
2456
|
+
if (this.tasks.length === 1) {
|
|
2457
|
+
this.processTasks();
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2460
|
+
}
|
|
2461
|
+
else {
|
|
2462
|
+
this.#getDataFromDB(query, options, callback);
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
getCounterDiff(msg) {
|
|
2466
|
+
const id = msg.message.id;
|
|
2467
|
+
const start = msg.message.options.start || 0;
|
|
2468
|
+
const end = msg.message.options.end || Date.now() + 5000000;
|
|
2469
|
+
if (!this.sqlDPs[id]) {
|
|
2470
|
+
this.sendTo(msg.from, msg.command, { result: [], step: null, error: 'Not enabled' }, msg.callback);
|
|
2471
|
+
}
|
|
2472
|
+
else {
|
|
2473
|
+
if (!this.sqlFuncs.getCounterDiff) {
|
|
2474
|
+
this.sendTo(msg.from, msg.command, { result: [], step: null, error: 'Counter option is not enabled for this type of SQL' }, msg.callback);
|
|
2475
|
+
}
|
|
2476
|
+
else {
|
|
2477
|
+
const options = { id, start, end, index: this.sqlDPs[id].index };
|
|
2478
|
+
this.getCounterDataFromDB(options, (err, data) => (0, aggregate_1.sendResponseCounter)(this, msg, options, err?.toString() || data || []));
|
|
2479
|
+
}
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
getHistorySql(msg) {
|
|
2483
|
+
const startTime = Date.now();
|
|
2484
|
+
if (!msg.message?.options) {
|
|
2485
|
+
return this.sendTo(msg.from, msg.command, {
|
|
2486
|
+
error: 'Invalid call. No options for getHistory provided',
|
|
2487
|
+
}, msg.callback);
|
|
2488
|
+
}
|
|
2489
|
+
// callers send this either as a real boolean/number or as a string
|
|
2490
|
+
let ignoreNull;
|
|
2491
|
+
if (msg.message.options.ignoreNull === true || msg.message.options.ignoreNull === 'true') {
|
|
2492
|
+
ignoreNull = true; // include nulls and replace them with the last value
|
|
2493
|
+
}
|
|
2494
|
+
else if (msg.message.options.ignoreNull === 0 || msg.message.options.ignoreNull === '0') {
|
|
2495
|
+
ignoreNull = 0; // include nulls and replace them with 0
|
|
2496
|
+
}
|
|
2497
|
+
else {
|
|
2498
|
+
ignoreNull = false; // include nulls
|
|
2499
|
+
}
|
|
2500
|
+
const logId = (msg.message.id ? msg.message.id : 'all') + Date.now() + Math.random();
|
|
2501
|
+
const options = {
|
|
2502
|
+
id: msg.message.id === '*' ? null : msg.message.id,
|
|
2503
|
+
start: msg.message.options.start,
|
|
2504
|
+
end: msg.message.options.end || Date.now() + 5000000,
|
|
2505
|
+
step: parseInt(msg.message.options.step, 10) || undefined,
|
|
2506
|
+
count: parseInt(msg.message.options.count, 10),
|
|
2507
|
+
ignoreNull,
|
|
2508
|
+
aggregate: msg.message.options.aggregate || 'average', // One of: max, min, average, total, none, on-change
|
|
2509
|
+
limit: parseInt(msg.message.options.limit, 10) || parseInt(msg.message.options.count, 10) || 2000,
|
|
2510
|
+
from: msg.message.options.from || false,
|
|
2511
|
+
q: msg.message.options.q || false,
|
|
2512
|
+
ack: msg.message.options.ack || false,
|
|
2513
|
+
addId: msg.message.options.addId || false,
|
|
2514
|
+
sessionId: msg.message.options.sessionId,
|
|
2515
|
+
returnNewestEntries: msg.message.options.returnNewestEntries || false,
|
|
2516
|
+
percentile: msg.message.options.aggregate === 'percentile'
|
|
2517
|
+
? parseInt(msg.message.options.percentile, 10) || 50
|
|
2518
|
+
: undefined,
|
|
2519
|
+
quantile: msg.message.options.aggregate === 'quantile'
|
|
2520
|
+
? parseFloat(msg.message.options.quantile) || 0.5
|
|
2521
|
+
: undefined,
|
|
2522
|
+
integralUnit: msg.message.options.aggregate === 'integral'
|
|
2523
|
+
? parseInt(msg.message.options.integralUnit, 10) || 60
|
|
2524
|
+
: undefined,
|
|
2525
|
+
integralInterpolation: msg.message.options.aggregate === 'integral'
|
|
2526
|
+
? msg.message.options.integralInterpolation || 'none'
|
|
2527
|
+
: null,
|
|
2528
|
+
removeBorderValues: msg.message.options.removeBorderValues || false,
|
|
2529
|
+
// ID in database
|
|
2530
|
+
index: msg.message.id === '*' ? null : this.sqlDPs[msg.message.id]?.index || null,
|
|
2531
|
+
};
|
|
2532
|
+
this.log.debug(`${logId} getHistory message: ${JSON.stringify(msg.message)}`);
|
|
2533
|
+
if (!options.count || isNaN(options.count)) {
|
|
2534
|
+
if (options.aggregate === 'none' || options.aggregate === 'onchange') {
|
|
2535
|
+
options.count = options.limit;
|
|
2536
|
+
}
|
|
2537
|
+
else {
|
|
2538
|
+
options.count = 500;
|
|
2539
|
+
}
|
|
2540
|
+
}
|
|
2541
|
+
try {
|
|
2542
|
+
if (options.start && typeof options.start !== 'number') {
|
|
2543
|
+
options.start = new Date(options.start).getTime();
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
catch {
|
|
2547
|
+
return this.sendTo(msg.from, msg.command, {
|
|
2548
|
+
error: `Invalid call. Start date ${JSON.stringify(options.start)} is not a valid date`,
|
|
2549
|
+
}, msg.callback);
|
|
2550
|
+
}
|
|
2551
|
+
try {
|
|
2552
|
+
if (options.end && typeof options.end !== 'number') {
|
|
2553
|
+
options.end = new Date(options.end).getTime();
|
|
2554
|
+
}
|
|
2555
|
+
}
|
|
2556
|
+
catch {
|
|
2557
|
+
return this.sendTo(msg.from, msg.command, {
|
|
2558
|
+
error: `Invalid call. End date ${JSON.stringify(options.end)} is not a valid date`,
|
|
2559
|
+
}, msg.callback);
|
|
2560
|
+
}
|
|
2561
|
+
if (!options.start && options.count) {
|
|
2562
|
+
options.returnNewestEntries = true;
|
|
2563
|
+
}
|
|
2564
|
+
if (msg.message.options.round !== null &&
|
|
2565
|
+
msg.message.options.round !== undefined &&
|
|
2566
|
+
msg.message.options.round !== '') {
|
|
2567
|
+
msg.message.options.round = parseInt(msg.message.options.round, 10);
|
|
2568
|
+
if (!isFinite(msg.message.options.round) || msg.message.options.round < 0) {
|
|
2569
|
+
options.round = this.config.round === null ? undefined : this.config.round;
|
|
2570
|
+
}
|
|
2571
|
+
else {
|
|
2572
|
+
options.round = Math.pow(10, parseInt(msg.message.options.round, 10));
|
|
2573
|
+
}
|
|
2574
|
+
}
|
|
2575
|
+
else {
|
|
2576
|
+
options.round = this.config.round === null ? undefined : this.config.round;
|
|
2577
|
+
}
|
|
2578
|
+
if (options.id && this.aliasMap[options.id]) {
|
|
2579
|
+
options.id = this.aliasMap[options.id];
|
|
2580
|
+
}
|
|
2581
|
+
if ((options.aggregate === 'percentile' && options.percentile < 0) || options.percentile > 100) {
|
|
2582
|
+
this.log.error(`Invalid percentile value: ${options.percentile}, use 50 as default`);
|
|
2583
|
+
options.percentile = 50;
|
|
2584
|
+
}
|
|
2585
|
+
if ((options.aggregate === 'quantile' && options.quantile < 0) || options.quantile > 1) {
|
|
2586
|
+
this.log.error(`Invalid quantile value: ${options.quantile}, use 0.5 as default`);
|
|
2587
|
+
options.quantile = 0.5;
|
|
2588
|
+
}
|
|
2589
|
+
if (options.aggregate === 'integral' &&
|
|
2590
|
+
(typeof options.integralUnit !== 'number' || options.integralUnit <= 0)) {
|
|
2591
|
+
this.log.error(`Invalid integralUnit value: ${options.integralUnit}, use 60s as default`);
|
|
2592
|
+
options.integralUnit = 60;
|
|
2593
|
+
}
|
|
2594
|
+
if (options.id) {
|
|
2595
|
+
this.sqlDPs[options.id] ||= {};
|
|
2596
|
+
}
|
|
2597
|
+
const debugLog = !!((options.id && this.sqlDPs[options.id]?.config?.enableDebugLogs) ||
|
|
2598
|
+
this.config.enableDebugLogs);
|
|
2599
|
+
if (options.start > options.end) {
|
|
2600
|
+
const _end = options.end;
|
|
2601
|
+
options.end = options.start;
|
|
2602
|
+
options.start = _end;
|
|
2603
|
+
}
|
|
2604
|
+
if (!options.start && !options.count) {
|
|
2605
|
+
options.start = Date.now() - 86400000; // - 1 day
|
|
2606
|
+
}
|
|
2607
|
+
if (debugLog) {
|
|
2608
|
+
this.log.debug(`${logId} getHistory options final: ${JSON.stringify(options)}`);
|
|
2609
|
+
}
|
|
2610
|
+
if (options.id && this.sqlDPs[options.id].type === undefined && this.sqlDPs[options.id].dbType !== undefined) {
|
|
2611
|
+
const storageType = this.sqlDPs[options.id].config?.storageType;
|
|
2612
|
+
if (storageType) {
|
|
2613
|
+
if (storageTypes.indexOf(storageType) === this.sqlDPs[options.id].dbType) {
|
|
2614
|
+
if (debugLog) {
|
|
2615
|
+
this.log.debug(`${logId} For getHistory for id ${options.id}: Type empty, use storageType dbType ${this.sqlDPs[options.id].dbType}`);
|
|
2616
|
+
}
|
|
2617
|
+
this.sqlDPs[options.id].type = this.sqlDPs[options.id].dbType;
|
|
2618
|
+
}
|
|
2619
|
+
}
|
|
2620
|
+
else {
|
|
2621
|
+
if (debugLog) {
|
|
2622
|
+
this.log.debug(`${logId} For getHistory for id ${options.id}: Type empty, use dbType ${this.sqlDPs[options.id].dbType}`);
|
|
2623
|
+
}
|
|
2624
|
+
this.sqlDPs[options.id].type = this.sqlDPs[options.id].dbType;
|
|
2625
|
+
}
|
|
2626
|
+
}
|
|
2627
|
+
if (options.id && this.sqlDPs[options.id].index === undefined) {
|
|
2628
|
+
// read or create in DB
|
|
2629
|
+
return this.getId(options.id, null, err => {
|
|
2630
|
+
if (err) {
|
|
2631
|
+
this.log.warn(`Cannot get index of "${options.id}": ${err}`);
|
|
2632
|
+
(0, aggregate_1.sendResponse)(this, msg, options.id, options, [], startTime);
|
|
2633
|
+
}
|
|
2634
|
+
else {
|
|
2635
|
+
this.getHistorySql(msg);
|
|
2636
|
+
}
|
|
2637
|
+
});
|
|
2638
|
+
}
|
|
2639
|
+
if (options.id && this.sqlDPs[options.id].type === undefined) {
|
|
2640
|
+
this.log.warn(`For getHistory for id "${options.id}": Type empty. Need to write data first. Index = ${this.sqlDPs[options.id].index}`);
|
|
2641
|
+
(0, aggregate_1.sendResponse)(this, msg, options.id, options, 'Please wait till next data record is logged and reload.', startTime);
|
|
2642
|
+
return;
|
|
2643
|
+
}
|
|
2644
|
+
// if specific id requested
|
|
2645
|
+
if (options.id) {
|
|
2646
|
+
const type = this.sqlDPs[options.id].type;
|
|
2647
|
+
options.index = this.sqlDPs[options.id].index;
|
|
2648
|
+
this.getCachedData(options, (cacheData, isFull, includesInFlightData, earliestTs) => {
|
|
2649
|
+
if (debugLog) {
|
|
2650
|
+
this.log.debug(`${logId} after getCachedData: length = ${cacheData.length}, isFull=${isFull}`);
|
|
2651
|
+
}
|
|
2652
|
+
// if all data read
|
|
2653
|
+
if (isFull &&
|
|
2654
|
+
cacheData.length &&
|
|
2655
|
+
(options.aggregate === 'onchange' || !options.aggregate || options.aggregate === 'none')) {
|
|
2656
|
+
cacheData.sort(sortByTs);
|
|
2657
|
+
if (options.count && cacheData.length > options.count && options.aggregate === 'none') {
|
|
2658
|
+
cacheData.splice(0, cacheData.length - options.count);
|
|
2659
|
+
if (debugLog) {
|
|
2660
|
+
this.log.debug(`${logId} cut cacheData to ${options.count} values`);
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
this.log.debug(`${logId} Send: ${cacheData.length} values in: ${Date.now() - startTime}ms`);
|
|
2664
|
+
this.sendTo(msg.from, msg.command, {
|
|
2665
|
+
result: cacheData,
|
|
2666
|
+
step: null,
|
|
2667
|
+
error: null,
|
|
2668
|
+
}, msg.callback);
|
|
2669
|
+
}
|
|
2670
|
+
else {
|
|
2671
|
+
const origEnd = options.end;
|
|
2672
|
+
if (includesInFlightData && earliestTs) {
|
|
2673
|
+
options.end = earliestTs;
|
|
2674
|
+
}
|
|
2675
|
+
// if not all data read
|
|
2676
|
+
this.getDataFromDB(dbNames[type], options, (err, data) => {
|
|
2677
|
+
if (!err && data) {
|
|
2678
|
+
options.end = origEnd;
|
|
2679
|
+
if (options.aggregate === 'none' && options.count && options.returnNewestEntries) {
|
|
2680
|
+
cacheData = cacheData.reverse();
|
|
2681
|
+
data = cacheData.concat(data);
|
|
2682
|
+
}
|
|
2683
|
+
else {
|
|
2684
|
+
data = data.concat(cacheData);
|
|
2685
|
+
}
|
|
2686
|
+
if (debugLog) {
|
|
2687
|
+
this.log.debug(`${logId} after getDataFromDB: length = ${data.length}`);
|
|
2688
|
+
}
|
|
2689
|
+
if (options.count &&
|
|
2690
|
+
data.length > options.count &&
|
|
2691
|
+
options.aggregate === 'none' &&
|
|
2692
|
+
!options.returnNewestEntries) {
|
|
2693
|
+
if (options.start) {
|
|
2694
|
+
for (let i = 0; i < data.length; i++) {
|
|
2695
|
+
if (data[i].ts < options.start) {
|
|
2696
|
+
data.splice(i, 1);
|
|
2697
|
+
i--;
|
|
2698
|
+
}
|
|
2699
|
+
else {
|
|
2700
|
+
break;
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
}
|
|
2704
|
+
data.splice(options.count);
|
|
2705
|
+
if (debugLog) {
|
|
2706
|
+
this.log.debug(`${logId} pre-cut data to ${options.count} oldest values`);
|
|
2707
|
+
}
|
|
2708
|
+
}
|
|
2709
|
+
data.sort(sortByTs);
|
|
2710
|
+
}
|
|
2711
|
+
try {
|
|
2712
|
+
(0, aggregate_1.sendResponse)(this, msg, options.id, options, err?.toString() || data || [], startTime, debugLog ? logId : undefined);
|
|
2713
|
+
}
|
|
2714
|
+
catch (e) {
|
|
2715
|
+
(0, aggregate_1.sendResponse)(this, msg, options.id, options, e.toString(), startTime);
|
|
2716
|
+
}
|
|
2717
|
+
});
|
|
2718
|
+
}
|
|
2719
|
+
});
|
|
2720
|
+
}
|
|
2721
|
+
else {
|
|
2722
|
+
// if all IDs requested
|
|
2723
|
+
let rows = [];
|
|
2724
|
+
let count = 0;
|
|
2725
|
+
this.getCachedData(options, (cacheData, isFull, includesInFlightData, earliestTs) => {
|
|
2726
|
+
if (isFull && cacheData.length) {
|
|
2727
|
+
cacheData.sort(sortByTs);
|
|
2728
|
+
(0, aggregate_1.sendResponse)(this, msg, '', options, cacheData, startTime, debugLog ? logId : undefined);
|
|
2729
|
+
}
|
|
2730
|
+
else {
|
|
2731
|
+
if (includesInFlightData && earliestTs) {
|
|
2732
|
+
options.end = earliestTs;
|
|
2733
|
+
}
|
|
2734
|
+
for (let db = 0; db < dbNames.length; db++) {
|
|
2735
|
+
count++;
|
|
2736
|
+
this.getDataFromDB(dbNames[db], options, (err, data) => {
|
|
2737
|
+
if (data) {
|
|
2738
|
+
rows = rows.concat(data);
|
|
2739
|
+
}
|
|
2740
|
+
if (!--count) {
|
|
2741
|
+
rows.sort(sortByTs);
|
|
2742
|
+
try {
|
|
2743
|
+
(0, aggregate_1.sendResponse)(this, msg, '', options, rows, startTime);
|
|
2744
|
+
}
|
|
2745
|
+
catch (e) {
|
|
2746
|
+
(0, aggregate_1.sendResponse)(this, msg, '', options, e.toString(), startTime);
|
|
2747
|
+
}
|
|
2748
|
+
}
|
|
2749
|
+
});
|
|
2750
|
+
}
|
|
2751
|
+
}
|
|
2752
|
+
});
|
|
2753
|
+
}
|
|
2754
|
+
}
|
|
2755
|
+
update(id, state, cb) {
|
|
2756
|
+
// first try to find the value in not yet saved data
|
|
2757
|
+
let found = false;
|
|
2758
|
+
if (this.sqlDPs[id]) {
|
|
2759
|
+
const res = this.sqlDPs[id].list;
|
|
2760
|
+
if (res) {
|
|
2761
|
+
for (let i = res.length - 1; i >= 0; i--) {
|
|
2762
|
+
if (res[i].state.ts === state.ts) {
|
|
2763
|
+
if (state.val !== undefined) {
|
|
2764
|
+
res[i].state.val = state.val;
|
|
2765
|
+
}
|
|
2766
|
+
if (state.q !== undefined && res[i].state.q !== undefined) {
|
|
2767
|
+
res[i].state.q = state.q;
|
|
2768
|
+
}
|
|
2769
|
+
if (state.from !== undefined && res[i].from !== undefined) {
|
|
2770
|
+
res[i].state.from = state.from;
|
|
2771
|
+
}
|
|
2772
|
+
if (state.ack !== undefined) {
|
|
2773
|
+
res[i].state.ack = state.ack;
|
|
2774
|
+
}
|
|
2775
|
+
found = true;
|
|
2776
|
+
break;
|
|
2777
|
+
}
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
}
|
|
2781
|
+
if (!found) {
|
|
2782
|
+
this.prepareTaskCheckTypeAndDbId(id, state, false, (err) => {
|
|
2783
|
+
if (err) {
|
|
2784
|
+
return cb?.(err);
|
|
2785
|
+
}
|
|
2786
|
+
const type = this.sqlDPs[id].type;
|
|
2787
|
+
const query = this.sqlFuncs.update(this.config.dbname, this.sqlDPs[id].index, state, this.from[state.from], dbNames[type]);
|
|
2788
|
+
if (!this.multiRequests) {
|
|
2789
|
+
if (this.tasks.length > MAX_TASKS) {
|
|
2790
|
+
const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
|
|
2791
|
+
this.log.error(error);
|
|
2792
|
+
cb?.(new Error(error));
|
|
2793
|
+
}
|
|
2794
|
+
else {
|
|
2795
|
+
this.tasks.push({ operation: 'query', query, id, callback: cb });
|
|
2796
|
+
this.tasks.length === 1 && this.processTasks();
|
|
2797
|
+
}
|
|
2798
|
+
}
|
|
2799
|
+
else {
|
|
2800
|
+
this._executeQuery(query, id, cb);
|
|
2801
|
+
}
|
|
2802
|
+
});
|
|
2803
|
+
}
|
|
2804
|
+
else {
|
|
2805
|
+
cb?.();
|
|
2806
|
+
}
|
|
2807
|
+
}
|
|
2808
|
+
#delete(id, state, cb) {
|
|
2809
|
+
// first try to find the value in not yet saved data
|
|
2810
|
+
let found = false;
|
|
2811
|
+
if (this.sqlDPs[id]) {
|
|
2812
|
+
const res = this.sqlDPs[id].list;
|
|
2813
|
+
if (res) {
|
|
2814
|
+
if (!state.ts && !state.start && !state.end) {
|
|
2815
|
+
this.sqlDPs[id].list = [];
|
|
2816
|
+
}
|
|
2817
|
+
else {
|
|
2818
|
+
for (let i = res.length - 1; i >= 0; i--) {
|
|
2819
|
+
if (state.start && state.end) {
|
|
2820
|
+
if (res[i].state.ts >= state.start && res[i].state.ts <= state.end) {
|
|
2821
|
+
res.splice(i, 1);
|
|
2822
|
+
}
|
|
2823
|
+
}
|
|
2824
|
+
else if (state.start) {
|
|
2825
|
+
if (res[i].state.ts >= state.start) {
|
|
2826
|
+
res.splice(i, 1);
|
|
2827
|
+
}
|
|
2828
|
+
}
|
|
2829
|
+
else if (state.end) {
|
|
2830
|
+
if (res[i].state.ts <= state.end) {
|
|
2831
|
+
res.splice(i, 1);
|
|
2832
|
+
}
|
|
2833
|
+
}
|
|
2834
|
+
else if (res[i].state.ts === state.ts) {
|
|
2835
|
+
res.splice(i, 1);
|
|
2836
|
+
found = true;
|
|
2837
|
+
break;
|
|
2838
|
+
}
|
|
2839
|
+
}
|
|
2840
|
+
}
|
|
2841
|
+
}
|
|
2842
|
+
}
|
|
2843
|
+
if (!found) {
|
|
2844
|
+
this.prepareTaskCheckTypeAndDbId(id, state, false, err => {
|
|
2845
|
+
if (err) {
|
|
2846
|
+
return cb?.(err);
|
|
2847
|
+
}
|
|
2848
|
+
const type = this.sqlDPs[id].type;
|
|
2849
|
+
let query;
|
|
2850
|
+
if (state.start && state.end) {
|
|
2851
|
+
query = this.sqlFuncs.deleteFromTable(this.config.dbname, dbNames[type], this.sqlDPs[id].index, state.start, state.end);
|
|
2852
|
+
}
|
|
2853
|
+
else if (state.ts) {
|
|
2854
|
+
query = this.sqlFuncs.deleteFromTable(this.config.dbname, dbNames[type], this.sqlDPs[id].index, state.ts);
|
|
2855
|
+
}
|
|
2856
|
+
else {
|
|
2857
|
+
// delete all entries for ID
|
|
2858
|
+
query = this.sqlFuncs.deleteFromTable(this.config.dbname, dbNames[type], this.sqlDPs[id].index);
|
|
2859
|
+
}
|
|
2860
|
+
if (!this.multiRequests) {
|
|
2861
|
+
if (this.tasks.length > MAX_TASKS) {
|
|
2862
|
+
const error = `Cannot queue new requests, because more than ${MAX_TASKS}`;
|
|
2863
|
+
this.log.error(error);
|
|
2864
|
+
cb?.(new Error(error));
|
|
2865
|
+
}
|
|
2866
|
+
else {
|
|
2867
|
+
this.tasks.push({ operation: 'query', query, id, callback: cb });
|
|
2868
|
+
this.tasks.length === 1 && this.processTasks();
|
|
2869
|
+
}
|
|
2870
|
+
}
|
|
2871
|
+
else {
|
|
2872
|
+
this._executeQuery(query, id, cb);
|
|
2873
|
+
}
|
|
2874
|
+
});
|
|
2875
|
+
}
|
|
2876
|
+
else {
|
|
2877
|
+
cb?.();
|
|
2878
|
+
}
|
|
2879
|
+
}
|
|
2880
|
+
updateState(msg) {
|
|
2881
|
+
if (!msg.message) {
|
|
2882
|
+
this.log.error('updateState called with invalid data');
|
|
2883
|
+
return this.sendTo(msg.from, msg.command, {
|
|
2884
|
+
error: `Invalid call: ${JSON.stringify(msg)}`,
|
|
2885
|
+
}, msg.callback);
|
|
2886
|
+
}
|
|
2887
|
+
let id;
|
|
2888
|
+
if (Array.isArray(msg.message)) {
|
|
2889
|
+
this.log.debug(`updateState ${msg.message.length} items`);
|
|
2890
|
+
for (let i = 0; i < msg.message.length; i++) {
|
|
2891
|
+
id = this.aliasMap[msg.message[i].id] ? this.aliasMap[msg.message[i].id] : msg.message[i].id;
|
|
2892
|
+
if (msg.message[i].state && typeof msg.message[i].state === 'object') {
|
|
2893
|
+
this.update(id, msg.message[i].state);
|
|
2894
|
+
}
|
|
2895
|
+
else {
|
|
2896
|
+
this.log.warn(`Invalid state for ${JSON.stringify(msg.message[i])}`);
|
|
2897
|
+
}
|
|
2898
|
+
}
|
|
2899
|
+
}
|
|
2900
|
+
else if (msg.message.state && Array.isArray(msg.message.state)) {
|
|
2901
|
+
this.log.debug(`updateState ${msg.message.state.length} items`);
|
|
2902
|
+
id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
|
|
2903
|
+
for (let j = 0; j < msg.message.state.length; j++) {
|
|
2904
|
+
if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
|
|
2905
|
+
this.update(id, msg.message.state[j]);
|
|
2906
|
+
}
|
|
2907
|
+
else {
|
|
2908
|
+
this.log.warn(`Invalid state for ${JSON.stringify(msg.message.state[j])}`);
|
|
2909
|
+
}
|
|
2910
|
+
}
|
|
2911
|
+
}
|
|
2912
|
+
else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
|
|
2913
|
+
this.log.debug('updateState 1 item');
|
|
2914
|
+
id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
|
|
2915
|
+
return this.update(id, msg.message.state, () => this.sendTo(msg.from, msg.command, {
|
|
2916
|
+
success: true,
|
|
2917
|
+
sqlConnected: !!this.clientPool,
|
|
2918
|
+
}, msg.callback));
|
|
2919
|
+
}
|
|
2920
|
+
else {
|
|
2921
|
+
this.log.error('updateState called with invalid data');
|
|
2922
|
+
return this.sendTo(msg.from, msg.command, {
|
|
2923
|
+
error: `Invalid call: ${JSON.stringify(msg)}`,
|
|
2924
|
+
}, msg.callback);
|
|
2925
|
+
}
|
|
2926
|
+
this.sendTo(msg.from, msg.command, {
|
|
2927
|
+
success: true,
|
|
2928
|
+
sqlConnected: !!this.clientPool,
|
|
2929
|
+
}, msg.callback);
|
|
2930
|
+
}
|
|
2931
|
+
deleteHistoryEntry(msg) {
|
|
2932
|
+
if (!msg.message) {
|
|
2933
|
+
this.log.error('deleteHistoryEntry called with invalid data');
|
|
2934
|
+
return this.sendTo(msg.from, msg.command, {
|
|
2935
|
+
error: `Invalid call: ${JSON.stringify(msg)}`,
|
|
2936
|
+
}, msg.callback);
|
|
2937
|
+
}
|
|
2938
|
+
let id;
|
|
2939
|
+
if (Array.isArray(msg.message)) {
|
|
2940
|
+
this.log.debug(`deleteHistoryEntry ${msg.message.length} items`);
|
|
2941
|
+
for (let i = 0; i < msg.message.length; i++) {
|
|
2942
|
+
id = this.aliasMap[msg.message[i].id] ? this.aliasMap[msg.message[i].id] : msg.message[i].id;
|
|
2943
|
+
// {id: 'blabla', ts: 892}
|
|
2944
|
+
if (msg.message[i].ts) {
|
|
2945
|
+
this.#delete(id, { ts: msg.message[i].ts });
|
|
2946
|
+
}
|
|
2947
|
+
else if (msg.message[i].start) {
|
|
2948
|
+
if (typeof msg.message[i].start === 'string') {
|
|
2949
|
+
msg.message[i].start = new Date(msg.message[i].start).getTime();
|
|
2950
|
+
}
|
|
2951
|
+
if (typeof msg.message[i].end === 'string') {
|
|
2952
|
+
msg.message[i].end = new Date(msg.message[i].end).getTime();
|
|
2953
|
+
}
|
|
2954
|
+
this.#delete(id, { start: msg.message[i].start, end: msg.message[i].end || Date.now() });
|
|
2955
|
+
}
|
|
2956
|
+
else if (typeof msg.message[i].state === 'object' &&
|
|
2957
|
+
msg.message[i].state &&
|
|
2958
|
+
msg.message[i].state.ts) {
|
|
2959
|
+
this.#delete(id, { ts: msg.message[i].state.ts });
|
|
2960
|
+
}
|
|
2961
|
+
else if (typeof msg.message[i].state === 'object' &&
|
|
2962
|
+
msg.message[i].state &&
|
|
2963
|
+
msg.message[i].state.start) {
|
|
2964
|
+
if (typeof msg.message[i].state.start === 'string') {
|
|
2965
|
+
msg.message[i].state.start = new Date(msg.message[i].state.start).getTime();
|
|
2966
|
+
}
|
|
2967
|
+
if (typeof msg.message[i].state.end === 'string') {
|
|
2968
|
+
msg.message[i].state.end = new Date(msg.message[i].state.end).getTime();
|
|
2969
|
+
}
|
|
2970
|
+
this.#delete(id, {
|
|
2971
|
+
start: msg.message[i].state.start,
|
|
2972
|
+
end: msg.message[i].state.end || Date.now(),
|
|
2973
|
+
});
|
|
2974
|
+
}
|
|
2975
|
+
else {
|
|
2976
|
+
this.log.warn(`Invalid state for ${JSON.stringify(msg.message[i])}`);
|
|
2977
|
+
}
|
|
2978
|
+
}
|
|
2979
|
+
}
|
|
2980
|
+
else if (msg.message.state && Array.isArray(msg.message.state)) {
|
|
2981
|
+
this.log.debug(`deleteHistoryEntry ${msg.message.state.length} items`);
|
|
2982
|
+
id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
|
|
2983
|
+
for (let j = 0; j < msg.message.state.length; j++) {
|
|
2984
|
+
if (msg.message.state[j] && typeof msg.message.state[j] === 'object') {
|
|
2985
|
+
if (msg.message.state[j].ts) {
|
|
2986
|
+
this.#delete(id, { ts: msg.message.state[j].ts });
|
|
2987
|
+
}
|
|
2988
|
+
else if (msg.message.state[j].start) {
|
|
2989
|
+
if (typeof msg.message.state[j].start === 'string') {
|
|
2990
|
+
msg.message.state[j].start = new Date(msg.message.state[j].start).getTime();
|
|
2991
|
+
}
|
|
2992
|
+
if (typeof msg.message.state[j].end === 'string') {
|
|
2993
|
+
msg.message.state[j].end = new Date(msg.message.state[j].end).getTime();
|
|
2994
|
+
}
|
|
2995
|
+
this.#delete(id, {
|
|
2996
|
+
start: msg.message.state[j].start,
|
|
2997
|
+
end: msg.message.state[j].end || Date.now(),
|
|
2998
|
+
});
|
|
2999
|
+
}
|
|
3000
|
+
}
|
|
3001
|
+
else if (msg.message.state[j] && typeof msg.message.state[j] === 'number') {
|
|
3002
|
+
this.#delete(id, { ts: msg.message.state[j] });
|
|
3003
|
+
}
|
|
3004
|
+
else {
|
|
3005
|
+
this.log.warn(`Invalid state for ${JSON.stringify(msg.message.state[j])}`);
|
|
3006
|
+
}
|
|
3007
|
+
}
|
|
3008
|
+
}
|
|
3009
|
+
else if (msg.message.ts && Array.isArray(msg.message.ts)) {
|
|
3010
|
+
this.log.debug(`deleteHistoryEntry ${msg.message.ts.length} items`);
|
|
3011
|
+
id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
|
|
3012
|
+
for (let j = 0; j < msg.message.ts.length; j++) {
|
|
3013
|
+
if (msg.message.ts[j] && typeof msg.message.ts[j] === 'number') {
|
|
3014
|
+
this.#delete(id, { ts: msg.message.ts[j] });
|
|
3015
|
+
}
|
|
3016
|
+
else {
|
|
3017
|
+
this.log.warn(`Invalid state for ${JSON.stringify(msg.message.ts[j])}`);
|
|
3018
|
+
}
|
|
3019
|
+
}
|
|
3020
|
+
}
|
|
3021
|
+
else if (msg.message.id && msg.message.state && typeof msg.message.state === 'object') {
|
|
3022
|
+
this.log.debug('deleteHistoryEntry 1 item');
|
|
3023
|
+
id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
|
|
3024
|
+
return this.#delete(id, { ts: msg.message.state.ts }, () => this.sendTo(msg.from, msg.command, {
|
|
3025
|
+
success: true,
|
|
3026
|
+
sqlConnected: !!this.clientPool,
|
|
3027
|
+
}, msg.callback));
|
|
3028
|
+
}
|
|
3029
|
+
else if (msg.message.id && msg.message.ts && typeof msg.message.ts === 'number') {
|
|
3030
|
+
this.log.debug('deleteHistoryEntry 1 item');
|
|
3031
|
+
id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
|
|
3032
|
+
return this.#delete(id, { ts: msg.message.ts }, () => this.sendTo(msg.from, msg.command, {
|
|
3033
|
+
success: true,
|
|
3034
|
+
sqlConnected: !!this.clientPool,
|
|
3035
|
+
}, msg.callback));
|
|
3036
|
+
}
|
|
3037
|
+
else {
|
|
3038
|
+
this.log.error('deleteHistoryEntry called with invalid data');
|
|
3039
|
+
return this.sendTo(msg.from, msg.command, { error: `Invalid call: ${JSON.stringify(msg)}` }, msg.callback);
|
|
3040
|
+
}
|
|
3041
|
+
this.sendTo(msg.from, msg.command, {
|
|
3042
|
+
success: true,
|
|
3043
|
+
sqlConnected: !!this.clientPool,
|
|
3044
|
+
}, msg.callback);
|
|
3045
|
+
}
|
|
3046
|
+
deleteStateAll(msg) {
|
|
3047
|
+
if (!msg.message) {
|
|
3048
|
+
this.log.error('deleteStateAll called with invalid data');
|
|
3049
|
+
return this.sendTo(msg.from, msg.command, {
|
|
3050
|
+
error: `Invalid call: ${JSON.stringify(msg)}`,
|
|
3051
|
+
}, msg.callback);
|
|
3052
|
+
}
|
|
3053
|
+
let id;
|
|
3054
|
+
if (Array.isArray(msg.message)) {
|
|
3055
|
+
this.log.debug(`deleteStateAll ${msg.message.length} items`);
|
|
3056
|
+
for (let i = 0; i < msg.message.length; i++) {
|
|
3057
|
+
id = this.aliasMap[msg.message[i].id] ? this.aliasMap[msg.message[i].id] : msg.message[i].id;
|
|
3058
|
+
this.#delete(id, {});
|
|
3059
|
+
}
|
|
3060
|
+
}
|
|
3061
|
+
else if (msg.message.id) {
|
|
3062
|
+
this.log.debug('deleteStateAll 1 item');
|
|
3063
|
+
id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
|
|
3064
|
+
return this.#delete(id, {}, () => this.sendTo(msg.from, msg.command, {
|
|
3065
|
+
success: true,
|
|
3066
|
+
sqlConnected: !!this.clientPool,
|
|
3067
|
+
}, msg.callback));
|
|
3068
|
+
}
|
|
3069
|
+
else {
|
|
3070
|
+
this.log.error('deleteStateAll called with invalid data');
|
|
3071
|
+
return this.sendTo(msg.from, msg.command, { error: `Invalid call: ${JSON.stringify(msg)}` }, msg.callback);
|
|
3072
|
+
}
|
|
3073
|
+
this.sendTo(msg.from, msg.command, {
|
|
3074
|
+
success: true,
|
|
3075
|
+
sqlConnected: !!this.clientPool,
|
|
3076
|
+
}, msg.callback);
|
|
3077
|
+
}
|
|
3078
|
+
storeStatePushData(id, state, applyRules) {
|
|
3079
|
+
if (!state || typeof state !== 'object') {
|
|
3080
|
+
throw new Error(`State ${JSON.stringify(state)} for ${id} is not valid`);
|
|
3081
|
+
}
|
|
3082
|
+
if (!this.sqlDPs[id]?.config) {
|
|
3083
|
+
if (applyRules) {
|
|
3084
|
+
throw new Error(`sql not enabled for ${id}, so can not apply the rules as requested`);
|
|
3085
|
+
}
|
|
3086
|
+
this.sqlDPs[id] ||= {};
|
|
3087
|
+
this.sqlDPs[id].realId = id;
|
|
3088
|
+
}
|
|
3089
|
+
return new Promise((resolve, reject) => {
|
|
3090
|
+
if (applyRules) {
|
|
3091
|
+
this.pushHistory(id, state);
|
|
3092
|
+
resolve(true);
|
|
3093
|
+
}
|
|
3094
|
+
else {
|
|
3095
|
+
this.pushHelper(id, state, err => {
|
|
3096
|
+
if (err) {
|
|
3097
|
+
reject(new Error(`Error writing state for ${id}: ${err.message}, Data: ${JSON.stringify(state)}`));
|
|
3098
|
+
}
|
|
3099
|
+
else {
|
|
3100
|
+
resolve(true);
|
|
3101
|
+
}
|
|
3102
|
+
});
|
|
3103
|
+
}
|
|
3104
|
+
});
|
|
3105
|
+
}
|
|
3106
|
+
async storeState(msg) {
|
|
3107
|
+
if (!msg.message) {
|
|
3108
|
+
this.log.error('storeState called with invalid data');
|
|
3109
|
+
return this.sendTo(msg.from, msg.command, {
|
|
3110
|
+
error: `Invalid call: ${JSON.stringify(msg)}`,
|
|
3111
|
+
}, msg.callback);
|
|
3112
|
+
}
|
|
3113
|
+
const errors = [];
|
|
3114
|
+
let successCount = 0;
|
|
3115
|
+
if (Array.isArray(msg.message)) {
|
|
3116
|
+
this.log.debug(`storeState ${msg.message.length} items`);
|
|
3117
|
+
for (let i = 0; i < msg.message.length; i++) {
|
|
3118
|
+
const id = this.aliasMap[msg.message[i].id] ? this.aliasMap[msg.message[i].id] : msg.message[i].id;
|
|
3119
|
+
try {
|
|
3120
|
+
await this.storeStatePushData(id, msg.message[i].state, msg.message[i].rules);
|
|
3121
|
+
successCount++;
|
|
3122
|
+
}
|
|
3123
|
+
catch (err) {
|
|
3124
|
+
errors.push(err.message);
|
|
3125
|
+
}
|
|
3126
|
+
}
|
|
3127
|
+
}
|
|
3128
|
+
else if (msg.message.id && Array.isArray(msg.message.state)) {
|
|
3129
|
+
this.log.debug(`storeState ${msg.message.state.length} items`);
|
|
3130
|
+
const id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
|
|
3131
|
+
for (let j = 0; j < msg.message.state.length; j++) {
|
|
3132
|
+
try {
|
|
3133
|
+
await this.storeStatePushData(id, msg.message.state[j], msg.message.rules);
|
|
3134
|
+
successCount++;
|
|
3135
|
+
}
|
|
3136
|
+
catch (err) {
|
|
3137
|
+
errors.push(err.message);
|
|
3138
|
+
}
|
|
3139
|
+
}
|
|
3140
|
+
}
|
|
3141
|
+
else if (msg.message.id && msg.message.state) {
|
|
3142
|
+
this.log.debug('storeState 1 item');
|
|
3143
|
+
const id = this.aliasMap[msg.message.id] ? this.aliasMap[msg.message.id] : msg.message.id;
|
|
3144
|
+
try {
|
|
3145
|
+
await this.storeStatePushData(id, msg.message.state, msg.message.rules);
|
|
3146
|
+
successCount++;
|
|
3147
|
+
}
|
|
3148
|
+
catch (err) {
|
|
3149
|
+
errors.push(err.message);
|
|
3150
|
+
}
|
|
3151
|
+
}
|
|
3152
|
+
else {
|
|
3153
|
+
this.log.error('storeState called with invalid data');
|
|
3154
|
+
return this.sendTo(msg.from, msg.command, {
|
|
3155
|
+
error: `Invalid call: ${JSON.stringify(msg)}`,
|
|
3156
|
+
}, msg.callback);
|
|
3157
|
+
}
|
|
3158
|
+
if (errors.length) {
|
|
3159
|
+
this.log.warn(`storeState executed with ${errors.length} errors: ${errors.join(', ')}`);
|
|
3160
|
+
return this.sendTo(msg.from, msg.command, {
|
|
3161
|
+
error: `${errors.length} errors happened while storing data`,
|
|
3162
|
+
errors: errors,
|
|
3163
|
+
successCount,
|
|
3164
|
+
}, msg.callback);
|
|
3165
|
+
}
|
|
3166
|
+
this.log.debug(`storeState executed with ${successCount} states successfully`);
|
|
3167
|
+
this.sendTo(msg.from, msg.command, {
|
|
3168
|
+
success: true,
|
|
3169
|
+
successCount,
|
|
3170
|
+
sqlConnected: !!this.clientPool,
|
|
3171
|
+
}, msg.callback);
|
|
3172
|
+
}
|
|
3173
|
+
getDpOverview(msg) {
|
|
3174
|
+
const result = [];
|
|
3175
|
+
const query = this.sqlFuncs.getIdSelect(this.config.dbname);
|
|
3176
|
+
this.log.info(query);
|
|
3177
|
+
this.borrowClientFromPool((err, client) => {
|
|
3178
|
+
if (err || !client) {
|
|
3179
|
+
this.returnClientToPool(client);
|
|
3180
|
+
return this.sendTo(msg.from, msg.command, {
|
|
3181
|
+
error: `Cannot select ${query}: ${err || 'no client'}`,
|
|
3182
|
+
}, msg.callback);
|
|
3183
|
+
}
|
|
3184
|
+
client.execute(query, (err, rows /* , fields */) => {
|
|
3185
|
+
if (err) {
|
|
3186
|
+
this.returnClientToPool(client);
|
|
3187
|
+
this.log.error(`Cannot select ${query}: ${err}`);
|
|
3188
|
+
this.sendTo(msg.from, msg.command, {
|
|
3189
|
+
error: `Cannot select ${query}: ${err}`,
|
|
3190
|
+
}, msg.callback);
|
|
3191
|
+
return;
|
|
3192
|
+
}
|
|
3193
|
+
this.log.info(`Query result ${JSON.stringify(rows)}`);
|
|
3194
|
+
if (rows?.length) {
|
|
3195
|
+
for (let r = 0; r < rows.length; r++) {
|
|
3196
|
+
result[rows[r].type] ||= {};
|
|
3197
|
+
result[rows[r].type][rows[r].id] = { name: rows[r].name };
|
|
3198
|
+
switch (dbNames[rows[r].type]) {
|
|
3199
|
+
case 'ts_number':
|
|
3200
|
+
result[rows[r].type][rows[r].id].type = 'number';
|
|
3201
|
+
break;
|
|
3202
|
+
case 'ts_string':
|
|
3203
|
+
result[rows[r].type][rows[r].id].type = 'string';
|
|
3204
|
+
break;
|
|
3205
|
+
case 'ts_bool':
|
|
3206
|
+
result[rows[r].type][rows[r].id].type = 'boolean';
|
|
3207
|
+
break;
|
|
3208
|
+
}
|
|
3209
|
+
}
|
|
3210
|
+
this.log.info(`initialisation result: ${JSON.stringify(result)}`);
|
|
3211
|
+
this.getFirstTsForIds(client, 0, result, msg);
|
|
3212
|
+
}
|
|
3213
|
+
});
|
|
3214
|
+
});
|
|
3215
|
+
}
|
|
3216
|
+
getFirstTsForIds(client, typeId, resultData, msg) {
|
|
3217
|
+
if (typeId < dbNames.length) {
|
|
3218
|
+
if (!resultData[typeId]) {
|
|
3219
|
+
this.getFirstTsForIds(client, (typeId + 1), resultData, msg);
|
|
3220
|
+
}
|
|
3221
|
+
else {
|
|
3222
|
+
const query = this.sqlFuncs.getFirstTs(this.config.dbname, dbNames[typeId]);
|
|
3223
|
+
this.log.info(query);
|
|
3224
|
+
client.execute(query, (err, rows /* , fields */) => {
|
|
3225
|
+
if (err) {
|
|
3226
|
+
this.returnClientToPool(client);
|
|
3227
|
+
this.log.error(`Cannot select ${query}: ${err}`);
|
|
3228
|
+
this.sendTo(msg.from, msg.command, {
|
|
3229
|
+
error: `Cannot select ${query}: ${err}`,
|
|
3230
|
+
}, msg.callback);
|
|
3231
|
+
return;
|
|
3232
|
+
}
|
|
3233
|
+
this.log.info(`Query result ${JSON.stringify(rows)}`);
|
|
3234
|
+
if (rows?.length) {
|
|
3235
|
+
for (let r = 0; r < rows.length; r++) {
|
|
3236
|
+
if (resultData[typeId][rows[r].id]) {
|
|
3237
|
+
resultData[typeId][rows[r].id].ts = rows[r].ts;
|
|
3238
|
+
}
|
|
3239
|
+
}
|
|
3240
|
+
}
|
|
3241
|
+
this.log.info(`enhanced result (${typeId}): ${JSON.stringify(resultData)}`);
|
|
3242
|
+
this.dpOverviewTimeout = setTimeout((_client, typeId, resultData, msg) => {
|
|
3243
|
+
this.dpOverviewTimeout = null;
|
|
3244
|
+
this.getFirstTsForIds(_client, typeId, resultData, msg);
|
|
3245
|
+
}, 5000, client, typeId + 1, resultData, msg);
|
|
3246
|
+
});
|
|
3247
|
+
}
|
|
3248
|
+
}
|
|
3249
|
+
else {
|
|
3250
|
+
this.returnClientToPool(client);
|
|
3251
|
+
this.log.info('consolidate data ...');
|
|
3252
|
+
const result = {};
|
|
3253
|
+
for (let ti = 0; ti < dbNames.length; ti++) {
|
|
3254
|
+
if (resultData[ti]) {
|
|
3255
|
+
for (const index in resultData[ti]) {
|
|
3256
|
+
if (!Object.prototype.hasOwnProperty.call(resultData[ti], index)) {
|
|
3257
|
+
continue;
|
|
3258
|
+
}
|
|
3259
|
+
const id = resultData[ti][index].name;
|
|
3260
|
+
if (!result[id]) {
|
|
3261
|
+
result[id] = {
|
|
3262
|
+
type: resultData[ti][index].type || 'undefined',
|
|
3263
|
+
ts: resultData[ti][index].ts,
|
|
3264
|
+
};
|
|
3265
|
+
}
|
|
3266
|
+
else {
|
|
3267
|
+
result[id].type = 'undefined';
|
|
3268
|
+
if (result[id].ts !== undefined &&
|
|
3269
|
+
(resultData[ti][index].ts === undefined || resultData[ti][index].ts < result[id].ts)) {
|
|
3270
|
+
result[id].ts = resultData[ti][index].ts;
|
|
3271
|
+
}
|
|
3272
|
+
}
|
|
3273
|
+
}
|
|
3274
|
+
}
|
|
3275
|
+
}
|
|
3276
|
+
this.log.info(`Result: ${JSON.stringify(result)}`);
|
|
3277
|
+
this.sendTo(msg.from, msg.command, {
|
|
3278
|
+
success: true,
|
|
3279
|
+
result: result,
|
|
3280
|
+
}, msg.callback);
|
|
3281
|
+
}
|
|
3282
|
+
}
|
|
3283
|
+
enableHistory(msg) {
|
|
3284
|
+
if (!msg.message?.id) {
|
|
3285
|
+
this.log.error('enableHistory called with invalid data');
|
|
3286
|
+
this.sendTo(msg.from, msg.command, { error: 'Invalid call' }, msg.callback);
|
|
3287
|
+
return;
|
|
3288
|
+
}
|
|
3289
|
+
const obj = {};
|
|
3290
|
+
obj.common = {};
|
|
3291
|
+
obj.common.custom = {};
|
|
3292
|
+
obj.common.custom[this.namespace] = msg.message.options || {};
|
|
3293
|
+
obj.common.custom[this.namespace].enabled = true;
|
|
3294
|
+
this.extendForeignObject(msg.message.id, obj, err => {
|
|
3295
|
+
if (err) {
|
|
3296
|
+
this.log.error(`enableHistory: ${err}`);
|
|
3297
|
+
this.sendTo(msg.from, msg.command, {
|
|
3298
|
+
error: err,
|
|
3299
|
+
}, msg.callback);
|
|
3300
|
+
}
|
|
3301
|
+
else {
|
|
3302
|
+
this.log.info(JSON.stringify(obj));
|
|
3303
|
+
this.sendTo(msg.from, msg.command, { success: true }, msg.callback);
|
|
3304
|
+
}
|
|
3305
|
+
});
|
|
3306
|
+
}
|
|
3307
|
+
disableHistory(msg) {
|
|
3308
|
+
if (!msg.message?.id) {
|
|
3309
|
+
this.log.error('disableHistory called with invalid data');
|
|
3310
|
+
return this.sendTo(msg.from, msg.command, {
|
|
3311
|
+
error: 'Invalid call',
|
|
3312
|
+
}, msg.callback);
|
|
3313
|
+
}
|
|
3314
|
+
const obj = {};
|
|
3315
|
+
obj.common = {};
|
|
3316
|
+
obj.common.custom = {
|
|
3317
|
+
[this.namespace]: {
|
|
3318
|
+
enabled: false,
|
|
3319
|
+
},
|
|
3320
|
+
};
|
|
3321
|
+
this.extendForeignObject(msg.message.id, obj, err => {
|
|
3322
|
+
if (err) {
|
|
3323
|
+
this.log.error(`disableHistory: ${err}`);
|
|
3324
|
+
this.sendTo(msg.from, msg.command, {
|
|
3325
|
+
error: err,
|
|
3326
|
+
}, msg.callback);
|
|
3327
|
+
}
|
|
3328
|
+
else {
|
|
3329
|
+
this.log.info(JSON.stringify(obj));
|
|
3330
|
+
this.sendTo(msg.from, msg.command, { success: true }, msg.callback);
|
|
3331
|
+
}
|
|
3332
|
+
});
|
|
3333
|
+
}
|
|
3334
|
+
getEnabledDPs(msg) {
|
|
3335
|
+
const data = {};
|
|
3336
|
+
for (const id in this.sqlDPs) {
|
|
3337
|
+
if (Object.prototype.hasOwnProperty.call(this.sqlDPs, id) && this.sqlDPs[id]?.config?.enabled) {
|
|
3338
|
+
data[this.sqlDPs[id].realId] = this.sqlDPs[id].config;
|
|
3339
|
+
}
|
|
3340
|
+
}
|
|
3341
|
+
this.sendTo(msg.from, msg.command, data, msg.callback);
|
|
3342
|
+
}
|
|
3343
|
+
/**
|
|
3344
|
+
* Align the connection settings with the MySQL container declared in docker-compose.yaml.
|
|
3345
|
+
*
|
|
3346
|
+
* The container itself (image, ports, volumes, credentials) is defined there and created by the
|
|
3347
|
+
* docker plugin. This only mirrors the values the adapter needs to connect, because the admin UI
|
|
3348
|
+
* hides host/port/user/password/dbname/dbtype while the docker container is enabled and those
|
|
3349
|
+
* fields may still hold stale values from a previous manual setup.
|
|
3350
|
+
*/
|
|
3351
|
+
applyDockerMysqlConfig(config) {
|
|
3352
|
+
config.dockerMysql ||= { enabled: false };
|
|
3353
|
+
config.dbtype = 'mysql';
|
|
3354
|
+
config.dbname = 'iobroker';
|
|
3355
|
+
config.user = 'iobroker';
|
|
3356
|
+
config.password = 'iobroker';
|
|
3357
|
+
config.dockerMysql.port = parseInt(config.dockerMysql.port || '3306', 10) || 3306;
|
|
3358
|
+
config.port = config.dockerMysql.port;
|
|
3359
|
+
config.host = config.dockerMysql.bind || '127.0.0.1';
|
|
3360
|
+
config.multiRequests = true;
|
|
3361
|
+
config.maxConnections = 100;
|
|
3362
|
+
if (config.dockerPhpMyAdmin) {
|
|
3363
|
+
config.dockerPhpMyAdmin.port = parseInt(config.dockerPhpMyAdmin.port || '8080', 10) || 8080;
|
|
3364
|
+
}
|
|
3365
|
+
}
|
|
3366
|
+
normalizeAdapterConfig(config) {
|
|
3367
|
+
config.dbname ||= 'iobroker';
|
|
3368
|
+
if (config.writeNulls === undefined) {
|
|
3369
|
+
config.writeNulls = true;
|
|
3370
|
+
}
|
|
3371
|
+
config.retention = parseInt(config.retention, 10) || 0;
|
|
3372
|
+
if (config.retention === -1) {
|
|
3373
|
+
// Custom timeframe
|
|
3374
|
+
config.retention = (parseInt(config.customRetentionDuration, 10) || 0) * 24 * 60 * 60;
|
|
3375
|
+
}
|
|
3376
|
+
config.debounce = parseInt(config.debounce, 10) || 0;
|
|
3377
|
+
config.requestInterval =
|
|
3378
|
+
config.requestInterval === undefined || config.requestInterval === null || config.requestInterval === ''
|
|
3379
|
+
? 0
|
|
3380
|
+
: parseInt(config.requestInterval, 10) || 0;
|
|
3381
|
+
if (config.changesRelogInterval !== null && config.changesRelogInterval !== undefined) {
|
|
3382
|
+
config.changesRelogInterval = parseInt(config.changesRelogInterval, 10);
|
|
3383
|
+
}
|
|
3384
|
+
else {
|
|
3385
|
+
config.changesRelogInterval = 0;
|
|
3386
|
+
}
|
|
3387
|
+
if (!clients[config.dbtype]) {
|
|
3388
|
+
this.log.error(`Unknown DB type: ${config.dbtype}`);
|
|
3389
|
+
void this.stop?.();
|
|
3390
|
+
}
|
|
3391
|
+
if (config.multiRequests !== undefined && config.dbtype !== 'sqlite') {
|
|
3392
|
+
clients[config.dbtype].multiRequests = config.multiRequests;
|
|
3393
|
+
}
|
|
3394
|
+
if (config.maxConnections !== undefined && config.dbtype !== 'sqlite') {
|
|
3395
|
+
config.maxConnections = parseInt(config.maxConnections, 10);
|
|
3396
|
+
if (config.maxConnections !== 0 && !config.maxConnections) {
|
|
3397
|
+
config.maxConnections = 100;
|
|
3398
|
+
}
|
|
3399
|
+
}
|
|
3400
|
+
else {
|
|
3401
|
+
config.maxConnections = 1; // SQLite does not support multiple connections
|
|
3402
|
+
}
|
|
3403
|
+
if (config.changesMinDelta !== null && config.changesMinDelta !== undefined) {
|
|
3404
|
+
config.changesMinDelta = parseFloat(config.changesMinDelta.toString().replace(/,/g, '.'));
|
|
3405
|
+
}
|
|
3406
|
+
else {
|
|
3407
|
+
config.changesMinDelta = 0;
|
|
3408
|
+
}
|
|
3409
|
+
if (config.blockTime !== null && config.blockTime !== undefined) {
|
|
3410
|
+
config.blockTime = parseInt(config.blockTime, 10) || 0;
|
|
3411
|
+
}
|
|
3412
|
+
else {
|
|
3413
|
+
if (config.debounce !== null && config.debounce !== undefined) {
|
|
3414
|
+
config.debounce = parseInt(config.debounce, 10) || 0;
|
|
3415
|
+
}
|
|
3416
|
+
else {
|
|
3417
|
+
config.blockTime = 0;
|
|
3418
|
+
}
|
|
3419
|
+
}
|
|
3420
|
+
if (config.debounceTime !== null && config.debounceTime !== undefined) {
|
|
3421
|
+
config.debounceTime = parseInt(config.debounceTime, 10) || 0;
|
|
3422
|
+
}
|
|
3423
|
+
else {
|
|
3424
|
+
config.debounceTime = 0;
|
|
3425
|
+
}
|
|
3426
|
+
if (config.maxLength !== null && config.maxLength !== undefined) {
|
|
3427
|
+
config.maxLength = parseInt(config.maxLength, 10) || 0;
|
|
3428
|
+
}
|
|
3429
|
+
else {
|
|
3430
|
+
config.maxLength = 0;
|
|
3431
|
+
}
|
|
3432
|
+
this.multiRequests = clients[config.dbtype].multiRequests;
|
|
3433
|
+
if (!this.multiRequests) {
|
|
3434
|
+
config.writeNulls = false;
|
|
3435
|
+
}
|
|
3436
|
+
config.port = parseInt(config.port, 10) || 0;
|
|
3437
|
+
if (config.round !== null && config.round !== undefined && config.round !== '') {
|
|
3438
|
+
config.round = parseInt(config.round, 10);
|
|
3439
|
+
if (!isFinite(config.round) || config.round < 0) {
|
|
3440
|
+
config.round = null;
|
|
3441
|
+
this.log.info(`Invalid round value: ${config.round} - ignore, do not round values`);
|
|
3442
|
+
}
|
|
3443
|
+
else {
|
|
3444
|
+
config.round = Math.pow(10, config.round);
|
|
3445
|
+
}
|
|
3446
|
+
}
|
|
3447
|
+
else {
|
|
3448
|
+
config.round = null;
|
|
3449
|
+
}
|
|
3450
|
+
return config;
|
|
3451
|
+
}
|
|
3452
|
+
/**
|
|
3453
|
+
* Make sure the 'iobroker' user exists in the containerized MySQL.
|
|
3454
|
+
*
|
|
3455
|
+
* The mysql image already creates it from MYSQL_USER/MYSQL_PASSWORD on first start, so this is a
|
|
3456
|
+
* fallback for volumes that were created before those variables were declared. The container is
|
|
3457
|
+
* started by the docker plugin and may still be initialising, therefore the connection is retried.
|
|
3458
|
+
*/
|
|
3459
|
+
async createUserInDocker(retries = 30) {
|
|
3460
|
+
const mySQLOptions = {
|
|
3461
|
+
host: this.config.host, // needed for PostgreSQL , MySQL
|
|
3462
|
+
user: 'root',
|
|
3463
|
+
password: this.config.dockerMysql.rootPassword || 'root_iobroker',
|
|
3464
|
+
port: this.config.port || undefined,
|
|
3465
|
+
ssl: this.config.encrypt
|
|
3466
|
+
? {
|
|
3467
|
+
rejectUnauthorized: !!this.config.rejectUnauthorized,
|
|
3468
|
+
}
|
|
3469
|
+
: undefined,
|
|
3470
|
+
};
|
|
3471
|
+
for (let attempt = 1; attempt <= retries; attempt++) {
|
|
3472
|
+
const client = new mysql_client_1.MySQL2Client(mySQLOptions);
|
|
3473
|
+
try {
|
|
3474
|
+
await client.connectAsync();
|
|
3475
|
+
// Show all users
|
|
3476
|
+
const exists = await client.executeAsync(`SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = 'iobroker') as "ex";`);
|
|
3477
|
+
if (exists?.[0]?.ex !== 1) {
|
|
3478
|
+
// create user
|
|
3479
|
+
await client.executeAsync(`CREATE USER 'iobroker'@'%' IDENTIFIED BY 'iobroker';`);
|
|
3480
|
+
await client.executeAsync(`GRANT ALL PRIVILEGES ON * . * TO 'iobroker'@'%';`);
|
|
3481
|
+
await client.executeAsync(`FLUSH PRIVILEGES;`);
|
|
3482
|
+
}
|
|
3483
|
+
await client.disconnectAsync();
|
|
3484
|
+
return;
|
|
3485
|
+
}
|
|
3486
|
+
catch (e) {
|
|
3487
|
+
try {
|
|
3488
|
+
await client.disconnectAsync();
|
|
3489
|
+
}
|
|
3490
|
+
catch {
|
|
3491
|
+
// the connection was never established
|
|
3492
|
+
}
|
|
3493
|
+
if (attempt === retries) {
|
|
3494
|
+
// Do not abort the start-up: the user is normally created by the image itself
|
|
3495
|
+
this.log.warn(`Cannot verify the "iobroker" user in the MySQL container: ${e}`);
|
|
3496
|
+
return;
|
|
3497
|
+
}
|
|
3498
|
+
this.log.debug(`MySQL container not ready yet (${attempt}/${retries}), waiting...`);
|
|
3499
|
+
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
3500
|
+
}
|
|
3501
|
+
}
|
|
3502
|
+
}
|
|
3503
|
+
async main() {
|
|
3504
|
+
this.setConnected(false);
|
|
3505
|
+
// set default history if not yet set
|
|
3506
|
+
try {
|
|
3507
|
+
const obj = await this.getForeignObjectAsync('system.config');
|
|
3508
|
+
if (obj?.common && !obj.common.defaultHistory) {
|
|
3509
|
+
obj.common.defaultHistory = this.namespace;
|
|
3510
|
+
await this.setForeignObjectAsync('system.config', obj);
|
|
3511
|
+
this.log.info(`Set default history instance to "${this.namespace}"`);
|
|
3512
|
+
}
|
|
3513
|
+
}
|
|
3514
|
+
catch (e) {
|
|
3515
|
+
this.log.error(`Cannot get system config: ${e}`);
|
|
3516
|
+
}
|
|
3517
|
+
// The MySQL and phpMyAdmin containers are declared in docker-compose.yaml and are started by
|
|
3518
|
+
// the docker plugin. Align the connection settings before normalising, because normalisation
|
|
3519
|
+
// derives multiRequests/maxConnections/writeNulls from dbtype.
|
|
3520
|
+
if (this.config.dockerMysql?.enabled) {
|
|
3521
|
+
this.applyDockerMysqlConfig(this.config);
|
|
3522
|
+
}
|
|
3523
|
+
// Normalize adapter config
|
|
3524
|
+
const config = this.normalizeAdapterConfig(this.config);
|
|
3525
|
+
this.sqlFuncs = SQLFuncs[config.dbtype];
|
|
3526
|
+
if (config.dockerMysql?.enabled) {
|
|
3527
|
+
// Check that the user 'iobroker' exists
|
|
3528
|
+
await this.createUserInDocker();
|
|
3529
|
+
}
|
|
3530
|
+
if (config.dbtype === 'sqlite' || this.config.host) {
|
|
3531
|
+
this.connect(() => {
|
|
3532
|
+
// read all custom settings
|
|
3533
|
+
this.getObjectView('system', 'custom', {}, (err, doc) => {
|
|
3534
|
+
let count = 0;
|
|
3535
|
+
if (doc?.rows) {
|
|
3536
|
+
for (let i = 0, l = doc.rows.length; i < l; i++) {
|
|
3537
|
+
if (doc.rows[i].value?.[this.namespace]) {
|
|
3538
|
+
let id = doc.rows[i].id;
|
|
3539
|
+
const realId = id;
|
|
3540
|
+
if (doc.rows[i].value[this.namespace] && doc.rows[i].value[this.namespace].aliasId) {
|
|
3541
|
+
this.aliasMap[id] = doc.rows[i].value[this.namespace].aliasId;
|
|
3542
|
+
this.log.debug(`Found Alias: ${id} --> ${this.aliasMap[id]}`);
|
|
3543
|
+
id = this.aliasMap[id];
|
|
3544
|
+
}
|
|
3545
|
+
let storedIndex = null;
|
|
3546
|
+
let storedType = null;
|
|
3547
|
+
if (this.sqlDPs[id] && this.sqlDPs[id].index !== undefined) {
|
|
3548
|
+
storedIndex = this.sqlDPs[id].index;
|
|
3549
|
+
}
|
|
3550
|
+
if (this.sqlDPs[id] && this.sqlDPs[id].dbType !== undefined) {
|
|
3551
|
+
storedType = this.sqlDPs[id].dbType;
|
|
3552
|
+
}
|
|
3553
|
+
// the view returns the whole custom container, the settings for this
|
|
3554
|
+
// instance are below the namespace key
|
|
3555
|
+
const config = this.normalizeCustomConfig(doc.rows[i].value[this.namespace]);
|
|
3556
|
+
this.sqlDPs[id] ||= {};
|
|
3557
|
+
const sqlDP = this.sqlDPs[id];
|
|
3558
|
+
sqlDP.config = config;
|
|
3559
|
+
if (storedIndex !== null) {
|
|
3560
|
+
sqlDP.index = storedIndex;
|
|
3561
|
+
}
|
|
3562
|
+
if (storedType !== null) {
|
|
3563
|
+
sqlDP.dbType = storedType;
|
|
3564
|
+
}
|
|
3565
|
+
if (!config || typeof config !== 'object' || config.enabled === false) {
|
|
3566
|
+
delete this.sqlDPs[id];
|
|
3567
|
+
}
|
|
3568
|
+
else {
|
|
3569
|
+
count++;
|
|
3570
|
+
this.log.info(`enabled logging of ${id}, Alias=${id !== realId}, ${count} points now activated`);
|
|
3571
|
+
// relogTimeout
|
|
3572
|
+
if (config.changesOnly && config.changesRelogInterval > 0) {
|
|
3573
|
+
if (sqlDP.relogTimeout) {
|
|
3574
|
+
clearTimeout(sqlDP.relogTimeout);
|
|
3575
|
+
}
|
|
3576
|
+
sqlDP.relogTimeout = setTimeout(_id => {
|
|
3577
|
+
this.sqlDPs[_id].relogTimeout = null;
|
|
3578
|
+
this.reLogHelper(_id);
|
|
3579
|
+
}, sqlDP.config.changesRelogInterval * 500 * (1 + Math.random()), id);
|
|
3580
|
+
}
|
|
3581
|
+
sqlDP.realId = realId;
|
|
3582
|
+
sqlDP.list ||= [];
|
|
3583
|
+
sqlDP.inFlight ||= {};
|
|
3584
|
+
// randomize lastCheck to avoid all datapoints to be checked at the same timepoint
|
|
3585
|
+
sqlDP.lastCheck = Date.now() - Math.floor(Math.random() * 21600000 /* 6 hours */);
|
|
3586
|
+
}
|
|
3587
|
+
}
|
|
3588
|
+
}
|
|
3589
|
+
}
|
|
3590
|
+
if (this.config.writeNulls) {
|
|
3591
|
+
this.writeNulls();
|
|
3592
|
+
}
|
|
3593
|
+
if (count < 200) {
|
|
3594
|
+
Object.keys(this.sqlDPs).forEach(id => this.sqlDPs[id]?.config &&
|
|
3595
|
+
!this.sqlDPs[id].realId &&
|
|
3596
|
+
this.log.warn(`No realID found for ${id}`));
|
|
3597
|
+
this.subscribeForeignStates(Object.keys(this.sqlDPs).filter(id => this.sqlDPs[id]?.config && this.sqlDPs[id].realId));
|
|
3598
|
+
}
|
|
3599
|
+
else {
|
|
3600
|
+
this.subscribeAll = true;
|
|
3601
|
+
this.subscribeForeignStates('*');
|
|
3602
|
+
}
|
|
3603
|
+
this.subscribeForeignObjects('*');
|
|
3604
|
+
this.log.debug('Initialization done');
|
|
3605
|
+
this.setConnected(true);
|
|
3606
|
+
this.processStartValues();
|
|
3607
|
+
// store all buffered data every 10 minutes to not lost the data
|
|
3608
|
+
this.bufferChecker = setInterval(() => this.storeCached(), 10 * 60000);
|
|
3609
|
+
});
|
|
3610
|
+
});
|
|
3611
|
+
}
|
|
3612
|
+
}
|
|
3613
|
+
}
|
|
3614
|
+
exports.SqlAdapter = SqlAdapter;
|
|
3615
|
+
// If started as allInOne mode => return function to create instance
|
|
3616
|
+
if (require.main !== module) {
|
|
3617
|
+
// Export the constructor in compact mode
|
|
3618
|
+
module.exports = (options) => new SqlAdapter(options);
|
|
3619
|
+
}
|
|
3620
|
+
else {
|
|
3621
|
+
// otherwise start the instance directly
|
|
3622
|
+
(() => new SqlAdapter())();
|
|
3623
|
+
}
|
|
3624
|
+
//# sourceMappingURL=main.js.map
|