light

Generate Go/Golang database/sql query code, spirit from MyBatis/iBatis.

Github星跟蹤圖

light Build Status

light is a tool for generating database query code from go source file with
interface methods commented with SQLs and Variables.

Interface methods commented with SQL and variables => go generate=> Database query code implementation

light.jpg

Usage

Install light tool. Make sure $GOBIN in your $PATH environment.

`go get -u -v github.com/arstd/light`

Run light -h, check install.

# light -h
Usage of light:
  -log
    	Generated file with log

Define a interface, and comment methods with SQLs and Variables, then write a directive //go:generate light.

//go:generate light -log -timeout 30

type User interface {
    // UPDATE users
    // SET [username=?,]
    //     [phone=?,]
    //     [address=?,]
    //     [status=?,]
    //     [birthday=?,]
    //     updated=CURRENT_TIMESTAMP
    // WHERE id=?
    Update(u *model.User) (int64, error)
}

After that, run go generate ./..., code generated.

# go generate ./...
Source file    /Users/Arstd/Reposits/src/github.com/arstd/light/example/store/user.go
Generated file /Users/Arstd/Reposits/src/github.com/arstd/light/example/store/user.light.go

type UserStore struct{}

func (*UserStore) Update(u *model.User) (int64, error) {
	var buf bytes.Buffer
	var args []interface{}
	buf.WriteString(`UPDATE users SET `)
	if u.Username != "" {
		buf.WriteString(`username=?, `)
		args = append(args, u.Username)
	}
	if u.Phone != "" {
		buf.WriteString(`phone=?, `)
		args = append(args, null.String(&u.Phone))
	}
	if u.Address != nil {
		buf.WriteString(`address=?, `)
		args = append(args, u.Address)
	}
	if u.Status != 0 {
		buf.WriteString(`status=?, `)
		args = append(args, null.Uint8(&u.Status))
	}
	if u.Birthday != nil {
		buf.WriteString(`birthday=?, `)
		args = append(args, u.Birthday)
	}
	buf.WriteString(`updated=CURRENT_TIMESTAMP WHERE id=? `)
	args = append(args, null.Uint64(&u.Id))
	query := buf.String()
	log.Debug(query)
	log.Debug(args...)
	res, err := db.Exec(query, args...)
	if err != nil {
		log.Error(query)
		log.Error(args...)
		log.Error(err)
		return 0, err
	}
	return res.RowsAffected()
}

More

Complete demo in example.

Source interface: example/store/user.go

Generated code: example/store/user.light.go

主要指標

概覽
名稱與所有者omigo/light
主編程語言Go
編程語言Go (語言數: 1)
平台
許可證
所有者活动
創建於2016-04-27 06:36:06
推送於2021-02-07 03:37:03
最后一次提交2021-02-07 11:35:06
發布數4
最新版本名稱v0.1.3 (發布於 )
第一版名稱v0.1.0 (發布於 )
用户参与
星數84
關注者數8
派生數7
提交數148
已啟用問題?
問題數6
打開的問題數0
拉請求數3
打開的拉請求數0
關閉的拉請求數0
项目设置
已啟用Wiki?
已存檔?
是復刻?
已鎖定?
是鏡像?
是私有?