/
query-shared.go
1316 lines (1177 loc) · 35.6 KB
/
query-shared.go
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
// MIT License
//
// (C) Copyright [2019-2023] Hewlett Packard Enterprise Development LP
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
package hmsds
import (
"fmt"
"strings"
base "github.com/Cray-HPE/hms-base"
"github.com/OpenCHAMI/smd/v2/pkg/sm"
)
// Matches generic query sources in external API, but with real table names,
// not just identifiers for the type of data.
const (
componentsTableDB = "components"
redfishEndpointsTableDB = "rf_endpoints"
componentEndpointsTableDB = "comp_endpoints"
componentEndpointInfoTableDB = "comp_endpoints_info"
nodeMapTableDB = "node_nid_mapping"
powerMapTableDB = "power_mapping"
hwInvByLocTableDB = "hwinv_by_loc"
hwInvByFRUTableDB = "hwinv_by_fru"
discoveryStatusTableDB = "discovery_status"
scnSubcriptionsTableDB = "scn_subscriptions"
)
// Generic id field queries
const getIDPrefix = "SELECT id FROM "
const getCompIDPrefix = getIDPrefix + componentsTableDB + " "
const getRFEndpointIDPrefix = getIDPrefix + redfishEndpointsTableDB + " "
const getCompEndpointIDPrefix = getIDPrefix + componentEndpointsTableDB + " "
const getNodeMapIDPrefix = getIDPrefix + nodeMapTableDB + " "
const getPowerMapIDPrefix = getIDPrefix + powerMapTableDB + " "
const getHWInvByLocIDPrefix = getIDPrefix + hwInvByLocTableDB + " "
const getHWInvByFRUIDPrefix = getIDPrefix + hwInvByFRUTableDB + " "
const getDiscoveryStatusIDPrefix = getIDPrefix + discoveryStatusTableDB + " "
//
// Suffix strings for various select queries
//
const suffixCompFilter = `
) AS filter;`
const suffixByID = `
WHERE id = ?;`
const suffixByIDForUpd = `
WHERE id = ? FOR UPDATE;`
const suffixByFRUID = `
WHERE fru_id = ?;`
const suffixByFRUIDForUpd = `
WHERE fru_id = ? FOR UPDATE;`
const suffixByType = `
WHERE type = ?;`
const suffixByTypeForUpd = `
WHERE type = ? FOR UPDATE;`
const suffixByNID = `
WHERE nid = ?;`
const suffixByNIDForUpd = `
WHERE nid = ? FOR UPDATE;`
const suffixByFQDN = `
WHERE fqdn = ?;`
const suffixByFQDNForUpd = `
WHERE fqdn = ? FOR UPDATE;`
const suffixByRfEP = `
WHERE rf_endpoint_id = ?;`
const suffixByRfEPForUpd = `
WHERE rf_endpoint_id = ? FOR UPDATE;`
const suffixByRfType = `
WHERE redfish_type = ?;`
const suffixByRfTypeForUpd = `
WHERE redfish_type = ? FOR UPDATE;`
const suffixByRfEPandRfType = `
WHERE rf_endpoint_id = ? AND redfish_type = ?;`
const suffixByRfEPandRfTypeForUpd = `
WHERE rf_endpoint_id = ? AND redfish_type = ? FOR UPDATE;`
const suffixByRfSubtype = `
WHERE redfish_subtype = ?;`
const suffixByRfSubtypeForUpd = `
WHERE redfish_subtype = ? FOR UPDATE;`
//
// Component structs
//
const getCompPrefix = `
SELECT
id,
type,
state,
flag,
enabled,
admin,
role,
subrole,
nid,
subtype,
nettype,
arch,
class,
reservation_disabled,
locked
FROM components `
const getCompStatePrefix = `
SELECT
filter.id,
filter.type,
filter.state,
filter.flag
FROM ( `
const getCompFlagPrefix = `
SELECT
filter.id,
filter.type,
filter.flag
FROM ( `
const getCompRolePrefix = `
SELECT
filter.id,
filter.type,
filter.role,
filter.subrole
FROM ( `
const getCompNIDPrefix = `
SELECT
filter.id,
filter.type,
filter.nid
FROM ( `
const getCompQueryPrefix = `
SELECT
comp.id,
comp.type,
comp.state,
comp.flag,
comp.enabled,
comp.admin,
comp.role,
comp.subrole,
comp.nid,
comp.subtype,
comp.nettype,
comp.arch,
comp.class,
comp.reservation_disabled,
comp.locked
FROM ( `
const getComponentByIDQuery = getCompPrefix + suffixByID
const getComponentByIDForUpdQuery = getCompPrefix + suffixByIDForUpd
const getComponentByTypeQuery = getCompPrefix + suffixByType
const getComponentByTypeForUpdQuery = getCompPrefix + suffixByTypeForUpd
const getComponentByNIDQuery = getCompPrefix + suffixByNID
const getComponentByNIDForUpdQuery = getCompPrefix + suffixByNIDForUpd
const getComponentsAllQuery = getCompPrefix + ";"
//const getComponentByFQDNQuery = getCompPrefix + suffixByFQDN
//
// Component queries
//
const updateCompPrefix = `UPDATE components SET `
const updateCompStatePrefix = `
UPDATE components SET
state = ?,
flag = ? `
const updateCompFlagOnlyPrefix = `
UPDATE components SET
flag = ? `
const updateCompEnabledPrefix = `
UPDATE components SET
enabled = ? `
const updateCompSwStatusPrefix = `
UPDATE components SET
admin = ? `
const updateCompRolePrefix = `
UPDATE components SET
role = ?,
subrole = ? `
const updateCompClassPrefix = `
UPDATE components SET
class = ? `
const updateCompNIDPrefix = `
UPDATE components SET
nid = ? `
const updateCompStateByIDQuery = updateCompStatePrefix + suffixByID
const updateCompFlagOnlyByIDQuery = updateCompFlagOnlyPrefix + suffixByID
const updateCompEnabledByIDQuery = updateCompEnabledPrefix + suffixByID
const updateCompSwStatusByIDQuery = updateCompSwStatusPrefix + suffixByID
const updateCompRoleByIDQuery = updateCompRolePrefix + suffixByID
const updateCompNIDByIDQuery = updateCompNIDPrefix + suffixByID
const deleteComponentPrefix = `
DELETE FROM components `
const deleteComponentByIDQuery = deleteComponentPrefix + suffixByID
const deleteComponentsAllQuery = deleteComponentPrefix + ";"
// getCompIDPrefix
// Node xname->NID mapping
const getNodeMapPrefix = `
SELECT
id,
nid,
role,
subrole,
node_info
FROM node_nid_mapping `
const getNodeMapByIDQuery = getNodeMapPrefix + suffixByID
const getNodeMapsAllQuery = getNodeMapPrefix + ";"
//
// Component NID map queries
//
const updateNodeMapPrefix = `
UPDATE node_nid_mapping SET
nid = ?,
role = ?,
subrole = ?,
node_info = ?`
const deleteNodeMapPrefix = `
DELETE FROM node_nid_mapping `
const deleteNodeMapByIDQuery = deleteNodeMapPrefix + suffixByID
const deleteNodeMapsAllQuery = deleteNodeMapPrefix + ";"
// Power mapping
const getPowerMapPrefix = `
SELECT
id,
powered_by
FROM power_mapping `
const getPowerMapByIDQuery = getPowerMapPrefix + suffixByID
const getPowerMapsAllQuery = getPowerMapPrefix + ";"
//
// Component Power map queries
//
const updatePowerMapPrefix = `
UPDATE power_mapping SET
powered_by = ?`
const deletePowerMapPrefix = `
DELETE FROM power_mapping `
const deletePowerMapByIDQuery = deletePowerMapPrefix + suffixByID
const deletePowerMapsAllQuery = deletePowerMapPrefix + ";"
//
// Hardware Inventory Queries
//
const getHWInvByLocPrefix = `
SELECT
id,
type,
ordinal,
status,
location_info,
fru_id
FROM hwinv_by_loc `
const getHWInvByFRUPrefix = `
SELECT
fru_id,
type,
subtype,
fru_info
FROM hwinv_by_fru `
const getHWInvByLocWithFRUPrefix = `
SELECT
id,
type,
ordinal,
status,
location_info,
fru_id,
fru_type,
fru_subtype,
fru_info
FROM hwinv_by_loc_with_fru `
const getHWInvByLocByIDQuery = getHWInvByLocPrefix + suffixByID
const getHWInvByFRUByFRUIDQuery = getHWInvByFRUPrefix + suffixByFRUID
const getHWInvByFRUAllQuery = getHWInvByFRUPrefix + ";"
const getHWInvByLocWithFRUByIDQuery = getHWInvByLocWithFRUPrefix + suffixByID
const getHWInvByLocWithFRUAllQuery = getHWInvByLocWithFRUPrefix + ";"
//
// Hardware Inventory - Delete operations
//
const deleteHWInvByLocPrefix = `
DELETE FROM hwinv_by_loc `
const deleteHWInvByLocIDQuery = deleteHWInvByLocPrefix + suffixByID
const deleteHWInvByLocsAllQuery = deleteHWInvByLocPrefix + ";"
const deleteHWInvByFRUPrefix = `
DELETE FROM hwinv_by_fru `
const deleteHWInvByFRUIDQuery = deleteHWInvByFRUPrefix + suffixByFRUID
const deleteHWInvByFRUsAllQuery = deleteHWInvByFRUPrefix + ";"
//
// Redfish Endpoints - Queries
//
const getRFEndpointPrefix = `
SELECT
rf.id,
rf.type,
rf.name,
rf.hostname,
rf.domain,
rf.fqdn,
rf.enabled,
rf.uuid,
rf.user,
rf.password,
rf.useSSDP,
rf.macRequired,
rf.macAddr,
rf.ipAddr,
rf.rediscoverOnUpdate,
rf.templateID,
rf.discovery_info
FROM rf_endpoints rf`
// Primary key is ID, other modifiers produce multiple results
const getRFEndpointByIDQuery = getRFEndpointPrefix + suffixByID
const getRFEndpointsByTypeQuery = getRFEndpointPrefix + suffixByType
const getRFEndpointsAllQuery = getRFEndpointPrefix + ";"
//
// RedfishEndpoints - Delete operations
//
const deleteRFEndpointPrefix = `
DELETE FROM rf_endpoints `
const deleteRFEndpointByIDQuery = deleteRFEndpointPrefix + suffixByID
const deleteRFEndpointsAllQuery = deleteRFEndpointPrefix + ";"
//
// Component and Service Endpoints - Queries
//
const getCompEndpointPrefix = `
SELECT
id,
type,
domain,
redfish_type,
redfish_subtype,
mac,
uuid,
odata_id,
rf_endpoint_id,
rf_endpoint_fqdn,
component_info,
enabled
FROM comp_endpoints_info `
const getServiceEndpointPrefix = `
SELECT
rf_endpoint_id,
redfish_type,
redfish_subtype,
uuid,
odata_id,
rf_endpoint_fqdn,
service_info
FROM service_endpoints_info `
// Primary key is ID, others modifiers produce multiple results
const getCompEndpointByIDQuery = getCompEndpointPrefix + suffixByID
const getCompEndpointsByRfEPQuery = getCompEndpointPrefix + suffixByRfEP
const getCompEndpointsByTypeQuery = getCompEndpointPrefix + suffixByType
const getCompEndpointsByRfSubtypeQuery = getCompEndpointPrefix + suffixByRfSubtype
const getCompEndpointsAllQuery = getCompEndpointPrefix + ";"
// Primary key is Redfish EP id + Redfish type, others produce multiple results
const getServiceEndpointsByRfEPQuery = getServiceEndpointPrefix + suffixByRfEP
const getServiceEndpointsByRfTypeQuery = getServiceEndpointPrefix + suffixByRfType
const getServiceEndpointsByRfSubtypeQuery = getServiceEndpointPrefix + suffixByRfSubtype
const getServiceEndpointByRfEPandRfTypeQuery = getServiceEndpointPrefix + suffixByRfEPandRfType
const getServiceEndpointsAllQuery = getServiceEndpointPrefix + ";"
//
// ComponentEndpoints - Delete operations
//
const deleteCompEndpointPrefix = `
DELETE FROM comp_endpoints `
const deleteCompEndpointByIDQuery = deleteCompEndpointPrefix + suffixByID
const deleteCompEndpointsAllQuery = deleteCompEndpointPrefix + ";"
//
// ServiceEndpoints - Delete operations
//
const deleteServiceEndpointPrefix = `
DELETE FROM service_endpoints `
const deleteServiceByRfEPandRfTypeQuery = deleteServiceEndpointPrefix + suffixByRfEPandRfType
const deleteServiceEndpointsAllQuery = deleteServiceEndpointPrefix + ";"
//
// Discovery status
//
const getDiscoveryStatusPrefix = `
SELECT
id,
status,
last_update,
details
FROM discovery_status `
const getDiscoveryStatusByIDQuery = getDiscoveryStatusPrefix + suffixByID
const getDiscoveryStatusesAllQuery = getDiscoveryStatusPrefix + ";"
//
// SCNs
//
const getSCNSubsAll = `
SELECT
id,
subscription
FROM scn_subscriptions;`
const getSCNSub = `
SELECT
id,
subscription
FROM scn_subscriptions WHERE id = ?;`
const getSCNSubUpdate = `
SELECT
id,
subscription
FROM scn_subscriptions WHERE id = ? FOR UPDATE;`
const insertSCNSub = `
INSERT INTO scn_subscriptions (
sub_url,
subscription)
VALUES (?, ?);`
const updateSCNSub = `
UPDATE scn_subscriptions SET
sub_url = ?,
subscription = ?
WHERE id = ?;`
const deleteSCNSubscription = `
DELETE FROM scn_subscriptions WHERE id = ?;`
const deleteSCNSubscriptionsAll = `
DELETE FROM scn_subscriptions;`
////////////////////////////////////////////////////////////////////////////
//
// Helper functions - Query building
//
////////////////////////////////////////////////////////////////////////////
// Puts together custom query of ServiceEndpoints collection to filter based
// on query strings provided by user.
func buildServiceEPQuery(baseQuery string, f *ServiceEPFilter) (string, []interface{}, error) {
q := newPreparedQuery(baseQuery)
err := q.doQueryArg("rf_endpoint_id", f.RfEndpointID, validXNameFilter)
if err != nil {
return baseQuery, q.args, ErrHMSDSArgBadID
}
err = q.doQueryArg("redfish_type", f.Service, strToAlphaNum)
if err != nil {
return baseQuery, q.args, ErrHMSDSArgBadType
}
// Terminate statement
if f.writeLock == true {
q.appendToQuery(" FOR UPDATE;")
} else {
q.appendToQuery(";")
}
return q.query, q.args, nil
}
// Puts together custom query of ComponentEndpoints collection to filter based
// on query strings provided by user.
func buildCompEPQuery(baseQuery string, f *CompEPFilter) (string, []interface{}, error) {
q := newPreparedQuery(baseQuery)
err := q.doQueryArg("id", f.ID, validXNameFilter)
if err != nil {
return baseQuery, q.args, ErrHMSDSArgBadID
}
err = q.doQueryArg("rf_endpoint_id", f.RfEndpointID, validXNameFilter)
if err != nil {
return baseQuery, q.args, ErrHMSDSArgBadID
}
err = q.doQueryArg("redfish_subtype", f.RedfishType, strToAlphaNum)
if err != nil {
return baseQuery, q.args, ErrHMSDSArgBadRedfishType
}
err = q.doQueryArg("type", f.Type, base.VerifyNormalizeType)
if err != nil {
return baseQuery, q.args, ErrHMSDSArgBadType
}
// Terminate statement
if f.writeLock == true {
q.appendToQuery(" FOR UPDATE;")
} else {
q.appendToQuery(";")
}
return q.query, q.args, nil
}
// Puts together custom query of ComponentEndpoints collection to filter based
// on query strings provided by user.
func buildRedfishEPQuery(baseQuery string, f *RedfishEPFilter) (string, []interface{}, error) {
q := newPreparedQuery(baseQuery)
if err := q.doQueryArg("id", f.ID, validXNameFilter); err != nil {
return baseQuery, q.args, ErrHMSDSArgBadID
}
if err := q.doQueryArg("fqdn", f.FQDN, nil); err != nil {
return baseQuery, q.args, ErrHMSDSArgBadArg
}
if err := q.doQueryArg("uuid", f.UUID, nil); err != nil {
return baseQuery, q.args, ErrHMSDSArgBadArg
}
err := q.doQueryArg("type", f.Type, base.VerifyNormalizeType)
if err != nil {
return baseQuery, q.args, ErrHMSDSArgBadType
}
if err := q.doQueryArg("macAddr", f.MACAddr, nil); err != nil {
return baseQuery, q.args, ErrHMSDSArgBadArg
}
if err := q.doQueryArg("ipAddr", f.IPAddr, nil); err != nil {
return baseQuery, q.args, ErrHMSDSArgBadArg
}
if err := q.doQueryArg("discovery_info ->> 'LastDiscoveryStatus'", f.LastStatus, nil); err != nil {
return baseQuery, q.args, ErrHMSDSArgBadArg
}
// Terminate statement
if f.writeLock == true {
q.appendToQuery(" FOR UPDATE;")
} else {
q.appendToQuery(";")
}
return q.query, q.args, nil
}
// Puts together custom query of HMS Components collection to filter based
// on query strings provided by user. Intended for prepared statements,
// inserting "?" variables and returning the args as interface array.
func buildComponentQuery(
baseQuery string,
f *ComponentFilter,
) (string, []interface{}, error) {
q := newPreparedQuery(baseQuery)
err := q.setCompWhereQuery(f, false)
return q.query, q.args, err
}
// Start a component update with the given filter options and the set of
// ids. If direct is set, non-id values will not be parameterized.
func startCompUpdate(ids []string, direct bool, f_opts ...CompFiltFunc) (*preparedQuery, error) {
q := newPreparedQuery(updateCompPrefix)
q.setDirectQuery(direct)
f := new(ComponentFilter)
for _, f_opt := range f_opts {
f_opt(f)
}
if err := q.setCompUpdateArgs(f); err != nil {
return q, err
}
q.setDirectQuery(false)
fcomp := ComponentFilter{ID: ids}
if err := q.setCompWhereQuery(&fcomp, true); err != nil {
return q, err
}
q.setDirectQuery(direct)
return q, nil
}
// Using filter ops, append the existing write query with filtering options
// to restrict the candidate rows based on the options give.
// NOTE: If started with direct=true, do not feed raw user input into these
// as we do not use the args as prepared query arguments.
func finishCompUpdate(
q *preparedQuery,
f_opts ...CompFiltFunc,
) (string, []interface{}, error) {
f := new(ComponentFilter)
for _, f_opt := range f_opts {
f_opt(f)
}
err := q.setCompWhereQuery(f, false)
return q.query, q.args, err
}
// Start custom Update ... SET arg1 = val1, arg2 = val2, ... query.
// Does NOT add WHERE clause and is unterminated.
func (q *preparedQuery) setCompUpdateArgs(f *ComponentFilter) error {
if q == nil {
return ErrHMSDSArgNil
}
err := q.doUpdateArg("type", f.Type, nil, base.VerifyNormalizeType, false)
if err != nil {
return ErrHMSDSArgBadType
}
// Addtional states to be added as normal AND options
err = q.doUpdateArg("state", f.State, nil, base.VerifyNormalizeState, false)
if err != nil {
return ErrHMSDSArgBadState
}
// Ditto flag
err = q.doUpdateArg("flag", f.Flag, f.flagCondition, base.VerifyNormalizeFlag, false)
if err != nil {
return ErrHMSDSArgBadFlag
}
err = q.doUpdateArg("admin", f.SwStatus, nil, nil, true)
if err != nil {
return ErrHMSDSArgBadArg
}
err = q.doUpdateArg("enabled", f.Enabled, nil, strToDbBool, false)
if err != nil {
return ErrHMSDSArgNoMatch
}
err = q.doUpdateArg("role", f.Role, nil, base.VerifyNormalizeRole, false)
if err != nil {
return ErrHMSDSArgBadRole
}
err = q.doUpdateArg("subrole", f.SubRole, nil, base.VerifyNormalizeSubRole, false)
if err != nil {
return ErrHMSDSArgBadSubRole
}
err = q.doUpdateArg("subtype", f.Subtype, nil, strToAlphaNum, true)
if err != nil {
return ErrHMSDSArgBadSubtype
}
err = q.doUpdateArg("arch", f.Arch, nil, base.VerifyNormalizeArch, false)
if err != nil {
return ErrHMSDSArgBadArch
}
err = q.doUpdateArg("class", f.Class, nil, base.VerifyNormalizeClass, false)
if err != nil {
return ErrHMSDSArgBadClass
}
// No NIDStart or NIDEnds. Just NIDs.
err = q.doUpdateArg("nid", f.NID, nil, nidStrTransform, false)
if err != nil {
return ErrHMSDSArgBadType
}
return nil
}
// Puts together WHERE query, starting one if cont=true or terminating it
// otherwise. Used prepared args or direct substitution depending on q
// options.
func (q *preparedQuery) setCompWhereQuery(f *ComponentFilter, cont bool) error {
// Build up a query string to filter the full results
// NOTE: if nothing is given, we still should end up with a
// valid query, ditto when more than one argument.
if q == nil {
return ErrHMSDSArgNil
}
//
// Construct 'where' arguments.
//
err := q.doQueryArg("id", f.ID, validXNameFilter)
if err != nil {
return ErrHMSDSArgBadID
}
err = q.doQueryArg("type", f.Type, base.VerifyNormalizeType)
if err != nil {
return ErrHMSDSArgBadType
}
// Allow state OR flag as a subclause without ORing the whole query
err = q.doQueryArgsWithOR(
"state", "flag",
f.orState, f.orFlag,
base.VerifyNormalizeState,
base.VerifyNormalizeFlag)
if err != nil {
return ErrHMSDSArgBadState
}
// Addtional states to be added as normal AND options
err = q.doQueryArg("state", f.State, base.VerifyNormalizeState)
if err != nil {
return ErrHMSDSArgBadState
}
// Ditto flag
err = q.doQueryArg("flag", f.Flag, base.VerifyNormalizeFlag)
if err != nil {
return ErrHMSDSArgBadFlag
}
err = q.doQueryArg("admin", f.SwStatus, nil)
if err != nil {
return ErrHMSDSArgBadArg
}
err = q.doQueryArg("enabled", f.Enabled, strToDbBool)
if err != nil {
return ErrHMSDSArgNoMatch
}
err = q.doQueryArg("role", f.Role, base.VerifyNormalizeRole)
if err != nil {
return ErrHMSDSArgBadRole
}
err = q.doQueryArg("subrole", f.SubRole, base.VerifyNormalizeSubRole)
if err != nil {
return ErrHMSDSArgBadSubRole
}
err = q.doQueryArg("subtype", f.Subtype, strToAlphaNum)
if err != nil {
return ErrHMSDSArgBadSubtype
}
err = q.doQueryArg("arch", f.Arch, base.VerifyNormalizeArch)
if err != nil {
return ErrHMSDSArgBadArch
}
err = q.doQueryArg("class", f.Class, base.VerifyNormalizeClass)
if err != nil {
return ErrHMSDSArgBadClass
}
// Specified NIDStart and NIDEnd keys will be AND paired.
// EX: (nid >= NIDStart AND nid <= NIDEnd)
// Multiple ranges need to be OR'd together.
// EX: (nid >= NIDStart1 AND nid <= NIDEnd1) OR (nid >= NIDStart2 AND nid <= NIDEnd2)
// Ranges need to be OR'd with NID keys.
// EX: ((nid >= NIDStart1 AND nid <= NIDEnd1) OR nid = NID)
if len(f.NIDStart) > 0 || len(f.NIDEnd) > 0 {
for i := 0; i < len(f.NIDStart); i++ {
if q.first == true {
q.appendToQuery(" WHERE ((nid >= ?")
q.first = false
} else {
if i > 0 {
q.appendToQuery(" OR (nid >= ?")
} else {
q.appendToQuery(" AND ((nid >= ?")
}
}
if !base.IsNumeric(f.NIDStart[i]) {
return ErrHMSDSArgNotAnInt
}
q.addArg(f.NIDStart[i])
// Check for a paired NIDEnd
if len(f.NIDEnd) >= i+1 {
if !base.IsNumeric(f.NIDEnd[i]) {
return ErrHMSDSArgNotAnInt
}
q.appendToQuery(" AND nid <= ?)")
q.addArg(f.NIDEnd[i])
} else {
q.appendToQuery(")")
}
}
// OR any leftover NIDEnd values if we had more NIDEnds than NIDStarts
for i := len(f.NIDStart); i < len(f.NIDEnd); i++ {
if q.first == true {
q.appendToQuery(" WHERE (nid <= ?")
q.first = false
} else {
if i > 0 {
q.appendToQuery(" OR nid <= ?")
} else {
q.appendToQuery(" AND (nid <= ?")
}
}
if !base.IsNumeric(f.NIDEnd[i]) {
return ErrHMSDSArgNotAnInt
}
q.addArg(f.NIDEnd[i])
}
// OR any NID values if we have them
if len(f.NID) > 0 {
for i := 0; i < len(f.NID); i++ {
if !base.IsNumeric(f.NID[i]) {
return ErrHMSDSArgNotAnInt
}
q.appendToQuery(" OR nid = ?")
q.addArg(f.NID[i])
}
}
// If no start, presume a start of positive nids.
if len(f.NIDStart) == 0 {
q.appendToQuery(") AND nid >= 0 ")
} else {
q.appendToQuery(")")
}
} else if len(f.NID) > 0 {
// No NIDStart or NIDEnds. Just NIDs.
err = q.doQueryArg("nid", f.NID, nidStrTransform)
if err != nil {
return ErrHMSDSArgNotAnInt
}
}
// Terminate statement
if cont == false {
if f.writeLock == true {
q.appendToQuery(" FOR UPDATE;")
} else {
q.appendToQuery(";")
}
}
return nil
}
// Puts together custom query of HMS Components collection to filter based
// on query strings provided by user and a list of component xnames.
// NOTE: baseQuery ends up as a subquery as a result of this function.
func buildBulkCompUpdateQuery(baseQuery string, ids []string) (string, []interface{}, error) {
args := make([]interface{}, 0, 1)
// If no 'type' is specified we'll be using the 'type' of the
// component (e.g. no component expansion). No need to use REGEXP.
filterQuery := baseQuery
for i := 0; i < len(ids); i++ {
if i > 0 {
// Multiples of the same key are OR'd together.
filterQuery += " OR id = ?"
} else {
filterQuery += " WHERE (id = ?"
}
args = append(args, base.NormalizeHMSCompID(ids[i]))
}
filterQuery += ");"
return filterQuery, args, nil
}
////////////////////////////////////////////////////////////////////////////
//
// Helper functions - PreparedQueries
//
////////////////////////////////////////////////////////////////////////////
// Holds a preparared query string and the corresponding argument interface
// array. Also holds a tracker to ensure only one WHERE clause is printed
// (and not printed if it is not needed)
type preparedQuery struct {
query string
args []interface{}
numArgs int // Postgres has unique numbered arguments.
first bool
firstUpdateArg bool
noArgs bool
postgresArgs bool // default false
}
// Creates a new prepared query with base query string baseQuery and
// an allocated but zero-length argument list.
func newPreparedQuery(baseQuery string) *preparedQuery {
p := new(preparedQuery)
p.args = make([]interface{}, 0, 1)
p.numArgs = 0 // Note: postgres starts numbering from one
p.query = baseQuery
p.first = true
p.noArgs = false
p.firstUpdateArg = true
return p
}
// Creates a new prepared query with base query string baseQuery that
// already includes baseArgs
func addPreparedQuery(baseQuery string, baseArgs []interface{}) *preparedQuery {
p := newPreparedQuery(baseQuery)
p.numArgs = len(baseArgs)
p.args = append(p.args, baseArgs...)
return p
}
// Don't parameterize arguments and add them to args array, put them
// directly into query.
func (p *preparedQuery) setDirectQuery(val bool) {
p.noArgs = val
}
// Appends parameters with name 'name' to mysql prepared query string and
// appends the matching 'params' values to args array.
// If 'parseF' is set, it is run on 'params' members before appending them to
// 'args', unless it returns the empty string with non-empty input, in which
// case it returns an error.
func (p *preparedQuery) doQueryArg(name string,
params []string,
parseF func(string) string,
) error {
names := []string{name}
paramset := [][]string{params}
parseFs := []func(string) string{parseF}
return p.doQueryArgSet(names, paramset, parseFs, false)
}
// Same as doQueryArg, but create a single clause that contains
// two parameter subclauses optionally separated by an OR instead of an
// AND. Because this OR is only local to this clause, it does not have
// global effect. For example, if we wanted to see if a new state and
// flag would update the existing state or flag, but while still
// allowing previous filters to work as intended (such as a set of nodes).
func (p *preparedQuery) doQueryArgsWithOR(name1, name2 string,
params1, params2 []string,
parseF1, parseF2 func(string) string,
) error {
names := []string{name1, name2}
paramset := [][]string{params1, params2}
parseFs := []func(string) string{parseF1, parseF2}
return p.doQueryArgSet(names, paramset, parseFs, true)
}
// Bulk version of doQueryArg, allowing for a set of parameters to be
// placed into a single clause. If we OR the subclauses together, they
// will be subclauses of the same function-wide AND clause, i.e. they don't
// be OR'd with the global query, just the parameters in this call.
//
// For example, if we wanted to see if a new state and flag would
// update the existing state or flag, but while still allowing previous
// filters to work as intended (such as a set of nodes).
func (p *preparedQuery) doQueryArgSet(names []string,
paramset [][]string,
parseFs []func(string) string,
doORnotAND bool,
) error {
var isMatch, orOper string
firstForFunc := true
closeOuter := false
// Create one AND clause with sub-clauses for each parameter. Sub
// clauses are ORed or ANDed depending on config.
for j, params := range paramset {