db_table_preview.go 2.3 KB
package service

import (
	"fmt"
	"github.com/linmadan/egglib-go/core/application"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/application/factory"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/application/table/command"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/application/table/dto"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/starrocks"
)

func (tableService *TableService) DBTablePreview(ctx *domain.Context, cmd *command.DBTablePreviewCommand) (interface{}, error) {
	if err := cmd.ValidateCommand(); err != nil {
		return nil, application.ThrowError(application.ARG_ERROR, err.Error())
	}
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		transactionContext.RollbackTransaction()
	}()

	var table *domain.Table
	var ok bool
	table, ok = domain.DBTables[cmd.ObjectId]
	if !ok {
		return nil, factory.FastError(fmt.Errorf("表%v不存在", cmd.ObjectId))
	}

	var options = starrocks.QueryOptions{
		Table:     table,
		TableName: table.SQLName,
		Select:    table.Fields(true),
		Context:   ctx,
	}
	options.SetCondition(cmd.Where.Conditions)
	options.SetOffsetLimit(cmd.Where.PageNumber, cmd.Where.PageSize)
	var dataTable *domain.DataTable
	options.AdditionOptionsByTable(table)

	dataTable, err = starrocks.Query(options, starrocks.WrapQueryFuncWithDB(pg.GormDB))
	if err != nil {
		return nil, factory.FastError(err)
	}
	dataTable.Total, err = starrocks.WrapQueryCountWithDB(options, pg.GormDB)()
	if err != nil {
		return nil, factory.FastError(err)
	}

	response := (&dto.TablePreviewDto{}).Load(table, dataTable, domain.ObjectDBTable)
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	return response, nil
}