table_add_table_struct_service.go 2.7 KB
package domainService

import (
	"fmt"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/repository"
)

type AddTableStructService struct {
	transactionContext *pgTransaction.TransactionContext
}

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

func (ptr *AddTableStructService) AddTableStruct(ctx *domain.Context, parentTableId int, fields []*domain.Field, name string) (*domain.Table, error) {
	tableRepository, _ := repository.NewTableRepository(ptr.transactionContext)
	mainTable, err := tableRepository.FindOne(map[string]interface{}{"tableId": parentTableId})
	if err != nil {
		return nil, err
	}
	if !(mainTable.TableType == domain.MainTable.ToString() || mainTable.TableType == domain.SideTable.ToString()) {
		return nil, fmt.Errorf("只有主表、副表允许新建分表")
	}

	// 验证表名是否重复
	duplicateTable, err := tableRepository.FindOne(map[string]interface{}{"context": ctx, "tableName": name})
	if err == nil && duplicateTable != nil {
		return nil, fmt.Errorf("表名称重复")
	}

	fields = MappingFields(mainTable, fields)
	dataFields := (domain.Fields)(fields).Select(map[string]interface{}{"flag": domain.MainTableField})
	manualFields := (domain.Fields)(fields).Select(map[string]interface{}{"flag": domain.ManualField})
	table := NewTable(domain.SubTable, name, fields, mainTable.RowCount).WithContext(ctx)
	table.DataFieldIndex = mainTable.DataFieldIndex
	table.DataFields = dataFields
	table.ManualFields = manualFields
	table.ParentId = parentTableId
	table.SQLName = mainTable.SQLName // 主表名跟分表名相同
	reserves, deletes, adds := domain.FieldsChange(table.Fields(false), fields)

	if err = domain.ValidFields(fields); err != nil {
		return nil, err
	}
	if table, err = tableRepository.Save(table); err != nil {
		return nil, err
	}
	if _, err = tableRepository.Save(mainTable); err != nil {
		return nil, err
	}

	// Log
	// 日志
	if err = FastLog(ptr.transactionContext, domain.CommonLog, table.TableId, &SpiltMainTableLog{
		LogEntry:        domain.NewLogEntry(table.Name, table.TableType, domain.SpiltMainTable, ctx),
		Reserve:         reserves,
		Delete:          deletes,
		Add:             adds,
		SourceTableName: mainTable.Name,
	}); err != nil {
		return nil, err
	}

	// 通知底层
	return table, nil
}