Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@truongns
Copy link
Contributor

@truongns truongns commented Mar 7, 2023

Fix #4930 workaround for databases that support auto-increment in composite primary key.

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

What did this pull request do?

Fix issue #4930

User Case Description

In MySQL, you can have composite primary key with auto-increment
For example:

https://github.com/nash90/playground/blob/7a82d16b1b1b626df01cf43089b302de7c2a6bd9/models.go#L63-L70

type CompositeKeyProduct struct {
	ProductPointID int       `gorm:"primaryKey;autoIncrement:true;column:product_point_id"`
	LanguageCode   int       `gorm:"primaryKey;autoIncrement:false;column:language_code"`
	Code           string    `gorm:"column:code"`
	Name           string    `gorm:"column:name"`
	CreatedAt      time.Time `gorm:"column:created_at"`
	UpdatedAt      time.Time `gorm:"column:updated_at"`
}

Upon insert new record into CompositeKeyProduct with the following values:
https://github.com/nash90/playground/blob/7a82d16b1b1b626df01cf43089b302de7c2a6bd9/main_test.go#L26-L30

prod := &CompositeKeyProduct{
		LanguageCode: 56,
		Code:         "56",
		Name:         "Test56",
}

res := DB.Create(prod)

expected

prod.ProductPointID: 1

actual

prod.ProductPointID: 0

This Pull Request is aiming to fix the above case

Copy link
Member

@a631807682 a631807682 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add more tests to describe it? just like doing in playground.

…INCREMENT"], add test to check autoincrement:false

create_test.go: remove unused code: drop table CompositeKeyProduct
@jinzhu jinzhu merged commit ed47415 into go-gorm:master Mar 10, 2023
}

newProd := &CompositeKeyProduct{}
if err := DB.First(&newProd).Error; err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not rigorous here. When I run the test repeatedly, the inserted record product id is self-increasing, so it will fail.
I suggest to do DropTable before AutoMigrate.

if err := DB.Migrator().DropTable(&CompositeKeyProduct{}); err != nil {
	t.Fatalf("failed to migrate, got error %v", err)
}

@black-06 black-06 mentioned this pull request Apr 19, 2023
3 tasks
black-06 added a commit to black-06/gorm that referenced this pull request Apr 19, 2023
jinzhu pushed a commit that referenced this pull request Apr 21, 2023
* fix: unit test

* fix create test

#6127 (comment)

* style: rename to adaptorSerializerModel
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.

composite key auto-increment returned 0 upon Create of new record

4 participants