forked from project-chip/zap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery-loader.js
2129 lines (2054 loc) · 56.9 KB
/
query-loader.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
/**
*
* Copyright (c) 2020 Silicon Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This module provides queries for ZCL loading
*
* @module DB API: zcl loading queries
*/
const env = require('../util/env')
const dbApi = require('./db-api.js')
const queryNotification = require('../db/query-package-notification')
const dbEnum = require('../../src-shared/db-enum.js')
// Some loading queries that are reused few times.
const INSERT_CLUSTER_QUERY = `
INSERT INTO CLUSTER (
PACKAGE_REF,
CODE,
MANUFACTURER_CODE,
NAME,
DESCRIPTION,
DEFINE,
DOMAIN_NAME,
IS_SINGLETON,
REVISION,
INTRODUCED_IN_REF,
REMOVED_IN_REF,
API_MATURITY
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?,
(SELECT SPEC_ID FROM SPEC WHERE CODE = ? AND PACKAGE_REF = ?),
(SELECT SPEC_ID FROM SPEC WHERE CODE = ? AND PACKAGE_REF = ?),
?
)
`
const INSERT_EVENT_QUERY = `
INSERT INTO EVENT (
CLUSTER_REF,
PACKAGE_REF,
CODE,
MANUFACTURER_CODE,
NAME,
DESCRIPTION,
SIDE,
IS_OPTIONAL,
IS_FABRIC_SENSITIVE,
PRIORITY,
INTRODUCED_IN_REF,
REMOVED_IN_REF
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
(SELECT SPEC_ID FROM SPEC WHERE CODE = ? AND PACKAGE_REF = ?),
(SELECT SPEC_ID FROM SPEC WHERE CODE = ? AND PACKAGE_REF = ?)
)
`
const INSERT_EVENT_FIELD_QUERY = `
INSERT INTO EVENT_FIELD (
EVENT_REF,
FIELD_IDENTIFIER,
NAME,
TYPE,
IS_ARRAY,
IS_NULLABLE,
IS_OPTIONAL,
INTRODUCED_IN_REF,
REMOVED_IN_REF
) VALUES (
?, ?, ?, ?, ?, ?, ?,
(SELECT SPEC_ID FROM SPEC WHERE CODE = ? AND PACKAGE_REF = ?),
(SELECT SPEC_ID FROM SPEC WHERE CODE = ? AND PACKAGE_REF = ?)
)
`
const INSERT_COMMAND_QUERY = `
INSERT INTO COMMAND (
CLUSTER_REF,
PACKAGE_REF,
CODE,
NAME,
DESCRIPTION,
SOURCE,
IS_OPTIONAL,
MUST_USE_TIMED_INVOKE,
IS_FABRIC_SCOPED,
RESPONSE_NAME,
MANUFACTURER_CODE,
INTRODUCED_IN_REF,
REMOVED_IN_REF,
IS_DEFAULT_RESPONSE_ENABLED
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
(SELECT SPEC_ID FROM SPEC WHERE CODE = ? AND PACKAGE_REF = ?),
(SELECT SPEC_ID FROM SPEC WHERE CODE = ? AND PACKAGE_REF = ?),
?
)`
const INSERT_COMMAND_ARG_QUERY = `
INSERT INTO COMMAND_ARG (
COMMAND_REF,
NAME,
TYPE,
MIN,
MAX,
MIN_LENGTH,
MAX_LENGTH,
IS_ARRAY,
PRESENT_IF,
IS_NULLABLE,
IS_OPTIONAL,
COUNT_ARG,
FIELD_IDENTIFIER,
INTRODUCED_IN_REF,
REMOVED_IN_REF
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
(SELECT SPEC_ID FROM SPEC WHERE CODE = ? AND PACKAGE_REF = ?),
(SELECT SPEC_ID FROM SPEC WHERE CODE = ? AND PACKAGE_REF = ?)
)`
// Replace here is used to prevent custom cluster extensions from being re-loaded again.
// Attribute table needs to be unique based on:
// UNIQUE("CLUSTER_REF", "PACKAGE_REF", "CODE", "MANUFACTURER_CODE")
const INSERT_ATTRIBUTE_QUERY = `
INSERT OR REPLACE INTO ATTRIBUTE (
CLUSTER_REF,
PACKAGE_REF,
CODE,
NAME,
TYPE,
SIDE,
DEFINE,
MIN,
MAX,
MIN_LENGTH,
MAX_LENGTH,
REPORT_MIN_INTERVAL,
REPORT_MAX_INTERVAL,
REPORTABLE_CHANGE,
REPORTABLE_CHANGE_LENGTH,
IS_WRITABLE,
DEFAULT_VALUE,
IS_OPTIONAL,
REPORTING_POLICY,
STORAGE_POLICY,
IS_NULLABLE,
IS_SCENE_REQUIRED,
ARRAY_TYPE,
MUST_USE_TIMED_WRITE,
MANUFACTURER_CODE,
INTRODUCED_IN_REF,
REMOVED_IN_REF,
API_MATURITY,
IS_CHANGE_COMITTED,
PERSISTENCE
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
(SELECT SPEC_ID FROM SPEC WHERE CODE = ? AND PACKAGE_REF = ?),
(SELECT SPEC_ID FROM SPEC WHERE CODE = ? AND PACKAGE_REF = ?),
?,
?,
?
)`
const SELECT_CLUSTER_SPECIFIC_DATA_TYPE = `
SELECT
DATA_TYPE.DATA_TYPE_ID
FROM
DATA_TYPE
INNER JOIN
DATA_TYPE_CLUSTER
ON
DATA_TYPE.DATA_TYPE_ID = DATA_TYPE_CLUSTER.DATA_TYPE_REF
WHERE
DATA_TYPE.NAME = ?
AND
DATA_TYPE.DISCRIMINATOR_REF = ?
AND
DATA_TYPE_CLUSTER.CLUSTER_CODE = ?`
// Data types which are not associated to any cluster specifically
const SELECT_GENERIC_DATA_TYPE = `
SELECT
DATA_TYPE.DATA_TYPE_ID
FROM
DATA_TYPE
WHERE
DATA_TYPE.NAME = ?
AND
DATA_TYPE.DISCRIMINATOR_REF = ?`
function attributeMap(clusterId, packageId, attributes) {
return attributes.map((attribute) => [
clusterId,
packageId,
attribute.code,
attribute.name,
attribute.type,
attribute.side,
attribute.define,
attribute.min,
attribute.max,
attribute.minLength,
attribute.maxLength,
attribute.reportMinInterval,
attribute.reportMaxInterval,
attribute.reportableChange,
attribute.reportableChangeLength,
attribute.isWritable,
attribute.defaultValue,
dbApi.toDbBool(attribute.isOptional),
attribute.reportingPolicy,
attribute.storagePolicy,
dbApi.toDbBool(attribute.isNullable),
dbApi.toDbBool(attribute.isSceneRequired),
attribute.entryType,
dbApi.toDbBool(attribute.mustUseTimedWrite),
attribute.manufacturerCode,
attribute.introducedIn,
packageId,
attribute.removedIn,
packageId,
attribute.apiMaturity,
])
}
function eventMap(clusterId, packageId, events) {
return events.map((event) => [
clusterId,
packageId,
event.code,
event.manufacturerCode,
event.name,
event.description,
event.side,
dbApi.toDbBool(event.isOptional),
dbApi.toDbBool(event.isFabricSensitive),
event.priority,
event.introducedIn,
packageId,
event.removedIn,
packageId,
])
}
function commandMap(clusterId, packageId, commands) {
return commands.map((command) => [
clusterId,
packageId,
command.code,
command.name,
command.description,
command.source,
dbApi.toDbBool(command.isOptional),
dbApi.toDbBool(command.mustUseTimedInvoke),
dbApi.toDbBool(command.isFabricScoped),
command.responseName,
command.manufacturerCode,
command.introducedIn,
packageId,
command.removedIn,
packageId,
dbApi.toDbBool(command.isDefaultResponseEnabled),
])
}
function fieldMap(eventId, packageId, fields) {
return fields.map((field) => [
eventId,
field.fieldIdentifier,
field.name,
field.type,
dbApi.toDbBool(field.isArray),
dbApi.toDbBool(field.isNullable),
dbApi.toDbBool(field.isOptional),
field.introducedIn,
packageId,
field.removedIn,
packageId,
])
}
function argMap(cmdId, packageId, args) {
return args.map((arg) => [
cmdId,
arg.name,
arg.type,
arg.min,
arg.max,
arg.minLength,
arg.maxLength,
dbApi.toDbBool(arg.isArray),
arg.presentIf,
dbApi.toDbBool(arg.isNullable),
dbApi.toDbBool(arg.isOptional),
arg.countArg,
arg.fieldIdentifier,
arg.introducedIn,
packageId,
arg.removedIn,
packageId,
])
}
// access data is array of objects, containing id/op/role/modifier
async function insertAttributeAccessData(db, packageId, accessData) {
let rowIds = await createAccessRows(db, packageId, accessData)
let insertData = []
for (let i = 0; i < rowIds.length; i++) {
insertData.push([accessData[i].id, rowIds[i]])
}
return dbApi.dbMultiInsert(
db,
`INSERT INTO ATTRIBUTE_ACCESS (ATTRIBUTE_REF, ACCESS_REF) VALUES (?,?)`,
insertData,
)
}
// access data is array of objects, containing id/op/role/modifier
async function insertCommandAccessData(db, packageId, accessData) {
let rowIds = await createAccessRows(db, packageId, accessData)
let insertData = []
for (let i = 0; i < rowIds.length; i++) {
insertData.push([accessData[i].id, rowIds[i]])
}
return dbApi.dbMultiInsert(
db,
`INSERT INTO COMMAND_ACCESS (COMMAND_REF, ACCESS_REF) VALUES (?,?)`,
insertData,
)
}
// access data is array of objects, containing id/op/role/modifier
async function insertEventAccessData(db, packageId, accessData) {
let rowIds = await createAccessRows(db, packageId, accessData)
let insertData = []
for (let i = 0; i < rowIds.length; i++) {
insertData.push([accessData[i].id, rowIds[i]])
}
return dbApi.dbMultiInsert(
db,
`INSERT INTO EVENT_ACCESS (EVENT_REF, ACCESS_REF) VALUES (?,?)`,
insertData,
)
}
async function insertAttributes(db, packageId, attributes) {
let data = attributes.data
let access = attributes.access
if (data == null || data.length == 0) return
let attributeIds = await dbApi.dbMultiInsert(db, INSERT_ATTRIBUTE_QUERY, data)
let accessData = []
for (let i = 0; i < attributeIds.length; i++) {
let atId = attributeIds[i]
let atAccess = access[i] // Array of accesses
if (atAccess != null && atAccess.length > 0) {
for (let ac of atAccess) {
accessData.push({
id: atId,
op: ac.op,
role: ac.role,
modifier: ac.modifier,
})
}
}
}
if (accessData.length > 0) {
await insertAttributeAccessData(db, packageId, accessData)
}
}
/**
* Load the attribute mapping table with associated attributes
* @param {*} db
* @param {*} data
* @returns attribute mapping ids of the associated attributes
*/
async function insertAttributeMappings(db, data) {
let selectAttributeIdQuery = `
(SELECT
ATTRIBUTE_ID
FROM
ATTRIBUTE
INNER JOIN
CLUSTER
ON
ATTRIBUTE.CLUSTER_REF = CLUSTER.CLUSTER_ID
WHERE
ATTRIBUTE.CODE = ?
AND
(ATTRIBUTE.MANUFACTURER_CODE = ? OR ATTRIBUTE.MANUFACTURER_CODE IS NULL)
AND
CLUSTER.CODE = ?
AND
(CLUSTER.MANUFACTURER_CODE = ? OR CLUSTER.MANUFACTURER_CODE IS NULL)
AND
ATTRIBUTE.PACKAGE_REF = ?
AND
CLUSTER.PACKAGE_REF = ?)
`
// Using insert or replace to cover the use case for updated attribute mappings in a file
return dbApi.dbMultiInsert(
db,
`
INSERT OR REPLACE INTO
ATTRIBUTE_MAPPING (ATTRIBUTE_LEFT_REF, ATTRIBUTE_RIGHT_REF)
VALUES
(${selectAttributeIdQuery}, ${selectAttributeIdQuery})
`,
data,
)
}
async function insertEvents(db, packageId, events) {
let data = events.data
let fieldData = events.fields
let access = events.access
if (data == null || data.length == 0) return
let eventIds = await dbApi.dbMultiInsert(db, INSERT_EVENT_QUERY, data)
let fieldsToLoad = []
for (let i = 0; i < eventIds.length; i++) {
let lastEventId = eventIds[i]
let fields = fieldData[i]
if (fields != undefined && fields != null) {
fieldsToLoad.push(...fieldMap(lastEventId, packageId, fields))
}
}
await dbApi.dbMultiInsert(db, INSERT_EVENT_FIELD_QUERY, fieldsToLoad)
let accessData = []
for (let i = 0; i < eventIds.length; i++) {
let evId = eventIds[i]
let evAccess = access[i] // Array of accesses
if (evAccess != null && evAccess.length > 0) {
for (let ac of evAccess) {
accessData.push({
id: evId,
op: ac.op,
role: ac.role,
modifier: ac.modifier,
})
}
}
}
if (accessData.length > 0) {
await insertEventAccessData(db, packageId, accessData)
}
}
async function insertCommands(db, packageId, commands) {
let data = commands.data
let argData = commands.args
let access = commands.access
if (data == null || data.length == 0) return
let commandIds = await dbApi.dbMultiInsert(db, INSERT_COMMAND_QUERY, data)
let argsToLoad = []
for (let i = 0; i < commandIds.length; i++) {
let lastCmdId = commandIds[i]
let args = argData[i]
if (args != undefined && args != null) {
argsToLoad.push(...argMap(lastCmdId, packageId, args))
}
}
await dbApi.dbMultiInsert(db, INSERT_COMMAND_ARG_QUERY, argsToLoad)
let accessData = []
for (let i = 0; i < commandIds.length; i++) {
let cmdId = commandIds[i]
let cmdAccess = access[i] // Array of accesses
if (cmdAccess != null && cmdAccess.length > 0) {
for (let ac of cmdAccess) {
accessData.push({
id: cmdId,
op: ac.op,
role: ac.role,
modifier: ac.modifier,
})
}
}
}
if (accessData.length > 0) {
await insertCommandAccessData(db, packageId, accessData)
}
}
/**
* Inserts globals into the database.
*
* @export
* @param {*} db
* @param {*} packageId
* @param {*} data
* @returns Promise of globals insertion.
*/
async function insertGlobals(db, packageId, data) {
env.logDebug(`Insert globals: ${data.length}`)
let commands = {
data: [],
args: [],
access: [],
}
let attributes = {
data: [],
access: [],
}
let i
for (i = 0; i < data.length; i++) {
if ('commands' in data[i]) {
let cmds = data[i].commands
commands.data.push(...commandMap(null, packageId, cmds))
commands.args.push(...cmds.map((command) => command.args))
}
if ('attributes' in data[i]) {
let atts = data[i].attributes
attributes.data.push(...attributeMap(null, packageId, atts))
}
}
let pCommand = insertCommands(db, packageId, commands)
let pAttribute = insertAttributes(db, packageId, attributes)
return Promise.all([pCommand, pAttribute])
}
/**
* Inserts cluster extensions into the database.
*
* @export
* @param {*} db
* @param {*} packageId
* @param {*} data
* @returns Promise of cluster extension insertion.
*/
async function insertClusterExtensions(db, packageId, knownPackages, data) {
return dbApi
.dbMultiSelect(
db,
`SELECT CLUSTER_ID FROM CLUSTER WHERE PACKAGE_REF IN (${dbApi.toInClause(
knownPackages,
)}) AND CODE = ?`,
data.map((cluster) => [cluster.code]),
)
.then((rows) => {
let commands = {
data: [],
args: [],
access: [],
}
let events = {
data: [],
fields: [],
access: [],
}
let attributes = {
data: [],
access: [],
}
let i, lastId
for (i = 0; i < rows.length; i++) {
let row = rows[i]
if (row != null) {
lastId = row.CLUSTER_ID
// NOTE: This code must stay in sync with insertClusters
if ('commands' in data[i]) {
let cmds = data[i].commands
commands.data.push(...commandMap(lastId, packageId, cmds))
commands.args.push(...cmds.map((command) => command.args))
commands.access.push(...cmds.map((command) => command.access))
}
if ('attributes' in data[i]) {
let atts = data[i].attributes
attributes.data.push(...attributeMap(lastId, packageId, atts))
attributes.access.push(...atts.map((at) => at.access))
}
if ('events' in data[i]) {
let evs = data[i].events
events.data.push(...eventMap(lastId, packageId, evs))
events.fields.push(...evs.map((event) => event.fields))
events.access.push(...evs.map((event) => event.access))
}
} else {
// DANGER: We got here because we are adding a cluster extension for a
// cluster which is not defined. For eg:
// <clusterExtension code="0x0000">
// <attribute side="server" code="0x4000" define="SW_BUILD_ID"
// type="CHAR_STRING" length="16" writable="false"
// default="" optional="true"
// introducedIn="zll-1.0-11-0037-10">sw build id</attribute>
// </clusterExtension>
// If a cluster with code 0x0000 does not exist then we run into this
// issue.
let message = `Attempting to insert cluster extension for a cluster which does not
exist. Check clusterExtension meta data in xml file.
Cluster Code: ${data[i].code}`
env.logWarning(message)
queryNotification.setNotification(
db,
'WARNING',
message,
packageId,
2,
)
}
}
let pCommand = insertCommands(db, packageId, commands)
let pAttribute = insertAttributes(db, packageId, attributes)
let pEvent = insertEvents(db, packageId, events)
return Promise.all([pCommand, pAttribute, pEvent])
})
}
/**
* Inserts clusters into the database.
*
* @export
* @param {*} db
* @param {*} packageId
* @param {*} data an array of objects that must contain: code, name, description, define. It also contains commands: and attributes:
* @returns Promise of cluster insertion.
*/
async function insertClusters(db, packageId, data) {
// If data is extension, we only have code there and we need to simply add commands and clusters.
// But if it's not an extension, we need to insert the cluster and then run with
return dbApi
.dbMultiInsert(
db,
INSERT_CLUSTER_QUERY,
data.map((cluster) => {
return [
packageId,
cluster.code,
cluster.manufacturerCode,
cluster.name,
cluster.description,
cluster.define,
cluster.domain,
cluster.isSingleton,
cluster.revision,
cluster.introducedIn,
packageId,
cluster.removedIn,
packageId,
cluster.apiMaturity,
]
}),
)
.then((lastIdsArray) => {
let commands = {
data: [],
args: [],
access: [],
}
let events = {
data: [],
fields: [],
access: [],
}
let attributes = {
data: [],
access: [],
}
let pTags = null
let pFeatures = null
let i
for (i = 0; i < lastIdsArray.length; i++) {
let lastId = lastIdsArray[i]
// NOTE: This code must stay in sync with insertClusterExtensionsx
if ('commands' in data[i]) {
let cmds = data[i].commands
commands.data.push(...commandMap(lastId, packageId, cmds))
commands.args.push(...cmds.map((command) => command.args))
commands.access.push(...cmds.map((command) => command.access))
}
if ('attributes' in data[i]) {
let atts = data[i].attributes
attributes.data.push(...attributeMap(lastId, packageId, atts))
attributes.access.push(...atts.map((at) => at.access))
}
if ('events' in data[i]) {
let evs = data[i].events
events.data.push(...eventMap(lastId, packageId, evs))
events.fields.push(...evs.map((event) => event.fields))
events.access.push(...evs.map((event) => event.access))
}
if ('tags' in data[i]) {
pTags = insertTags(db, packageId, data[i].tags, lastId)
}
if ('features' in data[i]) {
pFeatures = insertFeatures(db, packageId, data[i].features, lastId)
}
}
let pCommand = insertCommands(db, packageId, commands)
let pAttribute = insertAttributes(db, packageId, attributes)
let pEvent = insertEvents(db, packageId, events)
let pArray = [pCommand, pAttribute, pEvent]
if (pTags != null) pArray.push(pTags)
if (pFeatures != null) pArray.push(pFeatures)
return Promise.all(pArray)
})
}
/**
* Inserts features into the database.
* @param {*} db
* @param {*} packageId
* @param {*} data
* @returns A promise that resolves with array of rowids.
*/
async function insertFeatures(db, packageId, data, clusterId) {
return dbApi.dbMultiInsert(
db,
'INSERT INTO FEATURE (PACKAGE_REF, NAME, CODE, BIT, DEFAULT_VALUE, DESCRIPTION, CONFORMANCE, CLUSTER_REF) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
data.map((feature) => [
packageId,
feature.name,
feature.code,
feature.bit,
feature.defaultValue,
feature.description,
feature.conformance,
clusterId,
]),
)
}
/**
* Inserts tags into the database.
* data is an array of objects, containing 'name' and 'description'
* @param {*} db
* @param {*} packageId
* @param {*} data
* @returns A promise that resolves with array of rowids.
*/
async function insertTags(db, packageId, data, clusterRef) {
return dbApi.dbMultiInsert(
db,
'INSERT INTO TAG (PACKAGE_REF, CLUSTER_REF, NAME, DESCRIPTION) VALUES (?, ?, ?, ?)',
data.map((tag) => [packageId, clusterRef, tag.name, tag.description]),
)
}
/**
*
* Inserts domains into the database.
* data is an array of objects that must contain: name
*
* @export
* @param {*} db
* @param {*} packageId
* @param {*} data Data containing name and specRef
* @returns A promise that resolves with an array of rowids of all inserted domains.
*/
async function insertDomains(db, packageId, data) {
return dbApi.dbMultiInsert(
db,
'INSERT OR IGNORE INTO DOMAIN (PACKAGE_REF, NAME, LATEST_SPEC_REF) VALUES (?, ?, (SELECT SPEC_ID FROM SPEC WHERE PACKAGE_REF = ? AND CODE = ? ))',
data.map((domain) => [packageId, domain.name, packageId, domain.specCode]),
)
}
/**
* Inserts a spec into the database.
*
* @param {*} db
* @param {*} packageId
* @param {*} data Data contining specCode and specDescription.
* @returns Promise of insertion.
*/
async function insertSpecs(db, packageId, data) {
let olders = []
data.forEach((domain) => {
if ('older' in domain) {
domain.older.forEach((older) => olders.push(older))
}
})
if (olders.length > 0) {
await dbApi.dbMultiInsert(
db,
'INSERT OR IGNORE INTO SPEC (PACKAGE_REF, CODE, DESCRIPTION, CERTIFIABLE) VALUES (?, ?, ?, ?)',
olders.map((older) => [
packageId,
older.specCode,
older.specDescription,
older.specCertifiable ? 1 : 0,
]),
)
}
return dbApi.dbMultiInsert(
db,
'INSERT OR IGNORE INTO SPEC (PACKAGE_REF, CODE, DESCRIPTION, CERTIFIABLE) VALUES (?, ?, ?, ?)',
data.map((domain) => [
packageId,
domain.specCode,
domain.specDescription,
domain.specCertifiable ? 1 : 0,
]),
)
}
/**
* Inserts global attribute defaults into the database.
*
* @param {*} db
* @param {*} packageId
* @param {*} clusterData array of objects that contain: code, manufacturerCode and subarrays of globalAttribute[] which contain: side, code, value
* @returns Promise of data insertion.
*/
async function insertGlobalAttributeDefault(db, packageId, clusterData) {
let individualClusterPromise = []
clusterData.forEach((cluster) => {
let args = []
cluster.globalAttribute.forEach((ga) => {
args.push([
packageId,
cluster.code,
packageId,
ga.code,
ga.side,
ga.value,
])
})
let p = dbApi
.dbMultiInsert(
db,
`
INSERT OR IGNORE INTO GLOBAL_ATTRIBUTE_DEFAULT (
CLUSTER_REF, ATTRIBUTE_REF, DEFAULT_VALUE
) VALUES (
( SELECT CLUSTER_ID FROM CLUSTER WHERE PACKAGE_REF = ? AND CODE = ? ),
( SELECT ATTRIBUTE_ID FROM ATTRIBUTE WHERE PACKAGE_REF = ? AND CODE = ? AND SIDE = ? ),
?)
`,
args,
)
.then((individualGaIds) => {
let featureBitArgs = []
for (let i = 0; i < individualGaIds.length; i++) {
let id = individualGaIds[i]
let ga = cluster.globalAttribute[i]
if (id != null && 'featureBit' in ga) {
ga.featureBit.forEach((fb) => {
featureBitArgs.push([
id,
fb.bit,
dbApi.toDbBool(fb.value),
packageId,
fb.tag,
])
})
}
}
if (featureBitArgs.length == 0) {
return
} else {
return dbApi.dbMultiInsert(
db,
`
INSERT OR IGNORE INTO GLOBAL_ATTRIBUTE_BIT (
GLOBAL_ATTRIBUTE_DEFAULT_REF,
BIT,
VALUE,
TAG_REF
) VALUES (
?,
?,
?,
(SELECT TAG_ID FROM TAG WHERE PACKAGE_REF = ? AND NAME = ?)
)
`,
featureBitArgs,
)
}
})
individualClusterPromise.push(p)
})
return Promise.all(individualClusterPromise)
}
/**
* Insert atomics into the database.
* Data is an array of objects that must contains: name, id, description.
* Object might also contain 'size', but possibly not.
*
* @param {*} db
* @param {*} packageId
* @param {*} data
*/
async function insertAtomics(db, packageId, data) {
return dbApi.dbMultiInsert(
db,
'INSERT INTO ATOMIC (PACKAGE_REF, NAME, DESCRIPTION, ATOMIC_IDENTIFIER, ATOMIC_SIZE, IS_DISCRETE, IS_SIGNED, IS_STRING, IS_LONG, IS_CHAR) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
data.map((at) => [
packageId,
at.name,
at.description,
at.id,
at.size,
at.isDiscrete,
at.isSigned,
at.isString,
at.isLong,
at.isChar,
]),
)
}
/**
* Inserts endpoint composition data into the database based on the context's mandatory device type.
* This function checks if the context's mandatory device type matches the composition code.
* If they match, it performs an insert operation with a specific type from `dbEnum.mandatoryDeviceType`.
* If they do not match, it performs an insert with the composition's type.
*
* @param {*} db - The database connection object.
* @param {*} composition - The composition data to be inserted.
* @param {*} context - The context containing the mandatory device type to check against.
* @returns A promise resolved with the result of the database insert operation.
*/
async function insertEndpointComposition(db, composition, context) {
try {
if (parseInt(context.mandatoryDeviceTypes, 16) === composition.code) {
return await dbApi.dbInsert(
db,
'INSERT INTO ENDPOINT_COMPOSITION (TYPE, CODE) VALUES (?, ?)',
[dbEnum.composition.mandatoryEndpoint, composition.code],
)
} else {
return await dbApi.dbInsert(
db,
'INSERT INTO ENDPOINT_COMPOSITION (TYPE, CODE) VALUES (?, ?)',
[composition.compositionType, composition.code],
)
}
} catch (error) {
console.error('Error inserting endpoint composition:', error)
throw error // Re-throw the error after logging it
}
}
/**
* Retrieves the endpoint composition ID by device code.
*
* This function executes a SQL query to fetch the endpoint composition ID
* associated with a given device code. If the query fails, an error is logged.
*
* @param {Object} db - The database connection object.
* @param {Object} deviceType - The device type object containing the device code.
* @returns {Promise<number|null>} The endpoint composition ID or null if not found.
*/
async function getEndpointCompositionIdByCode(db, deviceType) {
const query =
'SELECT ENDPOINT_COMPOSITION_ID FROM ENDPOINT_COMPOSITION WHERE CODE = ?'
try {
const result = await dbApi.dbGet(db, query, [deviceType.code])
return result ? result.ENDPOINT_COMPOSITION_ID : null
} catch (error) {
console.error('Error retrieving endpoint composition ID:', error)
return null
}
}
/**
* Inserts a device composition record into the DEVICE_COMPOSITION table.
*
* This function constructs an SQL INSERT query to add a new record to the
* DEVICE_COMPOSITION table. It handles the insertion of the device code,
* endpoint composition reference, conformance, and constraint values.
* Note that the "CONSTRAINT" column name is escaped with double quotes
* to avoid conflicts with the SQL reserved keyword.
*
* @param {Object} db - The database connection object.
* @param {Object} deviceType - The device type object containing the data to be inserted.
* @param {number} endpointCompositionId - The ID of the endpoint composition.
* @returns {Promise} A promise that resolves when the insertion is complete.
*/
function insertDeviceComposition(db, deviceType, endpointCompositionId) {
const insertQuery = `