georgysavva / scany

Library for scanning data from a database into Go structs and more
MIT License
1.27k stars 67 forks source link

Scanning one column into pgtype #33

Closed AubSs closed 2 years ago

AubSs commented 3 years ago

How to scan one column (and one or multiple rows) into pgx type ?

I'm getting errors like scany: scan row into struct fields: can't scan into dest[0]: cannot assign &{[some bytes ...] 2} into *[]pgtype.UUID

all my attempts ended in failures ..

-- sql : SELECT array_agg(uuid) FROM ...
var ids pgtype.UUIDArray
if err := pgxscan.Get(ctx, pg.Client(tx), &ids, sql, args...); err != nil {
    return nil, err
}

------ or

-- sql : SELECT uuid FROM ...
var ids []pgtype.UUID
if err := pgxscan.Select(ctx, pg.Client(tx), &ids, sql, args...); err != nil {
    return nil, err
}
georgysavva commented 3 years ago

Hi. Thanks for opening this issue. Currently, it's not possible to scan single-column rows into pgtype like that (as you would do it with string or int). The problem happens because pgtype.UUID is actually a struct and scany treats that case as scanning into a struct.

The workaround for your situation would be the following:

-- sql : SELECT uuid FROM ...
type Row struct {
    ID pgtype.UUID
}
var rows []Row
if err := pgxscan.Select(ctx, pg.Client(tx), &rows, sql, args...); err != nil {
    return nil, err
}
var ids []pgtype.UUID
// extract ids from rows

I will think about some kind of exceptions for scany to support that case without workarounds.

AubSs commented 3 years ago

Ok, thx !

georgysavva commented 2 years ago

@AubSs Hi! I just released a new version of scany that now includes this feature.

AubSs commented 2 years ago

@georgysavva Hello! I just use the new functionality, and it's perfectly working! Many thanks to you!