genModels

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 7, 2020 License: MIT Imports: 8 Imported by: 1

README

model-gen

每次写go的orm的时候,总要去来回粘贴数据表,然后orm的东西又不对应,为此,懒人李只能造个轮子,为了提高效率(ps:就是想偷懒、摸鱼)。

一个Go专用的模型生成器就这样诞生啦

原理

通过获取数据库表结构,进行model文件生成。

迭代

目前支持mysql,未来预计支持mariadb和pgsql(sql server还未考量)

2019-12-19

  1. 支持多种风格文件生成(目前支持 bee、gorm、默认格式)
  2. 新增无符号整型和标签内容(size、type)

2019-12-23

  1. 增加主键支持

2019-12-24

  1. 增加gorm curd方法
  2. 增加orm自动初始化模板并支持orm

2019-12-26

  1. 增加gorm default

快速入门(命令行)

go get -u github.com/go-libraries/gmodel

gmodel -dsn="root:sa@tcp(localhost:3306)/blog" -dir=/tmp -style=bee -package=model

cat /tmp/cate.go

文件内容如下:

package model

import "github.com/astaxie/beego/orm"

func init(){
	orm.RegisterModel(new(Cate))
}

type Cate struct {
	Id         uint   `orm:"column(id);size(10);type(int(11) unsigned);" json:"id"`
	Name       string `orm:"column(name);size(50);type(varchar(50));" json:"name"`
	CreateTime string `orm:"column(create_time);type(timestamp);" json:"create_time"`
	UpdateTime string `orm:"column(update_time);type(timestamp);" json:"update_time"`
}

func (cate *Cate) GetTableName() string {
	return "cate"
}

s help:

Usage of gmodel:
  -dir string
    	a dir name save model file path, default is current path (default "/Users/limars/Go/bin")
  -driver mysql
    	database driver,like mysql `mariadb`, default is mysql (default "mysql")
  -dsn string
    	connection info names dsn
  -h	this help
  -help
    	this help
  -ig_tables string
    	ignore table names
  -package string
    	help
  -style bee
    	use orm style like bee `gorm`, default `default` (default "default")

代码应用

代码:

import (
	"github.com/go-libraries/genModels"
)

func BuildModels(dsn,path string) {


	if dsn != "" {
		Mysql := genModels.GetMysqlToGo()
		Mysql.Driver.SetDsn(dsn)

		//Mysql.SetStyle("bee")
		Mysql.SetStyle("gorm")
		Mysql.SetModelPath(build.ProjectPath)
		//Mysql.SetIgnoreTables("cate")
		Mysql.SetPackageName("models")
		Mysql.Run()
	}
}

执行结果:

ll /tmp
total *
-rw-r--r--  1 limars  wheel  297 12 18 17:59 cate.go
-rw-r--r--  1 limars  wheel  597 12 18 17:59 comment.go
-rw-r--r--  1 limars  wheel  826 12 18 17:59 content.go
......
cat cate.go
package models

type Cate struct {
	Id         int    `orm:"id" json:"id"`
	Name       string `orm:"name" json:"name"`
	CreateTime string `orm:"create_time" json:"create_time"`
	UpdateTime string `orm:"update_time" json:"update_time"`
}

func (cate *Cate) GetTableName() string {
	return "cate"
}

附带上sql:

CREATE DATABASE `blog`;

USE `blog`;

CREATE TABLE `cate` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL DEFAULT '',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;



CREATE TABLE `comment` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `blog_id` int(11) unsigned NOT NULL,
  `parent_id` int(11) unsigned NOT NULL DEFAULT '0',
  `ip` varchar(32) NOT NULL DEFAULT '',
  `email` varchar(255) NOT NULL DEFAULT '',
  `name` varchar(50) NOT NULL DEFAULT '',
  `content` tinytext NOT NULL,
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `status` tinyint(1) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


CREATE TABLE `content` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `cate_id` int(11) unsigned NOT NULL COMMENT '分类id',
  `title` varchar(255) NOT NULL DEFAULT '' COMMENT '标题',
  `description` tinytext NOT NULL COMMENT '简介',
  `content` text NOT NULL COMMENT '正文',
  `keyword` varchar(255) NOT NULL DEFAULT '' COMMENT 'seo关键字',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `status` tinyint(1) unsigned NOT NULL DEFAULT '1',
  `is_original` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1 原创  2 转载',
  `ext` text NOT NULL COMMENT '扩展字段',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Documentation

Index

Constants

This section is empty.

Variables

View Source
var GormInit = `` /* 235-byte string literal not displayed */
View Source
var GormTpl = `` /* 891-byte string literal not displayed */
View Source
var TypeMappingMysqlToGo = map[string]string{
	"int":                "int",
	"integer":            "int",
	"tinyint":            "int8",
	"smallint":           "int16",
	"mediumint":          "int32",
	"bigint":             "int64",
	"int unsigned":       "int",
	"integer unsigned":   "int",
	"tinyint unsigned":   "int8",
	"smallint unsigned":  "int16",
	"mediumint unsigned": "int32",
	"bigint unsigned":    "int64",
	"bit":                "int8",
	"bool":               "bool",
	"enum":               "string",
	"set":                "string",
	"varchar":            "string",
	"char":               "string",
	"tinytext":           "string",
	"mediumtext":         "string",
	"text":               "string",
	"longtext":           "string",
	"blob":               "string",
	"tinyblob":           "string",
	"mediumblob":         "string",
	"longblob":           "string",
	"date":               "string",
	"datetime":           "string",
	"timestamp":          "string",
	"time":               "string",
	"float":              "float32",
	"double":             "float64",
	"decimal":            "float64",
	"binary":             "[]byte",
	"varbinary":          "[]byte",
}

Functions

func Byte2Int64

func Byte2Int64(data []byte) int64

func CamelCase

func CamelCase(str, prefix string, ucFirst bool) string

aaa_bbb => AaaBbb if !ucFirst aaa_bbb => aaabbb

func CaseCamel

func CaseCamel(str string) string

func LcFirst

func LcFirst(s string) string

func Tab

func Tab(depth int) string

format

func UcFirst

func UcFirst(s string) string

Types

type Column

type Column struct {
	ColumnName      string
	Type            string
	Nullable        string
	TableName       string
	ColumnComment   string
	Tag             string
	MaxLength       int64
	NumberPrecision int64
	ColumnType      string
	ColumnKey       string
	Default         interface{}
}

func (Column) GetGoColumn

func (c Column) GetGoColumn(prefix string, ucFirst bool) string

func (Column) GetGoType

func (c Column) GetGoType() string

func (Column) GetMysqlType

func (c Column) GetMysqlType() string

func (Column) GetTag

func (c Column) GetTag(format Format) string

func (Column) IsAllowEmpty

func (c Column) IsAllowEmpty() bool

func (Column) IsPrimaryKey

func (c Column) IsPrimaryKey() bool

type Convert

type Convert struct {
	ModelPath   string // save path
	Style       string // tab key save like gorm ,orm ,bee orm......
	PackageName string // go package name

	TablePrefix  map[string]string   //if table exists prefix
	TableColumn  map[string][]Column //key is table , value is Column list
	IgnoreTables []string            // ignore tables
	Tables       []string            // all tables

	Driver SqlDriver // impl SqlDriver instance
	// contains filtered or unexported fields
}

func GetDriver

func GetDriver(dir, driver, dsn, style, packageName string) *Convert

func GetMysqlToGo

func GetMysqlToGo() *Convert

func (*Convert) GetStyle

func (convert *Convert) GetStyle() string

func (*Convert) Run

func (convert *Convert) Run()

run 1. connect 2. getTable 3. getColumns 4. build 5. write file

func (*Convert) SetIgnoreTables

func (convert *Convert) SetIgnoreTables(table ...string)

set model save path

func (*Convert) SetModelPath

func (convert *Convert) SetModelPath(path string)

set model save path

func (*Convert) SetPackageName

func (convert *Convert) SetPackageName(name string)

set model save path

func (*Convert) SetStyle

func (convert *Convert) SetStyle(name string)

func (*Convert) SetTablePrefix

func (convert *Convert) SetTablePrefix(table, prefix string)

set table prefix if exists replace prefix to empty string

type Format

type Format struct {
	Framework      string
	TabFormat      string // format must use 3 %s in it, first column name, second property  third json name
	AutoInfo       string
	PropertyFormat PropertyFormat // like size s
	JsonUseCamel   bool
}
var BeeFormat Format

`gorm:"column:beast_id"`

var DefaultFormat Format
var GormFormat Format

func GetFormat

func GetFormat(framework string) Format

func (Format) AutoImport

func (format Format) AutoImport(modelName string) string

func (Format) GetFuncTemplate

func (format Format) GetFuncTemplate(t string) string

func (Format) GetInitTemplate

func (format Format) GetInitTemplate(t string) string

func (Format) GetPropertyFormat

func (format Format) GetPropertyFormat() PropertyFormat

func (Format) GetTabFormat

func (format Format) GetTabFormat() string

type MysqlToGo

type MysqlToGo struct {
	Dsn string
	// contains filtered or unexported fields
}

func (*MysqlToGo) Connect

func (mtg *MysqlToGo) Connect() error

connection to mysql

func (*MysqlToGo) GetDriverType

func (mtg *MysqlToGo) GetDriverType() string

func (*MysqlToGo) GetDsn

func (mtg *MysqlToGo) GetDsn() string

connection to mysql

func (*MysqlToGo) GetTables

func (mtg *MysqlToGo) GetTables() (tables []string)

tables

func (*MysqlToGo) ReadTablesColumns

func (mtg *MysqlToGo) ReadTablesColumns(table string) []Column

read struct from db

func (*MysqlToGo) SetDsn

func (mtg *MysqlToGo) SetDsn(dsn string, options ...interface{})

connection to mysql

type PropertyFormat

type PropertyFormat struct {
	Size    string
	Type    string
	Index   string
	Default string
}

func (PropertyFormat) GetDefaultFormat

func (pf PropertyFormat) GetDefaultFormat() string

func (PropertyFormat) GetIndexFormat

func (pf PropertyFormat) GetIndexFormat() string

func (PropertyFormat) GetSizeFormat

func (pf PropertyFormat) GetSizeFormat() string

func (PropertyFormat) GetTypeFormat

func (pf PropertyFormat) GetTypeFormat() string

type SqlDriver

type SqlDriver interface {
	SetDsn(dsn string, options ...interface{})
	GetDsn() string
	Connect() error
	ReadTablesColumns(table string) []Column
	GetTables() []string
	GetDriverType() string
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL