{{/*
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 "dialect/sql/decode/one" }}
{{ $receiver := $.Receiver }}

// FromRows scans the sql response data into {{ $.Name }}.
func ({{ $receiver }} *{{ $.Name }}) FromRows(rows *sql.Rows) error {
	{{- $scan := print "scan" $receiver }}
	var {{ $scan }} struct {
		ID   {{ if $.ID.IsString }}int{{ else }}{{ $.ID.Type }}{{ end }}
		{{ range $_, $f := $.Fields }}
			{{- $f.StructField }} {{ $f.NullType }}
		{{ end }}
	}
	// the order here should be the same as in the `{{ $.Package }}.Columns`.
	if err := rows.Scan(
			&{{ $scan }}.ID,
			{{- range $_, $f := $.Fields }}
				&{{ $scan }}.{{ $f.StructField }},
			{{- end }}
	); err != nil {
		return err
	}
	{{ $receiver }}.ID = {{ if $.ID.IsString }}strconv.Itoa({{ $scan }}.ID){{ else }}{{ $scan }}.ID{{ end }}
	{{- range $_, $f := $.Fields }}
		{{- if $f.IsJSON }}
			if value := {{ $scan }}.{{ $f.StructField }}; len(value) > 0 {
				if err := json.Unmarshal(value, &{{ $receiver }}.{{ $f.StructField }}); err != nil {
					return fmt.Errorf("unmarshal field {{ $f.Name }}: %v", err)
				}
			}
		{{- else if $f.Nillable }}
			if {{ $scan }}.{{ $f.StructField }}.Valid {
				{{ $receiver }}.{{ $f.StructField }} = new({{ $f.Type }})
				*{{ $receiver }}.{{ $f.StructField }} = {{ printf "%s.%s" $scan $f.StructField | $f.NullTypeField }}
			}
		{{- else }}
			{{ $receiver }}.{{ $f.StructField }} = {{ printf "%s.%s" $scan $f.StructField | $f.NullTypeField }}
		{{- end }}
	{{- end }}
	return nil
}
{{ end }}

{{ define "dialect/sql/decode/many" }}
{{ $receiver := $.Receiver }}
{{ $slice := $.Scope.Slice }}

// FromRows scans the sql response data into {{ $slice }}.
func ({{ $receiver }} *{{ $slice }}) FromRows(rows *sql.Rows) error {
	for rows.Next() {
		{{- $scan := print "scan" $receiver }}
		{{ $scan }} := &{{ $.Name }}{}
		if err := {{ $scan }}.FromRows(rows); err != nil {
			return err
		}
		*{{ $receiver }} = append(*{{ $receiver }}, {{ $scan }})
	}
	return nil
}
{{ end }}
