-
Notifications
You must be signed in to change notification settings - Fork 3
/
delete.go
63 lines (53 loc) · 1.45 KB
/
delete.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
package sqlbuilder
import (
"strings"
)
// Delete returns a new DELETE statement with the default dialect.
func Delete() DeleteStatement {
return DeleteStatement{dialect: DefaultDialect}
}
// DeleteStatement represents a DELETE statement.
type DeleteStatement struct {
dialect Dialect
table string
wheres []where
args []interface{}
}
// Dialect returns a new statement with dialect set to 'dialect'.
func (s DeleteStatement) Dialect(dialect Dialect) DeleteStatement {
s.dialect = dialect
return s
}
// From returns a new statement with the table to delete from set to 'table'.
func (s DeleteStatement) From(table string) DeleteStatement {
s.table = table
return s
}
// Where returns a new statement with condition 'cond'.
// Multiple Where() are combined with AND.
func (s DeleteStatement) Where(cond string, args ...interface{}) DeleteStatement {
s.wheres = append(s.wheres, where{cond, args})
return s
}
// Build builds the SQL query. It returns the query and the argument slice.
func (s DeleteStatement) Build() (query string, args []interface{}) {
query = "DELETE FROM " + s.table
if len(s.wheres) > 0 {
var (
sqls []string
idx int
)
for _, w := range s.wheres {
sql := "(" + w.sql + ")"
for _, arg := range w.args {
p := s.dialect.Placeholder(idx)
idx++
sql = strings.Replace(sql, "?", p, 1)
sqls = append(sqls, sql)
args = append(args, arg)
}
}
query += " WHERE " + strings.Join(sqls, " AND ")
}
return
}