3
0

Fix create and update with unique constraints

When creating or updating resource that did not match unique constraint
filters, check wrongly reported not-unique error when matching (and
valid) resource was found in the store.

This fix adds explicit check if resource to be stored does not match
constraint filters and skips the rest of the constraint checking
procedure.
This commit is contained in:
Denis Arh
2021-10-12 19:49:45 +02:00
parent 1fa84826c3
commit 59ffe768a8
42 changed files with 506 additions and 37 deletions

View File

@@ -729,20 +729,36 @@ func (s *Store) check{{ export $.Types.Singular }}Constraints(ctx context.Contex
return nil
}
var checks = make([]func () error, 0)
{{- range $.Lookups }}
{{ if .UniqueConstraintCheck }}
{
checks = append(checks, func () error {
// Skip lookup by {{ .Suffix }} if {{ export $.Types.Singular }} does not match filters
{{- range $field, $value := .Filter }}
if res.{{ $field }} != {{ $value }} {
return nil
}
{{ end }}
ex, err := s.{{ toggleExport .Export "Lookup" $.Types.Singular "By" .Suffix }}(ctx{{ template "extraArgsCall" $ }}{{- range .RDBMSColumns }}, res.{{ .Field }} {{- end }})
if err == nil && ex != nil {{- range $.RDBMS.Columns.PrimaryKeyFields }} && ex.{{ .Field }} != res.{{ .Field }} {{ end }} {
return store.ErrNotUnique.Stack(1)
} else if !errors.IsNotFound(err) {
return err
}
}
return nil
})
{{ end }}
{{ end }}
for _, check := range checks {
if err := check(); err != nil {
return err
}
}
return nil
}