3 Star 4 Fork 0

workits / pkgs

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
codegen.go 5.69 KB
一键复制 编辑 原始数据 按行查看 历史
workits 提交于 2023-10-13 18:54 . 整合wk命令行工具
package toolx
import (
"fmt"
"strings"
"gitee.com/workits/pkgs/configx"
"gitee.com/workits/pkgs/dbx"
"gitee.com/workits/pkgs/utilx"
"github.com/fsgo/go_fmt/gofmtapi"
)
// GenCode 生成代码
func GenCode(projDir, moduleName, tableName string) {
genFiles := make([]string, 0)
// 错误处理
defer func() {
if err := recover(); err != nil {
for _, genFile := range genFiles {
_ = utilx.FsRemove(genFile, true)
}
if err == ErrExist {
panic(fmt.Sprintf("🔔已存在表%s生成的代码", tableName))
}
panic(err)
}
}()
// 判断模块是否存在
if !utilx.FsIsExist(projDir + PS + "internal" + PS + "app" + PS + moduleName) {
panic("🔔模块不存在, 请先创建模块")
}
// 读取配置文件
var wkcfg WkCfg
if _, err := configx.UnmarshalFiles(projDir+PS+".workits", &wkcfg); err != nil {
panic("🙅配置文件读取失败")
}
// 查询表信息
dbTool := NewDBTool(dbx.Config{
Alias: "default",
Dialect: wkcfg.DB.Dialect,
DSN: wkcfg.DB.DSN(),
})
tableInfo := dbTool.GetTableInfo(wkcfg.DB.Name, tableName)
// 构造模版数据
data := TypeConversion(true, tableInfo)
data.GoModule = wkcfg.GoModule
data.ProjModule = moduleName
data.ModName = UderscoreToUpperCamelCase(data.ProjModule)
// 生成文件并格式化
genFiles = append(genFiles, GenerateFile(projDir, "entity", data))
genFiles = append(genFiles, GenerateFile(projDir, "model", data))
genFiles = append(genFiles, GenerateFile(projDir, "handler", data))
genFiles = append(genFiles, GenerateFile(projDir, "router", data)) // TODO for http
}
// StructInfo 结构体信息
type StructInfo struct {
GoModule string
ProjModule string
ModName string
Name string
StructName string
TableName string
FileName string
PrimaryKeyColumn string
PrimaryKeyField string
PrimaryKeyType string
PrimaryKeyName string
Fields []StructField
HasTime bool
HasDecimal bool
Comment string
IsStandard bool
}
// StructField 结构体字段信息
type StructField struct {
FieldName string
ColumnName string
JsonName string
Type string
Required bool
Comment string
IsPrimaryKey bool
Default any
}
// TypeConversion 类型转换
func TypeConversion(isStandard bool, tb *TableInfo) StructInfo {
structInfo := StructInfo{
Name: UderscoreToLowerCamelCase(tb.Name),
StructName: UderscoreToUpperCamelCase(tb.Name),
TableName: tb.Name,
FileName: CamelCaseToUdnderscore(tb.Name),
Comment: tb.Comment,
IsStandard: isStandard,
}
var fields []StructField
for _, col := range tb.Fields {
field := StructField{
FieldName: UderscoreToUpperCamelCase(col.Field),
ColumnName: col.Field,
JsonName: UderscoreToLowerCamelCase(col.Field),
Comment: col.Comment,
}
// 是否必填项
if col.Null == "NO" {
field.Required = true
}
// 默认值
if isStandard {
if field.FieldName == "CreatedAt" || field.FieldName == "UpdatedAt" {
field.Default = "time.Now()"
}
} else {
if len(col.Default) > 0 {
switch col.Default {
case "CURRENT_TIMESTAMP":
field.Default = "time.Now()"
default:
field.Default = "\"" + col.Default + "\""
}
}
}
// 数据类型转换:db -> golang
typ := strings.ToUpper(col.Type)
switch typ {
case "DATETIME", "TIMESTAMP", "DATE", "TIME", "TIME WITH TIME ZONE", "TIMESTAMP WITH TIME ZONE", "TIMESTAMP WITH LOCAL TIME ZONE", "DATETIME WITH TIME ZONE":
field.Type = "time.Time"
if structInfo.IsStandard {
if field.FieldName != "CreatedAt" && field.FieldName != "UpdatedAt" && field.FieldName != "DeletedAt" {
structInfo.HasTime = true
}
} else {
structInfo.HasTime = true
}
case "INT", "INTEGER":
field.Type = "int"
case "BIGINT":
field.Type = "int64"
case "SMALLINT", "MEDIUMINT":
field.Type = "int32"
case "FLOAT":
field.Type = "float32"
case "DOUBLE", "REAL", "DOUBLE PRECISION":
field.Type = "float64"
case "DECIMAL", "NUMBER", "NUMERIC", "DEC":
field.Type = "decimal.Decimal"
structInfo.HasDecimal = true
case "TINYINT":
field.Type = "int8"
case "BIT", "BYTE":
field.Type = "byte"
case "BLOB":
field.Type = "[]byte"
default:
field.Type = "string"
}
// 主健
if col.Key == "PRI" {
structInfo.PrimaryKeyColumn = field.ColumnName
structInfo.PrimaryKeyField = field.FieldName
structInfo.PrimaryKeyName = field.JsonName
structInfo.PrimaryKeyType = field.Type
field.IsPrimaryKey = true
}
fields = append(fields, field)
}
structInfo.Fields = fields
return structInfo
}
// GenerateFile 生成文件
func GenerateFile(projDir, typ string, data StructInfo) string {
// 参数解析
var fPath, fName, tplDir, tplName string
fPath = projDir + PS + "internal" + PS + "app" + PS + data.ProjModule + PS
tplDir = projDir + PS + ".workits" + PS + "templates" + PS
switch typ {
case "entity":
fName = fPath + "entity" + PS + data.FileName + "_entity.go"
tplName = tplDir + "func.entity.go.tpl"
case "model":
fName = fPath + "model" + PS + data.FileName + "_model.go"
tplName = tplDir + "func.model.go.tpl"
case "handler":
fName = fPath + "handler" + PS + data.FileName + "_handler.go"
tplName = tplDir + "func.handler.go.tpl"
case "router":
fName = fPath + "component" + PS + "router" + PS + data.FileName + "_router.go"
tplName = tplDir + "router_handler.go.tpl"
}
if utilx.FsIsExist(fName) {
panic(ErrExist)
}
// 生成文件
ParseTemplate(tplName, fName, data)
// 格式化文件
opts := gofmtapi.NewOptions()
opts.Files = []string{fName}
if err := gofmtapi.NewFormatter().Execute(opts); err != nil {
panic(fmt.Sprintf("🙅文件%s格式化失败", fName))
}
return fName
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/workits/pkgs.git
git@gitee.com:workits/pkgs.git
workits
pkgs
pkgs
v0.0.3

搜索帮助

344bd9b3 5694891 D2dac590 5694891