Skip to content

Fix creating unique index on non-unique field #168

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

Merged
merged 1 commit into from
Apr 21, 2025

Conversation

fkollmann
Copy link
Contributor

What did this pull request do?

When having a named unique index on an non-unique column, the migrator will not check, if the index already exists, resulting in Error 1061 (42000): Duplicate key name 'index_name'

This fix adds the check, as done in the unique column code branch of the function (line 101).

User Case Description

Creating an index on a non-unique column, but not having a unique constraint:

type Ticket struct {
  ID        uint64            `gorm:"primarykey"`
  Hashes    datatypes.JSON    `gorm:"column:hashes;uniqueIndex:uq_tickets_hashes,expression:(CAST(hashes AS CHAR(40) ARRAY))"`
}

On the first migration, the index is successfully being created.

On the next migration the following error is given, and no information_schema check is being performed:

error="Error 1061 (42000): Duplicate key name 'uq_tickets_hashes'" sql="CREATE UNIQUE INDEX `uq_tickets_hashes` ON `tickets__simple`((CAST(hashes AS CHAR(40) ARRAY)))"
    parser.go:150: failed to migrate database: failed to migrate tickets table: Error 1061 (42000): Duplicate key name 'uq_tickets_hashes'

After the fix, the check is being performed:

sql="SELECT count(*) FROM information_schema.statistics WHERE table_schema = 'unittest' AND table_name = 'tickets__simple' AND index_name = 'uq_tickets_hashes'"

(which would be created multiple times and fail during migration)
@jinzhu jinzhu merged commit d815729 into go-gorm:master Apr 21, 2025
3 checks passed
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.

2 participants