You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用goctl从数据源生成代码未获取到sql.NullString类型问题

问题:goctl从MySQL数据源生成模型时无法生成sql.NullString等可空类型,从DDL文件生成则正常

现象说明

使用GoZero的goctl工具时,通过数据源连接生成模型代码,无法生成sql.NullString、sql.NullInt64这类对应可空SQL字段的类型;但通过SQL DDL文件生成时,能正常生成符合预期的可空类型代码。

有效命令(从SQL文件生成)

goctl model mysql ddl --src schema/db.sql --dir ./internal/model --style go_zero 

无效命令(从数据源生成)

goctl model mysql datasource --url "root:@tcp(127.0.0.1:3306)/qrmenu" --dir ./internal/model --style go_zero --table "*" --cache=true 

期望生成的结构体示例

type GroupToppingOption struct {
        Id             string         `db:"id"`
        ShopId         sql.NullString `db:"shop_id"`
        GroupToppingId string         `db:"group_topping_id"`
        Name           sql.NullString `db:"name"`
        Price          sql.NullInt64  `db:"price"`
        CreateAt       time.Time      `db:"create_at"`
        UpdateAt       time.Time      `db:"update_at"`
        CreateBy       string         `db:"create_by"`
        UpdateBy       string         `db:"update_by"`
}

排查与解决方向

  • 检查字段约束:确认数据库中对应字段是否真的允许NULL,goctl从数据源生成时依赖读取INFORMATION_SCHEMA的约束信息,若字段被误设为NOT NULL则不会生成可空类型。
  • 升级goctl版本:旧版本的goctl在数据源字段解析逻辑上可能存在缺陷,执行以下命令升级到最新版:
    go install github.com/zeromicro/go-zero/tools/goctl@latest
    
  • 关闭缓存重试:无效命令中使用了--cache=true,缓存可能留存了旧的字段元数据,尝试去掉该参数后重新生成。
  • 检查数据库驱动:确保使用的MySQL驱动为最新版本,驱动返回的字段元数据格式可能影响goctl的类型判断。

内容的提问来源于stack exchange,提问作者Des Han

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 04:17:43