pg_user_repository.go 5.1 KB
package repository

import (
	"fmt"
	"github.com/go-pg/pg/v10"

	"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/mmm-go-pp/partner01/pkg/domain"
	"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg/transform"
)

type UserRepository struct {
	transactionContext *pgTransaction.TransactionContext
}

func (repository *UserRepository) nextIdentify() (int64, error) {
	IdWorker, err := snowflake.NewIdWorker(1)
	if err != nil {
		return 0, err
	}
	id, err := IdWorker.NextId()
	return id, err
}
func (repository *UserRepository) Save(user *domain.User) (*domain.User, error) {
	sqlBuildFields := []string{
		"user_id",
		"user_type",
		"permissions",
		"company_id",
		"user_info",
		"partner_info",
		"status",
		"admin_type",
		"access_partners",
		"create_at",
		"update_at",
		"delete_at",
	}
	insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
	insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
	returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
	updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "user_id")
	updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
	tx := repository.transactionContext.PgTx
	if user.Identify() == nil {
		userId, err := repository.nextIdentify()
		if err != nil {
			return user, err
		} else {
			user.UserId = userId
		}
		if _, err := tx.QueryOne(
			pg.Scan(
				&user.UserId,
				&user.UserType,
				pg.Array(&user.Permissions),
				&user.CompanyId,
				&user.UserInfo,
				&user.PartnerInfo,
				&user.Status,
				&user.AdminType,
				pg.Array(&user.AccessPartners),
				&user.CreateAt,
				&user.UpdateAt,
				&user.DeleteAt,
			),
			fmt.Sprintf("INSERT INTO users (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
			user.UserId,
			user.UserType,
			pg.Array(user.Permissions),
			user.CompanyId,
			user.UserInfo,
			user.PartnerInfo,
			user.Status,
			user.AdminType,
			pg.Array(user.AccessPartners),
			user.CreateAt,
			user.UpdateAt,
			user.DeleteAt,
		); err != nil {
			return user, err
		}
	} else {
		if _, err := tx.QueryOne(
			pg.Scan(
				&user.UserId,
				&user.UserType,
				pg.Array(&user.Permissions),
				&user.CompanyId,
				&user.UserInfo,
				&user.PartnerInfo,
				&user.Status,
				&user.AdminType,
				pg.Array(&user.AccessPartners),
				&user.CreateAt,
				&user.UpdateAt,
				&user.DeleteAt,
			),
			fmt.Sprintf("UPDATE users SET %s WHERE user_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
			user.UserId,
			user.UserType,
			pg.Array(user.Permissions),
			user.CompanyId,
			user.UserInfo,
			user.PartnerInfo,
			user.Status,
			user.AdminType,
			pg.Array(user.AccessPartners),
			user.CreateAt,
			user.UpdateAt,
			user.DeleteAt,
			user.Identify(),
		); err != nil {
			return user, err
		}
	}
	return user, nil
}
func (repository *UserRepository) Remove(user *domain.User) (*domain.User, error) {
	tx := repository.transactionContext.PgTx
	userModel := new(models.User)
	userModel.UserId = user.Identify().(int64)
	if _, err := tx.Model(userModel).WherePK().Delete(); err != nil {
		return user, err
	}
	return user, nil
}
func (repository *UserRepository) FindOne(queryOptions map[string]interface{}) (*domain.User, error) {
	tx := repository.transactionContext.PgTx
	userModel := new(models.User)
	query := sqlbuilder.BuildQuery(tx.Model(userModel), queryOptions)
	query.SetWhereByQueryOption("users.user_id = ?", "userId")
	query.SetWhereByQueryOption("users.status = ?", "status")
	query.SetWhereByQueryOption("users.user_type = ?", "userType")
	if v, ok := queryOptions["inUserIds"]; ok {
		query.Where("users.user_id in (?)", pg.Array(v))
	}
	if err := query.First(); err != nil {
		if err.Error() == "pg: no rows in result set" {
			return nil, fmt.Errorf("没有此资源")
		} else {
			return nil, err
		}
	}
	if userModel.UserId == 0 {
		return nil, nil
	} else {
		return transform.TransformToUserDomainModelFromPgModels(userModel)
	}
}
func (repository *UserRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.User, error) {
	tx := repository.transactionContext.PgTx
	var userModels []*models.User
	users := make([]*domain.User, 0)
	query := sqlbuilder.BuildQuery(tx.Model(&userModels), queryOptions)
	query.SetOffsetAndLimit(20)
	query.SetOrderDirect("user_id", "DESC")
	if count, err := query.SelectAndCount(); err != nil {
		return 0, users, err
	} else {
		for _, userModel := range userModels {
			if user, err := transform.TransformToUserDomainModelFromPgModels(userModel); err != nil {
				return 0, users, err
			} else {
				users = append(users, user)
			}
		}
		return int64(count), users, nil
	}
}
func NewUserRepository(transactionContext *pgTransaction.TransactionContext) (*UserRepository, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &UserRepository{
			transactionContext: transactionContext,
		}, nil
	}
}