pg_org_repository.go 6.1 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 OrgRepository struct {
	*cache.CachedRepository
	transactionContext *pgTransaction.TransactionContext
}

func (repository *OrgRepository) nextIdentify() (int64, error) {
	IdWorker, err := snowflake.NewIdWorker(1)
	if err != nil {
		return 0, err
	}
	id, err := IdWorker.NextId()
	return id, err
}
func (repository *OrgRepository) Save(org *domain.Org) (*domain.Org, error) {
	sqlBuildFields := []string{
		"org_id",
		"company_id",
		"created_at",
		"updated_at",
		"deleted_at",
		"org_code",
		"org_name",
		"ext",
		"org_status",
		"is_org",
		"parent_id",
		"parent_path",
	}
	insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "org_id"))
	insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "org_id"))
	returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
	updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "org_id")
	updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
	tx := repository.transactionContext.PgTx
	if org.Identify() == nil {
		//orgId, err := repository.nextIdentify()
		//if err != nil {
		//	return org, err
		//} else {
		//	org.OrgId = orgId
		//}
		if _, err := tx.QueryOne(
			pg.Scan(
				&org.OrgId,
				&org.CompanyId,
				&org.CreatedAt,
				&org.UpdatedAt,
				&org.DeletedAt,
				&org.OrgCode,
				&org.OrgName,
				&org.Ext,
				&org.OrgStatus,
				&org.IsOrg,
				&org.ParentId,
				&org.ParentPath,
			),
			fmt.Sprintf("INSERT INTO users.org (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
			//org.OrgId,
			org.CompanyId,
			org.CreatedAt,
			org.UpdatedAt,
			org.DeletedAt,
			org.OrgCode,
			org.OrgName,
			org.Ext,
			&org.OrgStatus,
			org.IsOrg,
			org.ParentId,
			org.ParentPath,
		); err != nil {
			return org, err
		}
	} else {
		queryFunc := func() (interface{}, error) {
			if _, err := tx.QueryOne(
				pg.Scan(
					&org.OrgId,
					&org.CompanyId,
					&org.CreatedAt,
					&org.UpdatedAt,
					&org.DeletedAt,
					&org.OrgCode,
					&org.OrgName,
					&org.Ext,
					&org.OrgStatus,
					&org.IsOrg,
					&org.ParentId,
					&org.ParentPath,
				),
				fmt.Sprintf("UPDATE users.org SET %s WHERE org_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
				org.CompanyId,
				org.CreatedAt,
				org.UpdatedAt,
				org.DeletedAt,
				org.OrgCode,
				org.OrgName,
				org.Ext,
				org.OrgStatus,
				org.IsOrg,
				org.ParentId,
				org.ParentPath,
				org.Identify(),
			); err != nil {
				return org, err
			}
			return org, nil
		}

		if _, err := repository.Query(queryFunc, org.CacheKeyFunc()); err != nil {
			return org, err
		}
	}
	return org, nil
}
func (repository *OrgRepository) Remove(org *domain.Org) (*domain.Org, error) {
	tx := repository.transactionContext.PgTx
	orgModel := new(models.Org)
	orgModel.OrgId = org.Identify().(int64)
	queryFunc := func() (interface{}, error) {
		if _, err := tx.Model(orgModel).WherePK().Delete(); err != nil {
			return org, err
		}
		return org, nil
	}

	if _, err := repository.Query(queryFunc, org.CacheKeyFunc()); err != nil {
		return org, err
	}

	return org, nil
}
func (repository *OrgRepository) FindOne(queryOptions map[string]interface{}) (*domain.Org, error) {
	tx := repository.transactionContext.PgTx
	orgModel := new(models.Org)

	queryFunc := func() (interface{}, error) {
		query := sqlbuilder.BuildQuery(tx.Model(orgModel), queryOptions)
		query.SetWhereByQueryOption("company_id = ?", "companyId")
		query.SetWhereByQueryOption("org_id = ?", "orgId")
		query.SetWhereByQueryOption("org_name = ?", "orgName")
		query.SetWhereByQueryOption("org_code = ?", "orgCode")
		query.SetWhereByQueryOption("org_id != ?", "notEqualOrgId")
		if err := query.First(); err != nil {
			if err.Error() == "pg: no rows in result set" {
				return nil, fmt.Errorf("没有此资源")
			} else {
				return nil, err
			}
		}
		return orgModel, nil
	}

	var cacheModel = &domain.Org{}
	if _, ok := queryOptions["orgId"]; ok {
		cacheModel.OrgId = queryOptions["orgId"].(int64)
	}
	if err := repository.QueryCache(cacheModel.CacheKeyFunc, orgModel, queryFunc, cache.WithObjectToExpire(constant.REPOSITORY_CACHE_EXPIRE)); err != nil {
		return nil, err
	}

	if orgModel.OrgId == 0 {
		return nil, nil
	} else {
		return transform.TransformToOrgDomainModelFromPgModels(orgModel)
	}
}
func (repository *OrgRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Org, error) {
	tx := repository.transactionContext.PgTx
	var orgModels []*models.Org
	orgs := make([]*domain.Org, 0)
	query := sqlbuilder.BuildQuery(tx.Model(&orgModels), queryOptions)
	query.SetOffsetAndLimit(20)
	query.SetWhereByQueryOption("is_org = ?", "isOrg")
	query.SetWhereByQueryOption("org_name = ?", "depName")
	query.SetWhereByQueryOption("org_code = ?", "orgCode")
	query.SetOrderDirect("org_id", "ASC")
	if count, err := query.SelectAndCount(); err != nil {
		return 0, orgs, err
	} else {
		for _, orgModel := range orgModels {
			if org, err := transform.TransformToOrgDomainModelFromPgModels(orgModel); err != nil {
				return 0, orgs, err
			} else {
				orgs = append(orgs, org)
			}
		}
		return int64(count), orgs, nil
	}
}
func NewOrgRepository(transactionContext *pgTransaction.TransactionContext) (*OrgRepository, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &OrgRepository{
			transactionContext: transactionContext,
			CachedRepository:   cache.NewDefaultCachedRepository(),
		}, nil
	}
}