goweb3系列解析16:makeGocode解析
MakeGoCodes是goweb3项目中的代码生成工具,可根据数据库表结构自动生成Go实体类、DAO等代码。核心功能包括:1)通过MetaFactory获取表元数据并缓存;2)支持MySQL/PostgreSQL多数据库;3)自动映射数据库类型到Go类型;4)生成带GORM标签的实体结构体和配套DAO;5)支持批量生成和驼峰命名转换。工具采用模块化设计,包含元数据查询、代码生成、文件写入等流程,输出路径为data/code/dbentity/目录下的.go和_dao.go文件。扩展功能包括Elasticsearch索引生成和注释同步。该工具适用于快速构建CRUD应用、同步表结构变更等场景。

makego.MakeGoCodes 代码生成工具解析
MakeGoCodes 是 goweb3 项目中的 代码生成工具,根据数据库表结构自动生成 Go 实体类、DAO 等代码文件。
一、函数定义与入口
go
func MakeGoCodes(tableName ...string) error {
for i := 0; i < len(tableName); i++ {
var err = MakeGoCode(tableName[i])
if err != nil {
return err
}
}
return nil
}
func MakeGoCode(tableName string) error {
var _, err = metapropfactroy.FindBeanMetaFactroy().MakeCode(
metaprop.FindBeanMetapropService(), tableName)
return err
}
调用链:
plainText
MakeGoCodes("po_apply")
↓
MakeGoCode("po_apply")
↓
MetaFactroy.MakeCode(IMetapropService, "po_apply")
↓
MetaTableCamel("po_apply", false, true)
↓
TableEntity.ToGocodeFile(false)
二、核心生成流程
1. 元数据获取
go
func (self *MetaFactroy) MakeCode(imeta metaiface.IMetapropService, table string) (string, error) {
self.imeta = imeta
var dto, err = self.MetaTableCamel(table, false, true)
if err != nil {
return "", err
}
return dto.ToGocodeFile(false)
}
func (self *MetaFactroy) MetaTableCamel(table string, trimPre bool, camelCase bool) (*tableentity.TableEntity, error) {
var meta = self.FindMetaprop2Db(table) // 从数据库读取元数据
self.imeta.SaveTableProp(meta) // 保存属性配置
if !meta.TableExist {
return nil, errors.New("MetaTableCamel table not found")
}
var dto = tableentity.NewTableEntity()
dto.EntityName = table
for _, column := range meta.Columns {
var field = dto.AppendField(column.ColumnName, column.DataType)
field.GormTag = column.ToGormTag(meta.PkInfo.PkName)
field.FieldDesc = column.ColumnComment
}
dto.CamelCase = camelCase
return dto, nil
}
2. 元数据查询(MySQL/PostgreSQL 适配)
go
func (this *MetaFactroy) FindMetadata(table string) *metadb.MetadataTable {
// 先查缓存
var c, found = metadb.InstMetadataCache.CacheGet(table)
if found {
return c
}
this.IniDb()
this.Table = table
var metadataTable = metadb.NewMetadataTable()
if this.IsMysql() {
// MySQL 查询
metadataTable.Columns = *this.mysql.FindColumns()
} else {
// PostgreSQL 查询
metadataTable.Columns = *this.postgres.FindColumns()
}
metadataTable.TableSchema = this.DbClientDto.Dbname
metadataTable.TableName = table
metadataTable.BuildGoFields() // 构建 Go 字段
// 缓存元数据
metadb.InstMetadataCache.CacheSet(table, meta)
return meta
}
3. 代码生成与文件写入
go
func (self *TableEntity) ToGocodeFile(trimPre bool) (string, error) {
// 生成实体代码
var code = self.ToGocode(trimPre)
err := self.Write2File(self.FullName(), code)
// 生成 DAO 代码
var codeDao = self.ToGocodeDao(trimPre)
err = self.Write2File(self.FullNameDao(), codeDao)
return code, err
}
func (self *TableEntity) FullName() string {
self.FileName = self.DataCode + "dbentity/" + self.EntityName + ".go"
return self.FileName
}
func (self *TableEntity) FullNameDao() string {
self.FileName = self.DataCode + "dbentity/" + self.EntityName + "_dao.go"
return self.FileName
}
三、生成的文件结构
| 文件类型 | 路径模式 | 说明 |
|---|---|---|
| 实体类 | {DataCode}dbentity/{tableName}.go |
数据库实体结构 |
| DAO类 | {DataCode}dbentity/{tableName}_dao.go |
数据访问对象 |
实体类模板结构
go
// po_apply.go
type PoApply struct {
Id int64 `gorm:"column:id;primaryKey"`
ApplyNo string `gorm:"column:apply_no"`
Status int `gorm:"column:status"`
CreatedAt time.Time `gorm:"column:created_at"`
// ... 其他字段
}
func (PoApply) TableName() string {
return "po_apply"
}
DAO类模板结构
go
// po_apply_dao.go
type PoApplyDao struct {
*basedao.BaseDao[int64, *PoApply]
}
func NewPoApplyDao() *PoApplyDao {
return &PoApplyDao{
BaseDao: basedao.NewBaseDao[int64, *PoApply](),
}
}
四、元数据类型映射
从数据库类型到 Go 类型的映射:
go
func (this *MetaFactroy) FindGoType(fieldType string) (goType string) {
goType = metacontext.FindBeanMetadataContext().FindGoType(fieldType)
return
}
典型映射:
| 数据库类型 | Go 类型 |
|---|---|
int, int64 |
int64 |
varchar, text |
string |
datetime, timestamp |
time.Time |
decimal, float |
float64 |
boolean |
bool |
五、使用示例
1. 基本用法
go
// 生成单个表的代码
makego.MakeGoCodes("po_apply")
// 生成多个表的代码
makego.MakeGoCodes("user", "order", "product")
2. 测试代码中的使用
go
func TestMakeGoCode(t *testing.T) {
// 生成 po_apply 表的代码
makego.MakeGoCodes("po_apply")
}
3. 命令行使用(通过 goweb3 CLI)
bash
# 生成指定表的代码
goweb3 code -t po_apply
# 生成多个表
goweb3 code -t user,order,product
六、扩展功能
1. Elasticsearch 索引代码生成
go
func MakeGoEsCode(esIndex string) error {
var err = metafacade.FindBeanMetaFacade().MetaEs(esIndex)
return err
}
func MakeGoEsCodes(esIndex ...string) error {
for i := 0; i < len(esIndex); i++ {
var err = MakeGoEsCode(esIndex[i])
if err != nil {
return err
}
}
return nil
}
2. 注释同步
go
func (this *MetaFactroy) AlterTableComment(table string, comment string) error {
var mt = metadb.NewMetadataTable()
mt.TableComment = comment
mt.TableName = table
if this.IsMysql() {
err := mt.AlterTableComment(this.funcGetDb())
return err
}
return errors.New("invalid dbtype")
}
七、生成流程图
plainText
┌─────────────────────────────────────────────────────────────────┐
│ MakeGoCodes 执行流程 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 1. MakeGoCodes("po_apply") │
│ ↓ │
│ 2. MakeGoCode("po_apply") │
│ ↓ │
│ 3. MetaFactroy.MakeCode(IMetapropService, "po_apply") │
│ ↓ │
│ 4. MetaTableCamel("po_apply", false, true) │
│ │ │
│ ├─→ FindMetaprop2Db("po_apply") ← 读取数据库元数据 │
│ ├─→ 遍历列信息,构建 TableEntity.Fields │
│ └─→ 设置 GormTag、FieldDesc │
│ ↓ │
│ 5. TableEntity.ToGocodeFile(false) │
│ │ │
│ ├─→ ToGocode() → 生成实体代码 → Write2File(xxx.go) │
│ └─→ ToGocodeDao() → 生成DAO代码 → Write2File(xxx_dao.go)│
│ ↓ │
│ 输出文件: │
│ - data/code/dbentity/po_apply.go │
│ - data/code/dbentity/po_apply_dao.go │
│ │
└─────────────────────────────────────────────────────────────────┘
八、设计特点
| 特点 | 说明 |
|---|---|
| 元数据缓存 | 避免重复查询数据库,提升性能 |
| 多数据库支持 | 支持 MySQL、PostgreSQL |
| 驼峰命名 | 支持下划线到驼峰的自动转换 |
| GORM标签 | 自动生成 gorm 结构体标签 |
| 注释保留 | 保留数据库字段注释作为代码注释 |
| 批量生成 | 支持同时生成多个表 |
| DAO自动生成 | 自动生成数据访问对象 |
九、配置与扩展
1. 数据代码路径配置
go
const meta_table_out = "/data/output/meta/dbdict/"
2. 生成策略
go
type TableEntity struct {
*metaentity.EntityDto
CamelCase bool // 是否使用驼峰命名
}
3. 扩展接口
go
type IMetapropService interface {
SaveTableProp(meta *metadb.MetadataTable)
// ... 其他方法
}
十、总结
makego.MakeGoCodes 是一个数据库表结构到 Go 代码的自动生成工具,核心能力包括:
- 元数据采集:从数据库读取表结构信息
- 类型映射:数据库类型 → Go 类型
- 代码模板:生成实体类和 DAO 类
- 文件输出:自动写入指定目录
典型应用场景:
- 快速构建 CRUD 应用
- 数据库表变更后的代码同步
- 脚手架工具集成
- 团队代码规范统一
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)