0

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?

marsrover
  • 715
  • 11
  • 27

1 Answers1

3

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)
jcbwlkr
  • 7,789
  • 2
  • 22
  • 28
  • I read elsewhere that Exec was recommended for all Insert/Update transactions but this actually seems to work, so thank you. – marsrover Oct 04 '16 at 18:12
  • @marsrover yeah normally you'd use Exec but postgres plus `RETURNING` is just special. I'm glad I could help. – jcbwlkr Oct 04 '16 at 18:31