MySQL 直接导出 model

 db2struct

 Converts a mysql table into a golang struc
 
根据 mysql 数据库中的表自动生成 golang struct

 地址#

https://github.com/Shelnutt2/db2struct

 安装#

- 首先需要安装 go
- go get github.com/Shelnutt2/db2struct/cmd/db2struct

 使用#

- 首先看看工具的使用
Golang

- 为了更加的通用,我写量脚本,将数据库配置以及表名等参数独立了出来,方便使用
- 上述参数需要放到 shell 脚本同级的目录之下的.config 文件中
- 执行脚本之后,会为每个表生产一个对应的 *.go 文件,文件中包含了转化之后的 struct,struct 名、文件名就是表名
- 脚本如下所示:
    - gen-model.sh

#!/usr/bin/env bash

# check if db2struct exist
check()
{
      if !(hash ${convert_tool} 2>/dev/null); then
        echo "convert tool ${convert_tool} is absent, install..."
        go get github.com/Shelnutt2/db2struct/cmd/db2struct
      fi
}

# generate golang model
gen()
{
  for table in ${TABLES[@]};
  do
    echo "del old model/${table}.go" && rm ../../model/${table}.go
    struct_name="$(echo ${table:0:1} | tr '[a-z]' '[A-Z]')${table:1}"
    db2struct -H ${HOST} -u ${USER} -p ${PASSWORD}  \
      --package ${GO_PACKAGE_NAME} -d ${DB}  \
      --table ${table} --struct ${struct_name}  \
      --target=${SAVE_PATH}/${table}.go \
      --json -v
    echo "finish model/${table}.go\n"
  done

# import related config
source .config
convert_tool=db2struct
check
gen

- 配置文件实例如下:
    - .config

GO_PACKAGE_NAME=model
SAVE_PATH=../../model
HOST=127.0.0.1
USER=root
PASSWORD=12345678
DB=gp_oj
TABLES=("role" "tag" "algorithm")

.config 中具体参数含义如下所示:

| 参数名 | 意义 | 
| ----- | ---- |
| GO_PACKAGE_NAME | model 文件(.go)的 package name|
| SAVE_PATH | model 文件(
.go)保存路径 |
| HOST | MySQL host |
| USER | MySQL username |
| PASSWORD | MySQL password |
| DB | MySQL db name|
| TABLES | MySQL 需要转化成 struct 的表 |

 demo#

- 允许结果大致如下所示:
    - 我是通过 makefile 来运行的
Golang

- 然后在 model 文件夹就可以看到文件了

Golang

Golang

本作品采用《CC 协议》,转载必须注明作者和本文链接
qinhan