scan

package
v0.11.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 21, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package scan provides helpers for mapping pgx query results to Go structs.

Mapping is explicit: callers supply a RowMapper that returns field pointers in the same order as the SELECT columns. No reflection is used.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Row

func Row[T any](row pgx.Row, mapper RowMapper[T]) (T, error)

Row scans a single pgx.Row into a value of type T using mapper.

Example
package main

import (
	"context"
	"log"

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

	"github.com/benaskins/axon-base/scan"
)

// User is an example domain type used to illustrate scan usage.
type User struct {
	ID   string
	Name string
	Age  int
}

func main() {
	ctx := context.Background()
	db, err := pgxpool.New(ctx, "postgres://postgres@localhost:5432/mydb")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	row := db.QueryRow(ctx, "SELECT id, name, age FROM users WHERE id = $1", "abc")
	user, err := scan.Row(row, func(u *User) []any {
		return []any{&u.ID, &u.Name, &u.Age}
	})
	if err != nil {
		log.Fatal(err)
	}
	_ = user
}

func Rows

func Rows[T any](rows pgx.Rows, mapper RowMapper[T]) ([]T, error)

Rows scans all rows into a slice of T using mapper. The rows are closed before returning.

Example
package main

import (
	"context"
	"log"

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

	"github.com/benaskins/axon-base/scan"
)

// User is an example domain type used to illustrate scan usage.
type User struct {
	ID   string
	Name string
	Age  int
}

func main() {
	ctx := context.Background()
	db, err := pgxpool.New(ctx, "postgres://postgres@localhost:5432/mydb")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	rows, err := db.Query(ctx, "SELECT id, name, age FROM users ORDER BY name")
	if err != nil {
		log.Fatal(err)
	}
	users, err := scan.Rows(rows, func(u *User) []any {
		return []any{&u.ID, &u.Name, &u.Age}
	})
	if err != nil {
		log.Fatal(err)
	}
	_ = users
}

Types

type RowMapper

type RowMapper[T any] func(*T) []any

RowMapper returns a slice of destination pointers for the given struct, ordered to match the query's SELECT columns.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL