Add auto timestamps for upsert

* Add IsZero checks for auto timestamps
This commit is contained in:
Patrick O'brien 2016-08-29 23:22:23 +10:00
parent 7f24185544
commit ccdfc93fee
2 changed files with 52 additions and 6 deletions

View file

@ -26,6 +26,8 @@ func (o *{{$tableNameSingular}}) Upsert(exec boil.Executor, updateOnConflict boo
return errors.New("{{.PkgName}}: no {{.Table.Name}} provided for upsert")
}
{{- template "timestamp_upsert_helper" . }}
{{if not .NoHooks -}}
if err := o.doBeforeUpsertHooks(exec); err != nil {
return err

View file

@ -12,18 +12,26 @@
{{range $ind, $col := .Table.Columns}}
{{- if eq $col.Name "created_at" -}}
{{- if $col.Nullable}}
o.CreatedAt.Time = currTime
o.CreatedAt.Valid = true
if o.CreatedAt.Time.IsZero() {
o.CreatedAt.Time = currTime
o.CreatedAt.Valid = true
}
{{- else}}
o.CreatedAt = currTime
if o.CreatedAt.IsZero() {
o.CreatedAt = currTime
}
{{- end -}}
{{- end -}}
{{- if eq $col.Name "updated_at" -}}
{{- if $col.Nullable}}
o.UpdatedAt.Time = currTime
o.UpdatedAt.Valid = true
if o.UpdatedAt.Time.IsZero() {
o.UpdatedAt.Time = currTime
o.UpdatedAt.Valid = true
}
{{- else}}
o.UpdatedAt = currTime
if o.UpdatedAt.IsZero() {
o.UpdatedAt = currTime
}
{{- end -}}
{{- end -}}
{{end}}
@ -54,3 +62,39 @@
{{end}}
{{- end}}
{{end -}}
{{- define "timestamp_upsert_helper" -}}
{{- if not .NoAutoTimestamps -}}
{{- $colNames := .Table.Columns | columnNames -}}
{{if containsAny $colNames "created_at" "updated_at"}}
loc := boil.GetLocation()
currTime := time.Time{}
if loc != nil {
currTime = time.Now().In(boil.GetLocation())
} else {
currTime = time.Now()
}
{{range $ind, $col := .Table.Columns}}
{{- if eq $col.Name "created_at" -}}
{{- if $col.Nullable}}
if o.CreatedAt.Time.IsZero() {
o.CreatedAt.Time = currTime
o.CreatedAt.Valid = true
}
{{- else}}
if o.CreatedAt.IsZero() {
o.CreatedAt = currTime
}
{{- end -}}
{{- end -}}
{{- if eq $col.Name "updated_at" -}}
{{- if $col.Nullable}}
o.UpdatedAt.Time = currTime
o.UpdatedAt.Valid = true
{{- else}}
o.UpdatedAt = currTime
{{- end -}}
{{- end -}}
{{end}}
{{end}}
{{- end}}
{{end -}}