Is LastInsertId for pg broken?

I’m a golang begginer I really like the language but I can’t figure out why this refuses to work and promps me that there is no lastInstertedId. I’m using the sqlx package I also tried experimenting with the default sql one and I got pretty much the same error

type User struct {
    ID    int `db:"id" json:"id"`
    Name  string `db:"name" json:"name"`
    Hash  string `db:"hash" json:"-"`
}

func (u *User) Create() (int, error) {

res, err := db.NamedExec("insert into users (name, hash) values (:name, :hash) RETURNING users.id", u)

if err != nil {
  return 0, err
}

lastID, err := res.LastInsertId()

if err != nil {
  return 0, err 
}


return int(lastID), nil

}

I run it as following

var me m.User

me.Name = "ayyllxdamo"
me.Hash = "adsa$axdxsdax"

ID, err := me.Create()

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

the user does get inserted.
when I run the query (manually) on the database I do get a table with an id column back.

so what could be the issue?

You can’t use NamedExec here, as that does not return anything. You would have to use Query or NamedQuery.

Using RETURING users.id is correct.

1 Like

You can’t use NamedExec here, as that does not return anything.

thats weird I mean it does seem to a return a thing with a .LastInsertId() method.

You would have to use Query or NamedQuery.

but yeah, that did the trick, thanks.

That is because the database/sql interface is generic. Some databases, such as MySQL, return a LastInsertID when you exec an INSERT query. Some, such as PostgreSQL, don’t.

2 Likes

Assuming you’re using pq, this is documented behavior.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.