go-gorm / gorm

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

The constraint "unique" is not working #6850

Open 0x41337 opened 6 months ago

0x41337 commented 6 months ago

Your Question

I was trying to use the unique constraint in the email field of my model but this is not being migrated to the database.

type Account struct {
    gorm.Model
    ID       string `sql:"type:uuid;primary_key;default:uuid_generate_v4()"`
    Email    string `gorm:"unique;not null" json:"email"` // <- Here
    Password string `gorm:"not null" json:"password"`
    User User `gorm:"foreignKey:AccountID;references:ID"`
}

When I do automatic migration with AutoMigrate() everything works, however when I dump the tables with pg_dump the email field in the table is not unique:

CREATE TABLE public.accounts (
    id text NOT NULL,
    created_at timestamp with time zone,
    updated_at timestamp with time zone,
    deleted_at timestamp with time zone,
    email text NOT NULL,
    password text NOT NULL
);

The document you expected this should be explained

https://gorm.io/docs/constraints.html https://gorm.io/docs/models.html#Fields-Tags

Expected answer

CREATE TABLE public.accounts (
    id text NOT NULL,
    created_at timestamp with time zone,
    updated_at timestamp with time zone,
    deleted_at timestamp with time zone,
    email text UNIQUE NOT NULL, -- <- unique
    password text NOT NULL
);
piheta commented 6 months ago

Got the same problem, this does not catch it:

if errors.Is(result.Error, gorm.ErrDuplicatedKey) {
    return weberrors.NewError(409, "employee with this id alread exists")
}
{
    "error": "ERROR: duplicate key value violates unique constraint \"employees_pkey\" (SQLSTATE 23505)"
}

Im using psql for the db.

gg1229505432 commented 5 months ago

Sample: type IndexTest struct { FieldA string gorm:"unique;index" // unique and index FieldB string gorm:"unique" // unique

    FieldC string `gorm:"index:,unique"`     // uniqueIndex
    FieldD string `gorm:"uniqueIndex;index"` // uniqueIndex and index

    FieldE1 string `gorm:"uniqueIndex:uniq_field_e1_e2"` // mul uniqueIndex
    FieldE2 string `gorm:"uniqueIndex:uniq_field_e1_e2"`

    FieldF1 string `gorm:"uniqueIndex:uniq_field_f1_f2;index"` // mul uniqueIndex and index
    FieldF2 string `gorm:"uniqueIndex:uniq_field_f1_f2;"`

    FieldG string `gorm:"unique;uniqueIndex"` // unique and uniqueIndex

    FieldH1 string `gorm:"unique;uniqueIndex:uniq_field_h1_h2"` // unique and mul uniqueIndex
    FieldH2 string `gorm:"uniqueIndex:uniq_field_h1_h2"`        // unique and mul uniqueIndex
}

path: schema/index_test.go