Search code examples
postgresqlgopgx

Go, pgx: SELECT query returns only one row


Golang, pgx: I am trying to get all rows from t_example (currently 20 items), however for some reason only one returns (the first one). I tried to debug and rows.Next() returns false after the first iteration. Could you please help me with advice?

I'm a newbie, but I've tried to find similar cases here in advance :)

My code:

func (ts *exampleStorage) GetAll() *[]Example {
q := `SELECT id, name FROM t_example`

rows := ts.client.Query(context.Background(), q)

example := make([]Example, 0)

for rows.Next() {
    var ex Example
    rows.Scan(&ex.Id, &ex.Name)
    example = append(example, ex)
}

return &example
}

Solution

  • Your code doesn't check for errors :

    • row.Scan(&ex.Id, &ex.Name) could return an error (and, in pgx implementation, this error is fatal for the rows iteration) :
        err := rows.Scan(&ex.Id, &ex.Name)
        if err != nil {
            fmt.Printf("*** rows.Scan error: %s", err)
            return nil, err
        }
    
    • there is a gotcha with sql.Rows / pgx.Rows error checking : you should check if an error occurred after exiting the for rows.Next() { loop :
    
    for rows.Next() {
        ...
    }
    // check rows.Err() after the last rows.Next() :
    if err := rows.Err(); err != nil {
        // on top of errors triggered by bad conditions on the 'rows.Scan()' call,
        // there could also be some bad things like a truncated response because
        // of some network error, etc ...
        fmt.Printf("*** iteration error: %s", err)
        return nil, err
    }
    
    return example, nil
    

    a side note : in the vast majority of cases you don't want to return a pointer to a slice (e.g: *[]Example) but a slice (e.g: []Example)