forked from ecodeclub/eorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate.go
185 lines (168 loc) · 4.37 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
// 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 (
"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 struct {
builder
table interface{}
val valuer.Value
where []Predicate
assigns []Assignable
}
// Build returns UPDATE query
func (u *Updater) Build() (*Query, error) {
defer bytebufferpool.Put(u.buffer)
var err error
u.meta, err = u.metaRegistry.Get(u.table)
if err != nil {
return nil, err
}
u.val = u.valCreator(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) 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)
}
val, _ := u.val.Field(a.name)
u.quote(c.ColumnName)
_ = u.buffer.WriteByte('=')
u.parameter(val)
has = true
case columns:
for _, name := range a.cs {
c, ok := u.meta.FieldMap[name]
if !ok {
return errs.NewInvalidFieldError(name)
}
val, _ := u.val.Field(name)
if has {
u.comma()
}
u.quote(c.ColumnName)
_ = u.buffer.WriteByte('=')
u.parameter(val)
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) buildDefaultColumns() error {
has := false
for _, c := range u.meta.Columns {
val, _ := u.val.Field(c.FieldName)
if has {
_ = u.buffer.WriteByte(',')
}
u.quote(c.ColumnName)
_ = u.buffer.WriteByte('=')
u.parameter(val)
has = true
}
if !has {
return errs.NewValueNotSetError()
}
return nil
}
// Set represents SET clause
func (u *Updater) Set(assigns ...Assignable) *Updater {
u.assigns = assigns
return u
}
// Where represents WHERE clause
func (u *Updater) Where(predicates ...Predicate) *Updater {
u.where = predicates
return u
}
// AssignNotNilColumns uses the non-nil value to construct the Assignable instances.
func AssignNotNilColumns(entity interface{}) []Assignable {
return AssignColumns(entity, func(typ reflect.StructField, 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 true
})
}
// AssignNotZeroColumns uses the non-zero value to construct the Assignable instances.
func AssignNotZeroColumns(entity interface{}) []Assignable {
return AssignColumns(entity, func(typ reflect.StructField, val reflect.Value) bool {
return !val.IsZero()
})
}
// AssignColumns will check all columns and then apply the filter function.
// If the returned value is true, this column will be updated.
func AssignColumns(entity interface{}, filter func(typ reflect.StructField, val reflect.Value) bool) []Assignable {
val := reflect.ValueOf(entity).Elem()
typ := reflect.TypeOf(entity).Elem()
numField := val.NumField()
res := make([]Assignable, 0, numField)
for i := 0; i < numField; i++ {
fieldVal := val.Field(i)
fieldTyp := typ.Field(i)
if filter(fieldTyp, fieldVal) {
res = append(res, Assign(fieldTyp.Name, fieldVal.Interface()))
}
}
return res
}