sql.Row doubt

265 views
Skip to first unread message

Daniel da Silva

unread,
Aug 5, 2021, 1:34:54 PM8/5/21
to golang-nuts
Hello guys!

Why doesn't sql.Row implement the Columns() method? 

Thanks!

Eli Bendersky

unread,
Aug 5, 2021, 2:43:44 PM8/5/21
to Daniel da Silva, golang-nuts
In what case do you find the need to call Columns() on a Row? Generally if you have access to a Row, you also have access to a Rows, which does have a Columns() method.

Eli

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/1c521514-d267-456c-a66a-e56544965fd3n%40googlegroups.com.

Daniel da Silva

unread,
Aug 13, 2021, 7:42:08 AM8/13/21
to golang-nuts
Yes i ever use Query() instead of QueryRow(). 
My doubt is more about the API design.
If exists *sql.Row with Scan() method why not implements Columns() ?

daniel...@omie.com.br

unread,
Aug 13, 2021, 1:04:24 PM8/13/21
to golang-nuts
Yes i ever use Query() instead of QueryRow(). 
My doubt is more about the API design.
If exists *sql.Row with Scan() method why not implements Columns() ?

On Thursday, August 5, 2021 at 3:43:44 PM UTC-3 eli...@gmail.com wrote:

Tamás Gulácsi

unread,
Aug 14, 2021, 4:08:12 AM8/14/21
to golang-nuts
It could, but what for? sql.Row is already a convenience wrapper for I-know-I-want-only-one-row,
so you know what kind of data are you retrieving, but you know it's only one row?

Daniel da Silva

unread,
Aug 14, 2021, 9:43:01 AM8/14/21
to golang-nuts
I know my resultset will only have one row. But I don't know about columns. e.g.

func GetData(db *sql.DB, ent Entity, tableName, uniqueField string, value interface{}) error {
    query := fmt.Sprintf("SELECT * FROM %s WHERE %s = $1", tableName, uniqueField)

    row := db.QueryRow(query, value)

    columns := []string{} // columns, err := row.Columns()

    if err := row.Scan(ent.Pointers(columns)...); err != nil {
        return err
    }

    return nil
}

Gregor Best

unread,
Aug 17, 2021, 3:37:43 AM8/17/21
to Daniel da Silva, golang-nuts

FWIW, things like `SELECT * FROM ...` are in my opinion a code smell: there are usually some (implicit) expectations on which columns will be returned in what order that'll break horribly if someone two departments removed decides "this table needs another column".

In my experience, it's almost always better to explicitly encode queries (or build them with a query builder) than to build them manually at run time.

Reply all
Reply to author
Forward
0 new messages