pg_device_repository.go 6.2 KB
package repository

import (
	"fmt"
	"github.com/go-pg/pg/v10"
	"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"

	"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"github.com/linmadan/egglib-go/utils/snowflake"
)

type DeviceRepository struct {
	transactionContext *pgTransaction.TransactionContext
}

func (repository *DeviceRepository) nextIdentify() (int64, error) {
	IdWorker, err := snowflake.NewIdWorker(1)
	if err != nil {
		return 0, err
	}
	id, err := IdWorker.NextId()
	return id, err
}
func (repository *DeviceRepository) Save(device *domain.Device) (*domain.Device, error) {
	sqlBuildFields := []string{
		"device_id",
		"company_id",
		"org_id",
		"device_code",
		"device_name",
		"device_model",
		"device_type",
		"brand",
		"device_status",
		"risk_level",
		"created_at",
		"updated_at",
		"deleted_at",
		"work_station",
		"ext",
	}
	insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "device_id", "deleted_at"))
	insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "device_id", "deleted_at"))
	returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
	updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "device_id", "deleted_at")
	updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
	tx := repository.transactionContext.PgTx
	if device.Identify() == nil {
		if _, err := tx.QueryOne(
			pg.Scan(
				&device.DeviceId,
				&device.CompanyId,
				&device.OrgId,
				&device.DeviceCode,
				&device.DeviceName,
				&device.DeviceModel,
				&device.DeviceType,
				&device.Brand,
				&device.DeviceStatus,
				&device.RiskLevel,
				&device.CreatedAt,
				&device.UpdatedAt,
				&device.DeletedAt,
				&device.WorkStation,
				&device.Ext,
			),
			fmt.Sprintf("INSERT INTO manufacture.device (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
			//device.DeviceId,
			device.CompanyId,
			device.OrgId,
			device.DeviceCode,
			device.DeviceName,
			device.DeviceModel,
			device.DeviceType,
			device.Brand,
			device.DeviceStatus,
			device.RiskLevel,
			device.CreatedAt,
			device.UpdatedAt,
			//device.DeletedAt,
			device.WorkStation,
			device.Ext,
		); err != nil {
			return device, err
		}
	} else {
		if _, err := tx.QueryOne(
			pg.Scan(
				&device.DeviceId,
				&device.CompanyId,
				&device.OrgId,
				&device.DeviceCode,
				&device.DeviceName,
				&device.DeviceModel,
				&device.DeviceType,
				&device.Brand,
				&device.DeviceStatus,
				&device.RiskLevel,
				&device.CreatedAt,
				&device.UpdatedAt,
				&device.DeletedAt,
				&device.WorkStation,
				&device.Ext,
			),
			fmt.Sprintf("UPDATE manufacture.device SET %s WHERE device_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
			device.CompanyId,
			device.OrgId,
			device.DeviceCode,
			device.DeviceName,
			device.DeviceModel,
			device.DeviceType,
			device.Brand,
			device.DeviceStatus,
			device.RiskLevel,
			device.CreatedAt,
			device.UpdatedAt,
			device.WorkStation,
			device.Ext,
			device.Identify(),
		); err != nil {
			return device, err
		}
	}
	return device, nil
}
func (repository *DeviceRepository) Remove(device *domain.Device) (*domain.Device, error) {
	tx := repository.transactionContext.PgTx
	deviceModel := new(models.Device)
	deviceModel.DeviceId = device.Identify().(int)
	if _, err := tx.Model(deviceModel).WherePK().Delete(); err != nil {
		return device, err
	}
	return device, nil
}
func (repository *DeviceRepository) FindOne(queryOptions map[string]interface{}) (*domain.Device, error) {
	tx := repository.transactionContext.PgTx
	deviceModel := new(models.Device)
	query := sqlbuilder.BuildQuery(tx.Model(deviceModel), queryOptions)
	query.SetWhereByQueryOption("device_id = ?", "deviceId")
	query.SetWhereByQueryOption("company_id = ?", "companyId")
	query.SetWhereByQueryOption("org_id = ?", "orgId")
	query.SetWhereByQueryOption("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)
	}
}
func (repository *DeviceRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Device, error) {
	tx := repository.transactionContext.PgTx
	var deviceModels []*models.Device
	devices := make([]*domain.Device, 0)
	query := sqlbuilder.BuildQuery(tx.Model(&deviceModels), queryOptions)
	query.SetOffsetAndLimit(20)
	query.SetOrderDirect("device_id", "DESC")
	query.SetWhereByQueryOption("company_id = ?", "companyId")
	query.SetWhereByQueryOption("org_id = ?", "orgId")
	if v, ok := queryOptions["inOrgIds"]; ok && len(v.([]int)) > 0 {
		query.Where(`org_id in (?)`, pg.In(v))
	}
	if v, ok := queryOptions["inDeviceId"]; ok && len(v.([]int)) > 0 {
		query.Where(`device_id in (?)`, pg.In(v))
	}
	query.SetWhereByQueryOption("device_code = ?", "deviceCode")
	query.SetWhereByQueryOption("device_status = ?", "deviceStatus")
	if v, ok := queryOptions["deviceName"]; ok && len(v.(string)) > 0 {
		query.Where(fmt.Sprintf(`device_name like '%%%v%%'`, v))
	}
	if count, err := query.SelectAndCount(); err != nil {
		return 0, devices, err
	} else {
		for _, deviceModel := range deviceModels {
			if device, err := transform.TransformToDeviceDomainModelFromPgModels(deviceModel); err != nil {
				return 0, devices, err
			} else {
				devices = append(devices, device)
			}
		}
		return int64(count), devices, nil
	}
}
func NewDeviceRepository(transactionContext *pgTransaction.TransactionContext) (*DeviceRepository, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &DeviceRepository{
			transactionContext: transactionContext,
		}, nil
	}
}