-
Notifications
You must be signed in to change notification settings - Fork 0
/
delete.go
107 lines (81 loc) · 2.08 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
98
99
100
101
102
103
104
105
106
107
package query
import (
"fmt"
"log"
)
// Delete initiates a select statement
func Delete() *DeleteQuery {
s := &DeleteQuery{}
return s
}
// DeleteQuery is the containing struct for functionality to build select statements on domain objects
type DeleteQuery struct {
Object DomainObject
where []IQueryPart
limit IQueryPart
}
// Where is sugar for the And(queryParts...) method
func (s *DeleteQuery) Where(queryParts ...IQueryPart) *DeleteQuery {
return s.And(queryParts...)
}
// And adds an "and group" to the query
func (s *DeleteQuery) And(queryParts ...IQueryPart) *DeleteQuery {
l := len(queryParts)
if len(s.where) > 0 {
s.where = append(s.where, And{})
}
group := false
if l > 0 {
group = true
s.where = append(s.where, OpenParenthesis{})
}
for _, queryPart := range queryParts {
s.where = append(s.where, queryPart)
}
if group {
s.where = append(s.where, CloseParenthesis{})
}
return s
}
// Or adds an "or group" to the select query
func (s *DeleteQuery) Or(queryParts ...IQueryPart) *DeleteQuery {
l := len(queryParts)
if len(s.where) > 0 {
s.where = append(s.where, Or{})
}
group := false
if l > 0 {
group = true
s.where = append(s.where, OpenParenthesis{})
}
for _, queryPart := range queryParts {
s.where = append(s.where, queryPart)
}
if group {
s.where = append(s.where, CloseParenthesis{})
}
return s
}
// Limit adds a limit clause to the sql statement
func (s *DeleteQuery) Limit(count int) *DeleteQuery {
s.limit = LimitSimple(count)
return s
}
// ToSQL builds a sql select statement
func (s *DeleteQuery) ToSQL() (sql string, args []interface{}) {
fields := s.Object.GetFieldsOrdered()
escapedFields := []string{}
for _, field := range fields {
escapedFields = append(escapedFields, escapeField(field.Name))
}
sql, args = buildWhereClauseString(s.where)
if s.limit != nil {
sql += "LIMIT "
limitSQL, limitArgs := s.limit.ToSQL()
sql += limitSQL
args = append(args, limitArgs[0])
}
sql = fmt.Sprintf("DELETE FROM %s %s", escapeField(s.Object.GetName()), sql)
log.Printf("INF SQL: %s -- %v\n", sql, args)
return
}