Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return an error when no rows are returned by a query that is expected to return multiple rows

I have the code snippet below, the idea is to get the loyalty points of a customer from all our warehouses. There is a possibility that a customer will have an id but is not registered for loyalty.

Using that customer’s id will cause the query below to return zero rows, which is not an error.

I would like to return an error when that happens so that I can handle it later.
I am looking for the best possible way to do this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am new to programming and golang, I don’t really know my way around just yet.

query := `select coalesce(lc.total_points, 0), 
        w.machine_name from 
        lcustomerpoints lc
        join warehouses w
        on lc.machine_ip = w.machine_ip
        where lc.loyaltycard_number = $1;`

    rows, err := l.DB.Query(query, user_id)
    if err != nil {
        return nil, err
    }

    defer rows.Close()

    loyaltyPoints := []*LoyaltyPoint{}

    for rows.Next() {
        l := LoyaltyPoint{}

        err := rows.Scan(&l.Points, &l.Outlet)
        if err != nil {
            return nil, err
        }

        loyaltyPoints = append(loyaltyPoints, &l)

    }

    if err = rows.Err(); err != nil {
        return nil, err
    }

>Solution :

Count the number of times the for loop iterates:

    count := 0
    for rows.Next() {
        count++
        ...
    }
    if count == 0 {
       return fmt.Errorf("Got 0 rows from query")
    }

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading