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)
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With