CodeSampleX

Exemple

github.com/jackc/pgx/v5 v5.10.0: Rows

Échantillon vérifié pour golang github.com/jackc/pgx/v5 v5.10.0: Rows. Le contrat s'est exécuté sur go 1.26 · linux alpine/x64 · docker et a réussi.

sha256:bd36a77d5941f0ff9628cca9dfdff4a16e07790b2e3654c98440805e48f72eb7

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-23

Cas

HOW
Objectif
verify github.com/jackc/pgx/v5.Rows in pkg:golang/github.com/jackc/pgx/v5@v5.10.0
Paquets
Symboles
  • github.com/jackc/pgx/v5.Rows
Environnement
go 1.26.6
Créé
2026-08-23T14:56:27Z

Contrat

  1. MemoryRows implements the pgx.Rows interface providing FieldDescriptions, Next, Scan, Values, RawValues, CommandTag, Err, Close, and Conn
  2. pgx.Rows Next and Scan iterate and decode positional column values into Go typed destination pointers
  3. pgx.Rows Values and RawValues return decoded any slices and raw byte slices for the active row
  4. pgx.Rows Scan supports nil destinations to skip column decoding without error
  5. pgx.Rows Scan returns ScanArgError with column index and field name when destination type is incompatible
  6. pgx.CollectRows, pgx.CollectOneRow, and pgx.ForEachRow process pgx.Rows result sets offline
  7. pgx.RowToMap and pgx.RowToStructByName map active row values into map and struct instances via pgx.Rows and pgx.RowScanner
  8. pgx.Rows Close is idempotent and Err preserves errors after closure

Fichiers

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • sample.go
  • spec.json
  • test/contract.go

Télécharger l’artefact source (tar.gz)

Code source

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify github.com/jackc/pgx/v5.Rows in pkg:golang/github.com/jackc/pgx/v5@v5.10.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/jackc/pgx/v5@v5.10.0
Demonstrate these symbols/APIs:
  - github.com/jackc/pgx/v5.Rows

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:233a2ebcc3444f870ddd74dc9b500552f15c2f030e82f7a4fdfac1929907a45c","contract":["MemoryRows implements the pgx.Rows interface providing FieldDescriptions, Next, Scan, Values, RawValues, CommandTag, Err, Close, and Conn","pgx.Rows Next and Scan iterate and decode positional column values into Go typed destination pointers","pgx.Rows Values and RawValues return decoded any slices and raw byte slices for the active row","pgx.Rows Scan supports nil destinations to skip column decoding without error","pgx.Rows Scan returns ScanArgError with column index and field name when destination type is incompatible","pgx.CollectRows, pgx.CollectOneRow, and pgx.ForEachRow process pgx.Rows result sets offline","pgx.RowToMap and pgx.RowToStructByName map active row values into map and struct instances via pgx.Rows and pgx.RowScanner","pgx.Rows Close is idempotent and Err preserves errors after closure"],"goal":"verify github.com/jackc/pgx/v5.Rows in pkg:golang/github.com/jackc/pgx/v5@v5.10.0","kind":"HOW","packages":["pkg:golang/github.com/jackc/pgx/v5@v5.10.0"],"schemaVersion":1,"symbols":["github.com/jackc/pgx/v5.Rows"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/jackc/pgx/v5@v5.10.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/jackc/pgx/v5@v5.10.0","symbols":["github.com/jackc/pgx/v5.Rows"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/jackc/pgx/v5 v5.10.0

require (
	github.com/jackc/pgpassfile v1.0.0 // indirect
	github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
	golang.org/x/text v0.29.0 // indirect
)
go.sum
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
sample.go
package sample

import (
	"errors"
	"fmt"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgtype"
)

// MemoryRows is an in-memory implementation of pgx.Rows for testing, mocking,
// and offline result set processing without requiring a live PostgreSQL connection.
type MemoryRows struct {
	fields     []pgconn.FieldDescription
	data       [][][]byte
	typeMap    *pgtype.Map
	commandTag pgconn.CommandTag
	err        error
	index      int
	closed     bool
}

// Ensure MemoryRows statically implements the pgx.Rows interface.
var _ pgx.Rows = (*MemoryRows)(nil)

// NewMemoryRows creates a new MemoryRows instance from field descriptions and raw byte matrix.
func NewMemoryRows(fields []pgconn.FieldDescription, data [][][]byte, commandTag pgconn.CommandTag, typeMap *pgtype.Map) *MemoryRows {
	if typeMap == nil {
		typeMap = pgtype.NewMap()
	}
	return &MemoryRows{
		fields:     fields,
		data:       data,
		typeMap:    typeMap,
		commandTag: commandTag,
		index:      -1,
	}
}

// NewTextRows creates a MemoryRows instance populated with text-formatted string values.
func NewTextRows(colNames []string, colOIDs []uint32, stringRows [][]string, commandTag pgconn.CommandTag) (*MemoryRows, error) {
	if len(colNames) != len(colOIDs) {
		return nil, fmt.Errorf("length mismatch between column names (%d) and OIDs (%d)", len(colNames), len(colOIDs))
	}

	fields := make([]pgconn.FieldDescription, len(colNames))
	for i := range colNames {
		fields[i] = pgconn.FieldDescription{
			Name:        colNames[i],
			DataTypeOID: colOIDs[i],
			Format:      0, // Text format
		}
	}

	data := make([][][]byte, len(stringRows))
	for r, row := range stringRows {
		if len(row) != len(colNames) {
			return nil, fmt.Errorf("row %d has %d columns, expected %d", r, len(row), len(colNames))
		}
		data[r] = make([][]byte, len(row))
		for c, cell := range row {
			data[r][c] = []byte(cell)
		}
	}

	return NewMemoryRows(fields, data, commandTag, pgtype.NewMap()), nil
}

// FieldDescriptions returns the description of all columns in the result set.
func (r *MemoryRows) FieldDescriptions() []pgconn.FieldDescription {
	return r.fields
}

// Next advances the cursor to the next row. Returns true if another row exists, false otherwise.
// Automatically closes the rows when no more rows remain.
func (r *MemoryRows) Next() bool {
	if r.closed || r.err != nil {
		return false
	}

	r.index++
	if r.index < len(r.data) {
		return true
	}

	r.Close()
	return false
}

// Scan decodes column values of the active row into dest pointers positionally,
// or delegates to pgx.RowScanner when a single custom scanner is provided.
func (r *MemoryRows) Scan(dest ...any) error {
	if r.closed {
		return errors.New("cannot scan closed rows")
	}
	if r.index < 0 || r.index >= len(r.data) {
		return errors.New("scan called before Next() or after end of rows")
	}

	if len(dest) == 1 {
		if rc, ok := dest[0].(pgx.RowScanner); ok {
			err := rc.ScanRow(r)
			if err != nil {
				r.err = err
				r.Close()
				return err
			}
			return nil
		}
	}

	currentRow := r.data[r.index]
	err := pgx.ScanRow(r.typeMap, r.fields, currentRow, dest...)
	if err != nil {
		r.err = err
		r.Close()
		return err
	}

	return nil
}

// Values returns the decoded column values for the active row.
func (r *MemoryRows) Values() ([]any, error) {
	if r.closed {
		return nil, errors.New("cannot read values from closed rows")
	}
	if r.index < 0 || r.index >= len(r.data) {
		return nil, errors.New("values called before Next() or after end of rows")
	}

	currentRow := r.data[r.index]
	values := make([]any, len(r.fields))

	for i := range r.fields {
		buf := currentRow[i]
		if buf == nil {
			values[i] = nil
			continue
		}

		if dt, ok := r.typeMap.TypeForOID(r.fields[i].DataTypeOID); ok {
			val, err := dt.Codec.DecodeValue(r.typeMap, r.fields[i].DataTypeOID, r.fields[i].Format, buf)
			if err != nil {
				r.err = err
				r.Close()
				return nil, err
			}
			values[i] = val
		} else {
			values[i] = string(buf)
		}
	}

	return values, nil
}

// RawValues returns the unparsed byte buffers of the active row.
func (r *MemoryRows) RawValues() [][]byte {
	if r.closed || r.index < 0 || r.index >= len(r.data) {
		return nil
	}
	return r.data[r.index]
}

// CommandTag returns the command tag from the executed query.
func (r *MemoryRows) CommandTag() pgconn.CommandTag {
	return r.commandTag
}

// Err returns any error encountered during iteration or scanning.
func (r *MemoryRows) Err() error {
	return r.err
}

// Close marks the rows closed. It is idempotent.
func (r *MemoryRows) Close() {
	r.closed = true
}

// Conn returns nil as MemoryRows is self-contained and not tied to a network socket.
func (r *MemoryRows) Conn() *pgx.Conn {
	return nil
}

// CollectRowMaps collects all remaining rows into a slice of column-name to value maps.
func CollectRowMaps(rows pgx.Rows) ([]map[string]any, error) {
	return pgx.CollectRows(rows, pgx.RowToMap)
}

// CollectStructsByName collects all remaining rows into a slice of structs mapped by column names.
func CollectStructsByName[T any](rows pgx.Rows) ([]T, error) {
	return pgx.CollectRows(rows, pgx.RowToStructByName[T])
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/jackc/pgx/v5.Rows in pkg:golang/github.com/jackc/pgx/v5@v5.10.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/jackc/pgx/v5@v5.10.0"
  ],
  "symbols": [
    "github.com/jackc/pgx/v5.Rows"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"errors"
	"fmt"
	"os"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgtype"
	"sample"
)

type Account struct {
	ID       int32  `db:"id"`
	Username string `db:"username"`
	Balance  int64  `db:"balance"`
	Active   bool   `db:"is_active"`
}

func main() {
	colNames := []string{"id", "username", "balance", "is_active"}
	colOIDs := []uint32{pgtype.Int4OID, pgtype.TextOID, pgtype.Int8OID, pgtype.BoolOID}
	rowsData := [][]string{
		{"101", "carol", "5000", "t"},
		{"102", "dave", "7500", "f"},
		{"103", "eve", "12000", "t"},
	}

	cmdTag := pgconn.NewCommandTag("SELECT 3")

	// Assertion 1: MemoryRows implements the pgx.Rows interface
	var _ pgx.Rows = (*sample.MemoryRows)(nil)

	rows, err := sample.NewTextRows(colNames, colOIDs, rowsData, cmdTag)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL [setup]: NewTextRows returned error: %v\n", err)
		os.Exit(1)
	}

	// Verify FieldDescriptions before/during iteration
	fields := rows.FieldDescriptions()
	if len(fields) != 4 || fields[0].Name != "id" || fields[1].Name != "username" {
		fmt.Fprintf(os.Stderr, "FAIL [1]: FieldDescriptions mismatch: %+v\n", fields)
		os.Exit(1)
	}

	// Assertion 2: Iterating with Next() and Scan() decodes typed column values and advances through all rows
	var scanned []Account
	for rows.Next() {
		var acc Account
		err := rows.Scan(&acc.ID, &acc.Username, &acc.Balance, &acc.Active)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL [2]: Scan failed: %v\n", err)
			os.Exit(1)
		}
		scanned = append(scanned, acc)
	}

	if len(scanned) != 3 {
		fmt.Fprintf(os.Stderr, "FAIL [2]: expected 3 scanned accounts, got %d\n", len(scanned))
		os.Exit(1)
	}
	if scanned[0].ID != 101 || scanned[0].Username != "carol" || scanned[0].Balance != 5000 || !scanned[0].Active {
		fmt.Fprintf(os.Stderr, "FAIL [2]: row 0 mismatch: %+v\n", scanned[0])
		os.Exit(1)
	}
	if scanned[1].ID != 102 || scanned[1].Username != "dave" || scanned[1].Balance != 7500 || scanned[1].Active {
		fmt.Fprintf(os.Stderr, "FAIL [2]: row 1 mismatch: %+v\n", scanned[1])
		os.Exit(1)
	}
	if scanned[2].ID != 103 || scanned[2].Username != "eve" || scanned[2].Balance != 12000 || !scanned[2].Active {
		fmt.Fprintf(os.Stderr, "FAIL [2]: row 2 mismatch: %+v\n", scanned[2])
		os.Exit(1)
	}

	if rows.CommandTag().String() != "SELECT 3" {
		fmt.Fprintf(os.Stderr, "FAIL [2]: CommandTag mismatch: got %q, expected 'SELECT 3'\n", rows.CommandTag().String())
		os.Exit(1)
	}

	// Assertion 3: Values() and RawValues() return decoded any-slices and raw byte-slices
	rows3, err := sample.NewTextRows(colNames, colOIDs, rowsData, cmdTag)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL [3 setup]: %v\n", err)
		os.Exit(1)
	}
	if !rows3.Next() {
		fmt.Fprintln(os.Stderr, "FAIL [3]: Next() returned false for first row")
		os.Exit(1)
	}

	raw := rows3.RawValues()
	if len(raw) != 4 || !bytes.Equal(raw[0], []byte("101")) || !bytes.Equal(raw[1], []byte("carol")) {
		fmt.Fprintf(os.Stderr, "FAIL [3]: RawValues mismatch: %v\n", raw)
		os.Exit(1)
	}

	vals, err := rows3.Values()
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL [3]: Values() returned error: %v\n", err)
		os.Exit(1)
	}
	if len(vals) != 4 {
		fmt.Fprintf(os.Stderr, "FAIL [3]: Values() length mismatch: got %d, expected 4\n", len(vals))
		os.Exit(1)
	}
	if vals[0] != int32(101) || vals[1] != "carol" || vals[2] != int64(5000) || vals[3] != true {
		fmt.Fprintf(os.Stderr, "FAIL [3]: Values() contents mismatch: %+v\n", vals)
		os.Exit(1)
	}
	rows3.Close()

	// Assertion 4: Scan() supports nil destinations to skip column decoding without error
	rows4, _ := sample.NewTextRows(colNames, colOIDs, rowsData, cmdTag)
	if !rows4.Next() {
		fmt.Fprintln(os.Stderr, "FAIL [4]: Next() failed")
		os.Exit(1)
	}
	var nameOnly string
	err = rows4.Scan(nil, &nameOnly, nil, nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL [4]: Scan with nil skipped destinations failed: %v\n", err)
		os.Exit(1)
	}
	if nameOnly != "carol" {
		fmt.Fprintf(os.Stderr, "FAIL [4]: nameOnly mismatch: got %q, expected 'carol'\n", nameOnly)
		os.Exit(1)
	}
	rows4.Close()

	// Assertion 5: Scan() returns ScanArgError and terminates iteration when destination type is incompatible
	rows5, _ := sample.NewTextRows(colNames, colOIDs, rowsData, cmdTag)
	if !rows5.Next() {
		fmt.Fprintln(os.Stderr, "FAIL [5]: Next() failed")
		os.Exit(1)
	}
	var invalidBoolDest bool // trying to scan text "carol" into bool
	err = rows5.Scan(nil, &invalidBoolDest, nil, nil)
	if err == nil {
		fmt.Fprintln(os.Stderr, "FAIL [5]: expected Scan() to return ScanArgError for invalid type")
		os.Exit(1)
	}
	var scanArgErr pgx.ScanArgError
	if !errors.As(err, &scanArgErr) {
		fmt.Fprintf(os.Stderr, "FAIL [5]: error is not pgx.ScanArgError: %v\n", err)
		os.Exit(1)
	}
	if scanArgErr.ColumnIndex != 1 || scanArgErr.FieldName != "username" {
		fmt.Fprintf(os.Stderr, "FAIL [5]: ScanArgError metadata mismatch: ColumnIndex=%d, FieldName=%q\n", scanArgErr.ColumnIndex, scanArgErr.FieldName)
		os.Exit(1)
	}

	// Assertion 6: pgx.CollectRows, pgx.CollectOneRow, and pgx.ForEachRow seamlessly process MemoryRows results offline
	rows6a, _ := sample.NewTextRows(colNames, colOIDs, rowsData, cmdTag)
	collected, err := pgx.CollectRows(rows6a, func(row pgx.CollectableRow) (string, error) {
		var u string
		err := row.Scan(nil, &u, nil, nil)
		return u, err
	})
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL [6a]: CollectRows error: %v\n", err)
		os.Exit(1)
	}
	if len(collected) != 3 || collected[0] != "carol" || collected[1] != "dave" || collected[2] != "eve" {
		fmt.Fprintf(os.Stderr, "FAIL [6a]: CollectRows result mismatch: %v\n", collected)
		os.Exit(1)
	}

	singleData := [][]string{{"999", "superadmin", "99999", "t"}}
	rows6b, _ := sample.NewTextRows(colNames, colOIDs, singleData, pgconn.NewCommandTag("SELECT 1"))
	singleUser, err := pgx.CollectOneRow(rows6b, func(row pgx.CollectableRow) (string, error) {
		var u string
		err := row.Scan(nil, &u, nil, nil)
		return u, err
	})
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL [6b]: CollectOneRow error: %v\n", err)
		os.Exit(1)
	}
	if singleUser != "superadmin" {
		fmt.Fprintf(os.Stderr, "FAIL [6b]: CollectOneRow mismatch: got %q, expected 'superadmin'\n", singleUser)
		os.Exit(1)
	}

	var forEachUsers []string
	rows6c, _ := sample.NewTextRows(colNames, colOIDs, rowsData, cmdTag)
	var dummyID int32
	var dummyUser string
	var dummyBal int64
	var dummyActive bool
	ct, err := pgx.ForEachRow(rows6c, []any{&dummyID, &dummyUser, &dummyBal, &dummyActive}, func() error {
		forEachUsers = append(forEachUsers, dummyUser)
		return nil
	})
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL [6c]: ForEachRow error: %v\n", err)
		os.Exit(1)
	}
	if len(forEachUsers) != 3 || ct.String() != "SELECT 3" {
		fmt.Fprintf(os.Stderr, "FAIL [6c]: ForEachRow mismatch: count=%d, tag=%s\n", len(forEachUsers), ct.String())
		os.Exit(1)
	}

	// Assertion 7: pgx.RowToMap and pgx.RowToStructByName correctly map rows into maps and Go structs via pgx.Rows
	rows7a, _ := sample.NewTextRows(colNames, colOIDs, rowsData, cmdTag)
	mapList, err := sample.CollectRowMaps(rows7a)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL [7a]: CollectRowMaps error: %v\n", err)
		os.Exit(1)
	}
	if len(mapList) != 3 || mapList[0]["username"] != "carol" || mapList[0]["id"] != int32(101) {
		fmt.Fprintf(os.Stderr, "FAIL [7a]: mapList content mismatch: %+v\n", mapList)
		os.Exit(1)
	}

	rows7b, _ := sample.NewTextRows(colNames, colOIDs, rowsData, cmdTag)
	structList, err := sample.CollectStructsByName[Account](rows7b)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL [7b]: CollectStructsByName error: %v\n", err)
		os.Exit(1)
	}
	if len(structList) != 3 || structList[0].Username != "carol" || structList[2].Balance != 12000 {
		fmt.Fprintf(os.Stderr, "FAIL [7b]: structList content mismatch: %+v\n", structList)
		os.Exit(1)
	}

	// Assertion 8: Close() is idempotent and Err() preserves any error after closure
	rows8, _ := sample.NewTextRows(colNames, colOIDs, rowsData, cmdTag)
	rows8.Close()
	rows8.Close() // idempotent
	if rows8.Next() {
		fmt.Fprintln(os.Stderr, "FAIL [8]: Next() returned true on closed rows")
		os.Exit(1)
	}
	if rows8.Err() != nil {
		fmt.Fprintf(os.Stderr, "FAIL [8]: unexpected error on clean close: %v\n", rows8.Err())
		os.Exit(1)
	}

	fmt.Println("All pgx.Rows contract assertions passed successfully.")
}

Seeder d'origine

anonyme