CodeSampleX

Sample

github.com/jackc/pgx/v5 v5.10.0: pgx.Tx.Query

Verified sample for golang github.com/jackc/pgx/v5 v5.10.0: pgx.Tx.Query. The contract ran on go 1.26 · linux alpine/x64 · docker and passed.

sha256:c9c6556e098d5badc9d4e654f2fbaab0ba26efa89693f3192aa2fc64a0c490a6

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 go

Verification-run environments

Environment Contract Stages Run
go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-27

Case

HOW
Goal
verify pgx.Tx.Query in pkg:golang/github.com/jackc/pgx/v5@v5.10.0
Packages
Symbols
  • pgx.Tx.Query
Created
2026-08-27T02:17:40Z

Contract

  1. pgx.Tx.Query executes SQL queries with parameters in a transaction and returns pgx.Rows for iterative scanning
  2. pgx.Tx.Query correctly handles empty result sets without errors
  3. pgx.Tx.Query respects context cancellation and propagates errors appropriately
  4. pgx.Tx.Query returns pgx.Rows that supports Values extraction and proper closing

Files

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • tx_query.go
  • tx_query_test.go

Download the source artifact (tar.gz)

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 pgx.Tx.Query 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:
  - pgx.Tx.Query

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:f20e0f59c614f01100165b1d0657f3abe7c88dfb8782d643ad1b1359aea9c21e","contract":["pgx.Tx.Query executes SQL queries with parameters in a transaction and returns pgx.Rows for iterative scanning","pgx.Tx.Query correctly handles empty result sets without errors","pgx.Tx.Query respects context cancellation and propagates errors appropriately","pgx.Tx.Query returns pgx.Rows that supports Values extraction and proper closing"],"goal":"verify pgx.Tx.Query 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":["pgx.Tx.Query"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","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":["pgx.Tx.Query"],"verifierAdapter":"golang@1"}
go.mod
module example.com/pgxtxquery

go 1.25.0

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=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pgx.Tx.Query 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": [
    "pgx.Tx.Query"
  ]
}
tx_query.go
package pgxtxquery

import (
	"context"
	"errors"
	"fmt"

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

// Account represents a bank account entity fetched in a transaction.
type Account struct {
	ID      int64
	Owner   string
	Balance int64
}

// QueryAccountsByMinBalance demonstrates querying records within a pgx.Tx transaction.
// It executes tx.Query with SQL and parameters, iterates through pgx.Rows, and scans results.
func QueryAccountsByMinBalance(ctx context.Context, tx pgx.Tx, minBalance int64) ([]Account, error) {
	rows, err := tx.Query(ctx, "SELECT id, owner, balance FROM accounts WHERE balance >= $1 ORDER BY id ASC", minBalance)
	if err != nil {
		return nil, fmt.Errorf("query accounts failed: %w", err)
	}
	defer rows.Close()

	var accounts []Account
	for rows.Next() {
		var a Account
		if err := rows.Scan(&a.ID, &a.Owner, &a.Balance); err != nil {
			return nil, fmt.Errorf("scan account failed: %w", err)
		}
		accounts = append(accounts, a)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("rows iteration error: %w", err)
	}

	return accounts, nil
}

// MockRows implements pgx.Rows for offline testing of queries and transactions.
type MockRows struct {
	Rows   [][]any
	Fields []pgconn.FieldDescription
	ErrVal error
	Index  int
	Closed bool
}

func (m *MockRows) Close() {
	m.Closed = true
}

func (m *MockRows) Err() error {
	return m.ErrVal
}

func (m *MockRows) CommandTag() pgconn.CommandTag {
	return pgconn.NewCommandTag("SELECT")
}

func (m *MockRows) FieldDescriptions() []pgconn.FieldDescription {
	return m.Fields
}

func (m *MockRows) Next() bool {
	if m.Closed || m.ErrVal != nil {
		return false
	}
	if m.Index < len(m.Rows) {
		m.Index++
		return true
	}
	m.Closed = true
	return false
}

func (m *MockRows) Scan(dest ...any) error {
	if m.Index == 0 || m.Index > len(m.Rows) {
		return errors.New("scan called outside of valid row")
	}
	row := m.Rows[m.Index-1]
	if len(dest) != len(row) {
		return fmt.Errorf("expected %d destination values, got %d", len(row), len(dest))
	}
	for i, val := range row {
		switch target := dest[i].(type) {
		case *int64:
			if v, ok := val.(int64); ok {
				*target = v
			} else if v, ok := val.(int); ok {
				*target = int64(v)
			} else {
				return fmt.Errorf("cannot scan %T into *int64", val)
			}
		case *string:
			if v, ok := val.(string); ok {
				*target = v
			} else {
				return fmt.Errorf("cannot scan %T into *string", val)
			}
		case *bool:
			if v, ok := val.(bool); ok {
				*target = v
			} else {
				return fmt.Errorf("cannot scan %T into *bool", val)
			}
		default:
			return fmt.Errorf("unsupported destination type %T in mock scan", target)
		}
	}
	return nil
}

func (m *MockRows) Values() ([]any, error) {
	if m.Index == 0 || m.Index > len(m.Rows) {
		return nil, errors.New("values called outside of valid row")
	}
	return m.Rows[m.Index-1], nil
}

func (m *MockRows) RawValues() [][]byte {
	return nil
}

func (m *MockRows) Conn() *pgx.Conn {
	return nil
}

var _ pgx.Rows = (*MockRows)(nil)

// MockTx implements pgx.Tx for offline testing and verification.
type MockTx struct {
	QueryFunc func(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
	LastSQL   string
	LastArgs  []any
}

func (m *MockTx) Begin(ctx context.Context) (pgx.Tx, error) {
	return nil, errors.New("nested transactions not supported in mock")
}

func (m *MockTx) Commit(ctx context.Context) error {
	return nil
}

func (m *MockTx) Rollback(ctx context.Context) error {
	return nil
}

func (m *MockTx) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error) {
	return 0, errors.New("copy from not supported in mock")
}

func (m *MockTx) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults {
	return nil
}

func (m *MockTx) LargeObjects() pgx.LargeObjects {
	return pgx.LargeObjects{}
}

func (m *MockTx) Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error) {
	return nil, errors.New("prepare not supported in mock")
}

func (m *MockTx) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) {
	return pgconn.NewCommandTag(""), nil
}

func (m *MockTx) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
	if err := ctx.Err(); err != nil {
		return nil, err
	}
	m.LastSQL = sql
	m.LastArgs = args
	if m.QueryFunc != nil {
		return m.QueryFunc(ctx, sql, args...)
	}
	return &MockRows{}, nil
}

func (m *MockTx) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {
	return nil
}

func (m *MockTx) Conn() *pgx.Conn {
	return nil
}

var _ pgx.Tx = (*MockTx)(nil)
tx_query_test.go
package pgxtxquery

import (
	"context"
	"errors"
	"testing"
	"time"

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

func TestTxQuery_SuccessWithRows(t *testing.T) {
	// Assertion: pgx.Tx.Query executes SQL queries with parameters in a transaction and returns pgx.Rows for iterative scanning
	mockTx := &MockTx{
		QueryFunc: func(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
			return &MockRows{
				Rows: [][]any{
					{int64(1), "Alice", int64(250)},
					{int64(2), "Bob", int64(500)},
					{int64(3), "Charlie", int64(1000)},
				},
			}, nil
		},
	}

	ctx := context.Background()
	accounts, err := QueryAccountsByMinBalance(ctx, mockTx, 200)
	if err != nil {
		t.Fatalf("unexpected error querying accounts: %v", err)
	}

	if len(accounts) != 3 {
		t.Fatalf("expected 3 accounts, got %d", len(accounts))
	}

	if accounts[0].ID != 1 || accounts[0].Owner != "Alice" || accounts[0].Balance != 250 {
		t.Errorf("unexpected account[0]: %+v", accounts[0])
	}
	if accounts[1].ID != 2 || accounts[1].Owner != "Bob" || accounts[1].Balance != 500 {
		t.Errorf("unexpected account[1]: %+v", accounts[1])
	}
	if accounts[2].ID != 3 || accounts[2].Owner != "Charlie" || accounts[2].Balance != 1000 {
		t.Errorf("unexpected account[2]: %+v", accounts[2])
	}

	expectedSQL := "SELECT id, owner, balance FROM accounts WHERE balance >= $1 ORDER BY id ASC"
	if mockTx.LastSQL != expectedSQL {
		t.Errorf("expected SQL %q, got %q", expectedSQL, mockTx.LastSQL)
	}
	if len(mockTx.LastArgs) != 1 || mockTx.LastArgs[0] != int64(200) {
		t.Errorf("expected arg 200, got %v", mockTx.LastArgs)
	}
}

func TestTxQuery_EmptyResultSet(t *testing.T) {
	// Assertion: pgx.Tx.Query correctly handles empty result sets without errors
	mockTx := &MockTx{
		QueryFunc: func(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
			return &MockRows{
				Rows: [][]any{},
			}, nil
		},
	}

	ctx := context.Background()
	accounts, err := QueryAccountsByMinBalance(ctx, mockTx, 10000)
	if err != nil {
		t.Fatalf("unexpected error on empty result set: %v", err)
	}

	if len(accounts) != 0 {
		t.Fatalf("expected 0 accounts, got %d", len(accounts))
	}
}

func TestTxQuery_ContextCancellation(t *testing.T) {
	// Assertion: pgx.Tx.Query respects context cancellation and propagates errors appropriately
	mockTx := &MockTx{}

	ctx, cancel := context.WithCancel(context.Background())
	cancel() // Cancel immediately

	_, err := QueryAccountsByMinBalance(ctx, mockTx, 100)
	if err == nil {
		t.Fatal("expected error on canceled context, got nil")
	}
	if !errors.Is(err, context.Canceled) {
		t.Errorf("expected context.Canceled error, got: %v", err)
	}
}

func TestTxQuery_QueryExecutionError(t *testing.T) {
	// Assertion: pgx.Tx.Query propagates query execution errors
	expectedErr := errors.New("database transaction aborted")
	mockTx := &MockTx{
		QueryFunc: func(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
			return nil, expectedErr
		},
	}

	ctx := context.Background()
	_, err := QueryAccountsByMinBalance(ctx, mockTx, 100)
	if err == nil {
		t.Fatal("expected error from query failure, got nil")
	}
	if !errors.Is(err, expectedErr) {
		t.Errorf("expected error %v, got %v", expectedErr, err)
	}
}

func TestTxQuery_RowsValuesAndClose(t *testing.T) {
	// Assertion: pgx.Tx.Query returns pgx.Rows that supports Values() extraction and proper closing
	mockRows := &MockRows{
		Rows: [][]any{
			{int64(42), "Dave", int64(750)},
		},
	}
	mockTx := &MockTx{
		QueryFunc: func(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {
			return mockRows, nil
		},
	}

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	rows, err := mockTx.Query(ctx, "SELECT id, owner, balance FROM accounts WHERE id = $1", 42)
	if err != nil {
		t.Fatalf("unexpected query error: %v", err)
	}
	defer rows.Close()

	if !rows.Next() {
		t.Fatal("expected row to be available")
	}

	vals, err := rows.Values()
	if err != nil {
		t.Fatalf("unexpected error extracting values: %v", err)
	}
	if len(vals) != 3 || vals[0] != int64(42) || vals[1] != "Dave" || vals[2] != int64(750) {
		t.Errorf("unexpected values: %v", vals)
	}

	if rows.Next() {
		t.Fatal("expected no more rows")
	}
	if !mockRows.Closed {
		t.Error("expected rows to be closed after iteration completed")
	}
}

Origin Seeder

anonymous