Search code examples
databasepostgresqlgogo-gormpq

RETURNING must contain at least one value


I'm learning to use PostgreSQL and GORM. Trouble came relatively quickly, and it feels as if I'm the only one having this problem ever.

Here, I'm creating a struct, instantiating it, and trying to write it to database. However, it returns an error:

pq: RETURNING must contain at least one value

Tried googling it, and the only thing I found is Postgres source code which might as well be in Chinese.

Source code:

db, err := gorm.Open("postgres", "user=postgres dbname=testdb sslmode=disable password=qwerty")
if err != nil {
    panic(err.Error())
}
defer db.Close()

database := db.DB()

err = database.Ping()
if err != nil {
    panic(err.Error())
}

db.AutoMigrate(&Currency{})

fmt.Println("Connection to PostgreSQL was successful!")

testCur := Currency{"shekels", 20}
if db.NewRecord(testCur) {
    err := db.Create(&testCur).Error
    if err != nil {
        panic(err.Error())
    }
}

Struct:

type Currency struct {
name string
rate uint
}

And yes, it must be done with Postgres and GORM. Database is brand new, empty.


Solution

  • One thing that stands out is that your struct only contains non-exported fields:

    type Currency struct {
        name string
        rate uint
    }
    

    Neither of those fields will be visible to Gorm (which presumably uses reflection to convert your struct to SQL). That would lead to Gorm trying to do an empty INSERT with a RETURNING clause to get something back but, since Gorm can't see anything to INSERT it won't be asking for anything in the RETURNING clause and there's your rather confusing error.

    I think you'll have better luck if you fix your struct to export those fields:

    type Currency struct {
        Name string
        Rate uint
    }