Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to backfill primary key when use this plugin? #37

Closed
usual2970 opened this issue May 16, 2022 · 3 comments
Closed

How to backfill primary key when use this plugin? #37

usual2970 opened this issue May 16, 2022 · 3 comments
Assignees

Comments

@usual2970
Copy link

usual2970 commented May 16, 2022

Your Question

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

shard, err := sharding.Register(sharding.Config{
  ShardingKey:         "user_id",
  NumberOfShards:      1,
  PrimaryKeyGenerator: sharding.PKSnowflake,
  ShardingAlgorithm:   getShardFn(1),
}, "users"))
if err != nil {
  return nil, err
}

if err := db.Use(shard); err != nil {
  return nil, err
}

result := db.Create(&user) // pass pointer of data to Create

user.ID             // 0

The document you expected this should be explained

Expected answer

@Yii18
Copy link

Yii18 commented Jul 4, 2022

解决了吗

@huacnlee
Copy link
Collaborator

huacnlee commented Jul 4, 2022

@hyperphoton 看看这个问题

@hyperphoton
Copy link
Collaborator

hyperphoton commented Jul 12, 2022

The problem is that when result := db.Create(&user) is executed there is an error at the database level, but you didn't check it, so the user.ID is 0.

Here is a worked example:

package main

import (
	"fmt"

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

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

func main() {
	dsn := "postgres://localhost:5432/sharding-db?sslmode=disable"
	db, _ := gorm.Open(postgres.New(postgres.Config{DSN: dsn}))

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

	db.Use(shard)

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

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

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

No branches or pull requests

5 participants