Search code examples
postgresqlgopq

Go with Postgres: LastInsertedId for non sequential identifiers


I´m writing a small web service in Go which uses Postgres through the pq driver package.

I´m using a uuid´s as identifier for my models so LastInsertId won´t work.

So I´m thinking I could something like this:

  var id string
  res, err := session.Exec("INSERT INTO todos (text, list_id) VALUES ($1, $2) RETURNING todo_id", text, listId).Scan(&id)

Scan does seem to play well with Exec.

So how do I return the uuid from my new todo row?


Solution

  • From https://godoc.org/github.com/lib/pq#hdr-Queries it looks like you should use QueryRow instead of Exec

    pq does not support the LastInsertId() method of the Result type in database/sql. To return the identifier of an INSERT (or UPDATE or DELETE), use the Postgres RETURNING clause with a standard Query or QueryRow call:

    var userid int
    err := db.QueryRow(`INSERT INTO users(name, favorite_fruit, age)
        VALUES('beatrice', 'starfruit', 93) RETURNING id`).Scan(&userid)