Gorm: Cannot get gorm.ErrRecordNotFound when using pointer to slice

Created on 1 Aug 2018  路  3Comments  路  Source: go-gorm/gorm

I expect that can got gorm.ErrRecordNotFound If no record is found when using pointer to slice. And after trace code I noted that https://github.com/jinzhu/gorm/blob/master/callback_query.go#L87-L89 add isSlice bool value to block error setting.

So how can I got no database record found when I using pointer to slice? Thx.

} else if scope.db.RowsAffected == 0 && !isSlice {
                scope.Err(ErrRecordNotFound)
}

What version of Go are you using (go version)?

Latest

Which database and its version are you using?

sqlite

Please provide a complete runnable program to reproduce your issue. IMPORTANT

package main

import (
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
    "fmt"
)

type Product struct {
    gorm.Model
    Code string
    Price uint
}

func main() {
    db, _ := gorm.Open("sqlite3", "test.db")
    defer db.Close()

    // Migrate the schema
    db.AutoMigrate(&Product{})

    // Create
    db.Create(&Product{Code: "L1212", Price: 1000})

    var products []Product
    // No record can be found
    if err:= db.Where(map[string]interface{}{"code": ""}).Find(&products).Error;err!=nil {
        if err == gorm.ErrRecordNotFound {
            //expect getting ErrRecordNotFound error
            fmt.Print("ErrRecordNotFound")
        }
    }

}

Most helpful comment

After I search issue I found https://github.com/jinzhu/gorm/issues/228#issuecomment-281573321 Find a slice won't return error, bug find a struct will.

Can add this to document or consider that make behavior consistency?

All 3 comments

After I search issue I found https://github.com/jinzhu/gorm/issues/228#issuecomment-281573321 Find a slice won't return error, bug find a struct will.

Can add this to document or consider that make behavior consistency?

This is totally unexpected; find on a slice should also return the error.

An example of how real code would look like right now:

        var originalRecords []*Record
    err := db.
        Joins("JOIN records ON records.ext_id = external.id").
        Where(`external."key" = ?`, key).
        Find(&originalRecords).Error
    if err != nil {
        return nil, err
    }
        if len(originalRecords) == 0 {
             return nil, gorm.ErrRecordNotFound
        }
        return originalRecords, nil

Merged #2015 ,close it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fieryorc picture fieryorc  路  3Comments

RadhikaBhat picture RadhikaBhat  路  3Comments

hypertornado picture hypertornado  路  3Comments

bramp picture bramp  路  3Comments

sredxny picture sredxny  路  3Comments