{{/*
Copyright 2019-present Facebook Inc. All rights reserved.
This source code is licensed under the Apache 2.0 license found
in the LICENSE file in the root directory of this source tree.
*/}}

{{ define "delete" }}
{{ $pkg := base $.Config.Package }}

{{ template "header" $ }}

{{ template "import" $ }}

{{ $builder := print (pascal $.Name) "Delete" }}
{{ $receiver := receiver $builder }}
// {{ $builder }} is the builder for deleting a {{ pascal $.Name }} entity.
type {{ $builder }} struct {
	config
	predicates []predicate.{{ $.Name }}
}


// Where adds a new predicate to the delete builder.
func ({{ $receiver}} *{{ $builder }}) Where(ps ...predicate.{{ $.Name }}) *{{ $builder }} {
	{{ $receiver}}.predicates = append({{ $receiver}}.predicates, ps...)
	return {{ $receiver }}
}

// Exec executes the deletion query and returns how many vertices were deleted.
func ({{ $receiver}} *{{ $builder }}) Exec(ctx context.Context) (int, error) {
	{{- if $.MultiStorage -}}
		switch {{ $receiver }}.driver.Dialect() {
		{{- range $_, $storage := $.Storage }}
		case {{ join $storage.Dialects ", " }}:
			return {{ $receiver }}.{{ $storage }}Exec(ctx)
		{{- end }}
		default:
			return 0, errors.New("{{ $pkg }}: unsupported dialect")
		}
	{{- else -}}
		return {{ $receiver }}.{{ index $.Storage 0 }}Exec(ctx)
	{{- end }}
}

// ExecX is like Exec, but panics if an error occurs.
func ({{ $receiver }} *{{ $builder }}) ExecX(ctx context.Context) int {
	n, err := {{ $receiver }}.Exec(ctx)
	if err != nil {
		panic(err)
	}
	return n
}

{{- range $_, $storage := $.Storage }}
	{{ with extend $ "Builder" $builder }}
		{{ $tmpl := printf "dialect/%s/delete" $storage }}
		{{ xtemplate $tmpl . }}
	{{ end }}
{{ end }}

{{ $onebuilder := print $builder "One" }}
{{ $oneReceiver := receiver $onebuilder }}

// {{ $onebuilder }} is the builder for deleting a single {{ $.Name }} entity.
type {{ $onebuilder }} struct {
	{{ $receiver }} *{{ $builder }}
}

// Exec executes the deletion query.
func ({{ $oneReceiver }} *{{ $onebuilder }}) Exec(ctx context.Context) error {
	n, err := {{ $oneReceiver }}.{{ $receiver }}.Exec(ctx)
	switch {
	case err != nil:
		return err
	case n == 0:
		return &ErrNotFound{ {{ $.Package }}.Label}
	default:
		return nil
	}
}

// ExecX is like Exec, but panics if an error occurs.
func ({{ $oneReceiver }} *{{ $onebuilder }}) ExecX(ctx context.Context) {
	{{ $oneReceiver }}.{{ $receiver }}.ExecX(ctx)
}

{{ end }}
