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.
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
}
CodePudding user response:
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")
}