-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlq.go
More file actions
91 lines (74 loc) · 1.64 KB
/
sqlq.go
File metadata and controls
91 lines (74 loc) · 1.64 KB
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
package sqlq
import "strings"
type Sqlq struct {
Dialect string
Escape bool
skipEscapeOnce bool
}
func New(dialect string, escape bool) *Sqlq {
if d := strings.ToLower(dialect); d != "mysql" && d != "postgres" && d != "sqlite3" {
dialect = "mysql"
}
return &Sqlq{Dialect: dialect, Escape: escape, skipEscapeOnce: false}
}
func (sqlq *Sqlq) StopEscape() {
sqlq.Escape = false
}
func (sqlq *Sqlq) StartEscape() {
sqlq.Escape = true
}
func (sqlq *Sqlq) SkipEscapeOnce() {
sqlq.skipEscapeOnce = true
}
func (sqlq *Sqlq) Raw() *Sqlq {
sqlq.skipEscapeOnce = true
return sqlq
}
type query struct {
queryA []string
}
func (q *query) String() string {
return strings.Join(q.queryA, " ")
}
func (q *query) Append(queryA ...*query) *query {
for _, p := range queryA {
q.queryA = append(q.queryA, p.queryA...)
}
return q
}
func (q *query) Query(qParts ...string) *query {
q.queryA = append(q.queryA, qParts...)
return q
}
type Condition struct {
res bool
t string
}
func (sqlq *Sqlq) If(condition bool, s ...string) *Condition {
return &Condition{res: condition, t: sqlq.Query(s...).String()}
}
func (c *Condition) ElseIf(condition bool, s ...string) *Condition {
if !c.res {
c.res = condition
c.t = Sqlq{}.Query(s...).String()
}
return c
}
func (c *Condition) Else(s ...string) string {
if c.res {
return c.t
}
return Sqlq{}.Query(s...).String()
}
func (Sqlq) Query(qParts ...string) *query {
var q query
q.Query(qParts...)
return &q
}
func (Sqlq) Concat(queryA ...*query) *query {
var newquery query
for _, query := range queryA {
newquery.queryA = append(newquery.queryA, query.queryA...)
}
return &newquery
}