kra/docs/autocode.md

53 KiB
Raw Permalink Blame History

KRA AutoCode 自动代码生成工具

KRA AutoCode 是一个强大的代码生成工具,支持生成符合 Kratos DDD 架构的后端代码和 React TypeScript 前端代码。

目录

功能特性

  • Kratos DDD 架构: 生成符合 Kratos 分层架构的代码biz/data/service/server
  • GORM Gen 集成: 使用 GORM Gen 生成类型安全的数据库操作代码
  • React TypeScript: 生成现代化的 React 前端代码,使用 Ant Design Pro 组件
  • 双入口支持: 同时支持 CLI 命令行和 Web 界面两种生成方式
  • 多数据库支持: 支持 MySQL、PostgreSQL、SQLite 数据库
  • 代码注入: 自动注入 Wire Provider、路由注册等代码
  • 历史记录: 支持生成历史记录和代码回滚

快速开始

方式一:使用 CLI 工具

# 从配置文件生成代码
kra-gen generate -c autocode.yaml

# 交互模式(推荐新手使用)
kra-gen generate -i

# 预览模式(不写入文件)
kra-gen generate -c autocode.yaml -p

方式二:使用 Web 界面

  1. 启动 KRA 服务
  2. 访问 系统工具 > 代码生成器
  3. 选择数据库和表
  4. 配置字段选项
  5. 预览并生成代码

CLI 命令说明

KRA 代码生成工具提供了完整的命令行接口,支持配置文件、命令行参数和交互模式三种方式进行代码生成。

安装

# 从源码编译
go build -o kra-gen ./cmd/kra-gen

# 或者使用 go install
go install ./cmd/kra-gen

基础命令

kra-gen [command] [flags]

全局参数

以下参数可用于所有子命令:

参数 简写 说明 默认值
--config -c 配置文件路径 (YAML/JSON) -
--output -o 输出目录 当前项目目录
--template -t 模板目录 resource/package
--verbose -v 显示详细输出 false
--help -h 显示帮助信息 -

可用命令

命令 说明
generate 生成代码(核心命令)
preview 预览生成的代码(不写入文件)
list 列出可用资源(模板、包、数据库)
version 显示版本信息
help 显示帮助信息

generate 命令

生成 Kratos DDD 架构的后端代码和 React 前端代码。这是 CLI 工具的核心命令。

kra-gen generate [flags]

参数说明

参数 简写 说明 默认值
--config -c 配置文件路径 (YAML/JSON) -
--interactive -i 交互模式(推荐新手使用) false
--preview -p 预览模式(不写入文件) false
--output -o 输出目录 当前目录
--template -t 模板目录 resource/package
--db - 数据库连接名 -
--table - 表名 -
--package - 包名 -
--struct - 结构体名 -
--desc - 描述 -
--no-web - 不生成前端代码 false
--no-server - 不生成后端代码 false
--only-template - 仅生成模板(不注入代码) false
--add - 追加模式(不覆盖已有文件) false
--tree - 树形结构数据 false
--tree-json - 树形结构展示字段 -
--verbose -v 显示详细输出 false

三种使用方式

方式一:配置文件方式(推荐用于复杂配置)

# 使用 YAML 配置文件
kra-gen generate -c autocode.yaml

# 使用 JSON 配置文件
kra-gen generate -c autocode.json

方式二:命令行参数方式(适合简单场景)

# 基本用法
kra-gen generate --table users --package example --struct User

# 完整参数
kra-gen generate \
  --db mysql \
  --table users \
  --package example \
  --struct User \
  --desc "用户管理"

方式三:交互模式(推荐新手使用)

kra-gen generate -i

交互模式会引导你完成以下步骤:

  1. 配置数据库连接(支持从 configs/config.yaml 自动读取)
  2. 选择数据库
  3. 选择数据表
  4. 配置基本信息(结构体名、包名、描述等)
  5. 配置字段(显示、验证、搜索、关联等)
  6. 配置生成选项

使用示例

# 从配置文件生成
kra-gen generate -c autocode.yaml

# 使用命令行参数
kra-gen generate --db mysql --table users --package example --struct User --desc "用户管理"

# 交互模式
kra-gen generate -i

# 预览模式(不写入文件)
kra-gen generate -c autocode.yaml -p

# 仅生成后端代码
kra-gen generate -c autocode.yaml --no-web

# 仅生成前端代码
kra-gen generate -c autocode.yaml --no-server

# 仅生成模板(不注入代码到现有文件)
kra-gen generate -c autocode.yaml --only-template

# 追加模式(不覆盖已有文件)
kra-gen generate -c autocode.yaml --add

# 树形结构数据
kra-gen generate -c autocode.yaml --tree --tree-json name

# 详细输出模式
kra-gen generate -c autocode.yaml -v

# 指定输出目录
kra-gen generate -c autocode.yaml -o /path/to/project

# 使用自定义模板
kra-gen generate -c autocode.yaml -t /path/to/custom/templates

交互模式详细流程

交互模式提供了完整的引导式配置体验:

========================================
KRA 代码生成 - 交互模式
========================================

步骤 1/6: 配置数据库连接
----------------------------------------
检测到配置文件: configs/config.yaml
是否使用配置文件中的数据库连接? (y/n): y
使用 MySQL 数据库: root@127.0.0.1:3306/kra
正在连接数据库... 成功!

步骤 2/6: 选择数据库
----------------------------------------
可用数据库:
  1. information_schema
  2. kra (当前)
  3. mysql
请选择数据库 [2]: 2
已选择数据库: kra

步骤 3/6: 选择数据表
----------------------------------------
数据库 kra 中的表:
  1. sys_users
  2. sys_apis
  3. articles
请选择表 (输入序号): 3
已选择表: articles

步骤 4/6: 配置基本信息
----------------------------------------
结构体名称 [Articles]: Article
包名 [articles]: example
缩写 [article]: article
功能描述 [Article管理]: 文章管理

步骤 5/6: 配置字段
----------------------------------------
表 articles 的字段:
----------------------------------------
  [跳过] id (系统字段)
  [跳过] created_at (系统字段)
  [跳过] updated_at (系统字段)
  [跳过] deleted_at (系统字段)
  Title (string) - 标题
  Content (string) - 内容
  Status (int) - 状态
----------------------------------------
共 3 个字段
是否需要详细配置每个字段? (y/n): y

步骤 6/6: 配置生成选项
----------------------------------------
【基础配置】
使用 KRA_MODEL (包含 ID, CreatedAt, UpdatedAt, DeletedAt)? (y/n) [y]: y
自动迁移数据库表结构? (y/n) [y]: y

【生成范围】
生成后端代码? (y/n) [y]: y
生成前端代码? (y/n) [y]: y

【高级选项】
仅生成模板 (不注入代码到现有文件)? (y/n) [n]: n
追加模式 (不覆盖已有文件)? (y/n) [n]: n

【自动注册配置】
自动创建 API 记录? (y/n) [y]: y
自动创建菜单记录? (y/n) [y]: y
自动创建按钮权限? (y/n) [y]: y
自动创建资源标识? (y/n) [n]: n

【树形结构配置】
是否为树形结构数据? (y/n): n

========================================
配置完成!
========================================

preview 命令

预览将要生成的代码,不写入任何文件。这是 generate -p 的快捷方式,但提供了更多预览选项。

kra-gen preview [flags]

参数说明

参数 简写 说明 默认值
--config -c 配置文件路径 -
--db - 数据库连接名 -
--table - 表名 -
--package - 包名 -
--struct - 结构体名 -
--desc - 描述 -
--no-web - 不生成前端代码 false
--no-server - 不生成后端代码 false
--full - 显示完整代码内容(带语法高亮) false
--no-color - 不使用语法高亮 false

使用示例

# 简单预览(显示文件列表和配置摘要)
kra-gen preview -c autocode.yaml

# 完整预览(显示所有生成的代码内容)
kra-gen preview -c autocode.yaml --full

# 完整预览,不使用语法高亮(适合重定向到文件)
kra-gen preview -c autocode.yaml --full --no-color

# 仅预览后端代码
kra-gen preview -c autocode.yaml --full --no-web

# 仅预览前端代码
kra-gen preview -c autocode.yaml --full --no-server

# 使用命令行参数预览
kra-gen preview --table users --package example --struct User

预览输出示例

简单预览模式:

========================================
代码预览模式
========================================
包名: example
结构体: Article
表名: articles
描述: 文章管理
数据库: kra
----------------------------------------
生成选项:
  使用 KRA_MODEL: 是
  自动迁移: 是
  生成后端: 是
  生成前端: 是
  仅生成模板: 否
  追加模式: 否
  创建 API 记录: 是
  创建菜单记录: 是
  创建按钮权限: 是
  创建资源标识: 否
----------------------------------------
将生成以下文件:

后端文件:
  - ./internal/biz/example/article.go
  - ./internal/data/example/article.go
  - ./internal/data/model/example/article.go
  - ./internal/service/example/article.go
  - ./internal/service/types/example/request/article.go
  - ./internal/server/handler/example/article.go
  - ./internal/server/router/example/article.go

前端文件:
  - ./web/src/pages/example/article/index.tsx
  - ./web/src/pages/example/article/form.tsx
  - ./web/src/pages/example/article/detail.tsx
  - ./web/src/services/kratos/example.ts
  - ./web/src/types/example/article.d.ts

字段配置:
  - Title (string): 标题 [搜索:LIKE]
  - Content (string): 内容
  - Status (int): 状态 [搜索:EQ] [字典:article_status]

========================================
预览完成,未写入任何文件
========================================

完整预览模式(--full

╔════════════════════════════════════════════════════════════════╗
║                    KRA 代码预览 (完整模式)                      ║
╚════════════════════════════════════════════════════════════════╝

包名: example
结构体: Article
表名: articles
描述: 文章管理

────────────────────────────────────────────────────────────────
📄 Biz Layer
   输出路径: ./internal/biz/example/article.go

   1 │ package example
   2 │ 
   3 │ import (
   4 │     "context"
   5 │     "github.com/go-kratos/kratos/v2/log"
   6 │ )
   7 │ 
   8 │ // ArticleRepo 仓储接口
   9 │ type ArticleRepo interface {
  10 │     Create(ctx context.Context, article *Article) error
  ...

════════════════════════════════════════════════════════════════
预览统计
  成功: 12 个文件

⚠️  预览模式 - 未写入任何文件

list 命令

列出可用的模板、包或数据库连接。

kra-gen list [templates|packages|databases]

子命令说明

子命令 说明
templates 列出可用的代码生成模板
packages 列出已创建的业务包
databases 列出配置的数据库连接

使用示例

# 列出可用模板
kra-gen list templates

# 输出:
# 可用模板:
#   package  - 标准包模板 (Kratos DDD 架构)
#   plugin   - 插件模板 (独立功能模块)

# 列出已创建的包
kra-gen list packages

# 输出:
# 已创建的包:
#   (需要连接数据库获取)

# 列出数据库连接
kra-gen list databases

# 输出:
# 数据库连接:
#   MySQL: root@127.0.0.1:3306/kra

version 命令

显示 KRA 代码生成工具的版本信息。

kra-gen version

输出示例

kra-gen v1.0.0
KRA 自动代码生成工具
支持 Kratos DDD 架构 + GORM Gen + React TypeScript

退出码

退出码 说明
0 成功
1 一般错误(配置错误、验证失败等)

环境变量

变量名 说明 默认值
KRA_CONFIG 默认配置文件路径 -
KRA_TEMPLATE_DIR 默认模板目录 resource/package
KRA_OUTPUT_DIR 默认输出目录 当前目录

常用命令组合

# 快速生成(使用配置文件)
kra-gen generate -c autocode.yaml

# 新手入门(交互模式)
kra-gen generate -i

# 预览后生成
kra-gen preview -c autocode.yaml --full && kra-gen generate -c autocode.yaml

# 仅生成后端代码
kra-gen generate -c autocode.yaml --no-web

# 仅生成前端代码
kra-gen generate -c autocode.yaml --no-server

# 安全生成(追加模式,不覆盖已有文件)
kra-gen generate -c autocode.yaml --add

# 模板开发(仅生成模板,不注入代码)
kra-gen generate -c autocode.yaml --only-template

# 树形结构数据
kra-gen generate -c autocode.yaml --tree --tree-json name

# 使用自定义模板
kra-gen generate -c autocode.yaml -t /path/to/custom/templates

# 详细输出(调试用)
kra-gen generate -c autocode.yaml -v

配置文件格式

配置文件支持 YAML 和 JSON 两种格式,推荐使用 YAML 格式(更易读)。

配置文件结构概览

配置文件
├── 基础信息          # package, structName, tableName 等
├── 生成选项 (options) # gvaModel, autoMigrate, generateWeb 等
├── 字段配置 (fields)  # 字段列表,每个字段包含类型、显示、搜索等配置
└── 自定义方法 (customMethods) # 可选,用于生成自定义查询方法

YAML 格式完整示例

# autocode.yaml

# ==================== 基础信息 ====================
package: example           # 包名(小写,用于目录和包名)
structName: Article        # 结构体名称(大驼峰,用于 Go 结构体)
tableName: articles        # 数据库表名(下划线命名)
description: 文章管理       # 功能描述(用于注释和文档)
businessDB: ""             # 业务数据库(空表示默认数据库)
abbreviation: article      # 缩写(用于路由前缀和变量名)

# ==================== 生成选项 ====================
options:
  # --- 基础配置 ---
  gvaModel: true              # 使用 KRA_MODEL包含 ID, CreatedAt, UpdatedAt, DeletedAt
  autoMigrate: true           # 自动迁移数据库表结构
  
  # --- 生成范围 ---
  generateWeb: true           # 生成前端代码
  generateServer: true        # 生成后端代码
  
  # --- 高级选项 ---
  onlyTemplate: false         # 仅生成模板(不注入代码到现有文件)
  isAdd: false                # 追加模式(不覆盖已有文件)
  
  # --- 自动注册配置(仅在 onlyTemplate=false 时生效)---
  autoCreateApiToSql: true    # 自动创建 API 记录到 sys_apis 表
  autoCreateMenuToSql: true   # 自动创建菜单记录到 sys_base_menus 表
  autoCreateBtnAuth: true     # 自动创建按钮权限
  autoCreateResource: false   # 自动创建资源标识
  
  # --- 树形结构配置 ---
  isTree: false               # 是否为树形结构数据
  treeJson: ""                # 树形结构展示字段(如: name, title

# ==================== 字段配置 ====================
fields:
  # --- 字符串字段示例 ---
  - fieldName: Title          # Go 字段名(大驼峰)
    fieldDesc: 标题            # 字段描述/注释
    fieldType: string         # Go 类型
    fieldJson: title          # JSON 字段名(小驼峰)
    columnName: title         # 数据库列名(下划线)
    dataTypeLong: varchar(255) # 数据库类型
    form: true                # 显示在表单中
    table: true               # 显示在表格中
    desc: true                # 显示在详情页
    excel: true               # 支持导入/导出
    require: true             # 是否必填
    errorText: 请输入标题      # 校验失败提示
    clearable: true           # 是否可清空
    sort: false               # 是否支持排序
    fieldSearchType: LIKE     # 搜索类型
    fieldSearchHide: false    # 是否隐藏搜索条件
    fieldIndexType: ""        # 索引类型

  # --- 文本字段示例 ---
  - fieldName: Content
    fieldDesc: 内容
    fieldType: string
    fieldJson: content
    columnName: content
    dataTypeLong: text
    form: true
    table: false              # 长文本不在表格中显示
    desc: true
    excel: false
    require: false
    clearable: true

  # --- 带字典的字段示例 ---
  - fieldName: Status
    fieldDesc: 状态
    fieldType: int
    fieldJson: status
    columnName: status
    dataTypeLong: tinyint(1)
    form: true
    table: true
    desc: true
    require: false
    defaultValue: "1"         # 默认值
    fieldSearchType: EQ       # 精确匹配
    dictType: article_status  # 字典类型(用于下拉选择)

  # --- 带数据源的字段示例 ---
  - fieldName: AuthorID
    fieldDesc: 作者ID
    fieldType: uint
    fieldJson: authorId
    columnName: author_id
    dataTypeLong: bigint(20)
    form: true
    table: true
    require: true
    fieldSearchType: EQ
    fieldIndexType: index     # 普通索引
    dataSource:               # 数据源配置
      dbName: ""              # 数据库名(空表示当前数据库)
      table: sys_users        # 关联表名
      label: nick_name        # 显示字段
      value: id               # 值字段
      association: 1          # 关联关系: 1=一对一, 2=一对多
      hasDeletedAt: true      # 关联表是否有软删除

  # --- 时间字段示例 ---
  - fieldName: PublishTime
    fieldDesc: 发布时间
    fieldType: time.Time
    fieldJson: publishTime
    columnName: publish_time
    dataTypeLong: datetime
    form: true
    table: true
    desc: true
    require: false
    clearable: true
    sort: true
    fieldSearchType: BETWEEN  # 时间范围搜索

# ==================== 自定义查询方法(可选)====================
customMethods:
  # --- 单条查询示例 ---
  - name: FindByTitle         # 方法名称
    description: 根据标题查询  # 方法描述
    returnType: single        # 返回类型: single(单个), list(列表), count(计数), exists(存在检查)
    params:                   # 方法参数
      - name: title           # 参数名
        type: string          # 参数类型
        fieldName: Title      # 对应字段名
    conditions:               # 查询条件
      - fieldName: Title      # 字段名
        operator: eq          # 操作符
        paramName: title      # 参数名

  # --- 列表查询示例 ---
  - name: GetPublishedArticles
    description: 获取已发布的文章列表
    returnType: list
    params:
      - name: status
        type: int
        fieldName: Status
    conditions:
      - fieldName: Status
        operator: eq
        paramName: status
    orderBy: created_at DESC  # 排序
    limit: 100                # 限制数量

JSON 格式完整示例

{
  "package": "example",
  "structName": "Article",
  "tableName": "articles",
  "description": "文章管理",
  "businessDB": "",
  "abbreviation": "article",
  "options": {
    "gvaModel": true,
    "autoMigrate": true,
    "generateWeb": true,
    "generateServer": true,
    "onlyTemplate": false,
    "isAdd": false,
    "autoCreateApiToSql": true,
    "autoCreateMenuToSql": true,
    "autoCreateBtnAuth": true,
    "autoCreateResource": false,
    "isTree": false,
    "treeJson": ""
  },
  "fields": [
    {
      "fieldName": "Title",
      "fieldDesc": "标题",
      "fieldType": "string",
      "fieldJson": "title",
      "columnName": "title",
      "dataTypeLong": "varchar(255)",
      "form": true,
      "table": true,
      "desc": true,
      "excel": true,
      "require": true,
      "errorText": "请输入标题",
      "clearable": true,
      "sort": false,
      "fieldSearchType": "LIKE",
      "fieldSearchHide": false,
      "fieldIndexType": ""
    },
    {
      "fieldName": "Status",
      "fieldDesc": "状态",
      "fieldType": "int",
      "fieldJson": "status",
      "columnName": "status",
      "dataTypeLong": "tinyint(1)",
      "form": true,
      "table": true,
      "desc": true,
      "require": false,
      "defaultValue": "1",
      "fieldSearchType": "EQ",
      "dictType": "article_status"
    },
    {
      "fieldName": "AuthorID",
      "fieldDesc": "作者ID",
      "fieldType": "uint",
      "fieldJson": "authorId",
      "columnName": "author_id",
      "dataTypeLong": "bigint(20)",
      "form": true,
      "table": true,
      "require": true,
      "fieldSearchType": "EQ",
      "fieldIndexType": "index",
      "dataSource": {
        "dbName": "",
        "table": "sys_users",
        "label": "nick_name",
        "value": "id",
        "association": 1,
        "hasDeletedAt": true
      }
    }
  ],
  "customMethods": [
    {
      "name": "FindByTitle",
      "description": "根据标题查询",
      "returnType": "single",
      "params": [
        {
          "name": "title",
          "type": "string",
          "fieldName": "Title"
        }
      ],
      "conditions": [
        {
          "fieldName": "Title",
          "operator": "eq",
          "paramName": "title"
        }
      ]
    }
  ]
}

配置项详细说明

基础信息

属性 类型 必填 说明 示例
package string 包名(小写) example
structName string 结构体名称(大驼峰) Article
tableName string 数据库表名 articles
description string 功能描述 文章管理
businessDB string 业务数据库名(空=默认) ""
abbreviation string 缩写(用于路由) article

生成选项 (options)

属性 类型 默认值 说明
gvaModel bool true 使用 KRA_MODEL包含 ID, CreatedAt, UpdatedAt, DeletedAt
autoMigrate bool true 自动迁移数据库表结构
generateWeb bool true 生成前端代码
generateServer bool true 生成后端代码
onlyTemplate bool false 仅生成模板(不注入代码到现有文件)
isAdd bool false 追加模式(不覆盖已有文件)
autoCreateApiToSql bool true 自动创建 API 记录到 sys_apis 表
autoCreateMenuToSql bool true 自动创建菜单记录到 sys_base_menus 表
autoCreateBtnAuth bool true 自动创建按钮权限
autoCreateResource bool false 自动创建资源标识
isTree bool false 是否为树形结构数据
treeJson string "" 树形结构展示字段(如: name, title

字段配置说明

基础属性

属性 类型 必填 说明
fieldName string Go 结构体字段名(大驼峰)
fieldDesc string 字段描述/注释
fieldType string Go 类型string, int, uint, float64, bool, time.Time 等)
fieldJson string JSON 序列化字段名(小驼峰)
columnName string 数据库列名(下划线)
dataTypeLong string 数据库类型(如 varchar(255), bigint(20)

显示属性

属性 类型 默认值 说明
form bool false 是否显示在表单中
table bool false 是否显示在表格中
desc bool false 是否显示在详情页
excel bool false 是否支持导入/导出

验证属性

属性 类型 默认值 说明
require bool false 是否必填
defaultValue string "" 默认值
errorText string "" 校验失败提示文字
clearable bool true 是否可清空

搜索属性

属性 类型 默认值 说明
fieldSearchType string "" 搜索类型(见下表)
fieldSearchHide bool false 是否隐藏搜索条件(高级搜索)
sort bool false 是否支持排序

搜索类型说明:

类型 说明 生成的 SQL 条件
LIKE 模糊匹配 WHERE title LIKE '%keyword%'
EQ 精确匹配 WHERE status = 1
BETWEEN 范围查询 WHERE created_at BETWEEN ? AND ?
GT 大于 WHERE price > 100
GTE 大于等于 WHERE price >= 100
LT 小于 WHERE price < 100
LTE 小于等于 WHERE price <= 100
NEQ 不等于 WHERE status != 0

关联属性

属性 类型 默认值 说明
dictType string "" 字典类型(用于下拉选择)
dataSource object null 数据源配置(关联其他表)
fieldIndexType string "" 索引类型(index, unique
primaryKey bool false 是否为主键

数据源配置 (dataSource)

用于配置字段与其他表的关联关系,生成下拉选择组件。

属性 类型 必填 说明
dbName string 数据库名(空表示当前数据库)
table string 关联表名
label string 显示字段(用于下拉选项文本)
value string 值字段(用于下拉选项值)
association int 关联关系:1=一对一, 2=一对多
hasDeletedAt bool 关联表是否有软删除字段

示例:

dataSource:
  dbName: ""              # 当前数据库
  table: sys_users        # 关联 sys_users 表
  label: nick_name        # 显示用户昵称
  value: id               # 值为用户 ID
  association: 1          # 一对一关系
  hasDeletedAt: true      # sys_users 表有软删除

自定义查询方法 (customMethods)

用于生成 GORM Gen 自定义查询方法,适用于复杂查询场景。

方法配置

属性 类型 必填 说明
name string 方法名称(如: FindByTitle, GetActiveUsers
description string 方法描述
returnType string 返回类型(见下表)
params array 方法参数列表
conditions array 查询条件列表
orderBy string 排序字段(如: created_at DESC
limit int 限制数量0 表示不限制)

返回类型说明:

类型 说明 生成的方法签名
single 返回单条记录 func (r *repo) FindByTitle(ctx, title) (*Entity, error)
list 返回记录列表 func (r *repo) GetActiveUsers(ctx, status) ([]*Entity, error)
count 返回记录数量 func (r *repo) CountByStatus(ctx, status) (int64, error)
exists 返回是否存在 func (r *repo) ExistsByTitle(ctx, title) (bool, error)

参数配置 (params)

属性 类型 必填 说明
name string 参数名称
type string 参数类型string, int, uint, bool, time.Time 等)
fieldName string 对应的字段名(用于生成查询条件)

条件配置 (conditions)

属性 类型 必填 说明
fieldName string 字段名
operator string 操作符(见下表)
paramName string 参数名(对应 params 中的 name

操作符说明:

操作符 说明 生成的条件
eq 等于 field.Eq(param)
neq 不等于 field.Neq(param)
gt 大于 field.Gt(param)
gte 大于等于 field.Gte(param)
lt 小于 field.Lt(param)
lte 小于等于 field.Lte(param)
like 模糊匹配 field.Like("%" + param + "%")
in 包含 field.In(params...)
between 范围 field.Between(start, end)
isNull 为空 field.IsNull()
isNotNull 不为空 field.IsNotNull()

自定义方法示例

customMethods:
  # 根据标题精确查询单条记录
  - name: FindByTitle
    description: 根据标题查询文章
    returnType: single
    params:
      - name: title
        type: string
        fieldName: Title
    conditions:
      - fieldName: Title
        operator: eq
        paramName: title

  # 根据状态查询列表,带排序和限制
  - name: GetPublishedArticles
    description: 获取已发布的文章列表
    returnType: list
    params:
      - name: status
        type: int
        fieldName: Status
    conditions:
      - fieldName: Status
        operator: eq
        paramName: status
    orderBy: created_at DESC
    limit: 100

  # 统计指定作者的文章数量
  - name: CountByAuthor
    description: 统计作者的文章数量
    returnType: count
    params:
      - name: authorId
        type: uint
        fieldName: AuthorID
    conditions:
      - fieldName: AuthorID
        operator: eq
        paramName: authorId

  # 检查标题是否已存在
  - name: ExistsByTitle
    description: 检查标题是否已存在
    returnType: exists
    params:
      - name: title
        type: string
        fieldName: Title
    conditions:
      - fieldName: Title
        operator: eq
        paramName: title

  # 模糊搜索文章
  - name: SearchByKeyword
    description: 根据关键词搜索文章
    returnType: list
    params:
      - name: keyword
        type: string
        fieldName: Title
    conditions:
      - fieldName: Title
        operator: like
        paramName: keyword
    orderBy: created_at DESC

  # 多条件查询
  - name: FindByStatusAndAuthor
    description: 根据状态和作者查询
    returnType: list
    params:
      - name: status
        type: int
        fieldName: Status
      - name: authorId
        type: uint
        fieldName: AuthorID
    conditions:
      - fieldName: Status
        operator: eq
        paramName: status
      - fieldName: AuthorID
        operator: eq
        paramName: authorId

Go 类型与数据库类型映射

Go 类型 数据库类型 TypeScript 类型 说明
string varchar(n), text, longtext string 字符串
int int, tinyint, smallint number 整数
int64 bigint number 长整数
uint int unsigned, bigint unsigned number 无符号整数
float64 float, double, decimal number 浮点数
bool tinyint(1), boolean boolean 布尔值
time.Time datetime, timestamp, date string 时间
datatypes.JSON json, jsonb object JSON 对象
[]byte blob, binary string 二进制数据

Web 界面使用

访问代码生成器

  1. 登录 KRA 管理后台
  2. 导航到 系统工具 > 代码生成器

使用步骤

1. 选择数据库和表

  • 在左侧选择数据库连接
  • 选择要生成代码的数据表
  • 系统会自动读取表结构信息

2. 配置基本信息

  • 结构体名称: Go 结构体名(大驼峰命名)
  • 包名: 代码包名(小写)
  • 表名: 数据库表名
  • 描述: 功能描述
  • 缩写: 用于路由和变量名

3. 配置字段

对每个字段进行配置:

  • 显示配置: 表单、表格、详情页、导出
  • 验证配置: 必填、默认值、校验提示
  • 搜索配置: 搜索类型、是否隐藏
  • 关联配置: 字典类型、数据源

4. 配置生成选项

  • 基础配置: KRA_MODEL、自动迁移
  • 生成范围: 后端代码、前端代码
  • 自动注册: API 记录、菜单记录、按钮权限

5. 预览和生成

  • 点击「预览」查看将要生成的代码
  • 确认无误后点击「生成」
  • 生成完成后可在历史记录中查看

历史记录管理

  • 查看所有代码生成历史
  • 支持代码回滚(删除生成的文件,移除注入的代码)
  • 支持重新生成

模板自定义

KRA AutoCode 提供了灵活的模板自定义能力,允许开发者根据项目需求定制代码生成风格。本节详细介绍如何创建和使用自定义模板。

模板目录结构

默认模板位于 resource/package/ 目录下:

resource/package/
├── server/                    # 后端模板
│   ├── biz/                   # Biz 层模板
│   │   ├── biz.go.tpl         # Usecase + Repository 接口
│   │   └── enter.go.tpl       # 包入口
│   ├── data/                  # Data 层模板
│   │   ├── data.go.tpl        # Repository 实现
│   │   ├── enter.go.tpl       # 包入口
│   │   └── model.go.tpl       # GORM Gen 模型
│   ├── handler/               # Handler 层模板
│   │   ├── handler.go.tpl     # HTTP Handler
│   │   └── enter.go.tpl       # 包入口
│   ├── service/               # Service 层模板
│   │   ├── service.go.tpl     # Service 实现
│   │   └── enter.go.tpl       # 包入口
│   ├── router/                # Router 层模板
│   │   ├── router.go.tpl      # 路由配置
│   │   └── enter.go.tpl       # 包入口
│   └── types/                 # 类型定义模板
│       └── request.go.tpl     # 请求/响应类型
├── web/                       # 前端模板
│   ├── pages/                 # React 页面模板
│   │   ├── index.tsx.tpl      # 列表页面
│   │   ├── form.tsx.tpl       # 表单组件
│   │   └── detail.tsx.tpl     # 详情组件
│   ├── services/              # API 服务模板
│   │   └── api.ts.tpl         # TypeScript API
│   └── types/                 # 类型定义模板
│       └── types.d.ts.tpl     # TypeScript 类型
└── readme.txt.tpl             # 说明文件

模板语法基础

模板使用 Go 的 text/template 语法。以下是常用语法:

变量输出

// 输出变量
{{.StructName}}

// 输出嵌套变量
{{.PrimaryField.FieldName}}

条件判断

{{- if .GvaModel }}
// 使用 KRA_MODEL 时的代码
{{- else }}
// 不使用 KRA_MODEL 时的代码
{{- end }}

// 多条件判断
{{- if and .HasDataSource .Form }}
// 同时满足两个条件
{{- end }}

{{- if or .IsTree .HasDataSource }}
// 满足任一条件
{{- end }}

// 非判断
{{- if not .OnlyTemplate }}
// 不是仅模板模式
{{- end }}

循环遍历

// 遍历字段列表
{{- range .Fields }}
{{.FieldName}}: {{.FieldType}}
{{- end }}

// 带索引的遍历
{{- range $index, $field := .Fields }}
// $index 是索引,$field 是字段
{{- end }}

// 遍历 Map
{{- range $key, $value := .DataSourceMap }}
{{$key}}: {{$value.Table}}
{{- end }}

空白控制

// {{- 去除左侧空白
// -}} 去除右侧空白
{{- if .Condition -}}
内容
{{- end -}}

模板变量详解

基础信息变量

变量 类型 说明 示例值
{{.Package}} string 包名(小写) example
{{.PackageName}} string 包名(小写) example
{{.PackageT}} string 包名(首字母大写) Example
{{.StructName}} string 结构体名(大驼峰) Article
{{.TableName}} string 数据库表名 articles
{{.Description}} string 功能描述 文章管理
{{.Abbreviation}} string 缩写(用于路由) article
{{.Module}} string Go 模块名 github.com/xxx/kra
{{.HumpPackageName}} string 驼峰包名 example
{{.BusinessDB}} string 业务数据库名 ""

字段相关变量

变量 类型 说明
{{.Fields}} []*AutoCodeField 字段列表
{{.PrimaryField}} *AutoCodeField 主键字段
{{.DictTypes}} []string 字典类型列表
{{.DataSourceMap}} map[string]*DataSource 数据源映射

选项变量

变量 类型 说明
{{.GvaModel}} bool 是否使用 KRA_MODEL
{{.AutoMigrate}} bool 是否自动迁移
{{.AutoCreateResource}} bool 是否创建资源标识
{{.AutoCreateApiToSql}} bool 是否自动创建 API 记录
{{.AutoCreateMenuToSql}} bool 是否自动创建菜单
{{.AutoCreateBtnAuth}} bool 是否自动创建按钮权限
{{.OnlyTemplate}} bool 是否仅生成模板
{{.IsAdd}} bool 是否追加模式
{{.IsTree}} bool 是否树形结构
{{.TreeJson}} string 树形展示字段
{{.GenerateWeb}} bool 是否生成前端
{{.GenerateServer}} bool 是否生成后端

特性标记变量

变量 类型 说明
{{.HasPic}} bool 是否有图片字段
{{.HasFile}} bool 是否有文件字段
{{.HasTimer}} bool 是否有时间字段
{{.HasRichText}} bool 是否有富文本字段
{{.HasDataSource}} bool 是否有数据源字段
{{.HasSearchTimer}} bool 是否有时间搜索字段
{{.HasArray}} bool 是否有数组字段
{{.HasExcel}} bool 是否有导出字段
{{.NeedSort}} bool 是否需要排序
{{.NeedJSON}} bool 是否需要 JSON 类型
{{.HasCustomMethods}} bool 是否有自定义方法

字段对象属性

每个字段对象 (AutoCodeField) 包含以下属性:

属性 类型 说明
.FieldName string Go 字段名(大驼峰)
.FieldDesc string 字段描述
.FieldType string Go 类型
.FieldJson string JSON 字段名(小驼峰)
.ColumnName string 数据库列名
.DataTypeLong string 数据库类型
.Comment string 字段注释
.FieldSearchType string 搜索类型
.FieldSearchHide bool 是否隐藏搜索
.DictType string 字典类型
.Form bool 是否显示在表单
.Table bool 是否显示在表格
.Desc bool 是否显示在详情
.Excel bool 是否支持导出
.Require bool 是否必填
.DefaultValue string 默认值
.ErrorText string 校验失败提示
.Clearable bool 是否可清空
.Sort bool 是否支持排序
.PrimaryKey bool 是否主键
.DataSource *DataSource 数据源配置
.CheckDataSource bool 是否有数据源
.FieldIndexType string 索引类型

模板函数详解

类型转换函数

GenerateTSType - Go 类型转 TypeScript 类型

// 用法
{{ GenerateTSType .FieldType }}

// 类型映射
// string -> string
// int, int64, uint, float64 -> number
// bool -> boolean
// time.Time -> string
// json, array -> object

GenerateModelField - 生成 GORM Gen 模型字段

// 用法
{{ GenerateModelField . }}

// 输出示例
Title string `gorm:"column:title;type:varchar(255);comment:标题" json:"title"` // 标题

代码生成函数

GenerateGormGenSearchConditions - 生成 GORM Gen 搜索条件

// 用法
{{ GenerateGormGenSearchConditions .Fields .StructName }}

// 输出示例
if req.Title != nil && *req.Title != "" {
    q = q.Where(t.Title.Like("%" + *req.Title + "%"))
}
if req.Status != nil {
    q = q.Where(t.Status.Eq(*req.Status))
}

GenerateReactFormItem - 生成 React 表单项

// 用法
{{ GenerateReactFormItem . }}

// 输出示例(根据字段类型自动生成)
<Form.Item name="title" label="标题" rules={[{ required: true, message: '请输入标题' }]}>
    <Input placeholder="请输入标题" allowClear />
</Form.Item>

GenerateReactProTableColumn - 生成 ProTable 列配置

// 用法
{{ GenerateReactProTableColumn . }}

// 输出示例
{
    title: '标题',
    dataIndex: 'title',
    valueType: 'text',
    sorter: true,
},

GenerateReactSearchFormItem - 生成搜索表单项

// 用法
{{ GenerateReactSearchFormItem . }}

// 根据 FieldSearchType 生成不同的搜索组件
// LIKE -> Input
// EQ -> Select/Input
// BETWEEN -> DatePicker.RangePicker

GenerateReactDescriptionItem - 生成详情描述项

// 用法
{{ GenerateReactDescriptionItem . }}

// 输出示例
<Descriptions.Item label="标题">{currentRecord?.title}</Descriptions.Item>

GenerateReactDefaultValue - 生成默认值

// 用法
{{ GenerateReactDefaultValue . }}

// 根据字段类型生成默认值
// string -> ''
// int -> 0
// bool -> false
// time.Time -> undefined

自定义方法函数

GenerateCustomMethodInterface - 生成自定义方法接口

// 用法
{{ GenerateCustomMethodInterface .CustomMethods .StructName .Package }}

// 输出示例
FindByTitle(ctx context.Context, title string) (*example.Article, error)
GetPublishedArticles(ctx context.Context, status int) ([]*example.Article, error)

GenerateCustomMethodImpl - 生成自定义方法实现

// 用法
{{ GenerateCustomMethodImpl .CustomMethods .StructName .Package .Abbreviation }}

// 输出示例
func (r *articleRepo) FindByTitle(ctx context.Context, title string) (*example.Article, error) {
    t := query.Article
    m, err := t.WithContext(ctx).Where(t.Title.Eq(title)).First()
    if err != nil {
        return nil, err
    }
    return toBizArticle(m), nil
}

字符串处理函数

函数 说明 输入 输出
title 首字母大写 hello Hello
toPascalCase 转大驼峰 user_name UserName
ToCamelCase 转大驼峰 user_name UserName
ToLowerCamelCase 转小驼峰 user_name userName
ToSnakeCase 转下划线 UserName user_name
FirstLower 首字母小写 UserName userName
FirstUpper 首字母大写 userName UserName

创建自定义模板

步骤 1复制默认模板

# 复制默认模板到自定义目录
cp -r resource/package my-templates

步骤 2修改模板文件

根据项目需求修改模板文件。以下是一些常见的自定义场景:

场景 1修改 Handler 响应格式

编辑 my-templates/server/handler/handler.go.tpl

// 修改响应格式
func (h *{{.StructName}}Handler) Create{{.StructName}}(c *gin.Context) {
    var req request.{{.StructName}}Request
    if err := c.ShouldBindJSON(&req); err != nil {
        // 自定义错误响应
        c.JSON(400, gin.H{
            "code": 400,
            "message": err.Error(),
            "data": nil,
        })
        return
    }
    // ... 其他代码
}

场景 2添加自定义日志

编辑 my-templates/server/biz/biz.go.tpl

// Create 创建{{.Description}}
func (uc *{{.StructName}}Usecase) Create(ctx context.Context, {{.Abbreviation}} *{{.Package}}.{{.StructName}}) error {
    // 添加自定义日志
    uc.log.WithContext(ctx).Infof("[自定义日志] 开始创建{{.Description}}, 数据: %+v", {{.Abbreviation}})
    
    if err := uc.repo.Create(ctx, {{.Abbreviation}}); err != nil {
        uc.log.WithContext(ctx).Errorf("[自定义日志] 创建{{.Description}}失败: %v", err)
        return err
    }
    
    uc.log.WithContext(ctx).Infof("[自定义日志] 创建{{.Description}}成功, ID: %v", {{.Abbreviation}}.{{.PrimaryField.FieldName}})
    return nil
}

场景 3自定义前端组件样式

编辑 my-templates/web/pages/index.tsx.tpl

// 添加自定义样式
const {{.StructName}}Page: React.FC = () => {
    return (
        <PageContainer
            header={{
                title: '{{.Description}}管理',
                // 自定义头部样式
                style: { backgroundColor: '#f5f5f5' },
            }}
        >
            {/* 自定义内容 */}
        </PageContainer>
    );
};

步骤 3使用自定义模板

# 使用自定义模板生成代码
kra-gen generate -c autocode.yaml -t my-templates

# 或者设置环境变量
export KRA_TEMPLATE_DIR=my-templates
kra-gen generate -c autocode.yaml

模板开发最佳实践

1. 使用条件判断处理可选功能

{{- if .GvaModel }}
// 使用 KRA_MODEL 时包含 ID, CreatedAt, UpdatedAt, DeletedAt
type {{.StructName}} struct {
    global.KRA_MODEL
    {{- range .Fields}}
    {{- if not .PrimaryKey}}
    {{.FieldName}} {{.FieldType}} `json:"{{.FieldJson}}"`
    {{- end}}
    {{- end}}
}
{{- else }}
// 不使用 KRA_MODEL 时手动定义所有字段
type {{.StructName}} struct {
    {{- range .Fields}}
    {{.FieldName}} {{.FieldType}} `json:"{{.FieldJson}}"`
    {{- end}}
}
{{- end }}

2. 使用追加模式支持增量生成

{{- if .IsAdd}}
// 追加模式:只生成新增字段的代码片段
// 在 {{.StructName}}Repo 接口中新增如下方法
// 请根据实际需求添加

{{- else}}
// 完整模式:生成完整的代码文件
package {{.Package}}

// ... 完整代码
{{- end}}

3. 处理特殊字段类型

{{- range .Fields}}
{{- if eq .FieldType "time.Time" }}
// 时间类型字段特殊处理
{{.FieldName}} time.Time `json:"{{.FieldJson}}"`
{{- else if eq .FieldType "json" }}
// JSON 类型字段特殊处理
{{.FieldName}} datatypes.JSON `json:"{{.FieldJson}}"`
{{- else }}
// 普通字段
{{.FieldName}} {{.FieldType}} `json:"{{.FieldJson}}"`
{{- end }}
{{- end }}

4. 使用模板函数简化代码

// 不推荐:手动处理类型转换
{{- if eq .FieldType "int" }}
number
{{- else if eq .FieldType "string" }}
string
{{- else if eq .FieldType "bool" }}
boolean
{{- end }}

// 推荐:使用模板函数
{{ GenerateTSType .FieldType }}

5. 保持模板可读性

// 使用注释说明模板逻辑
{{/* 生成 CRUD 方法 */}}
{{- if not .OnlyTemplate }}

{{/* 创建方法 */}}
func (uc *{{.StructName}}Usecase) Create(ctx context.Context, {{.Abbreviation}} *{{.Package}}.{{.StructName}}) error {
    // ...
}

{{/* 删除方法 */}}
func (uc *{{.StructName}}Usecase) Delete(ctx context.Context, {{.PrimaryField.FieldJson}} {{.PrimaryField.FieldType}}) error {
    // ...
}

{{- end }}

模板调试技巧

1. 使用预览模式测试模板

# 预览生成的代码,不写入文件
kra-gen preview -c autocode.yaml -t my-templates --full

2. 检查模板语法错误

# 详细输出模式,显示模板解析过程
kra-gen generate -c autocode.yaml -t my-templates -v

3. 逐步调试

// 在模板中添加调试输出
{{/* DEBUG: 当前字段信息 */}}
// FieldName: {{.FieldName}}
// FieldType: {{.FieldType}}
// FieldSearchType: {{.FieldSearchType}}

模板版本管理

建议将自定义模板纳入版本控制:

# 项目结构
my-project/
├── resource/
│   └── package/           # 默认模板(不修改)
├── templates/
│   └── custom/            # 自定义模板(纳入版本控制)
│       ├── server/
│       └── web/
└── .gitignore
# .gitignore
# 忽略默认模板
resource/package/

# 保留自定义模板
!templates/custom/

生成的代码结构

后端代码结构

internal/
├── biz/                           # 业务逻辑层
│   └── {package}/
│       ├── {entity}.go            # Usecase + Repository 接口
│       └── enter.go               # 包入口Wire Provider
├── data/                          # 数据访问层
│   ├── model/                     # GORM Gen 模型
│   │   └── {package}/
│   │       └── {entity}.go        # 模型定义
│   └── {package}/
│       ├── {entity}.go            # Repository 实现
│       └── enter.go               # 包入口
├── service/                       # 服务层
│   ├── types/                     # 请求/响应类型
│   │   └── {package}/
│   │       └── request/
│   │           └── {entity}.go    # 请求结构体
│   └── {package}/
│       ├── {entity}.go            # Service 实现
│       └── enter.go               # 包入口
└── server/
    ├── handler/                   # HTTP Handler
    │   └── {package}/
    │       ├── {entity}.go        # Handler 实现
    │       └── enter.go           # 包入口
    └── router/                    # 路由配置
        └── {package}/
            ├── {entity}.go        # 路由注册
            └── enter.go           # 包入口

前端代码结构

web/src/
├── pages/                         # 页面组件
│   └── {package}/
│       └── {entity}/
│           ├── index.tsx          # 列表页面ProTable
│           ├── form.tsx           # 表单组件Modal Form
│           └── detail.tsx         # 详情组件Descriptions
├── services/kratos/               # API 服务
│   └── {package}.ts               # TypeScript API 调用
└── types/                         # 类型定义
    └── {package}/
        └── {entity}.d.ts          # TypeScript 类型

生成的 API 接口

接口 方法 路径 说明
创建 POST /{abbr}/create{Struct} 创建记录
删除 DELETE /{abbr}/delete{Struct} 删除单条记录
批量删除 DELETE /{abbr}/delete{Struct}ByIds 批量删除
更新 PUT /{abbr}/update{Struct} 更新记录
查询 GET /{abbr}/find{Struct} 根据 ID 查询
列表 GET /{abbr}/get{Struct}List 分页列表查询

常见问题

Q: 如何只生成后端代码?

使用 --no-web 参数:

kra-gen generate -c autocode.yaml --no-web

Q: 如何只生成前端代码?

使用 --no-server 参数:

kra-gen generate -c autocode.yaml --no-server

Q: 如何避免覆盖已有文件?

使用 --add 参数启用追加模式:

kra-gen generate -c autocode.yaml --add

Q: 如何只生成模板文件,不注入代码?

使用 --only-template 参数:

kra-gen generate -c autocode.yaml --only-template

Q: 如何回滚生成的代码?

  1. 通过 Web 界面:系统工具 > 代码生成器 > 历史记录 > 回滚
  2. 手动删除生成的文件和注入的代码

Q: 如何处理树形结构数据?

使用 --tree--tree-json 参数:

kra-gen generate -c autocode.yaml --tree --tree-json name

或在配置文件中设置:

options:
  isTree: true
  treeJson: name

Q: 如何配置字典类型?

在字段配置中设置 dictType

fields:
  - fieldName: Status
    dictType: article_status  # 字典类型名称

确保在系统中已创建对应的字典数据。

Q: 如何配置数据源(关联其他表)?

在字段配置中设置 dataSource

fields:
  - fieldName: AuthorID
    dataSource:
      table: sys_users        # 关联表名
      label: nick_name        # 显示字段
      value: id               # 值字段
      association: 1          # 1=一对一, 2=一对多
      hasDeletedAt: true      # 是否有软删除

Q: 生成的代码如何与 Wire 集成?

生成的代码会自动:

  1. 在各层的 enter.go 中导出 Provider
  2. 注入到 wire.go 的 ProviderSet 中
  3. 运行 wire 命令重新生成依赖注入代码
cd cmd/kratos-admin
wire

Q: 如何自定义生成的代码风格?

  1. 复制模板目录
  2. 修改模板文件
  3. 使用 --template 参数指定自定义模板
kra-gen generate -c autocode.yaml -t /path/to/custom/templates

更新日志

v1.0.0

  • 初始版本
  • 支持 Kratos DDD 架构代码生成
  • 支持 GORM Gen 数据层
  • 支持 React TypeScript 前端
  • 支持 CLI 和 Web 界面
  • 支持多数据库MySQL、PostgreSQL、SQLite