Search code examples
postgresqlgobeego

How to work around 'no LastInsertId available' using beego/orm


I am trying to use https://github.com/astaxie/beego/tree/master/orm to insert a struct into a postgres database. The operation should be simple

import "github.com/astaxie/beego/orm"

type Product struct {
    ID string `orm:"pk"`
    ...
}

product := &Product{ID: productID}
_, err := orm.NewOrm().Insert(product)
if err != nil {
    log.Fatal(err)
}

I keep getting this; no LastInsertId available whenever the code runs (the insert is otherwise successful) but I get a crash. I understand is it due to postgresql limitations because I use https://www.github.com/lib/pq driver.

Is there I way to work around this using beego/orm?


Solution

  • If the crash is being caused by your log.Fatal(err), you can avoid this by checking and avoiding it:

    _, err := orm.NewOrm().Insert(product)
    
    if err != nil {
        if err.Error() == "no LastInsertId available" {
            log.Println(err)
        } else {
            log.Fatal(err)
        }
    }