jackc / pgx

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

Pgx Scan bool Type is Always False #2131

Closed marcopolooo closed 1 month ago

marcopolooo commented 1 month ago

Hello, I have problem when I scan boolean type from sql, this example of data:

date exist 01092024 true 02092024 true 03092024 true 04092024 true 05092024 true ...

The problem is: The output of exist is always false when we scan to bool type like this:

{
    "status": 200,
    "message": "Success",
    "data": {
        "01092024": false,
        "02092024": false,
        "03092024": false,
        "04092024": false,
        "05092024": false,
        "06092024": false,
        "07092024": false,
        "08092024": false,
        "09092024": false,
        "10092024": false,
        "11092024": false,
        "12092024": false,
        "13092024": false,
        "14092024": false,
        "15092024": false
    }
}

My example code:

        type resultMapRow struct {
        Date   *string `db:"date"`
        Exists *bool   `db:"exists"`
    }

        var result = map[string]bool{}
    rows, err := repo.Db.Query(
        context.Background(),
        price.PriceExist2,
        pgx.NamedArgs{
            "provinceId":  params.ProvinceId,
            "commodityId": params.CommodityId,
            "startDate":   params.StartDate,
            "endDate":     params.EndDate,
        },
    )

    for rows.Next() {
        var resultMapRow2 resultMapRow
        err = rows.Scan(
            &resultMapRow2.Date,
            &resultMapRow2.Exists,
        )
        if err != nil {
            return nil, err
        }

        result[*resultMapRow2.Date] = *resultMapRow2.Exists
    }
    if err != nil {
        log.Error("QueryErrors:", err)
        return nil, err
    }

Thanks in advance for your help.

jackc commented 1 month ago

result[*resultMapRow2.Date] = *resultMapRow2.Exists - I'm not sure why you would need to dereference a pointer here, but my guess is that is leftover from your original source code. Nothing else looks out of the ordinary.

I think you would need to reduce this to a standalone example someone else can run for anyone to be able to help you more.

marcopolooo commented 1 month ago

result[*resultMapRow2.Date] = *resultMapRow2.Exists - I'm not sure why you would need to dereference a pointer here, but my guess is that is leftover from your original source code. Nothing else looks out of the ordinary.

I think you would need to reduce this to a standalone example someone else can run for anyone to be able to help you more.

Hello Jack, thank you so much for your response. I've checked again, I'm sorry this my query mistake, thanks for your help.