pg_users_base_repository.go 6.4 KB
package repository

import (
	"fmt"
	"github.com/go-pg/pg/v10"
	"github.com/linmadan/egglib-go/persistent/cache"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/constant"

	"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"github.com/linmadan/egglib-go/utils/snowflake"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/pg/transform"
)

type UserBaseRepository struct {
	*cache.CachedRepository
	transactionContext *pgTransaction.TransactionContext
}

func (repository *UserBaseRepository) nextIdentify() (int64, error) {
	IdWorker, err := snowflake.NewIdWorker(1)
	if err != nil {
		return 0, err
	}
	id, err := IdWorker.NextId()
	return id, err
}

var (
	sqlBuildFields = []string{
		"user_base_id",
		"user_info",
		"account",
		"password",
		"im",
		"related_user",
		"status",
		"favorite",
		"created_at",
		"updated_at",
	}
	insertFieldsSnippet       = sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "user_base_id"))
	insertPlaceHoldersSnippet = sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "user_base_id"))
	returningFieldsSnippet    = sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
	updateFields              = sqlbuilder.RemoveSqlFields(sqlBuildFields, "user_base_id")
	updateFieldsSnippet       = sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
)

func (repository *UserBaseRepository) Save(userBase *domain.UserBase) (*domain.UserBase, error) {

	tx := repository.transactionContext.PgTx
	if userBase.Identify() == nil {
		//userBaseId, err := repository.nextIdentify()
		//if err != nil {
		//	return userBase, err
		//} else {
		//	userBase.UserBaseId = userBaseId
		//}
		if _, err := tx.QueryOne(
			pg.Scan(
				&userBase.UserBaseId,
				&userBase.UserInfo,
				&userBase.Account,
				&userBase.Password,
				&userBase.Im,
				pg.Array(&userBase.RelatedUsers),
				&userBase.Status,
				&userBase.Favorite,
				&userBase.CreatedAt,
				&userBase.UpdatedAt,
			),
			fmt.Sprintf("INSERT INTO users.user_base (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
			//userBase.UserBaseId,
			userBase.UserInfo,
			userBase.Account,
			userBase.Password,
			userBase.Im,
			pg.Array(userBase.RelatedUsers),
			userBase.Status,
			userBase.Favorite,
			userBase.CreatedAt,
			userBase.UpdatedAt,
		); err != nil {
			return userBase, err
		}
	} else {
		queryFunc := func() (interface{}, error) {
			if _, err := tx.QueryOne(
				pg.Scan(
					&userBase.UserBaseId,
					&userBase.UserInfo,
					&userBase.Account,
					&userBase.Password,
					&userBase.Im,
					pg.Array(&userBase.RelatedUsers),
					&userBase.Status,
					&userBase.Favorite,
					&userBase.CreatedAt,
					&userBase.UpdatedAt,
				),
				fmt.Sprintf("UPDATE users.user_base SET %s WHERE user_base_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
				userBase.UserInfo,
				userBase.Account,
				userBase.Password,
				userBase.Im,
				pg.Array(userBase.RelatedUsers),
				userBase.Status,
				userBase.Favorite,
				userBase.CreatedAt,
				userBase.UpdatedAt,
				userBase.Identify(),
			); err != nil {
				return userBase, err
			}
			return userBase, nil
		}
		if _, err := repository.Query(queryFunc, userBase.CacheKeyFunc()); err != nil {
			return userBase, err
		}
	}
	return userBase, nil
}
func (repository *UserBaseRepository) Remove(userBase *domain.UserBase) (*domain.UserBase, error) {
	tx := repository.transactionContext.PgTx
	userBaseModel := new(models.UserBase)
	userBaseModel.UserBaseId = userBase.Identify().(int64)
	queryFunc := func() (interface{}, error) {
		if _, err := tx.Model(userBaseModel).WherePK().Delete(); err != nil {
			return userBase, err
		}
		return userBase, nil
	}
	if _, err := repository.Query(queryFunc, userBase.CacheKeyFunc()); err != nil {
		return userBase, err
	}
	return userBase, nil
}
func (repository *UserBaseRepository) FindOne(queryOptions map[string]interface{}) (*domain.UserBase, error) {
	tx := repository.transactionContext.PgTx
	userBaseModel := new(models.UserBase)
	queryFunc := func() (interface{}, error) {
		query := sqlbuilder.BuildQuery(tx.Model(userBaseModel), queryOptions)
		query.SetWhereByQueryOption("account = ?", "account")
		query.SetWhereByQueryOption("user_base.user_base_id = ?", "userBaseId")
		if err := query.First(); err != nil {
			if err.Error() == "pg: no rows in result set" {
				return nil, domain.ErrorNotFound
			} else {
				return nil, err
			}
		}
		return userBaseModel, nil
	}

	var cacheModel = &domain.UserBase{}
	if _, ok := queryOptions["userBaseId"]; ok {
		cacheModel.UserBaseId = queryOptions["userBaseId"].(int64)
	}
	if err := repository.QueryCache(cacheModel.CacheKeyFunc, userBaseModel, queryFunc, cache.WithObjectToExpire(constant.REPOSITORY_CACHE_EXPIRE)); err != nil {
		return nil, err
	}
	if userBaseModel.UserBaseId == 0 {
		return nil, nil
	} else {
		return transform.TransformToUserBaseDomainModelFromPgModels(userBaseModel)
	}
}
func (repository *UserBaseRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.UserBase, error) {
	tx := repository.transactionContext.PgTx
	var userBaseModels []*models.UserBase
	userBases := make([]*domain.UserBase, 0)
	query := sqlbuilder.BuildQuery(tx.Model(&userBaseModels), queryOptions)
	query.SetOffsetAndLimit(20) //InUserBaseIds
	if v, ok := queryOptions["inUserBaseIds"]; ok && len(v.([]int64)) > 0 {
		query.Where(`user_base_id in (?)`, pg.In(v))
	}
	query.SetOrderDirect("user_base_id", "DESC")
	if count, err := query.SelectAndCount(); err != nil {
		return 0, userBases, err
	} else {
		for _, userBaseModel := range userBaseModels {
			if userBase, err := transform.TransformToUserBaseDomainModelFromPgModels(userBaseModel); err != nil {
				return 0, userBases, err
			} else {
				userBases = append(userBases, userBase)
			}
		}
		return int64(count), userBases, nil
	}
}
func NewUserBaseRepository(transactionContext *pgTransaction.TransactionContext) (*UserBaseRepository, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &UserBaseRepository{
			transactionContext: transactionContext,
			CachedRepository:   cache.NewDefaultCachedRepository(),
		}, nil
	}
}