package pq import ( "database/sql" "fmt" "testing" ) // Inserting a row with RETURNING and violating a unique, or foreign key // constraint should return the *pq.Error, not sql.ErrNoRows, I believe // the root cause of this issue is inside the database/sql package itself // as it counts the returned rows before checking for errors returned. // // http://golang.org/src/pkg/database/sql/sql.go around line #1424 // // I had seen mention of this issue somewhere in the lib/pq issue tracker // and a link to a Gist with a workaround, as well as some discussion about // how eaigner\s hood ORM had worked around this. func Test_RaisingPqErrorOnQueryRowConstraintViolation(t *testing.T) { var returned string db := openTestConn(t) defer db.Close() _, err := db.Exec("CREATE TEMP TABLE pqerronviolateconstraint (a varchar(3) not null UNIQUE)") if err != nil { t.Fatal(err) } err = db.QueryRow("INSERT INTO pqerronviolateconstraint(a) values($1) RETURNING a", "abc").Scan(&returned) if err != nil { t.Fatal(err) } err = db.QueryRow("INSERT INTO pqerronviolateconstraint(a) values($1) RETURNING a", "abc").Scan(&returned) if err == sql.ErrNoRows { t.Fatal(err) } }