Search code examples
databasegogo-gorm

How to check if the value is existing in DB


How do I check if the value that I want to insert is existing in database or not

Let say I have


type studentRepository struct {
    db *gorm.DB
}

type Student struct {
    Name string     `json:"name"`
    Age int         `json:"age"`
}

func(s student) CreateStudent(v Student) (*Student, error) {
    db := p.db.Create(&v)
    return &v, db.Error
}

I want to create new student but cannot have the same name with other students. How can I check if the name that I want to insert is not existing in the db?

Example: 
StudentList = {Messi, Ronaldo, Tevez}
WantToInsert = {Ronaldo}
Result = Cannot happened because Ronaldo is existing on the list

Solution

  • you can prevent inputting the same value by creating "unique" constraint in your SQL database , Gorm allows that adding unique keyword to your struct:

    type Student struct {
        Name string     `json:"name" gorm:"unique"`
        Age int         `json:"age"`
    }
    

    you can refer to Gorm's documentation for more details: Gorm indexing documentation

    you can also catch duplicate error for logging purposes the implementation differs depending on the database you're using, this example works in the case of using Postgresql:

    err := db.Create(student).Error
    
    if err != nil {
        var pgErr *pgconn.PgError
        if errors.As(err, &pgErr) && (pgErr.Code == "23505") {
            // handle error here
        }
    }