gormer

package module
v0.0.0-...-62e2350 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2021 License: MIT Imports: 11 Imported by: 0

README

gormer

PkgGoDev

Useful scopes and tools for GORM V1

Chunk

db, err := gorm.Open(
    "mysql",
    "root:root@tcp(127.0.0.1:3306)/demo?charset=utf8mb4&parseTime=True&loc=Local&timeout=30s")
if err != nil {
    return
}

var data []YourObject
db = db.Table("your_object_table_name").Select("id, name").Where("bz_id = ?", 999)

gormer.ChunkByIDMaxMin(50, db, &data, func() {
    for _, item := range data {
        print(item.ID, ", ")
    }
    println("\n")
}, nil)

Pager

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

type QueryUserListParams struct {
    gormer.PageParam
    Name string `json:"name"`
}

type QueryUserListResult struct {
    gormer.PageResult
    List []User
}

var params = QueryUserListParams{}
var data = QueryUserListResult{}
data.PageParam = params.PageParam

db = db.Table("your_object_table_name").Where("bz_id = ?", 999)

data.Scan(db, &data.List)

Order

type QueryUserListParams struct {
    gormer.OrderParam
    Name string `json:"name"`
}
var params = QueryUserListParams{}

db = db.Table("your_object_table_name").Scopes(params.Order())

sql-gen

auto generate the helper functions for database field

  • Install
go install github.com/shockerli/gormer/sql-gen
  • Source code

source code of app/field/fields.go

//go:generate sql-gen
package field

import "app/enum"

//go:sql-gen -f=ALL
type IDX struct {
    ID int64 `json:"id" gorm:"column:id"`
}

//go:sql-gen -f=EQ,IN
type DispatchTypeX struct {
    DispatchType enum.DispatchType `json:"dispatch_type" sql:"column:dispatch_type"`
}
  • Generate code

execute command: go generate ./...

generate codes to app/field/fields_gen.go:

// Code generated by github.com/shockerli/gormer/sql-gen DO NOT EDIT

// Package field SQL build helper functions for field
package field

import (
  "github.com/jinzhu/gorm"
  "github.com/shockerli/gormer/tmp/enum"
)

// ****************** ID ****************** //

// Eq WHERE id = ?
func (i IDX) Eq(v ...int64) func(db *gorm.DB) *gorm.DB {
    if len(v) == 0 {
        v = append(v, i.ID)
    }
    return func(db *gorm.DB) *gorm.DB {
        return db.Where("id = ?", v[0])
    }
}

// Gt WHERE id > ?
func (i IDX) Gt(v ...int64) func(db *gorm.DB) *gorm.DB {
    if len(v) == 0 {
        v = append(v, i.ID)
    }
    return func(db *gorm.DB) *gorm.DB {
        return db.Where("id > ?", v[0])
    }
}

// ****************** DispatchType ****************** //

// Eq WHERE dispatch_type = ?
func (i DispatchTypeX) Eq(v ...enum.DispatchType) func(db *gorm.DB) *gorm.DB {
    if len(v) == 0 {
        v = append(v, i.DispatchType)
    }
    return func(db *gorm.DB) *gorm.DB {
        return db.Where("dispatch_type = ?", v[0])
    }
}
  • Use code

use Scope() build where condition

type ObjectItem struct {
    field.IDX
    field.DispatchTypeX
}

func (ObjectItem) TableName() string {
    return "object_item_01"
}

func main() {
    m := ObjectItem{}
    err := DB().Model(m).Scopes(m.IDX.Eq(1146)).Take(&m).Error
    s, _ := json.Marshal(m)
    spew.Dump(err, m)
    println(string(s), "\n")

    json.Unmarshal([]byte(`{"id":999}`), &m)
    println(m.DispatchType)
}

enum-gen

parse the enum const and comment, generate helper functions

  • Install
go install github.com/shockerli/gormer/enum-gen
  • Source code

source code of app/enum/pay_type.go

//go:generate enum-gen

package enum

type PayType uint8

const (
    PayTypeQQ     PayType = 1 // QQ支付
    PayTypeWeiXin PayType = 2 // 微信支付
    PayTypeAlipay PayType = 3 // 支付宝
)
  • Generate code

execute command: go generate ./...

generate codes to app/enum/pay_type_gen.go:

// Code generated by github.com/shockerli/gormer/enum-gen; DO NOT EDIT

// Package enum enum helpers
package enum

// ************ PayType ************ //

var payTypeMap = map[PayType]string{
    PayTypeQQ:     "QQ支付",
    PayTypeWeiXin: "微信支付",
    PayTypeAlipay: "支付宝",
}

// Check whether the type is exist
func (t PayType) Check() bool {
    _, ok := PayTypeMap()[t]
    return ok
}

// Desc return the desc of type
func (t PayType) Desc() string {
    return PayTypeMap()[t]
}

// PayTypeMap return all of the types
func PayTypeMap() map[PayType]string {
    return payTypeMap
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrBreakChunk = errors.New("break the chunk while")

ErrBreakChunk break the chunk while callback return error

Functions

func ChunkByIDMaxMin

func ChunkByIDMaxMin(size int64, db *gorm.DB, dest interface{}, callback ChunkCallback, l Logger, extra ...func(db *gorm.DB) *gorm.DB) (err error)

ChunkByIDMaxMin process data in chunks, scope by id

func JSONScanner

func JSONScanner(f interface{}, value interface{}) error

JSONScanner decoding DB field(JSON string) to custom type

func JSONValuer

func JSONValuer(f interface{}) (driver.Value, error)

JSONValuer encoding custom type to JSON string

func MaxMinID

func MaxMinID(db *gorm.DB) (max, min int64, err error)

MaxMinID fetch the max and min ID for scope, support GROUP BY

func TableName

func TableName(db *gorm.DB) string

TableName fetch table name from scope

Types

type ChunkCallback

type ChunkCallback func(loop int) error

ChunkCallback chunk callback type

type Column

type Column struct {
	Name          string      `json:"name"`
	Type          string      `json:"type"`
	NotNull       bool        `json:"not_null"`
	Unsigned      bool        `json:"unsigned"`
	AutoIncrement bool        `json:"auto_increment"`
	Charset       string      `json:"charset"`
	Collate       string      `json:"collate"`
	Default       interface{} `json:"default"`
	Comment       string      `json:"comment"`
}

Column table field info

type DefaultLogger

type DefaultLogger struct{}

DefaultLogger default logger, console output

func (*DefaultLogger) Debug

func (*DefaultLogger) Debug(v ...interface{})

Debug log a debug message

func (*DefaultLogger) Error

func (*DefaultLogger) Error(v ...interface{})

Error log a error message

func (*DefaultLogger) Info

func (*DefaultLogger) Info(v ...interface{})

Info log a message

type Key

type Key struct {
	Name        string   `json:"name"`
	IndexType   string   `json:"index_type"`
	IndexMethod string   `json:"index_method"`
	Comment     string   `json:"comment"`
	Columns     []string `json:"columns"`
}

Key table index key

type Logger

type Logger interface {
	Debug(...interface{})
	Info(...interface{})
	Error(...interface{})
}

Logger log message

type NoLogger

type NoLogger struct{}

NoLogger no log to output

func (*NoLogger) Debug

func (*NoLogger) Debug(...interface{})

Debug log a debug message

func (*NoLogger) Error

func (*NoLogger) Error(...interface{})

Error log a error message

func (*NoLogger) Info

func (*NoLogger) Info(...interface{})

Info log a message

type OrderParam

type OrderParam struct {
	OrderBy   string `json:"order_by"`   // (optional) column name, or SQL ORDER statement
	OrderType string `json:"order_type"` // (optional) ASC/DESC
}

OrderParam params of order by statement

func (*OrderParam) Order

func (p *OrderParam) Order() func(db *gorm.DB) *gorm.DB

Order scope: order by

type PageParam

type PageParam struct {
	CurrPage   int `json:"curr_page" binding:"number"` // (optional) current page number, default 1
	PageSize   int `json:"page_size" binding:"number"` // (optional) number of per page, default 10
	IgnorePage int `json:"ignore_page,omitempty"`      // (optional) no paging and no total count, while not 0
}

PageParam uniform paging parameters

func (*PageParam) Init

func (p *PageParam) Init()

Init init param

func (*PageParam) Page

func (p *PageParam) Page() func(db *gorm.DB) *gorm.DB

Page pager scope

type PageResult

type PageResult struct {
	PageParam
	TotalCount int `json:"total_count"`
	CurrCount  int `json:"curr_count"`
}

PageResult unified paging response structure

func (*PageResult) Count

func (p *PageResult) Count(db *gorm.DB) error

Count count result

func (*PageResult) Scan

func (p *PageResult) Scan(db *gorm.DB, dest interface{}) (err error)

Scan scan result and count

type Schema

type Schema struct {
	RawDDL           string    `json:"-"`
	TableName        string    `json:"table_name"`
	Engine           string    `json:"engine"`
	AutoIncrement    uint64    `json:"auto_increment"`
	DefaultCharset   string    `json:"default_charset"`
	DefaultCollation string    `json:"default_collation"`
	Comment          string    `json:"comment"`
	Columns          []*Column `json:"columns"`
	Keys             []*Key    `json:"keys"`
}

Schema table schema info

func (Schema) JSON

func (s Schema) JSON() string

JSON return json format content

func (Schema) Markdown

func (s Schema) Markdown() string

Markdown return markdown format content

func (Schema) NewDDL

func (s Schema) NewDDL() string

NewDDL new ddl for table, remove auto_increment

func (*Schema) Parse

func (s *Schema) Parse() error

Parse parse schema info from raw DDL

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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