jmoiron / sqlx

general purpose extensions to golang's database/sql
http://jmoiron.github.io/sqlx/
MIT License
16.3k stars 1.09k forks source link

StructScan into array of string #877

Open dennissetiawan opened 1 year ago

dennissetiawan commented 1 year ago

I have this snippet of code that works correctly when scanning varchar[] into []string in postgresql

type OrderDB struct {
    ID                string               `db:"id"`
    Users     []string             `db:"users"`
}

rows, err := tx.QueryxContext(ctx, query, args...)
    if err != nil {
        return nil, tracerr.Wrap(err)
    }
    defer rows.Close()

    var orderDB OrderDB

    for rows.Next() {
        err = rows.Scan(
            &orderDB.ID,
            pq.Array(&orderDB.Users),
        )
        if err != nil {
            return nil, tracerr.Wrap(err)
        }

    }

But i want to use StructScan instead, what should i do? I know that we can make an alias for []string and implement the Scan method like

type StringArrayDB []string
func (u *StringArrayDB) Scan(v interface{}) error {
    return pq.GenericArray{A: u}.Scan(v)
}

but i still got error like pq: parsing array element index 0: pq: scanning to string is not implemented; only sql.Scanner,

what should i do? and i think this should be handled in structscan?