Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scan a QueryRow into a struct with pgx

Tags:

psql

struct

go

pgx

We are using a user struct with alot of fields as follow :

type user struct {
    ID       int    `json:"id,omitempty"`
    UUID     string `json:"uuid,omitempty"`
    Role     int    `json:"role,omitempty"`
    Name     string `json:"name,omitempty"`
    Surname  string `json:"surname,omitempty"`
    Phone    string `json:"phone,omitempty"`
    Email    string `json:"email,omitempty"`
    Street   string `json:"street,omitempty"`
    City     string `json:"city,omitempty"`
    Password string `json:"password,omitempty"`
}

And a function to get a user by its email :

func getUserByEmail(email string) (u user, err error) {
    row := db.Psql.QueryRow(
        context.Background(),
        "SELECT * FROM users WHERE email=$1",
        email)
    err = row.Scan(&u.ID, &u.UUID, &u.Role, &u.Name, &u.Surname, &u.Phone, &u.Email, &u.Street, &u.City, &u.Password)
    if err != nil {
        log.Fatal(err)
    }
    return
}

Is there a way to scan directly to a struct rather than all of its property ? Ideally :

row.Scan(&u)
like image 266
Ado Ren Avatar asked May 09 '20 22:05

Ado Ren


2 Answers

There is another library scany. It works with pgx native interface and with database/sql as well:

package main

import (
    "context"

    "github.com/jackc/pgx/v4/pgxpool"

    "github.com/georgysavva/scany/pgxscan"
)

type User struct {
    ID    string
    Name  string
    Email string
    Age   int
}

func main() {
    ctx := context.Background()
    db, _ := pgxpool.Connect(ctx, "example-connection-url")

    var users []*User
    pgxscan.Select(ctx, db, &users, `SELECT id, name, email, age FROM users`)
    // users variable now contains data from all rows.
}

It's well tested and documented and has much fewer concepts than sqlx.

Disclaimer, I am the author of this library.

like image 163
Georgy Savva Avatar answered Sep 18 '22 10:09

Georgy Savva


Not with plain database/sql but there is an extension library called sqlx that builds on top of database/sql and adds some useful extensions such as row unmarshalling into structs (including nested), slices and arrays:

type Place struct {
    Country       string
    City          sql.NullString
    TelephoneCode int `db:"telcode"`
}

rows, err := db.Queryx("SELECT * FROM place")
for rows.Next() {
    var p Place
    err = rows.StructScan(&p)
}

See documentation and look for StructScan.

like image 41
blami Avatar answered Sep 19 '22 10:09

blami