query_set_service_load_calculate_item.go 1.0 KB
package domainService

import (
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain/astexpr"
)

// LoadCalculateItemData 加载计算项数据,实时计算某个列的值
func (ptr *QuerySetService) LoadCalculateItemData(ctx *domain.Context, t *domain.Table, formula *domain.FieldFormulaExpr) (*domain.DataTable, error) {
	var (
		res = &domain.DataTable{}
		err error
	)

	calc, err := astexpr.NewCalculator(formula.ExprSql)
	if err != nil {
		return nil, err
	}

	if len(formula.TableFields) > 0 {
		var tableId = formula.TableFields[0].TableId
		mapTable, _ := ptr.loadDataTables(ctx, []int{tableId})
		calc.SetDataTable(mapTable[tableId])
	}
	result, err := calc.ExprASTResult(calc.ExprAST)
	if err != nil {
		return nil, err
	}

	res.Data = [][]string{
		result.Data(),
	}
	if t != nil {
		res.Fields = t.Fields(false)
	}
	res.Total = int64(len(res.Data))
	// 数据持久化
	return res, nil
}