-
Notifications
You must be signed in to change notification settings - Fork 2
/
delete_query.go
75 lines (67 loc) · 1.73 KB
/
delete_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
package gosql
import (
"database/sql"
"fmt"
"strings"
)
// DeleteQuery is a query for deleting rows from a table.
type DeleteQuery struct {
db *DB
execer Execer
table string
joins []string
wheres []*where
whereArgs []interface{}
}
// Where specifies which rows will be returned.
func (dq *DeleteQuery) Where(condition string, args ...interface{}) *DeleteQuery {
w := &where{
conjunction: " and ",
condition: condition,
}
dq.wheres = append(dq.wheres, w)
dq.whereArgs = append(dq.whereArgs, args...)
return dq
}
// OrWhere specifies which rows will be returned.
func (dq *DeleteQuery) OrWhere(condition string, args ...interface{}) *DeleteQuery {
w := &where{
conjunction: " or ",
condition: condition,
}
dq.wheres = append(dq.wheres, w)
dq.whereArgs = append(dq.whereArgs, args...)
return dq
}
// Join joins another table to this query.
func (dq *DeleteQuery) Join(join string) *DeleteQuery {
dq.joins = append(dq.joins, fmt.Sprintf(" join %s", join))
return dq
}
// LeftJoin joins another table to this query.
func (dq *DeleteQuery) LeftJoin(join string) *DeleteQuery {
dq.joins = append(dq.joins, fmt.Sprintf(" left join %s", join))
return dq
}
// Exec executes the query.
func (dq *DeleteQuery) Exec() (sql.Result, error) {
return dq.execer.Exec(dq.String(), dq.whereArgs...)
}
// String returns the string representation of DeleteQuery.
func (dq *DeleteQuery) String() string {
var q strings.Builder
q.WriteString("delete from ")
q.WriteString(dq.table)
for _, join := range dq.joins {
q.WriteString(join)
}
for i, where := range dq.wheres {
if i == 0 {
q.WriteString(" where ")
} else {
q.WriteString(where.conjunction)
}
q.WriteString(where.condition)
}
return q.String()
}