CodeSampleX

Exemplo

github.com/jackc/pgx/v5 v5.10.0: pgxpool.NewWithConfig

Amostra verificada para golang github.com/jackc/pgx/v5 v5.10.0: pgxpool.NewWithConfig. O contrato rodou em go 1.26 · linux alpine/x64 · docker e passou.

sha256:66a62cbde8c3376d5d3bd2029d0321108bf594133786c195d8ab49040971b694

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado go linux 24 · ubuntu · glibc 2.39 x64 go go go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
verify github.com/jackc/pgx/v5/pgxpool.NewWithConfig in pkg:golang/github.com/jackc/pgx/v5@v5.10.0
Pacotes
Símbolos
  • github.com/jackc/pgx/v5/pgxpool.NewWithConfig
Ambiente
go
Criado
2026-08-28T01:58:51Z

Contrato

  1. pgxpool.ParseConfig parses PostgreSQL connection URI parameters including pool_max_conns, pool_min_conns, pool_max_conn_lifetime, pool_max_conn_idle_time, and pool_health_check_period into a pgxpool.Config.
  2. pgxpool.NewWithConfig initializes and returns a *pgxpool.Pool configured with connection settings, pool bounds, and lifecycle hook callbacks.
  3. pgxpool.Pool.Config returns the active *pgxpool.Config reflecting configured MaxConns, MinConns, ConnConfig, and pool lifetimes.
  4. pgxpool.Pool.Stat returns initial pool statistics including TotalConns, IdleConns, and MaxConns matching configuration.
  5. pgxpool.Config.Copy creates an independent copy of pool configuration where modifications do not mutate the source config.
  6. pgxpool.ParseConfig returns an error when given a malformed connection URI string.
  7. pgxpool.NewWithConfig panics when invoked with a nil config pointer.

Arquivos

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract_test.go

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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/pgxpool.NewWithConfig 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/pgxpool.NewWithConfig
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.
csx.json
{"case":{"caseId":"case:sha256:57d568638e58f43fd37dda087a7b9e7853d85121faf1d37a49379f058b9c482a","contract":["pgxpool.ParseConfig parses PostgreSQL connection URI parameters including pool_max_conns, pool_min_conns, pool_max_conn_lifetime, pool_max_conn_idle_time, and pool_health_check_period into a pgxpool.Config.","pgxpool.NewWithConfig initializes and returns a *pgxpool.Pool configured with connection settings, pool bounds, and lifecycle hook callbacks.","pgxpool.Pool.Config returns the active *pgxpool.Config reflecting configured MaxConns, MinConns, ConnConfig, and pool lifetimes.","pgxpool.Pool.Stat returns initial pool statistics including TotalConns, IdleConns, and MaxConns matching configuration.","pgxpool.Config.Copy creates an independent copy of pool configuration where modifications do not mutate the source config.","pgxpool.ParseConfig returns an error when given a malformed connection URI string.","pgxpool.NewWithConfig panics when invoked with a nil config pointer."],"goal":"verify github.com/jackc/pgx/v5/pgxpool.NewWithConfig 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/pgxpool.NewWithConfig"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"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":["github.com/jackc/pgx/v5/pgxpool.NewWithConfig"],"verifierAdapter":"golang@1"}
go.mod
module example.com/pgxpool-verify

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
	github.com/jackc/puddle/v2 v2.2.2 // indirect
	golang.org/x/sync v0.17.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.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=
main.go
package main

import (
	"context"
	"fmt"
	"time"

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

func main() {
	ctx := context.Background()

	// Parse configuration from connection string with pool parameters
	connStr := "postgres://user:secret@127.0.0.1:5432/sampledb?sslmode=disable&pool_max_conns=20&pool_min_conns=4&pool_max_conn_lifetime=1h&pool_max_conn_idle_time=15m&pool_health_check_period=30s"
	config, err := pgxpool.ParseConfig(connStr)
	if err != nil {
		panic(fmt.Sprintf("ParseConfig failed: %v", err))
	}

	// Customize pool settings and lifecycle hooks
	config.MaxConns = 30
	config.MinConns = 5
	config.MaxConnLifetime = 2 * time.Hour
	config.MaxConnIdleTime = 10 * time.Minute
	config.HealthCheckPeriod = 45 * time.Second

	config.BeforeAcquire = func(ctx context.Context, c *pgx.Conn) bool {
		return true
	}
	config.AfterRelease = func(c *pgx.Conn) bool {
		return true
	}
	config.BeforeConnect = func(ctx context.Context, cc *pgx.ConnConfig) error {
		return nil
	}
	config.AfterConnect = func(ctx context.Context, c *pgx.Conn) error {
		return nil
	}

	// Initialize connection pool with custom configuration
	pool, err := pgxpool.NewWithConfig(ctx, config)
	if err != nil {
		panic(fmt.Sprintf("NewWithConfig failed: %v", err))
	}
	defer pool.Close()

	// Inspect active configuration and metrics
	cfg := pool.Config()
	stat := pool.Stat()

	fmt.Printf("Configured pool: MaxConns=%d, MinConns=%d, Host=%s, Database=%s\n",
		cfg.MaxConns, cfg.MinConns, cfg.ConnConfig.Host, cfg.ConnConfig.Database)
	fmt.Printf("Initial pool stats: TotalConns=%d, IdleConns=%d, MaxConns=%d\n",
		stat.TotalConns(), stat.IdleConns(), stat.MaxConns())
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/jackc/pgx/v5/pgxpool.NewWithConfig 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/pgxpool.NewWithConfig"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract_test.go
package test

import (
	"context"
	"testing"
	"time"

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

func TestParseConfigParams(t *testing.T) {
	connStr := "postgres://user:secret@127.0.0.1:5432/sampledb?sslmode=disable&pool_max_conns=15&pool_min_conns=3&pool_max_conn_lifetime=1h&pool_max_conn_idle_time=15m&pool_health_check_period=30s"
	config, err := pgxpool.ParseConfig(connStr)
	if err != nil {
		t.Fatalf("pgxpool.ParseConfig failed: %v", err)
	}

	if config.MaxConns != 15 {
		t.Errorf("config.MaxConns = %d, want 15", config.MaxConns)
	}
	if config.MinConns != 3 {
		t.Errorf("config.MinConns = %d, want 3", config.MinConns)
	}
	if config.MaxConnLifetime != time.Hour {
		t.Errorf("config.MaxConnLifetime = %v, want 1h", config.MaxConnLifetime)
	}
	if config.MaxConnIdleTime != 15*time.Minute {
		t.Errorf("config.MaxConnIdleTime = %v, want 15m", config.MaxConnIdleTime)
	}
	if config.HealthCheckPeriod != 30*time.Second {
		t.Errorf("config.HealthCheckPeriod = %v, want 30s", config.HealthCheckPeriod)
	}
	if config.ConnConfig.User != "user" || config.ConnConfig.Database != "sampledb" {
		t.Errorf("config.ConnConfig mismatch: user=%s, db=%s", config.ConnConfig.User, config.ConnConfig.Database)
	}
}

func TestNewWithConfigAndInspect(t *testing.T) {
	ctx := context.Background()
	connStr := "postgres://user:secret@127.0.0.1:5432/sampledb?sslmode=disable"
	config, err := pgxpool.ParseConfig(connStr)
	if err != nil {
		t.Fatalf("pgxpool.ParseConfig failed: %v", err)
	}

	config.MaxConns = 25
	config.MinConns = 4
	config.MaxConnLifetime = 2 * time.Hour
	config.MaxConnIdleTime = 10 * time.Minute
	config.HealthCheckPeriod = 45 * time.Second

	hookTriggered := false
	config.BeforeAcquire = func(ctx context.Context, c *pgx.Conn) bool {
		hookTriggered = true
		return true
	}
	config.AfterRelease = func(c *pgx.Conn) bool {
		return true
	}
	config.BeforeConnect = func(ctx context.Context, cc *pgx.ConnConfig) error {
		return nil
	}
	config.AfterConnect = func(ctx context.Context, c *pgx.Conn) error {
		return nil
	}

	pool, err := pgxpool.NewWithConfig(ctx, config)
	if err != nil {
		t.Fatalf("pgxpool.NewWithConfig failed: %v", err)
	}
	defer pool.Close()

	cfg := pool.Config()
	if cfg.MaxConns != 25 {
		t.Errorf("pool.Config().MaxConns = %d, want 25", cfg.MaxConns)
	}
	if cfg.MinConns != 4 {
		t.Errorf("pool.Config().MinConns = %d, want 4", cfg.MinConns)
	}
	if cfg.MaxConnLifetime != 2*time.Hour {
		t.Errorf("pool.Config().MaxConnLifetime = %v, want 2h", cfg.MaxConnLifetime)
	}
	if cfg.MaxConnIdleTime != 10*time.Minute {
		t.Errorf("pool.Config().MaxConnIdleTime = %v, want 10m", cfg.MaxConnIdleTime)
	}
	if cfg.HealthCheckPeriod != 45*time.Second {
		t.Errorf("pool.Config().HealthCheckPeriod = %v, want 45s", cfg.HealthCheckPeriod)
	}
	if cfg.BeforeAcquire == nil || cfg.AfterRelease == nil || cfg.BeforeConnect == nil || cfg.AfterConnect == nil {
		t.Error("pool.Config() did not preserve lifecycle hook callbacks")
	}

	stat := pool.Stat()
	if stat.MaxConns() != 25 {
		t.Errorf("pool.Stat().MaxConns() = %d, want 25", stat.MaxConns())
	}
	if stat.TotalConns() != 0 {
		t.Errorf("pool.Stat().TotalConns() = %d, want 0", stat.TotalConns())
	}
	if stat.IdleConns() != 0 {
		t.Errorf("pool.Stat().IdleConns() = %d, want 0", stat.IdleConns())
	}
	if stat.AcquiredConns() != 0 {
		t.Errorf("pool.Stat().AcquiredConns() = %d, want 0", stat.AcquiredConns())
	}

	_ = hookTriggered
}

func TestConfigCopy(t *testing.T) {
	connStr := "postgres://user:secret@127.0.0.1:5432/sampledb?sslmode=disable"
	config, err := pgxpool.ParseConfig(connStr)
	if err != nil {
		t.Fatalf("pgxpool.ParseConfig failed: %v", err)
	}

	config.MaxConns = 10
	configCopy := config.Copy()
	configCopy.MaxConns = 50

	if config.MaxConns != 10 {
		t.Errorf("original config.MaxConns mutated: got %d, want 10", config.MaxConns)
	}
	if configCopy.MaxConns != 50 {
		t.Errorf("copied config.MaxConns = %d, want 50", configCopy.MaxConns)
	}
}

func TestParseConfigInvalidURI(t *testing.T) {
	_, err := pgxpool.ParseConfig("://invalid uri %%%")
	if err == nil {
		t.Error("pgxpool.ParseConfig did not return error for malformed URI")
	}
}

func TestNewWithConfigNilPanics(t *testing.T) {
	ctx := context.Background()
	var panicking bool
	func() {
		defer func() {
			if r := recover(); r != nil {
				panicking = true
			}
		}()
		_, _ = pgxpool.NewWithConfig(ctx, nil)
	}()

	if !panicking {
		t.Error("pgxpool.NewWithConfig(ctx, nil) did not panic")
	}
}

Seeder de origem

anônimo