-
Notifications
You must be signed in to change notification settings - Fork 0
/
delete.go
97 lines (81 loc) · 2.38 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
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
package statement
import (
"strings"
)
// DeleteStatement statement.
type DeleteStatement struct {
table string
with Statement
comment []Statement
where []Statement
returning []string
}
// Delete creates a new `DELETE` statement.
func Delete() (s *DeleteStatement) {
return &DeleteStatement{}
}
// Comment adds a SQL comment to the generated query.
// Each call to comment creates a new `-- <comment>` line.
func (s *DeleteStatement) Comment(c string, values ...interface{}) *DeleteStatement {
p := &part{}
p.query = "-- " + c
p.values = values
s.comment = append(s.comment, p)
return s
}
// From sets the table name or for the `FROM` clause.
func (s *DeleteStatement) From(table string) *DeleteStatement {
s.table = table
return s
}
// With adds a `WITH alias AS (stmt)`
func (s *DeleteStatement) With(alias string, stmt Statement) *DeleteStatement {
s.with = &with{alias: alias, stmt: stmt}
return s
}
// Where adds a `WHERE` clause, multiple calls to Where are `ANDed` together.
func (s *DeleteStatement) Where(q string, values ...interface{}) *DeleteStatement {
s.where = append(s.where, &part{query: q, values: values})
return s
}
// WhereIn adds a `WHERE IN (values)` clause, multiple calls to WhereIn are `ANDed` together.
func (s *DeleteStatement) WhereIn(column string, values ...interface{}) *DeleteStatement {
s.where = append(s.where, buildWhereIn(column, values...))
return s
}
// Returning adds a `RETURNING columns` clause.
func (s *DeleteStatement) Returning(columns ...string) *DeleteStatement {
s.returning = columns
return s
}
// Build builds the statement into the given buffer.
func (s *DeleteStatement) Build(buf Buffer) (err error) {
for x := 0; x < len(s.comment); x++ {
if err = s.comment[x].Build(buf); err != nil {
return err
}
_, _ = buf.WriteString("\n")
}
if s.with != nil {
if err = s.with.Build(buf); err != nil {
return err
}
_, _ = buf.WriteString(" ")
}
_, _ = buf.WriteString("DELETE FROM " + s.table)
if err = buildWhere(buf, s.where); err != nil {
return err
}
if len(s.returning) > 0 {
_, _ = buf.WriteString(" RETURNING " + strings.Join(s.returning, ","))
}
return nil
}
// String builds the statement and returns the resulting query string.
func (s *DeleteStatement) String() (q string, err error) {
var buf strings.Builder
if err = s.Build(&buf); err != nil {
return "", err
}
return buf.String(), nil
}