CodeSampleX

Exemplo

github.com/jackc/pgx/v5 v5.10.0: Parse PostgreSQL connection URIs and keyword configurations with pgx.ParseConfig, escape SQL table and column identifiers with pgx.Identifier, and construct batch copy sources with pgx.CopyFromSlice

Amostra verificada para golang github.com/jackc/pgx/v5 v5.10.0: Parse PostgreSQL connection URIs and keyword configurations with pgx.ParseConfig, escape SQL…

sha256:5dfb25bfef776b2cd20246bba10de7241702c42aeb668ce1b27940c36ee6ee5f

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 linux 24 · ubuntu · glibc 2.39 x64 go wsl

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-19

Caso

HOW
Objetivo
Parse PostgreSQL connection URIs and keyword configurations with pgx.ParseConfig, escape SQL table and column identifiers with pgx.Identifier, and construct batch copy sources with pgx.CopyFromSlice
Pacotes
Símbolos
  • pgx.CopyFromSlice
  • pgx.Identifier
  • pgx.ParseConfig
Criado
2026-08-18T21:40:54Z

Contrato

  1. assert pgx.ParseConfig parses PostgreSQL URI connection strings, extracting host, port, user, password, database, and runtime parameters
  2. assert pgx.ParseConfig parses keyword/value DSN connection strings into ConnConfig
  3. assert pgx.ParseConfig rejects malformed connection strings with an error
  4. assert pgx.Identifier quotes table, column, and schema names and escapes double quote characters with Sanitize
  5. assert pgx.CopyFromSlice iterates through row generators providing Next, Values, and Err for batch copy operations
  6. assert pgx.CopyFromRows constructs CopyFromSource from 2D slices and yields all rows sequentially

Arquivos

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.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: Parse PostgreSQL connection URIs and keyword configurations with pgx.ParseConfig, escape SQL table and column identifiers with pgx.Identifier, and construct batch copy sources with pgx.CopyFromSlice
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/jackc/pgx/v5@v5.10.0
Demonstrate these symbols/APIs:
  - pgx.CopyFromSlice
  - pgx.Identifier
  - pgx.ParseConfig

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:b1624f30cdeb9449984c2767e8df865bfb364782fb1941762d44157ab913c42a","contract":["assert pgx.ParseConfig parses PostgreSQL URI connection strings, extracting host, port, user, password, database, and runtime parameters","assert pgx.ParseConfig parses keyword/value DSN connection strings into ConnConfig","assert pgx.ParseConfig rejects malformed connection strings with an error","assert pgx.Identifier quotes table, column, and schema names and escapes double quote characters with Sanitize","assert pgx.CopyFromSlice iterates through row generators providing Next, Values, and Err for batch copy operations","assert pgx.CopyFromRows constructs CopyFromSource from 2D slices and yields all rows sequentially"],"goal":"Parse PostgreSQL connection URIs and keyword configurations with pgx.ParseConfig, escape SQL table and column identifiers with pgx.Identifier, and construct batch copy sources with pgx.CopyFromSlice","kind":"HOW","packages":["pkg:golang/github.com/jackc/pgx/v5@v5.10.0"],"schemaVersion":1,"symbols":["pgx.CopyFromSlice","pgx.Identifier","pgx.ParseConfig"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1,"virtualization":"wsl"},"license":"MIT-0","packages":["pkg:golang/github.com/jackc/pgx/v5@v5.10.0"],"schemaVersion":1,"symbols":["pgx.CopyFromSlice","pgx.Identifier","pgx.ParseConfig"],"verifierAdapter":"golang@1"}
go.mod
module sample

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=
main.go
package main

import (
	"fmt"
	"os"

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

func main() {
	// 1. Parse connection configuration from a PostgreSQL connection string URI
	connURI := "postgres://app_user:secret_pass@localhost:5432/app_db?sslmode=disable&application_name=demo"
	cfg, err := pgx.ParseConfig(connURI)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ParseConfig failed: %v\n", err)
		os.Exit(1)
	}
	fmt.Printf("Config: Host=%s, Port=%d, Database=%s, User=%s\n", cfg.Host, cfg.Port, cfg.Database, cfg.User)

	// 2. Sanitize SQL identifiers (schema and table names) to prevent SQL injection
	ident := pgx.Identifier{"public", "user_records"}
	sanitizedTable := ident.Sanitize()
	fmt.Printf("Sanitized SQL Identifier: %s\n", sanitizedTable)

	// 3. Construct batch copy source using CopyFromSlice
	rows := [][]any{
		{1, "alice", "alice@example.com"},
		{2, "bob", "bob@example.com"},
	}
	copySource := pgx.CopyFromSlice(len(rows), func(i int) ([]any, error) {
		return rows[i], nil
	})

	count := 0
	for copySource.Next() {
		vals, err := copySource.Values()
		if err != nil {
			fmt.Fprintf(os.Stderr, "CopyFromSlice values error: %v\n", err)
			os.Exit(1)
		}
		count++
		fmt.Printf("Row %d: %v\n", count, vals)
	}
	if err := copySource.Err(); err != nil {
		fmt.Fprintf(os.Stderr, "CopyFromSlice iteration error: %v\n", err)
		os.Exit(1)
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Parse PostgreSQL connection URIs and keyword configurations with pgx.ParseConfig, escape SQL table and column identifiers with pgx.Identifier, and construct batch copy sources with pgx.CopyFromSlice",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/jackc/pgx/v5@v5.10.0"
  ],
  "symbols": [
    "pgx.CopyFromSlice",
    "pgx.Identifier",
    "pgx.ParseConfig"
  ]
}
test/contract.go
package main

import (
	"errors"
	"fmt"
	"os"
	"reflect"
	"time"

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

func main() {
	// 1. assert pgx.ParseConfig parses PostgreSQL URI connection strings, extracting host, port, user, password, database, and runtime parameters
	uri := "postgres://db_user:secure_pwd@db.example.com:5432/sample_db?sslmode=disable&search_path=public,app&application_name=worker_service&connect_timeout=10"
	cfg1, err := pgx.ParseConfig(uri)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: ParseConfig URI failed: %v\n", err)
		os.Exit(1)
	}
	if cfg1.Host != "db.example.com" {
		fmt.Fprintf(os.Stderr, "FAIL: expected host 'db.example.com', got %q\n", cfg1.Host)
		os.Exit(1)
	}
	if cfg1.Port != 5432 {
		fmt.Fprintf(os.Stderr, "FAIL: expected port 5432, got %d\n", cfg1.Port)
		os.Exit(1)
	}
	if cfg1.User != "db_user" {
		fmt.Fprintf(os.Stderr, "FAIL: expected user 'db_user', got %q\n", cfg1.User)
		os.Exit(1)
	}
	if cfg1.Password != "secure_pwd" {
		fmt.Fprintf(os.Stderr, "FAIL: expected password 'secure_pwd', got %q\n", cfg1.Password)
		os.Exit(1)
	}
	if cfg1.Database != "sample_db" {
		fmt.Fprintf(os.Stderr, "FAIL: expected database 'sample_db', got %q\n", cfg1.Database)
		os.Exit(1)
	}
	if cfg1.RuntimeParams["search_path"] != "public,app" {
		fmt.Fprintf(os.Stderr, "FAIL: expected search_path 'public,app', got %q\n", cfg1.RuntimeParams["search_path"])
		os.Exit(1)
	}
	if cfg1.RuntimeParams["application_name"] != "worker_service" {
		fmt.Fprintf(os.Stderr, "FAIL: expected application_name 'worker_service', got %q\n", cfg1.RuntimeParams["application_name"])
		os.Exit(1)
	}
	if cfg1.ConnectTimeout != 10*time.Second {
		fmt.Fprintf(os.Stderr, "FAIL: expected connect_timeout 10s, got %v\n", cfg1.ConnectTimeout)
		os.Exit(1)
	}

	// 2. assert pgx.ParseConfig parses keyword/value DSN connection strings into ConnConfig
	dsn := "host=localhost port=5433 user=analyst password=querypass dbname=warehouse sslmode=disable connect_timeout=5"
	cfg2, err := pgx.ParseConfig(dsn)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: ParseConfig DSN failed: %v\n", err)
		os.Exit(1)
	}
	if cfg2.Host != "localhost" || cfg2.Port != 5433 || cfg2.User != "analyst" || cfg2.Password != "querypass" || cfg2.Database != "warehouse" {
		fmt.Fprintf(os.Stderr, "FAIL: DSN fields mismatch: %+v\n", cfg2)
		os.Exit(1)
	}
	if cfg2.ConnectTimeout != 5*time.Second {
		fmt.Fprintf(os.Stderr, "FAIL: expected DSN connect_timeout 5s, got %v\n", cfg2.ConnectTimeout)
		os.Exit(1)
	}

	// 3. assert pgx.ParseConfig rejects malformed connection strings with an error
	_, errInvalid := pgx.ParseConfig("://invalid-url-format")
	if errInvalid == nil {
		fmt.Fprintf(os.Stderr, "FAIL: expected error when parsing invalid connection string\n")
		os.Exit(1)
	}

	// 4. assert pgx.Identifier quotes table, column, and schema names and escapes double quote characters with Sanitize
	singleIdent := pgx.Identifier{"users"}
	if sanitized := singleIdent.Sanitize(); sanitized != "\"users\"" {
		fmt.Fprintf(os.Stderr, "FAIL: single identifier sanitize mismatch: got %s, expected %s\n", sanitized, "\"users\"")
		os.Exit(1)
	}

	multiIdent := pgx.Identifier{"my_schema", "orders"}
	if sanitized := multiIdent.Sanitize(); sanitized != "\"my_schema\".\"orders\"" {
		fmt.Fprintf(os.Stderr, "FAIL: schema qualified identifier sanitize mismatch: got %s, expected %s\n", sanitized, "\"my_schema\".\"orders\"")
		os.Exit(1)
	}

	quoteIdent := pgx.Identifier{`weird"name`}
	if sanitized := quoteIdent.Sanitize(); sanitized != "\"weird\"\"name\"" {
		fmt.Fprintf(os.Stderr, "FAIL: escaped double quote sanitize mismatch: got %s, expected %s\n", sanitized, "\"weird\"\"name\"")
		os.Exit(1)
	}

	// 5. assert pgx.CopyFromSlice iterates through row generators providing Next, Values, and Err for batch copy operations
	rowsData := [][]any{
		{101, "item_a", 19.99},
		{102, "item_b", 49.50},
		{103, "item_c", 9.95},
	}
	sliceSource := pgx.CopyFromSlice(len(rowsData), func(i int) ([]any, error) {
		return rowsData[i], nil
	})

	var collectedSlice [][]any
	for sliceSource.Next() {
		v, err := sliceSource.Values()
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: unexpected Values() error: %v\n", err)
			os.Exit(1)
		}
		collectedSlice = append(collectedSlice, v)
	}
	if err := sliceSource.Err(); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: unexpected CopyFromSlice.Err(): %v\n", err)
		os.Exit(1)
	}
	if !reflect.DeepEqual(collectedSlice, rowsData) {
		fmt.Fprintf(os.Stderr, "FAIL: CopyFromSlice collected data mismatch: got %#v, expected %#v\n", collectedSlice, rowsData)
		os.Exit(1)
	}

	// Error propagation in CopyFromSlice
	expectedCustomErr := errors.New("generator failed")
	failingSliceSource := pgx.CopyFromSlice(5, func(i int) ([]any, error) {
		if i == 2 {
			return nil, expectedCustomErr
		}
		return []any{i}, nil
	})
	failingCount := 0
	for failingSliceSource.Next() {
		_, valErr := failingSliceSource.Values()
		if valErr != nil {
			break
		}
		failingCount++
	}
	if failingCount != 2 {
		fmt.Fprintf(os.Stderr, "FAIL: expected failingSliceSource to yield 2 successful rows before error, got %d\n", failingCount)
		os.Exit(1)
	}
	if !errors.Is(failingSliceSource.Err(), expectedCustomErr) {
		fmt.Fprintf(os.Stderr, "FAIL: expected error %v from failingSliceSource.Err(), got %v\n", expectedCustomErr, failingSliceSource.Err())
		os.Exit(1)
	}

	// 6. assert pgx.CopyFromRows constructs CopyFromSource from 2D slices and yields all rows sequentially
	rowsSliceData := [][]any{
		{"alpha", 1},
		{"beta", 2},
	}
	rowsSource := pgx.CopyFromRows(rowsSliceData)
	var collectedRows [][]any
	for rowsSource.Next() {
		v, err := rowsSource.Values()
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: unexpected rowsSource Values() error: %v\n", err)
			os.Exit(1)
		}
		collectedRows = append(collectedRows, v)
	}
	if err := rowsSource.Err(); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: unexpected CopyFromRows.Err(): %v\n", err)
		os.Exit(1)
	}
	if !reflect.DeepEqual(collectedRows, rowsSliceData) {
		fmt.Fprintf(os.Stderr, "FAIL: CopyFromRows collected data mismatch: got %#v, expected %#v\n", collectedRows, rowsSliceData)
		os.Exit(1)
	}

	fmt.Println("PASS: all pgx contracts verified successfully")
}

Seeder de origem

anônimo