Why am I getting ErrNoRows("sql: no rows in result set") after inserting into postgres, even when insert was actually successful?
Asked Answered
H

1

9

I am working with golang-postgres:

"database/sql"
_ "github.com/lib/pq"

What I am doing:

I run a select query. If I don't get any entry on selecting, I go ahead and insert one. Else, update, or something else...

The problem is, every time insert returns ErrNoRows("sql: no rows in result set") , even when I can see in database that INSERT was successful, and row was added.

Also lastInsertID always remains 0, while if I check in DB, it has an actual value(say, 131)

It seems as if the error near comment 2 below in the code, is cached somewhere, and shows up again.

// 1. Select first
sQueryStmt, sPrepErr := db.Prepare(selectQuery)
    if sPrepErr != nil {
        glog.V(3).Infof("selectQuery prepare failed. err: %v", sPrepErr)
        return sPrepErr
    }

    queryErr := sQueryStmt.QueryRow(today, itemID).Scan(&a, &b, &c, &d, &e, &f, &g, &h, &i, &j)
    if queryErr != nil {

// 2. Getting ErrNoRows here is expected, for the first entry
        if queryErr == sql.ErrNoRows {
            glog.V(3).Infof("selectQuery returned no results. err: %v", queryErr)

            var lastInsertID int
            iQueryStmt, iPrepErr := db.Prepare(insertQuery)
            if iPrepErr != nil {
                glog.V(3).Infof("insertQuery prepare failed. err: %v", iPrepErr)
                return iPrepErr
            }
            insertErr := iQueryStmt.QueryRow(today, today, today, taskID).Scan(&lastInsertID)
            if insertErr != nil {
                // 3. Somehow, even after row is correctly being created, I am getting insertErr as "sql: no rows in result set" here
                glog.V(3).Infof("insertQuery failed. err: %v", insertErr)
            } else {
// control never comes to this part.
                glog.V(3).Infof("insertQuery Successful. lastInsertID: %v", lastInsertID)
            }
        } else {
            glog.V(3).Infof("Couldn't run query on Postgres database. err: %v", queryErr)
            return queryErr
        }
}

Debugging inside database/sql, shows that it is returning this error in below code block:

    if !r.rows.Next() {
        if err := r.rows.Err(); err != nil {
            return err
        }
        return ErrNoRows
    }

But every time, if I check in DB, the data is always already inserted.

Edit:

selectQuery = `select task_id, creation_date, times_x_ran,
                        a_count, b_count, c_count, d_count, e_count 
                        from reports where creation_date = $1 and task_id = $2`

insertQuery = `insert into reports 
                (creation_date, creation_time, last_modified, task_id, times_x_ran, times_y_ran, a, b, c, d, e, x_errors, y_errors) 
                    values 
                    ($1, $2, $3, $4,
                    1, 0, 
                    0, 0, 0, 0, 0, 
                    '', '' )`
Hulsey answered 27/11, 2018 at 20:39 Comment(5)
Can you show the contents of your queries? the insertQuery/selectQuery strings? I'm asking because you would get this error if your insertQuery doens't have a returning clause, ie. there's nothing to scan.Hamrah
Updated the questionHulsey
Well your insert query doesn't return anything, so calling Scan(&lastInsertedID) is always gonna get you that error.Hamrah
Here's what you need postgresql.org/docs/9.5/dml-returning.htmlHamrah
Great, got it. Thanks mate. I think I just need to add "returning id"Hulsey
T
12

You've effectively asked two questions, so I'll answer both:

  1. Why ErrNoRows even when your insert is successful?

    This is expected behavior, because by default an INSERT returns no rows. Your "error" isn't actually problematic. If you want an INSERT to return rows, you must use a 'RETURNING' clause at the end.

    The fact that the "No rows in result set" state is communicated by way of an error may be the reason for your confusion. But this should only be considered an error if you expected rows.

  2. Also lastInsertID always remains 0.

    This is also expected behavior. As documented:

    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:

Tiemannite answered 28/11, 2018 at 7:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.