sqlgen

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2024 License: MIT Imports: 25 Imported by: 1

README

sql gen

由 Gen Guides https://gorm.io/gen/index.html 改写。

安装

go install github.com/githubzhaoqian/sqlgen/tools/gentool@latest

命令

  -c string
        is path for sqlgen.yml
  -db string
        input mysql|postgres|sqlite|sqlserver|clickhouse. consult[https://gorm.io/docs/connecting_to_the_database.html]
  -dsn string
        consult[https://gorm.io/docs/connecting_to_the_database.html]
  -fieldCoverable
        generate with pointer when field has default value
  -fieldNullable
        generate with pointer when field is nullable
  -fieldSignable
        detect integer field's unsigned type, adjust generated data type
  -fieldWithTags string
        generate field with custom tag
  -ot string
        output template 指定模板数据目录
  -overwrite
        overwrite existing file
  -tableRegexp string
        table regexp
  -tableRegexpStyle string
        table regexp style: lower/camel/snake
  -tables string
        enter the required data table or leave it blank
  -templateDir string
        generated with template directory

配置文件

version: "0.1"
database:
  # 数据库连接 consult[https://gorm.io/docs/connecting_to_the_database.html]"
  dsn: "dbUser:dbPassword@tcp(host:port)/dbName?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai"
  # 数据库类型 consult[https://gorm.io/docs/connecting_to_the_database.html]
  db: "mysql"
  # 表类型 You can cli input : orders,users,goods
  tables: # 指定表 可以在命令行使用 tables
    - failed_job
    - server_user
    - admin_user
  defaultAllTable: false  # 未指定table 是否生成全部表
  # generate with pointer when field is nullable
  #  默认生成指针类型
  fieldNullable: false  
  fieldCoverable: false
  # 数字类型是否支持 无负数类型
  fieldSignable: true 

  # 是否覆盖文件
  overwrite: false
  # table 正则用于替换路径使用
  tableRegexp: ^([a-z]+)_([a-z_]+)$
  modelName: "{2}"
  #  table 正则风格
  tableRegexpStyle: lower  # lower/camel/snake
  # 自定义tag 按json 蛇形添加
  fieldWithTags:
    - json
  # 指定模板目录,默认系统模板
  templateDir:
  templates:
    - outPath: "./internal/domain/{1}/internal/model/{2}/model.go"
      name: "Model"
    - outPath: "./internal/domain/{1}/bean/{2}/interface.go"
      name: "BeanInterface"
    - outPath: "./internal/domain/{1}/bean/{2}/bean.go"
      name: "Bean"
    - outPath: "./internal/domain/{1}/bean/{2}/po.go"
      name: "PO"
    - outPath: "./internal/types/{2}/types.go"
      name: "Types"
    - outPath: "./internal/domain/{1}/internal/mapper/{2}/interface.go"
      name: "MapperInterface"
    - outPath: "./internal/domain/{1}/internal/mapper/{2}/mapper.go"
      name: "Mapper"
    - outPath: "./internal/domain/{1}/service/{2}/interface.go"
      name: "ServiceInterface"
    - outPath: "./internal/domain/{1}/service/{2}/service.go"
      name: "Service"
  # 动态常量
  dynamicConstSuffixes:
    - "Status"
    - "Type"
  # 哪些是自动生成值的字段
  autoValueFields:
    - "ID"
    - "UpdateTime"
    - "CreateTime"
  dynamicConstOutPath: "./internal/consts/{2}/consts.go"
  dynamicConstTemplate: "Consts"
  # 常量包是否自动导入 ImportPkgPaths 变量中
  dynamicConstImport: false
  # 常量包后缀
  dynamicAliasSuffix: "Consts"
  # 自定义类型转换
  convTypeMap:
    timestamp: "timex.Time"
    datetime: "timex.Time"
  # 自定义类型包
  convTypePkgMap:
    "timex.Time": "gofastddd/internal/utils/timex"

功能

  • 输出默认模板
  • 指定模板路径
  • 指定tag
  • 生成 model 属性get方法
  • 是否覆盖已生成的文件
  • table 正则并生成 model query 路径
  • table 路径风格
  • 动态常量类型生成
  • 自定义类型对应包的导入
  • 动态模板生成代码

License

Released under the MIT License

Documentation

Index

Constants

View Source
const TemplateName = "template"
View Source
const TemplatePrefix = "*tpl"

Variables

View Source
var (
	// ErrEmptyCondition empty condition
	ErrEmptyCondition = errors.New("empty condition")
)
View Source
var (
	ErrFileExist = errors.New("file exist skip overwrite")
)
View Source
var TemplateFs embed.FS

Functions

func OutputTemplate

func OutputTemplate(dir string) error

Types

type Config

type Config struct {

	// generate model global configuration
	FieldNullable  bool // generate pointer when field is nullable
	FieldCoverable bool // generate pointer when field has default value, to fix problem zero value cannot be assign: https://gorm.io/docs/create.html#Default-Values
	FieldSignable  bool // detect integer field's unsigned type, adjust generated data type

	Mode GenerateMode // generate mode

	QueryPkgName string // generated query code's package name

	TemplateDir      string   // generated with template directory
	FieldWithTags    []string // generate field with custom tag
	Overwrite        bool     // overwrite existing file
	DefaultAllTable  bool     // 默认全部表
	TableRegexp      string   // table regexp
	TableRegexpStyle string   // table regexp style
	ModelName        string   // model 名称

	Templates            []Template // dynamic const suffix
	DynamicConstSuffixes []string   // dynamic const suffix
	DynamicConstOutPath  string     // dynamic const out path
	DynamicConstTemplate string     // 动态常量模板
	DynamicAliasSuffix   string     // 动态常量包别名后缀
	DynamicConstImport   bool       // 动态常量自动导入
	AutoValueFields      []string   // dynamic const suffix

	ConvTypeMap    map[string]string `yaml:"convType"`    // conv type
	ConvTypePkgMap map[string]string `yaml:"convTypePkg"` // conv type pkg
	// contains filtered or unexported fields
}

Config generator's basic configuration

func (*Config) Revise

func (cfg *Config) Revise() (err error)

Revise format path and db

func (*Config) WithJSONTagNameStrategy

func (cfg *Config) WithJSONTagNameStrategy(ns func(columnName string) (tagContent string))

WithJSONTagNameStrategy specify json tag naming strategy

type GenerateMode

type GenerateMode uint

GenerateMode generate mode

const (
	// WithDefaultQuery create default query in generated code
	WithDefaultQuery GenerateMode = 1 << iota

	// WithoutContext generate code without context constrain
	WithoutContext

	// WithQueryInterface generate code with exported interface object
	WithQueryInterface
)

type Generator

type Generator struct {
	Config

	Data map[string]*genInfo //gen query data
	// contains filtered or unexported fields
}

Generator code generator

func NewGenerator

func NewGenerator(cfg Config) *Generator

NewGenerator create a new generator

func (*Generator) ApplyBasic

func (g *Generator) ApplyBasic(models ...interface{})

ApplyBasic specify models which will implement basic .diy_method

func (*Generator) ApplyInterface

func (g *Generator) ApplyInterface(fc interface{}, models ...interface{})

ApplyInterface specifies .diy_method interfaces on structures, implment codes will be generated after calling g.Execute() eg: g.ApplyInterface(func(model.Method){}, model.User{}, model.Company{})

func (*Generator) Execute

func (g *Generator) Execute()

Execute generate code to output path

func (*Generator) GenerateAllTable

func (g *Generator) GenerateAllTable() (tableModels []interface{})

GenerateAllTable generate all tables in db

func (*Generator) GenerateModel

func (g *Generator) GenerateModel(tableName string) *generate.StructMeta

GenerateModel catch table info from db, return a BaseStruct

func (*Generator) GenerateModelAs

func (g *Generator) GenerateModelAs(tableName string, modelName string) *generate.StructMeta

GenerateModelAs catch table info from db, return a BaseStruct

func (*Generator) UseDB

func (g *Generator) UseDB(db *gorm.DB)

UseDB set db connection

type M

type M map[string]interface{}

M map[string]interface{}

type RowsAffected

type RowsAffected int64

RowsAffected execute affected raws

type SQLResult

type SQLResult sql.Result

SQLResult sql.result

type SQLRow

type SQLRow sql.Row

SQLRow sql.Row

type SQLRows

type SQLRows sql.Rows

SQLRows sql.Rows

type T

type T interface{}

T generic type

type Template added in v1.0.0

type Template struct {
	OutPath     string // specify a directory for output
	Name        string // template name
	DynamicType bool
}

Directories

Path Synopsis
internal
utils/pools
Package pools : goroutine pools
Package pools : goroutine pools
tools
gentool Module

Jump to

Keyboard shortcuts

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