-
-
Notifications
You must be signed in to change notification settings - Fork 397
/
update.go
120 lines (95 loc) · 1.95 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
package orm
import (
"errors"
"github.com/go-pg/pg/internal"
)
func Update(db DB, model interface{}) error {
res, err := NewQuery(db, model).Update()
if err != nil {
return err
}
return internal.AssertOneRow(res.RowsAffected())
}
type updateQuery struct {
q *Query
}
var _ QueryAppender = (*updateQuery)(nil)
func (q updateQuery) Copy() QueryAppender {
return updateQuery{
q: q.q.Copy(),
}
}
func (q updateQuery) Query() *Query {
return q.q
}
func (q updateQuery) AppendQuery(b []byte) ([]byte, error) {
if q.q.stickyErr != nil {
return nil, q.q.stickyErr
}
var err error
if len(q.q.with) > 0 {
b, err = q.q.appendWith(b, "")
if err != nil {
return nil, err
}
}
b = append(b, "UPDATE "...)
b = q.q.appendFirstTable(b)
b, err = q.mustAppendSet(b)
if err != nil {
return nil, err
}
if q.q.hasOtherTables() {
b = append(b, " FROM "...)
b = q.q.appendOtherTables(b)
}
b, err = q.q.mustAppendWhere(b)
if err != nil {
return nil, err
}
if len(q.q.returning) > 0 {
b = q.q.appendReturning(b)
}
return b, nil
}
func (q updateQuery) mustAppendSet(b []byte) ([]byte, error) {
if len(q.q.set) > 0 {
b = q.q.appendSet(b)
return b, nil
}
if q.q.model == nil {
return nil, errors.New("pg: Model(nil)")
}
b = append(b, " SET "...)
table := q.q.model.Table()
strct := q.q.model.Value()
if fields := q.q.getFields(); len(fields) > 0 {
for i, fieldName := range fields {
field, err := table.GetField(fieldName)
if err != nil {
return nil, err
}
if i > 0 {
b = append(b, ", "...)
}
b = append(b, field.ColName...)
b = append(b, " = "...)
b = field.AppendValue(b, strct, 1)
}
return b, nil
}
start := len(b)
for _, field := range table.Fields {
if field.HasFlag(PrimaryKeyFlag) {
continue
}
b = append(b, field.ColName...)
b = append(b, " = "...)
b = field.AppendValue(b, strct, 1)
b = append(b, ", "...)
}
if len(b) > start {
b = b[:len(b)-2]
}
return b, nil
}