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

index: add composite id #5269

Merged
merged 3 commits into from Apr 25, 2022
Merged

index: add composite id #5269

merged 3 commits into from Apr 25, 2022

Conversation

photon3108
Copy link
Contributor

@photon3108 photon3108 commented Apr 18, 2022

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

What did this pull request do?

In the issue #3973, if a struct with any composite indexes, these indexes will be invalid when the struct is embedded more than once. Because a composite index must specify its name, embedding more than once results in the duplicated name in db. Also if the name of index is specified manually, NamingStrategy will not be applied. Take the example of #3973:

type Bar0 struct {
  Foo
}
type Bar1 struct {
  Foo
}

Both Bar0 and Bar1 will try to create an index of the same name my_idx. In this pull request, it provides a new field of index tag which is named to composite. It means the id of composite index. All fields which have the same composite id of the struct are put together to the same index, just like the original rule. But the improvement is it lets the most derived/embedding struct generates the name of index by NamingStrategy. For example:

type Foo struct {
  IndexA int `gorm:"index:,unique,composite:myname"`
  IndexB int `gorm:"index:,unique,composite:myname"`
}

If the table Foo is created, the name of composite index will be idx_foo_myname.

type Bar0 struct {
  Foo
}
type Bar1 struct {
  Foo
}

Respectively, the name of composite index are idx_bar0_myname and idx_bar1_myname.

composite only works if not specify the name of index, so it keeps the original API from being broken.

@jinzhu
Copy link
Member

jinzhu commented Apr 24, 2022

Hello,

@photon3108 can you add a test to index_test.go to test the composite logic.

Thank you.

@daheige
Copy link
Contributor

daheige commented Apr 24, 2022 via email

@jinzhu jinzhu merged commit 0211ac9 into go-gorm:master Apr 25, 2022
ukewea added a commit to ukewea/crypto-project-go that referenced this pull request May 26, 2023
index name must be unique across database, thus use the new mechanism to
automatically create unique name for same embedded struct

source: go-gorm/gorm#5269
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.

None yet

3 participants