Exemple
github.com/jackc/pgx/v5 v5.10.0: pgx.Conn.BeginTx
Échantillon vérifié pour golang github.com/jackc/pgx/v5 v5.10.0: pgx.Conn.BeginTx. Le contrat s'est exécuté sur go 1.26 · linux alpine/x64 · docker et a…
sha256:27981df6a19e12ce85470e2df1f708788b6faeeae89ae1b1fb0942e18dcf19ff
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é
linux 24 · ubuntu · glibc 2.39 x64 go
Environnements des exécutions de vérification
| Environnement | Contrat | Étapes | Exécution |
|---|---|---|---|
| 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 |
Cas
HOW- Objectif
- verify pgx.Conn.BeginTx in pkg:golang/github.com/jackc/pgx/v5@v5.10.0
- Paquets
- Symboles
-
- pgx.Conn.BeginTx
- Créé
- 2026-08-27T02:17:28Z
Contrat
- pgx.Conn.BeginTx starts a transaction with custom isolation level and access mode
- pgx.Tx Commit successfully commits an active transaction
- pgx.Tx Rollback aborts an active transaction and reverts uncommitted changes
- pgx.Tx.Begin creates nested transaction savepoints that can be individually rolled back or committed
- pgx.Tx Commit and Rollback return pgx.ErrTxClosed on already completed transactions
- pgx.Conn.BeginTx with cancelled context returns an error without starting a transaction
Fichiers
- PROMPT.md
- csx.json
- go.mod
- go.sum
- sample.go
- spec.json
- test/contract.go
Code source
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.Conn.BeginTx 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.Conn.BeginTx
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.
{"case":{"caseId":"case:sha256:1143e007fd857bce65677b484c75a49ca2185359e351b0d4adb7946f3f000bc9","contract":["pgx.Conn.BeginTx starts a transaction with custom isolation level and access mode","pgx.Tx Commit successfully commits an active transaction","pgx.Tx Rollback aborts an active transaction and reverts uncommitted changes","pgx.Tx.Begin creates nested transaction savepoints that can be individually rolled back or committed","pgx.Tx Commit and Rollback return pgx.ErrTxClosed on already completed transactions","pgx.Conn.BeginTx with cancelled context returns an error without starting a transaction"],"goal":"verify pgx.Conn.BeginTx 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.Conn.BeginTx"]},"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.10.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/jackc/pgx/v5@v5.10.0","symbols":["pgx.Conn.BeginTx"],"verifierAdapter":"golang@1"}
module sample
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
golang.org/x/text v0.29.0 // indirect
)
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=
package sample
import (
"context"
"fmt"
"net"
"strings"
"sync"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgproto3"
)
// StartTx begins a transaction on the connection using the provided transaction options.
func StartTx(ctx context.Context, conn *pgx.Conn, opts pgx.TxOptions) (pgx.Tx, error) {
if conn == nil {
return nil, fmt.Errorf("connection cannot be nil")
}
return conn.BeginTx(ctx, opts)
}
// WithTransaction executes an operation within a transaction managed by BeginTx.
// If fn returns an error, the transaction is rolled back; otherwise it is committed.
func WithTransaction(ctx context.Context, conn *pgx.Conn, opts pgx.TxOptions, fn func(tx pgx.Tx) error) error {
tx, err := StartTx(ctx, conn, opts)
if err != nil {
return fmt.Errorf("begin transaction failed: %w", err)
}
defer func() {
_ = tx.Rollback(ctx)
}()
if err := fn(tx); err != nil {
return err
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit transaction failed: %w", err)
}
return nil
}
// WithSavepoint executes an operation within a nested transaction (savepoint) created from an active transaction.
func WithSavepoint(ctx context.Context, tx pgx.Tx, fn func(spTx pgx.Tx) error) error {
if tx == nil {
return fmt.Errorf("parent transaction cannot be nil")
}
spTx, err := tx.Begin(ctx)
if err != nil {
return fmt.Errorf("create savepoint failed: %w", err)
}
defer func() {
_ = spTx.Rollback(ctx)
}()
if err := fn(spTx); err != nil {
return err
}
if err := spTx.Commit(ctx); err != nil {
return fmt.Errorf("release savepoint failed: %w", err)
}
return nil
}
// MockPostgresServer provides a lightweight offline mock PostgreSQL server for testing pgx transactions.
type MockPostgresServer struct {
listener net.Listener
queries []string
mu sync.Mutex
}
// StartMockPostgresServer initializes and starts a local mock PostgreSQL server.
func StartMockPostgresServer() (*MockPostgresServer, error) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, fmt.Errorf("failed to bind mock server: %w", err)
}
srv := &MockPostgresServer{
listener: ln,
}
go srv.serve()
return srv, nil
}
// Address returns the TCP address of the mock server.
func (s *MockPostgresServer) Address() string {
return s.listener.Addr().String()
}
// RecordedQueries returns all queries executed against the mock server.
func (s *MockPostgresServer) RecordedQueries() []string {
s.mu.Lock()
defer s.mu.Unlock()
copied := make([]string, len(s.queries))
copy(copied, s.queries)
return copied
}
// Close terminates the mock server listener.
func (s *MockPostgresServer) Close() error {
return s.listener.Close()
}
func (s *MockPostgresServer) serve() {
for {
conn, err := s.listener.Accept()
if err != nil {
return
}
go s.handleConnection(conn)
}
}
func (s *MockPostgresServer) handleConnection(conn net.Conn) {
defer conn.Close()
backend := pgproto3.NewBackend(conn, conn)
msg, err := backend.ReceiveStartupMessage()
if err != nil {
return
}
switch msg.(type) {
case *pgproto3.StartupMessage:
backend.Send(&pgproto3.AuthenticationOk{})
backend.Send(&pgproto3.ParameterStatus{Name: "server_version", Value: "15.0"})
backend.Send(&pgproto3.ReadyForQuery{TxStatus: 'I'})
if err := backend.Flush(); err != nil {
return
}
default:
return
}
for {
feMsg, err := backend.Receive()
if err != nil {
return
}
switch m := feMsg.(type) {
case *pgproto3.Query:
q := strings.TrimSpace(strings.ToLower(m.String))
s.mu.Lock()
s.queries = append(s.queries, q)
s.mu.Unlock()
tag := "OK"
status := byte('I')
if strings.HasPrefix(q, "begin") {
tag = "BEGIN"
status = 'T'
} else if strings.HasPrefix(q, "savepoint") {
tag = "SAVEPOINT"
status = 'T'
} else if strings.HasPrefix(q, "release") {
tag = "RELEASE"
status = 'T'
} else if strings.HasPrefix(q, "rollback to") {
tag = "ROLLBACK"
status = 'T'
} else if q == "commit" {
tag = "COMMIT"
status = 'I'
} else if q == "rollback" {
tag = "ROLLBACK"
status = 'I'
}
backend.Send(&pgproto3.CommandComplete{CommandTag: []byte(tag)})
backend.Send(&pgproto3.ReadyForQuery{TxStatus: status})
if err := backend.Flush(); err != nil {
return
}
case *pgproto3.Terminate:
return
}
}
}
{
"schemaVersion": 1,
"goal": "verify pgx.Conn.BeginTx 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.Conn.BeginTx"
]
}
package main
import (
"context"
"errors"
"fmt"
"net"
"os"
"sample"
"strings"
"github.com/jackc/pgx/v5"
)
func main() {
server, err := sample.StartMockPostgresServer()
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [setup]: StartMockPostgresServer error: %v\n", err)
os.Exit(1)
}
defer server.Close()
host, port, err := net.SplitHostPort(server.Address())
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [setup]: SplitHostPort error: %v\n", err)
os.Exit(1)
}
connStr := fmt.Sprintf("postgres://user:pass@%s:%s/testdb?sslmode=disable", host, port)
cfg, err := pgx.ParseConfig(connStr)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [setup]: ParseConfig error: %v\n", err)
os.Exit(1)
}
ctx := context.Background()
conn, err := pgx.ConnectConfig(ctx, cfg)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [setup]: ConnectConfig error: %v\n", err)
os.Exit(1)
}
defer conn.Close(ctx)
// Assertion 1: pgx.Conn.BeginTx starts a transaction with custom isolation level and access mode
opts := pgx.TxOptions{
IsoLevel: pgx.Serializable,
AccessMode: pgx.ReadOnly,
DeferrableMode: pgx.Deferrable,
}
tx1, err := conn.BeginTx(ctx, opts)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [1]: BeginTx failed: %v\n", err)
os.Exit(1)
}
if tx1 == nil {
fmt.Fprintf(os.Stderr, "FAIL [1]: BeginTx returned nil Tx\n")
os.Exit(1)
}
if tx1.Conn() != conn {
fmt.Fprintf(os.Stderr, "FAIL [1]: tx1.Conn() did not return underlying connection\n")
os.Exit(1)
}
// Assertion 2: pgx.Tx Commit successfully commits an active transaction
err = tx1.Commit(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [2]: Commit failed: %v\n", err)
os.Exit(1)
}
// Check query sent for serializable read-only deferrable transaction
queries := server.RecordedQueries()
foundBegin := false
for _, q := range queries {
if strings.Contains(q, "begin") && strings.Contains(q, "serializable") && strings.Contains(q, "read only") && strings.Contains(q, "deferrable") {
foundBegin = true
break
}
}
if !foundBegin {
fmt.Fprintf(os.Stderr, "FAIL [1/2]: expected BEGIN with serializable read only deferrable, got queries: %v\n", queries)
os.Exit(1)
}
// Assertion 3: pgx.Tx Rollback aborts an active transaction and reverts uncommitted changes
tx2, err := conn.BeginTx(ctx, pgx.TxOptions{
IsoLevel: pgx.RepeatableRead,
AccessMode: pgx.ReadWrite,
})
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [3]: BeginTx for tx2 failed: %v\n", err)
os.Exit(1)
}
err = tx2.Rollback(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [3]: Rollback failed: %v\n", err)
os.Exit(1)
}
// Assertion 4: pgx.Tx.Begin creates nested transaction savepoints that can be individually rolled back or committed
tx3, err := conn.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [4]: BeginTx for tx3 failed: %v\n", err)
os.Exit(1)
}
savepointTx, err := tx3.Begin(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [4]: tx.Begin (savepoint) failed: %v\n", err)
os.Exit(1)
}
if savepointTx == nil {
fmt.Fprintf(os.Stderr, "FAIL [4]: tx.Begin returned nil savepoint Tx\n")
os.Exit(1)
}
err = savepointTx.Rollback(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [4]: savepointTx.Rollback failed: %v\n", err)
os.Exit(1)
}
// Parent tx can still be committed after rolling back savepoint
err = tx3.Commit(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "FAIL [4]: tx3.Commit after savepoint rollback failed: %v\n", err)
os.Exit(1)
}
// Assertion 5: pgx.Tx Commit and Rollback return pgx.ErrTxClosed on already completed transactions
err = tx1.Commit(ctx)
if !errors.Is(err, pgx.ErrTxClosed) {
fmt.Fprintf(os.Stderr, "FAIL [5]: expected ErrTxClosed on double Commit, got %v\n", err)
os.Exit(1)
}
err = tx1.Rollback(ctx)
if !errors.Is(err, pgx.ErrTxClosed) {
fmt.Fprintf(os.Stderr, "FAIL [5]: expected ErrTxClosed on Rollback after Commit, got %v\n", err)
os.Exit(1)
}
err = tx2.Rollback(ctx)
if !errors.Is(err, pgx.ErrTxClosed) {
fmt.Fprintf(os.Stderr, "FAIL [5]: expected ErrTxClosed on double Rollback, got %v\n", err)
os.Exit(1)
}
// Assertion 6: pgx.Conn.BeginTx with cancelled context returns an error without starting a transaction
cancCtx, cancel := context.WithCancel(ctx)
cancel()
_, err = conn.BeginTx(cancCtx, pgx.TxOptions{})
if err == nil {
fmt.Fprintf(os.Stderr, "FAIL [6]: expected error when BeginTx is called with cancelled context\n")
os.Exit(1)
}
fmt.Println("All pgx.Conn.BeginTx contract assertions passed successfully.")
}
Seeder d'origine
anonyme