device_dao.go 1.5 KB
package dao

import (
	"fmt"
	"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/transform"
)

type DeviceDao struct {
	transactionContext *pgTransaction.TransactionContext
}

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

func (d *DeviceDao) FindDeviceByDeviceCode(companyId, orgId int, deviceCode string) (*domain.Device, error) {
	tx := d.transactionContext.PgTx
	deviceModel := new(models.Device)
	query := sqlbuilder.BuildQuery(tx.Model(deviceModel), map[string]interface{}{})
	query.Where("company_id = ?", companyId)
	query.Where("org_id = ?", orgId)
	query.Where("device_code = ?", deviceCode)
	//if v, ok := queryOptions["includeDeleted"]; ok && v.(bool) {
	//	query.AllWithDeleted()
	//}
	if err := query.First(); err != nil {
		if err.Error() == "pg: no rows in result set" {
			return nil, domain.ErrorNotFound
		} else {
			return nil, err
		}
	}
	if deviceModel.DeviceId == 0 {
		return nil, nil
	} else {
		return transform.TransformToDeviceDomainModelFromPgModels(deviceModel)
	}
	return nil, nil
}