-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathupdate_query.go
99 lines (89 loc) · 2.25 KB
/
update_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
package gosql
import (
"database/sql"
"fmt"
"strings"
)
// UpdateQuery holds information for an update query.
type UpdateQuery struct {
db *DB
execer Execer
table string
joins []string
wheres []*where
sets []string
whereArgs []interface{}
setArgs []interface{}
}
// Execer .
type Execer interface {
Exec(query string, args ...interface{}) (sql.Result, error)
}
// Where specifies which rows will be returned.
func (uq *UpdateQuery) Where(condition string, args ...interface{}) *UpdateQuery {
w := &where{
conjunction: " and ",
condition: condition,
}
uq.wheres = append(uq.wheres, w)
uq.whereArgs = append(uq.whereArgs, args...)
return uq
}
// OrWhere specifies which rows will be returned.
func (uq *UpdateQuery) OrWhere(condition string, args ...interface{}) *UpdateQuery {
w := &where{
conjunction: " or ",
condition: condition,
}
uq.wheres = append(uq.wheres, w)
uq.whereArgs = append(uq.whereArgs, args...)
return uq
}
// Set specifies how to update a row in a table.
func (uq *UpdateQuery) Set(set string, args ...interface{}) *UpdateQuery {
uq.sets = append(uq.sets, set)
uq.setArgs = append(uq.setArgs, args...)
return uq
}
// Join joins another table to this query.
func (uq *UpdateQuery) Join(join string) *UpdateQuery {
uq.joins = append(uq.joins, fmt.Sprintf(" join %s", join))
return uq
}
// LeftJoin joins another table to this query.
func (uq *UpdateQuery) LeftJoin(join string) *UpdateQuery {
uq.joins = append(uq.joins, fmt.Sprintf(" left join %s", join))
return uq
}
// Exec executes the query.
func (uq *UpdateQuery) Exec() (sql.Result, error) {
args := uq.setArgs
args = append(args, uq.whereArgs...)
return uq.execer.Exec(uq.String(), args...)
}
// String returns the string representation of UpdateQuery.
func (uq *UpdateQuery) String() string {
var q strings.Builder
q.WriteString("update ")
q.WriteString(uq.table)
for _, join := range uq.joins {
q.WriteString(join)
}
for i, set := range uq.sets {
if i == 0 {
q.WriteString(" set ")
} else {
q.WriteString(", ")
}
q.WriteString(set)
}
for i, where := range uq.wheres {
if i == 0 {
q.WriteString(" where ")
} else {
q.WriteString(where.conjunction)
}
q.WriteString(where.condition)
}
return q.String()
}