Skip to content

Newer versions of GORM remove the unique index incorrectly  #287

Description

@Ponywka

GORM Playground Link

<I have no time for write tests for your "playground" while working at office, sorry. Maybe later>

Description

I use gorm.io/driver/postgres v1.5.9, gorm.io/gorm v1.25.11 and go 1.22.6 in our project.

Sample environment:

type Smth struct {
	ID string `gorm:"uniqueIndex"`
	SmthDifferentID *int64 `gorm:"uniqueIndex"`
}

db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
	NamingStrategy: schema.NamingStrategy{TablePrefix: schemaName + "."},
})
if err != nil {
	return fmt.Errorf("database connecting error: %w", err)
}

err = db.Exec("CREATE SCHEMA IF NOT EXISTS " + schemaName).Error
if err != nil {
	return fmt.Errorf("creating schema error: %w", err)
}

err = db.AutoMigrate(&Smth{})
if err != nil {
	return fmt.Errorf("models automigrating error: %w", err)
}

When I run this code in already initialized before database in older versions of GORM I got this (place SmthDifferentID instead of FIELD):

[rows:0] ALTER TABLE "<SERVICE>"."<TABLE>" DROP CONSTRAINT "uni_<TABLE>_<FIELD>"
ERR: models automigrating error: ERROR: constraint "uni_<TABLE>_<FIELD>" of relation "<TABLE>" does not exist (SQLSTATE 42704)

After researching the issue, it was discovered that I have an existing record:

ALTER TABLE ONLY "<SERVICE>"."<TABLE>" ADD CONSTRAINT idx_<TABLE>_<FIELD> UNIQUE (<FIELD>);

GORM tries delete the uni_... index instead of idx_...

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions