-
Notifications
You must be signed in to change notification settings - Fork 37
/
update.go
84 lines (69 loc) · 1.78 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
package dialect
import (
"io"
"github.com/stephenafamo/bob"
"github.com/stephenafamo/bob/clause"
)
// Trying to represent the select query structure as documented in
// https://www.postgresql.org/docs/current/sql-update.html
type UpdateQuery struct {
hints
modifiers[any]
clause.With
clause.Set
clause.From
clause.Where
clause.OrderBy
clause.Limit
}
func (u UpdateQuery) WriteSQL(w io.Writer, d bob.Dialect, start int) ([]any, error) {
var args []any
withArgs, err := bob.ExpressIf(w, d, start+len(args), u.With,
len(u.With.CTEs) > 0, "\n", "")
if err != nil {
return nil, err
}
args = append(args, withArgs...)
w.Write([]byte("UPDATE"))
// no optimizer hint args
_, err = bob.ExpressIf(w, d, start+len(args), u.hints,
len(u.hints.hints) > 0, "\n", "\n")
if err != nil {
return nil, err
}
// no modifiers args
_, err = bob.ExpressIf(w, d, start+len(args), u.modifiers,
len(u.modifiers.modifiers) > 0, " ", "")
if err != nil {
return nil, err
}
fromArgs, err := bob.ExpressIf(w, d, start+len(args), u.From,
u.From.Table != nil, " ", "")
if err != nil {
return nil, err
}
args = append(args, fromArgs...)
setArgs, err := bob.ExpressIf(w, d, start+len(args), u.Set, true, " SET\n", "")
if err != nil {
return nil, err
}
args = append(args, setArgs...)
whereArgs, err := bob.ExpressIf(w, d, start+len(args), u.Where,
len(u.Where.Conditions) > 0, "\n", "")
if err != nil {
return nil, err
}
args = append(args, whereArgs...)
orderArgs, err := bob.ExpressIf(w, d, start+len(args), u.OrderBy,
len(u.OrderBy.Expressions) > 0, "\n", "")
if err != nil {
return nil, err
}
args = append(args, orderArgs...)
_, err = bob.ExpressIf(w, d, start+len(args), u.Limit,
u.Limit.Count != nil, "\n", "")
if err != nil {
return nil, err
}
return args, nil
}