I am having a problem with this library because this function returns false even when the given input is not in the database, when in fact it should return true.
type User struct {
ID uint `gorm:"primary_key"`
Username string `json:",omitempty"`
Password string `json:",omitempty"`
CreatedAt time.Time `json:",omitempty"`
}
b, err := db.Con()
if err != nil {
log.Panic(err)
}
defer db.Close()
// We want an empty struct
// Otherwise it will trigger the unique key constraint
user := []User{}
// Check if the username is taken
// BUX, MUST FIX: This always returns false for some reason
if db.Where(&User{Username: "MyUsername"}).Find(&user).RecordNotFound() == false {
fmt.Println("Username found")
}
Why is it always returning false, even when the string is empty?
So return nullif it is can happen in your domain, that records do not exist (in my experience this is most often the case). If you expect a record to exist and it is not there, then it is valid to throw an exception. Share Follow answered Aug 27 '16 at 19:40
This has many advantages including that when you have no records it is an empty array. So when you have records, you would be returning: And when you have no records, you would be returning: Show activity on this post.
@chrismarx: If your query returns no row (nothing at all), there is no place for a function to catch that. So we need an outer SELECT - and then we don't even need a function. This works in DB2 as well, provided you substitute DUAL with SYSIBM.SYSDUMMY1. To make it more simplier, this should work fine.
If you return nullthen it will be a normal and 'non exceptional' state in your model. So return nullif it is can happen in your domain, that records do not exist (in my experience this is most often the case). If you expect a record to exist and it is not there, then it is valid to throw an exception.
Looks like .RecordNotFound(
) is removed from the SDK for some reason.
Now use this for handling record not found errors
dbRresult := userHandler.db.Where("email = ?", email).First(&user)
if errors.Is(dbRresult.Error, gorm.ErrRecordNotFound) {
// handle record not found
}
The following code should work as you expect it:
// We want an empty struct
user := User{} // We expect to have one (or no) user returned.
// Check if the username is taken
// Notice the use of First() instead of Find()
if !db.Where("username = ?", "MyUsername").First(&user).RecordNotFound() {
fmt.Println("Username found, here's the user:", user)
} else {
fmt.Println("Username not found")
}
As mkopriva already mentioned the ErrRecordNotFound
will not trigger when you're working with slices.
Since you don't need slices (your username should be unique) we can:
Reference not a slice of Users but a single User User{}
instead of []User{}
.
Use gorms
First()
method instead of Find()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With