go-gorm / sharding

High performance table sharding plugin for Gorm.
MIT License
268 stars 58 forks source link

mysql 驱动没有回填snowflake id #85

Closed ppanphper closed 1 year ago

ppanphper commented 1 year ago

GORM Playground Link

https://github.com/go-gorm/playground/pull/1

Description

https://github.com/go-gorm/sharding/issues/37

Env: go 1.16 mysql: 5.7.28 sharding: 0.5.2 gorm: 1.24.3

package main

import (
    "fmt"

    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/sharding"
)

type User struct {
    ID     int64 `gorm:"column:id;primaryKey"`
    UserId int64 `gorm:"column:user_id"`
}

func main() {
    dsn := "username:pwd@tcp(host:3306)/database_name?charset=utf8mb4&parseTime=true&loc=Local"
    db, _ := gorm.Open(mysql.New(mysql.Config{DSN: dsn}))

    shard := sharding.Register(sharding.Config{
        ShardingKey:         "user_id",
        NumberOfShards:      2,
        PrimaryKeyGenerator: sharding.PKSnowflake,
    }, "users")

    db.Use(shard)

    user := User{UserId: 42}
    err := db.Create(&user).Error // nil
    if err != nil {
        panic(err)
    }

    fmt.Println(user.ID) // 0
}

debug code

gorm: callbacks/create.go
Create() {
     insertID, err := result.LastInsertId() // 0
     insertOk := err == nil && insertID > 0
}

// return 0
func (res *mysqlResult) LastInsertId() (int64, error) {
    return res.insertId, nil
}
ppanphper commented 1 year ago

原因是因为表主键去掉了AUTO_INCREMENT属性,加上就可以获取到最近插入的id...

blight19 commented 5 months ago

原因是因为表主键去掉了AUTO_INCREMENT属性,加上就可以获取到最近插入的id...

这是什么原理