forked from OpenBazaar/openbazaar-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
106 lines (93 loc) · 2.31 KB
/
query.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
package db
import (
"github.com/OpenBazaar/openbazaar-go/pb"
"strconv"
"strings"
)
type query struct {
table string
columns []string
stateFilter []pb.OrderState
searchTerm string
searchColumns []string
sortByAscending bool
sortByRead bool
id string
exclude []string
limit int
}
func filterQuery(q query) (stm string, args []interface{}) {
stateFilterClause := ""
var states []int
if len(q.stateFilter) > 0 {
stateFilterClauseParts := make([]string, 0, len(q.stateFilter))
for i := 0; i < len(q.stateFilter); i++ {
states = append(states, int(q.stateFilter[i]))
stateFilterClauseParts = append(stateFilterClauseParts, "?")
}
stateFilterClause = "state in (" + strings.Join(stateFilterClauseParts, ",") + ")"
}
var exclude string
if len(q.exclude) > 0 {
excludeFilterClauseParts := make([]string, 0, len(q.exclude))
for i := 0; i < len(q.exclude); i++ {
excludeFilterClauseParts = append(excludeFilterClauseParts, "?")
}
exclude = q.id + " not in (" + strings.Join(excludeFilterClauseParts, ",") + ")"
}
order := "desc"
if q.sortByAscending {
order = "asc"
}
var filter string
var search string
searchFilter := `(`
for i, c := range q.searchColumns {
searchFilter += c
if i < len(q.searchColumns)-1 {
searchFilter += " || "
}
}
searchFilter += `)`
queryColumns := ``
for i, c := range q.columns {
queryColumns += c
if i < len(q.columns)-1 {
queryColumns += ", "
}
}
var readSort string
if q.sortByRead {
readSort = "read asc, "
}
if stateFilterClause != "" {
filter = " where " + stateFilterClause
}
if q.searchTerm != "" {
if filter == "" {
search = " where " + searchFilter + " like ?"
} else {
search = " and " + searchFilter + " like ?"
}
}
if exclude != "" {
if filter != "" || search != "" {
exclude = " and " + exclude
} else {
exclude = " where " + exclude
}
}
stm = "select " + queryColumns + " from " + q.table + filter + search + exclude + " order by " + readSort + "timestamp " + order + " limit " + strconv.Itoa(q.limit) + ";"
for _, s := range states {
args = append(args, s)
}
if q.searchTerm != "" {
args = append(args, "%"+q.searchTerm+"%")
}
if len(q.exclude) > 0 {
for _, s := range q.exclude {
args = append(args, s)
}
}
return stm, args
}