database to golang struct

Overview

Build Status Go Report Card GoDoc Mentioned in Awesome Go

中文文档

mysql database to golang struct conversion tools base on gorm(v1/v2),You can automatically generate golang sturct from mysql database. big Camel-Case Name Rule, JSON tag.

gui support

show

./gormt -g=true

cmd support

show

./gormt -g=false

install

go get -u -v github.com/xxjwxc/[email protected]

or: Dowloading


1. Configure default configuration items through the current directory config.yml file

note: for latest version of config format, please check /data/config/MyIni.go

out_dir : "./model"  # out dir
url_tag : json # web url tag(json,db(https://github.com/google/go-querystring))
language :  # language(English,中 文)
db_tag : gorm # DB tag(gorm,db)
simple : false #simple output
is_out_sql : false # Whether to output sql
is_out_func : true # Whether to output function
is_foreign_key : true # Whether to mark foreign key or not
is_gui : false # Whether to operate on gui
is_table_name : false # Whether to out GetTableName/column function
is_null_to_point : false # database is 'DEFAULT NULL' then set element type as point
is_web_tag: false
is_web_tag_pk_hidden: false
table_prefix: "" #table prefix
table_names: "" # Specified table generation, multiple tables with , separated
is_column_name: true # Whether to generate column names
is_out_file_by_table_name: false # Whether to generate multiple models based on table names
db_info :
    host : "127.0.0.1"
    port : 3306
    username : "root"
    password : "qwer"
    database : "oauth_db"
    type: 0 # database type (0:mysql , 1:sqlite , 2:mssql)
self_type_define: # Custom data type mapping
    datetime: time.Time
    date: time.Time
out_file_name: "" # Custom build file name
web_tag_type: 0 # json tag 0: Small Camel-Case 1: _

2. get help

./gormt --help
or
./gormt -h

-------------------------------------------------------
base on gorm tools for mysql database to golang struct

Usage:
  main [flags]

Flags:
  -d, --database string   数据库名
  -f, --foreign           是否导出外键关联
  -F, --fun               是否导出函数
  -g, --gui               是否ui显示模式
  -h, --help              help for main
  -H, --host string       数据库地址.(注意-H为大写)
  -o, --outdir string     输出目录
  -p, --password string   密码.
      --port int          端口号 (default 3306)
  -s, --singular          是否禁用表名复数
  -b, --table_names string 表名称  
  -l, --url string        url标签(json,url)
  -u, --user string       用户名.
  

3. Can be updated configuration items using command line tools

./gormt -H=127.0.0.1 -d=oauth_db -p=qwer -u=root --port=3306 -F=true

4. Support for gorm attributes

  • Database tables, column field annotation support
  • json tag json tag output
  • gorm.Model Support export gorm.model>>>
  • PRIMARY_KEY Specifies column as primary key
  • UNIQUE Specifies column as unique
  • NOT NULL Specifies column as NOT NULL
  • INDEX Create index with or without name, same name creates composite indexes
  • UNIQUE_INDEX Like INDEX, create unique index
  • Support foreign key related properties Support export gorm.model>>>
  • Support function export (foreign key, association, index , unique and more)Support export function >>>

You can enrich data types in def

5. Demonstration

  • sql:
CREATE TABLE `user_account_tbl` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `account` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `password` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `account_type` int(11) NOT NULL DEFAULT '0' COMMENT '帐号类型:0手机号,1邮件',
  `app_key` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT 'authbucket_oauth2_client表的id',
  `user_info_tbl_id` int(11) NOT NULL,
  `reg_time` datetime DEFAULT NULL,
  `reg_ip` varchar(15) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `bundle_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `describ` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE KEY `account` (`account`) USING BTREE,
  KEY `user_info_id` (`user_info_tbl_id`) USING BTREE,
  CONSTRAINT `user_account_tbl_ibfk_1` FOREIGN KEY (`user_info_tbl_id`) REFERENCES `user_info_tbl` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='用户账号'
--->Derived results
// UserAccountTbl 用户账号
type UserAccountTbl struct {
	ID            int    `gorm:"primary_key"`
	Account       string `gorm:"unique"`
	Password      string
	AccountType   int         // 帐号类型:0手机号,1邮件
	AppKey        string      // authbucket_oauth2_client表的id
	UserInfoTblID int         `gorm:"index"`
	UserInfoTbl   UserInfoTbl `gorm:"association_foreignkey:user_info_tbl_id;foreignkey:id"` // 用户信息
	RegTime       time.Time
	RegIP         string
	BundleID      string
	Describ       string
}

more>>>

6. support func export

The exported function is only the auxiliary class function of Gorm, and calls Gorm completely

// FetchByPrimaryKey primay or index 获取唯一内容
func (obj *_UserAccountTblMgr) FetchByPrimaryKey(ID int) (result UserAccountTbl, err error) {
	err = obj.DB.Table(obj.GetTableName()).Where("id = ?", ID).Find(&result).Error
	if err == nil && obj.isRelated {
		{
			var info UserInfoTbl // 用户信息
			err = obj.DB.Table("user_info_tbl").Where("id = ?", result.UserInfoTblID).Find(&info).Error
			if err != nil {
				return
			}
			result.UserInfoTbl = info
		}
	}

	return
}

more>>>

how to use call style>>>

7. build

make windows
make linux
make mac

or

go generate

8 note : in windows not support utf-8 style . ASCALL model

  • Switch encoding mode
CHCP 65001 

column notes default

  • Add a comment to the column starting with [@gorm default:'test']
  • example [@gorm default:'test';->;<-:create]this is my notes Indicates that the default value is 'test',can read/creat/write
  • Use of foreign key notes[@fk tableName.columnName]this is my notes Represents the 'columnName' column associated with the 'tableName'

9. one windows gui tools

1

2

3

4

Download

Stargazers over time

Stargazers over time

Issues
  • this is my question,what should i do

    this is my question,what should i do

    goroutine 1 [running]: github.com/xxjwxc/gormt/data/view/model.getTypeName(0xc0003fc790, 0x8, 0x1560455, 0x1) /Users/apple/go/src/github.com/xxjwxc/gormt/data/view/model/common.go:47 +0x218 github.com/xxjwxc/gormt/data/view/model.(_Model).genTableElement(0xc000555cf8, 0xc00047a000, 0x14, 0x27, 0xc00014a700, 0x7, 0x8) /Users/apple/go/src/github.com/xxjwxc/gormt/data/view/model/model.go:46 +0xc44 github.com/xxjwxc/gormt/data/view/model.(_Model).generate(0xc000555cf8, 0x7ffeefbffab8, 0x6) /Users/apple/go/src/github.com/xxjwxc/gormt/data/view/model/model.go:29 +0x1f9 github.com/xxjwxc/gormt/data/view/model.Generate(...) /Users/apple/go/src/github.com/xxjwxc/gormt/data/view/model/model.go:19 github.com/xxjwxc/gormt/data/view/gtools.Execute() /Users/apple/go/src/github.com/xxjwxc/gormt/data/view/gtools/gtools.go:25 +0x14a github.com/xxjwxc/gormt/data/cmd.glob..func1(0x1a41e60, 0xc00033e420, 0x0, 0x6) /Users/apple/go/src/github.com/xxjwxc/gormt/data/cmd/cmd.go:27 +0x20 github.com/spf13/cobra.(*Command).execute(0x1a41e60, 0xc0000b0010, 0x6, 0x6, 0x1a41e60, 0xc0000b0010)

    opened by zilinyo 10
  • status字段生成model的时候变为Statu

    status字段生成model的时候变为Statu

    这是我的config.yml配置

    base:
        is_dev: false
    db_info:
        host: 127.0.0.1
        port: 3306
        username: root
        password: 123456
        database: competitorAnalysis
        type: 0
    out_dir: ./internal/model/
    url_tag: json
    language: english
    db_tag: gorm
    is_web_tag_pk_hidden: false
    is_foreign_key: true
    is_out_sql: false
    is_out_func: false
    is_gui: false
    is_table_name: false
    is_null_to_point: false
    singular_table : false 
    simple : true 
    is_web_tag : false
    

    这是我的sql,每张表里的status字段都是生成为

    Statu int 
    

    所以我只放一张表的sql上来,

    CREATE TABLE `version` (
      `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
      `status` int NOT NULL DEFAULT '1' COMMENT '状态',
      `gmt_create` bigint NOT NULL COMMENT '创建时间',
      `gmt_modified` bigint NOT NULL COMMENT '更新时间',
      `online_time` bigint NOT NULL COMMENT '上线时间',
      `market_id` bigint NOT NULL COMMENT 'market id',
      `version` varchar(255) NOT NULL COMMENT '应用版本',
      `bundle_id` varchar(255) NOT NULL COMMENT '包名',
      `app_name` varchar(255) NOT NULL COMMENT '应用名字',
      `app_icon` varchar(255) DEFAULT NULL COMMENT '应用图标',
      `developer` varchar(255) NOT NULL COMMENT '开发者',
      `package_size` bigint NOT NULL COMMENT '包大小',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='版本';
    

    生成的字段 截屏2020-12-03 上午10 44 58

    opened by Pissssofshit 8
  • 给自定义SQL增加了根据条件判断是否生成的功能

    给自定义SQL增加了根据条件判断是否生成的功能

    给自定义SQL增加了根据条件判断是否生成的功能。因为有时候在查询时,某些字段需要根据前端传过来的查询参数来决定是否需要,例如对文章标题或者内容字段进行查找时,只有当前端传递过来的title这个字段不为空时才需要添加。使用类似下列情况

    query := model.Query{}
    query.AndOnCondition(vo.GetTitle()!= nil,"title","=",vo.GetTitle())
    query.And("username", "=", "name1")
    

    像下面这个生成的sql为

    query := model.Query{}
    query.And("username", "=", "name1")
    query.OrOnCondition(false, "password", "=", "pwd1")
    fmt.Println(query.Get())
    
    `username` = ? [name1]
    

    在使用自定义SQL时,直接把Get()的返回值当作参数传给db.Where() 会出现下列问题,所有的参数都只会被放到第一个变量里面而已。

    SELECT * FROM `blog_admin` WHERE `username` = ('name1','pwd1') or `password` = ?
    

    所以应该接受Get()的返回值后,再分别传入

    accountMgr := model.AccountMgr(db.Where(where, obj))
    
    opened by jiang4869 6
  • is_table_name : true  最新版本无效没有生成列名

    is_table_name : true 最新版本无效没有生成列名

    go get -u -v github.com/xxjwxc/[email protected] 生成出来的不带列名了

    base:
        is_dev : false
    out_dir : ./model  # 输出目录
    url_tag : json # web url tag(json,db(https://github.com/google/go-querystring))
    language :  # 语言(English,中 文)
    db_tag : gorm # 数据库标签(gorm,db)
    simple : false # 简单输出(默认gorm标签不输出)
    is_out_sql : true # 是否输出 sql 原信息
    is_out_func : false # 是否输出 快捷函数
    is_web_tag : true # 是否打web标记(json标记前提条件)
    is_web_tag_pk_hidden: true # web标记是否隐藏主键
    is_foreign_key : false # 是否导出外键关联
    is_gui : false # 是否ui模式显示
    is_table_name : true # 是否直接生成表名,列名
    is_null_to_point : false # 数据库默认 'DEFAULT NULL' 时设置结构为指针类型
    table_prefix : "" # 表前缀, 如果有则使用, 没有留空
    db_info:
        host :
        port : 3306
        username : 
        password :
        database : 
        type: 0 # 数据库类型:0:mysql , 1:sqlite ,  #2:mssql
    
    opened by april68666 6
  • how to use

    how to use

    大神,你这个文档写的看完也不知道怎么用,我的理解是:1.配置好yml 2.go build根目录下的main.go 但是貌似会编译失败 提示:go: github.com/go-playground/[email protected]: Get https://proxy.golang.org/github.com/go-playground/universal-translator/@v/v0.17.0.mod: dial tcp [2404:6800:4008:803::2011]:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. 求大神回复指导下

    opened by ClearWang 6
  • 当表名为order或者match时,无法生成对应的struct

    当表名为order或者match时,无法生成对应的struct

    以下为程序生成的日志: (/Users/jianghongchao/Downloads/gormt-master/data/view/model/genmysql/genmysql.go:113) [2020-04-30 15:59:20] [Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'match' at line 1] goroutine 18 [running]: runtime/debug.Stack(0xc0000119a0, 0xc0002ac6c0, 0x116) /usr/local/go/src/runtime/debug/stack.go:24 +0x9d github.com/xxjwxc/public/mylog.SaveError(0xc0002ac480, 0x114, 0x160aa2a, 0x3) /Users/jianghongchao/go/pkg/mod/github.com/xxjwxc/[email protected]/mylog/mylog.go:100 +0x382 github.com/xxjwxc/public/mysqldb.DbLog.Print(0x0, 0x0, 0xc000380a80, 0x3, 0x3) /Users/jianghongchao/go/pkg/mod/github.com/xxjwxc/[email protected]/mysqldb/log.go:36 +0x99 github.com/jinzhu/gorm.(*DB).print(0xc0003b40d0, 0xc000380a80, 0x3, 0x3) /Users/jianghongchao/go/pkg/mod/github.com/jinzhu/[email protected]/main.go:841 +0x52 created by github.com/jinzhu/gorm.(*DB).AddError /Users/jianghongchao/go/pkg/mod/github.com/jinzhu/[email protected]/main.go:781 +0x2fc

    good first issue 
    opened by hutu1st 5
  • GetByOption/GetByOptions系列函数功能无效

    GetByOption/GetByOptions系列函数功能无效

    win10环境下,在gin这个web server下引入gormt生成的代码,调用方式跟测试案例类似,即: userMgr := model.UserMgr(db) userMgr.GetByOption(userMgr.WithAccount("aa"), userMgr.WithPwd("bb")) 发觉返回数据不正确,经调试,发觉GetByOption函数内部,调用apply的时候,拿不到传入进去的参数"aa"和"bb",调试查看变量的时候,提示报错 error code 299—— Only part of a ReadProcessMemory or WriteProcessMemory request was completed。而且最终得到的options.options这个map里存在Account和Pwd的key,但是里面的内容都是"",不知道具体是什么原因。

    opened by jet-xita 5
  • 不支持smallint类型

    不支持smallint类型

    {"Host":"127.0.0.1","Port":3306,"Username":"root","Password":"123456","Database":"xjaccountsdb"} panic: type (smallint(6)) not match in any way.maybe need to add on ()

    opened by android-coco 5
  • 修改simple配置为true不输出gorm标签,将is_table_name中的column生成单独抽成配置,以免配置的耦合,增加根据表名生成多个model的配置(一个表一个model)

    修改simple配置为true不输出gorm标签,将is_table_name中的column生成单独抽成配置,以免配置的耦合,增加根据表名生成多个model的配置(一个表一个model)

    1.simple配置为true不输出gorm标签 2.将is_table_name中的column生成单独抽成配置,以免配置的耦合。 3.增加根据表名生成多个model的配置(一个表一个model)

    1. Simple is configured as true and does not output Gorm tag
    2. Will be_ table_ The column in name generates a separate extraction configuration to avoid the coupling of configuration.
    3. Add the configuration of generating multiple models according to the table name (one model for each table)
    opened by crabmanY 4
  • 表前缀匹配不生效

    表前缀匹配不生效

    目标:支持单个表的代码生成 实际:GUI经常卡死,遂尝试cmd命令,看到代码应该支持表前缀模糊匹配的,但是各种尝试均不生效,'-t','--table_prefix',求解,不想每次生成全量 ./gormt -g=false -H=xxx.xxx.xxx.xxx -d=xx -p=x -u=x --port=x --table_prefix=table_name -F=true -o=/Users/xxx/model

    opened by nanfangstation 4
  • 有计划生成struct的时候顺便把 字段字符串也生成出来吗

    有计划生成struct的时候顺便把 字段字符串也生成出来吗

    type User struct{
      ID int
     Name string
    }
    
    Columns = struct {
    	ID              string
            Name         string       
    	}{
    	ID:  "id",                  
            Name: "name",           
    	}
    

    类似这样的,然后使用gorm 的 Select(Columns.Name) ,就可以了不用写死硬编码字符串容易出错

    good first issue Repaired 
    opened by april68666 4
  • error info:  Key: 'MysqlDbInfo.Port' Error:Field validation for 'Port' failed on the 'required' tag Key: 'MysqlDbInfo.Port' Error:Field validation for 'Port' failed on the 'required' tag

    error info: Key: 'MysqlDbInfo.Port' Error:Field validation for 'Port' failed on the 'required' tag Key: 'MysqlDbInfo.Port' Error:Field validation for 'Port' failed on the 'required' tag

    error info: Key: 'MysqlDbInfo.Port' Error:Field validation for 'Port' failed on the 'required' tag Key: 'MysqlDbInfo.Port' Error:Field validation for 'Port' failed on the 'required' tag

    gormt -H=127.0.0.1 -d=test -p=root -u=root -port=3306 -o=./model -s=true

    maC

    opened by cxjhk 0
  • 自增字段tag缺失,迁移后,创建的表无自增属性,导致执行sql失败

    自增字段tag缺失,迁移后,创建的表无自增属性,导致执行sql失败

    数据表中的主键是自增的,生成go文件后,tag中未包含自增的描述autoIncrement

    ID       uint32 `gorm:"primaryKey;column:id;type:int unsigned;not null"`
    

    当执行db. AutoMigrate后,插入一条数据会报错:

    Could not save row: Error 1364: Field 'id' doesn't have a default value
    

    gorm迁移的sql语句是:

    CREATE TABLE `rank` (`id` int unsigned NOT NULL,PRIMARY KEY (`id`))
    

    解决方案:在生成go文件的时候,把是否自增的信息写进tag中。

    详细tag参考:https://gorm.io/zh_CN/docs/models.html#%E5%AD%97%E6%AE%B5%E6%A0%87%E7%AD%BE

    经过了解,这是两个bug:

    1. gormt没有把autoIncrement写进tag中(不过,该实现还是要实现的吧~
    2. gorm没有实现autoIncrement (参考:https://github.com/go-gorm/gorm/issues/5266
    opened by wclssdn 7
Releases(v2.1.gorm)
Schemable - Schemable provides basic struct mapping against a database, using the squirrel package

Schemable Schemable provides basic struct mapping against a database, using the

null 6 Mar 7, 2022
[mirror] the database client and tools for the Go vulnerability database

The Go Vulnerability Database golang.org/x/vulndb This repository is a prototype of the Go Vulnerability Database. Read the Draft Design. Neither the

Go 53 Aug 12, 2022
Database - Example project of database realization using drivers and models

database Golang based database realization Description Example project of databa

Denis 1 Feb 10, 2022
一个使 mysql,pgsql 数据库表自动生成 go struct 的工具

db2go 一个使 mysql、pgsql 数据库表自动生成 go struct 的工具 快速使用 将项目放入到GOPATH/src目录下

易水韩 18 Jun 1, 2022
auto generate sql from gorm model struct

gorm2sql: auto generate sql from gorm model struct A Swiss Army Knife helps you generate sql from gorm model struct. Installation go get github.com/li

Danieliu 115 Aug 15, 2022
A Go SQL query builder and struct mapper.

godb - a Go query builder and struct mapper godb is a simple Go query builder and struct mapper, not a full-featured ORM. godb does not manage relatio

Samuel GAY 716 Aug 8, 2022
ddl-maker generate ddl (SQL file) from Go struct.

[日本語] What is ddl-maker ddl-maker generate ddl (SQL file) from golang struct. It's only supported MySQL only now. The original code is kayac/ddl-maker

CHIKAMATSU Naohiro 3 Jun 16, 2022
Database migrations. CLI and Golang library.

migrate Database migrations written in Go. Use as CLI or import as library. Migrate reads migrations from sources and applies them in correct order to

null 9.4k Aug 12, 2022
Constant Database native golang implementation

CDB golang implementation cdb is a fast, reliable, simple package for creating and reading constant databases see docs for more details Advantages Ite

Alexander Petrov 32 Jul 15, 2022
Golang restAPI crud project with mySql database.

Golang RestAPI using gorilla/mux Golang restAPI crud project with mySql database. Test Api with Thunder Client vs code beautiful Extension. and use Be

Md Abu. Raihan 6 Mar 26, 2022
Database Access Layer for Golang - Testable, Extendable and Crafted Into a Clean and Elegant API

REL Modern Database Access Layer for Golang. REL is golang orm-ish database layer for layered architecture. It's testable and comes with its own test

REL 555 Aug 9, 2022
A simple Golang-based application that queries a PostgreSQL database

Qwik-E-Mart Demo App A simple Golang-based application that queries a PostgreSQL database named qwikemart to read and return customer data stored in t

Joe Garcia 0 Nov 6, 2021
Implementasi database oracle kedalam golang

Go with Oracle database Implementasi database oracle kedalam golang How to using swagger Install generator swagger menggunakan perintah : go get -u gi

Muhammad Rais Adlani 0 Nov 20, 2021
Golang database driver for SQLite

go-sqlite Golang database driver for SQLite. Does not use cgo. This driver is based on pure-Go SQLite implementation (https://gitlab.com/cznic/sqlite)

glebarez 69 Aug 14, 2022
BigQuery database/sql golang driver

BigQuery SQL Driver This library is compatible with Go 1.17+ Please refer to CHA

Viant, Inc 5 Jun 7, 2022
🏋️ dbbench is a simple database benchmarking tool which supports several databases and own scripts

dbbench Table of Contents Description Example Installation Supported Databases Usage Custom Scripts Troubeshooting Development Acknowledgements Descri

Simon Jürgensmeyer 72 Jul 25, 2022
Database wrapper that manage read write connections

rwdb Database wrapper that manage read write connections Install go get github.com/andizzle/rwdb Create connections package main import "github.com/

Andy Zhang 15 Aug 5, 2022
Vitess is a database clustering system for horizontal scaling of MySQL.

Vitess Vitess is a database clustering system for horizontal scaling of MySQL through generalized sharding. By encapsulating shard-routing logic, Vite

Vitess 14.5k Aug 8, 2022