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
讨论数量: 2
qinhan

欢迎大家指正

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!