Skip to content

Instantly share code, notes, and snippets.

@nilsmagnus
Created May 12, 2022 04:56
Show Gist options
  • Save nilsmagnus/29f4cf356d450a7cde37523693e95605 to your computer and use it in GitHub Desktop.
Save nilsmagnus/29f4cf356d450a7cde37523693e95605 to your computer and use it in GitHub Desktop.
Function to return id from postgresql query
package pgsql-helper
import (
"database/sql"
"fmt"
)
//ExecReturningId executes query and returns id.
// The query must specify what field is returned.
// Example:
//
// id, err := ExecReturningId(db, "insert into user(name) values($1) returning id", "Nils Larsgård")
// log.Printf("Inserted row with id %d with result %v", id, err)
//
func ExecReturningId(db *sql.DB, query string, args ...interface{}) (int, error) {
id := -1
result, err := db.Query(query, args...)
if err != nil {
return id, err
}
if result.Next() {
err = result.Scan(&id)
if err != nil {
return id, err
}
return id, nil
} else {
return id, fmt.Errorf("no rows returned from query %q", query)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment