jackc / pgx

PostgreSQL driver and toolkit for Go
MIT License
10.83k stars 845 forks source link

rows.scan stops when encountering a null value #2149

Open prr123 opened 1 month ago

prr123 commented 1 month ago

Describe the bug The program stops execution without an error message when executin rows.scan which contains results with a null value. I was able to work around by using coalesce in the sql statement.

*To Reproduce** I created a table with three columns column_name | data_type | character_maximum_length -------------+-------------------+-------------------------- user_id | integer | first | character varying | 15 last | character varying | 25

sql: select column_name, data_type, character_maximum_length from information_schema.columns where table_name = 'person';

when using pgx.Query to execute the same query, the execution stops when scanning the resulting rows:

If possible, please provide runnable example such as:

package main

import (
    "context"
    "log"
    "os"

    "github.com/jackc/pgx/v5"
)

func main() {
       ctx := context.Background()
    dbcon, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
    if err != nil {
        log.Fatal(err)
    }
    defer dbcon.Close(ctx)

    var ColNam, DTyp string
    var MaxChars int

    tbl := "person"
    query := "select column_name, data_type, character_maximum_length from information_schema.columns where table_name=$1;"

    rows, err := dbcon.Query(ctx, query, tbl)
    if err != nil {
        fmt.Printf("error -- query failed: %v\n", err)
        os.Exit(1)
    }
    fmt.Printf("query success\n%v\n", rows)

    count :=0
    for rows.Next() {
        fmt.Printf("scanning row[%d]\n", count)
        count++
        err = rows.Scan(&ColNam, &DTyp, &MaxChars)
        if err != nil {
            fmt.Errorf("error row[%d] -- unable to scan row: %w", count, err)
            os.Exit(1)
        }
        fmt.Printf("row[%d]: %-15s %-20s %d\n", count, ColNam, DTyp, MaxChars)
    }

}

Please run your example with the race detector enabled. For example, go run -race main.go or go test -race.

Expected behavior I expected a code completion wiyht a nil for the DTyp. Alertnatively a return with an error message.

Actual behavior The program ends in the middle of the code witout returning an error message.

Version

jackc commented 1 month ago

You need to check rows.Err() after the rows.Next() loop completes.