示例
github.com/jackc/pgx/v5 v5.10.0: CollectableRow
已验证示例 — golang github.com/jackc/pgx/v5 v5.10.0: CollectableRow. contract 在 go 1.26 · linux alpine/x64 · docker 上运行并通过: StaticRow implements…
sha256:3f79e5e0fb7e0034ce7633c48ebaaa8c4e7b23248e192ceb2e7948df9fda7847
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 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-28 |
案例
HOW- 目标
- verify github.com/jackc/pgx/v5.CollectableRow in pkg:golang/github.com/jackc/pgx/v5@v5.10.0
- 符号
-
- github.com/jackc/pgx/v5.CollectableRow
- 环境
- go 1.26.6
- 创建时间
- 2026-08-28T01:08:24Z
契约
- StaticRow implements pgx.CollectableRow and pgx.Rows for offline testing and custom mapping
- CollectableRow.FieldDescriptions returns column names, OIDs, and format codes
- CollectableRow.Scan decodes column values into destination pointers and skips nil destinations
- CollectableRow.Values and RawValues return decoded any slices and raw byte slices
- CollectableRow.Scan returns pgx.ScanArgError with column index and field name on type mismatch
- pgx.RowToStructByName, pgx.RowToStructByPos, and pgx.RowToMap map CollectableRow into Go structs and maps
- Custom pgx.RowToFunc mappers validate and transform CollectableRow instances
- pgx.CollectRows and pgx.CollectExactlyOneRow iterate rows streams using pgx.RowToFunc mappers
- Dynamic column lookup resolves column values by name via CollectableRow.FieldDescriptions
文件
- PROMPT.md
- csx.json
- go.mod
- go.sum
- sample.go
- spec.json
- test/contract.go
源代码
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.CollectableRow 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.CollectableRow
Constraints:
- executionContext: node
Required runtime conditions:
- ecosystem: npm
- language: javascript
- moduleSystem: cjs
- packageManager: npm@10.9.8
- runtime: node@22.23.2
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.
{"case":{"caseId":"case:sha256:8649152f9e2ef96b48ca5b8108b3cec715b01822547563e6a01587921971e2dc","contract":["StaticRow implements pgx.CollectableRow and pgx.Rows for offline testing and custom mapping","CollectableRow.FieldDescriptions returns column names, OIDs, and format codes","CollectableRow.Scan decodes column values into destination pointers and skips nil destinations","CollectableRow.Values and RawValues return decoded any slices and raw byte slices","CollectableRow.Scan returns pgx.ScanArgError with column index and field name on type mismatch","pgx.RowToStructByName, pgx.RowToStructByPos, and pgx.RowToMap map CollectableRow into Go structs and maps","Custom pgx.RowToFunc mappers validate and transform CollectableRow instances","pgx.CollectRows and pgx.CollectExactlyOneRow iterate rows streams using pgx.RowToFunc mappers","Dynamic column lookup resolves column values by name via CollectableRow.FieldDescriptions"],"goal":"verify github.com/jackc/pgx/v5.CollectableRow 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.CollectableRow"]},"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.CollectableRow"],"verifierAdapter":"golang@1"}
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
)
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=
package sample
import (
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
)
// StaticRow is an in-memory implementation of pgx.CollectableRow (and pgx.Rows)
// for offline testing, mock query result processing, and custom row mapping without requiring a live PostgreSQL connection.
type StaticRow struct {
fields []pgconn.FieldDescription
values [][]byte
typeMap *pgtype.Map
commandTag pgconn.CommandTag
err error
consumed bool
closed bool
}
// Ensure StaticRow statically satisfies both pgx.CollectableRow and pgx.Rows interfaces.
var (
_ pgx.CollectableRow = (*StaticRow)(nil)
_ pgx.Rows = (*StaticRow)(nil)
)
// NewStaticRow creates a new StaticRow from field descriptions, raw byte values, and a type map.
func NewStaticRow(fields []pgconn.FieldDescription, values [][]byte, typeMap *pgtype.Map) *StaticRow {
if typeMap == nil {
typeMap = pgtype.NewMap()
}
return &StaticRow{
fields: fields,
values: values,
typeMap: typeMap,
commandTag: pgconn.NewCommandTag("SELECT 1"),
}
}
// NewTextStaticRow creates a StaticRow from column names, OIDs, and string text values.
func NewTextStaticRow(colNames []string, colOIDs []uint32, stringValues []string) (*StaticRow, error) {
if len(colNames) != len(colOIDs) || len(colNames) != len(stringValues) {
return nil, fmt.Errorf("length mismatch between column names (%d), OIDs (%d), and values (%d)", len(colNames), len(colOIDs), len(stringValues))
}
fields := make([]pgconn.FieldDescription, len(colNames))
values := make([][]byte, len(stringValues))
for i := range colNames {
fields[i] = pgconn.FieldDescription{
Name: colNames[i],
DataTypeOID: colOIDs[i],
Format: 0, // TextFormat
}
values[i] = []byte(stringValues[i])
}
return NewStaticRow(fields, values, pgtype.NewMap()), nil
}
// FieldDescriptions returns the slice of FieldDescriptions representing column metadata.
func (r *StaticRow) FieldDescriptions() []pgconn.FieldDescription {
return r.fields
}
// Next allows StaticRow to act as a single-row pgx.Rows stream.
func (r *StaticRow) Next() bool {
if r.closed || r.consumed || r.err != nil {
return false
}
r.consumed = true
return true
}
// Scan decodes column values into the provided destination pointers using pgx.ScanRow,
// or delegates to pgx.RowScanner when a single custom scanner is provided.
func (r *StaticRow) Scan(dest ...any) error {
if r.closed {
return errors.New("cannot scan closed row")
}
if len(dest) == 1 {
if rc, ok := dest[0].(pgx.RowScanner); ok {
err := rc.ScanRow(r)
if err != nil {
r.err = err
return err
}
return nil
}
}
err := pgx.ScanRow(r.typeMap, r.fields, r.values, dest...)
if err != nil {
r.err = err
return err
}
return nil
}
// Values decodes and returns all column values as a slice of any.
func (r *StaticRow) Values() ([]any, error) {
if r.closed {
return nil, errors.New("cannot read values from closed row")
}
vals := make([]any, len(r.fields))
for i := range r.fields {
buf := r.values[i]
if buf == nil {
vals[i] = nil
continue
}
if dt, ok := r.typeMap.TypeForOID(r.fields[i].DataTypeOID); ok {
v, err := dt.Codec.DecodeValue(r.typeMap, r.fields[i].DataTypeOID, r.fields[i].Format, buf)
if err != nil {
r.err = err
return nil, err
}
vals[i] = v
} else {
vals[i] = string(buf)
}
}
return vals, nil
}
// RawValues returns the raw byte buffers of the row.
func (r *StaticRow) RawValues() [][]byte {
if r.closed {
return nil
}
return r.values
}
// CommandTag returns the command tag from the simulated query.
func (r *StaticRow) CommandTag() pgconn.CommandTag {
return r.commandTag
}
// Err returns any error encountered during iteration or scanning.
func (r *StaticRow) Err() error {
return r.err
}
// Close marks the row as closed.
func (r *StaticRow) Close() {
r.closed = true
}
// Conn returns nil as StaticRow is self-contained.
func (r *StaticRow) Conn() *pgx.Conn {
return nil
}
// StaticRows is an in-memory pgx.Rows implementation that streams a sequence of StaticRow instances.
type StaticRows struct {
fields []pgconn.FieldDescription
rows []*StaticRow
commandTag pgconn.CommandTag
index int
closed bool
err error
}
var _ pgx.Rows = (*StaticRows)(nil)
// NewStaticRows constructs a StaticRows stream from multiple StaticRow instances.
func NewStaticRows(rows []*StaticRow, commandTag pgconn.CommandTag) (*StaticRows, error) {
var fields []pgconn.FieldDescription
if len(rows) > 0 {
fields = rows[0].FieldDescriptions()
}
return &StaticRows{
fields: fields,
rows: rows,
commandTag: commandTag,
index: -1,
}, nil
}
func (r *StaticRows) FieldDescriptions() []pgconn.FieldDescription {
return r.fields
}
func (r *StaticRows) Next() bool {
if r.closed || r.err != nil {
return false
}
r.index++
if r.index < len(r.rows) {
return true
}
r.Close()
return false
}
func (r *StaticRows) Scan(dest ...any) error {
if r.closed || r.index < 0 || r.index >= len(r.rows) {
return errors.New("scan called outside active row boundary")
}
return r.rows[r.index].Scan(dest...)
}
func (r *StaticRows) Values() ([]any, error) {
if r.closed || r.index < 0 || r.index >= len(r.rows) {
return nil, errors.New("values called outside active row boundary")
}
return r.rows[r.index].Values()
}
func (r *StaticRows) RawValues() [][]byte {
if r.closed || r.index < 0 || r.index >= len(r.rows) {
return nil
}
return r.rows[r.index].RawValues()
}
func (r *StaticRows) CommandTag() pgconn.CommandTag {
return r.commandTag
}
func (r *StaticRows) Err() error {
return r.err
}
func (r *StaticRows) Close() {
r.closed = true
}
func (r *StaticRows) Conn() *pgx.Conn {
return nil
}
// UserProfile is a domain struct demonstrating struct mapping from pgx.CollectableRow.
type UserProfile struct {
ID int64 `db:"id"`
Email string `db:"email"`
Score int32 `db:"score"`
IsPremium bool `db:"is_premium"`
}
// MapUserProfile is a custom pgx.RowToFunc that scans and validates a UserProfile from a CollectableRow.
func MapUserProfile(row pgx.CollectableRow) (UserProfile, error) {
var profile UserProfile
err := row.Scan(&profile.ID, &profile.Email, &profile.Score, &profile.IsPremium)
if err != nil {
return UserProfile{}, err
}
if profile.Score < 0 {
return UserProfile{}, fmt.Errorf("invalid negative score %d for user %d", profile.Score, profile.ID)
}
return profile, nil
}
// GetColumnByName extracts a specific column value by name dynamically using FieldDescriptions and Values.
func GetColumnByName(row pgx.CollectableRow, colName string) (any, error) {
fields := row.FieldDescriptions()
targetIdx := -1
for i, f := range fields {
if f.Name == colName {
targetIdx = i
break
}
}
if targetIdx == -1 {
return nil, fmt.Errorf("column %q not found in row fields", colName)
}
vals, err := row.Values()
if err != nil {
return nil, err
}
return vals[targetIdx], nil
}
{
"schemaVersion": 1,
"goal": "verify github.com/jackc/pgx/v5.CollectableRow 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.CollectableRow"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"packageManager": "npm@10.9.8",
"runtime": "node@22.23.2"
}
}
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"
)
func main() {
colNames := []string{"id", "email", "score", "is_premium"}
colOIDs := []uint32{pgtype.Int8OID, pgtype.TextOID, pgtype.Int4OID, pgtype.BoolOID}
rowVals1 := []string{"1001", "alice@example.com", "85", "t"}
rowVals2 := []string{"1002", "bob@example.com", "92", "f"}
rowVals3 := []string{"1003", "charlie@example.com", "40", "t"}
// 1. Verify StaticRow satisfies pgx.CollectableRow interface
row1, err := sample.NewTextStaticRow(colNames, colOIDs, rowVals1)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [setup 1]: NewTextStaticRow returned error: %v\n", err)
os.Exit(1)
}
var collectable pgx.CollectableRow = row1
if collectable == nil {
fmt.Fprintf(os.Stderr, "FAIL [1]: StaticRow does not satisfy pgx.CollectableRow\n")
os.Exit(1)
}
// 2. Verify CollectableRow.FieldDescriptions returns accurate column metadata
fields := collectable.FieldDescriptions()
if len(fields) != 4 || fields[0].Name != "id" || fields[1].Name != "email" || fields[2].Name != "score" || fields[3].Name != "is_premium" {
fmt.Fprintf(os.Stderr, "FAIL [2]: FieldDescriptions mismatch: %+v\n", fields)
os.Exit(1)
}
if fields[0].DataTypeOID != pgtype.Int8OID || fields[1].DataTypeOID != pgtype.TextOID {
fmt.Fprintf(os.Stderr, "FAIL [2]: DataTypeOID mismatch: %+v\n", fields)
os.Exit(1)
}
// 3. Verify CollectableRow.Scan positionally decodes columns into destination pointers and supports nil to skip
var id int64
var email string
var score int32
var isPrem bool
err = collectable.Scan(&id, &email, &score, &isPrem)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [3]: Scan failed: %v\n", err)
os.Exit(1)
}
if id != 1001 || email != "alice@example.com" || score != 85 || !isPrem {
fmt.Fprintf(os.Stderr, "FAIL [3]: Scan values mismatch: got (%d, %q, %d, %v)\n", id, email, score, isPrem)
os.Exit(1)
}
var skippedEmail string
err = collectable.Scan(nil, &skippedEmail, nil, nil)
if err != nil || skippedEmail != "alice@example.com" {
fmt.Fprintf(os.Stderr, "FAIL [3]: Scan with nil skip failed: err=%v, got=%q\n", err, skippedEmail)
os.Exit(1)
}
// 4. Verify CollectableRow.Values and RawValues return decoded any slices and raw byte buffers
vals, err := collectable.Values()
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [4]: Values() error: %v\n", err)
os.Exit(1)
}
if len(vals) != 4 || vals[0] != int64(1001) || vals[1] != "alice@example.com" || vals[2] != int32(85) || vals[3] != true {
fmt.Fprintf(os.Stderr, "FAIL [4]: Values() mismatch: %+v\n", vals)
os.Exit(1)
}
rawVals := collectable.RawValues()
if len(rawVals) != 4 || !bytes.Equal(rawVals[0], []byte("1001")) || !bytes.Equal(rawVals[1], []byte("alice@example.com")) {
fmt.Fprintf(os.Stderr, "FAIL [4]: RawValues() mismatch: %+v\n", rawVals)
os.Exit(1)
}
// 5. Verify CollectableRow.Scan returns pgx.ScanArgError on type mismatch
var badBool bool
err = collectable.Scan(nil, &badBool, nil, nil) // email "alice@example.com" into bool
if err == nil {
fmt.Fprintf(os.Stderr, "FAIL [5]: expected ScanArgError on type mismatch, got nil\n")
os.Exit(1)
}
var scanArgErr pgx.ScanArgError
if !errors.As(err, &scanArgErr) {
fmt.Fprintf(os.Stderr, "FAIL [5]: expected pgx.ScanArgError, got %T: %v\n", err, err)
os.Exit(1)
}
if scanArgErr.ColumnIndex != 1 || scanArgErr.FieldName != "email" {
fmt.Fprintf(os.Stderr, "FAIL [5]: ScanArgError metadata mismatch: col=%d, field=%q\n", scanArgErr.ColumnIndex, scanArgErr.FieldName)
os.Exit(1)
}
// 6. Verify built-in pgx row mapping functions against CollectableRow
structByName, err := pgx.RowToStructByName[sample.UserProfile](collectable)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [6]: RowToStructByName error: %v\n", err)
os.Exit(1)
}
if structByName.ID != 1001 || structByName.Email != "alice@example.com" || structByName.Score != 85 || !structByName.IsPremium {
fmt.Fprintf(os.Stderr, "FAIL [6]: RowToStructByName mismatch: %+v\n", structByName)
os.Exit(1)
}
structByPos, err := pgx.RowToStructByPos[sample.UserProfile](collectable)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [6]: RowToStructByPos error: %v\n", err)
os.Exit(1)
}
if structByPos.ID != 1001 || structByPos.Email != "alice@example.com" || structByPos.Score != 85 || !structByPos.IsPremium {
fmt.Fprintf(os.Stderr, "FAIL [6]: RowToStructByPos mismatch: %+v\n", structByPos)
os.Exit(1)
}
rowMap, err := pgx.RowToMap(collectable)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [6]: RowToMap error: %v\n", err)
os.Exit(1)
}
if rowMap["id"] != int64(1001) || rowMap["email"] != "alice@example.com" || rowMap["score"] != int32(85) {
fmt.Fprintf(os.Stderr, "FAIL [6]: RowToMap mismatch: %+v\n", rowMap)
os.Exit(1)
}
// 7. Verify custom RowToFunc mapping and validation using CollectableRow
customProfile, err := sample.MapUserProfile(collectable)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [7]: MapUserProfile error: %v\n", err)
os.Exit(1)
}
if customProfile.ID != 1001 || customProfile.Score != 85 {
fmt.Fprintf(os.Stderr, "FAIL [7]: MapUserProfile mismatch: %+v\n", customProfile)
os.Exit(1)
}
// 8. Verify CollectRows, CollectOneRow, and CollectExactlyOneRow with CollectableRow stream
row2, _ := sample.NewTextStaticRow(colNames, colOIDs, rowVals2)
row3, _ := sample.NewTextStaticRow(colNames, colOIDs, rowVals3)
rowsStream, err := sample.NewStaticRows([]*sample.StaticRow{row1, row2, row3}, pgconn.NewCommandTag("SELECT 3"))
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [8 setup]: NewStaticRows error: %v\n", err)
os.Exit(1)
}
profiles, err := pgx.CollectRows(rowsStream, sample.MapUserProfile)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [8]: CollectRows error: %v\n", err)
os.Exit(1)
}
if len(profiles) != 3 || profiles[0].Email != "alice@example.com" || profiles[1].Email != "bob@example.com" || profiles[2].Email != "charlie@example.com" {
fmt.Fprintf(os.Stderr, "FAIL [8]: CollectRows result mismatch: %+v\n", profiles)
os.Exit(1)
}
singleStream, _ := sample.NewStaticRows([]*sample.StaticRow{row1}, pgconn.NewCommandTag("SELECT 1"))
singleP, err := pgx.CollectExactlyOneRow(singleStream, sample.MapUserProfile)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [8]: CollectExactlyOneRow error: %v\n", err)
os.Exit(1)
}
if singleP.ID != 1001 {
fmt.Fprintf(os.Stderr, "FAIL [8]: CollectExactlyOneRow mismatch: %+v\n", singleP)
os.Exit(1)
}
// 9. Verify dynamic column extraction by name using CollectableRow.FieldDescriptions
extractedScore, err := sample.GetColumnByName(collectable, "score")
if err != nil || extractedScore != int32(85) {
fmt.Fprintf(os.Stderr, "FAIL [9]: GetColumnByName error=%v, got=%v\n", err, extractedScore)
os.Exit(1)
}
_, err = sample.GetColumnByName(collectable, "non_existent_column")
if err == nil {
fmt.Fprintf(os.Stderr, "FAIL [9]: expected error for missing column\n")
os.Exit(1)
}
fmt.Println("PASS: all pgx.CollectableRow contract assertions verified successfully.")
}
原始种子者
匿名