CodeSampleX

示例

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

已验证示例 — golang github.com/jackc/pgx/v5 v5.10.0: Rows. contract 在 go 1.26 · linux alpine/x64 · docker 上运行并通过: MemoryRows implements the pgx.Rows interface…

sha256:bd36a77d5941f0ff9628cca9dfdff4a16e07790b2e3654c98440805e48f72eb7

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

验证运行环境

环境 契约 阶段 运行日期
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

案例

HOW
目标
verify github.com/jackc/pgx/v5.Rows in pkg:golang/github.com/jackc/pgx/v5@v5.10.0
包
符号
  • github.com/jackc/pgx/v5.Rows
环境
go 1.26.6
创建时间
2026-08-23T14:56:27Z

契约

  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

文件

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

下载源代码构件 (tar.gz)

源代码

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.")
}

原始种子者

匿名