-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert_build.go
More file actions
88 lines (77 loc) · 1.86 KB
/
insert_build.go
File metadata and controls
88 lines (77 loc) · 1.86 KB
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
package squildx
import "strings"
func (b *insertBuilder) Build() (string, Params, error) {
if b.err != nil {
return "", nil, b.err
}
if b.table == "" {
return "", nil, ErrNoTable
}
if len(b.columns) == 0 {
return "", nil, ErrNoInsertColumns
}
hasValues := len(b.valueRows) > 0
hasSelect := b.selectQuery != nil
switch {
case hasValues && hasSelect:
return "", nil, ErrValuesAndSelect
case !hasValues && !hasSelect:
return "", nil, ErrNoInsertValues
}
params := make(Params)
var sb strings.Builder
sb.WriteString("INSERT INTO ")
sb.WriteString(b.table)
sb.WriteString(" (")
sb.WriteString(strings.Join(b.columns, ", "))
sb.WriteString(")")
switch {
case hasValues:
sb.WriteString(" VALUES ")
for i, row := range b.valueRows {
if i > 0 {
sb.WriteString(", ")
}
sb.WriteString("(")
sb.WriteString(row.sql)
sb.WriteString(")")
if err := mergeParams(params, row.params); err != nil {
return "", nil, err
}
}
case hasSelect:
subSQL, subParams, err := b.selectQuery.Build()
if err != nil {
return "", nil, err
}
subPrefix := detectPrefix(subSQL)
if _, err := reconcilePrefix(b.paramPrefix, subPrefix); err != nil {
return "", nil, err
}
sb.WriteString(" ")
sb.WriteString(subSQL)
if err := mergeParams(params, subParams); err != nil {
return "", nil, err
}
}
if b.conflict != nil {
sb.WriteString(" ON CONFLICT (")
sb.WriteString(strings.Join(b.conflict.columns, ", "))
sb.WriteString(")")
switch {
case b.conflict.doUpdate:
sb.WriteString(" DO UPDATE SET ")
sb.WriteString(b.conflict.set)
if err := mergeParams(params, b.conflict.params); err != nil {
return "", nil, err
}
default:
sb.WriteString(" DO NOTHING")
}
}
if len(b.returnings) > 0 {
sb.WriteString(" RETURNING ")
sb.WriteString(strings.Join(b.returnings, ", "))
}
return sb.String(), params, nil
}