Files
ent/entc/gen/template/dialect/sql/decode.tmpl
Hylke Visser 6a1c9e73fe entc/sql/decode: fix decoding of NullTime in optional and nillable time fields (#60)
Summary:
While trying out this project I think I found a bug in the generated code when using an optional and nillable time field.

```
vet: ent/user.go:46:16: cannot use &vu.DeletedAt (value of type *sql.NullTime) as *time.Time value in assignment
```

7438104b5d made a change to the `{{ $scan }}` struct, which now always uses `{{ $f.NullType }}` as type, so the `$f.IsTime` check can now be removed. This pull request does that.

This is my fist contribution here. I hope I didn't miss anything.
Pull Request resolved: https://github.com/facebookincubator/ent/pull/60

Differential Revision: D17760925

Pulled By: a8m

fbshipit-source-id: 675005be62487b1b9eb77302b8185bd3b6ef0195
2019-10-04 03:38:45 -07:00

66 lines
2.1 KiB
Cheetah

{{/*
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 "v" $receiver }}
var {{ $scan }} struct {
ID {{ if $.ID.IsString }}int{{ else }}{{ $.ID.Type }}{{ end }}
{{ range $_, $f := $.Fields }}
{{- pascal $f.Name }} {{ $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 }}.{{- pascal $f.Name }},
{{- 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 }}.{{ pascal $f.Name }}; len(value) > 0 {
if err := json.Unmarshal(value, &{{ $receiver }}.{{ pascal $f.Name }}); err != nil {
return fmt.Errorf("unmarshal field {{ $f.Name }}: %v", err)
}
}
{{- else if $f.Nillable }}
if {{ $scan }}.{{- pascal $f.Name }}.Valid {
{{ $receiver }}.{{ pascal $f.Name }} = new({{ $f.Type }})
*{{ $receiver }}.{{ pascal $f.Name }} = {{ printf "%s.%s" $scan (pascal $f.Name) | $f.NullTypeField }}
}
{{- else }}
{{ $receiver }}.{{ pascal $f.Name }} = {{ printf "%s.%s" $scan (pascal $f.Name) | $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 "v" $receiver }}
{{ $scan }} := &{{ $.Name }}{}
if err := {{ $scan }}.FromRows(rows); err != nil {
return err
}
*{{ $receiver }} = append(*{{ $receiver }}, {{ $scan }})
}
return nil
}
{{ end }}