-
Notifications
You must be signed in to change notification settings - Fork 24
/
main.js
3469 lines (3084 loc) · 145 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* jshint -W097 */
/* jshint strict: false */
/* jslint node: true */
'use strict';
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const adapterName = require('./package.json').name.split('.').pop();
const SQL = require('sql-client');
const commons = require('./lib/aggregate');
const fs = require('fs');
const path = require('path');
let SQLFuncs = null;
const clients = {
postgresql: {name: 'PostgreSQLClient', multiRequests: true},
mysql: {name: 'MySQL2Client', multiRequests: true},
sqlite: {name: 'SQLite3Client', multiRequests: false},
mssql: {name: 'MSSQLClient', multiRequests: true}
};
const types = {
number: 0,
string: 1,
boolean: 2,
object: 1,
};
const dbNames = [
'ts_number',
'ts_string',
'ts_bool',
];
const storageTypes = [
'Number',
'String',
'Boolean',
];
const sqlDPs = {};
const from = {};
const MAXTASKS = 100;
const tasks = [];
const tasksReadType = [];
const tasksStart = [];
const isFromRunning = {};
const aliasMap = {};
let finished = false;
let connected = null;
let multiRequests = true;
let subscribeAll = false;
let clientPool;
let reconnectTimeout = null;
let testConnectTimeout = null;
let dpOverviewTimeout = null;
let bufferChecker = null;
let activeConnections = 0;
let poolBorrowGuard = []; // required until https://github.com/intellinote/sql-client/issues/7 is fixed
const logConnectionUsage = true;
function isEqual(a, b) {
//console.log('Compare ' + JSON.stringify(a) + ' with ' + JSON.stringify(b));
// Create arrays of property names
if (a === null || a === undefined || b === null || b === undefined) {
return a === b;
}
const aProps = Object.getOwnPropertyNames(a);
const bProps = Object.getOwnPropertyNames(b);
// If number of properties is different,
// objects are not equivalent
if (aProps.length !== bProps.length) {
//console.log('num props different: ' + JSON.stringify(aProps) + ' / ' + JSON.stringify(bProps));
return false;
}
for (let i = 0; i < aProps.length; i++) {
const propName = aProps[i];
if (typeof a[propName] !== typeof b[propName]) {
//console.log('type props ' + propName + ' different');
return false;
} else
if (typeof a[propName] === 'object') {
if (!isEqual(a[propName], b[propName])) {
return false;
}
} else {
// If values of same property are not equal,
// objects are not equivalent
if (a[propName] !== b[propName]) {
//console.log('props ' + propName + ' different');
return false;
}
}
}
// If we made it this far, objects
// are considered equivalent
return true;
}
let adapter;
function startAdapter(options) {
options = options || {};
Object.assign(options, {name: adapterName});
adapter = new utils.Adapter(options);
adapter.on('objectChange', (id, obj) => {
let tmpState;
const now = Date.now();
const formerAliasId = aliasMap[id] ? aliasMap[id] : id;
if (obj && obj.common && obj.common.custom && obj.common.custom[adapter.namespace] && typeof obj.common.custom[adapter.namespace] === 'object' && obj.common.custom[adapter.namespace].enabled) {
const realId = id;
let checkForRemove = true;
if (obj.common.custom && obj.common.custom[adapter.namespace] && obj.common.custom[adapter.namespace].aliasId) {
if (obj.common.custom[adapter.namespace].aliasId !== id) {
aliasMap[id] = obj.common.custom[adapter.namespace].aliasId;
adapter.log.debug(`Registered Alias: ${id} --> ${aliasMap[id]}`);
id = aliasMap[id];
checkForRemove = false;
} else {
adapter.log.warn(`Ignoring Alias-ID because identical to ID for ${id}`);
obj.common.custom[adapter.namespace].aliasId = '';
}
}
if (checkForRemove && aliasMap[id]) {
adapter.log.debug(`Removed Alias: ${id} !-> ${aliasMap[id]}`);
delete aliasMap[id];
}
if (!(sqlDPs[formerAliasId] && sqlDPs[formerAliasId][adapter.namespace]) && !subscribeAll) {
// un-subscribe
for (const _id in sqlDPs) {
if (sqlDPs.hasOwnProperty(_id) && sqlDPs.hasOwnProperty(sqlDPs[_id].realId)) {
adapter.unsubscribeForeignStates(sqlDPs[_id].realId);
}
}
subscribeAll = true;
adapter.subscribeForeignStates('*');
}
if (sqlDPs[id] && sqlDPs[id].index === undefined) {
getId(id, sqlDPs[id].dbtype, () => reInit(id, realId, formerAliasId, obj));
} else {
reInit(id, realId, formerAliasId, obj);
}
} else {
if (aliasMap[id]) {
adapter.log.debug(`Removed Alias: ${id} !-> ${aliasMap[id]}`);
delete aliasMap[id];
}
id = formerAliasId;
if (sqlDPs[id] && sqlDPs[id][adapter.namespace]) {
adapter.log.info(`disabled logging of ${id}`);
if (sqlDPs[id].relogTimeout) {
clearTimeout(sqlDPs[id].relogTimeout);
sqlDPs[id].relogTimeout = null;
}
if (sqlDPs[id].timeout) {
clearTimeout(sqlDPs[id].timeout);
sqlDPs[id].timeout = null;
}
tmpState = Object.assign({}, sqlDPs[id].state);
const state = sqlDPs[id].state ? tmpState : null;
if (sqlDPs[id][adapter.namespace]) {
sqlDPs[id][adapter.namespace].enabled = false;
if (sqlDPs[id].skipped && !sqlDPs[id][adapter.namespace].disableSkippedValueLogging) {
pushValueIntoDB(id, sqlDPs[id].skipped, false, true);
sqlDPs[id].skipped = null;
}
if (adapter.config.writeNulls) {
const nullValue = {
val: null,
ts: now,
lc: now,
q: 0x40,
from: `system.adapter.${adapter.namespace}`
};
if (sqlDPs[id][adapter.namespace].changesOnly && state && state.val !== null) {
(function (_id, _state, _nullValue) {
_state.ts = now;
_state.from = `system.adapter.${adapter.namespace}`;
nullValue.ts += 4;
nullValue.lc += 4; // because of MS SQL
adapter.log.debug(`Write 1/2 "${_state.val}" _id: ${_id}`);
pushValueIntoDB(_id, _state, false, true, () => {
// terminate values with null to indicate adapter stop. timestamp + 1
adapter.log.debug(`Write 2/2 "null" _id: ${_id}`);
pushValueIntoDB(_id, _nullValue, () => delete sqlDPs[id]);
});
})(id, state, nullValue);
} else {
// terminate values with null to indicate adapter stop. timestamp + 1
adapter.log.debug(`Write 0 NULL _id: ${id}`);
pushValueIntoDB(id, nullValue, () => delete sqlDPs[id]);
}
} else {
storeCached(id, () => delete sqlDPs[id]);
}
} else {
delete sqlDPs[id];
}
}
}
});
adapter.on('stateChange', (id, state) => {
id = aliasMap[id] ? aliasMap[id] : id;
pushHistory(id, state);
});
adapter.on('unload', callback => finish(callback));
adapter.on('ready', () => main());
adapter.on('message', msg => processMessage(msg));
return adapter;
}
function borrowClientFromPool(callback) {
if (typeof callback !== 'function') {
return;
}
if (!clientPool) {
setConnected(false);
return callback('No database connection');
}
setConnected(true);
if (activeConnections >= adapter.config.maxConnections) {
logConnectionUsage && adapter.log.debug(`Borrow connection not possible: ${activeConnections} >= Max - Store for Later`);
poolBorrowGuard.push(callback);
return;
}
activeConnections++;
logConnectionUsage && adapter.log.debug(`Borrow connection from pool: ${activeConnections} now`);
clientPool.borrow((err, client) => {
if (!err && client) {
// make sure we always have at least one error listener to prevent crashes
if (client.on && client.listenerCount && client.listenerCount('error') === 0) {
client.on('error', err =>
adapter.log.warn(`SQL client error: ${err}`));
}
} else if (!client) {
activeConnections--;
}
callback(err, client);
});
}
function returnClientToPool(client) {
if (client) {
activeConnections--;
}
logConnectionUsage && adapter.log.debug(`Return connection to pool: ${activeConnections} now`);
if (clientPool && client) {
if (poolBorrowGuard.length) {
activeConnections++;
logConnectionUsage && adapter.log.debug(`Borrow returned connection directly: ${activeConnections} now`);
const callback = poolBorrowGuard.shift();
callback(null, client);
} else {
try {
clientPool.return(client);
} catch (err) {
// Ignore
}
}
}
}
function reInit(id, realId, formerAliasId, obj) {
// maxLength
if (!obj.common.custom[adapter.namespace].maxLength && obj.common.custom[adapter.namespace].maxLength !== '0' && obj.common.custom[adapter.namespace].maxLength !== 0) {
obj.common.custom[adapter.namespace].maxLength = parseInt(adapter.config.maxLength, 10) || 0;
} else {
obj.common.custom[adapter.namespace].maxLength = parseInt(obj.common.custom[adapter.namespace].maxLength, 10);
}
// retention
if (obj.common.custom[adapter.namespace].retention || obj.common.custom[adapter.namespace].retention === 0) {
obj.common.custom[adapter.namespace].retention = parseInt(obj.common.custom[adapter.namespace].retention, 10) || 0;
} else {
obj.common.custom[adapter.namespace].retention = adapter.config.retention;
}
if (obj.common.custom[adapter.namespace].retention === -1) {
// customRetentionDuration
if (obj.common.custom[adapter.namespace].customRetentionDuration !== undefined && obj.common.custom[adapter.namespace].customRetentionDuration !== null && obj.common.custom[adapter.namespace].customRetentionDuration !== '') {
obj.common.custom[adapter.namespace].customRetentionDuration = parseInt(obj.common.custom[adapter.namespace].customRetentionDuration, 10) || 0;
} else {
obj.common.custom[adapter.namespace].customRetentionDuration = adapter.config.customRetentionDuration;
}
obj.common.custom[adapter.namespace].retention = obj.common.custom[adapter.namespace].customRetentionDuration * 24 * 60 * 60
}
// debounceTime and debounce compatibility handling
if (!obj.common.custom[adapter.namespace].blockTime && obj.common.custom[adapter.namespace].blockTime !== '0' && obj.common.custom[adapter.namespace].blockTime !== 0) {
if (!obj.common.custom[adapter.namespace].debounce && obj.common.custom[adapter.namespace].debounce !== '0' && obj.common.custom[adapter.namespace].debounce !== 0) {
obj.common.custom[adapter.namespace].blockTime = parseInt(adapter.config.blockTime, 10) || 0;
} else {
obj.common.custom[adapter.namespace].blockTime = parseInt(obj.common.custom[adapter.namespace].debounce, 10) || 0;
}
} else {
obj.common.custom[adapter.namespace].blockTime = parseInt(obj.common.custom[adapter.namespace].blockTime, 10) || 0;
}
if (!obj.common.custom[adapter.namespace].debounceTime && obj.common.custom[adapter.namespace].debounceTime !== '0' && obj.common.custom[adapter.namespace].debounceTime !== 0) {
obj.common.custom[adapter.namespace].debounceTime = parseInt(adapter.config.debounceTime, 10) || 0;
} else {
obj.common.custom[adapter.namespace].debounceTime = parseInt(obj.common.custom[adapter.namespace].debounceTime, 10) || 0;
}
// changesOnly
obj.common.custom[adapter.namespace].changesOnly = obj.common.custom[adapter.namespace].changesOnly === 'true' || obj.common.custom[adapter.namespace].changesOnly === true;
// ignoreZero
obj.common.custom[adapter.namespace].ignoreZero = obj.common.custom[adapter.namespace].ignoreZero === 'true' || obj.common.custom[adapter.namespace].ignoreZero === true;
// round
if (obj.common.custom[adapter.namespace].round !== null && obj.common.custom[adapter.namespace].round !== undefined && obj.common.custom[adapter.namespace] !== '') {
obj.common.custom[adapter.namespace].round = parseInt(obj.common.custom[adapter.namespace], 10);
if (!isFinite(obj.common.custom[adapter.namespace].round) || obj.common.custom[adapter.namespace].round < 0) {
obj.common.custom[adapter.namespace].round = adapter.config.round;
} else {
obj.common.custom[adapter.namespace].round = Math.pow(10, parseInt(obj.common.custom[adapter.namespace].round, 10));
}
} else {
obj.common.custom[adapter.namespace].round = adapter.config.round;
}
// ignoreAboveNumber
if (obj.common.custom[adapter.namespace].ignoreAboveNumber !== undefined && obj.common.custom[adapter.namespace].ignoreAboveNumber !== null && obj.common.custom[adapter.namespace].ignoreAboveNumber !== '') {
obj.common.custom[adapter.namespace].ignoreAboveNumber = parseFloat(obj.common.custom[adapter.namespace].ignoreAboveNumber) || null;
}
// ignoreBelowNumber incl. ignoreBelowZero compatibility handling
if (obj.common.custom[adapter.namespace].ignoreBelowNumber !== undefined && obj.common.custom[adapter.namespace].ignoreBelowNumber !== null && obj.common.custom[adapter.namespace].ignoreBelowNumber !== '') {
obj.common.custom[adapter.namespace].ignoreBelowNumber = parseFloat(obj.common.custom[adapter.namespace].ignoreBelowNumber) || null;
} else if (obj.common.custom[adapter.namespace].ignoreBelowZero === 'true' || obj.common.custom[adapter.namespace].ignoreBelowZero === true) {
obj.common.custom[adapter.namespace].ignoreBelowNumber = 0;
}
// disableSkippedValueLogging
if (obj.common.custom[adapter.namespace].disableSkippedValueLogging !== undefined && obj.common.custom[adapter.namespace].disableSkippedValueLogging !== null && obj.common.custom[adapter.namespace].disableSkippedValueLogging !== '') {
obj.common.custom[adapter.namespace].disableSkippedValueLogging = obj.common.custom[adapter.namespace].disableSkippedValueLogging === 'true' || obj.common.custom[adapter.namespace].disableSkippedValueLogging === true;
} else {
obj.common.custom[adapter.namespace].disableSkippedValueLogging = adapter.config.disableSkippedValueLogging;
}
// enableDebugLogs
if (obj.common.custom[adapter.namespace].enableDebugLogs !== undefined && obj.common.custom[adapter.namespace].enableDebugLogs !== null && obj.common.custom[adapter.namespace].enableDebugLogs !== '') {
obj.common.custom[adapter.namespace].enableDebugLogs = obj.common.custom[adapter.namespace].enableDebugLogs === 'true' || obj.common.custom[adapter.namespace].enableDebugLogs === true;
} else {
obj.common.custom[adapter.namespace].enableDebugLogs = adapter.config.enableDebugLogs;
}
// changesRelogInterval
if (obj.common.custom[adapter.namespace].changesRelogInterval || obj.common.custom[adapter.namespace].changesRelogInterval === 0) {
obj.common.custom[adapter.namespace].changesRelogInterval = parseInt(obj.common.custom[adapter.namespace].changesRelogInterval, 10) || 0;
} else {
obj.common.custom[adapter.namespace].changesRelogInterval = adapter.config.changesRelogInterval;
}
// changesMinDelta
if (obj.common.custom[adapter.namespace].changesMinDelta || obj.common.custom[adapter.namespace].changesMinDelta === 0) {
obj.common.custom[adapter.namespace].changesMinDelta = parseFloat(obj.common.custom[adapter.namespace].changesMinDelta.toString().replace(/,/g, '.')) || 0;
} else {
obj.common.custom[adapter.namespace].changesMinDelta = adapter.config.changesMinDelta;
}
// storageType
if (!obj.common.custom[adapter.namespace].storageType) {
obj.common.custom[adapter.namespace].storageType = false;
}
// add one day if retention is too small
if (obj.common.custom[adapter.namespace].retention && obj.common.custom[adapter.namespace].retention <= 604800) {
obj.common.custom[adapter.namespace].retention += 86400;
}
if (sqlDPs[formerAliasId] &&
sqlDPs[formerAliasId][adapter.namespace] &&
isEqual(obj.common.custom[adapter.namespace], sqlDPs[formerAliasId][adapter.namespace])) {
return obj.common.custom[adapter.namespace].enableDebugLogs && adapter.log.debug(`Object ${id} unchanged. Ignore`);
}
// relogTimeout
if (sqlDPs[formerAliasId] && sqlDPs[formerAliasId].relogTimeout) {
clearTimeout(sqlDPs[formerAliasId].relogTimeout);
sqlDPs[formerAliasId].relogTimeout = null;
}
const writeNull = !(sqlDPs[id] && sqlDPs[id][adapter.namespace]);
const state = sqlDPs[id] ? sqlDPs[id].state : null;
const list = sqlDPs[id] ? sqlDPs[id].list : null;
const inFlight = sqlDPs[id] ? sqlDPs[id].inFlight: null;
const timeout = sqlDPs[id] ? sqlDPs[id].timeout : null;
const ts = sqlDPs[id] ? sqlDPs[id].ts : null;
const lastCheck = sqlDPs[id] ? sqlDPs[id].lastCheck : null;
sqlDPs[id] = obj.common.custom;
sqlDPs[id].state = state;
sqlDPs[id].list = list || [];
sqlDPs[id].inFlight = inFlight || {};
sqlDPs[id].timeout = timeout;
sqlDPs[id].ts = ts;
sqlDPs[id].realId = realId;
sqlDPs[id].lastCheck = lastCheck || Date.now() - Math.floor(Math.random() * 21600000/* 6 hours */); // randomize lastCheck to avoid all datapoints to be checked at same timepoint
;
// changesRelogInterval
if (sqlDPs[id][adapter.namespace].changesOnly && sqlDPs[id][adapter.namespace].changesRelogInterval > 0) {
sqlDPs[id].relogTimeout = setTimeout(reLogHelper, (sqlDPs[id][adapter.namespace].changesRelogInterval * 500 * Math.random()) + sqlDPs[id][adapter.namespace].changesRelogInterval * 500, id);
}
if (writeNull && adapter.config.writeNulls) {
writeNulls(id);
}
adapter.log.info(`enabled logging of ${id}, Alias=${id !== realId}, WriteNulls=${writeNull}`);
}
function setConnected(isConnected) {
if (connected !== isConnected) {
connected = isConnected;
adapter.setState('info.connection', connected, true);
}
}
let postgresDbCreated = false;
function connect(callback) {
if (reconnectTimeout) {
clearTimeout(reconnectTimeout);
reconnectTimeout = null;
}
if (!clientPool) {
setConnected(false);
let params = {
server: adapter.config.host, // needed for MSSQL
host: adapter.config.host, // needed for PostgreSQL , MySQL
user: adapter.config.user || '',
password: adapter.config.password || '',
max_idle: (adapter.config.dbtype === 'sqlite') ? 1 : 2
};
if (adapter.config.maxConnections) {
params.max_active = adapter.config.maxConnections + 1; // we use our own Pool limiter logic, so let library have one more to not block us too early
params.max_wait = 10000; // hard code for now
params.when_exhausted = 'block';
}
if (adapter.config.port) {
params.port = adapter.config.port;
}
if (!adapter.config.dbtype) {
return adapter.log.error('DB Type is not defined!');
} else
if (!clients[adapter.config.dbtype] || !clients[adapter.config.dbtype].name) {
return adapter.log.error(`Unknown type "${adapter.config.dbtype}"`);
} else
if (!SQL[clients[adapter.config.dbtype].name]) {
return adapter.log.error(`SQL package "${clients[adapter.config.dbtype].name}" is not installed.`);
}
if (adapter.config.dbtype === 'postgresql') {
params.database = 'postgres';
if (adapter.config.encrypt) {
params.ssl = {
rejectUnauthorized: !!adapter.config.rejectUnauthorized
};
}
} else if (adapter.config.dbtype === 'mssql') {
params.options = {
encrypt: !!adapter.config.encrypt,
};
if (adapter.config.encrypt) {
params.options.trustServerCertificate = !adapter.config.rejectUnauthorized
}
} else if (adapter.config.dbtype === 'mysql') {
if (adapter.config.encrypt) {
params.ssl = {
rejectUnauthorized: !!adapter.config.rejectUnauthorized
};
}
}
if (adapter.config.dbtype === 'sqlite') {
params = getSqlLiteDir(adapter.config.fileName);
} else
// special solution for postgres. Connect first to Db "postgres", create new DB "iobroker" and then connect to "iobroker" DB.
if (adapter.config.dbtype === 'postgresql' && !postgresDbCreated) {
// connect first to DB postgres and create iobroker DB
adapter.log.info(`Postgres connection options: ${JSON.stringify(params).replace(params.password, '****')}`);
const _client = new SQL[clients[adapter.config.dbtype].name](params);
_client.on && _client.on('error', err =>
adapter.log.warn(`SQL client error: ${err}`));
return _client.connect(err => {
if (err) {
adapter.log.error(err);
reconnectTimeout && clearTimeout(reconnectTimeout);
reconnectTimeout = setTimeout(() => connect(callback), 30000);
return;
}
if (adapter.config.doNotCreateDatabase) {
_client.disconnect();
postgresDbCreated = true;
reconnectTimeout && clearTimeout(reconnectTimeout);
reconnectTimeout = setTimeout(() => connect(callback), 100);
} else {
_client.execute(`CREATE DATABASE ${adapter.config.dbname};`, (err /* , rows, fields */) => {
_client.disconnect();
if (err && err.code !== '42P04') { // if error not about yet exists
postgresDbCreated = false;
adapter.log.error(err);
reconnectTimeout && clearTimeout(reconnectTimeout);
reconnectTimeout = setTimeout(() => connect(callback), 30000);
} else {
postgresDbCreated = true;
reconnectTimeout && clearTimeout(reconnectTimeout);
reconnectTimeout = setTimeout(() => connect(callback), 100);
}
});
}
});
}
if (adapter.config.dbtype === 'postgresql') {
params.database = adapter.config.dbname;
}
try {
if (!clients[adapter.config.dbtype].name) {
adapter.log.error(`Unknown SQL type selected: "${adapter.config.dbtype}"`);
} else if (!SQL[`${clients[adapter.config.dbtype].name}Pool`]) {
adapter.log.error(`Selected SQL DB was not installed properly: "${adapter.config.dbtype}". SQLite requires build tools on system. See README.md`);
} else {
clientPool = new SQL[`${clients[adapter.config.dbtype].name}Pool`](params);
return clientPool.open(err => {
activeConnections = 0;
if (err) {
clientPool = null;
setConnected(false);
adapter.log.error(err);
reconnectTimeout && clearTimeout(reconnectTimeout);
reconnectTimeout = setTimeout(() => connect(callback), 30000);
} else {
reconnectTimeout && clearTimeout(reconnectTimeout);
reconnectTimeout = setImmediate(() => connect(callback));
}
});
}
} catch (ex) {
if (ex.toString() === 'TypeError: undefined is not a function') {
adapter.log.error(`Node.js DB driver for "${adapter.config.dbtype}" could not be installed.`);
} else {
adapter.log.error(ex.toString());
adapter.log.error(ex.stack);
}
clientPool = null;
activeConnections = 0;
setConnected(false);
reconnectTimeout && clearTimeout(reconnectTimeout);
reconnectTimeout = setTimeout(() => connect(callback), 30000);
return;
}
}
allScripts(SQLFuncs.init(adapter.config.dbname, adapter.config.doNotCreateDatabase), err => {
if (err) {
//adapter.log.error(err);
reconnectTimeout && clearTimeout(reconnectTimeout);
reconnectTimeout = setTimeout(() => connect(callback), 30000);
} else {
adapter.log.info(`Connected to ${adapter.config.dbtype}`);
// read all DB IDs and all FROM ids
getAllIds(() =>
getAllFroms(callback));
}
});
}
// Find sqlite data directory
function getSqlLiteDir(fileName) {
fileName = fileName || 'sqlite.db';
fileName = fileName.replace(/\\/g, '/');
if (fileName[0] === '/' || fileName.match(/^\w:\//)) {
return fileName;
} else {
// normally /opt/iobroker/node_modules/iobroker.js-controller
// but can be /example/ioBroker.js-controller
let config = path.join(utils.getAbsoluteDefaultDataDir(), 'sqlite');
// create sqlite directory
if (!fs.existsSync(config)) {
fs.mkdirSync(config);
}
return path.normalize(path.join(config, fileName));
}
}
function testConnection(msg) {
if (!msg.message.config) {
return msg.callback && adapter.sendTo(msg.from, msg.command, {error: 'invalid config'}, msg.callback);
}
msg.message.config.port = parseInt(msg.message.config.port, 10) || 0;
let params = {
server: msg.message.config.host,
host: msg.message.config.host,
user: msg.message.config.user,
password: msg.message.config.password
};
if (msg.message.config.port) {
params.port = msg.message.config.port;
}
if (msg.message.config.dbtype === 'postgresql' && !SQL.PostgreSQLClient) {
const postgres = require('./lib/postgresql-client');
Object.keys(postgres)
.filter(attr => !SQL[attr])
.forEach(attr => SQL[attr] = postgres[attr]);
} else if (msg.message.config.dbtype === 'mssql' && !SQL.MSSQLClient) {
const mssql = require('./lib/mssql-client');
Object.keys(mssql)
.filter(attr => !SQL[attr])
.forEach(attr => SQL[attr] = mssql[attr]);
} else if (msg.message.config.dbtype === 'mysql' && !SQL.MySQL2Client) {
const mysql = require('./lib/mysql-client');
Object.keys(mysql)
.filter(attr => !SQL[attr])
.forEach(attr => SQL[attr] = mysql[attr]);
}
if (msg.message.config.dbtype === 'postgresql') {
params.database = 'postgres';
} else if (msg.message.config.dbtype === 'sqlite') {
params = getSqlLiteDir(msg.message.config.fileName);
}
if (msg.message.config.dbtype === 'postgresql') {
if (msg.message.config.encrypt) {
params.ssl = {
rejectUnauthorized: !!msg.message.config.rejectUnauthorized
};
}
} else if (msg.message.config.dbtype === 'mssql') {
params.options = {
encrypt: !!msg.message.config.encrypt,
};
if (msg.message.config.encrypt) {
params.options. trustServerCertificate= !msg.message.config.rejectUnauthorized
}
} else if (msg.message.config.dbtype === 'mysql') {
if (msg.message.config.encrypt) {
params.ssl = {
rejectUnauthorized: !!msg.message.config.rejectUnauthorized
};
}
}
try {
const client = new SQL[clients[msg.message.config.dbtype].name](params);
client.on && client.on('error', err =>
adapter.log.warn(`SQL client error: ${err}`));
testConnectTimeout = setTimeout(() => {
testConnectTimeout = null;
adapter.sendTo(msg.from, msg.command, {error: 'connect timeout'}, msg.callback);
}, 5000);
client.connect(err => {
if (err) {
if (testConnectTimeout) {
clearTimeout(testConnectTimeout);
testConnectTimeout = null;
}
return adapter.sendTo(msg.from, msg.command, {error: err.toString()}, msg.callback);
}
client.execute('SELECT 2 + 3 AS x', (err /* , rows, fields */) => {
client.disconnect();
if (testConnectTimeout) {
clearTimeout(testConnectTimeout);
testConnectTimeout = null;
return adapter.sendTo(msg.from, msg.command, {error: err ? err.toString() : null}, msg.callback);
}
});
});
} catch (ex) {
if (testConnectTimeout) {
clearTimeout(testConnectTimeout);
testConnectTimeout = null;
}
if (ex.toString() === 'TypeError: undefined is not a function') {
return adapter.sendTo(msg.from, msg.command, {error: 'Node.js DB driver could not be installed.'}, msg.callback);
} else {
return adapter.sendTo(msg.from, msg.command, {error: ex.toString()}, msg.callback);
}
}
}
function destroyDB(msg) {
try {
allScripts(SQLFuncs.destroy(adapter.config.dbname), err => {
if (err) {
adapter.log.error(err);
adapter.sendTo(msg.from, msg.command, {error: err.toString()}, msg.callback);
} else {
adapter.sendTo(msg.from, msg.command, {error: null, result: 'deleted'}, msg.callback);
// restart adapter
setTimeout(() =>
adapter.getForeignObject(`system.adapter.${adapter.namespace}`, (err, obj) => {
if (!err) {
adapter.setForeignObject(obj._id, obj);
} else {
adapter.log.error(`Cannot read object "system.adapter.${adapter.namespace}": ${err}`);
adapter.stop();
}
}), 2000);
}
});
} catch (ex) {
return adapter.sendTo(msg.from, msg.command, {error: ex.toString()}, msg.callback);
}
}
function _userQuery(msg, callback) {
try {
if (typeof msg.message !== 'string' || !msg.message.length) {
throw new Error('No query provided');
}
adapter.log.debug(msg.message);
borrowClientFromPool((err, client) => {
if (err) {
adapter.sendTo(msg.from, msg.command, {error: err.toString()}, msg.callback);
returnClientToPool(client);
callback && callback();
} else {
client.execute(msg.message, (err, rows /* , fields */) => {
if (rows && rows.rows) rows = rows.rows;
returnClientToPool(client);
//convert ts for postgresql and ms sqlserver
if (!err && rows && rows[0] && typeof rows[0].ts === 'string') {
for (let i = 0; i < rows.length; i++) {
rows[i].ts = parseInt(rows[i].ts, 10);
}
}
adapter.sendTo(msg.from, msg.command, {error: err ? err.toString() : null, result: rows}, msg.callback);
callback && callback();
});
}
});
} catch (err) {
adapter.sendTo(msg.from, msg.command, {error: err.toString()}, msg.callback);
callback && callback();
}
}
// execute custom query
function query(msg) {
if (!multiRequests) {
if (tasks.length > MAXTASKS) {
const error = `Cannot queue new requests, because more than ${MAXTASKS}`;
adapter.log.error(error);
adapter.sendTo(msg.from, msg.command, {error}, msg.callback);
} else {
tasks.push({operation: 'userQuery', msg});
tasks.length === 1 && processTasks();
}
} else {
_userQuery(msg);
}
}
// one script
function oneScript(script, cb) {
try {
borrowClientFromPool((err, client) => {
if (err || !client) {
clientPool && clientPool.close();
activeConnections = 0;
clientPool = null;
setConnected(false);
adapter.log.error(err);
return cb && cb(err);
}
adapter.log.debug(script);
client.execute(script, (err /* , rows, fields */) => {
adapter.log.debug(`Response: ${JSON.stringify(err)}`);
if (err) {
// Database 'iobroker' already exists. Choose a different database name.
if (err.number === 1801 ||
//There is already an object named 'sources' in the database.
err.number === 2714) {
// do nothing
err = null;
} else
if (err.message && err.message.match(/^SQLITE_ERROR: table [\w_]+ already exists$/)) {
// do nothing
err = null;
} else
if (err.errno == 1007 || err.errno == 1050) { // if database exists or table exists
// do nothing
err = null;
} else
if (err.code === '42P04') {// if database exists or table exists
// do nothing
err = null;
}
else if (err.code === '42P07') {
const match = script.match(/CREATE\s+TABLE\s+(\w*)\s+\(/);
if (match) {
adapter.log.debug(`OK. Table "${match[1]}" yet exists`);
err = null;
} else {
adapter.log.error(script);
adapter.log.error(err);
}
} else if (script.startsWith('CREATE INDEX')) {
adapter.log.info('Ignore Error on Create index. You might want to create the index yourself!');
adapter.log.info(script);
adapter.log.info(`${err.code}: ${err}`);
err = null;
} else {
adapter.log.error(script);
adapter.log.error(err);
}
}
returnClientToPool(client);
cb && cb(err);
});
});
} catch (ex) {
adapter.log.error(ex);
cb && cb(ex);
}
}
// all scripts
function allScripts(scripts, index, cb) {
if (typeof index === 'function') {
cb = index;
index = 0;
}
index = index || 0;
if (scripts && index < scripts.length) {
oneScript(scripts[index], err => {
if (err) {
cb && cb(err);
} else {
allScripts(scripts, index + 1, cb);
}
});
} else {
cb && cb();
}
}
function finish(callback) {
function allFinished() {
if (clientPool) {
clientPool.close();
activeConnections = 0;
clientPool = null;
setConnected(false);
}
if (typeof finished === 'object') {
setTimeout(cb => {
for (let f = 0; f < cb.length; f++) {
typeof cb[f] === 'function' && cb[f]();
}
}, 500, finished);
finished = true;
}
}
function finishId(id) {
if (!sqlDPs[id]) {
return;
}
if (sqlDPs[id].relogTimeout) {
clearTimeout(sqlDPs[id].relogTimeout);
sqlDPs[id].relogTimeout = null;
}
if (sqlDPs[id].timeout) {
clearTimeout(sqlDPs[id].timeout);
sqlDPs[id].timeout = null;
}
let tmpState = Object.assign({}, sqlDPs[id].state);
const state = sqlDPs[id].state ? tmpState : null;
if (sqlDPs[id].skipped && !(sqlDPs[id][adapter.namespace] && sqlDPs[id][adapter.namespace].disableSkippedValueLogging)) {
count++;
pushValueIntoDB(id, sqlDPs[id].skipped, false, true,() => {
if (!--count) {
pushValuesIntoDB(id, sqlDPs[id].list, () => {
allFinished();
});
}
});
sqlDPs[id].skipped = null;
}
const nullValue = {val: null, ts: now, lc: now, q: 0x40, from: `system.adapter.${adapter.namespace}`};
if (sqlDPs[id][adapter.namespace] && adapter.config.writeNulls) {
if (sqlDPs[id][adapter.namespace].changesOnly && state && state.val !== null) {
count++;
(function (_id, _state, _nullValue) {
_state.ts = now;
_state.from = `system.adapter.${adapter.namespace}`;
nullValue.ts += 4;
nullValue.lc += 4; // because of MS SQL
adapter.log.debug(`Write 1/2 "${_state.val}" _id: ${_id}`);
pushValueIntoDB(_id, _state, false, true,() => {
// terminate values with null to indicate adapter stop. timestamp + 1
adapter.log.debug(`Write 2/2 "null" _id: ${_id}`);
pushValueIntoDB(_id, _nullValue, false, true,() => {
if (!--count) {
pushValuesIntoDB(id, sqlDPs[id].list, () => {
allFinished();
});
}
});
});
})(id, state, nullValue);
} else {
// terminate values with null to indicate adapter stop. timestamp + 1
count++;
adapter.log.debug(`Write 0 NULL _id: ${id}`);
pushValueIntoDB(id, nullValue, false, true,() => {
if (!--count) {
pushValuesIntoDB(id, sqlDPs[id].list, () => {
allFinished();
});
}
});
}
}
}
if (!subscribeAll) {
for (const _id in sqlDPs) {
if (sqlDPs.hasOwnProperty(_id) && sqlDPs.hasOwnProperty(sqlDPs[_id].realId)) {
adapter.unsubscribeForeignStates(sqlDPs[_id].realId);
}
}
} else {
subscribeAll = false;
adapter.unsubscribeForeignStates('*');
}
if (reconnectTimeout) {
clearTimeout(reconnectTimeout);
reconnectTimeout = null;
}
if (testConnectTimeout) {
clearTimeout(testConnectTimeout);
testConnectTimeout = null;
}
if (dpOverviewTimeout) {
clearTimeout(dpOverviewTimeout);
dpOverviewTimeout = null;
}
if (bufferChecker) {
clearInterval(bufferChecker);
bufferChecker = null;
}