forked from umisama/go-sqlbuilder
-
Notifications
You must be signed in to change notification settings - Fork 2
/
delete.go
62 lines (55 loc) · 1.28 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
package sqlbuilder
// DeleteStatement represents a DELETE statement.
type DeleteStatement struct {
from Table
where Condition
err error
}
// Delete returns new DELETE statement. The table is Table object to delete from.
func Delete(from Table) *DeleteStatement {
if from == nil {
return &DeleteStatement{
err: newError("from is nil."),
}
}
if _, ok := from.(*table); !ok {
return &DeleteStatement{
err: newError("CreateTable can use only natural table."),
}
}
return &DeleteStatement{
from: from,
}
}
// Where sets WHERE clause. cond is filter condition.
func (b *DeleteStatement) Where(cond Condition) *DeleteStatement {
if b.err != nil {
return b
}
for _, col := range cond.columns() {
if !b.from.hasColumn(col) {
b.err = newError("column not found in FROM")
return b
}
}
b.where = cond
return b
}
// ToSql generates query string, placeholder arguments, and returns err on errors.
func (b *DeleteStatement) ToSql() (query string, args []interface{}, err error) {
bldr := newBuilder()
defer func() {
query, args, err = bldr.Query(), bldr.Args(), bldr.Err()
}()
if b.err != nil {
bldr.SetError(b.err)
return
}
bldr.Append("DELETE FROM ")
bldr.AppendItem(b.from)
if b.where != nil {
bldr.Append(" WHERE ")
bldr.AppendItem(b.where)
}
return
}