Create & Init Project...

This commit is contained in:
2019-04-22 18:49:16 +08:00
commit fc4fa37393
25440 changed files with 4054998 additions and 0 deletions

View File

@@ -0,0 +1,89 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"business_config_test.go",
"business_test.go",
"common_test.go",
"dao_test.go",
"direction_test.go",
"flow_resource_test.go",
"flow_test.go",
"net_test.go",
"report_test.go",
"resource_test.go",
"task_config_test.go",
"task_test.go",
"token_test.go",
"transition_test.go",
],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//app/admin/main/aegis/conf:go_default_library",
"//app/admin/main/aegis/model/business:go_default_library",
"//app/admin/main/aegis/model/common:go_default_library",
"//app/admin/main/aegis/model/net:go_default_library",
"//app/admin/main/aegis/model/resource:go_default_library",
"//app/admin/main/aegis/model/task:go_default_library",
"//library/ecode:go_default_library",
"//vendor/github.com/jinzhu/gorm:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"business.go",
"business_config.go",
"common.go",
"dao.go",
"direction.go",
"flow.go",
"flow_resource.go",
"net.go",
"report.go",
"resource.go",
"task.go",
"task_config.go",
"token.go",
"transition.go",
],
importpath = "go-common/app/admin/main/aegis/dao/gorm",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/admin/main/aegis/conf:go_default_library",
"//app/admin/main/aegis/model:go_default_library",
"//app/admin/main/aegis/model/business:go_default_library",
"//app/admin/main/aegis/model/net:go_default_library",
"//app/admin/main/aegis/model/resource:go_default_library",
"//app/admin/main/aegis/model/task:go_default_library",
"//library/database/orm:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//vendor/github.com/jinzhu/gorm:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,66 @@
package gorm
import (
"context"
"go-common/app/admin/main/aegis/model/business"
"github.com/jinzhu/gorm"
)
// AddBusiness .
func (d *Dao) AddBusiness(c context.Context, e *business.Business) (id int64, err error) {
err = d.orm.Table("business").Create(&e).Error
id = e.ID
return
}
// UpdateBusiness .
func (d *Dao) UpdateBusiness(c context.Context, e *business.Business) (err error) {
return d.orm.Table("business").Where("id = ?", e.ID).Update(map[string]interface{}{
"name": e.Name,
"desc": e.Desc,
"developer": e.Developer,
}).Error
}
// EnableBusiness .
func (d *Dao) EnableBusiness(c context.Context, id int64) (err error) {
return d.orm.Table("business").Where("id = ?", id).Update(map[string]interface{}{
"state": business.StateEnable,
}).Error
}
// DisableBusiness .
func (d *Dao) DisableBusiness(c context.Context, id int64) (err error) {
return d.orm.Table("business").Where("id = ?", id).Update(map[string]interface{}{
"state": business.StateDisable,
}).Error
}
// Business .
func (d *Dao) Business(c context.Context, id int64) (res *business.Business, err error) {
res = &business.Business{}
if err = d.orm.Where("id = ?", id).First(&res).Error; err == gorm.ErrRecordNotFound {
res = nil
err = nil
}
return
}
// BusinessList .
func (d *Dao) BusinessList(c context.Context, tp int8, ids []int64, onlyEnable bool) (res []*business.Business, err error) {
res = []*business.Business{}
db := d.orm
if len(ids) > 0 {
db = db.Where("id in (?)", ids)
}
if onlyEnable {
db = db.Where("state=?", business.StateEnable)
}
if tp > 0 {
db = db.Where("type = ?", tp)
}
err = db.Find(&res).Error
return
}

View File

@@ -0,0 +1,68 @@
package gorm
import (
"context"
"database/sql"
"go-common/app/admin/main/aegis/model/business"
"go-common/library/log"
)
// GetConfigs .
func (d *Dao) GetConfigs(c context.Context, bizid int64) (cfgs []*business.BizCFG, err error) {
if err = d.orm.Table("business_config").Where("business_id=? AND state=0", bizid).Scan(&cfgs).Error; err != nil {
log.Error("GetURL error(%v)", err)
}
return
}
// GetConfig .
func (d *Dao) GetConfig(c context.Context, bizid int64, tp int8) (config string, err error) {
if err = d.orm.Table("business_config").Select("`config`").
Where("business_id=? AND type=? AND state=0", bizid, tp).
Order("mtime DESC").Limit(1).
Row().Scan(&config); err != nil {
if err == sql.ErrNoRows {
err = nil
return
}
log.Error("GetConfig error(%v)", err)
return
}
return
}
// ActiveConfigs 所有任务配置
func (d *Dao) ActiveConfigs(c context.Context) (configs []*business.BizCFG, err error) {
configs = []*business.BizCFG{}
if err = d.orm.Where("state=0").Find(&configs).Error; err != nil {
log.Error("ActiveConfigs find error(%v)", err)
}
return
}
// AddBizConfig 每个业务每种配置只有一条
func (d *Dao) AddBizConfig(c context.Context, cfg *business.BizCFG) (lastid int64, err error) {
if err = d.orm.Table("business_config").Where("business_id=? AND `type`=?", cfg.BusinessID, cfg.TP).
Assign(map[string]interface{}{
"config": cfg.Config,
"state": cfg.State,
}).FirstOrCreate(cfg).Error; err != nil {
log.Error("AddBizConfig error(%v)", err)
}
lastid = cfg.ID
return
}
// EditBizConfig .
func (d *Dao) EditBizConfig(c context.Context, cfg *business.BizCFG) (err error) {
if err = d.orm.Table("business_config").Where("id=?", cfg.ID).
Update(map[string]interface{}{
"config": cfg.Config,
"state": cfg.State,
}).Error; err != nil {
log.Error("EditBizConfig error(%v)", err)
}
return
}

View File

@@ -0,0 +1,94 @@
package gorm
import (
"context"
"go-common/app/admin/main/aegis/model/business"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestGormGetConfigs(t *testing.T) {
convey.Convey("GetConfigs", t, func(ctx convey.C) {
var (
c = context.Background()
bizid = int64(1)
)
ctx.Convey("success", func(ctx convey.C) {
cfgs, err := d.GetConfigs(c, bizid)
ctx.Convey("Then err should be nil.cfgs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(cfgs, convey.ShouldNotBeNil)
})
})
ctx.Convey("empty", func(ctx convey.C) {
_, err := d.GetConfigs(c, -1)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestGormGetConfig(t *testing.T) {
convey.Convey("GetConfig", t, func(ctx convey.C) {
var (
c = context.Background()
bizid = int64(0)
tp = int8(-1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
config, err := d.GetConfig(c, bizid, tp)
ctx.Convey("Then err should be nil.config should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(config, convey.ShouldNotBeNil)
})
})
})
}
func TestGormActiveConfigs(t *testing.T) {
convey.Convey("ActiveConfigs", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
configs, err := d.ActiveConfigs(c)
ctx.Convey("Then err should be nil.configs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(configs, convey.ShouldNotBeNil)
})
})
})
}
func TestGormAddBizConfig(t *testing.T) {
convey.Convey("AddBizConfig", t, func(ctx convey.C) {
var (
c = context.Background()
cfg = &business.BizCFG{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
lastid, err := d.AddBizConfig(c, cfg)
ctx.Convey("Then err should be nil.lastid should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(lastid, convey.ShouldNotBeNil)
})
})
})
}
func TestGormEditBizConfig(t *testing.T) {
convey.Convey("EditBizConfig", t, func(ctx convey.C) {
var (
c = context.Background()
cfg = &business.BizCFG{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.EditBizConfig(c, cfg)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,80 @@
package gorm
import (
"context"
"testing"
"go-common/app/admin/main/aegis/model/business"
"github.com/smartystreets/goconvey/convey"
)
func TestEnableBusiness(t *testing.T) {
convey.Convey("EnableBusiness", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.EnableBusiness(c, 0)
ctx.Convey("Then err should be nil.cfgs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDisableBusiness(t *testing.T) {
convey.Convey("DisableBusiness", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DisableBusiness(c, 0)
ctx.Convey("Then err should be nil.cfgs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestBusiness(t *testing.T) {
convey.Convey("Business", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.Business(c, 0)
ctx.Convey("Then err should be nil.cfgs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestBusinessList(t *testing.T) {
convey.Convey("BusinessList", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.BusinessList(c, 1, []int64{0}, true)
ctx.Convey("Then err should be nil.cfgs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestUpdateBusiness(t *testing.T) {
convey.Convey("UpdateBusiness", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.UpdateBusiness(c, &business.Business{})
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,106 @@
package gorm
import (
"context"
"database/sql"
"fmt"
"strings"
"github.com/jinzhu/gorm"
"go-common/app/admin/main/aegis/model/net"
"go-common/library/log"
)
// Available .
func Available(db *gorm.DB) *gorm.DB {
return db.Where("disable_time = '0000-00-00 00:00:00'")
}
// Disable .
func Disable(db *gorm.DB) *gorm.DB {
return db.Not("disable_time = '0000-00-00 00:00:00'")
}
func state(state string) func(db *gorm.DB) *gorm.DB {
state = strings.TrimSpace(state)
if state == net.StateAvailable {
return func(db *gorm.DB) *gorm.DB {
return Available(db)
}
} else if state == net.StateDisable {
return func(db *gorm.DB) *gorm.DB {
return Disable(db)
}
} else {
return func(db *gorm.DB) *gorm.DB {
return db
}
}
}
func pager(ps int64, pn int64, sort string) func(db *gorm.DB) *gorm.DB {
offset := ps * (pn - 1)
order := fmt.Sprintf("id %s", sort)
return func(db *gorm.DB) *gorm.DB {
return db.Limit(ps).Offset(offset).Order(order)
}
}
// UpdateFields .
func (d *Dao) UpdateFields(c context.Context, db *gorm.DB, table string, id int64, fields map[string]interface{}) (err error) {
if db == nil {
db = d.orm
}
if err = db.Table(table).Where("id=?", id).Updates(fields).Error; err != nil {
log.Error("UpdateFlow(%s,%d) error(%v) changed(%+v)", table, id, err, fields)
}
return
}
// AddItem .
func (d *Dao) AddItem(c context.Context, db *gorm.DB, n interface{}) (err error) {
if db == nil {
db = d.orm
}
if err = db.Create(n).Error; err != nil {
log.Error("AddItem error(%v) (%+v)", err, n)
}
return
}
// ColumnMapString .
func (d *Dao) ColumnMapString(c context.Context, table string, column string, ids []int64, where string) (result map[int64]string, err error) {
var (
rows *sql.Rows
id int64
value string
slt = fmt.Sprintf("`id`,`%s`", column)
)
result = map[int64]string{}
db := d.orm.Table(table).Select(slt).Where("id in (?)", ids)
where = strings.TrimSpace(where)
if where != "" {
db = db.Where(where)
}
rows, err = db.Rows()
if err == sql.ErrNoRows {
err = nil
return
}
if err != nil {
log.Error("ColumnMapString(%s, %s) rows error(%v) ids(%v)", table, column, err, ids)
return
}
defer rows.Close()
for rows.Next() {
if err = rows.Scan(&id, &value); err != nil {
log.Error("ColumnMapString(%s, %s) rows.scan error(%v) ids(%v)", table, column, err, ids)
return
}
result[id] = value
}
return
}

View File

@@ -0,0 +1,61 @@
package gorm
import (
"testing"
"github.com/jinzhu/gorm"
"github.com/smartystreets/goconvey/convey"
"go-common/app/admin/main/aegis/model/net"
)
func TestDaoAvailable(t *testing.T) {
var (
db = &gorm.DB{}
)
convey.Convey("Available", t, func(ctx convey.C) {
p1 := Available(db)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaoDisable(t *testing.T) {
var (
db = &gorm.DB{}
)
convey.Convey("Disable", t, func(ctx convey.C) {
p1 := Disable(db)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDaostatePager(t *testing.T) {
var (
s1 = ""
)
convey.Convey("state", t, func(ctx convey.C) {
p1 := state(s1)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestDao_ColumnMapString(t *testing.T) {
var (
table = net.TableFlow
column = "ch_name"
ids = []int64{1, 2, 3}
)
convey.Convey("ColumnMapString", t, func(ctx convey.C) {
result, err := d.ColumnMapString(cntx, table, column, ids, "")
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
t.Logf("result(%+v)", result)
})
}

View File

@@ -0,0 +1,47 @@
package gorm
import (
"context"
"go-common/app/admin/main/aegis/conf"
"go-common/library/database/orm"
"go-common/library/log"
"github.com/jinzhu/gorm"
)
// Dao dao
type Dao struct {
c *conf.Config
orm *gorm.DB
}
// New init mysql orm
func New(c *conf.Config) (dao *Dao) {
dao = &Dao{
c: c,
orm: orm.NewMySQL(c.ORM),
}
dao.orm.LogMode(true)
return
}
// Close close the resource.
func (d *Dao) Close() {
d.orm.Close()
}
// BeginTx .
func (d *Dao) BeginTx(c context.Context) (tx *gorm.DB, err error) {
tx = d.orm.Begin()
if err = tx.Error; err != nil {
log.Error("orm begin tx error(%v)", err)
}
return
}
// Ping dao ping
func (d *Dao) Ping(c context.Context) error {
return d.orm.DB().PingContext(c)
}

View File

@@ -0,0 +1,50 @@
package gorm
import (
"context"
"flag"
"os"
"testing"
"go-common/app/admin/main/aegis/conf"
"github.com/smartystreets/goconvey/convey"
)
var (
d *Dao
cntx context.Context
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.aegis-admin")
flag.Set("conf_token", "cad913269be022e1eb8c45a8d5408d78")
flag.Set("tree_id", "60977")
flag.Set("conf_version", "1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../../cmd/aegis-admin.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
cntx = context.Background()
os.Exit(m.Run())
}
func TestDaoPing(t *testing.T) {
convey.Convey("Ping", t, func(ctx convey.C) {
err := d.Ping(context.TODO())
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,122 @@
package gorm
import (
"context"
"github.com/jinzhu/gorm"
"go-common/app/admin/main/aegis/model/net"
"go-common/library/ecode"
"go-common/library/log"
)
// DirectionByFlowID .
func (d *Dao) DirectionByFlowID(c context.Context, flowID []int64, direction int8) (dirs []*net.Direction, err error) {
dirs = []*net.Direction{}
db := d.orm.Where("flow_id in (?)", flowID)
if direction == net.DirInput || direction == net.DirOutput {
db = db.Where("direction=?", direction)
}
err = db.Scopes(Available).Find(&dirs).Error
if err != nil {
log.Error("DirectionByFlowID find error(%v) flowid(%v) direction(%d)", err, flowID, direction)
}
return
}
// DirectionByTransitionID .
func (d *Dao) DirectionByTransitionID(c context.Context, transitionID []int64, direction int8, onlyAvailable bool) (dirs []*net.Direction, err error) {
dirs = []*net.Direction{}
db := d.orm.Where("transition_id in (?)", transitionID)
if direction == net.DirInput || direction == net.DirOutput {
db = db.Where("direction=?", direction)
}
if onlyAvailable {
db = db.Scopes(Available)
}
err = db.Find(&dirs).Error
if err != nil {
log.Error("DirectionByTransitionID find error(%v) transitionid(%v) direction(%d)", err, transitionID, direction)
}
return
}
// DirectionByID .
func (d *Dao) DirectionByID(c context.Context, id int64) (n *net.Direction, err error) {
n = &net.Direction{}
err = d.orm.Where("id=?", id).First(n).Error
if err == gorm.ErrRecordNotFound {
err = ecode.NothingFound
return
}
if err != nil {
log.Error("DirectionByID(%+v) error(%v)", id, err)
}
return
}
func (d *Dao) Directions(c context.Context, ids []int64) (n []*net.Direction, err error) {
n = []*net.Direction{}
if err = d.orm.Where("id in (?)", ids).Find(&n).Error; err != nil {
log.Error("Directions error(%v) ids(%v)", err, ids)
}
return
}
// DirectionList .
func (d *Dao) DirectionList(c context.Context, pm *net.ListDirectionParam) (result *net.ListDirectionRes, err error) {
result = &net.ListDirectionRes{
Pager: net.Pager{
Num: pm.Pn,
Size: pm.Ps,
},
}
db := d.orm.Table(net.TableDirection).Where("net_id=?", pm.NetID)
if len(pm.ID) > 0 {
db = db.Where("id in (?)", pm.ID)
}
if pm.FlowID > 0 {
db = db.Where("flow_id=?", pm.FlowID)
}
if pm.TransitionID > 0 {
db = db.Where("transition_id=?", pm.TransitionID)
}
if pm.Direction == net.DirInput || pm.Direction == net.DirOutput {
db = db.Where("direction=?", pm.Direction)
}
err = db.Scopes(state(pm.State)).Count(&result.Pager.Total).Scopes(pager(pm.Ps, pm.Pn, pm.Sort)).Find(&result.Result).Error
if err != nil {
log.Error("DirectionList find error(%v) params(%+v)", err, pm)
}
return
}
// DirectionByUnique .
func (d *Dao) DirectionByUnique(c context.Context, netID int64, flowID int64, transitionID int64, direction int8) (t *net.Direction, err error) {
t = &net.Direction{}
err = d.orm.Where("net_id=? AND flow_id=? AND transition_id=? AND direction=?", netID, flowID, transitionID, direction).
First(t).Error
if err == gorm.ErrRecordNotFound {
err = nil
t = nil
return
}
if err != nil {
log.Error("DirectionByUnique(%d,%d,%d,%d) error(%v)", netID, flowID, transitionID, direction, err)
}
return
}
// DirectionByNet .
func (d *Dao) DirectionByNet(c context.Context, netID int64) (n []*net.Direction, err error) {
n = []*net.Direction{}
err = d.orm.Where("net_id=?", netID).Scopes(Available).Find(&n).Error
if err != nil {
log.Error("DirectionByNet(%d) error(%v)", netID, err)
}
return
}

View File

@@ -0,0 +1,89 @@
package gorm
import (
"testing"
"go-common/app/admin/main/aegis/model/net"
"go-common/library/ecode"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoDirectionByTransitionID(t *testing.T) {
convey.Convey("DirectionByTransitionID", t, func(ctx convey.C) {
_, err := d.DirectionByTransitionID(cntx, []int64{}, 1, true)
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoDirectionByID(t *testing.T) {
convey.Convey("DirectionByID", t, func(ctx convey.C) {
_, err := d.DirectionByID(cntx, -1)
ctx.Convey("Then err should be 404", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, ecode.NothingFound)
})
})
}
func TestDaoDirectionList(t *testing.T) {
var (
pm = &net.ListDirectionParam{
NetID: 1,
Ps: 20,
ID: []int64{1},
FlowID: 1,
TransitionID: 1,
Direction: 1,
}
)
convey.Convey("DirectionList", t, func(ctx convey.C) {
result, err := d.DirectionList(cntx, pm)
ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(result, convey.ShouldNotBeNil)
t.Logf("list result(%+v)", result)
for _, dir := range result.Result {
t.Logf("bylist dir(%+v)", dir)
}
})
})
}
func TestDaoDirectionByUnique(t *testing.T) {
convey.Convey("DirectionByUnique", t, func(ctx convey.C) {
_, err := d.DirectionByUnique(cntx, 0, 0, 0, 0)
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoDirectionByFlowID(t *testing.T) {
convey.Convey("DirectionByFlowID", t, func(ctx convey.C) {
_, err := d.DirectionByFlowID(cntx, []int64{}, 1)
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoDirectionByNet(t *testing.T) {
convey.Convey("DirectionByNet", t, func(ctx convey.C) {
_, err := d.DirectionByNet(cntx, 0)
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoDirections(t *testing.T) {
convey.Convey("Directions", t, func(ctx convey.C) {
_, err := d.Directions(cntx, []int64{0})
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,105 @@
package gorm
import (
"context"
"strings"
"github.com/jinzhu/gorm"
"go-common/app/admin/main/aegis/model/net"
"go-common/library/ecode"
"go-common/library/log"
)
// FlowByID .
func (d *Dao) FlowByID(c context.Context, id int64) (f *net.Flow, err error) {
f = &net.Flow{}
err = d.orm.Where("id=?", id).First(f).Error
if err == gorm.ErrRecordNotFound {
err = ecode.AegisFlowNotFound
return
}
if err != nil {
log.Error("FlowByID(%+v) error(%v)", id, err)
}
return
}
// FlowList .
func (d *Dao) FlowList(c context.Context, pm *net.ListNetElementParam) (result *net.ListFlowRes, err error) {
result = &net.ListFlowRes{
Pager: net.Pager{
Num: pm.Pn,
Size: pm.Ps,
},
}
db := d.orm.Table(net.TableFlow).Where("net_id=?", pm.NetID)
if len(pm.ID) > 0 {
db = db.Where("id in (?)", pm.ID)
}
pm.Name = strings.TrimSpace(pm.Name)
if pm.Name != "" {
db = db.Where("name=?", pm.Name)
}
err = db.Scopes(state(pm.State)).Count(&result.Pager.Total).Scopes(pager(pm.Ps, pm.Pn, pm.Sort)).Find(&result.Result).Error
if err != nil {
log.Error("FlowList find error(%v) params(%+v)", err, pm)
}
return
}
// FlowByUnique .
func (d *Dao) FlowByUnique(c context.Context, netID int64, name string) (f *net.Flow, err error) {
f = &net.Flow{}
err = d.orm.Where("net_id=? AND name=?", netID, name).First(f).Error
if err == gorm.ErrRecordNotFound {
err = nil
f = nil
return
}
if err != nil {
log.Error("FlowByUnique(%d,%s) error(%v)", netID, name, err)
}
return
}
// Flows .
func (d *Dao) Flows(c context.Context, ids []int64) (fs []*net.Flow, err error) {
fs = []*net.Flow{}
err = d.orm.Where("id in (?)", ids).Find(&fs).Error
if err != nil {
log.Error("Flows(%v) error(%v)", ids, err)
}
return
}
// FlowsByNet .
func (d *Dao) FlowsByNet(c context.Context, netID []int64) (fs []*net.Flow, err error) {
fs = []*net.Flow{}
err = d.orm.Scopes(Available).Where("net_id in (?)", netID).Order("id ASC").Find(&fs).Error
if err != nil {
log.Error("Flows(%d) error(%v)", netID, err)
}
return
}
func (d *Dao) FlowIDByNet(c context.Context, nid []int64) (res map[int64][]int64, err error) {
res = map[int64][]int64{}
listi := []struct {
ID int64 `gorm:"column:id"`
NetID int64 `gorm:"column:net_id"`
}{}
if err = d.orm.Table(net.TableFlow).Select("id,net_id").
Where("net_id in (?)", nid).Scopes(Available).Scan(&listi).Error; err != nil {
log.Error("FlowIDByNet error(%v) nid(%v)", err, nid)
return
}
for _, item := range listi {
res[item.NetID] = append(res[item.NetID], item.ID)
}
return
}

View File

@@ -0,0 +1,70 @@
package gorm
import (
"context"
"github.com/jinzhu/gorm"
"go-common/app/admin/main/aegis/model/net"
"go-common/library/log"
)
// FRByFlow .
func (d *Dao) FRByFlow(c context.Context, flowID []int64) (fr *net.FlowResource, err error) {
fr = &net.FlowResource{}
if err = d.orm.Where("flow_id in (?)", flowID).First(fr).Error; err == gorm.ErrRecordNotFound {
fr = nil
err = nil
return
}
if err != nil {
log.Error("FRByFlow error(%v) flowid(%v)", err, flowID)
}
return
}
// FRByNetRID .
func (d *Dao) FRByNetRID(c context.Context, netID []int64, rids []int64, onlyRunning bool) (frs []*net.FlowResource, err error) {
frs = []*net.FlowResource{}
db := d.orm.Where("rid in (?) AND net_id in (?)", rids, netID)
if onlyRunning {
db = db.Scopes(running)
}
if err = db.Find(&frs).Error; err != nil {
log.Error("FRByNetRID error(%v) netid(%v) rids(%v)", err, netID, rids)
}
return
}
// FRByUniques .
func (d *Dao) FRByUniques(c context.Context, rids []int64, flowID []int64, onlyRunning bool) (frs []*net.FlowResource, err error) {
frs = []*net.FlowResource{}
db := d.orm
if len(rids) > 0 {
db = db.Where("rid in (?)", rids)
}
if len(flowID) > 0 {
db = db.Where("flow_id in (?)", flowID)
}
if onlyRunning {
db = db.Scopes(running)
}
if err = db.Find(&frs).Error; err != nil {
log.Error("FRByUniques error(%v) rids(%+v) flowid(%d)", err, rids, flowID)
}
return
}
// CancelFlowResource .
func (d *Dao) CancelFlowResource(c context.Context, tx *gorm.DB, rids []int64) (err error) {
fields := map[string]interface{}{"state": net.FRStateDeleted}
if err = tx.Table(net.TableFlowResource).Where("rid in (?)", rids).Updates(fields).Error; err != nil {
log.Error("CancelFlowResource error(%v) rids(%+v)", err, rids)
}
return
}
func running(db *gorm.DB) *gorm.DB {
return db.Where("state!=?", net.FRStateDeleted)
}

View File

@@ -0,0 +1,45 @@
package gorm
import (
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoFRByFlow(t *testing.T) {
convey.Convey("FRByFlow", t, func(ctx convey.C) {
_, err := d.FRByFlow(cntx, []int64{})
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoFRByNetRID(t *testing.T) {
convey.Convey("FRByNetRID", t, func(ctx convey.C) {
_, err := d.FRByNetRID(cntx, []int64{}, []int64{}, false)
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoFRByUniques(t *testing.T) {
convey.Convey("FRByUniques", t, func(ctx convey.C) {
_, err := d.FRByUniques(cntx, []int64{1}, []int64{1}, true)
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoCancelFlowResource(t *testing.T) {
tx, _ := d.BeginTx(cntx)
defer tx.Commit()
convey.Convey("CancelFlowResource", t, func(ctx convey.C) {
err := d.CancelFlowResource(cntx, tx, []int64{})
ctx.Convey("Then err should be nil", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,73 @@
package gorm
import (
"testing"
"github.com/smartystreets/goconvey/convey"
"go-common/app/admin/main/aegis/model/net"
)
func TestDaoFlowByID(t *testing.T) {
convey.Convey("FlowByID", t, func(ctx convey.C) {
_, err := d.FlowByID(cntx, 1)
ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoFlowList(t *testing.T) {
var (
pm = &net.ListNetElementParam{
NetID: 1,
State: net.StateAvailable,
Ps: 5,
Pn: 2,
ID: []int64{1},
Name: "name",
}
)
convey.Convey("FlowList", t, func(ctx convey.C) {
result, err := d.FlowList(cntx, pm)
ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(result, convey.ShouldNotBeNil)
})
})
}
func TestDaoFlowByUnique(t *testing.T) {
convey.Convey("FlowByUnique", t, func(ctx convey.C) {
_, err := d.FlowByUnique(cntx, 0, "")
ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoFlowsByNet(t *testing.T) {
convey.Convey("FlowsByNet", t, func(ctx convey.C) {
_, err := d.FlowsByNet(cntx, []int64{})
ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoFlows(t *testing.T) {
convey.Convey("Flows", t, func(ctx convey.C) {
_, err := d.Flows(cntx, []int64{})
ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoFlowIDByNet(t *testing.T) {
convey.Convey("FlowIDByNet", t, func(ctx convey.C) {
_, err := d.FlowIDByNet(cntx, []int64{})
ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,120 @@
package gorm
import (
"context"
"time"
"go-common/app/admin/main/aegis/model/net"
"go-common/library/ecode"
"go-common/library/log"
"github.com/jinzhu/gorm"
)
// NetByID .
func (d *Dao) NetByID(c context.Context, id int64) (n *net.Net, err error) {
n = &net.Net{}
err = d.orm.Where("id=?", id).First(n).Error
if err == gorm.ErrRecordNotFound {
err = ecode.NothingFound
return
}
if err != nil {
log.Error("NetByID(%+v) error(%v)", id, err)
}
return
}
func (d *Dao) Nets(c context.Context, ids []int64) (n []*net.Net, err error) {
n = []*net.Net{}
if err = d.orm.Where("id in (?)", ids).Find(&n).Error; err != nil {
log.Error("Nets error(%v) ids(%v)", err, ids)
}
return
}
// NetByUnique .
func (d *Dao) NetByUnique(c context.Context, name string) (n *net.Net, err error) {
n = &net.Net{}
err = d.orm.Where("ch_name=?", name).First(n).Error
if err == gorm.ErrRecordNotFound {
err = nil
n = nil
return
}
if err != nil {
log.Error("NetByUnique(%+v) error(%v)", name, err)
}
return
}
// NetList .
func (d *Dao) NetList(c context.Context, pm *net.ListNetParam) (result *net.ListNetRes, err error) {
result = &net.ListNetRes{
Pager: net.Pager{
Num: pm.Pn,
Size: pm.Ps,
},
}
db := d.orm.Table(net.TableNet)
if len(pm.ID) > 0 {
db = db.Where("id in (?)", pm.ID)
}
if pm.BusinessID > 0 {
db = db.Where("business_id=?", pm.BusinessID)
}
err = db.Scopes(state(pm.State)).Count(&result.Pager.Total).Scopes(pager(pm.Ps, pm.Pn, pm.Sort)).Find(&result.Result).Error
if err != nil {
log.Error("NetList find error(%v) params(%+v)", err, pm)
}
return
}
// NetBindStartFlow .
func (d *Dao) NetBindStartFlow(c context.Context, tx *gorm.DB, id int64, flowID int64) (err error) {
if err = d.UpdateFields(c, tx, net.TableNet, id, map[string]interface{}{"start_flow_id": flowID}); err != nil {
log.Error("NetBindStartFlow d.UpdateFields error(%v) id(%d) flowid(%d)", err, id, flowID)
}
return
}
// NetIDByBusiness .
func (d *Dao) NetIDByBusiness(c context.Context, businessID []int64) (bizmap map[int64][]int64, err error) {
res := []struct {
ID int64 `gorm:"column:id"`
BusinessID int64 `gorm:"column:business_id"`
}{}
list := []*net.Net{}
bizmap = map[int64][]int64{}
if err = d.orm.Select("id, business_id").Where("business_id in (?)", businessID).
Scopes(Available).Find(&list).Scan(&res).Error; err != nil {
return
}
for _, item := range res {
bizmap[item.BusinessID] = append(bizmap[item.BusinessID], item.ID)
}
return
}
// NetsByBusiness .
func (d *Dao) NetsByBusiness(c context.Context, businessID []int64, onlyAvailable bool) (list []*net.Net, err error) {
list = []*net.Net{}
db := d.orm
if len(businessID) > 0 {
db = db.Where("business_id in (?)", businessID)
}
if onlyAvailable {
db = db.Scopes(Available)
}
if err = db.Find(&list).Error; err != nil {
log.Error("NetsByBusiness(%v) error(%v) onlyavailable(%v)", businessID, err, onlyAvailable)
}
return
}
// DisableNet .
func (d *Dao) DisableNet(c context.Context, tx *gorm.DB, id int64) (err error) {
err = d.UpdateFields(c, tx, net.TableNet, id, map[string]interface{}{"disable_time": time.Now()})
return
}

View File

@@ -0,0 +1,93 @@
package gorm
import (
"testing"
"github.com/smartystreets/goconvey/convey"
"go-common/app/admin/main/aegis/model/net"
)
func TestDaoNetByID(t *testing.T) {
convey.Convey("NetByID", t, func(ctx convey.C) {
d.NetByID(cntx, 1)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
})
})
}
func TestDao_NetList(t *testing.T) {
convey.Convey("NetList", t, func(ctx convey.C) {
pm := &net.ListNetParam{
BusinessID: 1,
//State: net.StateAvailable,
Ps: 20,
Pn: 1,
ID: []int64{1},
}
_, err := d.NetList(cntx, pm)
convey.So(err, convey.ShouldBeNil)
})
}
func TestDaoNetIDByBusiness(t *testing.T) {
convey.Convey("NetIDByBusiness", t, func(ctx convey.C) {
res, err := d.NetIDByBusiness(cntx, []int64{1, 2, 3})
t.Logf("res(%+v)", res)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoNetsByBusiness(t *testing.T) {
convey.Convey("NetsByBusiness", t, func(ctx convey.C) {
_, err := d.NetsByBusiness(cntx, []int64{1}, true)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoNets(t *testing.T) {
convey.Convey("Nets", t, func(ctx convey.C) {
_, err := d.Nets(cntx, []int64{})
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoNetByUnique(t *testing.T) {
convey.Convey("NetByUnique", t, func(ctx convey.C) {
_, err := d.NetByUnique(cntx, "")
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoNetBindStartFlow(t *testing.T) {
var (
tx, _ = d.BeginTx(cntx)
)
defer tx.Commit()
convey.Convey("NetBindStartFlow", t, func(ctx convey.C) {
err := d.NetBindStartFlow(cntx, tx, 0, 0)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoDisableNet(t *testing.T) {
var (
tx, _ = d.BeginTx(cntx)
)
defer tx.Commit()
convey.Convey("DisableNet", t, func(ctx convey.C) {
err := d.DisableNet(cntx, tx, 0)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,67 @@
package gorm
import (
"context"
"database/sql"
"go-common/app/admin/main/aegis/model"
"go-common/library/log"
)
//ReportTaskMetas 任务数据统计
func (d *Dao) ReportTaskMetas(c context.Context, bt string, et string, bizid, flowid int64, uids []int64, mnames map[int64]string, tp int8) (metas []*model.ReportMeta, missuid []int64, err error) {
db := d.orm.Table("task_report").Select("mtime,uid,type,content").Where("business_id=? AND type=?", bizid, tp)
if flowid != 0 {
db.Where("flow_id=?", flowid)
}
db = db.Where("mtime>=? AND mtime<?", bt, et)
if len(uids) > 0 {
db = db.Where("uid IN (?)", uids)
}
var rows *sql.Rows
if rows, err = db.Order("mtime asc").Rows(); err != nil {
log.Error("ReportTaskFlow error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
meta := &model.ReportMeta{}
if err = rows.Scan(&meta.Mtime, &meta.UID, &meta.Type, &meta.Content); err != nil {
return
}
if uname, ok := mnames[meta.UID]; ok {
meta.Uname = uname
} else {
missuid = append(missuid, meta.UID)
}
metas = append(metas, meta)
}
return
}
//TaskReports 任务报表记录
func (d *Dao) TaskReports(c context.Context, biz int64, flowID int64, tp []int8, statdateFrom string, statdateTo string) (res []*model.TaskReport, err error) {
res = []*model.TaskReport{}
db := d.orm
if statdateFrom != "" {
db = db.Where("stat_date>=?", statdateFrom)
}
if statdateTo != "" {
db = db.Where("stat_date <=?", statdateTo)
}
db = db.Where("business_id=?", biz)
if flowID > 0 {
db = db.Where("flow_id=?", flowID)
}
if len(tp) >= 0 {
db = db.Where("type in (?)", tp)
}
db = db.Order("stat_date desc, business_id desc, flow_id desc")
if err = db.Find(&res).Error; err != nil {
log.Error("TaskReports error(%v)", err)
}
return
}

View File

@@ -0,0 +1,40 @@
package gorm
import (
"context"
"fmt"
"testing"
"github.com/smartystreets/goconvey/convey"
"time"
)
func TestGormReportTaskFlow(t *testing.T) {
convey.Convey("ReportTaskFlow", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
metas, _, err := d.ReportTaskMetas(c, "", "", 1, 1, []int64{}, map[int64]string{}, 0)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
for _, meta := range metas {
fmt.Println("meta:", meta)
}
})
})
})
}
func TestDao_TaskReports(t *testing.T) {
time.Time{}.Unix()
t.Logf("%s", time.Duration(time.Duration(3661)*time.Second).String())
return
convey.Convey("TaskReports", t, func(ctx convey.C) {
res, err := d.TaskReports(cntx, 1, 1, []int8{2, 3, 4}, "2019-01-14", "2019-01-15")
ctx.So(err, convey.ShouldBeNil)
for _, item := range res {
t.Logf("item(%+v)", item)
}
})
}

View File

@@ -0,0 +1,304 @@
package gorm
import (
"context"
"database/sql"
"encoding/json"
"go-common/app/admin/main/aegis/model/resource"
"go-common/library/log"
"github.com/jinzhu/gorm"
"go-common/app/admin/main/aegis/model"
)
const (
_resourceResSQL = "SELECT r.id, r.business_id, r.oid, r.mid,r.content,r.extra1,r.extra2,r.extra3,r.extra4,r.extra1s,r.extra2s,r.metadata, rr.attribute, rr.note, rr.reject_reason, rr.reason_id, rr.state, rr.pubtime, rr.deltime " +
"FROM resource r LEFT JOIN resource_result rr ON r.id = rr.rid WHERE r.id = ?"
_resByOIDSQL = "SELECT r.id, r.business_id, r.oid, r.mid,r.content,r.extra1,r.extra2,r.extra3,r.extra4,r.extra1s,r.extra2s,r.metadata, rr.attribute, rr.note, rr.reject_reason, rr.reason_id, rr.state, rr.pubtime, rr.deltime " +
"FROM resource r LEFT JOIN resource_result rr ON r.id = rr.rid WHERE r.business_id = ? AND r.oid = ?"
)
var _changeableFields = map[string]struct{}{
"extra1": {},
"extra2": {},
"extra3": {},
"extra4": {},
"extra5": {},
"extra6": {},
"extra1s": {},
"extra2s": {},
"extra3s": {},
"extra4s": {},
"extratime1": {},
}
// ListHelperForTask 补充任务列表里面的oid和content
func (d *Dao) ListHelperForTask(c context.Context, rids []int64) (res map[int64][]interface{}, err error) {
var (
rows *sql.Rows
id int64
oid, content, metadata string
)
if rows, err = d.orm.Table("resource").Select("id,oid,content,metadata").Where("id IN (?)", rids).Rows(); err != nil {
log.Error("listHelperForTask err(%v)", err)
return
}
res = make(map[int64][]interface{})
defer rows.Close()
for rows.Next() {
if err = rows.Scan(&id, &oid, &content, &metadata); err != nil {
log.Error("rows.Scan error(%v)", err)
return
}
metas := make(map[string]interface{})
if len(metadata) > 0 {
if err = json.Unmarshal([]byte(metadata), &metas); err != nil {
log.Error("ListHelperForTask err(%+v)\n", err)
}
err = nil
}
res[id] = []interface{}{oid, content, metas}
}
return
}
// TxAddResource .
func (d *Dao) TxAddResource(tx *gorm.DB, r *resource.Resource, rr *resource.Result) (rid int64, err error) {
err = tx.Table("resource").Where("business_id=? AND oid=?", r.BusinessID, r.OID).
Assign(map[string]interface{}{
"oid": r.OID,
"content": r.Content,
"extra1": r.Extra1,
"extra2": r.Extra2,
"extra3": r.Extra3,
"extra4": r.Extra4,
"extra1s": r.Extra1s,
"extra2s": r.Extra2s,
"metadata": r.MetaData,
"extra5": r.Extra5,
"extra6": r.Extra6,
"extra3s": r.Extra3s,
"extra4s": r.Extra4s,
"extratime1": r.ExtraTime1,
"octime": r.OCtime,
"ptime": r.Ptime,
}).FirstOrCreate(&r).Error
if err != nil {
return
}
rid = r.ID
rr.RID = r.ID
err = tx.Table("resource_result").Where("rid=?", rr.RID).Assign(map[string]interface{}{
"attribute": rr.Attribute,
"note": rr.Note,
"reject_reason": rr.RejectReason,
"reason_id": rr.ReasonID,
"state": rr.State,
"pubtime": rr.PubTime,
"deltime": rr.DelTime,
}).FirstOrCreate(&rr).Error
return
}
// ResourceByOID .
func (d *Dao) ResourceByOID(c context.Context, OID string, bizID int64) (res *resource.Resource, err error) {
res = &resource.Resource{}
if err = d.orm.Where("oid = ? AND business_id = ?", OID, bizID).First(res).Error; err == gorm.ErrRecordNotFound {
res = nil
err = nil
}
return
}
// RidsByOids .
func (d *Dao) RidsByOids(c context.Context, bizID int64, oids []string) (rids string, err error) {
err = d.orm.Table("resource").Select("GROUP_CONCAT(id)").Where("business_id=? AND oid IN (?)", bizID, oids).Row().Scan(&rids)
return
}
// OidByRID 通过rid查到oid
func (d *Dao) OidByRID(c context.Context, rid int64) (oid string, err error) {
if err = d.orm.Table("resource").Select("oid").Where("id=?", rid).Row().Scan(&oid); err == sql.ErrNoRows {
err = nil
}
return
}
// TxUpdateResult .
func (d *Dao) TxUpdateResult(ormTx *gorm.DB, rid int64, res map[string]interface{}, rscRes *resource.Result) (err error) {
params := make(map[string]interface{})
for k, v := range res {
if k != "state" && k != "attribute" {
continue
}
params[k] = v
}
db := ormTx.Table("resource_result").
Where("rid = ?", rid)
//Update(params)
if rscRes != nil {
if rscRes.Attribute != -1 {
params["attribute"] = rscRes.Attribute
}
if rscRes.Note != "" {
params["note"] = rscRes.Note
}
if rscRes.RejectReason != "" {
params["reject_reason"] = rscRes.RejectReason
}
if rscRes.ReasonID != 0 {
params["reason_id"] = rscRes.ReasonID
}
}
return db.Update(params).Error
}
// TxUpdateResource . TODO Resource表的字段要不要直接审核提交变更 还是等待业务方同步更新?(例如单话的上线下线)
func (d *Dao) TxUpdateResource(ormTx *gorm.DB, rid int64, res map[string]interface{}) (err error) {
params := make(map[string]interface{})
for k, v := range res {
if _, ok := _changeableFields[k]; !ok {
continue
}
params[k] = v
}
return ormTx.Table("resource").Where("id = ?", rid).Update(params).Error
}
// TxUpdateState 更新状态
func (d *Dao) TxUpdateState(tx *gorm.DB, rids []int64, state int) (err error) {
return tx.Table("resource_result").Where("rid IN (?)", rids).Update("state", state).Error
}
// UpdateResource 更新资源
func (d *Dao) UpdateResource(c context.Context, bizid int64, oid string, update map[string]interface{}) (rows int64, err error) {
db := d.orm.Table("resource").Where("business_id=? AND oid=?", bizid, oid).Update(update)
return db.RowsAffected, db.Error
}
// ResourceRes .
func (d *Dao) ResourceRes(c context.Context, rid int64) (res *resource.Res, err error) {
res = &resource.Res{}
if err = d.orm.Raw(_resourceResSQL, rid).Scan(res).Error; err == gorm.ErrRecordNotFound {
res = nil
err = nil
}
return
}
// ResByOID .
func (d *Dao) ResByOID(c context.Context, bizID int64, OID string) (res *resource.Res, err error) {
res = &resource.Res{}
if err = d.orm.Raw(_resByOIDSQL, bizID, OID).Scan(res).Error; err == gorm.ErrRecordNotFound {
res = nil
err = nil
}
return
}
//ResOIDByID 根据id获取资源oid
func (d *Dao) ResOIDByID(c context.Context, rids []int64) (res map[int64]string, err error) {
list := []struct {
ID int64 `gorm:"column:id"`
OID string `gorm:"column:oid"`
}{}
res = map[int64]string{}
if err = d.orm.Table("resource").Select("id,oid").Where("id in (?)", rids).Find(&list).Error; err != nil {
log.Error("ResOIDByID error(%v) rids(%v)", err, rids)
return
}
for _, item := range list {
res[item.ID] = item.OID
}
return
}
//ResIDByOID 根据oid获取rid
func (d *Dao) ResIDByOID(C context.Context, bizID int64, oids []string) (res map[string]int64, err error) {
list := []struct {
ID int64 `gorm:"column:id"`
OID string `gorm:"column:oid"`
}{}
res = map[string]int64{}
if err = d.orm.Table("resource").Select("id,oid").Where("business_id=? and oid in (?)", bizID, oids).Find(&list).Error; err != nil {
log.Error("ResIDByOID error(%v) oids(%v)", err, oids)
return
}
for _, item := range list {
res[item.OID] = item.ID
}
return
}
//ResourceHit 根据状态筛选资源
func (d *Dao) ResourceHit(c context.Context, rids []int64) (hitids map[int64]int64, err error) {
hitids = make(map[int64]int64)
rows, err := d.orm.Table("resource_result").Select("rid,state").Where("rid IN (?)", rids).Rows()
if err != nil {
log.Error("ResourceHitState error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
var rid, state int64
if err = rows.Scan(&rid, &state); err != nil {
log.Error("ResourceHitState error(%v)", err)
}
hitids[rid] = state
}
return
}
//ResultByRID result by rid
func (d *Dao) ResultByRID(c context.Context, rid int64) (res *resource.Result, err error) {
res = &resource.Result{}
if err = d.orm.Where("rid=?", rid).First(&res).Error; err == gorm.ErrRecordNotFound {
log.Error("ResultByRID rid(%d) error(%v)", rid, err)
}
return
}
//MetaByRID .
func (d *Dao) MetaByRID(c context.Context, rids []int64) (metas map[int64]string, err error) {
var rows *sql.Rows
metas = make(map[int64]string)
rows, err = d.orm.Table("resource").Select("id,metadata").Where("id IN (?)", rids).Rows()
if err != nil {
log.Error("MetaByRID Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
var (
id int64
meta string
)
if err = rows.Scan(&id, &meta); err != nil {
log.Error("MetaByRID rows.Scan error(%v)", err)
return
}
metas[id] = meta
}
return
}
//UpsertByOIDs 获取需要更新到搜索部分
func (d *Dao) UpsertByOIDs(c context.Context, businessID int64, oids []string) (res []*model.UpsertItem, err error) {
res = []*model.UpsertItem{}
sqlstr := `SELECT r.id,r.extra1,r.extra2,r.extra3,r.extra4,rr.state
FROM resource r
LEFT JOIN resource_result rr ON r.id=rr.rid
WHERE r.business_id=? AND r.oid IN (?)`
if err = d.orm.Raw(sqlstr, businessID, oids).Find(&res).Error; err != nil {
log.Error("UpsertByOIDs error(%+v) businessid(%d) oids(%+v)", err, businessID, oids)
}
return
}

View File

@@ -0,0 +1,220 @@
package gorm
import (
"context"
"testing"
"go-common/app/admin/main/aegis/model/resource"
"github.com/smartystreets/goconvey/convey"
)
func TestGormListHelperForTask(t *testing.T) {
convey.Convey("ListHelperForTask", t, func(ctx convey.C) {
var (
c = context.Background()
rids = []int64{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.ListHelperForTask(c, rids)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestGormResourceByOID(t *testing.T) {
var (
c = context.Background()
)
convey.Convey("ResourceByOID", t, func(ctx convey.C) {
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.ResourceByOID(c, "", 0)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestGormOidByRID(t *testing.T) {
var (
c = context.Background()
)
convey.Convey("OidByRID", t, func(ctx convey.C) {
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.OidByRID(c, 0)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestGormTxUpdateResult(t *testing.T) {
convey.Convey("TxUpdateResult", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTx(context.TODO())
rid = int64(0)
res = map[string]interface{}{"extra1": 1}
rscRes = &resource.Result{}
)
defer tx.Commit()
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.TxUpdateResult(tx, rid, res, rscRes)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestGormResourceRes(t *testing.T) {
convey.Convey("ResourceRes", t, func(ctx convey.C) {
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.ResourceRes(context.TODO(), 0)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestGormResByOID(t *testing.T) {
convey.Convey("ResByOID", t, func(ctx convey.C) {
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.ResByOID(context.TODO(), 0, "")
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestGormUpdateResource(t *testing.T) {
convey.Convey("UpdateResource", t, func(ctx convey.C) {
ctx.Convey("When everything gose positive", func(ctx convey.C) {
d.UpdateResource(context.TODO(), 1, "xyz", map[string]interface{}{"mid": 123})
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
})
})
})
}
func TestGormResOIDByID(t *testing.T) {
convey.Convey("ResOIDByID", t, func(ctx convey.C) {
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.ResOIDByID(context.TODO(), []int64{1, 2})
t.Logf("res(%+v)", res)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
convey.So(err, convey.ShouldBeNil)
})
})
})
}
func TestGormResIDByOID(t *testing.T) {
convey.Convey("ResIDByOID", t, func(ctx convey.C) {
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.ResIDByOID(context.TODO(), 1, []string{"1", "2"})
t.Logf("res(%+v)", res)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
convey.So(err, convey.ShouldBeNil)
})
})
})
}
func TestGormResourceHit(t *testing.T) {
convey.Convey("ResourceHit", t, func(ctx convey.C) {
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.ResourceHit(context.TODO(), []int64{})
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
convey.So(err, convey.ShouldBeNil)
})
})
})
}
func TestGormResultByRID(t *testing.T) {
convey.Convey("ResultByRID", t, func(ctx convey.C) {
ctx.Convey("When everything gose positive", func(ctx convey.C) {
d.ResultByRID(context.TODO(), 50)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
})
})
})
}
func TestGormRidsByOids(t *testing.T) {
convey.Convey("RidsByOids", t, func(ctx convey.C) {
ctx.Convey("When everything gose positive", func(ctx convey.C) {
d.RidsByOids(cntx, 0, []string{})
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
})
})
})
}
func TestGormTxUpdateResource(t *testing.T) {
convey.Convey("TxUpdateResource", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTx(context.TODO())
rid = int64(0)
res = map[string]interface{}{"extra1": 1}
)
defer tx.Commit()
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.TxUpdateResource(tx, rid, res)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestGormTxUpdateState(t *testing.T) {
convey.Convey("TxUpdateState", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTx(context.TODO())
rids = []int64{0}
)
defer tx.Commit()
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.TxUpdateState(tx, rids, 0)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestGormMetaByRID(t *testing.T) {
convey.Convey("MetaByRID", t, func(ctx convey.C) {
var (
rids = []int64{0}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.MetaByRID(cntx, rids)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestGormUpsertByOIDs(t *testing.T) {
convey.Convey("UpsertByOIDs", t, func(ctx convey.C) {
ctx.Convey("When everything gose positive", func(ctx convey.C) {
res, err := d.UpsertByOIDs(context.TODO(), 1, []string{"oid000001", "oid000002"})
for _, item := range res {
t.Logf("res(%+v)", item)
}
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,146 @@
package gorm
import (
"context"
"database/sql"
"go-common/app/admin/main/aegis/model/task"
"go-common/library/log"
"github.com/jinzhu/gorm"
)
const (
_submitSQL = "UPDATE task SET state=?,uid=?,utime=? WHERE id=? AND state=? AND uid=?"
)
// TxSubmit 提交任务
func (d *Dao) TxSubmit(tx *gorm.DB, opt *task.SubmitOptions, state int8) (rows int64, err error) {
rows = tx.Exec(_submitSQL, state, opt.UID, opt.Utime, opt.TaskID, opt.OldState, opt.OldUID).RowsAffected
return
}
// TxCloseTasks close
func (d *Dao) TxCloseTasks(tx *gorm.DB, rids []int64, uid int64) (err error) {
err = tx.Table("task").Where("rid IN (?) AND state<?", rids, task.TaskStateSubmit).Update("state", task.TaskStateClosed).Update("uid", uid).Error
return
}
// CloseTask .
func (d *Dao) CloseTask(c context.Context, id int64) (err error) {
return d.orm.Table("task").Where("id=?", id).Update("state", task.TaskStateClosed).Update("uid", 399).Error
}
// TaskByRID task by rid
func (d *Dao) TaskByRID(c context.Context, rid, flowid int64) (t *task.Task, err error) {
db := d.orm.Model(&task.Task{}).Where("rid = ? AND state<?", rid, task.TaskStateSubmit)
if flowid > 0 {
db = db.Where("flow_id=?", flowid)
}
t = &task.Task{}
if err = db.Find(t).Error; err == gorm.ErrRecordNotFound {
err = nil
t = nil
}
return
}
// MaxWeight max weight
func (d *Dao) MaxWeight(c context.Context, bizID, flowID int64) (max int64, err error) {
if err = d.orm.Table("task").Select("max(weight)").Where("business_id = ? AND flow_id = ?", bizID, flowID).
Where("state = ? OR state = ?", task.TaskStateInit, task.TaskStateDispatch).Row().Scan(&max); err != nil {
max = 0
err = nil
}
return
}
// UndoStat 未完成
func (d *Dao) UndoStat(c context.Context, bizID, flowID, UID int64) (stat *task.UnDOStat, err error) {
stat = &task.UnDOStat{}
err = d.orm.Raw(`SELECT COUNT(CASE WHEN admin_id>0 AND state = 0 THEN 1 ELSE NULL END) assign,
COUNT(CASE WHEN admin_id = 0 AND state = 2 THEN 1 ELSE NULL END) delay,
COUNT(CASE WHEN admin_id = 0 AND state = 1 THEN 1 ELSE NULL END) normal
FROM task WHERE business_id=? AND flow_id=? AND uid=?`, bizID, flowID, UID).Scan(stat).Error
return
}
// TaskStat 任务详情统计
func (d *Dao) TaskStat(c context.Context, bizID, flowID, UID int64) (stat *task.Stat, err error) {
stat = &task.Stat{}
err = d.orm.Raw(`SELECT COUNT(CASE WHEN admin_id=0 AND state = 0 THEN 1 ELSE NULL END) normal,
COUNT(CASE WHEN admin_id>0 AND state = 0 THEN 1 ELSE NULL END) assign,
COUNT(CASE WHEN state=2 THEN 1 ELSE NULL END) delayTotal,
COUNT(CASE WHEN uid=? AND state=2 THEN 1 ELSE NULL END) delayPersonal
FROM task WHERE business_id=? AND flow_id=?`, UID, bizID, flowID).Scan(stat).Error
return
}
// TaskListSeized 停滞任务
func (d *Dao) TaskListSeized(c context.Context, opt *task.ListOptions) (ids []int64, count int64, err error) {
return d.tasklist(c, "seized", opt.BusinessID, opt.FlowID, opt.UID, opt.Pn, opt.Ps)
}
// TaskListDelayd 延迟任务
func (d *Dao) TaskListDelayd(c context.Context, opt *task.ListOptions) (ids []int64, count int64, err error) {
return d.tasklist(c, "delayd", opt.BusinessID, opt.FlowID, opt.UID, opt.Pn, opt.Ps)
}
// TaskListAssignd 指派停滞任务
func (d *Dao) TaskListAssignd(c context.Context, opt *task.ListOptions) (ids []int64, count int64, err error) {
return d.tasklist(c, "assignd", opt.BusinessID, opt.FlowID, opt.UID, opt.Pn, opt.Ps)
}
func (d *Dao) tasklist(c context.Context, ltp string, bizID, flowID, UID int64, pn, ps int) (ids []int64, count int64, err error) {
db := d.orm.Table("task").Where("business_id=? AND flow_id=?", bizID, flowID)
switch ltp {
case "seized":
db = db.Where("state=?", task.TaskStateDispatch)
case "delayd":
db = db.Where("state=?", task.TaskStateDelay)
case "assignd":
db = db.Where("state=? AND admin_id>0", task.TaskStateDispatch)
}
if UID > 0 {
db = db.Where("uid=?", UID)
}
var rows *sql.Rows
rows, err = db.Count(&count).Select("id").Order("weight DESC").Offset((pn - 1) * ps).Limit(ps).Rows()
if err != nil {
log.Error("tasklist error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
var id int64
if err = rows.Scan(&id); err != nil {
log.Error("tasklist error(%v)", err)
return
}
ids = append(ids, id)
}
return
}
//TaskHitAuditing 检查资源是否正在审核
func (d *Dao) TaskHitAuditing(c context.Context, rids []int64) (map[int64]struct{}, error) {
hitids := make(map[int64]struct{})
rows, err := d.orm.Table("task").Select("rid").Where("rid IN (?)", rids).
Where("state = ? AND gtime!=0", task.TaskStateDispatch).Rows()
if err != nil {
return hitids, err
}
defer rows.Close()
for rows.Next() {
var id int64
if err = rows.Scan(&id); err != nil {
return hitids, err
}
hitids[id] = struct{}{}
}
return hitids, err
}

View File

@@ -0,0 +1,64 @@
package gorm
import (
"context"
taskmod "go-common/app/admin/main/aegis/model/task"
"go-common/library/log"
)
// AddConfig add config
func (d *Dao) AddConfig(c context.Context, config *taskmod.Config, confJSON interface{}) (err error) {
if config.ConfType == taskmod.TaskConfigRangeWeight { //粉丝数,等待时长,分组权重配置去重
name := "%" + confJSON.(*taskmod.RangeWeightConfig).Name + "%"
err = d.orm.Table("task_config").Where("business_id=? AND flow_id=? AND conf_type=? AND conf_json LIKE ?", config.BusinessID, config.FlowID, taskmod.TaskConfigRangeWeight, name).
Assign(map[string]interface{}{
"conf_json": config.ConfJSON,
"btime": config.Btime,
"etime": config.Etime,
"uid": config.UID,
"uname": config.Uname,
"description": config.Description,
}).FirstOrCreate(config).Error
return err
}
return d.orm.Create(config).Error
}
// UpdateConfig update config
func (d *Dao) UpdateConfig(c context.Context, config *taskmod.Config) (err error) {
return d.orm.Model(&taskmod.Config{}).Where("id=?", config.ID).Update(config).Error
}
// SetStateConfig update config
func (d *Dao) SetStateConfig(c context.Context, id int64, state int8) (err error) {
return d.orm.Model(&taskmod.Config{}).Where("id=?", id).Update("state", state).Error
}
// QueryConfigs list config
func (d *Dao) QueryConfigs(c context.Context, queryParams *taskmod.QueryParams) (configs []*taskmod.Config, count int64, err error) {
db := d.orm.Model(&taskmod.Config{}).Where("conf_type=?", queryParams.ConfType).Where("state=?", queryParams.State)
if queryParams.BusinessID > 0 {
db = db.Where("business_id=?", queryParams.BusinessID)
}
if queryParams.FlowID > 0 {
db = db.Where("flow_id=?", queryParams.FlowID)
}
if len(queryParams.Btime) > 0 && len(queryParams.Etime) > 0 {
db = db.Where("mtime>=? AND mtime<=?", queryParams.Btime, queryParams.Etime)
}
if len(queryParams.ConfName) > 0 {
db = db.Where("conf_json LIKE '%" + queryParams.ConfName + "%'")
}
if err = db.Count(&count).Offset((queryParams.Pn - 1) * queryParams.Ps).Order("mtime DESC").Limit(queryParams.Ps).Find(&configs).Error; err != nil {
log.Error("query error(%v)", err)
return
}
return
}
// DeleteConfig delete config
func (d *Dao) DeleteConfig(c context.Context, id int64) (err error) {
return d.orm.Where("id=?", id).Delete(&taskmod.Config{}).Error
}

View File

@@ -0,0 +1,73 @@
package gorm
import (
"context"
"testing"
"go-common/app/admin/main/aegis/model/task"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoQueryConfigs(t *testing.T) {
convey.Convey("QueryConfigs", t, func(ctx convey.C) {
var (
c = context.Background()
params = &task.QueryParams{
BusinessID: 1,
FlowID: 1,
Btime: "0000-00-00 00:00:00",
Etime: "2018-12-12 12:12:12",
ConfName: "mid",
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, _, err := d.QueryConfigs(c, params)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDeleteConfig(t *testing.T) {
convey.Convey("DeleteConfig", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DeleteConfig(c, 0)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetStateConfig(t *testing.T) {
convey.Convey("SetStateConfig", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetStateConfig(c, 0, 0)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoUpdateConfig(t *testing.T) {
convey.Convey("UpdateConfig", t, func(ctx convey.C) {
var (
config = &task.Config{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.UpdateConfig(cntx, config)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,155 @@
package gorm
import (
"context"
"testing"
"go-common/app/admin/main/aegis/model/common"
taskmod "go-common/app/admin/main/aegis/model/task"
"github.com/smartystreets/goconvey/convey"
)
func TestUndoStat(t *testing.T) {
convey.Convey("UndoStat", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.UndoStat(c, 0, 0, 0)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestTaskStat(t *testing.T) {
convey.Convey("TaskStat", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.TaskStat(c, 0, 0, 0)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestTaskMaxWeight(t *testing.T) {
convey.Convey("MaxWeight", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.MaxWeight(c, 0, 0)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestTaskListSeized(t *testing.T) {
convey.Convey("TaskListSeized", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, _, err := d.TaskListSeized(c, &taskmod.ListOptions{})
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestTxCloseTasks(t *testing.T) {
convey.Convey("TxCloseTasks", t, func(ctx convey.C) {
var (
c = context.Background()
tx, _ = d.BeginTx(c)
)
defer tx.Commit()
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.TxCloseTasks(tx, []int64{}, 0)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestTxSubmit(t *testing.T) {
convey.Convey("TxSubmit", t, func(ctx convey.C) {
var (
tx, _ = d.BeginTx(cntx)
opt = &taskmod.SubmitOptions{}
)
defer tx.Commit()
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.TxSubmit(tx, opt, 0)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestCloseTask(t *testing.T) {
convey.Convey("CloseTask", t, func(ctx convey.C) {
ctx.Convey("When everything gose positive", func(ctx convey.C) {
err := d.CloseTask(cntx, 0)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestTaskByRID(t *testing.T) {
convey.Convey("TaskByRID", t, func(ctx convey.C) {
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, err := d.TaskByRID(cntx, 0, 1)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestTaskListAssignd(t *testing.T) {
convey.Convey("TaskListAssignd", t, func(ctx convey.C) {
var (
opt = &taskmod.ListOptions{}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, _, err := d.TaskListAssignd(cntx, opt)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestTaskListDelayd(t *testing.T) {
convey.Convey("TaskListDelayd", t, func(ctx convey.C) {
var (
opt = &taskmod.ListOptions{
BaseOptions: common.BaseOptions{
UID: 1,
},
}
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
_, _, err := d.TaskListDelayd(cntx, opt)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,126 @@
package gorm
import (
"context"
"strings"
"github.com/jinzhu/gorm"
"go-common/app/admin/main/aegis/model/net"
"go-common/library/ecode"
"go-common/library/log"
)
// TokenByID .
func (d *Dao) TokenByID(c context.Context, id int64) (t *net.Token, err error) {
t = &net.Token{}
err = d.orm.Where("id=?", id).First(t).Error
if err == gorm.ErrRecordNotFound {
err = ecode.AegisTokenNotFound
return
}
if err != nil {
log.Error("TokenByID(%+v) error(%v)", id, err)
}
return
}
// Tokens .
func (d *Dao) Tokens(c context.Context, ids []int64) (list []*net.Token, err error) {
list = []*net.Token{}
err = d.orm.Where("id in (?)", ids).Find(&list).Error
if err != nil {
log.Error("Tokens(%v) error(%v)", ids, err)
}
return
}
func (d *Dao) tokenListDB(netID []int64, id []int64, name string, onlyAssign bool) (db *gorm.DB) {
db = d.orm.Table(net.TableToken).Where("net_id in (?)", netID)
if len(id) > 0 {
db = db.Where("id in (?)", id)
}
name = strings.TrimSpace(name)
if name != "" {
db = db.Where("name=?", name)
}
if onlyAssign {
db = db.Where("compare=?", net.TokenCompareAssign)
}
return
}
// TokenListWithPager .
func (d *Dao) TokenListWithPager(c context.Context, pm *net.ListTokenParam) (result *net.ListTokenRes, err error) {
result = &net.ListTokenRes{
Pager: net.Pager{
Num: pm.Pn,
Size: pm.Ps,
},
}
db := d.tokenListDB([]int64{pm.NetID}, pm.ID, pm.Name, pm.Assign)
err = db.Count(&result.Pager.Total).Scopes(pager(pm.Ps, pm.Pn, pm.Sort)).Find(&result.Result).Error
if err != nil {
log.Error("TokenListWithPager find error(%v) params(%+v)", err, pm)
}
return
}
// TokenList .
func (d *Dao) TokenList(c context.Context, netID []int64, id []int64, name string, onlyAssign bool) (list []*net.Token, err error) {
err = d.tokenListDB(netID, id, name, onlyAssign).Find(&list).Error
if err != nil {
log.Error("TokenList find error(%v)", err)
}
return
}
// TokenByUnique .
func (d *Dao) TokenByUnique(c context.Context, netID int64, name string, compare int8, value string) (t *net.Token, err error) {
t = &net.Token{}
err = d.orm.Where("net_id=? AND name=? AND compare=? AND value=?", netID, name, compare, value).First(t).Error
if err == gorm.ErrRecordNotFound {
err = nil
t = nil
return
}
if err != nil {
log.Error("TokenByUnique(%d,%s,%d,%s) error(%v)", netID, name, compare, value, err)
}
return
}
// TokenBinds .
func (d *Dao) TokenBinds(c context.Context, id []int64) (t []*net.TokenBind, err error) {
t = []*net.TokenBind{}
err = d.orm.Where("id in (?)", id).Find(&t).Error
if err != nil {
log.Error("TokenBinds(%+v) error(%v)", id, err)
}
return
}
// TokenBindByElement .
func (d *Dao) TokenBindByElement(c context.Context, elementID []int64, tp []int8, onlyAvailable bool) (binds map[int64][]*net.TokenBind, err error) {
binds = map[int64][]*net.TokenBind{}
list := []*net.TokenBind{}
db := d.orm.Where("element_id in (?) AND type in (?)", elementID, tp)
if onlyAvailable {
db = db.Scopes(Available)
}
if err = db.Find(&list).Error; err != nil {
log.Error("TokenBindByElement error(%v) elementid(%d) type(%v) onlyavailable(%v)", err, elementID, tp, onlyAvailable)
return
}
for _, item := range list {
if _, exist := binds[item.ElementID]; !exist {
binds[item.ElementID] = []*net.TokenBind{item}
continue
}
binds[item.ElementID] = append(binds[item.ElementID], item)
}
return
}

View File

@@ -0,0 +1,81 @@
package gorm
import (
"go-common/app/admin/main/aegis/model/net"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoTokens(t *testing.T) {
var (
ids = []int64{}
)
convey.Convey("Tokens", t, func(ctx convey.C) {
no, err := d.Tokens(cntx, ids)
ctx.Convey("Then err should be nil.no should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(no, convey.ShouldNotBeNil)
})
})
}
func TestDaoTokenList(t *testing.T) {
convey.Convey("TokenList", t, func(ctx convey.C) {
result, err := d.TokenList(cntx, []int64{1}, []int64{}, "1", true)
ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(result, convey.ShouldNotBeNil)
})
})
}
func TestDaoTokenByID(t *testing.T) {
convey.Convey("TokenByID", t, func(ctx convey.C) {
d.TokenByID(cntx, 1)
ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
})
})
}
func TestDaoTokenListWithPager(t *testing.T) {
var (
pm = &net.ListTokenParam{}
)
convey.Convey("TokenListWithPager", t, func(ctx convey.C) {
result, err := d.TokenListWithPager(cntx, pm)
ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(result, convey.ShouldNotBeNil)
})
})
}
func TestDaoTokenByUnique(t *testing.T) {
convey.Convey("TokenByUnique", t, func(ctx convey.C) {
_, err := d.TokenByUnique(cntx, 0, "", 0, "")
ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoTokenBinds(t *testing.T) {
convey.Convey("TokenBinds", t, func(ctx convey.C) {
result, err := d.TokenBinds(cntx, []int64{})
ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(result, convey.ShouldNotBeNil)
})
})
}
func TestDaoTokenBindByElement(t *testing.T) {
convey.Convey("TokenBindByElement", t, func(ctx convey.C) {
result, err := d.TokenBindByElement(cntx, []int64{}, []int8{}, true)
ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(result, convey.ShouldNotBeNil)
})
})
}

View File

@@ -0,0 +1,118 @@
package gorm
import (
"context"
"strings"
"github.com/jinzhu/gorm"
"go-common/app/admin/main/aegis/model/net"
"go-common/library/ecode"
"go-common/library/log"
)
// TransitionByID .
func (d *Dao) TransitionByID(c context.Context, id int64) (n *net.Transition, err error) {
n = &net.Transition{}
err = d.orm.Where("id=?", id).First(n).Error
if err == gorm.ErrRecordNotFound {
err = ecode.AegisTranNotFound
return
}
if err != nil {
log.Error("TransitionByID(%d) error(%v)", id, err)
}
return
}
// Transitions .
func (d *Dao) Transitions(c context.Context, id []int64) (n []*net.Transition, err error) {
n = []*net.Transition{}
err = d.orm.Where("id in (?)", id).Find(&n).Error
if err != nil {
log.Error("Transitions(%v) error(%v)", id, err)
}
return
}
// TransitionList .
func (d *Dao) TransitionList(c context.Context, pm *net.ListNetElementParam) (result *net.ListTransitionRes, err error) {
result = &net.ListTransitionRes{
Pager: net.Pager{
Num: pm.Pn,
Size: pm.Ps,
},
}
db := d.orm.Table(net.TableTransition).Where("net_id=?", pm.NetID)
if len(pm.ID) > 0 {
db = db.Where("id in (?)", pm.ID)
}
pm.Name = strings.TrimSpace(pm.Name)
if pm.Name != "" {
db = db.Where("name=?", pm.Name)
}
err = db.Scopes(state(pm.State)).Count(&result.Pager.Total).Scopes(pager(pm.Ps, pm.Pn, pm.Sort)).Find(&result.Result).Error
if err != nil {
log.Error("TransitionList find error(%v) params(%+v)", err, pm)
}
return
}
// TransitionByUnique .
func (d *Dao) TransitionByUnique(c context.Context, netID int64, name string) (t *net.Transition, err error) {
t = &net.Transition{}
err = d.orm.Where("net_id=? AND name=?", netID, name).First(t).Error
if err == gorm.ErrRecordNotFound {
err = nil
t = nil
return
}
if err != nil {
log.Error("TransitionByUnique(%d,%s) error(%v)", netID, name, err)
}
return
}
// TransitionIDByNet .
func (d *Dao) TransitionIDByNet(c context.Context, netID []int64, onlyDispatch bool, onlyAvailable bool) (ids map[int64][]int64, err error) {
ids = map[int64][]int64{}
listi := []struct {
ID int64 `gorm:"column:id"`
NetID int64 `gorm:"column:net_id"`
}{}
db := d.orm.Table(net.TableTransition).Where("net_id in (?)", netID)
if onlyAvailable {
db = db.Scopes(Available)
}
if onlyDispatch {
db = db.Where("`limit`>0").Scopes(manual)
}
if err = db.Find(&listi).Error; err != nil {
log.Error("TransitionIDByNet netid(%v) error(%v)", netID, err)
return
}
for _, item := range listi {
ids[item.NetID] = append(ids[item.NetID], item.ID)
}
return
}
func manual(db *gorm.DB) *gorm.DB {
return db.Where("`trigger`=?", net.TriggerManual)
}
// TranByNet .
func (d *Dao) TranByNet(c context.Context, netID int64, onlyAvailable bool) (list []*net.Transition, err error) {
list = []*net.Transition{}
db := d.orm
if netID > 0 {
db = db.Where("net_id=?", netID)
}
if onlyAvailable {
db = db.Scopes(Available)
}
if err = db.Find(&list).Error; err != nil {
log.Error("TranByNet error(%v)", err)
}
return
}

View File

@@ -0,0 +1,83 @@
package gorm
import (
"go-common/app/admin/main/aegis/model/net"
"testing"
"github.com/smartystreets/goconvey/convey"
)
var tt = &net.Transition{
ID: 1,
NetID: 1,
Trigger: net.TriggerManual,
Name: "first",
ChName: "第一次审核",
Description: "新建变迁",
UID: 421,
}
func TestDaoTransitionByID(t *testing.T) {
convey.Convey("TransitionByID", t, func(ctx convey.C) {
n, err := d.TransitionByID(cntx, tt.ID)
ctx.Convey("Then err should be nil.n should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(n, convey.ShouldNotBeNil)
})
})
}
func TestDaoTransitionList(t *testing.T) {
var (
pm = &net.ListNetElementParam{
NetID: 1,
Ps: 20,
ID: []int64{1},
Name: "1",
}
)
convey.Convey("TransitionList", t, func(ctx convey.C) {
result, err := d.TransitionList(cntx, pm)
ctx.Convey("Then err should be nil.result should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(result, convey.ShouldNotBeNil)
})
})
}
func TestDaoTransitions(t *testing.T) {
convey.Convey("TransitionList", t, func(ctx convey.C) {
_, err := d.Transitions(cntx, []int64{})
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoTransitionByUnique(t *testing.T) {
convey.Convey("TransitionByUnique", t, func(ctx convey.C) {
_, err := d.TransitionByUnique(cntx, 0, "")
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoTransitionIDByNet(t *testing.T) {
convey.Convey("TransitionIDByNet", t, func(ctx convey.C) {
a, err := d.TransitionIDByNet(cntx, []int64{1}, true, true)
t.Logf("a(%+v)", a)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoTranByNet(t *testing.T) {
convey.Convey("TranByNet", t, func(ctx convey.C) {
_, err := d.TranByNet(cntx, 0, true)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}