entc/gen: add column-check for selection and grouping (#744)

This commit is contained in:
Ariel Mashraki
2020-09-09 12:27:28 +03:00
committed by GitHub
parent d16e78e686
commit 8b8744022e
114 changed files with 1272 additions and 8 deletions

View File

@@ -9,6 +9,11 @@ in the LICENSE file in the root directory of this source tree.
{{ $receiver := receiver $builder }}
func ({{ $receiver }} *{{ $builder }}) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range {{ $receiver }}.fields {
if !{{ $.Package }}.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
rows := &sql.Rows{}
query, args := {{ $receiver }}.sqlQuery().Query()
if err := {{ $receiver }}.driver.Query(ctx, query, args, rows); err != nil {

View File

@@ -61,3 +61,23 @@ in the LICENSE file in the root directory of this source tree.
)
{{ end }}
{{ end }}
{{/* functions needed for sql dialects. */}}
{{ define "dialect/sql/meta/functions" }}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
{{- with $.ForeignKeys }}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
{{- end }}
return false
}
{{ end }}

View File

@@ -9,6 +9,11 @@ in the LICENSE file in the root directory of this source tree.
{{ $receiver := receiver $builder }}
func ({{ $receiver }} *{{ $builder }}) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range {{ $receiver }}.fields {
if !{{ $.Package }}.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for selection", f)}
}
}
rows := &sql.Rows{}
query, args := {{ $receiver }}.sqlQuery().Query()
if err := {{ $receiver }}.driver.Query(ctx, query, args, rows); err != nil {