Tom Haines
Tom Haines

Reputation: 123

Gorm: pq duplicate key violates unique constraint

I'm trying to learn go & Gorm currently so I apologize if i'm missing something obvious.

I have declared the following GORM Models

type User struct {
    gorm.Model
    DiscordID            string `gorm:"unique"`
    SteamID              string `gorm:"unique"`
    SteamID64            uint64 `gorm:"unique"`
    DiscordNickname      string
    DiscordProfilePicURL string
}

type DeepLink struct {
    gorm.Model
    ShortURL   string `gorm:"unique"`
    UserID     uint
    User       User
    LinkAction Action
    Payload    interface{} `gorm:"-"`
}

I want to be able to identify the User that created the deeplink - this may not be the best way to do this.

When on a new database, when creating a second user using

func (m *Models) CreateUserFromDiscord(discordID, discordNickname, discordProfilePicURL string) *User {
    u := &User{
        DiscordID:            discordID,
        DiscordNickname:      discordNickname,
        DiscordProfilePicURL: discordProfilePicURL,
    }

    m.db.Create(u)
    return u
}

I get an error saying pq: duplicate key value violates unique constraint "users_steam_id_key"

Creating the first user using this method and creating deeplinks for this User works fine, but creating a second user throws the error. Neither user has a SteamID set.

Im wondering if theres any way to fix this or better structure my models to solve this problem.

The database is created using Gorms AutoMigrate function. This happens on a new db

Thanks

Upvotes: 3

Views: 10494

Answers (1)

Eklavya
Eklavya

Reputation: 18480

In golang if you don't set value for String variable it means it's value is ""(empty string). Ref

Since you don't set SteamID then ""(empty string) set as value for first user. Then when your trying to save second user SteamID column as ""(empty) then unique constraint violates because ""(empty string) is a not null value for database and gives you error.

Solution: Use *(pointer) for those fields in struct. If variable of *string/*int64 is not set then it's value nil. Also make optional columns nullable in DB.

type User struct {
    gorm.Model
    DiscordID            string `gorm:"unique"`
    SteamID              *string `gorm:"unique"`
    SteamID64            *uint64 `gorm:"unique"`
    DiscordNickname      string
    DiscordProfilePicURL string
}

Upvotes: 3

Related Questions