GORM Playground Link
https://github.com/go-gorm/playground/pull/709
Description
DB
- TiDB(MySQL compatible)
AutoMigrate to add primary key is not working
I'm currently using gorm + TiDB(MySQL compatible) in my project. At first, I migrated with this struct
type User struct {
UserID string `gorm:"type:VARCHAR(36)"`
Email string `gorm:"type:VARCHAR(200);unique;index;not null"`
Deleted bool `gorm:"not null"`
CreatedAt time.Time `gorm:"not null"`
UpdatedAt time.Time `gorm:"not null"`
}
this worked but, after migrated, I realized I should've set primary key to UserID column. so I changed the struct to this
type User struct {
UserID string `gorm:"primarykey;type:VARCHAR(36)"`
Email string `gorm:"type:VARCHAR(200);unique;index;not null"`
Deleted bool `gorm:"not null"`
CreatedAt time.Time `gorm:"not null"`
UpdatedAt time.Time `gorm:"not null"`
}
after migrated with this struct,
* Expected: PrimaryKey is set to UserID column
* Result
* PrimaryKey is not set
* No error logged out
* When I opened TiDB Cloud and SHOW COLUMN FROM user, I checked that primary key has not been added
What I tried which did not worked
- change UserID string
gorm:"primarykey;type:VARCHAR(36)"to - UserID string
gorm:"primaryKey;type:VARCHAR(36)" - UserID string
gorm:"primary_key;type:VARCHAR(36)" - UserID string
gorm:"type:VARCHAR(36);primaryKey" - UserID string
gorm:"type:VARCHAR(36);primary_key"
Comment From: gg1229505432
ID uint32 `gorm:"primary_key;auto_increment;not null" json:"id"`
Comment From: shedyfreak
as far as I remember automigrate doesn't support altering columns. you need to drop the table and rebuild it, unless you're sure all your primaryID are unique you can set it manually in the database
Comment From: sgasho
I read some codes and realized that this behavior is expected.
as far as I remember automigrate doesn't support altering columns
that some changes like adding unique constraints, indexes etc worked made me feel like this behavior is a kind of bug.
I realized that if I want to AutoMigrate to add primary key, I have to change more codes than I expected (need additional methods for each drivers and so on). I have no idea if this worth commit so I close this issue for now.
Comment From: bo-er
@sgasho may I ask what do you mean by
I realized that if I want to AutoMigrate to add primary key, I have to change more codes than I expected
I'm having the same problem here.