使用 golang 操做数据库的同窗都会遇到一个问题 —— 根据数据表结构建立对应的 struct 模型。由于 golang 的使用首字母控制可见范围,咱们常常要设计 struct 字段名和数据库字段名的对应关系。长此以往,这是一个很是繁琐的过程。事情变得繁琐了,咱们都会想,有没有好的办法自动生成 model 呢?今天,记录一种自动生成代码的方法 —— xorm 工具。mysql
xorm是一个简单而强大的Go语言ORM库. 经过它能够使数据库操做很是简便。我在项目中常用,它的特性以下:git
想了解更多请移步:http://www.xorm.io/github
xorm 是一组数据库操做命令的工具,包含以下命令:golang
那咱们该如何使用 reverse 命令根据数据表结构生成 go 代码呢?redis
首先咱们要下载该工具 :sql
go get github.com/go-xorm/cmd/xorm
同时须要安装对应的 driver :shell
go get github.com/go-sql-driver/mysql //MyMysql go get github.com/ziutek/mymysql/godrv //MyMysql go get github.com/lib/pq //Postgres go get github.com/mattn/go-sqlite3 //SQLite
还须要下载 xorm :数据库
go get github.com/go-xorm/xorm
编译 cmd/xorm
会生成 xorm 工具, 假如环境变量。json
cd到安装路径
1.cd G:\go_workspace\GOPATH\src\github.com\go-xorm\cmd\xorm
2.go build
3.go build //这样就生成了xorm.exe缓存
3.xorm reverse postgres “dbname=test sslmode=disable user=postgres password=123” templates/goxorm
执行完毕,会在当前路径cd G:\go_workspace\GOPATH\src\github.com\go-xorm\cmd\xorm下的model文件夹里
出现test数据库中,全部表的go model
user.go
package model import ( "time" ) type User struct { Id int `xorm:"not null pk autoincr INTEGER"` Name string `xorm:"VARCHAR(20)"` Created time.Time `xorm:"default 'now()' DATETIME"` ClassId int `xorm:"default 1 INTEGER"` }
class.go
package model type Class struct { Id int `xorm:"not null pk autoincr INTEGER"` Name string `xorm:"VARCHAR(20)"` }
这时候,执行 xorm help reverse
能获取帮助信息以下:
usage: xorm reverse [-s] driverName datasourceName tmplPath [generatedPath] [tableFilterReg] according database's tables and columns to generate codes for Go, C++ and etc. -s Generated one go file for every table driverName Database driver name, now supported four: mysql mymysql sqlite3 postgres datasourceName Database connection uri, for detail infomation please visit driver's project page tmplPath Template dir for generated. the default templates dir has provide 1 template generatedPath This parameter is optional, if blank, the default value is model, then will generated all codes in model dir tableFilterReg Table name filter regexp
能够知道,执行参数 -s 表示为每张表建立一个单独文件。接下来的参数依次是:驱动,数据源,模板目录(在源码的 /cmd/xorm/templates/goxorm
可根据需求定制),生成目录,表格过滤条件。
接下来咱们以 Mysql 为例介绍使用方法。
xorm reverse mysql name:password@(ip:port)/xxx?charset=utf8 /cmd/xorm/templates/goxorm
这里输出目录参数省略,会在当前目录创建一个 model
目录,该目录下就是自动生成的 go 代码,, 驼峰命名方式。具体内容以下:
package model type TestModel struct { Id int `json:"id" xorm:"not null pk autoincr INT(11)"` VpsName string `json:"vps_name" xorm:"VARCHAR(30)"` VpsIp string `json:"vps_ip" xorm:"CHAR(15)"` VpsPrivateIp string `json:"vps_private_ip" xorm:"CHAR(50)"` VpsCpu int `json:"vps_cpu" xorm:"INT(11)"` VpsMem int `json:"vps_mem" xorm:"INT(11)"` VpsDisk int `json:"vps_disk" xorm:"INT(11)"` VpsStatus string `json:"vps_status" xorm:"VARCHAR(255)"` LastHeartTime int `json:"last_heart_time" xorm:"INT(11)"` CreateTime int `json:"create_time" xorm:"INT(11)"` LastTime int `json:"last_time" xorm:"INT(11)"` }
到这里,就生成了咱们想要的 model , 免去了手写的繁琐过程。