export_table.go 2.6 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/domain"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/excel"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/starrocks"
	"time"
)

func (tableService *TableService) ExportDataTable(ctx *domain.Context, cmd *command.TablePreviewCommand) (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()
	}()

	// TODO:加锁 同一个用户同一个时间点只允许一次下载

	var table *domain.Table
	var mainTable *domain.Table
	_, table, err = factory.FastPgTable(transactionContext, cmd.TableId)
	if err != nil {
		return nil, factory.FastError(err)
	}
	if table.TableType == domain.SubTable.ToString() {
		_, mainTable, err = factory.FastPgTable(transactionContext, cmd.TableId)
		if err != nil {
			return nil, factory.FastError(err)
		}
	} else {
		mainTable = table
	}
	var options = starrocks.QueryOptions{
		TableName: mainTable.SQLName,
		Select:    table.Fields(true),
	}
	// 待优化分批下载,压缩
	var dataTable *domain.DataTable
	dataTable, err = starrocks.Query(options, starrocks.DefaultQueryFunc)
	if err != nil {
		return nil, factory.FastError(err)
	}
	count, err := starrocks.QueryCount(options)
	if err != nil {
		return nil, factory.FastError(err)
	}
	filename := fmt.Sprintf("%v_%v.xlsx", table.Name, time.Now().Format("060102150405"))
	path := fmt.Sprintf("public/%v", filename)
	excelWriter := excel.NewXLXSWriterTo(domain.Fields(table.Fields(false)).NameArrayString(), dataTable.Data) //
	if err = excelWriter.Save(path); err != nil {
		return nil, factory.FastError(err)
	}

	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	return map[string]interface{}{
		"url":   domain.DownloadUrl(filename),
		"count": count,
	}, nil
}