model template fix (#169)

* replace quote

* rpc disable override main.go

* reactor template

* add model flag -style

* add model flag -style

* reactor model  template name of error
master
Keson 4 years ago committed by GitHub
parent 4287877b74
commit 607fc3297a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -275,6 +275,10 @@ var (
Name: "dir, d", Name: "dir, d",
Usage: "the target dir", Usage: "the target dir",
}, },
cli.StringFlag{
Name: "style",
Usage: "the file naming style, lower|camel|underline,default is lower",
},
cli.BoolFlag{ cli.BoolFlag{
Name: "cache, c", Name: "cache, c",
Usage: "generate code with cache [optional]", Usage: "generate code with cache [optional]",
@ -306,6 +310,10 @@ var (
Name: "dir, d", Name: "dir, d",
Usage: "the target dir", Usage: "the target dir",
}, },
cli.StringFlag{
Name: "style",
Usage: "the file naming style, lower|camel|underline,default is lower",
},
cli.BoolFlag{ cli.BoolFlag{
Name: "idea", Name: "idea",
Usage: "for idea plugin [optional]", Usage: "for idea plugin [optional]",

@ -2,6 +2,7 @@ package command
import ( import (
"errors" "errors"
"fmt"
"io/ioutil" "io/ioutil"
"path/filepath" "path/filepath"
"strings" "strings"
@ -21,6 +22,7 @@ const (
flagDir = "dir" flagDir = "dir"
flagCache = "cache" flagCache = "cache"
flagIdea = "idea" flagIdea = "idea"
flagStyle = "style"
flagUrl = "url" flagUrl = "url"
flagTable = "table" flagTable = "table"
) )
@ -30,12 +32,21 @@ func MysqlDDL(ctx *cli.Context) error {
dir := ctx.String(flagDir) dir := ctx.String(flagDir)
cache := ctx.Bool(flagCache) cache := ctx.Bool(flagCache)
idea := ctx.Bool(flagIdea) idea := ctx.Bool(flagIdea)
namingStyle := strings.TrimSpace(ctx.String(flagStyle))
log := console.NewConsole(idea) log := console.NewConsole(idea)
src = strings.TrimSpace(src) src = strings.TrimSpace(src)
if len(src) == 0 { if len(src) == 0 {
return errors.New("expected path or path globbing patterns, but nothing found") return errors.New("expected path or path globbing patterns, but nothing found")
} }
switch namingStyle {
case gen.NamingLower, gen.NamingCamel, gen.NamingUnderline:
case "":
namingStyle = gen.NamingLower
default:
return fmt.Errorf("unexpected naming style: %s", namingStyle)
}
files, err := util.MatchFiles(src) files, err := util.MatchFiles(src)
if err != nil { if err != nil {
return err return err
@ -49,7 +60,7 @@ func MysqlDDL(ctx *cli.Context) error {
} }
source = append(source, string(data)) source = append(source, string(data))
} }
generator := gen.NewDefaultGenerator(strings.Join(source, "\n"), dir, gen.WithConsoleOption(log)) generator := gen.NewDefaultGenerator(strings.Join(source, "\n"), dir, namingStyle, gen.WithConsoleOption(log))
err = generator.Start(cache) err = generator.Start(cache)
if err != nil { if err != nil {
log.Error("%v", err) log.Error("%v", err)
@ -62,6 +73,7 @@ func MyDataSource(ctx *cli.Context) error {
dir := strings.TrimSpace(ctx.String(flagDir)) dir := strings.TrimSpace(ctx.String(flagDir))
cache := ctx.Bool(flagCache) cache := ctx.Bool(flagCache)
idea := ctx.Bool(flagIdea) idea := ctx.Bool(flagIdea)
namingStyle := strings.TrimSpace(ctx.String(flagStyle))
pattern := strings.TrimSpace(ctx.String(flagTable)) pattern := strings.TrimSpace(ctx.String(flagTable))
log := console.NewConsole(idea) log := console.NewConsole(idea)
if len(url) == 0 { if len(url) == 0 {
@ -74,6 +86,14 @@ func MyDataSource(ctx *cli.Context) error {
return nil return nil
} }
switch namingStyle {
case gen.NamingLower, gen.NamingCamel, gen.NamingUnderline:
case "":
namingStyle = gen.NamingLower
default:
return fmt.Errorf("unexpected naming style: %s", namingStyle)
}
cfg, err := mysql.ParseDSN(url) cfg, err := mysql.ParseDSN(url)
if err != nil { if err != nil {
return err return err
@ -114,7 +134,7 @@ func MyDataSource(ctx *cli.Context) error {
return nil return nil
} }
generator := gen.NewDefaultGenerator(strings.Join(ddl, "\n"), dir, gen.WithConsoleOption(log)) generator := gen.NewDefaultGenerator(strings.Join(ddl, "\n"), dir, namingStyle, gen.WithConsoleOption(log))
err = generator.Start(cache) err = generator.Start(cache)
if err != nil { if err != nil {
log.Error("%v", err) log.Error("%v", err)

@ -17,6 +17,9 @@ import (
const ( const (
pwd = "." pwd = "."
createTableFlag = `(?m)^(?i)CREATE\s+TABLE` // ignore case createTableFlag = `(?m)^(?i)CREATE\s+TABLE` // ignore case
NamingLower = "lower"
NamingCamel = "camel"
NamingUnderline = "underline"
) )
type ( type (
@ -24,16 +27,17 @@ type (
source string source string
dir string dir string
console.Console console.Console
pkg string pkg string
namingStyle string
} }
Option func(generator *defaultGenerator) Option func(generator *defaultGenerator)
) )
func NewDefaultGenerator(source, dir string, opt ...Option) *defaultGenerator { func NewDefaultGenerator(source, dir, namingStyle string, opt ...Option) *defaultGenerator {
if dir == "" { if dir == "" {
dir = pwd dir = pwd
} }
generator := &defaultGenerator{source: source, dir: dir} generator := &defaultGenerator{source: source, dir: dir, namingStyle: namingStyle}
var optionList []Option var optionList []Option
optionList = append(optionList, newDefaultOption()) optionList = append(optionList, newDefaultOption())
optionList = append(optionList, opt...) optionList = append(optionList, opt...)
@ -72,7 +76,14 @@ func (g *defaultGenerator) Start(withCache bool) error {
} }
for tableName, code := range modelList { for tableName, code := range modelList {
name := fmt.Sprintf("%smodel.go", strings.ToLower(stringx.From(tableName).ToCamel())) tn := stringx.From(tableName)
name := fmt.Sprintf("%smodel.go", strings.ToLower(tn.ToCamel()))
switch g.namingStyle {
case NamingCamel:
name = fmt.Sprintf("%sModel.go", tn.ToCamel())
case NamingUnderline:
name = fmt.Sprintf("%s_model.go", tn.ToSnake())
}
filename := filepath.Join(dirAbs, name) filename := filepath.Join(dirAbs, name)
if util.FileExists(filename) { if util.FileExists(filename) {
g.Warning("%s already exists, ignored.", name) g.Warning("%s already exists, ignored.", name)
@ -85,7 +96,7 @@ func (g *defaultGenerator) Start(withCache bool) error {
} }
// generate error file // generate error file
filename := filepath.Join(dirAbs, "vars.go") filename := filepath.Join(dirAbs, "vars.go")
text, err := util.LoadTemplate(category, modelTemplateFile, template.Error) text, err := util.LoadTemplate(category, errTemplateFile, template.Error)
if err != nil { if err != nil {
return err return err
} }

@ -8,13 +8,27 @@ import (
) )
var ( var (
source = "CREATE TABLE `test` (\n `id` bigint NOT NULL AUTO_INCREMENT,\n `nanosecond` bigint NOT NULL DEFAULT '0',\n `data` varchar(255) DEFAULT '',\n `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,\n `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`),\n UNIQUE KEY `nanosecond_unique` (`nanosecond`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;" source = "CREATE TABLE `test_user_info` (\n `id` bigint NOT NULL AUTO_INCREMENT,\n `nanosecond` bigint NOT NULL DEFAULT '0',\n `data` varchar(255) DEFAULT '',\n `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,\n `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`),\n UNIQUE KEY `nanosecond_unique` (`nanosecond`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;"
) )
func TestCacheModel(t *testing.T) { func TestCacheModel(t *testing.T) {
logx.Disable() logx.Disable()
_ = Clean() _ = Clean()
g := NewDefaultGenerator(source, "./testmodel") g := NewDefaultGenerator(source, "./testmodel/cache", NamingLower)
err := g.Start(true) err := g.Start(true)
assert.Nil(t, err) assert.Nil(t, err)
g = NewDefaultGenerator(source, "./testmodel/nocache", NamingLower)
err = g.Start(false)
assert.Nil(t, err)
}
func TestNamingModel(t *testing.T) {
logx.Disable()
_ = Clean()
g := NewDefaultGenerator(source, "./testmodel/camel", NamingCamel)
err := g.Start(true)
assert.Nil(t, err)
g = NewDefaultGenerator(source, "./testmodel/snake", NamingUnderline)
err = g.Start(true)
assert.Nil(t, err)
} }

@ -9,9 +9,9 @@ func (m *{{.upperStartCamelObject}}Model) Delete({{.lowerStartCamelPrimaryKey}}
{{.keys}} {{.keys}}
_, err {{if .containsIndexCache}}={{else}}:={{end}} m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) { _, err {{if .containsIndexCache}}={{else}}:={{end}} m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
query := ` + "`" + `delete from ` + "` +" + ` m.table + ` + " `" + ` where {{.originalPrimaryKey}} = ?` + "`" + ` query := fmt.Sprintf("delete from %s where {{.originalPrimaryKey}} = ?", m.table)
return conn.Exec(query, {{.lowerStartCamelPrimaryKey}}) return conn.Exec(query, {{.lowerStartCamelPrimaryKey}})
}, {{.keyValues}}){{else}}query := ` + "`" + `delete from ` + "` +" + ` m.table + ` + " `" + ` where {{.originalPrimaryKey}} = ?` + "`" + ` }, {{.keyValues}}){{else}}query := fmt.Sprintf("delete from %s where {{.originalPrimaryKey}} = ?", m.table)
_,err:=m.conn.Exec(query, {{.lowerStartCamelPrimaryKey}}){{end}} _,err:=m.conn.Exec(query, {{.lowerStartCamelPrimaryKey}}){{end}}
return err return err
} }

@ -6,8 +6,7 @@ func (m *{{.upperStartCamelObject}}Model) FindOne({{.lowerStartCamelPrimaryKey}}
{{if .withCache}}{{.cacheKey}} {{if .withCache}}{{.cacheKey}}
var resp {{.upperStartCamelObject}} var resp {{.upperStartCamelObject}}
err := m.QueryRow(&resp, {{.cacheKeyVariable}}, func(conn sqlx.SqlConn, v interface{}) error { err := m.QueryRow(&resp, {{.cacheKeyVariable}}, func(conn sqlx.SqlConn, v interface{}) error {
query := ` + "`" + `select ` + "`" + ` + {{.lowerStartCamelObject}}Rows + ` + "`" + ` from ` + "` + " + `m.table ` + query := fmt.Sprintf("select %s from %s where {{.originalPrimaryKey}} = ? limit 1", {{.lowerStartCamelObject}}Rows, m.table)
" + `" + ` where {{.originalPrimaryKey}} = ? limit 1` + "`" + `
return conn.QueryRow(v, query, {{.lowerStartCamelPrimaryKey}}) return conn.QueryRow(v, query, {{.lowerStartCamelPrimaryKey}})
}) })
switch err { switch err {
@ -17,8 +16,7 @@ func (m *{{.upperStartCamelObject}}Model) FindOne({{.lowerStartCamelPrimaryKey}}
return nil, ErrNotFound return nil, ErrNotFound
default: default:
return nil, err return nil, err
}{{else}}query := ` + "`" + `select ` + "`" + ` + {{.lowerStartCamelObject}}Rows + ` + "`" + ` from ` + "` + " + `m.table ` + " + `" + }{{else}}query := fmt.Sprintf("select %s from %s where {{.originalPrimaryKey}} = ? limit 1", {{.lowerStartCamelObject}}Rows, m.table)
` where {{.originalPrimaryKey}} = ? limit 1` + "`" + `
var resp {{.upperStartCamelObject}} var resp {{.upperStartCamelObject}}
err := m.conn.QueryRow(&resp, query, {{.lowerStartCamelPrimaryKey}}) err := m.conn.QueryRow(&resp, query, {{.lowerStartCamelPrimaryKey}})
switch err { switch err {
@ -38,8 +36,7 @@ func (m *{{.upperStartCamelObject}}Model) FindOneBy{{.upperField}}({{.in}}) (*{{
{{if .withCache}}{{.cacheKey}} {{if .withCache}}{{.cacheKey}}
var resp {{.upperStartCamelObject}} var resp {{.upperStartCamelObject}}
err := m.QueryRowIndex(&resp, {{.cacheKeyVariable}}, m.formatPrimary, func(conn sqlx.SqlConn, v interface{}) (i interface{}, e error) { err := m.QueryRowIndex(&resp, {{.cacheKeyVariable}}, m.formatPrimary, func(conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
query := ` + "`" + `select ` + "`" + ` + {{.lowerStartCamelObject}}Rows + ` + "`" + ` from ` + "` + " + `m.table ` + " + `" + query := fmt.Sprintf("select %s from %s where {{.originalField}} = ? limit 1", {{.lowerStartCamelObject}}Rows, m.table)
` where {{.originalField}} = ? limit 1` + "`" + `
if err := conn.QueryRow(&resp, query, {{.lowerStartCamelField}}); err != nil { if err := conn.QueryRow(&resp, query, {{.lowerStartCamelField}}); err != nil {
return nil, err return nil, err
} }
@ -54,8 +51,7 @@ func (m *{{.upperStartCamelObject}}Model) FindOneBy{{.upperField}}({{.in}}) (*{{
return nil, err return nil, err
} }
}{{else}}var resp {{.upperStartCamelObject}} }{{else}}var resp {{.upperStartCamelObject}}
query := ` + "`" + `select ` + "`" + ` + {{.lowerStartCamelObject}}Rows + ` + "`" + ` from ` + "` + " + `m.table ` + " + `" + query := fmt.Sprintf("select %s from %s where {{.originalField}} = ? limit 1", {{.lowerStartCamelObject}}Rows, m.table )
` where {{.originalField}} = ? limit 1` + "`" + `
err := m.conn.QueryRow(&resp, query, {{.lowerStartCamelField}}) err := m.conn.QueryRow(&resp, query, {{.lowerStartCamelField}})
switch err { switch err {
case nil: case nil:
@ -73,8 +69,7 @@ func (m *{{.upperStartCamelObject}}Model) formatPrimary(primary interface{}) str
} }
func (m *{{.upperStartCamelObject}}Model) queryPrimary(conn sqlx.SqlConn, v, primary interface{}) error { func (m *{{.upperStartCamelObject}}Model) queryPrimary(conn sqlx.SqlConn, v, primary interface{}) error {
query := ` + "`" + `select ` + "`" + ` + {{.lowerStartCamelObject}}Rows + ` + "`" + ` from ` + "` + " + `m.table ` + " + `" + query := fmt.Sprintf("select %s from %s where {{.originalPrimaryField}} = ? limit 1", {{.lowerStartCamelObject}}Rows, m.table )
` where {{.originalPrimaryField}} = ? limit 1` + "`" + `
return conn.QueryRow(v, query, primary) return conn.QueryRow(v, query, primary)
} }
` `

@ -16,6 +16,7 @@ var (
` `
ImportsNoCache = `import ( ImportsNoCache = `import (
"database/sql" "database/sql"
"fmt"
"strings" "strings"
{{if .time}}"time"{{end}} {{if .time}}"time"{{end}}

@ -4,11 +4,11 @@ var Insert = `
func (m *{{.upperStartCamelObject}}Model) Insert(data {{.upperStartCamelObject}}) (sql.Result,error) { func (m *{{.upperStartCamelObject}}Model) Insert(data {{.upperStartCamelObject}}) (sql.Result,error) {
{{if .withCache}}{{if .containsIndexCache}}{{.keys}} {{if .withCache}}{{if .containsIndexCache}}{{.keys}}
ret, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) { ret, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
query := ` + "`" + `insert into ` + "`" + ` + m.table + ` + "` (` + " + `{{.lowerStartCamelObject}}RowsExpectAutoSet` + " + `) values ({{.expression}})` " + ` query := fmt.Sprintf("insert into %s (%s) values ({{.expression}})", m.table, {{.lowerStartCamelObject}}RowsExpectAutoSet)
return conn.Exec(query, {{.expressionValues}}) return conn.Exec(query, {{.expressionValues}})
}, {{.keyValues}}){{else}}query := ` + "`" + `insert into ` + "`" + ` + m.table + ` + "` (` + " + `{{.lowerStartCamelObject}}RowsExpectAutoSet` + " + `) values ({{.expression}})` " + ` }, {{.keyValues}}){{else}}query := fmt.Sprintf("insert into %s (%s) values ({{.expression}})", m.table, {{.lowerStartCamelObject}}RowsExpectAutoSet)
ret,err:=m.ExecNoCache(query, {{.expressionValues}}) ret,err:=m.ExecNoCache(query, {{.expressionValues}})
{{end}}{{else}}query := ` + "`" + `insert into ` + "`" + ` + m.table + ` + "` (` + " + `{{.lowerStartCamelObject}}RowsExpectAutoSet` + " + `) values ({{.expression}})` " + ` {{end}}{{else}}query := fmt.Sprintf("insert into %s (%s) values ({{.expression}})", m.table, {{.lowerStartCamelObject}}RowsExpectAutoSet)
ret,err:=m.conn.Exec(query, {{.expressionValues}}){{end}} ret,err:=m.conn.Exec(query, {{.expressionValues}}){{end}}
return ret,err return ret,err
} }

@ -1,13 +1,13 @@
package template package template
var Update = ` var Update = `
func (m *{{.upperStartCamelObject}}Model) Update(data {{.upperStartCamelObject}}) (sql.Result,error) { func (m *{{.upperStartCamelObject}}Model) Update(data {{.upperStartCamelObject}}) error {
{{if .withCache}}{{.primaryCacheKey}} {{if .withCache}}{{.primaryCacheKey}}
ret, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) { _, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
query := ` + "`" + `update ` + "` +" + `m.table +` + "` " + `set ` + "` +" + `{{.lowerStartCamelObject}}RowsWithPlaceHolder` + " + `" + ` where {{.originalPrimaryKey}} = ?` + "`" + ` query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = ?", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder)
return conn.Exec(query, {{.expressionValues}}) return conn.Exec(query, {{.expressionValues}})
}, {{.primaryKeyVariable}}){{else}}query := ` + "`" + `update ` + "` +" + `m.table +` + "` " + `set ` + "` +" + `{{.lowerStartCamelObject}}RowsWithPlaceHolder` + " + `" + ` where {{.originalPrimaryKey}} = ?` + "`" + ` }, {{.primaryKeyVariable}}){{else}}query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = ?", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder)
ret,err:=m.conn.Exec(query, {{.expressionValues}}){{end}} _,err:=m.conn.Exec(query, {{.expressionValues}}){{end}}
return ret,err return err
} }
` `

@ -70,7 +70,7 @@ func (g *defaultRpcGenerator) genMain() error {
"srv": srv, "srv": srv,
"registers": registers, "registers": registers,
"imports": strings.Join(imports, util.NL), "imports": strings.Join(imports, util.NL),
}, fileName, true) }, fileName, false)
} }
func (g *defaultRpcGenerator) genServer(pkg string, list []*parser.RpcService) (string, string) { func (g *defaultRpcGenerator) genServer(pkg string, list []*parser.RpcService) (string, string) {

Loading…
Cancel
Save