go-gorm / sharding

High performance table sharding plugin for Gorm.
MIT License
263 stars 55 forks source link

When the table suffix is non numeric, the insertion operation will report an error when generating the primary key ID #111

Closed mocanxi closed 1 year ago

mocanxi commented 1 year ago

Solving the problem of generating primary key errors when the table suffix is a string eg:

type FileRecord struct {
    ID        int64  `gorm:"primary_key;column:id"`
    Project   string `gorm:"column:project"`
    UserID    int64  `gorm:"column:user_id"`
    ProductID int64  `gorm:"column:product_id"`
}

func (FileRecord) TableName() string {
    return "file_record"
}

middleware := sharding.Register(sharding.Config{
        ShardingKey: "project",
        ShardingAlgorithm: func(value interface{}) (suffix string, err error) {
            if project, ok := value.(string); ok {
                return fmt.Sprintf("_%s", project), nil
            }
            return "", errors.New("invalid project")
        },
        NumberOfShards: 8,
        //PrimaryKeyGenerator: sharding.PKSnowflake,
    }, "file_record")
    db.Use(middleware)

    // 插入数据
    err = db.Create(&FileRecord{UserID: 221, Project: "a"}).Error
    if err != nil {
        fmt.Println(err)
    }

Error message: strconv.Atoi: parsing "a": invalid syntax

Now, ShardingSuffixs should be set. eg:

middleware := sharding.Register(sharding.Config{
        ShardingKey: "project",
        ShardingAlgorithm: func(value interface{}) (suffix string, err error) {
            if project, ok := value.(string); ok {
                return fmt.Sprintf("_%s", project), nil
            }
            return "", errors.New("invalid project")
        },
        ShardingSuffixs: func() (suffixs []string) {
            return []string{"a", "b", "c", "d", "e", "f"}
        },
        NumberOfShards:      8,
        PrimaryKeyGenerator: sharding.PKSnowflake,
    }, "file_record")
    db.Use(middleware)