-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
insert.go
235 lines (198 loc) · 5.59 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
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package pgq
import (
"bytes"
"errors"
"fmt"
"io"
"sort"
"strings"
)
// InsertBuilder builds SQL INSERT statements.
type InsertBuilder struct {
prefixes []SQLizer
verb string
into string
columns []string
values [][]any
returning []SQLizer
suffixes []SQLizer
selectBuilder *SelectBuilder
}
// Verb to be used for the operation (default: INSERT).
func (b InsertBuilder) Verb(v string) InsertBuilder {
b.verb = v
return b
}
// SQL builds the query into a SQL string and bound args.
func (b InsertBuilder) SQL() (sqlStr string, args []any, err error) {
if b.into == "" {
err = errors.New("insert statements must specify a table")
return
}
if len(b.values) == 0 && b.selectBuilder == nil {
err = errors.New("insert statements must have at least one set of values or select clause")
return
}
sql := &bytes.Buffer{}
if len(b.prefixes) > 0 {
args, err = appendSQL(b.prefixes, sql, " ", args)
if err != nil {
return
}
sql.WriteString(" ")
}
if b.verb != "" {
sql.WriteString(b.verb + " ")
} else {
sql.WriteString("INSERT ")
}
sql.WriteString("INTO ")
sql.WriteString(b.into)
sql.WriteString(" ")
if len(b.columns) > 0 {
sql.WriteString("(")
sql.WriteString(strings.Join(b.columns, ","))
sql.WriteString(") ")
}
if b.selectBuilder != nil {
args, err = b.appendSelectToSQL(sql, args)
} else {
args, err = b.appendValuesToSQL(sql, args)
}
if err != nil {
return
}
if len(b.returning) > 0 {
sql.WriteString(" RETURNING ")
args, err = appendSQL(b.returning, sql, ", ", args)
if err != nil {
return
}
}
if len(b.suffixes) > 0 {
sql.WriteString(" ")
args, err = appendSQL(b.suffixes, sql, " ", args)
if err != nil {
return
}
}
sqlStr, err = dollarPlaceholder(sql.String())
return
}
func (b InsertBuilder) appendValuesToSQL(w io.Writer, args []any) ([]any, error) {
if len(b.values) == 0 {
return args, errors.New("values for insert statements are not set")
}
io.WriteString(w, "VALUES ")
valuesStrings := make([]string, len(b.values))
for r, row := range b.values {
valueStrings := make([]string, len(row))
for v, val := range row {
if vs, ok := val.(SQLizer); ok {
vsql, vargs, err := vs.SQL()
if err != nil {
return nil, err
}
valueStrings[v] = vsql
args = append(args, vargs...)
} else {
valueStrings[v] = "?"
args = append(args, val)
}
}
valuesStrings[r] = fmt.Sprintf("(%s)", strings.Join(valueStrings, ","))
}
io.WriteString(w, strings.Join(valuesStrings, ","))
return args, nil
}
func (b InsertBuilder) appendSelectToSQL(w io.Writer, args []any) ([]any, error) {
if b.selectBuilder == nil {
return args, errors.New("select clause for insert statements are not set")
}
selectClause, sArgs, err := b.selectBuilder.SQL()
if err != nil {
return args, err
}
io.WriteString(w, selectClause)
args = append(args, sArgs...)
return args, nil
}
// MustSQL builds the query into a SQL string and bound args.
// It panics if there are any errors.
func (b InsertBuilder) MustSQL() (string, []any) {
sql, args, err := b.SQL()
if err != nil {
panic(err)
}
return sql, args
}
// Prefix adds an expression to the beginning of the query
func (b InsertBuilder) Prefix(sql string, args ...any) InsertBuilder {
return b.PrefixExpr(Expr(sql, args...))
}
// PrefixExpr adds an expression to the very beginning of the query
func (b InsertBuilder) PrefixExpr(expr SQLizer) InsertBuilder {
b.prefixes = append(b.prefixes, expr)
return b
}
// Into sets the INTO clause of the query.
func (b InsertBuilder) Into(from string) InsertBuilder {
b.into = from
return b
}
// Columns adds insert columns to the query.
func (b InsertBuilder) Columns(columns ...string) InsertBuilder {
b.columns = append(b.columns, columns...)
return b
}
// Values adds a single row's values to the query.
func (b InsertBuilder) Values(values ...any) InsertBuilder {
b.values = append(b.values, values)
return b
}
// Returning adds RETURNING expressions to the query.
func (b InsertBuilder) Returning(columns ...string) InsertBuilder {
parts := make([]SQLizer, 0, len(columns))
for _, col := range columns {
parts = append(parts, newPart(col))
}
b.returning = append(b.returning, parts...)
return b
}
// ReturningSelect adds a RETURNING expressions to the query similar to Using, but takes a Select statement.
func (b InsertBuilder) ReturningSelect(from SelectBuilder, alias string) InsertBuilder {
b.returning = append(b.returning, Alias{Expr: from, As: alias})
return b
}
// Suffix adds an expression to the end of the query
func (b InsertBuilder) Suffix(sql string, args ...any) InsertBuilder {
return b.SuffixExpr(Expr(sql, args...))
}
// SuffixExpr adds an expression to the end of the query
func (b InsertBuilder) SuffixExpr(expr SQLizer) InsertBuilder {
b.suffixes = append(b.suffixes, expr)
return b
}
// SetMap set columns and values for insert builder from a map of column name and value
// note that it will reset all previous columns and values was set if any
func (b InsertBuilder) SetMap(clauses map[string]any) InsertBuilder {
// Keep the columns in a consistent order by sorting the column key string.
cols := make([]string, 0, len(clauses))
for col := range clauses {
cols = append(cols, col)
}
sort.Strings(cols)
vals := make([]any, 0, len(clauses))
for _, col := range cols {
vals = append(vals, clauses[col])
}
b.columns = cols
b.values = [][]any{vals}
return b
}
// Select set Select clause for insert query
// If Values and Select are used, then Select has higher priority
func (b InsertBuilder) Select(sb SelectBuilder) InsertBuilder {
b.selectBuilder = &sb
return b
}