go-zero/tools/goctl/model/sql/gen/field.go
方航 fabea4c448
fix bug: crash when generate model with goctl. (#1777)
* fix bug: crash when generate model with goctl.

situation: column name with line.

CREATE TABLE test (
id int NOT NULL AUTO_INCREMENT,
zh-cn text CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT '中文简体',
PRIMARY KEY (id) USING BTREE,
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

* group imports

group imports

* Use

go-zero/tools/goctl/util/string.go
 func SafeString(in string) string {
instead of ReplaceAll

Co-authored-by: 方航 <fanghang@tange.ai>
2022-04-11 10:11:40 +08:00

54 lines
1.1 KiB
Go

package gen
import (
"strings"
"github.com/zeromicro/go-zero/tools/goctl/model/sql/parser"
"github.com/zeromicro/go-zero/tools/goctl/model/sql/template"
"github.com/zeromicro/go-zero/tools/goctl/util"
"github.com/zeromicro/go-zero/tools/goctl/util/pathx"
)
func genFields(table Table, fields []*parser.Field) (string, error) {
var list []string
for _, field := range fields {
result, err := genField(table, field)
if err != nil {
return "", err
}
list = append(list, result)
}
return strings.Join(list, "\n"), nil
}
func genField(table Table, field *parser.Field) (string, error) {
tag, err := genTag(table, field.NameOriginal)
if err != nil {
return "", err
}
text, err := pathx.LoadTemplate(category, fieldTemplateFile, template.Field)
if err != nil {
return "", err
}
output, err := util.With("types").
Parse(text).
Execute(map[string]interface{}{
"name": util.SafeString(field.Name.ToCamel()),
"type": field.DataType,
"tag": tag,
"hasComment": field.Comment != "",
"comment": field.Comment,
"data": table,
})
if err != nil {
return "", err
}
return output.String(), nil
}