table_delete_data_table_service.go 2.6 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 DeleteDataTableService struct {
	transactionContext *pgTransaction.TransactionContext
}

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

// DeleteTable 表删除 【data-table】
func (ptr *DeleteDataTableService) DeleteTable(ctx *domain.Context, tableId int) (interface{}, error) {
	tableRepository, _ := repository.NewTableRepository(ptr.transactionContext)
	table, err := tableRepository.FindOne(map[string]interface{}{"tableId": tableId})
	if err != nil {
		return nil, err
	}

	var subTables []*domain.Table
	if table.TableType == domain.MainTable.ToString() {
		_, subTables, err = tableRepository.Find(map[string]interface{}{"parentId": tableId, "tableTypes": []string{domain.SubTable.ToString()}})
		if err != nil {
			return nil, err
		}
	}

	// 日志
	if err = FastLog(ptr.transactionContext, domain.CommonLog, table.TableId, &DeleteTableLog{
		LogEntry:        domain.NewLogEntry(table.Name, table.TableType, domain.DeleteTable, ctx),
		SourceTableName: table.Name,
		RowCount:        table.RowCount,
		SubTables:       subTables,
	}); err != nil {
		return nil, err
	}

	if err := ptr.DeleteTables(ctx, table); err != nil {
		return nil, err
	}
	if err := ptr.DeleteTables(ctx, subTables...); err != nil {
		return nil, err
	}
	// 通知底层

	return nil, nil
}

func (ptr *DeleteDataTableService) DeleteTables(ctx *domain.Context, tables ...*domain.Table) error {
	// delete table
	if len(tables) == 0 {
		return nil
	}
	tableRepository, _ := repository.NewTableRepository(ptr.transactionContext)
	tableDependencyService, _ := NewTableDependencyService(ptr.transactionContext)
	var tableIds []int
	for _, t := range tables {
		if err := tableDependencyService.HasDependencyError(ctx, t.TableId); err != nil {
			return err
		}
		if _, err := tableRepository.Remove(t); err != nil {
			return err
		}
		AsyncEvent(domain.NewEventTable(ctx, domain.TableDeleteEvent).WithTable(t))
		tableIds = append(tableIds, t.TableId)
	}
	// delete log
	//if err := dao.LogSoftDelete(ptr.transactionContext, tableIds, domain.CommonLog); err != nil {
	//	return err
	//}
	return nil
}