pg_role_access_dao.go 1.7 KB
package dao

import (
	"fmt"
	"github.com/go-pg/pg/v10"
	"github.com/tiptok/gocomm/common"
	"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/domain"
	"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/infrastructure/pg/transaction"
)

type RoleAccessDao struct {
	transactionContext *transaction.TransactionContext
}

func (dao *RoleAccessDao) DeleteRoleAccess(roleId int64) error {
	tx := dao.transactionContext.PgTx
	q := tx.Model(new(models.RoleAccess))
	q.Where("role_id=?", roleId)
	_, err := q.Delete()
	return err
}

func (dao *RoleAccessDao) GetRoleAccess(roleId ...int64) ([]int64, error) {
	if len(roleId) == 0 {
		return []int64{}, nil
	}
	tx := dao.transactionContext.PgDd
	q := tx.Model(new(models.RoleAccess))
	q.Column("access_id")
	if len(roleId) == 1 {
		q.Where("role_id=?", roleId[0])
	} else {
		q.Where("role_id in (?)", pg.In(roleId))
	}
	var accessIds []int64
	err := q.Distinct().Select(&accessIds)
	return accessIds, err
}

func (dao *RoleAccessDao) SaveRoleAccess(roleAccess []*domain.RoleAccess) error {
	if len(roleAccess) == 0 {
		return nil
	}
	tx := dao.transactionContext.PgTx
	var modelsRoleAccess []*models.RoleAccess
	for i := range roleAccess {
		var item *models.RoleAccess
		common.GobModelTransform(&item, roleAccess[i])
		if item == nil {
			continue
		}
		modelsRoleAccess = append(modelsRoleAccess, item)
	}
	_, err := tx.Model(&modelsRoleAccess).Insert()
	return err
}

func NewRoleAccessDao(transactionContext *transaction.TransactionContext) (*RoleAccessDao, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &RoleAccessDao{
			transactionContext: transactionContext,
		}, nil
	}
}