func support

支持 函数导出。支持外键关联
This commit is contained in:
谢小军
2020-01-11 22:23:59 +08:00
parent 1ff17da96f
commit f8daa91659
9 changed files with 169 additions and 29 deletions

View File

@@ -48,6 +48,7 @@ Usage:
Flags:
-d, --database string 数据库名
-f, --foreign 是否导出外键关联
-F, --fun 是否导出函数
-h, --help help for main
-H, --host string 数据库地址.(注意-H为大写)
-o, --outdir string 输出目录

View File

@@ -52,6 +52,7 @@ Usage:
Flags:
-d, --database string 数据库名
-f, --foreign 是否导出外键关联
-F, --fun 是否导出函数
-h, --help help for main
-H, --host string 数据库地址.(注意-H为大写)
-o, --outdir string 输出目录

View File

@@ -2,7 +2,7 @@ base:
is_dev : false
out_dir : ./model # 输出目录
singular_table : false # 单表模式:true:禁用表名复数,false:采用表明复数 参考:gorm.SingularTable
simple : true # 简单输出(默认gorm标签不输出)
simple : false # 简单输出(默认gorm标签不输出)
is_out_sql : false # 是否输出 sql 原信息
is_out_func : true # 是否输出 快捷函数
is_json_tag : true # 是否打json标记

View File

@@ -18,6 +18,7 @@ var mysqlInfo config.MysqlDbInfo
var outDir string
var singularTable bool
var foreignKey bool
var funcKey bool
var rootCmd = &cobra.Command{
Use: "main",
@@ -60,6 +61,9 @@ func init() {
rootCmd.PersistentFlags().BoolVarP(&foreignKey, "foreign", "f", false, "是否导出外键关联")
rootCmd.MarkFlagRequired("foreign key")
rootCmd.PersistentFlags().BoolVarP(&funcKey, "fun", "F", false, "是否导出函数")
rootCmd.MarkFlagRequired("func export")
rootCmd.Flags().IntVar(&mysqlInfo.Port, "port", 3306, "端口号")
}
@@ -110,4 +114,8 @@ func MergeMysqlDbInfo() {
if foreignKey {
config.SetForeignKey(foreignKey)
}
if funcKey {
config.SetIsOutFunc(funcKey)
}
}

View File

@@ -36,7 +36,7 @@ func GetMysqlDbInfo() MysqlDbInfo {
// GetMysqlConStr Get MySQL connection string.获取mysql 连接字符串
func GetMysqlConStr() string {
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local&interpolateParams=true",
_map.MySQLInfo.Username,
_map.MySQLInfo.Password,
_map.MySQLInfo.Host,

View File

@@ -131,13 +131,32 @@ func (obj *_{{$obj.StructName}}Mgr) GetFrom{{$oem.ColStructName}}({{$oem.ColStr
return
}
{{end}}
// GetsBatchFrom{{$oem.ColStructName}} 批量唯一主键查找 {{$oem.Notes}}
func (obj *_{{$obj.StructName}}Mgr) GetsBatchFrom{{$oem.ColStructName}}({{$oem.ColStructName}}s []{{$oem.Type}}) (results []*{{$obj.StructName}}, err error) {
// GetBatchFrom{{$oem.ColStructName}} 批量唯一主键查找 {{$oem.Notes}}
func (obj *_{{$obj.StructName}}Mgr) GetBatchFrom{{$oem.ColStructName}}({{$oem.ColStructName}}s []{{$oem.Type}}) (results []*{{$obj.StructName}}, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("{{$oem.ColName}} IN (?)", {{$oem.ColStructName}}s).Find(&results).Error
{{GenPreloadList $obj.PreloadList true}}
return
}
{{end}}
//////////////////////////primary index case ////////////////////////////////////////////
{{range $ofm := $obj.Primay}}
// {{GenFListIndex $ofm 1}} primay or index 获取唯一内容
func (obj *_{{$obj.StructName}}Mgr) {{GenFListIndex $ofm 1}}({{GenFListIndex $ofm 2}}) (result {{$obj.StructName}}, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("{{GenFListIndex $ofm 3}}", {{GenFListIndex $ofm 4}}).Find(&result).Error
{{GenPreloadList $obj.PreloadList false}}
return
}
{{end}}
{{range $ofm := $obj.Index}}
// {{GenFListIndex $ofm 1}} 获取多个内容
func (obj *_{{$obj.StructName}}Mgr) {{GenFListIndex $ofm 1}}({{GenFListIndex $ofm 2}}) (results []*{{$obj.StructName}}, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("{{GenFListIndex $ofm 3}}", {{GenFListIndex $ofm 4}}).Find(&results).Error
{{GenPreloadList $obj.PreloadList true}}
return
}
{{end}}
`
genPreload = `if err == nil && obj.isRelated { {{range $obj := .}}{{if $obj.IsMulti}}
{

View File

@@ -1,11 +1,15 @@
package model
import (
"bytes"
"fmt"
"regexp"
"strings"
"text/template"
"github.com/xxjwxc/gormt/data/config"
"github.com/xxjwxc/gormt/data/view/cnf"
"github.com/xxjwxc/gormt/data/view/genfunc"
"github.com/xxjwxc/public/mybigcamel"
)
@@ -89,3 +93,94 @@ func getGormModelElement() []EmInfo {
})
return result
}
func buildFList(list *[]FList, key ColumusKey, keyName, tp, colName string) {
for i := 0; i < len(*list); i++ {
if (*list)[i].KeyName == keyName {
(*list)[i].Kem = append((*list)[i].Kem, FEm{
Type: tp,
ColName: colName,
ColStructName: getCamelName(colName),
})
return
}
}
// 没有 添加一个
*list = append(*list, FList{
Key: key,
KeyName: keyName,
Kem: []FEm{FEm{
Type: tp,
ColName: colName,
ColStructName: getCamelName(colName),
}},
})
}
// GenPreloadList 生成list
func GenPreloadList(list []PreloadInfo, multi bool) string {
if len(list) > 0 {
tmpl, err := template.New("gen_preload").Parse(genfunc.GetGenPreloadTemp(multi))
if err != nil {
panic(err)
}
var buf bytes.Buffer
tmpl.Execute(&buf, list)
return buf.String()
}
return ""
}
// GenFListIndex 生成list status(1:获取函数名,2:获取参数列表,3:获取sql case,4:值列表)
func GenFListIndex(info FList, status int) string {
switch status {
case 1: // 1:获取函数名
{
return widthFunctionName(info)
}
case 2: // 2:获取参数列表
{
var strs []string
for _, v := range info.Kem {
strs = append(strs, fmt.Sprintf("%v %v ", v.ColStructName, v.Type))
}
return strings.Join(strs, ",")
}
case 3: // 3:获取sql case,
{
var strs []string
for _, v := range info.Kem {
strs = append(strs, fmt.Sprintf("%v = ?", v.ColName))
}
return strings.Join(strs, " AND ")
}
case 4: // 4:值列表
{
var strs []string
for _, v := range info.Kem {
strs = append(strs, v.ColStructName)
}
return strings.Join(strs, " , ")
}
}
return ""
}
func widthFunctionName(info FList) string {
switch info.Key {
// case ColumusKeyDefault:
case ColumusKeyPrimary: // primary key.主键
return "FetchByPrimaryKey"
case ColumusKeyUnique: // unique key.唯一索引
return "FetchByUnique"
case ColumusKeyIndex: // index key.复合索引
return "FetchBy" + getCamelName(info.KeyName) + "Index"
case ColumusKeyUniqueIndex: // unique index key.唯一复合索引
return "FetchBy" + getCamelName(info.KeyName) + "UniqueIndex"
}
return ""
}

View File

@@ -82,19 +82,37 @@ type PreloadInfo struct {
}
// EmInfo func 表结构定义
// FEm ...
type FEm struct {
Type string // 类型
ColName string // 列名
ColStructName string // 列结构体
}
// FList index of list
type FList struct {
Key ColumusKey // non_unique of (show keys from [table])
KeyName string // key_name of (show keys from [table])
Kem []FEm
}
// EmInfo element of func info
type EmInfo struct {
IsMulti bool
Notes string // 注释
Type string // 类型
ColName string //
ColStructName string // 结构体
ColName string //
ColStructName string // 结构体
}
type funDef struct {
StructName string
TableName string
PreloadList []PreloadInfo
Em []EmInfo
PreloadList []PreloadInfo // 外键列表,(生成关联数据)
Em []EmInfo // index 列表
Primay []FList // primay unique
Index []FList // index
}
//

View File

@@ -33,7 +33,9 @@ func Generate(info DBInfo) (out []GenOutInfo) {
// ------end
// gen function
out = append(out, m.generateFunc()...)
if config.GetIsOutFunc() {
out = append(out, m.generateFunc()...)
}
// -------------- end
return
}
@@ -213,26 +215,32 @@ func (m *_Model) generateFunc() (genOut []GenOutInfo) {
TableName: tab.Name,
}
var primary, unique, uniqueIndex, index []FList
for _, el := range tab.Em {
if strings.EqualFold(el.Type, "gorm.Model") {
data.Em = append(data.Em, getGormModelElement()...)
pkg.AddImport(`"time"`)
buildFList(&primary, ColumusKeyPrimary, "", "int64", "id")
} else {
typeName := getTypeName(el.Type)
isMulti := true
for _, v1 := range el.Index {
switch v1.Key {
// case ColumusKeyDefault:
case ColumusKeyPrimary: // primary key.主键
isMulti = false
buildFList(&primary, ColumusKeyPrimary, "", typeName, el.Name)
case ColumusKeyUnique: // unique key.唯一索引
isMulti = false
//case ColumusKeyIndex: // index key.复合索引
buildFList(&unique, ColumusKeyUnique, "", typeName, el.Name)
case ColumusKeyIndex: // index key.复合索引
buildFList(&uniqueIndex, ColumusKeyIndex, v1.KeyName, typeName, el.Name)
case ColumusKeyUniqueIndex: // unique index key.唯一复合索引
isMulti = false
buildFList(&index, ColumusKeyUniqueIndex, v1.KeyName, typeName, el.Name)
}
}
typeName := getTypeName(el.Type)
data.Em = append(data.Em, EmInfo{
IsMulti: isMulti,
Notes: el.Notes,
@@ -263,10 +271,16 @@ func (m *_Model) generateFunc() (genOut []GenOutInfo) {
}
}
// ---------end--
}
tmpl, err := template.New("gen_logic").Funcs(template.FuncMap{"GenPreloadList": GenPreloadList}).Parse(genfunc.GetGenLogicTemp())
data.Primay = append(data.Primay, primary...)
data.Primay = append(data.Primay, unique...)
data.Primay = append(data.Primay, uniqueIndex...)
data.Index = append(data.Index, index...)
tmpl, err := template.New("gen_logic").
Funcs(template.FuncMap{"GenPreloadList": GenPreloadList, "GenFListIndex": GenFListIndex}).
Parse(genfunc.GetGenLogicTemp())
if err != nil {
panic(err)
}
@@ -282,19 +296,3 @@ func (m *_Model) generateFunc() (genOut []GenOutInfo) {
return
}
// GenPreloadList 生成list
func GenPreloadList(list []PreloadInfo, multi bool) string {
if len(list) > 0 {
tmpl, err := template.New("gen_preload").Parse(genfunc.GetGenPreloadTemp(multi))
if err != nil {
panic(err)
}
var buf bytes.Buffer
tmpl.Execute(&buf, list)
return buf.String()
}
return ""
}