mirror of
https://github.com/zhufuyi/sponge.git
synced 2025-11-03 01:33:55 +08:00
feat: implement sponge commands
This commit is contained in:
36
pkg/sql2code/parser/mysql.go
Normal file
36
pkg/sql2code/parser/mysql.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package parser
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
_ "github.com/go-sql-driver/mysql" //nolint
|
||||
)
|
||||
|
||||
// GetTableInfo get table info from mysql
|
||||
func GetTableInfo(dsn, tableName string) (string, error) {
|
||||
db, err := sql.Open("mysql", dsn)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("connect mysql error, %v", err)
|
||||
}
|
||||
defer db.Close() //nolint
|
||||
|
||||
rows, err := db.Query("SHOW CREATE TABLE " + tableName)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("query show create table error, %v", err)
|
||||
}
|
||||
|
||||
defer rows.Close() //nolint
|
||||
if !rows.Next() {
|
||||
return "", fmt.Errorf("not found found table '%s'", tableName)
|
||||
}
|
||||
|
||||
var table string
|
||||
var info string
|
||||
err = rows.Scan(&table, &info)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return info, nil
|
||||
}
|
||||
123
pkg/sql2code/parser/option.go
Normal file
123
pkg/sql2code/parser/option.go
Normal file
@@ -0,0 +1,123 @@
|
||||
package parser
|
||||
|
||||
// NullStyle null type
|
||||
type NullStyle int
|
||||
|
||||
// nolint
|
||||
const (
|
||||
NullDisable NullStyle = iota
|
||||
NullInSql
|
||||
NullInPointer
|
||||
)
|
||||
|
||||
// Option function
|
||||
type Option func(*options)
|
||||
|
||||
type options struct {
|
||||
Charset string
|
||||
Collation string
|
||||
JSONTag bool
|
||||
JSONNamedType int // json命名类型,0:默认,其他值表示驼峰
|
||||
TablePrefix string
|
||||
ColumnPrefix string
|
||||
NoNullType bool
|
||||
NullStyle NullStyle
|
||||
Package string
|
||||
GormType bool
|
||||
ForceTableName bool
|
||||
IsEmbed bool // 是否嵌入gorm.Model
|
||||
}
|
||||
|
||||
var defaultOptions = options{
|
||||
NullStyle: NullInSql,
|
||||
Package: "model",
|
||||
}
|
||||
|
||||
// WithCharset set charset
|
||||
func WithCharset(charset string) Option {
|
||||
return func(o *options) {
|
||||
o.Charset = charset
|
||||
}
|
||||
}
|
||||
|
||||
// WithCollation set collation
|
||||
func WithCollation(collation string) Option {
|
||||
return func(o *options) {
|
||||
o.Collation = collation
|
||||
}
|
||||
}
|
||||
|
||||
// WithTablePrefix set table prefix
|
||||
func WithTablePrefix(p string) Option {
|
||||
return func(o *options) {
|
||||
o.TablePrefix = p
|
||||
}
|
||||
}
|
||||
|
||||
// WithColumnPrefix set column prefix
|
||||
func WithColumnPrefix(p string) Option {
|
||||
return func(o *options) {
|
||||
o.ColumnPrefix = p
|
||||
}
|
||||
}
|
||||
|
||||
// WithJSONTag json名称命名类型,0:表示默认,其他值表示驼峰
|
||||
func WithJSONTag(namedType int) Option {
|
||||
return func(o *options) {
|
||||
o.JSONTag = true
|
||||
o.JSONNamedType = namedType
|
||||
}
|
||||
}
|
||||
|
||||
// WithNoNullType set NoNullType
|
||||
func WithNoNullType() Option {
|
||||
return func(o *options) {
|
||||
o.NoNullType = true
|
||||
}
|
||||
}
|
||||
|
||||
// WithNullStyle set NullType
|
||||
func WithNullStyle(s NullStyle) Option {
|
||||
return func(o *options) {
|
||||
o.NullStyle = s
|
||||
}
|
||||
}
|
||||
|
||||
// WithPackage set package name
|
||||
func WithPackage(pkg string) Option {
|
||||
return func(o *options) {
|
||||
o.Package = pkg
|
||||
}
|
||||
}
|
||||
|
||||
// WithGormType will write type in gorm tag
|
||||
func WithGormType() Option {
|
||||
return func(o *options) {
|
||||
o.GormType = true
|
||||
}
|
||||
}
|
||||
|
||||
// WithForceTableName set forceFloats
|
||||
func WithForceTableName() Option {
|
||||
return func(o *options) {
|
||||
o.ForceTableName = true
|
||||
}
|
||||
}
|
||||
|
||||
// WithEmbed is embed gorm.Model
|
||||
func WithEmbed() Option {
|
||||
return func(o *options) {
|
||||
o.IsEmbed = true
|
||||
}
|
||||
}
|
||||
|
||||
func parseOption(options []Option) options {
|
||||
o := defaultOptions
|
||||
for _, f := range options {
|
||||
f(&o)
|
||||
}
|
||||
if o.NoNullType {
|
||||
o.NullStyle = NullDisable
|
||||
}
|
||||
return o
|
||||
}
|
||||
811
pkg/sql2code/parser/parser.go
Normal file
811
pkg/sql2code/parser/parser.go
Normal file
@@ -0,0 +1,811 @@
|
||||
package parser
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"github.com/blastrain/vitess-sqlparser/tidbparser/ast"
|
||||
"github.com/blastrain/vitess-sqlparser/tidbparser/dependency/mysql"
|
||||
"github.com/blastrain/vitess-sqlparser/tidbparser/dependency/types"
|
||||
"github.com/blastrain/vitess-sqlparser/tidbparser/parser"
|
||||
"github.com/huandu/xstrings"
|
||||
"github.com/jinzhu/inflection"
|
||||
"go/format"
|
||||
"sort"
|
||||
"strings"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
const (
|
||||
// TableName table name
|
||||
TableName = "__table_name__"
|
||||
// CodeTypeModel model code
|
||||
CodeTypeModel = "model"
|
||||
// CodeTypeJSON json code
|
||||
CodeTypeJSON = "json"
|
||||
// CodeTypeDAO update fields code
|
||||
CodeTypeDAO = "dao"
|
||||
// CodeTypeHandler handler request and respond code
|
||||
CodeTypeHandler = "handler"
|
||||
// CodeTypeProto proto file code
|
||||
CodeTypeProto = "proto"
|
||||
// CodeTypeService grpc service code
|
||||
CodeTypeService = "service"
|
||||
)
|
||||
|
||||
// Codes 生成的代码
|
||||
type Codes struct {
|
||||
Model []string // model code
|
||||
UpdateFields []string // update fields code
|
||||
ModelJSON []string // model json code
|
||||
HandlerStruct []string // handler request and respond code
|
||||
}
|
||||
|
||||
// modelCodes 生成的代码
|
||||
type modelCodes struct {
|
||||
Package string
|
||||
ImportPath []string
|
||||
StructCode []string
|
||||
}
|
||||
|
||||
// ParseSQL 根据sql生成不同用途代码
|
||||
func ParseSQL(sql string, options ...Option) (map[string]string, error) {
|
||||
initTemplate()
|
||||
opt := parseOption(options)
|
||||
|
||||
stmts, err := parser.New().Parse(sql, opt.Charset, opt.Collation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
modelStructCodes := make([]string, 0, len(stmts))
|
||||
updateFieldsCodes := make([]string, 0, len(stmts))
|
||||
handlerStructCodes := make([]string, 0, len(stmts))
|
||||
protoFileCodes := make([]string, 0, len(stmts))
|
||||
serviceStructCodes := make([]string, 0, len(stmts))
|
||||
modelJSONCodes := make([]string, 0, len(stmts))
|
||||
importPath := make(map[string]struct{})
|
||||
tableNames := make([]string, 0, len(stmts))
|
||||
for _, stmt := range stmts {
|
||||
if ct, ok := stmt.(*ast.CreateTableStmt); ok {
|
||||
code, err := makeCode(ct, opt) //nolint
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
modelStructCodes = append(modelStructCodes, code.modelStruct)
|
||||
updateFieldsCodes = append(updateFieldsCodes, code.updateFields)
|
||||
handlerStructCodes = append(handlerStructCodes, code.handlerStruct)
|
||||
protoFileCodes = append(protoFileCodes, code.protoFile)
|
||||
serviceStructCodes = append(serviceStructCodes, code.serviceStruct)
|
||||
modelJSONCodes = append(modelJSONCodes, code.modelJSON)
|
||||
tableNames = append(tableNames, toCamel(ct.Table.Name.String()))
|
||||
for _, s := range code.importPaths {
|
||||
importPath[s] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
importPathArr := make([]string, 0, len(importPath))
|
||||
for s := range importPath {
|
||||
importPathArr = append(importPathArr, s)
|
||||
}
|
||||
sort.Strings(importPathArr)
|
||||
|
||||
mc := modelCodes{
|
||||
Package: opt.Package,
|
||||
ImportPath: importPathArr,
|
||||
StructCode: modelStructCodes,
|
||||
}
|
||||
modelCode, err := getModelCode(mc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var codesMap = map[string]string{
|
||||
CodeTypeModel: modelCode,
|
||||
CodeTypeJSON: strings.Join(modelJSONCodes, "\n\n"),
|
||||
CodeTypeDAO: strings.Join(updateFieldsCodes, "\n\n"),
|
||||
CodeTypeHandler: strings.Join(handlerStructCodes, "\n\n"),
|
||||
CodeTypeProto: strings.Join(protoFileCodes, "\n\n"),
|
||||
CodeTypeService: strings.Join(serviceStructCodes, "\n\n"),
|
||||
TableName: strings.Join(tableNames, ", "),
|
||||
}
|
||||
|
||||
return codesMap, nil
|
||||
}
|
||||
|
||||
type tmplData struct {
|
||||
TableName string
|
||||
TName string
|
||||
NameFunc bool
|
||||
RawTableName string
|
||||
Fields []tmplField
|
||||
Comment string
|
||||
}
|
||||
|
||||
type tmplField struct {
|
||||
Name string
|
||||
ColName string
|
||||
GoType string
|
||||
Tag string
|
||||
Comment string
|
||||
}
|
||||
|
||||
// ConditionZero type of condition 0
|
||||
func (t tmplField) ConditionZero() string {
|
||||
switch t.GoType {
|
||||
case "int8", "int16", "int32", "int64", "int", "uint8", "uint16", "uint32", "uint64", "uint", "float64", "float32", //nolint
|
||||
"sql.NullInt32", "sql.NullInt64", "sql.NullFloat64": //nolint
|
||||
return `!= 0`
|
||||
case "string", "sql.NullString": //nolint
|
||||
return `!= ""`
|
||||
case "time.Time", "*time.Time", "sql.NullTime": //nolint
|
||||
return `.IsZero() == false`
|
||||
}
|
||||
|
||||
return `!= ` + t.GoType
|
||||
}
|
||||
|
||||
// GoZero type of 0 逗号分隔
|
||||
func (t tmplField) GoZero() string {
|
||||
switch t.GoType {
|
||||
case "int8", "int16", "int32", "int64", "int", "uint8", "uint16", "uint32", "uint64", "uint", "float64", "float32", //nolint
|
||||
"sql.NullInt32", "sql.NullInt64", "sql.NullFloat64": //nolint
|
||||
return `= 0`
|
||||
case "string", "sql.NullString": //nolint
|
||||
return `= "string"`
|
||||
case "time.Time", "*time.Time", "sql.NullTime": //nolint
|
||||
return `= "0000-01-00T00:00:00.000+08:00"`
|
||||
}
|
||||
|
||||
return `= ` + t.GoType
|
||||
}
|
||||
|
||||
// GoTypeZero type of 0 逗号分隔
|
||||
func (t tmplField) GoTypeZero() string {
|
||||
switch t.GoType {
|
||||
case "int8", "int16", "int32", "int64", "int", "uint8", "uint16", "uint32", "uint64", "uint", "float64", "float32", //nolint
|
||||
"sql.NullInt32", "sql.NullInt64", "sql.NullFloat64": //nolint
|
||||
return `0`
|
||||
case "string", "sql.NullString": //nolint
|
||||
return `""`
|
||||
case "time.Time", "*time.Time", "sql.NullTime": //nolint
|
||||
return `0 /*time.Now().Second()*/`
|
||||
}
|
||||
|
||||
return t.GoType
|
||||
}
|
||||
|
||||
// AddOne 加一
|
||||
func (t tmplField) AddOne(i int) int {
|
||||
return i + 1
|
||||
}
|
||||
|
||||
const (
|
||||
__mysqlModel__ = "__mysqlModel__" //nolint
|
||||
__type__ = "__type__" //nolint
|
||||
)
|
||||
|
||||
var replaceFields = map[string]string{
|
||||
__mysqlModel__: "mysql.Model",
|
||||
__type__: "",
|
||||
}
|
||||
|
||||
const (
|
||||
columnID = "id"
|
||||
columnCreatedAt = "created_at"
|
||||
columnUpdatedAt = "updated_at"
|
||||
columnDeletedAt = "deleted_at"
|
||||
columnMysqlModel = __mysqlModel__
|
||||
)
|
||||
|
||||
// nolint
|
||||
var ignoreColumns = map[string]struct{}{
|
||||
columnID: {},
|
||||
columnCreatedAt: {},
|
||||
columnUpdatedAt: {},
|
||||
columnDeletedAt: {},
|
||||
columnMysqlModel: {},
|
||||
}
|
||||
|
||||
func isIgnoreFields(colName string, falseColumn ...string) bool {
|
||||
for _, v := range falseColumn {
|
||||
if colName == v {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
_, ok := ignoreColumns[colName]
|
||||
return ok
|
||||
}
|
||||
|
||||
type codeText struct {
|
||||
importPaths []string
|
||||
modelStruct string
|
||||
modelJSON string
|
||||
updateFields string
|
||||
handlerStruct string
|
||||
protoFile string
|
||||
serviceStruct string
|
||||
}
|
||||
|
||||
// nolint
|
||||
func makeCode(stmt *ast.CreateTableStmt, opt options) (*codeText, error) {
|
||||
importPath := make([]string, 0, 1)
|
||||
data := tmplData{
|
||||
TableName: stmt.Table.Name.String(),
|
||||
RawTableName: stmt.Table.Name.String(),
|
||||
Fields: make([]tmplField, 0, 1),
|
||||
}
|
||||
tablePrefix := opt.TablePrefix
|
||||
if tablePrefix != "" && strings.HasPrefix(data.TableName, tablePrefix) {
|
||||
data.NameFunc = true
|
||||
data.TableName = data.TableName[len(tablePrefix):]
|
||||
}
|
||||
if opt.ForceTableName || data.RawTableName != inflection.Plural(data.RawTableName) {
|
||||
data.NameFunc = true
|
||||
}
|
||||
|
||||
data.TableName = toCamel(data.TableName)
|
||||
data.TName = firstLetterToLow(data.TableName)
|
||||
|
||||
// find table comment
|
||||
for _, o := range stmt.Options {
|
||||
if o.Tp == ast.TableOptionComment {
|
||||
data.Comment = o.StrValue
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
isPrimaryKey := make(map[string]bool)
|
||||
for _, con := range stmt.Constraints {
|
||||
if con.Tp == ast.ConstraintPrimaryKey {
|
||||
isPrimaryKey[con.Keys[0].Column.String()] = true
|
||||
}
|
||||
}
|
||||
|
||||
columnPrefix := opt.ColumnPrefix
|
||||
for _, col := range stmt.Cols {
|
||||
colName := col.Name.Name.String()
|
||||
goFieldName := colName
|
||||
if columnPrefix != "" && strings.HasPrefix(goFieldName, columnPrefix) {
|
||||
goFieldName = goFieldName[len(columnPrefix):]
|
||||
}
|
||||
|
||||
field := tmplField{
|
||||
Name: toCamel(goFieldName),
|
||||
ColName: colName,
|
||||
}
|
||||
|
||||
tags := make([]string, 0, 4)
|
||||
// make GORM's tag
|
||||
gormTag := strings.Builder{}
|
||||
gormTag.WriteString("column:")
|
||||
gormTag.WriteString(colName)
|
||||
if opt.GormType {
|
||||
gormTag.WriteString(";type:")
|
||||
gormTag.WriteString(col.Tp.InfoSchemaStr())
|
||||
}
|
||||
if isPrimaryKey[colName] {
|
||||
gormTag.WriteString(";primary_key")
|
||||
}
|
||||
isNotNull := false
|
||||
canNull := false
|
||||
for _, o := range col.Options {
|
||||
switch o.Tp {
|
||||
case ast.ColumnOptionPrimaryKey:
|
||||
if !isPrimaryKey[colName] {
|
||||
gormTag.WriteString(";primary_key")
|
||||
isPrimaryKey[colName] = true
|
||||
}
|
||||
case ast.ColumnOptionNotNull:
|
||||
isNotNull = true
|
||||
case ast.ColumnOptionAutoIncrement:
|
||||
gormTag.WriteString(";AUTO_INCREMENT")
|
||||
case ast.ColumnOptionDefaultValue:
|
||||
if value := getDefaultValue(o.Expr); value != "" {
|
||||
gormTag.WriteString(";default:")
|
||||
gormTag.WriteString(value)
|
||||
}
|
||||
case ast.ColumnOptionUniqKey:
|
||||
gormTag.WriteString(";unique")
|
||||
case ast.ColumnOptionNull:
|
||||
//gormTag.WriteString(";NULL")
|
||||
canNull = true
|
||||
case ast.ColumnOptionOnUpdate: // For Timestamp and Datetime only.
|
||||
case ast.ColumnOptionFulltext:
|
||||
case ast.ColumnOptionComment:
|
||||
field.Comment = o.Expr.GetDatum().GetString()
|
||||
default:
|
||||
//return "", nil, errors.Errorf(" unsupport option %d\n", o.Tp)
|
||||
}
|
||||
}
|
||||
if !isPrimaryKey[colName] && isNotNull {
|
||||
gormTag.WriteString(";NOT NULL")
|
||||
}
|
||||
tags = append(tags, "gorm", gormTag.String())
|
||||
|
||||
if opt.JSONTag {
|
||||
if opt.JSONNamedType != 0 {
|
||||
colName = xstrings.FirstRuneToLower(xstrings.ToCamelCase(colName)) // 使用驼峰类型json名称
|
||||
}
|
||||
tags = append(tags, "json", colName)
|
||||
}
|
||||
|
||||
field.Tag = makeTagStr(tags)
|
||||
|
||||
// get type in golang
|
||||
nullStyle := opt.NullStyle
|
||||
if !canNull {
|
||||
nullStyle = NullDisable
|
||||
}
|
||||
goType, pkg := mysqlToGoType(col.Tp, nullStyle)
|
||||
if pkg != "" {
|
||||
importPath = append(importPath, pkg)
|
||||
}
|
||||
field.GoType = goType
|
||||
|
||||
data.Fields = append(data.Fields, field)
|
||||
}
|
||||
|
||||
updateFieldsCode, err := getUpdateFieldsCode(data, opt.IsEmbed)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
handlerStructCode, err := getHandlerStructCodes(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
modelStructCode, importPaths, err := getModelStructCode(data, importPath, opt.IsEmbed)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
modelJSONCode, err := getModelJSONCode(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
protoFileCode, err := getProtoFileCode(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
serviceStructCode, err := getServiceStructCode(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &codeText{
|
||||
importPaths: importPaths,
|
||||
modelStruct: modelStructCode,
|
||||
modelJSON: modelJSONCode,
|
||||
updateFields: updateFieldsCode,
|
||||
handlerStruct: handlerStructCode,
|
||||
protoFile: protoFileCode,
|
||||
serviceStruct: serviceStructCode,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func getModelStructCode(data tmplData, importPaths []string, isEmbed bool) (string, []string, error) {
|
||||
// 过滤忽略字段字段
|
||||
var newFields = []tmplField{}
|
||||
var newImportPaths = []string{}
|
||||
if isEmbed {
|
||||
// 嵌入字段
|
||||
newFields = append(newFields, tmplField{
|
||||
Name: __mysqlModel__,
|
||||
ColName: __mysqlModel__,
|
||||
GoType: __type__,
|
||||
Tag: `gorm:"embedded"`,
|
||||
Comment: "embed id and time\n",
|
||||
})
|
||||
|
||||
isHaveTimeType := false
|
||||
for _, field := range data.Fields {
|
||||
if isIgnoreFields(field.ColName) {
|
||||
continue
|
||||
}
|
||||
newFields = append(newFields, field)
|
||||
if strings.Contains(field.GoType, "time.Time") {
|
||||
isHaveTimeType = true
|
||||
}
|
||||
}
|
||||
data.Fields = newFields
|
||||
|
||||
// 过滤time包名
|
||||
if isHaveTimeType {
|
||||
newImportPaths = importPaths
|
||||
} else {
|
||||
for _, path := range importPaths {
|
||||
if path == "time" {
|
||||
continue
|
||||
}
|
||||
newImportPaths = append(newImportPaths, path)
|
||||
}
|
||||
}
|
||||
newImportPaths = append(newImportPaths, "github.com/zhufuyi/sponge/pkg/mysql")
|
||||
} else {
|
||||
for i, field := range data.Fields {
|
||||
if strings.Contains(field.GoType, "time.Time") {
|
||||
data.Fields[i].GoType = "*time.Time"
|
||||
}
|
||||
}
|
||||
newImportPaths = importPaths
|
||||
}
|
||||
|
||||
builder := strings.Builder{}
|
||||
err := modelStructTmpl.Execute(&builder, data)
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("modelStructTmpl.Execute error: %v", err)
|
||||
}
|
||||
code, err := format.Source([]byte(builder.String()))
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("modelStructTmpl format.Source error: %v", err)
|
||||
}
|
||||
structCode := string(code)
|
||||
// 还原真实的嵌入字段
|
||||
if isEmbed {
|
||||
structCode = strings.ReplaceAll(structCode, __mysqlModel__, replaceFields[__mysqlModel__])
|
||||
structCode = strings.ReplaceAll(structCode, __type__, replaceFields[__type__])
|
||||
}
|
||||
|
||||
return structCode, newImportPaths, nil
|
||||
}
|
||||
|
||||
func getModelCode(data modelCodes) (string, error) {
|
||||
builder := strings.Builder{}
|
||||
err := modelTmpl.Execute(&builder, data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
code, err := format.Source([]byte(builder.String()))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("format.Source error: %v", err)
|
||||
}
|
||||
|
||||
return string(code), nil
|
||||
}
|
||||
|
||||
func getUpdateFieldsCode(data tmplData, isEmbed bool) (string, error) {
|
||||
// 过滤字段
|
||||
var newFields = []tmplField{}
|
||||
for _, field := range data.Fields {
|
||||
falseColumns := []string{}
|
||||
//if !isEmbed {
|
||||
//falseColumns = append(falseColumns, columnCreatedAt, columnUpdatedAt, columnDeletedAt)
|
||||
//}
|
||||
if isIgnoreFields(field.ColName, falseColumns...) {
|
||||
continue
|
||||
}
|
||||
newFields = append(newFields, field)
|
||||
}
|
||||
data.Fields = newFields
|
||||
|
||||
builder := strings.Builder{}
|
||||
err := updateFieldTmpl.Execute(&builder, data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
code, err := format.Source([]byte(builder.String()))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(code), nil
|
||||
}
|
||||
|
||||
func getHandlerStructCodes(data tmplData) (string, error) {
|
||||
postStructCode, err := tmplExecuteWithFilter(data, handlerCreateStructTmpl)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("handlerCreateStructTmpl error: %v", err)
|
||||
}
|
||||
|
||||
putStructCode, err := tmplExecuteWithFilter(data, handlerUpdateStructTmpl, columnID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("handlerUpdateStructTmpl error: %v", err)
|
||||
}
|
||||
|
||||
getStructCode, err := tmplExecuteWithFilter(data, handlerDetailStructTmpl, columnID, columnCreatedAt, columnUpdatedAt)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("handlerDetailStructTmpl error: %v", err)
|
||||
}
|
||||
|
||||
return postStructCode + putStructCode + getStructCode, nil
|
||||
}
|
||||
|
||||
// 自定义过滤字段
|
||||
func tmplExecuteWithFilter(data tmplData, tmpl *template.Template, reservedColumns ...string) (string, error) {
|
||||
var newFields = []tmplField{}
|
||||
for _, field := range data.Fields {
|
||||
if isIgnoreFields(field.ColName, reservedColumns...) {
|
||||
continue
|
||||
}
|
||||
newFields = append(newFields, field)
|
||||
}
|
||||
data.Fields = newFields
|
||||
|
||||
builder := strings.Builder{}
|
||||
err := tmpl.Execute(&builder, data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("tmpl.Execute error: %v", err)
|
||||
}
|
||||
return builder.String(), nil
|
||||
}
|
||||
|
||||
func getModelJSONCode(data tmplData) (string, error) {
|
||||
builder := strings.Builder{}
|
||||
err := modelJSONTmpl.Execute(&builder, data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
code, err := format.Source([]byte(builder.String()))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("format.Source error: %v", err)
|
||||
}
|
||||
|
||||
modelJSONCode := strings.ReplaceAll(string(code), " =", ":")
|
||||
modelJSONCode = addCommaToJSON(modelJSONCode)
|
||||
|
||||
return modelJSONCode, nil
|
||||
}
|
||||
|
||||
func getProtoFileCode(data tmplData) (string, error) {
|
||||
data.Fields = goTypeToProto(data.Fields)
|
||||
|
||||
builder := strings.Builder{}
|
||||
err := protoFileTmpl.Execute(&builder, data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
code := builder.String()
|
||||
|
||||
protoMessageCreateCode, err := tmplExecuteWithFilter(data, protoMessageCreateTmpl)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("handlerCreateStructTmpl error: %v", err)
|
||||
}
|
||||
|
||||
protoMessageUpdateCode, err := tmplExecuteWithFilter(data, protoMessageUpdateTmpl, columnID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("handlerCreateStructTmpl error: %v", err)
|
||||
}
|
||||
|
||||
protoMessageDetailCode, err := tmplExecuteWithFilter(data, protoMessageDetailTmpl, columnID, columnCreatedAt, columnUpdatedAt)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("handlerCreateStructTmpl error: %v", err)
|
||||
}
|
||||
|
||||
code = strings.ReplaceAll(code, "// protoMessageCreateCode", protoMessageCreateCode)
|
||||
code = strings.ReplaceAll(code, "// protoMessageUpdateCode", protoMessageUpdateCode)
|
||||
code = strings.ReplaceAll(code, "// protoMessageDetailCode", protoMessageDetailCode)
|
||||
code = strings.ReplaceAll(code, "*time.Time", "int64")
|
||||
code = strings.ReplaceAll(code, "time.Time", "int64")
|
||||
|
||||
return code, nil
|
||||
}
|
||||
|
||||
func getServiceStructCode(data tmplData) (string, error) {
|
||||
builder := strings.Builder{}
|
||||
err := serviceStructTmpl.Execute(&builder, data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
code := builder.String()
|
||||
|
||||
serviceCreateStructCode, err := tmplExecuteWithFilter(data, serviceCreateStructTmpl)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("handlerCreateStructTmpl error: %v", err)
|
||||
}
|
||||
serviceCreateStructCode = strings.ReplaceAll(serviceCreateStructCode, "ID:", "Id:")
|
||||
|
||||
serviceUpdateStructCode, err := tmplExecuteWithFilter(data, serviceUpdateStructTmpl, columnID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("handlerCreateStructTmpl error: %v", err)
|
||||
}
|
||||
serviceUpdateStructCode = strings.ReplaceAll(serviceUpdateStructCode, "ID:", "Id:")
|
||||
|
||||
code = strings.ReplaceAll(code, "// serviceCreateStructCode", serviceCreateStructCode)
|
||||
code = strings.ReplaceAll(code, "// serviceUpdateStructCode", serviceUpdateStructCode)
|
||||
|
||||
return code, nil
|
||||
}
|
||||
|
||||
func addCommaToJSON(modelJSONCode string) string {
|
||||
r := strings.NewReader(modelJSONCode)
|
||||
buf := bufio.NewReader(r)
|
||||
|
||||
lines := []string{}
|
||||
count := 0
|
||||
for {
|
||||
line, err := buf.ReadString(byte('\n'))
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
lines = append(lines, line)
|
||||
if len(line) > 5 {
|
||||
count++
|
||||
}
|
||||
}
|
||||
|
||||
out := ""
|
||||
for _, line := range lines {
|
||||
if len(line) < 5 && (strings.Contains(line, "{") || strings.Contains(line, "}")) {
|
||||
out += line
|
||||
continue
|
||||
}
|
||||
count--
|
||||
if count == 0 {
|
||||
out += line
|
||||
continue
|
||||
}
|
||||
index := bytes.IndexByte([]byte(line), '\n')
|
||||
out += line[:index] + "," + line[index:]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func mysqlToGoType(colTp *types.FieldType, style NullStyle) (name string, path string) {
|
||||
if style == NullInSql {
|
||||
path = "database/sql"
|
||||
switch colTp.Tp {
|
||||
case mysql.TypeTiny, mysql.TypeShort, mysql.TypeInt24, mysql.TypeLong:
|
||||
name = "sql.NullInt32"
|
||||
case mysql.TypeLonglong:
|
||||
name = "sql.NullInt64"
|
||||
case mysql.TypeFloat, mysql.TypeDouble:
|
||||
name = "sql.NullFloat64"
|
||||
case mysql.TypeString, mysql.TypeVarchar, mysql.TypeVarString,
|
||||
mysql.TypeBlob, mysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeLongBlob:
|
||||
name = "sql.NullString" //nolint
|
||||
case mysql.TypeTimestamp, mysql.TypeDatetime, mysql.TypeDate:
|
||||
name = "sql.NullTime"
|
||||
case mysql.TypeDecimal, mysql.TypeNewDecimal:
|
||||
name = "sql.NullString" //nolint
|
||||
case mysql.TypeJSON:
|
||||
name = "sql.NullString" //nolint
|
||||
default:
|
||||
return "UnSupport", ""
|
||||
}
|
||||
} else {
|
||||
switch colTp.Tp {
|
||||
case mysql.TypeTiny, mysql.TypeShort, mysql.TypeInt24, mysql.TypeLong:
|
||||
if mysql.HasUnsignedFlag(colTp.Flag) {
|
||||
name = "uint"
|
||||
} else {
|
||||
name = "int"
|
||||
}
|
||||
case mysql.TypeLonglong:
|
||||
if mysql.HasUnsignedFlag(colTp.Flag) {
|
||||
name = "uint64"
|
||||
} else {
|
||||
name = "int64" //nolint
|
||||
}
|
||||
case mysql.TypeFloat, mysql.TypeDouble:
|
||||
name = "float64"
|
||||
case mysql.TypeString, mysql.TypeVarchar, mysql.TypeVarString,
|
||||
mysql.TypeBlob, mysql.TypeTinyBlob, mysql.TypeMediumBlob, mysql.TypeLongBlob:
|
||||
name = "string"
|
||||
case mysql.TypeTimestamp, mysql.TypeDatetime, mysql.TypeDate:
|
||||
path = "time"
|
||||
name = "time.Time"
|
||||
case mysql.TypeDecimal, mysql.TypeNewDecimal:
|
||||
name = "string"
|
||||
case mysql.TypeJSON:
|
||||
name = "string"
|
||||
default:
|
||||
return "UnSupport", ""
|
||||
}
|
||||
if style == NullInPointer {
|
||||
name = "*" + name
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func goTypeToProto(fields []tmplField) []tmplField {
|
||||
var newFields []tmplField
|
||||
for _, field := range fields {
|
||||
switch field.GoType {
|
||||
case "int":
|
||||
field.GoType = "int32"
|
||||
case "uint":
|
||||
field.GoType = "uint32"
|
||||
case "time.Time":
|
||||
field.GoType = "int64"
|
||||
}
|
||||
newFields = append(newFields, field)
|
||||
}
|
||||
return newFields
|
||||
}
|
||||
|
||||
func makeTagStr(tags []string) string {
|
||||
builder := strings.Builder{}
|
||||
for i := 0; i < len(tags)/2; i++ {
|
||||
builder.WriteString(tags[i*2])
|
||||
builder.WriteString(`:"`)
|
||||
builder.WriteString(tags[i*2+1])
|
||||
builder.WriteString(`" `)
|
||||
}
|
||||
if builder.Len() > 0 {
|
||||
return builder.String()[:builder.Len()-1]
|
||||
}
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func getDefaultValue(expr ast.ExprNode) (value string) {
|
||||
if expr.GetDatum().Kind() != types.KindNull {
|
||||
value = fmt.Sprintf("%v", expr.GetDatum().GetValue())
|
||||
} else if expr.GetFlag() != ast.FlagConstant {
|
||||
if expr.GetFlag() == ast.FlagHasFunc {
|
||||
if funcExpr, ok := expr.(*ast.FuncCallExpr); ok {
|
||||
value = funcExpr.FnName.O
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var acronym = map[string]struct{}{
|
||||
"ID": {},
|
||||
"IP": {},
|
||||
"RPC": {},
|
||||
}
|
||||
|
||||
func toCamel(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return s
|
||||
}
|
||||
s += "."
|
||||
|
||||
n := strings.Builder{}
|
||||
n.Grow(len(s))
|
||||
temp := strings.Builder{}
|
||||
temp.Grow(len(s))
|
||||
wordFirst := true
|
||||
for _, v := range []byte(s) {
|
||||
vIsCap := v >= 'A' && v <= 'Z'
|
||||
vIsLow := v >= 'a' && v <= 'z'
|
||||
if wordFirst && vIsLow {
|
||||
v -= 'a' - 'A'
|
||||
}
|
||||
|
||||
if vIsCap || vIsLow {
|
||||
temp.WriteByte(v)
|
||||
wordFirst = false
|
||||
} else {
|
||||
isNum := v >= '0' && v <= '9'
|
||||
wordFirst = isNum || v == '_' || v == ' ' || v == '-' || v == '.'
|
||||
if temp.Len() > 0 && wordFirst {
|
||||
word := temp.String()
|
||||
upper := strings.ToUpper(word)
|
||||
if _, ok := acronym[upper]; ok {
|
||||
n.WriteString(upper)
|
||||
} else {
|
||||
n.WriteString(word)
|
||||
}
|
||||
temp.Reset()
|
||||
}
|
||||
if isNum {
|
||||
n.WriteByte(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
return n.String()
|
||||
}
|
||||
|
||||
func firstLetterToLow(str string) string {
|
||||
if len(str) == 0 {
|
||||
return str
|
||||
}
|
||||
|
||||
if (str[0] >= 'A' && str[0] <= 'Z') || (str[0] >= 'a' && str[0] <= 'z') {
|
||||
return strings.ToLower(str[:1]) + str[1:]
|
||||
}
|
||||
|
||||
return str
|
||||
}
|
||||
158
pkg/sql2code/parser/parser_test.go
Normal file
158
pkg/sql2code/parser/parser_test.go
Normal file
@@ -0,0 +1,158 @@
|
||||
package parser
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/blastrain/vitess-sqlparser/tidbparser/dependency/mysql"
|
||||
"github.com/blastrain/vitess-sqlparser/tidbparser/dependency/types"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestParseSql(t *testing.T) {
|
||||
sql := `CREATE TABLE t_person_info (
|
||||
age INT(11) unsigned NULL,
|
||||
id BIGINT(11) PRIMARY KEY AUTO_INCREMENT NOT NULL COMMENT '这是id',
|
||||
name VARCHAR(30) NOT NULL DEFAULT 'default_name' COMMENT '这是名字',
|
||||
created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
login_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
sex VARCHAR(2) NULL,
|
||||
num INT(11) DEFAULT 3 NULL,
|
||||
comment TEXT
|
||||
) COMMENT="person info";`
|
||||
|
||||
codes, err := ParseSQL(sql, WithTablePrefix("t_"), WithJSONTag(0))
|
||||
assert.Nil(t, err)
|
||||
for k, v := range codes {
|
||||
//if k == CodeTypeModel {
|
||||
// t.Log(v)
|
||||
//}
|
||||
assert.NotEmpty(t, k)
|
||||
assert.NotEmpty(t, v)
|
||||
}
|
||||
|
||||
codes, err = ParseSQL(sql, WithTablePrefix("t_"), WithJSONTag(0), WithEmbed())
|
||||
assert.Nil(t, err)
|
||||
for k, v := range codes {
|
||||
assert.NotEmpty(t, k)
|
||||
assert.NotEmpty(t, v)
|
||||
}
|
||||
}
|
||||
|
||||
var testData = [][]string{
|
||||
{
|
||||
"CREATE TABLE information (age INT(11) NULL);",
|
||||
"Age int `gorm:\"column:age\"`", "",
|
||||
},
|
||||
{
|
||||
"CREATE TABLE information (age BIGINT(11) NULL COMMENT 'is age');",
|
||||
"Age int64 `gorm:\"column:age\"` // is age", "",
|
||||
},
|
||||
{
|
||||
"CREATE TABLE information (id BIGINT(11) PRIMARY KEY AUTO_INCREMENT);",
|
||||
"ID int64 `gorm:\"column:id;primary_key;AUTO_INCREMENT\"`", "",
|
||||
},
|
||||
{
|
||||
"CREATE TABLE information (user_ip varchar(20));",
|
||||
"UserIP string `gorm:\"column:user_ip\"`", "",
|
||||
},
|
||||
{
|
||||
"CREATE TABLE information (created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP);",
|
||||
"CreatedAt time.Time `gorm:\"column:created_at;default:CURRENT_TIMESTAMP;NOT NULL\"`", "time",
|
||||
},
|
||||
{
|
||||
"CREATE TABLE information (num INT(11) DEFAULT 3 NULL);",
|
||||
"Num int `gorm:\"column:num;default:3\"`", "",
|
||||
},
|
||||
{
|
||||
"CREATE TABLE information (num double(5,6) DEFAULT 31.50 NULL);",
|
||||
"Num float64 `gorm:\"column:num;default:31.50\"`", "",
|
||||
},
|
||||
{
|
||||
"CREATE TABLE information (comment TEXT);",
|
||||
"Comment string `gorm:\"column:comment\"`", "",
|
||||
},
|
||||
{
|
||||
"CREATE TABLE information (comment TINYTEXT);",
|
||||
"Comment string `gorm:\"column:comment\"`", "",
|
||||
},
|
||||
{
|
||||
"CREATE TABLE information (comment LONGTEXT);",
|
||||
"Comment string `gorm:\"column:comment\"`", "",
|
||||
},
|
||||
}
|
||||
|
||||
func TestParseSQLs(t *testing.T) {
|
||||
for i, test := range testData {
|
||||
msg := fmt.Sprintf("sql-%d", i)
|
||||
codes, err := ParseSQL(test[0], WithNoNullType())
|
||||
if !assert.NoError(t, err, msg) {
|
||||
continue
|
||||
}
|
||||
for k, v := range codes {
|
||||
t.Log(i+1, k, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func Test_toCamel(t *testing.T) {
|
||||
str := "user_example"
|
||||
t.Log(toCamel(str))
|
||||
}
|
||||
|
||||
func Test_parseOption(t *testing.T) {
|
||||
opts := []Option{
|
||||
WithCharset("foo"),
|
||||
WithCollation("foo"),
|
||||
WithTablePrefix("foo"),
|
||||
WithColumnPrefix("foo"),
|
||||
WithJSONTag(1),
|
||||
WithNoNullType(),
|
||||
WithNullStyle(1),
|
||||
WithPackage("model"),
|
||||
WithGormType(),
|
||||
WithForceTableName(),
|
||||
WithEmbed(),
|
||||
}
|
||||
o := parseOption(opts)
|
||||
assert.NotNil(t, o)
|
||||
}
|
||||
|
||||
func Test_mysqlToGoType(t *testing.T) {
|
||||
testData := []*types.FieldType{
|
||||
{Tp: uint8('n')},
|
||||
{Tp: mysql.TypeTiny},
|
||||
{Tp: mysql.TypeLonglong},
|
||||
{Tp: mysql.TypeFloat},
|
||||
{Tp: mysql.TypeString},
|
||||
{Tp: mysql.TypeTimestamp},
|
||||
{Tp: mysql.TypeDecimal},
|
||||
{Tp: mysql.TypeJSON},
|
||||
}
|
||||
var names []string
|
||||
for _, d := range testData {
|
||||
name1, _ := mysqlToGoType(d, NullInSql)
|
||||
name2, _ := mysqlToGoType(d, NullInPointer)
|
||||
names = append(names, name1, name2)
|
||||
}
|
||||
t.Log(names)
|
||||
}
|
||||
|
||||
func Test_goTypeToProto(t *testing.T) {
|
||||
testData := []tmplField{
|
||||
{GoType: "int"},
|
||||
{GoType: "uint"},
|
||||
{GoType: "time.Time"},
|
||||
}
|
||||
v := goTypeToProto(testData)
|
||||
assert.NotNil(t, v)
|
||||
}
|
||||
|
||||
func TestGetTableInfo(t *testing.T) {
|
||||
info, err := GetTableInfo("root:123456@(192.168.3.37:3306)/test", "user")
|
||||
t.Log(err, info)
|
||||
}
|
||||
|
||||
func Test_templateNew(t *testing.T) {
|
||||
|
||||
}
|
||||
274
pkg/sql2code/parser/template.go
Normal file
274
pkg/sql2code/parser/template.go
Normal file
@@ -0,0 +1,274 @@
|
||||
package parser
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
var (
|
||||
modelStructTmpl *template.Template
|
||||
modelStructTmplRaw = `
|
||||
{{- if .Comment -}}
|
||||
// {{.TableName}} {{.Comment}}
|
||||
{{end -}}
|
||||
type {{.TableName}} struct {
|
||||
{{- range .Fields}}
|
||||
{{.Name}} {{.GoType}} {{if .Tag}}` + "`{{.Tag}}`" + `{{end}}{{if .Comment}} // {{.Comment}}{{end}}
|
||||
{{- end}}
|
||||
}
|
||||
{{if .NameFunc}}
|
||||
// TableName table name
|
||||
func (m *{{.TableName}}) TableName() string {
|
||||
return "{{.RawTableName}}"
|
||||
}
|
||||
{{end}}
|
||||
`
|
||||
|
||||
modelTmpl *template.Template
|
||||
modelTmplRaw = `package {{.Package}}
|
||||
{{if .ImportPath}}
|
||||
import (
|
||||
{{- range .ImportPath}}
|
||||
"{{.}}"
|
||||
{{- end}}
|
||||
)
|
||||
{{- end}}
|
||||
{{range .StructCode}}
|
||||
{{.}}
|
||||
{{end}}`
|
||||
|
||||
updateFieldTmpl *template.Template
|
||||
updateFieldTmplRaw = `
|
||||
{{- range .Fields}}
|
||||
if table.{{.Name}} {{.ConditionZero}} {
|
||||
update["{{.ColName}}"] = table.{{.Name}}
|
||||
}
|
||||
{{- end}}`
|
||||
|
||||
handlerCreateStructTmpl *template.Template
|
||||
handlerCreateStructTmplRaw = `
|
||||
// Create{{.TableName}}Request create params
|
||||
// todo fill in the binding rules https://github.com/go-playground/validator
|
||||
type Create{{.TableName}}Request struct {
|
||||
{{- range .Fields}}
|
||||
{{.Name}} {{.GoType}} ` + "`" + `json:"{{.ColName}}" binding:""` + "`" + `{{if .Comment}} // {{.Comment}}{{end}}
|
||||
{{- end}}
|
||||
}
|
||||
`
|
||||
|
||||
handlerUpdateStructTmpl *template.Template
|
||||
handlerUpdateStructTmplRaw = `
|
||||
// Update{{.TableName}}ByIDRequest update params
|
||||
type Update{{.TableName}}ByIDRequest struct {
|
||||
{{- range .Fields}}
|
||||
{{.Name}} {{.GoType}} ` + "`" + `json:"{{.ColName}}" binding:""` + "`" + `{{if .Comment}} // {{.Comment}}{{end}}
|
||||
{{- end}}
|
||||
}
|
||||
`
|
||||
|
||||
handlerDetailStructTmpl *template.Template
|
||||
handlerDetailStructTmplRaw = `
|
||||
// Get{{.TableName}}ByIDRespond respond detail
|
||||
type Get{{.TableName}}ByIDRespond struct {
|
||||
{{- range .Fields}}
|
||||
{{.Name}} {{.GoType}} ` + "`" + `json:"{{.ColName}}"` + "`" + `{{if .Comment}} // {{.Comment}}{{end}}
|
||||
{{- end}}
|
||||
}`
|
||||
|
||||
modelJSONTmpl *template.Template
|
||||
modelJSONTmplRaw = `{
|
||||
{{- range .Fields}}
|
||||
"{{.ColName}}" {{.GoZero}}
|
||||
{{- end}}
|
||||
}
|
||||
`
|
||||
|
||||
protoFileTmpl *template.Template
|
||||
protoFileTmplRaw = `syntax = "proto3";
|
||||
|
||||
package api.serverNameExample.v1;
|
||||
|
||||
import "api/types/types.proto";
|
||||
// import "validate/validate.proto";
|
||||
|
||||
option go_package = "github.com/zhufuyi/sponge/api/serverNameExample/v1;v1";
|
||||
|
||||
service {{.TName}}Service {
|
||||
rpc Create(Create{{.TableName}}Request) returns (Create{{.TableName}}Reply) {}
|
||||
rpc DeleteByID(Delete{{.TableName}}ByIDRequest) returns (Delete{{.TableName}}ByIDReply) {}
|
||||
rpc UpdateByID(Update{{.TableName}}ByIDRequest) returns (Update{{.TableName}}ByIDReply) {}
|
||||
rpc GetByID(Get{{.TableName}}ByIDRequest) returns (Get{{.TableName}}ByIDReply) {}
|
||||
rpc ListByIDs(List{{.TableName}}ByIDsRequest) returns (List{{.TableName}}ByIDsReply) {}
|
||||
rpc List(List{{.TableName}}Request) returns (List{{.TableName}}Reply) {}
|
||||
}
|
||||
|
||||
// todo fill in the validate rules https://github.com/envoyproxy/protoc-gen-validate#constraint-rules
|
||||
|
||||
// protoMessageCreateCode
|
||||
|
||||
message Create{{.TableName}}Reply {
|
||||
uint64 id =1;
|
||||
}
|
||||
|
||||
message Delete{{.TableName}}ByIDRequest {
|
||||
uint64 id =1;
|
||||
}
|
||||
|
||||
message Delete{{.TableName}}ByIDReply {
|
||||
|
||||
}
|
||||
|
||||
// protoMessageUpdateCode
|
||||
|
||||
message Update{{.TableName}}ByIDReply {
|
||||
|
||||
}
|
||||
|
||||
// protoMessageDetailCode
|
||||
|
||||
message Get{{.TableName}}ByIDRequest {
|
||||
uint64 id =1;
|
||||
}
|
||||
|
||||
message Get{{.TableName}}ByIDReply {
|
||||
{{.TableName}} {{.TName}} = 1;
|
||||
}
|
||||
|
||||
message List{{.TableName}}ByIDsRequest {
|
||||
repeated uint64 ids = 1;
|
||||
}
|
||||
|
||||
message List{{.TableName}}ByIDsReply {
|
||||
repeated {{.TableName}} {{.TName}}s = 1;
|
||||
}
|
||||
|
||||
message List{{.TableName}}Request {
|
||||
types.Params params = 1;
|
||||
}
|
||||
|
||||
message List{{.TableName}}Reply {
|
||||
int64 total =1;
|
||||
repeated {{.TableName}} {{.TName}}s = 2;
|
||||
}
|
||||
`
|
||||
|
||||
protoMessageCreateTmpl *template.Template
|
||||
protoMessageCreateTmplRaw = `message Create{{.TableName}}Request {
|
||||
{{- range $i, $v := .Fields}}
|
||||
{{$v.GoType}} {{$v.ColName}} = {{$v.AddOne $i}}; {{if $v.Comment}} // {{$v.Comment}}{{end}}
|
||||
{{- end}}
|
||||
}`
|
||||
|
||||
protoMessageUpdateTmpl *template.Template
|
||||
protoMessageUpdateTmplRaw = `message Update{{.TableName}}ByIDRequest {
|
||||
{{- range $i, $v := .Fields}}
|
||||
{{$v.GoType}} {{$v.ColName}} = {{$v.AddOne $i}}; {{if $v.Comment}} // {{$v.Comment}}{{end}}
|
||||
{{- end}}
|
||||
}`
|
||||
|
||||
protoMessageDetailTmpl *template.Template
|
||||
protoMessageDetailTmplRaw = `message {{.TableName}} {
|
||||
{{- range $i, $v := .Fields}}
|
||||
{{$v.GoType}} {{$v.ColName}} = {{$v.AddOne $i}}; {{if $v.Comment}} // {{$v.Comment}}{{end}}
|
||||
{{- end}}
|
||||
}`
|
||||
|
||||
serviceStructTmpl *template.Template
|
||||
serviceStructTmplRaw = `
|
||||
{
|
||||
name: "Create",
|
||||
fn: func() (interface{}, error) {
|
||||
// todo test after filling in parameters
|
||||
// serviceCreateStructCode
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
|
||||
{
|
||||
name: "UpdateByID",
|
||||
fn: func() (interface{}, error) {
|
||||
// todo test after filling in parameters
|
||||
// serviceUpdateStructCode
|
||||
},
|
||||
wantErr: false,
|
||||
},
|
||||
`
|
||||
|
||||
serviceCreateStructTmpl *template.Template
|
||||
serviceCreateStructTmplRaw = ` return cli.Create(ctx, &pb.Create{{.TableName}}Request{
|
||||
{{- range .Fields}}
|
||||
{{.Name}}: {{.GoTypeZero}}, {{if .Comment}} // {{.Comment}}{{end}}
|
||||
{{- end}}
|
||||
})`
|
||||
|
||||
serviceUpdateStructTmpl *template.Template
|
||||
serviceUpdateStructTmplRaw = ` return cli.UpdateByID(ctx, &pb.Update{{.TableName}}ByIDRequest{
|
||||
{{- range .Fields}}
|
||||
{{.Name}}: {{.GoTypeZero}}, {{if .Comment}} // {{.Comment}}{{end}}
|
||||
{{- end}}
|
||||
})`
|
||||
|
||||
tmplParseOnce sync.Once
|
||||
)
|
||||
|
||||
func initTemplate() {
|
||||
tmplParseOnce.Do(func() {
|
||||
var err error
|
||||
modelStructTmpl, err = template.New("goStruct").Parse(modelStructTmplRaw)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
modelTmpl, err = template.New("goFile").Parse(modelTmplRaw)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
updateFieldTmpl, err = template.New("goUpdateField").Parse(updateFieldTmplRaw)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
handlerCreateStructTmpl, err = template.New("goPostStruct").Parse(handlerCreateStructTmplRaw)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
handlerUpdateStructTmpl, err = template.New("goPutStruct").Parse(handlerUpdateStructTmplRaw)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
handlerDetailStructTmpl, err = template.New("goGetStruct").Parse(handlerDetailStructTmplRaw)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
modelJSONTmpl, err = template.New("modelJSON").Parse(modelJSONTmplRaw)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
protoFileTmpl, err = template.New("protoFile").Parse(protoFileTmplRaw)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
protoMessageCreateTmpl, err = template.New("protoMessageCreate").Parse(protoMessageCreateTmplRaw)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
protoMessageUpdateTmpl, err = template.New("protoMessageUpdate").Parse(protoMessageUpdateTmplRaw)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
protoMessageDetailTmpl, err = template.New("protoMessageDetail").Parse(protoMessageDetailTmplRaw)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
serviceCreateStructTmpl, err = template.New("serviceCreateStruct").Parse(serviceCreateStructTmplRaw)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
serviceUpdateStructTmpl, err = template.New("serviceUpdateStruct").Parse(serviceUpdateStructTmplRaw)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
serviceStructTmpl, err = template.New("serviceStruct").Parse(serviceStructTmplRaw)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user