sqlboiler/templates/17_upsert.tpl

239 lines
7.8 KiB
Smarty
Raw Normal View History

2016-08-04 05:11:45 +02:00
{{- $tableNameSingular := .Table.Name | singular | titleCase -}}
{{- $varNameSingular := .Table.Name | singular | camelCase -}}
{{- $schemaTable := .Table.Name | .SchemaTable}}
2016-08-04 05:11:45 +02:00
// UpsertG attempts an insert, and does an update or ignore on conflict.
2017-03-21 11:04:07 +01:00
func (o *{{$tableNameSingular}}) UpsertG({{if eq .DriverName "postgres"}}updateOnConflict bool, conflictColumns []string, {{end}}updateColumns []string, whitelist ...string) error {
return o.Upsert(boil.GetDB(), {{if eq .DriverName "postgres"}}updateOnConflict, conflictColumns, {{end}}updateColumns, whitelist...)
2016-08-04 05:11:45 +02:00
}
// UpsertGP attempts an insert, and does an update or ignore on conflict. Panics on error.
2017-03-21 11:04:07 +01:00
func (o *{{$tableNameSingular}}) UpsertGP({{if eq .DriverName "postgres"}}updateOnConflict bool, conflictColumns []string, {{end}}updateColumns []string, whitelist ...string) {
if err := o.Upsert(boil.GetDB(), {{if eq .DriverName "postgres"}}updateOnConflict, conflictColumns, {{end}}updateColumns, whitelist...); err != nil {
2016-09-14 17:36:36 +02:00
panic(boil.WrapErr(err))
}
2016-08-04 05:11:45 +02:00
}
// UpsertP attempts an insert using an executor, and does an update or ignore on conflict.
// UpsertP panics on error.
2017-03-21 11:04:07 +01:00
func (o *{{$tableNameSingular}}) UpsertP(exec boil.Executor, {{if eq .DriverName "postgres"}}updateOnConflict bool, conflictColumns []string, {{end}}updateColumns []string, whitelist ...string) {
if err := o.Upsert(exec, {{if eq .DriverName "postgres"}}updateOnConflict, conflictColumns, {{end}}updateColumns, whitelist...); err != nil {
2016-09-14 17:36:36 +02:00
panic(boil.WrapErr(err))
}
}
2016-09-15 08:03:05 +02:00
2016-08-04 05:11:45 +02:00
// Upsert attempts an insert using an executor, and does an update or ignore on conflict.
2017-03-21 11:04:07 +01:00
func (o *{{$tableNameSingular}}) Upsert(exec boil.Executor, {{if eq .DriverName "postgres"}}updateOnConflict bool, conflictColumns []string, {{end}}updateColumns []string, whitelist ...string) error {
if o == nil {
2016-09-14 17:36:36 +02:00
return errors.New("{{.PkgName}}: no {{.Table.Name}} provided for upsert")
}
{{- template "timestamp_upsert_helper" . }}
{{if not .NoHooks -}}
if err := o.doBeforeUpsertHooks(exec); err != nil {
2016-09-14 17:36:36 +02:00
return err
}
{{- end}}
2016-08-04 05:11:45 +02:00
nzDefaults := queries.NonZeroDefaultSet({{$varNameSingular}}ColumnsWithDefault, o)
2016-09-15 08:03:05 +02:00
// Build cache key in-line uglily - mysql vs postgres problems
buf := strmangle.GetBuffer()
2017-03-21 11:04:07 +01:00
{{if eq .DriverName "postgres"}}
2016-09-15 08:03:05 +02:00
if updateOnConflict {
buf.WriteByte('t')
} else {
buf.WriteByte('f')
}
buf.WriteByte('.')
for _, c := range conflictColumns {
buf.WriteString(c)
}
buf.WriteByte('.')
{{end -}}
for _, c := range updateColumns {
buf.WriteString(c)
}
buf.WriteByte('.')
for _, c := range whitelist {
buf.WriteString(c)
}
buf.WriteByte('.')
for _, c := range nzDefaults {
buf.WriteString(c)
}
2016-09-15 08:03:05 +02:00
key := buf.String()
strmangle.PutBuffer(buf)
{{$varNameSingular}}UpsertCacheMut.RLock()
cache, cached := {{$varNameSingular}}UpsertCache[key]
{{$varNameSingular}}UpsertCacheMut.RUnlock()
var err error
2016-09-15 08:03:05 +02:00
if !cached {
2017-03-21 11:04:07 +01:00
insert, ret := strmangle.InsertColumnSet(
2016-09-15 08:03:05 +02:00
{{$varNameSingular}}Columns,
{{$varNameSingular}}ColumnsWithDefault,
{{$varNameSingular}}ColumnsWithoutDefault,
nzDefaults,
2016-09-15 08:03:05 +02:00
whitelist,
)
{{if eq .DriverName "mssql" -}}
2017-03-21 11:04:07 +01:00
insert = strmangle.SetComplement(insert, {{$varNameSingular}}ColumnsWithAuto)
for i, v := range insert {
if strmangle.ContainsAny({{$varNameSingular}}PrimaryKeyColumns, v) && strmangle.ContainsAny({{$varNameSingular}}ColumnsWithDefault, v) {
insert = append(insert[:i], insert[i+1:]...)
}
}
if len(insert) == 0 {
2017-03-31 09:52:54 +02:00
return errors.New("{{.PkgName}}: unable to upsert {{.Table.Name}}, could not build insert column list")
2017-03-21 11:04:07 +01:00
}
ret = strmangle.SetMerge(ret, {{$varNameSingular}}ColumnsWithAuto)
ret = strmangle.SetMerge(ret, {{$varNameSingular}}ColumnsWithDefault)
2017-04-05 04:40:12 +02:00
{{end}}
2016-09-15 08:03:05 +02:00
update := strmangle.UpdateColumnSet(
{{$varNameSingular}}Columns,
{{$varNameSingular}}PrimaryKeyColumns,
updateColumns,
)
{{if eq .DriverName "mssql" -}}
2017-03-21 11:04:07 +01:00
update = strmangle.SetComplement(update, {{$varNameSingular}}ColumnsWithAuto)
{{end -}}
2017-04-05 04:40:12 +02:00
if len(update) == 0 {
return errors.New("{{.PkgName}}: unable to upsert {{.Table.Name}}, could not build update column list")
}
2016-09-15 08:03:05 +02:00
2017-03-21 11:04:07 +01:00
{{if eq .DriverName "postgres"}}
2016-09-21 06:22:35 +02:00
conflict := conflictColumns
if len(conflict) == 0 {
2016-09-15 08:03:05 +02:00
conflict = make([]string, len({{$varNameSingular}}PrimaryKeyColumns))
copy(conflict, {{$varNameSingular}}PrimaryKeyColumns)
}
2017-03-21 11:04:07 +01:00
cache.query = queries.BuildUpsertQueryPostgres(dialect, "{{$schemaTable}}", updateOnConflict, ret, update, conflict, insert)
2017-03-31 09:59:03 +02:00
{{else if eq .DriverName "mysql"}}
cache.query = queries.BuildUpsertQueryMySQL(dialect, "{{.Table.Name}}", update, insert, {{$varNameSingular}}AutoIncrementColumn)
2016-09-15 08:03:05 +02:00
cache.retQuery = fmt.Sprintf(
"SELECT %s FROM {{.LQ}}{{.Table.Name}}{{.RQ}} WHERE {{whereClause .LQ .RQ 0 .Table.PKey.Columns}}",
strings.Join(strmangle.IdentQuoteSlice(dialect.LQ, dialect.RQ, ret), ","),
)
2017-03-31 09:59:03 +02:00
{{else if eq .DriverName "mssql"}}
2017-03-21 11:04:07 +01:00
cache.query = queries.BuildUpsertQueryMSSQL(dialect, "{{.Table.Name}}", {{$varNameSingular}}PrimaryKeyColumns, update, insert, ret)
whitelist = append({{$varNameSingular}}PrimaryKeyColumns, update...)
whitelist = append(whitelist, insert...)
2016-09-15 08:03:05 +02:00
{{- end}}
cache.valueMapping, err = queries.BindMapping({{$varNameSingular}}Type, {{$varNameSingular}}Mapping, {{if eq .DriverName "mssql"}}whitelist{{else}}insert{{end}})
2016-09-15 08:03:05 +02:00
if err != nil {
return err
}
if len(ret) != 0 {
cache.retMapping, err = queries.BindMapping({{$varNameSingular}}Type, {{$varNameSingular}}Mapping, ret)
if err != nil {
return err
}
}
}
value := reflect.Indirect(reflect.ValueOf(o))
2016-09-25 01:10:26 +02:00
vals := queries.ValuesFromMapping(value, cache.valueMapping)
2016-09-15 08:03:05 +02:00
var returns []interface{}
if len(cache.retMapping) != 0 {
returns = queries.PtrsFromMapping(value, cache.retMapping)
}
if boil.DebugMode {
qStr, err := interpolateParams(cache.query, vals...)
if err != nil {
return err
}
fmt.Fprintln(boil.DebugWriter, qStr)
}
2016-08-04 05:11:45 +02:00
2016-09-25 01:10:26 +02:00
{{if .UseLastInsertID -}}
{{- $canLastInsertID := .Table.CanLastInsertID -}}
{{if $canLastInsertID -}}
result, err := exec.Exec(cache.query, vals...)
{{else -}}
_, err = exec.Exec(cache.query, vals...)
{{- end}}
2016-09-14 17:36:36 +02:00
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to upsert for {{.Table.Name}}")
}
2016-08-13 18:58:18 +02:00
2016-09-25 01:10:26 +02:00
{{if $canLastInsertID -}}
var lastID int64
2016-09-25 01:10:26 +02:00
{{- end}}
var identifierCols []interface{}
2016-09-25 01:10:26 +02:00
2016-09-15 08:03:05 +02:00
if len(cache.retMapping) == 0 {
goto CacheNoHooks
}
2016-08-04 05:11:45 +02:00
2016-09-25 01:10:26 +02:00
{{if $canLastInsertID -}}
lastID, err = result.LastInsertId()
if err != nil {
2016-09-14 17:36:36 +02:00
return ErrSyncFail
}
2016-09-14 17:36:36 +02:00
2016-09-25 01:10:26 +02:00
{{$colName := index .Table.PKey.Columns 0 -}}
2016-09-17 05:13:44 +02:00
{{- $col := .Table.GetColumn $colName -}}
2016-09-25 01:10:26 +02:00
{{- $colTitled := $colName | titleCase}}
2016-09-17 05:13:44 +02:00
o.{{$colTitled}} = {{$col.Type}}(lastID)
2016-09-25 01:10:26 +02:00
if lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == {{$varNameSingular}}Mapping["{{$colTitled}}"] {
goto CacheNoHooks
}
{{- end}}
2016-09-17 05:13:44 +02:00
identifierCols = []interface{}{
{{range .Table.PKey.Columns -}}
2016-09-25 01:10:26 +02:00
o.{{. | titleCase}},
2016-09-17 05:13:44 +02:00
{{end -}}
}
2016-09-14 17:36:36 +02:00
2016-09-25 01:10:26 +02:00
if boil.DebugMode {
qStr, err := interpolateParams(cache.retQuery, identifierCols...)
if err != nil {
return err
}
fmt.Fprintln(boil.DebugWriter, qStr)
2016-09-25 01:10:26 +02:00
}
2016-09-14 17:36:36 +02:00
2016-09-25 01:10:26 +02:00
err = exec.QueryRow(cache.retQuery, identifierCols...).Scan(returns...)
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to populate default values for {{.Table.Name}}")
}
2016-09-14 17:36:36 +02:00
{{- else}}
2016-09-15 08:03:05 +02:00
if len(cache.retMapping) != 0 {
2016-09-25 01:10:26 +02:00
err = exec.QueryRow(cache.query, vals...).Scan(returns...)
if err == sql.ErrNoRows {
err = nil // Postgres doesn't return anything when there's no update
}
2016-09-14 17:36:36 +02:00
} else {
2016-09-25 01:10:26 +02:00
_, err = exec.Exec(cache.query, vals...)
2016-09-14 17:36:36 +02:00
}
if err != nil {
return errors.Wrap(err, "{{.PkgName}}: unable to upsert {{.Table.Name}}")
}
{{- end}}
2016-08-04 05:11:45 +02:00
{{if .UseLastInsertID -}}
CacheNoHooks:
{{end -}}
2016-09-15 08:03:05 +02:00
if !cached {
{{$varNameSingular}}UpsertCacheMut.Lock()
{{$varNameSingular}}UpsertCache[key] = cache
{{$varNameSingular}}UpsertCacheMut.Unlock()
}
{{if not .NoHooks -}}
2016-09-15 06:59:48 +02:00
return o.doAfterUpsertHooks(exec)
{{- else -}}
return nil
2016-09-15 06:59:48 +02:00
{{- end}}
2017-03-31 10:05:52 +02:00
}