Skip to content

Conversation

@AlbertChenshiqi
Copy link

@AlbertChenshiqi AlbertChenshiqi commented Jul 22, 2025

  • Do only one thing
  • Non breaking API changes
  • Tested

What did this pull request do?

有些情况下,我们的自增id不一定是int64,有可能是其他类型,比如uint64或者uint32,使用主键分表会报类型错误, 修改如果config里有ShardingAlgorithm方法接收字段,则id的查询结果会回到这个方法来实现表后缀名修改

User Case Description

使用案例

type Order struct {
	ID      uint64 `gorm:"primarykey"`
	UserID  int64
	Product string
	Deleted gorm.DeletedAt
}

middleware = Register(Config{
		DoubleWrite:         true,
		ShardingKey:         "id",
		NumberOfShards:      4,
                ShardingAlgorithm: func(columnValue any) (suffix string, err error) {
			switch value := columnValue.(type) {
			case uint64, int64:
				return fmt.Sprintf("_%01d", cast.ToUint64(value)%4), nil
			default:
				return "", errors.New("invalid column value")
			}
		},
		PrimaryKeyGenerator: PKCustom,
		PrimaryKeyGeneratorFn: func(_ int64) int64 {
			return 0
		},
	}, &Order{})

db.Use(middleware)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant