go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
37.05k stars 3.94k forks source link

Two unique indices created when using syntax `uniqueIndex:custom_index_name`, PostgreSQL #7206

Closed ilmari-h closed 1 month ago

ilmari-h commented 2 months ago

Issue:

Two indices created when using syntax uniqueIndex:custom_index_name

Expected result

Using the uniqueIndex with a custom name for the index creates just one unique index with the given name

Actual result

Both the default index (that would be created without the given name) and the named index are created:

Description

I was unable to make go-playground run (there's an active issue for that) but this issue is easily reproduced with e.g. the following go code

package main

import (
    "log"

    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

type User struct {
    gorm.Model
    Name  string `gorm:"uniqueIndex:uni_name_index_gorm"`
    Email string
}

func main() {
    dsn := "postgres://postgres:postgres@localhost:5432/testdb?sslmode=disable"
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        log.Fatal("failed to connect database")
    }

    // Migrate the schema
    db.AutoMigrate(&User{})

}

This creates two indexes in the PostgreSQL database: idx_users_name and the index I wanted to create uni_name_index_gorm.

If I use just the tag gorm:"uniqueIndex" without a given name, only the first index idx_users_name is created

However, if I have the uniqueIndex:custom_index_name tag with the same name applied to multiple columns, then only that one named index gets created, so in that use-case it works as intended.

github-actions[bot] commented 2 months ago

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.ioSearch Before Asking