This repository has been archived by the owner on Feb 24, 2023. It is now read-only.
forked from ecodeclub/eorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.go
213 lines (192 loc) · 4.48 KB
/
update.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// Copyright 2021 gotomicro
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package eorm
import (
"context"
"fmt"
"reflect"
"github.com/gotomicro/eorm/internal/errs"
"github.com/gotomicro/eorm/internal/valuer"
"github.com/valyala/bytebufferpool"
)
// Updater is the builder responsible for building UPDATE query
type Updater[T any] struct {
builder
session
table interface{}
val valuer.Value
where []Predicate
assigns []Assignable
ignoreNilVal bool
ignoreZeroVal bool
}
// NewUpdater 开始构建一个 UPDATE 查询
func NewUpdater[T any](sess session) *Updater[T] {
return &Updater[T]{
builder: builder{
core: sess.getCore(),
buffer: bytebufferpool.Get(),
},
session: sess,
}
}
func (u *Updater[T]) Update(val *T) *Updater[T] {
u.table = val
return u
}
// Build returns UPDATE query
func (u *Updater[T]) Build() (*Query, error) {
defer bytebufferpool.Put(u.buffer)
var err error
t := new(T)
if u.table == nil {
u.table = t
}
u.meta, err = u.metaRegistry.Get(t)
if err != nil {
return nil, err
}
u.val = u.valCreator.NewBasicTypeValue(u.table, u.meta)
u.args = make([]interface{}, 0, len(u.meta.Columns))
u.writeString("UPDATE ")
u.quote(u.meta.TableName)
u.writeString(" SET ")
if len(u.assigns) == 0 {
err = u.buildDefaultColumns()
} else {
err = u.buildAssigns()
}
if err != nil {
return nil, err
}
if len(u.where) > 0 {
u.writeString(" WHERE ")
err = u.buildPredicates(u.where)
if err != nil {
return nil, err
}
}
u.end()
return &Query{
SQL: u.buffer.String(),
Args: u.args,
}, nil
}
func (u *Updater[T]) buildAssigns() error {
has := false
for _, assign := range u.assigns {
if has {
u.comma()
}
switch a := assign.(type) {
case Column:
c, ok := u.meta.FieldMap[a.name]
if !ok {
return errs.NewInvalidFieldError(a.name)
}
refVal, _ := u.val.Field(a.name)
u.quote(c.ColumnName)
_ = u.buffer.WriteByte('=')
u.parameter(refVal.Interface())
has = true
case columns:
for _, name := range a.cs {
c, ok := u.meta.FieldMap[name]
if !ok {
return errs.NewInvalidFieldError(name)
}
refVal, _ := u.val.Field(name)
if has {
u.comma()
}
u.quote(c.ColumnName)
_ = u.buffer.WriteByte('=')
u.parameter(refVal.Interface())
has = true
}
case Assignment:
if err := u.buildExpr(binaryExpr(a)); err != nil {
return err
}
has = true
default:
return fmt.Errorf("eorm: unsupported assignment %v", a)
}
}
if !has {
return errs.NewValueNotSetError()
}
return nil
}
func (u *Updater[T]) buildDefaultColumns() error {
has := false
for _, c := range u.meta.Columns {
refVal, _ := u.val.Field(c.FieldName)
if u.ignoreZeroVal && isZeroValue(refVal) {
continue
}
if u.ignoreNilVal && isNilValue(refVal) {
continue
}
if has {
_ = u.buffer.WriteByte(',')
}
u.quote(c.ColumnName)
_ = u.buffer.WriteByte('=')
u.parameter(refVal.Interface())
has = true
}
if !has {
return errs.NewValueNotSetError()
}
return nil
}
// Set represents SET clause
func (u *Updater[T]) Set(assigns ...Assignable) *Updater[T] {
u.assigns = assigns
return u
}
// Where represents WHERE clause
func (u *Updater[T]) Where(predicates ...Predicate) *Updater[T] {
u.where = predicates
return u
}
// SkipNilValue 忽略 nil 值 columns
func (u *Updater[T]) SkipNilValue() *Updater[T] {
u.ignoreNilVal = true
return u
}
func isNilValue(val reflect.Value) bool {
switch val.Kind() {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice:
return val.IsNil()
}
return false
}
// SkipZeroValue 忽略零值 columns
func (u *Updater[T]) SkipZeroValue() *Updater[T] {
u.ignoreZeroVal = true
return u
}
func isZeroValue(val reflect.Value) bool {
return val.IsZero()
}
// Exec sql
func (u *Updater[T]) Exec(ctx context.Context) Result {
query, err := u.Build()
if err != nil {
return Result{err: err}
}
return newQuerier[T](u.session, query, u.meta, UPDATE).Exec(ctx)
}