CodeSampleX

Пример

github.com/jackc/pgx/v5 v5.7.4: ConnConfig

Проверенный пример — golang github.com/jackc/pgx/v5 v5.7.4: ConnConfig. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:a4b342c7cf13a6e7b5f2f0894abc6b23beb4c820be3cdeb37d2d04068bb9d144

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 go

Среды запусков проверки

Окружение Контракт Этапы Запуск
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

Кейс

HOW
Цель
verify github.com/jackc/pgx/v5.ConnConfig in pkg:golang/github.com/jackc/pgx/v5@v5.7.4
Пакеты
Символы
  • github.com/jackc/pgx/v5.ConnConfig
Создан
2026-09-08T18:33:56Z

Контракт

  1. pgx.ParseConfig creates a ConnConfig with default cache capacities and QueryExecModeCacheStatement
  2. ConnConfig.ConnString formats a valid PostgreSQL connection URI reflecting configured fields
  3. ConnConfig.Copy creates an isolated deep copy that does not mutate the source configuration
  4. ConnConfig statement cache capacities and QueryExecMode can be reconfigured for transaction poolers
  5. ConnConfig supports customizing ConnectTimeout and session runtime parameters

Файлы

  • PROMPT.md
  • conn_config.go
  • csx.json
  • go.mod
  • go.sum
  • 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.ConnConfig in pkg:golang/github.com/jackc/pgx/v5@v5.7.4
Kind: HOW

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

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.
conn_config.go
package sample

import (
	"fmt"
	"time"

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

// ParseAndConfigure parses a PostgreSQL connection string and sets custom execution options.
func ParseAndConfigure(connStr string, mode pgx.QueryExecMode, timeout time.Duration) (*pgx.ConnConfig, error) {
	cfg, err := pgx.ParseConfig(connStr)
	if err != nil {
		return nil, fmt.Errorf("failed to parse conn string: %w", err)
	}
	cfg.DefaultQueryExecMode = mode
	cfg.ConnectTimeout = timeout
	return cfg, nil
}

// ConfigureForPooler clones a ConnConfig and adjusts statement caching for transaction poolers.
func ConfigureForPooler(cfg *pgx.ConnConfig) (*pgx.ConnConfig, error) {
	if cfg == nil {
		return nil, fmt.Errorf("config cannot be nil")
	}
	clone := cfg.Copy()
	clone.StatementCacheCapacity = 0
	clone.DescriptionCacheCapacity = 0
	clone.DefaultQueryExecMode = pgx.QueryExecModeExec
	return clone, nil
}

// SetRuntimeParameter sets or updates a runtime parameter on ConnConfig.
func SetRuntimeParameter(cfg *pgx.ConnConfig, key, value string) error {
	if cfg == nil {
		return fmt.Errorf("config cannot be nil")
	}
	if cfg.RuntimeParams == nil {
		cfg.RuntimeParams = make(map[string]string)
	}
	cfg.RuntimeParams[key] = value
	return nil
}
csx.json
{"case":{"caseId":"case:sha256:82ad4e3e8a1ce551862dfa7444c0e2ab9157b90ba9036f61f6f0526b1f0a3c01","contract":["pgx.ParseConfig creates a ConnConfig with default cache capacities and QueryExecModeCacheStatement","ConnConfig.ConnString formats a valid PostgreSQL connection URI reflecting configured fields","ConnConfig.Copy creates an isolated deep copy that does not mutate the source configuration","ConnConfig statement cache capacities and QueryExecMode can be reconfigured for transaction poolers","ConnConfig supports customizing ConnectTimeout and session runtime parameters"],"goal":"verify github.com/jackc/pgx/v5.ConnConfig in pkg:golang/github.com/jackc/pgx/v5@v5.7.4","kind":"HOW","packages":["pkg:golang/github.com/jackc/pgx/v5@v5.7.4"],"schemaVersion":1,"symbols":["github.com/jackc/pgx/v5.ConnConfig"]},"contractCommand":["go","run","./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.7.4"],"schemaVersion":1,"subject":"pkg:golang/github.com/jackc/pgx/v5@v5.7.4","symbols":["github.com/jackc/pgx/v5.ConnConfig"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

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

require (
	github.com/jackc/pgpassfile v1.0.0 // indirect
	github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
	golang.org/x/crypto v0.31.0 // 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.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg=
github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
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.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
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 github.com/jackc/pgx/v5.ConnConfig in pkg:golang/github.com/jackc/pgx/v5@v5.7.4",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/jackc/pgx/v5@v5.7.4"
  ],
  "symbols": [
    "github.com/jackc/pgx/v5.ConnConfig"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"strings"
	"time"

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

func main() {
	// Assertion 1: pgx.ParseConfig creates a ConnConfig with default cache capacities and QueryExecModeCacheStatement
	connStr := "postgres://test_user:test_pass@127.0.0.1:5432/test_db?sslmode=disable"
	cfg, err := pgx.ParseConfig(connStr)
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 1 failed: %v\n", err)
		os.Exit(1)
	}
	if cfg.StatementCacheCapacity != 512 {
		fmt.Fprintf(os.Stderr, "assertion 1 failed: expected StatementCacheCapacity 512, got %d\n", cfg.StatementCacheCapacity)
		os.Exit(1)
	}
	if cfg.DescriptionCacheCapacity != 512 {
		fmt.Fprintf(os.Stderr, "assertion 1 failed: expected DescriptionCacheCapacity 512, got %d\n", cfg.DescriptionCacheCapacity)
		os.Exit(1)
	}
	if cfg.DefaultQueryExecMode != pgx.QueryExecModeCacheStatement {
		fmt.Fprintf(os.Stderr, "assertion 1 failed: expected QueryExecModeCacheStatement, got %v\n", cfg.DefaultQueryExecMode)
		os.Exit(1)
	}
	if cfg.Host != "127.0.0.1" || cfg.Port != 5432 || cfg.Database != "test_db" || cfg.User != "test_user" {
		fmt.Fprintf(os.Stderr, "assertion 1 failed: unexpected field values in ConnConfig\n")
		os.Exit(1)
	}

	// Assertion 2: ConnConfig.ConnString formats a valid PostgreSQL connection URI reflecting configured fields
	cs := cfg.ConnString()
	expectedPrefix := "postgres://test_user:test_pass@127.0.0.1:5432/test_db"
	if !strings.HasPrefix(cs, expectedPrefix) {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: expected ConnString to start with %q, got %q\n", expectedPrefix, cs)
		os.Exit(1)
	}
	reparsed, err := pgx.ParseConfig(cs)
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: failed to reparse ConnString: %v\n", err)
		os.Exit(1)
	}
	if reparsed.Host != cfg.Host || reparsed.Port != cfg.Port || reparsed.Database != cfg.Database {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: reparsed fields do not match original\n")
		os.Exit(1)
	}

	// Assertion 3: ConnConfig.Copy creates an isolated deep copy that does not mutate the source configuration
	clone := cfg.Copy()
	if clone == nil || clone == cfg {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: expected separate non-nil copy\n")
		os.Exit(1)
	}
	clone.Host = "127.0.0.2"
	clone.Port = 5433
	clone.StatementCacheCapacity = 100
	clone.DefaultQueryExecMode = pgx.QueryExecModeSimpleProtocol
	if cfg.Host != "127.0.0.1" || cfg.Port != 5432 || cfg.StatementCacheCapacity != 512 || cfg.DefaultQueryExecMode != pgx.QueryExecModeCacheStatement {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: mutating clone affected original ConnConfig\n")
		os.Exit(1)
	}
	err = sample.SetRuntimeParameter(clone, "custom_setting", "clone_val")
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: SetRuntimeParameter error: %v\n", err)
		os.Exit(1)
	}
	if cfg.RuntimeParams != nil && cfg.RuntimeParams["custom_setting"] != "" {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: RuntimeParams map was not deep copied\n")
		os.Exit(1)
	}

	// Assertion 4: ConnConfig statement cache capacities and QueryExecMode can be reconfigured for transaction poolers
	poolerCfg, err := sample.ConfigureForPooler(cfg)
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 4 failed: %v\n", err)
		os.Exit(1)
	}
	if poolerCfg.StatementCacheCapacity != 0 || poolerCfg.DescriptionCacheCapacity != 0 {
		fmt.Fprintf(os.Stderr, "assertion 4 failed: expected zero cache capacity for pooler, got %d, %d\n",
			poolerCfg.StatementCacheCapacity, poolerCfg.DescriptionCacheCapacity)
		os.Exit(1)
	}
	if poolerCfg.DefaultQueryExecMode != pgx.QueryExecModeExec {
		fmt.Fprintf(os.Stderr, "assertion 4 failed: expected QueryExecModeExec for pooler, got %v\n", poolerCfg.DefaultQueryExecMode)
		os.Exit(1)
	}

	// Assertion 5: ConnConfig supports customizing ConnectTimeout and session runtime parameters
	timeout := 10 * time.Second
	configured, err := sample.ParseAndConfigure(connStr, pgx.QueryExecModeDescribeExec, timeout)
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 5 failed: %v\n", err)
		os.Exit(1)
	}
	if configured.ConnectTimeout != timeout {
		fmt.Fprintf(os.Stderr, "assertion 5 failed: expected ConnectTimeout %v, got %v\n", timeout, configured.ConnectTimeout)
		os.Exit(1)
	}
	if configured.DefaultQueryExecMode != pgx.QueryExecModeDescribeExec {
		fmt.Fprintf(os.Stderr, "assertion 5 failed: expected QueryExecModeDescribeExec, got %v\n", configured.DefaultQueryExecMode)
		os.Exit(1)
	}
	err = sample.SetRuntimeParameter(configured, "application_name", "sample_service")
	if err != nil || configured.RuntimeParams["application_name"] != "sample_service" {
		fmt.Fprintf(os.Stderr, "assertion 5 failed: expected application_name runtime parameter to be set\n")
		os.Exit(1)
	}

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

Исходный сидер

аноним