其他分享
首页 > 其他分享> > golang 用gorm生成module文件

golang 用gorm生成module文件

作者:互联网

网上的包过于繁琐复杂。所以写个简单。mysql的多种数据类型没有全部实现转化。可以编译成可执行文件。

package main

import (
	"flag"
	"fmt"
	"io"
	"os"
	"strings"
	"gorm.io/gorm"
	"gorm.io/driver/mysql"

)


var db *gorm.DB

func main()  {
	var host string
	var user string
	var pass string
	var database string
	var table string
	var pack string
	// 端口
	var port string

	flag.StringVar(&host,"h","","数据库地址")
	flag.StringVar(&pass,"p","","密码")
	flag.StringVar(&user,"u","","用户")
	flag.StringVar(&database,"d","","数据库")
	flag.StringVar(&table,"t","","表名")
	flag.StringVar(&port,"P","","端口")
	flag.StringVar(&pack,"k","","端口")
	// 解析
	flag.Parse()
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s)/%s?parseTime=True&loc=Local",
		user,
		pass,
		host,
		database,
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println(err)
	}
	type Field struct {
		Field string `gorm:"column:Field"`
		Type string `gorm:"column:Type"`
		Comment string `gorm:"column:Comment"`
	}
	var fieldObj []Field
	packageName := fmt.Sprintf("package %s\n\n", pack)
	structName := toUp(table)
	sns := fmt.Sprintf("type %s struct {", structName)
	file := packageName + sns
	sql := fmt.Sprintf("SELECT TABLE_NAME, COLUMN_COMMENT as Comment, COLUMN_NAME as Field, DATA_TYPE as Type from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='%s';", table)
	db.Raw(sql).Scan(&fieldObj)
	for _, value := range fieldObj {
		f := fmt.Sprintf("\n\t%s %s `json:\"%s\"` // %s ", toUp(value.Field), getType(value.Type), value.Field, value.Comment )
		file = file + f
	}
	sne := "\n}"
	file = file + sne
	tableName := fmt.Sprintf("\n\nfunc (%s) TableName() string {\n\treturn \"%s\"\n}" , structName, table )
	file = file + tableName
	fileName := fmt.Sprintf("%s.go", structName)
	fileInfo, er := os.Stat(fileName)
	if er == nil {
		// 存在就是不允许覆盖
		if fileInfo.Size() != 0 {
			fmt.Println("文件已存在!")
			return
		}
	}
	
	f, e := os.Create(fileName)
	if e != nil {
		fmt.Println("打开文件错误", e)
		return
	}
	_, we := io.WriteString(f, file)
	if we != nil {
		fmt.Println("写入文件错误", we )
		return
	}

}



func toUp( field string ) string {
	var nextUp bool
	str := ""
	for key, value := range field {
		if key == 0 {
			str = str + strings.ToUpper(string(value))
			continue
		}
		if string(value) == "_" {
			nextUp = true
			continue
		}
		if nextUp {
			str = str + strings.ToUpper(string(value))
			nextUp = false
		} else {
			str = str + string(value)
		}
	}

	return str

}

func getType( typeString string ) string {
	i := strings.Index(typeString, "(")
	if i < 0 {
		i = len(typeString) - 1
	}

	t := typeString[:i]
	m := map[string]string{
		"tinyint" : "int64",
		"smallint" : "int64",
		"mediumint" : "int64",
		"int" : "int64",
		"bigint" : "int64",
		"float" : "float64",
		"decimal" : "string",
		"bit" : "string",
		"year" : "string",
		"time" : "string",
		"date" : "string",
		"datetime" : "string",
		"timestamp" : "string",
		"char" : "string",
		"varchar" : "string",
		"tinytext" : "string",
		"text" : "string",
		"mediumtext" : "string",
		"longtext" : "string",
		"enum" : "string",
		// 其他类型默认转字符
	}
	if val, ex := m[t]; ex {
		return val
	} else {
		return "string"
	}
}

示例执行命令:

 go run main.go  -h 127.0.0.1  -P 3306 -u test -p passwrod -d db -t table -k module

释义:
根据指定的数据库地址表名,在当前目录下为表生成 package 名为module 的go文件。

标签:string,fmt,module,golang,flag,value,var,gorm
来源: https://www.cnblogs.com/jing1024/p/16409986.html