forked from si3nloong/sqlike
-
Notifications
You must be signed in to change notification settings - Fork 0
/
modify.go
112 lines (99 loc) · 2.41 KB
/
modify.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
package sqlike
import (
"context"
"errors"
"reflect"
"github.com/RevenueMonster/sqlike/reflext"
sqldialect "github.com/RevenueMonster/sqlike/sql/dialect"
sqldriver "github.com/RevenueMonster/sqlike/sql/driver"
"github.com/RevenueMonster/sqlike/sql/expr"
sqlstmt "github.com/RevenueMonster/sqlike/sql/stmt"
"github.com/RevenueMonster/sqlike/sqlike/actions"
"github.com/RevenueMonster/sqlike/sqlike/logs"
"github.com/RevenueMonster/sqlike/sqlike/options"
)
// ModifyOne :
func (tb *Table) ModifyOne(ctx context.Context, update interface{}, opts ...*options.ModifyOneOptions) error {
return modifyOne(
ctx,
tb.dbName,
tb.name,
tb.pk,
tb.client.cache,
tb.dialect,
tb.driver,
tb.logger,
update,
opts,
)
}
func modifyOne(ctx context.Context, dbName, tbName, pk string, cache reflext.StructMapper, dialect sqldialect.Dialect, driver sqldriver.Driver, logger logs.Logger, update interface{}, opts []*options.ModifyOneOptions) error {
v := reflext.ValueOf(update)
if !v.IsValid() {
return ErrInvalidInput
}
t := v.Type()
if !reflext.IsKind(t, reflect.Ptr) {
return ErrUnaddressableEntity
}
if v.IsNil() {
return ErrNilEntity
}
cdc := cache.CodecByType(t)
opt := new(options.ModifyOneOptions)
if len(opts) > 0 && opts[0] != nil {
opt = opts[0]
}
fields := skipColumns(cdc.Properties(), opt.Omits)
x := new(actions.UpdateActions)
x.Table = tbName
var pkv = [2]interface{}{}
for _, sf := range fields {
fv := cache.FieldByIndexesReadOnly(v, sf.Index())
if _, ok := sf.Tag().LookUp("primary_key"); ok {
if pkv[0] != nil {
x.Set(expr.ColumnValue(pkv[0].(string), pkv[1]))
}
pkv[0] = sf.Name()
pkv[1] = fv.Interface()
continue
}
if sf.Name() == pk && pkv[0] == nil {
pkv[0] = sf.Name()
pkv[1] = fv.Interface()
continue
}
x.Set(expr.ColumnValue(sf.Name(), fv.Interface()))
}
if pkv[0] == nil {
return errors.New("sqlike: missing primary key field")
}
x.Where(expr.Equal(pkv[0], pkv[1]))
x.Limit(1)
x.Table = tbName
x.Database = dbName
stmt := sqlstmt.AcquireStmt(dialect)
defer sqlstmt.ReleaseStmt(stmt)
if err := dialect.Update(stmt, x); err != nil {
return err
}
result, err := sqldriver.Execute(
ctx,
driver,
stmt,
getLogger(logger, opt.Debug),
)
if err != nil {
return err
}
if !opt.NoStrict {
affected, err := result.RowsAffected()
if err != nil {
return err
}
if affected < 1 {
return ErrNoRecordAffected
}
}
return nil
}