Skip to content

Commit

Permalink
entc/gen: move column default quoting to template (ent#2406)
Browse files Browse the repository at this point in the history
  • Loading branch information
a8m authored and gitlawr committed Apr 13, 2022
1 parent fd7ee2a commit dba8eab
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 8 deletions.
10 changes: 9 additions & 1 deletion entc/gen/func.go
Expand Up @@ -41,7 +41,7 @@ var (
"aggregate": aggregate,
"primitives": primitives,
"singular": rules.Singularize,
"quote": strconv.Quote,
"quote": quote,
"base": filepath.Base,
"keys": keys,
"join": join,
Expand Down Expand Up @@ -73,6 +73,14 @@ var (
acronyms = make(map[string]struct{})
)

// quote only strings.
func quote(v interface{}) interface{} {
if s, ok := v.(string); ok {
return strconv.Quote(s)
}
return v
}

// fieldOps returns all predicate operations for a given field.
func fieldOps(f *Field) (ops []Op) {
switch t := f.Type.Type; {
Expand Down
4 changes: 2 additions & 2 deletions entc/gen/template/migrate/schema.tmpl
Expand Up @@ -38,8 +38,8 @@ var (
{{- with $c.Size }} Size: {{ . }},{{ end }}
{{- with $c.Attr }} Attr: "{{ . }}",{{ end }}
{{- with $c.Enums }} Enums: []string{ {{ range $e := . }}"{{ $e }}",{{ end }} },{{ end }}
{{- if not (isNil $c.Default) }} Default: {{ $c.Default }},{{ end }}
{{- if ne (len $c.Collation) 0 }} Collation: {{ $c.Collation }},{{ end }}
{{- if not (isNil $c.Default) }} Default: {{ quote $c.Default }},{{ end }}
{{- if $c.Collation }} Collation: "{{ $c.Collation }}",{{ end }}
{{- with $c.SchemaType }} SchemaType: map[string]string{ {{ range $k, $v := . }}"{{ $k }}": "{{ $v }}",{{ end }}}{{ end }}},
{{- end }}
}
Expand Down
9 changes: 4 additions & 5 deletions entc/gen/type.go
Expand Up @@ -13,7 +13,6 @@ import (
"path"
"reflect"
"sort"
"strconv"
"strings"
"unicode"

Expand Down Expand Up @@ -1219,18 +1218,18 @@ func (f Field) Column() *schema.Column {
c.Default = f.DefaultValue()
case f.Default && (f.IsString() || f.IsEnum()):
if s, ok := f.DefaultValue().(string); ok {
c.Default = strconv.Quote(s)
c.Default = s
}
}
// Override the default-value defined in the
// schema if it was provided by an annotation.
if ant := f.EntSQL(); ant != nil && ant.Default != "" {
c.Default = strconv.Quote(ant.Default)
c.Default = ant.Default
}
// Override the collation defined in the
// schema if it was provided by an annotation.
if ant := f.EntSQL(); ant != nil && ant.Collation != "" {
c.Collation = strconv.Quote(ant.Collation)
c.Collation = ant.Collation
}
if f.def != nil {
c.SchemaType = f.def.SchemaType
Expand Down Expand Up @@ -1278,7 +1277,7 @@ func (f Field) PK() *schema.Column {
// Override the default-value defined in the
// schema if it was provided by an annotation.
if ant := f.EntSQL(); ant != nil && ant.Default != "" {
c.Default = strconv.Quote(ant.Default)
c.Default = ant.Default
}
if f.def != nil {
c.SchemaType = f.def.SchemaType
Expand Down

0 comments on commit dba8eab

Please sign in to comment.