GORM skips ids when fails to create account in Postgres

26 Views Asked by At

My code:

func (s *service) CreateAccount(account *models.Account) error {
    result := s.db.Create(account)

    if result.Error != nil {
        return result.Error
    }

    fmt.Println("Successfully created!")

    return nil
}

Yes, that works well. But in case when I create an account with the same email I get:

"ERROR: duplicate key value violates unique constraint \"uni_accounts_email\" (SQLSTATE 23505)"

Account type:

type Account struct {
    gorm.Model
    Email       string    `json:"email" gorm:"unique"`
    Password    string    `json:"-"`
    FirstName   string    `json:"firstName"`
    LastName    string    `json:"lastName"`
    Birthday    time.Time `json:"birthday"`
    PhoneNumber string    `json:"phoneNumber"`
    Cards       []Card    `gorm:"foreignKey:AccountID" json:"cards,omitempty"`
}

The problem is when the fail happens the id moves by 1 (increments).

Example: If user created with id = 5 successfully, and then fails 2 times. Then, next data row created will have id = 8.

So, how can I fix that movement such that id will not move?

0

There are 0 best solutions below