pg_log_repository.go 5.7 KB
package repository

import (
	"fmt"
	"github.com/go-pg/pg/v10"
	"github.com/go-pg/pg/v10/orm"
	"github.com/linmadan/egglib-go/utils/xtime"
	"time"

	"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
	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/pg/models"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/pg/transform"
)

type LogRepository struct {
	transactionContext *pgTransaction.TransactionContext
}

func (repository *LogRepository) Save(log *domain.Log) (*domain.Log, error) {
	sqlBuildFields := []string{
		"log_id",
		"log_type",
		"source_id",
		"object_name",
		"object_type",
		"operation_type",
		"content",
		"operator_name",
		"created_at",
		"entry",
		"context",
		"log_time",
	}
	insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "log_id"))
	insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "log_id"))
	returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
	updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "log_id")
	updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
	tx := repository.transactionContext.PgTx
	if log.Identify() == nil {
		if _, err := tx.QueryOne(
			pg.Scan(
				&log.LogId,
				&log.LogType,
				&log.SourceId,
				&log.ObjectName,
				&log.ObjectType,
				&log.OperationType,
				&log.Content,
				&log.OperatorName,
				&log.CreatedAt,
				&log.Entry,
				&log.Context,
				&log.LogTime,
			),
			fmt.Sprintf("INSERT INTO metadata.logs (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
			log.LogType,
			log.SourceId,
			log.ObjectName,
			log.ObjectType,
			log.OperationType,
			log.Content,
			log.OperatorName,
			log.CreatedAt,
			log.Entry,
			log.Context,
			log.LogTime,
		); err != nil {
			return log, err
		}
	} else {
		if _, err := tx.QueryOne(
			pg.Scan(
				&log.LogId,
				&log.LogType,
				&log.SourceId,
				&log.ObjectName,
				&log.ObjectType,
				&log.OperationType,
				&log.Content,
				&log.OperatorName,
				&log.CreatedAt,
				&log.Entry,
				&log.Context,
				&log.LogTime,
			),
			fmt.Sprintf("UPDATE metadata.logs SET %s WHERE log_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
			log.LogType,
			log.SourceId,
			log.ObjectName,
			log.ObjectType,
			log.OperationType,
			log.Content,
			log.OperatorName,
			log.CreatedAt,
			log.Entry,
			log.Context,
			log.LogTime,
			log.Identify(),
		); err != nil {
			return log, err
		}
	}
	return log, nil
}
func (repository *LogRepository) Remove(log *domain.Log) (*domain.Log, error) {
	tx := repository.transactionContext.PgTx
	logModel := new(models.Log)
	logModel.LogId = log.Identify().(int)
	if _, err := tx.Model(logModel).WherePK().Delete(); err != nil {
		return log, err
	}
	return log, nil
}
func (repository *LogRepository) FindOne(queryOptions map[string]interface{}) (*domain.Log, error) {
	tx := repository.transactionContext.PgTx
	logModel := new(models.Log)
	query := sqlbuilder.BuildQuery(tx.Model(logModel), queryOptions)
	query.SetWhereByQueryOption("log.log_id = ?", "logId")
	if err := query.First(); err != nil {
		if err.Error() == "pg: no rows in result set" {
			return nil, domain.ErrorNotFound
		} else {
			return nil, err
		}
	}
	if logModel.LogId == 0 {
		return nil, nil
	} else {
		return transform.TransformToLogDomainModelFromPgModels(logModel)
	}
}
func (repository *LogRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Log, error) {
	tx := repository.transactionContext.PgTx
	var logModels []*models.Log
	logs := make([]*domain.Log, 0)
	query := sqlbuilder.BuildQuery(tx.Model(&logModels), queryOptions)
	WhereContext(query, queryOptions)
	query.SetWhereByQueryOption(" log_type = ?", "logType")
	query.SetWhereByQueryOption(" source_id = ?", "sourceId")
	query.SetWhereByQueryOption("object_name = ?", "objectName")
	if v, ok := queryOptions["inSourceId"]; ok && len(v.([]int)) > 0 {
		query.Where("source_id in (?)", pg.In(v.([]int)))
	}
	if v, ok := queryOptions["matchContent"]; ok && len(v.(string)) > 0 {
		query.WhereGroup(func(query *orm.Query) (*orm.Query, error) {
			matchContent := v.(string)
			query.WhereOr(fmt.Sprintf("content like '%%%v%%'", matchContent))
			query.WhereOr(fmt.Sprintf("operator_name like '%%%v%%'", matchContent))
			query.WhereOr(fmt.Sprintf("object_name like '%%%v%%'", matchContent))
			return query, nil
		})
	}

	if v, ok := queryOptions["beginTime"]; ok && !xtime.IsZero(v.(time.Time)) {
		query.SetWhereByQueryOption(" created_at >= ?", "beginTime")
	}
	if v, ok := queryOptions["endTime"]; ok && !xtime.IsZero(v.(time.Time)) {
		query.SetWhereByQueryOption(" created_at < ?", "endTime")
	}

	SetOffsetAndLimit(query, queryOptions, 20)
	if v, ok := queryOptions["sortByLogId"]; ok && len(v.(string)) > 0 {
		query.SetOrderDirect("log_id", v.(string))
	} else {
		query.SetOrderDirect("log_id", "ASC")
	}
	if count, err := query.SelectAndCount(); err != nil {
		return 0, logs, err
	} else {
		for _, logModel := range logModels {
			if log, err := transform.TransformToLogDomainModelFromPgModels(logModel); err != nil {
				return 0, logs, err
			} else {
				logs = append(logs, log)
			}
		}
		return int64(count), logs, nil
	}
}
func NewLogRepository(transactionContext *pgTransaction.TransactionContext) (*LogRepository, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &LogRepository{
			transactionContext: transactionContext,
		}, nil
	}
}