GORM Playground Link

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

Description

do AutoMigrate twice, it will failed on uniqueIndex column

type User struct {
    gorm.Model
    Name      string `gorm:"uniqueIndex;size:255"`
}

2023/02/04 17:37:52 /home/runner/go/pkg/mod/gorm.io/driver/postgres@v1.4.6/migrator.go:339 ERROR: relation "idx_users_name" already exists (SQLSTATE 42P07)
[0.881ms] [rows:0] ALTER TABLE "users" ADD CONSTRAINT "idx_users_name" UNIQUE("name")
    main_test.go:18: Failed, migrate error: ERROR: relation "idx_users_name" already exists (SQLSTATE 42P07)

Comment From: sixcolors

bump relation "idx_whatever" already exists (SQLSTATE 42P07) PostgreSQL 14.1

Comment From: wimspaargaren

Had a quick look, it seems that the following PR introduced this issue: https://github.com/go-gorm/gorm/pull/5974/files

The problem seems to be as follows. The PR mentioned above, correctly marks a unique database field as unique when the database is read. However, the column definitions from the GORM DSL are parsed into a ColumnType: https://github.com/go-gorm/gorm/blob/48ced75d1d8d8aab844ab29787ae97337095b8e1/migrator/column_type.go#L9

This ColumnType has a UniqueValue field which is never set. Therefore, when we now perform the following check, the migrator incorrectly indicates that the field should be migrated: https://github.com/go-gorm/gorm/blame/master/migrator/migrator.go#L490

We could remove the unique check mentioned above, the only problem is that in that case unique indexes won't be automatically removed anymore, only added.