-
Notifications
You must be signed in to change notification settings - Fork 558
Expand file tree
/
Copy path17_upsert.go.tpl
More file actions
232 lines (201 loc) · 7.32 KB
/
17_upsert.go.tpl
File metadata and controls
232 lines (201 loc) · 7.32 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
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
{{- if or (not .Table.IsView) .Table.ViewCapabilities.CanUpsert -}}
{{- $alias := .Aliases.Table .Table.Name}}
{{- $schemaTable := .Table.Name | .SchemaTable}}
{{if .AddGlobal -}}
// UpsertG attempts an insert, and does an update or ignore on conflict.
func (o *{{$alias.UpSingular}}) UpsertG({{if not .NoContext}}ctx context.Context, {{end -}} updateColumns, insertColumns boil.Columns) error {
return o.Upsert({{if .NoContext}}boil.GetDB(){{else}}ctx, boil.GetContextDB(){{end}}, updateColumns, insertColumns)
}
{{end -}}
{{if and .AddGlobal .AddPanic -}}
// UpsertGP attempts an insert, and does an update or ignore on conflict. Panics on error.
func (o *{{$alias.UpSingular}}) UpsertGP({{if not .NoContext}}ctx context.Context, {{end -}} updateColumns, insertColumns boil.Columns) {
if err := o.Upsert({{if .NoContext}}boil.GetDB(){{else}}ctx, boil.GetContextDB(){{end}}, updateColumns, insertColumns); err != nil {
panic(boil.WrapErr(err))
}
}
{{end -}}
{{if .AddPanic -}}
// UpsertP attempts an insert using an executor, and does an update or ignore on conflict.
// UpsertP panics on error.
func (o *{{$alias.UpSingular}}) UpsertP({{if .NoContext}}exec boil.Executor{{else}}ctx context.Context, exec boil.ContextExecutor{{end}}, updateColumns, insertColumns boil.Columns) {
if err := o.Upsert({{if not .NoContext}}ctx, {{end -}} exec, updateColumns, insertColumns); err != nil {
panic(boil.WrapErr(err))
}
}
{{end -}}
var mySQL{{$alias.UpSingular}}UniqueColumns = []string{
{{- range $i, $col := .Table.Columns -}}
{{- if $col.Unique}}
"{{$col.Name}}",
{{- end -}}
{{- end}}
}
// Upsert attempts an insert using an executor, and does an update or ignore on conflict.
// See boil.Columns documentation for how to properly use updateColumns and insertColumns.
func (o *{{$alias.UpSingular}}) Upsert({{if .NoContext}}exec boil.Executor{{else}}ctx context.Context, exec boil.ContextExecutor{{end}}, updateColumns, insertColumns boil.Columns) error {
if o == nil {
return errors.New("{{.PkgName}}: no {{.Table.Name}} provided for upsert")
}
{{- template "timestamp_upsert_helper" . }}
{{if not .NoHooks -}}
if err := o.doBeforeUpsertHooks({{if not .NoContext}}ctx, {{end -}} exec); err != nil {
return err
}
{{- end}}
nzDefaults := queries.NonZeroDefaultSet({{$alias.DownSingular}}ColumnsWithDefault, o)
nzUniques := queries.NonZeroDefaultSet(mySQL{{$alias.UpSingular}}UniqueColumns, o)
if len(nzUniques) == 0 {
return errors.New("cannot upsert with a table that cannot conflict on a unique column")
}
// Build cache key in-line uglily - mysql vs psql problems
buf := strmangle.GetBuffer()
buf.WriteString(strconv.Itoa(updateColumns.Kind))
for _, c := range updateColumns.Cols {
buf.WriteString(c)
}
buf.WriteByte('.')
buf.WriteString(strconv.Itoa(insertColumns.Kind))
for _, c := range insertColumns.Cols {
buf.WriteString(c)
}
buf.WriteByte('.')
for _, c := range nzDefaults {
buf.WriteString(c)
}
buf.WriteByte('.')
for _, c := range nzUniques {
buf.WriteString(c)
}
key := buf.String()
strmangle.PutBuffer(buf)
{{$alias.DownSingular}}UpsertCacheMut.RLock()
cache, cached := {{$alias.DownSingular}}UpsertCache[key]
{{$alias.DownSingular}}UpsertCacheMut.RUnlock()
var err error
if !cached {
insert, ret := insertColumns.InsertColumnSet(
{{$alias.DownSingular}}AllColumns,
{{$alias.DownSingular}}ColumnsWithDefault,
{{$alias.DownSingular}}ColumnsWithoutDefault,
nzDefaults,
)
update := updateColumns.UpdateColumnSet(
{{$alias.DownSingular}}AllColumns,
{{$alias.DownSingular}}PrimaryKeyColumns,
)
{{if filterColumnsByAuto true .Table.Columns }}
insert = strmangle.SetComplement(insert, {{$alias.DownSingular}}GeneratedColumns)
update = strmangle.SetComplement(update, {{$alias.DownSingular}}GeneratedColumns)
{{- end }}
if !updateColumns.IsNone() && len(update) == 0 {
return errors.New("{{.PkgName}}: unable to upsert {{.Table.Name}}, could not build update column list")
}
ret = strmangle.SetComplement(ret, nzUniques)
cache.query = buildUpsertQueryMySQL(dialect, "{{$schemaTable}}", update, insert)
cache.retQuery = fmt.Sprintf(
"SELECT %s FROM {{.LQ}}{{.Table.Name}}{{.RQ}} WHERE %s",
strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, ret), ","),
strmangle.WhereClause("{{.LQ}}", "{{.RQ}}", 0, nzUniques),
)
cache.valueMapping, err = queries.BindMapping({{$alias.DownSingular}}Type, {{$alias.DownSingular}}Mapping, insert)
if err != nil {
return err
}
if len(ret) != 0 {
cache.retMapping, err = queries.BindMapping({{$alias.DownSingular}}Type, {{$alias.DownSingular}}Mapping, ret)
if err != nil {
return err
}
}
}
value := reflect.Indirect(reflect.ValueOf(o))
vals := queries.ValuesFromMapping(value, cache.valueMapping)
var returns []interface{}
if len(cache.retMapping) != 0 {
returns = queries.PtrsFromMapping(value, cache.retMapping)
}
{{if .NoContext -}}
if boil.DebugMode {
boil.PrintQuery(boil.DebugWriter, cache.query, vals...)
}
{{else -}}
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
boil.PrintQuery(writer, cache.query, vals...)
}
{{end -}}
{{$canLastInsertID := .Table.CanLastInsertID -}}
{{if $canLastInsertID -}}
{{if .NoContext -}}
result, err := exec.Exec(cache.query, vals...)
{{else -}}
result, err := exec.ExecContext(ctx, cache.query, vals...)
{{end -}}
{{else -}}
{{if .NoContext -}}
_, err = exec.Exec(cache.query, vals...)
{{else -}}
_, err = exec.ExecContext(ctx, cache.query, vals...)
{{end -}}
{{- end}}
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to upsert for {{.Table.Name}}")
}
{{if $canLastInsertID -}}
var lastID int64
{{- end}}
var uniqueMap []uint64
var nzUniqueCols []interface{}
if len(cache.retMapping) == 0 {
goto CacheNoHooks
}
{{if $canLastInsertID -}}
lastID, err = result.LastInsertId()
if err != nil {
return ErrSyncFail
}
{{$colName := index .Table.PKey.Columns 0 -}}
{{- $col := .Table.GetColumn $colName -}}
{{- $colTitled := $alias.Column $colName}}
o.{{$colTitled}} = {{$col.Type}}(lastID)
if lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == {{$alias.DownSingular}}Mapping["{{$colName}}"] {
goto CacheNoHooks
}
{{- end}}
uniqueMap, err = queries.BindMapping({{$alias.DownSingular}}Type, {{$alias.DownSingular}}Mapping, nzUniques)
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to retrieve unique values for {{.Table.Name}}")
}
nzUniqueCols = queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), uniqueMap)
{{if .NoContext -}}
if boil.DebugMode {
boil.PrintQuery(boil.DebugWriter, cache.retQuery, nzUniqueCols...)
}
{{else -}}
if boil.IsDebug(ctx) {
writer := boil.DebugWriterFrom(ctx)
boil.PrintQuery(writer, cache.retQuery, nzUniqueCols...)
}
{{end -}}
{{if .NoContext -}}
err = exec.QueryRow(cache.retQuery, nzUniqueCols...).Scan(returns...)
{{else -}}
err = exec.QueryRowContext(ctx, cache.retQuery, nzUniqueCols...).Scan(returns...)
{{end -}}
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to populate default values for {{.Table.Name}}")
}
CacheNoHooks:
if !cached {
{{$alias.DownSingular}}UpsertCacheMut.Lock()
{{$alias.DownSingular}}UpsertCache[key] = cache
{{$alias.DownSingular}}UpsertCacheMut.Unlock()
}
{{if not .NoHooks -}}
return o.doAfterUpsertHooks({{if not .NoContext}}ctx, {{end -}} exec)
{{- else -}}
return nil
{{- end}}
}
{{end}}