gt

package module
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2020 License: MIT Imports: 35 Imported by: 0

README

Erwin Schrödinger's Cat

gt使用手册 (v1.9.0+)

api快速开发业务框架,模型生成

demo: deercoder-gin

API

API Examples

Model

// user model
type User struct {
	ID         uint64     `json:"id"`
	Name       string     `json:"name"`
	Createtime time.CTime `json:"createtime"`
}

// service model
type Service struct {
	ID   uint64 `json:"id"`
	Name string `json:"name"`
}

// order model
type Order struct {
	ID         uint64     `json:"id"`
	UserID     int64      `json:"user_id"`    // user id
	ServiceID  int64      `json:"service_id"` // service table id
	Createtime time.CTime `json:"createtime"` // createtime
}

// order detail
type OrderD struct {
	Order
	UserName    string `json:"user_name"`    // user table column name
	ServiceName string `json:"service_name"` // service table column `name`
}

    // select more
    // 多表查询
	// get more search
	var params = make(cmap.CMap)
	params.Add("user_id", "1")
	//params.Add("key", "梦") // key word
	params.Add("clientPage", "1") // 第一页
	params.Add("everyPage", "2") // 每页2条
	var or []*OrderD
	crud := NewCrud(
		Inner("order", "user", "order", "service"),
		//Left("order", "service"),
		Model(OrderD{}),
		Data(&or),
		SubWhereSQL("1 = 1", "2 = 2", ""),
	)
	err := crud.GetMoreBySearch(params).Error()
	if err != nil {
		log.Println(err)
	}
	t.Log("\n[User Info]:", or[0])
    
// output:
    TestGetMoreDataBySearch: db_test.go:243: 
        [User Info]: &{{1 1 1 "2019-01-28 15:07:06"} 梦sql 服务名称}
--- PASS: TestGetMoreDataBySearch (0.00s)
PASS

Struct Gt

gt:"sub_sql"<忽略该字段解析,<可进行子查询>>

type Client struct {
	models.AdminCom
	Name    string `gorm:"type:varchar(30)" json:"name" valid:"required,len=2-20"` // 昵称
	Openid  string `json:"openid" gorm:"varchar(30);UNIQUE_INDEX:openid已存在"`       // openID
	HeadImg string `json:"head_img"`                                               // 头像
}

type ClientD struct {
	Client      // 头像
	BuyNum int8 `json:"buy_num" gt:"sub_sql"` // 购买次数
}
// search
func (c *Client) GetBySearch(params cmap.CMap) interface{} {

	buyNumSQL := "(select count(*) from `order` where client_id = `client`.id and status >= 3) as buy_num"
	var datas []*ClientD
	crud.Params(
		gt.Data(&datas),
		gt.SubSQL(buyNumSQL),
		)
	cd := crud.GetBySearch(params)
	if cd.Error() != nil {
		//log.Log.Error(err.Error())
		return result.CError(cd.Error())
	}
	return result.GetSuccessPager(datas, cd.Pager())
}
// output:
print sql: select `id`,`createtime`,`admin_id`,`name`,`openid`,`head_img`,(select count(*) from `order` where client_id = `client`.id and status >= 3) as buy_num from `client` order by id desc limit 0, 2 

gt:"field:fieldName"<特殊情况下,替代json解析>

    type CVB struct {
		ID          int64      `gorm:"type:bigint(20)" json:"id"`
		ClientVipID int64      `gorm:"type:bigint(20)" json:"client_vip_id"`
		ShopId      int64      `gorm:"type:bigint(20)" json:"shop_id"`
	}

	// 客户行为详情
	type CVBDe struct {
		CVB
		ClientName    string `json:"client_name"`
		VipType       int64  `json:"vip_type" gt:"sub_sql"`
		IsSp          int64  `json:"-" gt:"field:is_sp"`
	}
	gt := &GT{
		Params: &Params{
			InnerTable: []string{"client_vip_behavior", "client_vip", "client_vip", "client"},
			Model:      CVBDe{},
		},
	}
	sqlNt, sql, _, _, _ := GetMoreSearchSQL(gt)
	t.Log(sqlNt)
	t.Log(sql)
// output:
TestGetMoreSearchSQL: db_test.go:267: select count(`client_vip_behavior`.id) as total_num from `client_vip_behavior` inner join `client_vip` on `client_vip_behavior`.`client_vip_id`=`client_vip`.`id`  inner join `client` on `client_vip`.`client_id`=`client`.`id` 
TestGetMoreSearchSQL: db_test.go:268: select `client_vip_behavior`.`id`,`client_vip_behavior`.`client_vip_id`,`client_vip_behavior`.`shop_id`,`client`.`name` as client_name,`client_vip_behavior`.`is_sp` from `client_vip_behavior` inner join `client_vip` on `client_vip_behavior`.`client_vip_id`=`client_vip`.`id`  inner join `client` on `client_vip`.`client_id`=`client`.`id`  order by `client_vip_behavior`.id desc 

Crud Request

// GET Request
//func ToCMap(u *gin.Context) cmap.CMap {
//	err := u.Request.ParseForm()
//	if err != nil {
//		gt.Logger().Error(err.Error())
//		return nil
//	}
//	values := cmap.CMap(u.Request.Form)
//	xss.XssMap(values)
//	return values
//}

var crud = gt.NewCrud(
	gt.Model(Client{}),
)

// get data, by id
func (c *Client) GetByID(id string) (*Client, error) {

	var data Client // not use *Client
	crud.Params(gt.Data(&data))
	if err := crud.GetByID(id).Error(); err != nil {
		return nil, err
	}
	return &data, nil
}

// get data, limit and search
// clientPage 1, everyPage 10 default
func (c *Client) GetBySearch(params cmap.CMap) (datas []*Client, pager result.Pager, err error) {
	//var datas []*Client
	crud.Params(gt.Data(&datas))
	cd := crud.GetBySearch(params)
	if cd.Error() != nil {
		return nil, pager, cd.Error()
	}
	return datas, cd.Pager(), nil
}

// id支持批量删除(逗号分割), 如: id = 12,13,14
// delete data, by id
func (c *Client) Delete(id string) error {

	return crud.Delete(id).Error()
}

// update data
func (c *Client) Update(data *Client) (*Client, error) {

	crud.Params(gt.Data(data))
	if err := crud.Update().Error(); err != nil {
		return nil, err
	}
	return data, nil
}

// create data
func (c *Client) Create(data *Client) (*Client, error) {

	crud.Params(gt.Data(data))
	if err := crud.Create().Error(); err != nil {
		return nil, err
	}
	return data, nil
}

Crud More

多表查询支持多表/同一个mysql跨数据库查询/mock假数据等等

    // 多表查询
	// get more search
	var params = make(cmap.CMap)
	//params.Add("user_id", "1")
	//params.Add("key", "梦") // key work
	params.Add("clientPage", "1")
	params.Add("everyPage", "2")
	//params.Add("mock", "1") // mock data
	var or []*OrderD
	crud := NewCrud(
		// 支持同一个mysql多数据库跨库查询
		Inner("gt.order", "user"),
		Left("order", "service"),
		Model(OrderD{}),
		Data(&or),
		//SubWhereSQL("1 = 1", "2 = 2", ""),
	)
	err := crud.GetMoreBySearch(params).Error()
	if err != nil {
		log.Println(err)
	}
	t.Log("\n[User Info]:", or)

CreateMore

// 批量创建
func TestCreateMoreDataJ(t *testing.T) {
    type UserPar struct {
		Name       string     `json:"name"`
		Createtime time.CTime `json:"createtime"`
	}
	type User struct {
		ID uint64 `json:"id"`
		UserPar
	}
	
	var up = []UserPar{
		{Name: "测试1", Createtime: time.CTime(time2.Now())},
		{Name: "测试2"},
	}
	crud := NewCrud(
		//Table("user"),
		Model(UserPar{}),
		Data(up),
		//SubSQL("(asdf) as a","(asdfa) as b"),
	)

	err := crud.CreateMore()
	t.Log(err)
}

  • 多模式配置文件

配置方式: conf/app.yaml 中 devMode = dev 对应conf/app-dev.yaml

GetDevMode

    type dba struct {
    	User        string
    	Password    string
    	Host        string
    	Name        string
    	MaxIdleConn int
    	MaxOpenConn int
    	// db log mode
    	Log bool
    }
    config := gt.Configger()
    dbS := &dba{
        user:     config.GetString("app.db.user"),
        password: config.GetString("app.db.password"),
        host:     config.GetString("app.db.host"),
        name:     config.GetString("app.db.name"),
    }
    // or
    dbS := &dba{}
    gt.Configger().GetStruct("app.db", dbS)

CacheManager

    ce = gt.NewCache()
    data := CacheModel{
		Time: 50 * CacheMinute,
		Data: user,
	}

	// key can use user.ID,user.Name,user
	// because it can be interface
	// set
	err := ce.Set(user, data)
	t.Log("set err: ", err)

	// get
	reply, _ := ce.Get(user)
	t.Log("user data :", reply.Data)

AesEnDe

log.Println("[加密测试]:", AesEn("123456"))
log.Println("[解密测试]:", AesDe("lIEbR7cEp2U10gtM0j8dCg=="))

Time

// 时间格式化2006-01-02 15:04:05
type CTime time.Time
// 时间格式化2006-01-02
type CDate time.Time 

JSONType

// 返回json类型
type CJSON []byte

Validator

func TestValidator(t *testing.T) {

	type Test struct {
		ID   int64  `json:"id" valid:"required,min=0,max=5"`
		Name string `json:"name" valid:"required,len=2-5" trans:"用户名"`
	}

	// form request data
	var maps = make(map[string][]string)
	maps["name"] = append(maps["name"], "梦1")
	info := Valid(maps, Test{})
	log.Println(info)

	// json request data
	var test = Test{
		ID:   6,
		Name: "梦1",
	}
	log.Println(Valid(test, Test{}))

}

CustomLog

func TestNewFileLog(t *testing.T) {

	myLog.Info("项目路径", projectPath)
	for {
		time.Sleep(1 * time.Second)
		myLog.Error("测试")
	}
}

SnowflakeId

func TestId(t *testing.T) {
	id, err := NewID(1)
	if err != nil {
		log.Print(err)
		return
	}
	t.Log(id.String())
}

Msg

消息中间件nsq

前提: 运行nsq, 参考docker-compose.yaml

参考:nsq_test.go

Extend Examples

Crud Selectsql

    sql := "update `user` set name=? where id=?"
    t.Log("[Info]:", crud.Select(sql, "梦sql", 1).Exec())
    var user []*User
	cd := crud.Params(
		Data(&user),
		//ClientPage(1), // serch()分页需要
		//EveryPage(2),
	).
		Select("select *from user").
		Select("where id > 0")
	if true {
		cd.Select("and 1=1")
	}
	cd.Search() // 查询 + 分页
    t.Log(crud.Pager()) // Search()分页数据
	//cd.Single() // 注释Search使用Single()直接查询

Crud Update

    type UserPar struct {
		Name string `json:"name"`
	}
	crud := crud.Params(
		//Table("user"),
		Model(User{}),
		Data(&UserPar{
			//ID:   1,
			Name: "梦S",
		}),
	)
	t.Log(crud.Update().RowsAffected())
	t.Log(crud.Select("`name` = ?", "梦").Update().RowsAffected())
	t.Log(crud.Error())

Transcation

    cd := crud.Begin()
	cd.Params(
		Table("user"),
		Data(&User{
			ID:   11234,
			Name: "梦S",
		}),
	).Create()
	if cd.Error() != nil {
		cd.Rollback()
	}
	cd.Params(
		Data(&User{
			Name: "梦SSS2",
		})).Create()
	if cd.Error() != nil {
		cd.Rollback()
	}
	// add select sql test
	var u []User
	cd.Params(Data(&u)).Select("select * from `user`").Select("where 1=1").Single()
	cd.Params(Data(&u)).Select("select * from `user`").Select("where 1=1").Single()
	//cd.DB().Raw("select * from `user`").Scan(&u)

	cd.Commit()
	if cd.Error() != nil {
		cd.Rollback()
	}

Use Gorm

模型定义需遵循:模型定义

// example 1:
// 根据模型定义自动生成表
gt.NewDBTool().AutoMigrate(&User{},&Order{})
// 直接使用gorm:
db := gt.NewCrud().DB()

Mock Data

使用mock参数, 生成随机数据, 将不会进行数据库查询

    GetBySearch(params cmap.CMap) Crud     // search
    GetByData(params cmap.CMap) Crud       // get data no search
    GetMoreBySearch(params cmap.CMap) Crud // more search    
    // 以上三种支持mock参数,传递的参数mock=1即可

Crud clone

// 关于crud的
一个crud = gt.NewCrud()对象中的参数是共享的,通用的增删改查针对同一张表可复用  
如果进行了表关联或改变了模型, 需要重新cd = gt.NewCrud(),否则继续使用crud容易影响到其他使用这个变量的地方

ps:
1.不支持CJSON类型, 请使用tag: faker:"-"进行过滤
2.不支持图片等实体文件数据
3.默认随机生成,如有长度等其他要求,请参考:faker_test

  • 约定
    1.模型结构体json 内容与表字段保持一致
    2.返回格式参考result
    3.多表关联命名, 模型中其他表字段命名: 他表名 + "_" + 他表字段名
    n....

Documentation

Index

Constants

View Source
const (
	Debug = "debug" // default level
	Info  = "info"
	Warn  = "warn"
	Error = "error"
)

log level

View Source
const Version = "1.9.0+"

Variables

View Source
var LogFormatter = func(values ...interface{}) (messages []interface{}) {
	if len(values) > 1 {
		var (
			sql             string
			formattedValues []string
			level           = values[0]
			currentTime     = "\033[33m[" + gorm.NowFunc().Format("2006-01-02 15:04:05") + "]\033[0m"
		)

		messages = []interface{}{currentTime}

		if len(values) == 2 {

			currentTime = currentTime[1:]

			messages = []interface{}{currentTime}
		}

		if level == "sql" {

			messages = append(messages, fmt.Sprintf(" \033[36;1m[%.2fms]\033[0m ", float64(values[2].(time.Duration).Nanoseconds()/1e4)/100.0))

			for _, value := range values[4].([]interface{}) {
				indirectValue := reflect.Indirect(reflect.ValueOf(value))
				if indirectValue.IsValid() {
					value = indirectValue.Interface()
					if t, ok := value.(time.Time); ok {
						if t.IsZero() {
							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", "0000-00-00 00:00:00"))
						} else {
							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", t.Format("2006-01-02 15:04:05")))
						}
					} else if b, ok := value.([]byte); ok {
						if str := string(b); isPrintable(str) {
							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", str))
						} else {
							formattedValues = append(formattedValues, "'<binary>'")
						}
					} else if r, ok := value.(driver.Valuer); ok {
						if value, err := r.Value(); err == nil && value != nil {
							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
						} else {
							formattedValues = append(formattedValues, "NULL")
						}
					} else {
						switch value.(type) {
						case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, bool:
							formattedValues = append(formattedValues, fmt.Sprintf("%v", value))
						default:
							formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
						}
					}
				} else {
					formattedValues = append(formattedValues, "NULL")
				}
			}

			if numericPlaceHolderRegexp.MatchString(values[3].(string)) {
				sql = values[3].(string)
				for index, value := range formattedValues {
					placeholder := fmt.Sprintf(`\$%d([^\d]|$)`, index+1)
					sql = regexp.MustCompile(placeholder).ReplaceAllString(sql, value+"$1")
				}
			} else {
				formattedValuesLength := len(formattedValues)
				for index, value := range sqlRegexp.Split(values[3].(string), -1) {
					sql += value
					if index < formattedValuesLength {
						sql += formattedValues[index]
					}
				}
			}

			messages = append(messages, sql)
			messages = append(messages, fmt.Sprintf(" \n\033[36;31m[%v]\033[0m ", strconv.FormatInt(values[5].(int64), 10)+" rows affected or returned "))
		} else {
			messages = append(messages, "\033[31;1m")
			messages = append(messages, values[2:]...)
			messages = append(messages, "\033[0m")
		}
	}

	return
}

Functions

func DBTooler

func DBTooler()

single db

func GetColParamSQL

func GetColParamSQL(model interface{}) (sql string)

get col ?

func GetColSQL

func GetColSQL(model interface{}) (sql string)

根据model中表模型的json标签获取表字段 将select* 变为对应的字段名

func GetColSQLAlias

func GetColSQLAlias(model interface{}, alias string) (sql string)

根据model中表模型的json标签获取表字段 将select* 中'*'变为对应的字段名 增加别名,表连接问题

func GetDataSQL

func GetDataSQL(gt *GT) (sql string, args []interface{})

get data sql

func GetInsertSQL

func GetInsertSQL(table string, params cmap.CMap) (sql string, args []interface{})

传入数据库表名 插入语句拼接

func GetMoreSearchSQL

func GetMoreSearchSQL(gt *GT) (sqlNt, sql string, clientPage, everyPage int64, args []interface{})

More Table params: innerTables is inner join tables, must even number params: leftTables is left join tables return: select sql table1 as main table, include other tables_id(foreign key)

func GetMoreTableColumnSQL

func GetMoreTableColumnSQL(model interface{}, tables ...string) (sql string)

select * replace select more tables tables : table name / table alias name 主表放在tables中第一个, 紧接着为主表关联的外键表名(无顺序)

func GetParams

func GetParams(data interface{}) (params []interface{})

get data value like GetColSQL

func GetReflectTag

func GetReflectTag(reflectType reflect.Type, buf *bytes.Buffer)

层级递增解析tag

func GetReflectTagAlias

func GetReflectTagAlias(ref reflect.Type, buf *bytes.Buffer, alias string)

层级递增解析tag, 别名

func GetReflectTagMore

func GetReflectTagMore(ref reflect.Type, buf *bytes.Buffer, tables ...string)

层级递增解析tag, more tables

func GetSearchSQL

func GetSearchSQL(gt *GT) (sqlNt, sql string, clientPage, everyPage int64, args []interface{})

分页参数不传, 查询所有 默认根据id倒序 单张表

func GetSelectSearchSQL

func GetSelectSearchSQL(gt *GT) (sqlNt, sql string, clientPage, everyPage int64)

select sql

func GetUpdateSQL

func GetUpdateSQL(table string, params cmap.CMap) (sql string, args []interface{})

传入数据库表名 更新语句拼接

Types

type Config

type Config struct {
	// different devMode yaml data
	YamlS map[string]*Yaml
	// contains filtered or unexported fields
}

config

func Configger

func Configger(params ...string) *Config

single config

func NewConfig

func NewConfig(params ...string) *Config

new Config load all devMode yaml data

func (*Config) Get

func (c *Config) Get(name string) interface{}

get yaml data find the first data, must different from app.yaml

func (*Config) GetBool

func (c *Config) GetBool(name string) bool

func (*Config) GetInt

func (c *Config) GetInt(name string) int

func (*Config) GetString

func (c *Config) GetString(name string) string

func (*Config) GetStruct

func (c *Config) GetStruct(name string, s interface{})

yaml to struct only support Accessible Field

type Crud

type Crud interface {

	// DB
	DB() *DBTool
	// new/replace param
	// return param
	Params(param ...Param) Crud

	// get url params
	// like form data
	GetBySearch(params cmap.CMap) Crud     // search
	GetByData(params cmap.CMap) Crud       // get data no search
	GetByID(id interface{}) Crud           // by id
	GetMoreBySearch(params cmap.CMap) Crud // more search

	// delete by id
	Delete(id interface{}) Crud // delete

	// crud and search id
	// form data
	// [create/update] future all will use json replace form request
	// form will not update
	UpdateForm(params cmap.CMap) error            // update
	CreateForm(params cmap.CMap) error            // create
	CreateResID(params cmap.CMap) (str.ID, error) // create res insert id

	// crud and search id
	// json data
	Update() Crud     // update
	Create() Crud     // create, include res insert id
	CreateMore() Crud // create more, data must array type, single table

	// select
	Select(q interface{}, args ...interface{}) Crud // select sql
	From(query string) Crud                         // from sql, if use search, From must only once
	Group(query string) Crud                        // the last group by
	Search(params cmap.CMap) Crud                   // search pager
	Single() Crud                                   // no search
	Exec() Crud                                     // exec insert/update/delete sql
	Error() error                                   // crud error
	RowsAffected() int64                            // inflect rows
	Pager() result.Pager                            // search pager
	Begin() Crud                                    // start a transaction
	Commit() Crud                                   // commit a transaction
	Rollback() Crud                                 // rollback a transaction
	// contains filtered or unexported methods
}

crud is db driver extend

func NewCrud

func NewCrud(params ...Param) Crud

new crud

type DBCrud

type DBCrud struct {
	// contains filtered or unexported fields
}

implement DBCrud form data

func (*DBCrud) Begin

func (c *DBCrud) Begin() Crud

func (*DBCrud) Commit

func (c *DBCrud) Commit() Crud

func (*DBCrud) Create

func (c *DBCrud) Create() Crud

create

func (*DBCrud) CreateForm

func (c *DBCrud) CreateForm(params cmap.CMap) error

create

func (*DBCrud) CreateMore

func (c *DBCrud) CreateMore() Crud

create more

func (*DBCrud) CreateResID

func (c *DBCrud) CreateResID(params cmap.CMap) (str.ID, error)

create res insert id

func (*DBCrud) DB

func (c *DBCrud) DB() *DBTool

func (*DBCrud) Delete

func (c *DBCrud) Delete(id interface{}) Crud

delete

func (*DBCrud) Error

func (c *DBCrud) Error() error

func (*DBCrud) Exec

func (c *DBCrud) Exec() Crud

func (*DBCrud) From

func (c *DBCrud) From(query string) Crud

func (*DBCrud) GetByData

func (c *DBCrud) GetByData(params cmap.CMap) Crud

func (*DBCrud) GetByID

func (c *DBCrud) GetByID(id interface{}) Crud

by id

func (*DBCrud) GetBySearch

func (c *DBCrud) GetBySearch(params cmap.CMap) Crud

search pager info

func (*DBCrud) GetMoreBySearch

func (c *DBCrud) GetMoreBySearch(params cmap.CMap) Crud

the same as search more tables

func (*DBCrud) Group

func (c *DBCrud) Group(query string) Crud

func (*DBCrud) Pager

func (c *DBCrud) Pager() result.Pager

func (*DBCrud) Params

func (c *DBCrud) Params(params ...Param) Crud

func (*DBCrud) Rollback

func (c *DBCrud) Rollback() Crud

func (*DBCrud) RowsAffected

func (c *DBCrud) RowsAffected() int64

func (*DBCrud) Search

func (c *DBCrud) Search(params cmap.CMap) Crud

func (*DBCrud) Select

func (c *DBCrud) Select(q interface{}, args ...interface{}) Crud

create

func (*DBCrud) Single

func (c *DBCrud) Single() Crud

func (*DBCrud) Update

func (c *DBCrud) Update() Crud

update

func (*DBCrud) UpdateForm

func (c *DBCrud) UpdateForm(params cmap.CMap) error

update

type DBTool

type DBTool struct {

	// db driver
	*gorm.DB
	// contains filtered or unexported fields
}

DB tool

func NewDBTool

func NewDBTool() *DBTool

init DBTool

func (*DBTool) CreateData

func (db *DBTool) CreateData(table string, data interface{})

create

func (*DBTool) CreateDataResID

func (db *DBTool) CreateDataResID(table string, params cmap.CMap) (id str.ID, err error)

创建数据,通用 返回id,事务,慎用 业务少可用

func (*DBTool) CreateFormData

func (db *DBTool) CreateFormData(table string, params cmap.CMap) error

via form data create

func (*DBTool) CreateMoreData

func (db *DBTool) CreateMoreData(table string, model interface{}, data interface{})

data must array type more data create single table

func (*DBTool) Delete

func (db *DBTool) Delete(table string, id interface{})

delete

func (*DBTool) ExecSQL

func (db *DBTool) ExecSQL(sql string, args ...interface{})

exec sql

func (*DBTool) GetData

func (db *DBTool) GetData(gt *GT)

获得数据, no search

func (*DBTool) GetDataByID

func (db *DBTool) GetDataByID(gt *GT, id interface{})

获得数据,根据id

func (*DBTool) GetDataByName

func (db *DBTool) GetDataByName(data interface{}, name, value string) (err error)

获得数据,根据name条件 Deprecated

func (*DBTool) GetDataBySQL

func (db *DBTool) GetDataBySQL(data interface{}, sql string, args ...interface{})

获得数据,根据sql语句,无分页

func (*DBTool) GetDataBySQLSearch

func (db *DBTool) GetDataBySQLSearch(data interface{}, sql, sqlNt string, clientPage, everyPage int64, args []interface{}, argsNt []interface{}) (pager result.Pager)

获得数据,根据sql语句,分页 args : sql参数'?' sql, sqlNt args 相同, 共用args

func (*DBTool) GetDataBySearch

func (db *DBTool) GetDataBySearch(gt *GT) (pager result.Pager)

获得数据,分页/查询

func (*DBTool) GetDataBySelectSQLSearch

func (db *DBTool) GetDataBySelectSQLSearch(gt *GT) (pager result.Pager)

select sql search

func (*DBTool) GetMoreDataBySearch

func (db *DBTool) GetMoreDataBySearch(gt *GT) (pager result.Pager)

More Table params: innerTables is inner join tables params: leftTables is left join tables return: search info table1 as main table, include other tables_id(foreign key)

func (*DBTool) NewDB

func (db *DBTool) NewDB()

new db driver

func (*DBTool) UpdateData

func (db *DBTool) UpdateData(gt *GT)

update

func (*DBTool) UpdateFormData

func (db *DBTool) UpdateFormData(table string, params cmap.CMap) (err error)

via form data update

func (*DBTool) UpdateStructData

func (db *DBTool) UpdateStructData(data interface{}) (err error)

结合struct修改

func (*DBTool) ValidateSQL

func (db *DBTool) ValidateSQL(sql string) (err error)

select检查是否存在 == nil 即存在

type GT

type GT struct {
	*Params
	// CMap
	CMaps cmap.CMap // params

	// select sql
	Select string // select sql
	From   string // only once
	Group  string // the last group
	Args   []interface{}
	ArgsNt []interface{}
	// contains filtered or unexported fields
}

GT SQL struct

type Log

type Log struct {
	*logrus.Logger
	LogWriter
}

log

func Logger

func Logger() *Log

one single log

func NewLog

func NewLog() *Log

new log

func (*Log) DefaultFileLog

func (l *Log) DefaultFileLog()

Default file log maintain 7 days data, every 24 hour split file

func (*Log) FileLog

func (l *Log) FileLog(logPath string, logFileName string, maxNum uint, rotationTime time.Duration)

new output file log

func (Log) Print

func (l Log) Print(values ...interface{})

Print format & print log

type LogWriter

type LogWriter interface {
	Println(v ...interface{})
}

LogWriter log writer interface

type Param

type Param func(*Params)

func Data

func Data(Data interface{}) Param

func Inner added in v1.8.1

func Inner(InnerTables ...string) Param

func InnerTable

func InnerTable(InnerTables []string) Param

Deprecated

func KeyModel

func KeyModel(KeyModel interface{}) Param

func Left added in v1.8.1

func Left(LeftTable ...string) Param

func LeftTable

func LeftTable(LeftTable []string) Param

Deprecated

func Model

func Model(Model interface{}) Param

func SubSQL

func SubSQL(SubSQL ...string) Param

func SubWhereSQL

func SubWhereSQL(SubWhereSQL ...string) Param

func Table

func Table(Table string) Param

type Params

type Params struct {
	// attributes
	InnerTable []string    // inner join tables
	LeftTable  []string    // left join tables
	Table      string      // table name
	Model      interface{} // table model, like User{}
	KeyModel   interface{} // key like model
	Data       interface{} // table model data, like var user User{}, it is 'user', it store real data

	// count
	SubSQL string // SubQuery SQL
	// where
	SubWhereSQL string // SubWhere SQL
}

crud params

type Yaml

type Yaml struct {
	// contains filtered or unexported fields
}

go tool yaml use go-yaml

func (*Yaml) Get

func (c *Yaml) Get(name string) interface{}

从配置文件中获取值

func (*Yaml) GetBool

func (c *Yaml) GetBool(name string) bool

bool

func (*Yaml) GetInt

func (c *Yaml) GetInt(name string) int

int

func (*Yaml) GetString

func (c *Yaml) GetString(name string) string

string

func (*Yaml) GetStruct

func (c *Yaml) GetStruct(name string, s interface{})

从配置文件中获取Struct类型的值 这里的struct是你自己定义的根据配置文件

Jump to

Keyboard shortcuts

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