...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package core
17
18 import (
19 "encoding/json"
20 "strings"
21
22 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
23 )
24
25 type ObjectBase struct {
26 Namespace string `json:"namespace"`
27 Name string `json:"name"`
28 Kind string `json:"kind"`
29 UID string `json:"uid"`
30 Created string `json:"created_at"`
31 }
32
33
34 type KubeObjectDesc struct {
35 metav1.TypeMeta
36 Meta KubeObjectMeta `json:"metadata"`
37 Spec interface{} `json:"spec"`
38 }
39
40
41 type KubeObjectMeta struct {
42 Namespace string `json:"namespace"`
43 Name string `json:"name"`
44 Labels map[string]string `json:"labels,omitempty"`
45 Annotations map[string]string `json:"annotations,omitempty"`
46 }
47
48 type Filter struct {
49 ObjectID string `json:"object_id"`
50 Start string `json:"start"`
51 End string `json:"end"`
52 Namespace string `json:"namespace"`
53 Name string `json:"name"`
54 Kind string `json:"kind"`
55 Limit string `json:"limit"`
56 }
57
58 func (f *Filter) toMap() map[string]interface{} {
59 var fMap map[string]interface{}
60
61 marshal, _ := json.Marshal(f)
62 _ = json.Unmarshal(marshal, &fMap)
63
64 return fMap
65 }
66
67 const zeroTime = "0001-01-01 00:00:00"
68
69 func (f *Filter) ConstructQueryArgs() (string, []interface{}) {
70 fMap, query, args := f.toMap(), make([]string, 0), make([]interface{}, 0)
71
72 for k, v := range fMap {
73 if v != "" {
74 if k == "start" || k == "end" || k == "limit" {
75 continue
76 }
77
78 if len(args) > 0 {
79 query = append(query, "AND", k, "= ?")
80 } else {
81 query = append(query, k, "= ?")
82 }
83
84 args = append(args, v)
85 }
86 }
87
88 startEnd := ""
89 if f.Start != zeroTime && f.End != zeroTime {
90 startEnd = "created_at BETWEEN ? AND ?"
91 args = append(args, f.Start, f.End)
92 } else if f.Start != zeroTime && f.End == zeroTime {
93 startEnd = "created_at >= ?"
94 args = append(args, f.Start)
95 } else if f.Start == zeroTime && f.End != zeroTime {
96 startEnd = "created_at <= ?"
97 args = append(args, f.End)
98 }
99
100 if startEnd != "" {
101 if len(query) > 0 {
102 query = append(query, "AND", startEnd)
103 } else {
104 query = append(query, startEnd)
105 }
106 }
107
108 return strings.Join(query, " "), args
109 }
110