-
Notifications
You must be signed in to change notification settings - Fork 36
/
insert.go
116 lines (97 loc) · 2.41 KB
/
insert.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
package dialect
import (
"fmt"
"io"
"github.com/stephenafamo/bob"
"github.com/stephenafamo/bob/clause"
)
// Trying to represent the query structure as documented in
// https://dev.mysql.com/doc/refman/8.0/en/insert.html
type InsertQuery struct {
hints
modifiers[string]
partitions
clause.Values
Table any
Columns []string
RowAlias string
ColumnAlias []string
Sets []Set
DuplicateKeyUpdate clause.Set
}
func (i InsertQuery) WriteSQL(w io.Writer, d bob.Dialect, start int) ([]any, error) {
var args []any
var err error
w.Write([]byte("INSERT "))
// no optimizer hint args
_, err = bob.ExpressIf(w, d, start+len(args), i.hints,
len(i.hints.hints) > 0, "\n", "\n")
if err != nil {
return nil, err
}
// no modifiers args
_, err = bob.ExpressIf(w, d, start+len(args), i.modifiers,
len(i.modifiers.modifiers) > 0, "", " ")
if err != nil {
return nil, err
}
// no expected table args
_, err = bob.ExpressIf(w, d, start+len(args), i.Table, true, "INTO ", " ")
if err != nil {
return nil, err
}
// no partition args
_, err = bob.ExpressIf(w, d, start+len(args), i.partitions,
len(i.partitions.partitions) > 0, "", " ")
if err != nil {
return nil, err
}
// No columns args
if len(i.Columns) > 0 {
w.Write([]byte(" ("))
for k, cAlias := range i.Columns {
if k != 0 {
w.Write([]byte(", "))
}
d.WriteQuoted(w, cAlias)
}
w.Write([]byte(")"))
}
// Either this or the values will get expressed
setArgs, err := bob.ExpressSlice(w, d, start+len(args), i.Sets, "\nSET ", "\n", " ")
if err != nil {
return nil, err
}
args = append(args, setArgs...)
// Either this or SET will get expressed
valArgs, err := bob.ExpressIf(w, d, start+len(args), i.Values, len(i.Sets) == 0, "\n", " ")
if err != nil {
return nil, err
}
args = append(args, valArgs...)
// The aliases
if i.RowAlias != "" {
_, err = fmt.Fprintf(w, "\nAS %s", i.RowAlias)
if err != nil {
return nil, err
}
if len(i.ColumnAlias) > 0 {
w.Write([]byte("("))
for k, cAlias := range i.ColumnAlias {
if k != 0 {
w.Write([]byte(", "))
}
d.WriteQuoted(w, cAlias)
}
w.Write([]byte(")"))
}
}
updateArgs, err := bob.ExpressSlice(w, d, start+len(args), i.DuplicateKeyUpdate.Set,
"\nON DUPLICATE KEY UPDATE\n", ",\n", "")
if err != nil {
return nil, err
}
args = append(args, updateArgs...)
w.Write([]byte("\n"))
return args, nil
}