CodeSampleX

Exemple

github.com/jackc/pgx/v5 v5.11.0: Conn

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

sha256:6801182062f1bea5ba668882d450fb1e1d9e3b6c99372c89d9a5bf907d2e26c3

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 debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-08

Cas

HOW
Objectif
verify github.com/jackc/pgx/v5.Conn in pkg:golang/github.com/jackc/pgx/v5@v5.11.0
Paquets
Symboles
  • github.com/jackc/pgx/v5.Conn
Environnement
go 1.26.6
Créé
2026-09-08T21:38:24Z

Contrat

  1. pgx.ConnectConfig establishes an active non-nil *pgx.Conn connection from a valid ConnConfig
  2. Conn.IsClosed returns false on an active connection and true after Close
  3. Conn.Config returns an isolated copy of the configuration that does not mutate the connection
  4. Conn.PgConn and Conn.TypeMap provide access to the underlying protocol connection and type registry
  5. Conn.Ping sends a sync query and verifies connection responsiveness
  6. Conn.Exec executes statements and returns the command tag with affected rows
  7. Conn.QueryRow scans query results into target variables
  8. Conn.Close cleanly terminates the PostgreSQL connection

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.Conn in pkg:golang/github.com/jackc/pgx/v5@v5.11.0
Kind: HOW

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

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:c7db863b09ea0e763df325d0b47549fc9aadc01592b4618f3e6884fb24b95def","contract":["pgx.ConnectConfig establishes an active non-nil *pgx.Conn connection from a valid ConnConfig","Conn.IsClosed returns false on an active connection and true after Close","Conn.Config returns an isolated copy of the configuration that does not mutate the connection","Conn.PgConn and Conn.TypeMap provide access to the underlying protocol connection and type registry","Conn.Ping sends a sync query and verifies connection responsiveness","Conn.Exec executes statements and returns the command tag with affected rows","Conn.QueryRow scans query results into target variables","Conn.Close cleanly terminates the PostgreSQL connection"],"goal":"verify github.com/jackc/pgx/v5.Conn in pkg:golang/github.com/jackc/pgx/v5@v5.11.0","kind":"HOW","packages":["pkg:golang/github.com/jackc/pgx/v5@v5.11.0"],"schemaVersion":1,"symbols":["github.com/jackc/pgx/v5.Conn"]},"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.11.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/jackc/pgx/v5@v5.11.0","symbols":["github.com/jackc/pgx/v5.Conn"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/jackc/pgx/v5 v5.11.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.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
github.com/jackc/pgx/v5 v5.11.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 (
	"context"
	"fmt"

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

// Connect establishes a connection to PostgreSQL using the provided ConnConfig.
func Connect(ctx context.Context, cfg *pgx.ConnConfig) (*pgx.Conn, error) {
	if cfg == nil {
		return nil, fmt.Errorf("config cannot be nil")
	}
	return pgx.ConnectConfig(ctx, cfg)
}

// Ping verifies that the connection to PostgreSQL is responsive.
func Ping(ctx context.Context, conn *pgx.Conn) error {
	if conn == nil {
		return fmt.Errorf("conn cannot be nil")
	}
	return conn.Ping(ctx)
}

// ExecuteCommand executes a SQL statement and returns the resulting command tag.
func ExecuteCommand(ctx context.Context, conn *pgx.Conn, sql string, args ...any) (pgconn.CommandTag, error) {
	if conn == nil {
		return pgconn.CommandTag{}, fmt.Errorf("conn cannot be nil")
	}
	return conn.Exec(ctx, sql, args...)
}

// QueryValue queries a single value and scans it into the target destination.
func QueryValue[T any](ctx context.Context, conn *pgx.Conn, sql string, args ...any) (T, error) {
	var val T
	if conn == nil {
		return val, fmt.Errorf("conn cannot be nil")
	}
	err := conn.QueryRow(ctx, sql, args...).Scan(&val)
	return val, err
}

// InspectConnection extracts the underlying pgconn handle, type map, and config copy.
func InspectConnection(conn *pgx.Conn) (*pgconn.PgConn, *pgtype.Map, *pgx.ConnConfig, error) {
	if conn == nil {
		return nil, nil, nil, fmt.Errorf("conn cannot be nil")
	}
	return conn.PgConn(), conn.TypeMap(), conn.Config(), nil
}

// CloseConnection cleanly closes the database connection handle.
func CloseConnection(ctx context.Context, conn *pgx.Conn) error {
	if conn == nil {
		return fmt.Errorf("conn cannot be nil")
	}
	return conn.Close(ctx)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/jackc/pgx/v5.Conn in pkg:golang/github.com/jackc/pgx/v5@v5.11.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/jackc/pgx/v5@v5.11.0"
  ],
  "symbols": [
    "github.com/jackc/pgx/v5.Conn"
  ]
}
test/contract.go
package main

import (
	"context"
	"fmt"
	"net"
	"os"

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

func startMockServer() (net.Listener, error) {
	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		return nil, err
	}
	go func() {
		for {
			conn, err := ln.Accept()
			if err != nil {
				return
			}
			go handleConn(conn)
		}
	}()
	return ln, nil
}

func handleConn(conn net.Conn) {
	defer conn.Close()
	backend := pgproto3.NewBackend(conn, conn)

	// Handshake
	_, err := backend.ReceiveStartupMessage()
	if err != nil {
		return
	}
	backend.Send(&pgproto3.AuthenticationOk{})
	backend.Send(&pgproto3.ParameterStatus{Name: "server_version", Value: "16.0"})
	backend.Send(&pgproto3.ParameterStatus{Name: "client_encoding", Value: "UTF8"})
	backend.Send(&pgproto3.ParameterStatus{Name: "standard_conforming_strings", Value: "on"})
	backend.Send(&pgproto3.BackendKeyData{ProcessID: 1001, SecretKey: []byte{1, 2, 3, 4}})
	backend.Send(&pgproto3.ReadyForQuery{TxStatus: 'I'})
	if err := backend.Flush(); err != nil {
		return
	}

	// Query loop
	for {
		msg, err := backend.Receive()
		if err != nil {
			return
		}
		switch m := msg.(type) {
		case *pgproto3.Terminate:
			return
		case *pgproto3.Query:
			if m.String == "-- ping" {
				backend.Send(&pgproto3.EmptyQueryResponse{})
				backend.Send(&pgproto3.ReadyForQuery{TxStatus: 'I'})
				if err := backend.Flush(); err != nil {
					return
				}
			} else if m.String == "SELECT 42" {
				backend.Send(&pgproto3.RowDescription{Fields: []pgproto3.FieldDescription{
					{Name: []byte("val"), DataTypeOID: 23, DataTypeSize: 4, Format: 0},
				}})
				backend.Send(&pgproto3.DataRow{Values: [][]byte{[]byte("42")}})
				backend.Send(&pgproto3.CommandComplete{CommandTag: []byte("SELECT 1")})
				backend.Send(&pgproto3.ReadyForQuery{TxStatus: 'I'})
				if err := backend.Flush(); err != nil {
					return
				}
			} else if m.String == "UPDATE test_table SET status = 'active'" {
				backend.Send(&pgproto3.CommandComplete{CommandTag: []byte("UPDATE 2")})
				backend.Send(&pgproto3.ReadyForQuery{TxStatus: 'I'})
				if err := backend.Flush(); err != nil {
					return
				}
			} else {
				backend.Send(&pgproto3.CommandComplete{CommandTag: []byte("OK")})
				backend.Send(&pgproto3.ReadyForQuery{TxStatus: 'I'})
				if err := backend.Flush(); err != nil {
					return
				}
			}
		}
	}
}

func main() {
	ln, err := startMockServer()
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to start mock server: %v\n", err)
		os.Exit(1)
	}
	defer ln.Close()

	ctx := context.Background()
	connStr := fmt.Sprintf("postgres://app_user:app_pass@%s/app_db?sslmode=disable", ln.Addr().String())
	cfg, err := pgx.ParseConfig(connStr)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: ParseConfig failed: %v\n", err)
		os.Exit(1)
	}
	cfg.DefaultQueryExecMode = pgx.QueryExecModeSimpleProtocol

	// 1. pgx.ConnectConfig establishes an active non-nil *pgx.Conn connection from a valid ConnConfig
	conn, err := sample.Connect(ctx, cfg)
	if err != nil || conn == nil {
		fmt.Fprintf(os.Stderr, "FAIL [1]: expected successful non-nil connection: %v\n", err)
		os.Exit(1)
	}

	// 2. Conn.IsClosed returns false on an active connection and true after Close
	if conn.IsClosed() {
		fmt.Fprintf(os.Stderr, "FAIL [2]: expected active connection to not be closed\n")
		os.Exit(1)
	}

	// 3. Conn.Config returns an isolated copy of the configuration that does not mutate the connection
	cfgCopy := conn.Config()
	if cfgCopy == nil || cfgCopy == cfg {
		fmt.Fprintf(os.Stderr, "FAIL [3]: expected isolated non-nil copy of ConnConfig\n")
		os.Exit(1)
	}
	cfgCopy.Host = "192.0.2.1"
	cfgCopy2 := conn.Config()
	if cfgCopy2.Host == "192.0.2.1" {
		fmt.Fprintf(os.Stderr, "FAIL [3]: mutating config copy affected subsequent Config() returns\n")
		os.Exit(1)
	}

	// 4. Conn.PgConn and Conn.TypeMap provide access to the underlying protocol connection and type registry
	pgConn, typeMap, _, err := sample.InspectConnection(conn)
	if err != nil || pgConn == nil || typeMap == nil {
		fmt.Fprintf(os.Stderr, "FAIL [4]: InspectConnection failed: %v\n", err)
		os.Exit(1)
	}
	if pgConn.ParameterStatus("server_version") != "16.0" {
		fmt.Fprintf(os.Stderr, "FAIL [4]: unexpected server_version parameter status: %q\n", pgConn.ParameterStatus("server_version"))
		os.Exit(1)
	}

	// 5. Conn.Ping sends a sync query and verifies connection responsiveness
	if err := sample.Ping(ctx, conn); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL [5]: Ping failed: %v\n", err)
		os.Exit(1)
	}

	// 6. Conn.Exec executes statements and returns the command tag with affected rows
	tag, err := sample.ExecuteCommand(ctx, conn, "UPDATE test_table SET status = 'active'")
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL [6]: ExecuteCommand failed: %v\n", err)
		os.Exit(1)
	}
	if tag.RowsAffected() != 2 || tag.String() != "UPDATE 2" {
		fmt.Fprintf(os.Stderr, "FAIL [6]: expected tag UPDATE 2 with 2 rows affected, got %q (rows=%d)\n", tag.String(), tag.RowsAffected())
		os.Exit(1)
	}

	// 7. Conn.QueryRow scans query results into target variables
	val, err := sample.QueryValue[int](ctx, conn, "SELECT 42")
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL [7]: QueryValue failed: %v\n", err)
		os.Exit(1)
	}
	if val != 42 {
		fmt.Fprintf(os.Stderr, "FAIL [7]: expected value 42, got %d\n", val)
		os.Exit(1)
	}

	// 8. Conn.Close cleanly terminates the PostgreSQL connection
	if err := sample.CloseConnection(ctx, conn); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL [8]: CloseConnection failed: %v\n", err)
		os.Exit(1)
	}
	if !conn.IsClosed() {
		fmt.Fprintf(os.Stderr, "FAIL [8]: expected connection to be closed after CloseConnection\n")
		os.Exit(1)
	}
	// Calling Close again should be idempotent
	if err := conn.Close(ctx); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL [8]: idempotent Close failed: %v\n", err)
		os.Exit(1)
	}

	fmt.Println("PASS: all pgx.Conn contract assertions verified successfully.")
}

Seeder d'origine

anonyme