-
Notifications
You must be signed in to change notification settings - Fork 0
/
delete.go
90 lines (81 loc) · 1.64 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
package orm
import (
"context"
"github.com/valyala/bytebufferpool"
)
type Deleter[T any] struct {
Builder
sess session
table string
where *predicates
}
func NewDeleter[T any](sess session) *Deleter[T] {
c := sess.getCore()
return &Deleter[T]{
sess: sess,
Builder: Builder{
core: c,
buffer: bytebufferpool.Get(),
aliasMap: make(map[string]int, 8),
quoter: c.dialect.quoter(),
},
}
}
func (d *Deleter[T]) Where(ps ...Predicate) *Deleter[T] {
d.where = &predicates{
ps: ps,
}
return d
}
// From 指定表名,如果是空字符串,那么将会使用默认表名
func (d *Deleter[T]) From(tbl string) *Deleter[T] {
d.table = tbl
return d
}
func (d *Deleter[T]) Build() (*Query, error) {
defer bytebufferpool.Put(d.buffer)
var (
t T
err error
)
d.model, err = d.r.Get(&t)
if err != nil {
return nil, err
}
d.writeString("DELETE FROM ")
if d.table == "" {
d.writeByte('`')
d.writeString(d.model.TableName)
d.writeByte('`')
} else {
d.writeString(d.table)
}
// 构造 WHERE
if d.where != nil && len(d.where.ps) > 0 {
// 类似这种可有可无的部分,都要在前面加一个空格
d.writeString(" WHERE ")
// WHERE 是不允许用别名的
if err = d.buildPredicates(d.where); err != nil {
return nil, err
}
}
d.writeString(";")
return &Query{
SQL: d.buffer.String(),
Args: d.args,
}, nil
}
func (d *Deleter[T]) Exec(ctx context.Context) Result {
if d.model == nil {
m, err := d.r.Get(new(T))
if err != nil {
return Result{err: err}
}
d.model = m
}
return exec[T](ctx, d.core, d.sess, &QueryContext{
Type: "DELETE",
Builder: d,
Meta: d.model,
})
}