-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwhere.go
68 lines (58 loc) · 1.46 KB
/
where.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
package orm
import (
"reflect"
"strings"
"github.com/pkg/errors"
)
type Where interface {
String() string
GetParameters() []any
}
type BaseWhere struct {
query string
parameters []any
}
func (w *BaseWhere) String() string {
return w.query
}
func (w *BaseWhere) SetParameter(index int, param any) *BaseWhere {
w.parameters[index-1] = param
return w
}
func (w *BaseWhere) SetParameters(params ...any) *BaseWhere {
w.parameters = params
return w
}
func (w *BaseWhere) GetParameters() []any {
return w.parameters
}
func (w *BaseWhere) Append(query string, parameters ...any) {
newWhere := NewWhere(query, parameters...)
if !strings.HasPrefix(query, " ") {
w.query += " "
}
w.query += newWhere.query
w.parameters = append(w.parameters, newWhere.parameters...)
}
func NewWhere(query string, parameters ...any) *BaseWhere {
finalParameters := make([]any, 0, len(parameters))
for _, value := range parameters {
if value == nil {
panic(errors.New("nil nt allowed"))
}
switch reflect.TypeOf(value).Kind().String() {
case "slice", "array":
val := reflect.ValueOf(value)
length := val.Len()
in := strings.Repeat(",?", length)
in = strings.TrimLeft(in, ",")
query = strings.Replace(query, "IN ?", "IN ("+in+")", 1)
for i := 0; i < length; i++ {
finalParameters = append(finalParameters, val.Index(i).Interface())
}
continue
}
finalParameters = append(finalParameters, value)
}
return &BaseWhere{query, finalParameters}
}