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

@ -2,6 +2,7 @@ package command
import (
"errors"
"fmt"
"io/ioutil"
"path/filepath"
"strings"
@ -21,6 +22,7 @@ const (
flagDir = "dir"
flagCache = "cache"
flagIdea = "idea"
flagStyle = "style"
flagUrl = "url"
flagTable = "table"
)
@ -30,12 +32,21 @@ func MysqlDDL(ctx *cli.Context) error {
dir := ctx.String(flagDir)
cache := ctx.Bool(flagCache)
idea := ctx.Bool(flagIdea)
namingStyle := strings.TrimSpace(ctx.String(flagStyle))
log := console.NewConsole(idea)
src = strings.TrimSpace(src)
if len(src) == 0 {
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)
if err != nil {
return err
@ -49,7 +60,7 @@ func MysqlDDL(ctx *cli.Context) error {
}
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)
if err != nil {
log.Error("%v", err)
@ -62,6 +73,7 @@ func MyDataSource(ctx *cli.Context) error {
dir := strings.TrimSpace(ctx.String(flagDir))
cache := ctx.Bool(flagCache)
idea := ctx.Bool(flagIdea)
namingStyle := strings.TrimSpace(ctx.String(flagStyle))
pattern := strings.TrimSpace(ctx.String(flagTable))
log := console.NewConsole(idea)
if len(url) == 0 {
@ -74,6 +86,14 @@ func MyDataSource(ctx *cli.Context) error {
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)
if err != nil {
return err
@ -114,7 +134,7 @@ func MyDataSource(ctx *cli.Context) error {
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)
if err != nil {
log.Error("%v", err)

@ -17,6 +17,9 @@ import (
const (
pwd = "."
createTableFlag = `(?m)^(?i)CREATE\s+TABLE` // ignore case
NamingLower = "lower"
NamingCamel = "camel"
NamingUnderline = "underline"
)
type (
@ -25,15 +28,16 @@ type (
dir string
console.Console
pkg string
namingStyle string
}
Option func(generator *defaultGenerator)
)
func NewDefaultGenerator(source, dir string, opt ...Option) *defaultGenerator {
func NewDefaultGenerator(source, dir, namingStyle string, opt ...Option) *defaultGenerator {
if dir == "" {
dir = pwd
}
generator := &defaultGenerator{source: source, dir: dir}
generator := &defaultGenerator{source: source, dir: dir, namingStyle: namingStyle}
var optionList []Option
optionList = append(optionList, newDefaultOption())
optionList = append(optionList, opt...)
@ -72,7 +76,14 @@ func (g *defaultGenerator) Start(withCache bool) error {
}
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)
if util.FileExists(filename) {
g.Warning("%s already exists, ignored.", name)
@ -85,7 +96,7 @@ func (g *defaultGenerator) Start(withCache bool) error {
}
// generate error file
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 {
return err
}

@ -8,13 +8,27 @@ import (
)
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) {
logx.Disable()
_ = Clean()
g := NewDefaultGenerator(source, "./testmodel")
g := NewDefaultGenerator(source, "./testmodel/cache", NamingLower)
err := g.Start(true)
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}}
_, 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}})
}, {{.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}}
return err
}

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

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

@ -4,11 +4,11 @@ var Insert = `
func (m *{{.upperStartCamelObject}}Model) Insert(data {{.upperStartCamelObject}}) (sql.Result,error) {
{{if .withCache}}{{if .containsIndexCache}}{{.keys}}
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}})
}, {{.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}})
{{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}}
return ret,err
}

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

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

Loading…
Cancel
Save