-
Notifications
You must be signed in to change notification settings - Fork 3
/
postgresql.go
118 lines (102 loc) · 2.54 KB
/
postgresql.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
package querysql
import (
"fmt"
"strings"
)
type PostgreSQL struct {
counter int
}
func (m *PostgreSQL) Reset() {
m.counter = 1
}
func (m *PostgreSQL) Mark() string {
m.counter += 1
t := fmt.Sprintf("$%d", m.counter)
return t
}
func (m *PostgreSQL) IsJSON(v string) (string, bool) {
//table.json:field.name:type
fieldOnly := strings.HasPrefix(v, "json:")
var dot int
if !fieldOnly {
dot = strings.Index(v, ".")
if dot == -1 || !strings.HasPrefix(v[dot+1:], "json:") {
return v, false
}
}
// separate table and field
table := ""
field := v
if !fieldOnly {
table = v[:dot]
field = v[dot+1:]
}
// separate field name and meta info
meta := strings.Split(field, ":")
name := strings.Split(meta[1], ".")
var tp string
if len(meta) == 3 {
tp = meta[2]
}
var s, e string
if tp == "date" {
s = "CAST("
e = " AS DATE)"
tp = "text"
} else if tp == "" {
tp = "text"
}
if table != "" {
return fmt.Sprintf("%s(\"%s\".\"%s\"->'%s')::%s%s", s, table, name[0], name[1], tp, e), true
}
return fmt.Sprintf("%s(\"%s\"->'%s')::%s%s", s, name[0], name[1], tp, e), true
}
func (m *PostgreSQL) Contains(v string, isJSON bool) string {
if isJSON {
// Quotes (" ... ") are needed for correct work. Fields of type text in JSONB are wrapped by default
return fmt.Sprintf("%s LIKE '\"%%' || %s || '%%\"'", v, m.Mark())
}
return fmt.Sprintf("%s LIKE '%%' || %s || '%%'", v, m.Mark())
}
func (m *PostgreSQL) NotContains(v string, isJSON bool) string {
if isJSON {
return fmt.Sprintf("%s NOT LIKE '\"%%' || %s || '%%\"'", v, m.Mark())
}
return fmt.Sprintf("%s NOT LIKE '%%' || %s || '%%'", v, m.Mark())
}
func (m *PostgreSQL) BeginsWith(v string, isJSON bool) string {
var search string
if isJSON {
search = "'\"' || " + m.Mark() + " || '%'"
} else {
search = m.Mark() + " || '%'"
}
return fmt.Sprintf("%s LIKE %s", v, search)
}
func (m *PostgreSQL) NotBeginsWith(v string, isJSON bool) string {
var search string
if isJSON {
search = "'\"' || " + m.Mark() + " || '%'"
} else {
search = m.Mark() + " || '%'"
}
return fmt.Sprintf("%s NOT LIKE %s", v, search)
}
func (m *PostgreSQL) EndsWith(v string, isJSON bool) string {
var search string
if isJSON {
search = "'%' || " + m.Mark() + " || '\"'"
} else {
search = "'%' || " + m.Mark()
}
return fmt.Sprintf("%s LIKE %s", v, search)
}
func (m *PostgreSQL) NotEndsWith(v string, isJSON bool) string {
var search string
if isJSON {
search = "'%' || " + m.Mark() + " || '\"'"
} else {
search = "'%' || " + m.Mark()
}
return fmt.Sprintf("%s NOT LIKE %s", v, search)
}