加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
model_struct.go 2.45 KB
一键复制 编辑 原始数据 按行查看 历史
chad.wang 提交于 2024-03-22 16:32 . add new lib
// Copyright 2022 marcello<volibearw@gmail.com>. All rights reserved.
package main
import (
"fmt"
"strings"
)
// generateModelStructPart 生成struct部分
func generateModelStructPart(param *CLIParam, tableName string, columns []Columns) string {
var structStr string
if len(columns) == 0 {
// 没有字段的情况
structStr += "type " + toCamelString(tableName) + " struct{\n"
structStr += "}\n"
return structStr
}
structStr += "// " + columns[0].TableNameCame + " 表\n"
structStr += "type " + columns[0].TableNameCame + " struct{\n"
if param.ModelUseGorm && param.ModelIncludeGormModel {
structStr += " gorm.Model\n"
}
// 组装字段部分
var field string
for _, val := range columns {
if param.ModelUseGorm && param.ModelIncludeGormModel {
// 如果使用了 gorm.Model 就必须跳过这几个字段
if isGormDefaultModelField(val.ColumnName) {
continue
}
}
field += " " + val.ColumnNameCame + " " + val.ColumnGoDataType
if param.ModelUseGorm {
var columnAttr []string
// 列名
columnAttr = append(columnAttr, "column:"+val.ColumnName)
// 类型
columnAttr = append(columnAttr, val.ColumnType)
if val.IsNullable == "NO" {
columnAttr = append(columnAttr, "not null")
}
if val.Extra != MySQLExtraAutoIncrement {
// 自增列不太一样
if !val.Default.Valid {
// default is null
columnAttr = append(columnAttr, "default null")
} else {
// default is not null
columnAttr = append(columnAttr, fmt.Sprintf("default '%s'", val.Default.String))
}
}
if val.Extra == MySQLExtraAutoIncrement {
// 自增列表
// AUTO_INCREMENT
columnAttr = append(columnAttr, "autoIncrement")
}
if val.ColumnKey == MySQLColumnKeyPrimaryKey {
// primaryKey
columnAttr = append(columnAttr, "primaryKey")
}
if val.ColumnKey == MySQLColumnKeyUniqueKey {
// unique key
columnAttr = append(columnAttr, "unique")
}
if len(val.Comment) > 0 {
// 备注
columnAttr = append(columnAttr, fmt.Sprintf("comment:'%s'", val.Comment))
}
field += " `gorm:\"" + strings.Join(columnAttr, ";") + "\"`\n"
} else {
field += "\n"
}
}
structStr += field + "}\n\n"
// 生成实例化 New 部分
if param.ModelUseGorm {
structStr += "// TableName 设置表名\n"
structStr += "func (*" + columns[0].TableNameCame + ") TableName() string {\n"
structStr += " return \"" + tableName + "\"\n"
structStr += "}\n\n"
}
return structStr
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化