Ejemplo
github.com/jackc/pgx/v5 v5.10.0: Differentiate CollectOneRow and CollectExactlyOneRow cardinality enforcement, distinguish empty PostgreSQL ranges from SQL NULL in pgtype.Range, decode infinity timestamps into pgtype.Timestamptz without time.Time failure, and verify nested savepoint transaction lifecycle
Muestra verificada para golang github.com/jackc/pgx/v5 v5.10.0: Differentiate CollectOneRow and CollectExactlyOneRow cardinality enforcement, distinguish…
sha256:39b6a8729d5dbe2e91f27c744a4aad5510b74b605fdc30802740b9db2bbea784
Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido.
Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas.
MIT-0
Evidencia de ejecución
El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.
- Base de evidencia
- Contrato firmado aprobado
- Recibos de verificación
- 2
- Claves de firma que lo compilaron
- 2
Entorno declarado
go linux x64 go go gomod
Entornos de las ejecuciones de verificación
| Entorno | Contrato | Etapas | Ejecución |
|---|---|---|---|
| go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1 |
2026-08-17 |
| go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1 |
2026-08-18 |
Caso
HOW- Objetivo
- Differentiate CollectOneRow and CollectExactlyOneRow cardinality enforcement, distinguish empty PostgreSQL ranges from SQL NULL in pgtype.Range, decode infinity timestamps into pgtype.Timestamptz without time.Time failure, and verify nested savepoint transaction lifecycle
- Paquetes
- Símbolos
-
- pgx.CollectOneRow
- pgx.CollectExactlyOneRow
- pgx.CollectRows
- pgx.ForEachRow
- pgtype.Range
- pgtype.Timestamptz
- pgtype.Interval
- pgtype.Bits
- pgx.Tx
- Entorno
- go
- Creado
- 2026-08-17T20:07:10Z
Contrato
- CollectOneRow consumes the first row without error on multi-row results whereas CollectExactlyOneRow rejects multiple rows with ErrTooManyRows
- assert empty PostgreSQL ranges parse as Valid=true with Empty bound types whereas SQL NULL ranges parse as Valid=false
- assert scanning PostgreSQL infinity or -infinity timestamps into time.Time fails whereas pgtype.Timestamptz and pgtype.Timestamp record InfinityModifier
- assert pgtype.Interval preserves calendar Months, Days, and Microseconds as distinct components
- assert pgtype.Bits stores bit length and MSB-aligned byte representations
- assert nested tx.Begin subtransactions execute savepoint, rollback to savepoint, and release savepoint commands leaving outer transaction intact
Archivos
- NOTES.md
- csx.json
- go.mod
- go.sum
- sample_test.go
Código fuente
# Notes
## Search Results
`search_known_solution` returned existing samples `sha256:1828fbbfed3d7f79407a28034dc3d318b13a6d334dbb0990653dedf2c9696b20` (DSN connection configuration, query execution modes, and pool parameter extraction), `sha256:ff6af08598a4e3fc137ed941f6d4febe37974700677148ef2b547bef8cdf052c` (extended protocol multi-statement execution, array NULL element scanning, and batch error handling), and `sha256:99c23efc0d189ad74817464888e317aebe1d850b1a21d9ccc02346cd485f882a` (ConnConfig initialization, multi-host fallbacks, and ErrNoRows checking).
We author a distinct contract targeting row cardinality constraints in generic collectors (`CollectOneRow` vs `CollectExactlyOneRow`), `pgtype.Range` representation of PostgreSQL empty ranges versus SQL NULL, PostgreSQL `infinity` timestamp decoding, calendar component preservation in `pgtype.Interval`, and savepoint lifecycles in `pgx.Tx` subtransactions.
## Pinned Release
- `github.com/jackc/pgx/v5` `v5.10.0`
## Observed Behaviour
1. **Row Collector Cardinality (`CollectOneRow` vs `CollectExactlyOneRow`)**:
- `pgx.CollectOneRow` consumes the first row returned by `pgx.Rows` and closes the iterator without raising an error when multiple rows exist.
- `pgx.CollectExactlyOneRow` verifies that exactly one row was returned; if more than one row exists, it returns `pgx.ErrTooManyRows`.
- Both functions return `pgx.ErrNoRows` when zero rows are returned.
- `pgx.ForEachRow` iterates through rows, populates target variables, and halts execution immediately when the callback returns an error.
2. **Range Type Representation (`pgtype.Range[T]`)**:
- PostgreSQL range string `"[10,20)"` parses into `pgtype.Range[int32]` with `Lower: 10`, `Upper: 20`, `LowerType: pgtype.Inclusive`, `UpperType: pgtype.Exclusive`, and `Valid: true`.
- Unbounded bounds (such as `"(,50]"` or `"[100,)"`) set the corresponding `LowerType` or `UpperType` to `pgtype.Unbounded`.
- PostgreSQL `'empty'` range string parses as `Valid: true` with `LowerType: pgtype.Empty` and `UpperType: pgtype.Empty`.
- SQL `NULL` range parses with `Valid: false`.
3. **PostgreSQL Infinity Timestamps**:
- Scanning PostgreSQL `'infinity'` or `'-infinity'` into standard Go `*time.Time` fails because standard Go `time.Time` cannot represent infinite timestamps.
- Scanning into `*pgtype.Timestamptz` or `*pgtype.Timestamp` succeeds with `Valid: true` and `InfinityModifier: pgtype.Infinity` (or `pgtype.NegativeInfinity`).
- Scanning `'infinity'` into `*pgtype.Date` succeeds with `Valid: true` and `InfinityModifier: pgtype.Infinity`.
4. **Interval and Bit String Types**:
- PostgreSQL `interval` stores calendar `Months`, `Days`, and `Microseconds` as independent integer quantities to preserve timezone and variable-length month arithmetic.
- PostgreSQL `bit`/`varbit` string (e.g. `"1101001"`) parses into `pgtype.Bits` with `Len: 7` and MSB-aligned bytes (`[]byte{0xd2}`).
5. **Subtransactions and Savepoint Lifecycle**:
- Calling `tx.Begin` on an existing `pgx.Tx` issues `savepoint sp_1`.
- Calling `subTx.Rollback` issues `rollback to savepoint sp_1`, keeping the outer transaction open and valid.
- Calling `subTx.Commit` issues `release savepoint sp_1`.
- Subsequent `Rollback` calls on closed transactions return `pgx.ErrTxClosed`.
## How the Wrong Expectation Fails
- **Row Cardinality (`CollectOneRow`)**: Silently with unexpected application state. If a developer expects `CollectOneRow` to guard against duplicate records, queries returning duplicate rows will succeed without error, silently discarding subsequent rows.
- **Empty Ranges (`pgtype.Range`)**: Silently with inverted logic. A developer testing `!r.Valid` to check if a range is empty will evaluate `'empty'` ranges as non-empty because PostgreSQL empty ranges have `Valid: true` with `LowerType == pgtype.Empty`.
- **Infinity Timestamps (`time.Time`)**: Loudly at runtime with `cannot scan Infinity into *time.Time` when querying PostgreSQL tables containing infinity values.
{"case":{"believed":"CollectOneRow errors when multiple rows match, empty PostgreSQL ranges scan as Valid=false like SQL NULL, and PostgreSQL infinity timestamps scan into time.Time","caseId":"case:sha256:4a765fd3bebeed1d75b84f44fb0880221178ceaae02f9c93be55976c8a33040c","contract":["CollectOneRow consumes the first row without error on multi-row results whereas CollectExactlyOneRow rejects multiple rows with ErrTooManyRows","assert empty PostgreSQL ranges parse as Valid=true with Empty bound types whereas SQL NULL ranges parse as Valid=false","assert scanning PostgreSQL infinity or -infinity timestamps into time.Time fails whereas pgtype.Timestamptz and pgtype.Timestamp record InfinityModifier","assert pgtype.Interval preserves calendar Months, Days, and Microseconds as distinct components","assert pgtype.Bits stores bit length and MSB-aligned byte representations","assert nested tx.Begin subtransactions execute savepoint, rollback to savepoint, and release savepoint commands leaving outer transaction intact"],"goal":"Differentiate CollectOneRow and CollectExactlyOneRow cardinality enforcement, distinguish empty PostgreSQL ranges from SQL NULL in pgtype.Range, decode infinity timestamps into pgtype.Timestamptz without time.Time failure, and verify nested savepoint transaction lifecycle","kind":"HOW","packages":["pkg:golang/github.com/jackc/pgx/v5@v5.10.0"],"schemaVersion":1,"symbols":["pgx.CollectOneRow","pgx.CollectExactlyOneRow","pgx.CollectRows","pgx.ForEachRow","pgtype.Range","pgtype.Timestamptz","pgtype.Interval","pgtype.Bits","pgx.Tx"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"gomod","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/jackc/pgx/v5@v5.10.0"],"schemaVersion":1,"symbols":["pgx.CollectOneRow","pgx.CollectExactlyOneRow","pgx.CollectRows","pgx.ForEachRow","pgtype.Range","pgtype.Timestamptz","pgtype.Interval","pgtype.Bits","pgx.Tx"],"verifierAdapter":"golang@1"}
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
)
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"
"errors"
"net"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgproto3"
"github.com/jackc/pgx/v5/pgtype"
)
type Customer struct {
ID int32 `db:"id"`
Email string `db:"email"`
}
// newMockConn creates a net.Pipe connection simulating PostgreSQL backend for pgx protocol tests
func newMockConn(t *testing.T, rowCount int, customQueryHandler func(m pgproto3.FrontendMessage, b *pgproto3.Backend) bool) (*pgx.Conn, context.Context) {
t.Helper()
cfg, err := pgx.ParseConfig("postgres://127.0.0.1/mydb?sslmode=disable")
if err != nil {
t.Fatalf("ParseConfig failed: %v", err)
}
cfg.DialFunc = func(ctx context.Context, _, _ string) (net.Conn, error) {
c, s := net.Pipe()
go func(conn net.Conn) {
defer conn.Close()
b := pgproto3.NewBackend(conn, conn)
if msg, _ := b.ReceiveStartupMessage(); msg != nil {
if _, ok := msg.(*pgproto3.SSLRequest); ok {
_, _ = conn.Write([]byte{'N'})
_, _ = b.ReceiveStartupMessage()
}
}
b.Send(&pgproto3.AuthenticationOk{})
b.Send(&pgproto3.ParameterStatus{Name: "standard_conforming_strings", Value: "on"})
b.Send(&pgproto3.ParameterStatus{Name: "server_version", Value: "16.0"})
b.Send(&pgproto3.ParameterStatus{Name: "client_encoding", Value: "UTF8"})
b.Send(&pgproto3.ReadyForQuery{TxStatus: 'I'})
_ = b.Flush()
for {
msg, err := b.Receive()
if err != nil || msg == nil {
return
}
if customQueryHandler != nil && customQueryHandler(msg, b) {
continue
}
switch m := msg.(type) {
case *pgproto3.Terminate:
return
case *pgproto3.Query:
// Simple protocol query
b.Send(&pgproto3.CommandComplete{CommandTag: []byte("OK")})
b.Send(&pgproto3.ReadyForQuery{TxStatus: 'I'})
_ = b.Flush()
case *pgproto3.Parse:
b.Send(&pgproto3.ParseComplete{})
_ = b.Flush()
case *pgproto3.Describe:
if m.ObjectType == 'S' {
b.Send(&pgproto3.ParameterDescription{})
}
b.Send(&pgproto3.RowDescription{
Fields: []pgproto3.FieldDescription{
{Name: []byte("id"), DataTypeOID: pgtype.Int4OID, Format: 1},
{Name: []byte("email"), DataTypeOID: pgtype.TextOID, Format: 1},
},
})
_ = b.Flush()
case *pgproto3.Bind:
b.Send(&pgproto3.BindComplete{})
_ = b.Flush()
case *pgproto3.Execute:
for i := 1; i <= rowCount; i++ {
idBytes := []byte{byte(i >> 24), byte(i >> 16), byte(i >> 8), byte(i)}
emailBytes := []byte("user@example.com")
b.Send(&pgproto3.DataRow{Values: [][]byte{idBytes, emailBytes}})
}
b.Send(&pgproto3.CommandComplete{CommandTag: []byte("SELECT")})
_ = b.Flush()
case *pgproto3.Sync:
b.Send(&pgproto3.ReadyForQuery{TxStatus: 'I'})
_ = b.Flush()
}
}
}(s)
return c, nil
}
ctx := context.Background()
conn, err := pgx.ConnectConfig(ctx, cfg)
if err != nil {
t.Fatalf("ConnectConfig failed: %v", err)
}
t.Cleanup(func() { _ = conn.Close(ctx) })
return conn, ctx
}
func TestCollectRows_OneVsExactlyOneVsAll(t *testing.T) {
// 1. When a query produces multiple rows (2 rows):
// CollectOneRow consumes the first row and closes rows WITHOUT error.
conn2, ctx2 := newMockConn(t, 2, nil)
rows2, err := conn2.Query(ctx2, "SELECT id, email FROM customers")
if err != nil {
t.Fatalf("Query failed: %v", err)
}
c1, err := pgx.CollectOneRow(rows2, pgx.RowToStructByName[Customer])
if err != nil {
t.Fatalf("expected CollectOneRow to succeed on multiple rows, got: %v", err)
}
if c1.ID != 1 || c1.Email != "user@example.com" {
t.Fatalf("unexpected customer: %+v", c1)
}
// In contrast, CollectExactlyOneRow strictly enforces a single row and returns ErrTooManyRows.
conn2Exact, ctx2Exact := newMockConn(t, 2, nil)
rows2Exact, err := conn2Exact.Query(ctx2Exact, "SELECT id, email FROM customers")
if err != nil {
t.Fatalf("Query failed: %v", err)
}
_, err = pgx.CollectExactlyOneRow(rows2Exact, pgx.RowToStructByName[Customer])
if !errors.Is(err, pgx.ErrTooManyRows) {
t.Fatalf("expected ErrTooManyRows from CollectExactlyOneRow on 2 rows, got: %v", err)
}
// 2. When a query produces 0 rows:
// Both CollectOneRow and CollectExactlyOneRow return ErrNoRows.
conn0, ctx0 := newMockConn(t, 0, nil)
rows0, err := conn0.Query(ctx0, "SELECT id, email FROM customers")
if err != nil {
t.Fatalf("Query failed: %v", err)
}
_, err = pgx.CollectOneRow(rows0, pgx.RowToStructByName[Customer])
if !errors.Is(err, pgx.ErrNoRows) {
t.Fatalf("expected ErrNoRows from CollectOneRow on 0 rows, got: %v", err)
}
conn0Exact, ctx0Exact := newMockConn(t, 0, nil)
rows0Exact, err := conn0Exact.Query(ctx0Exact, "SELECT id, email FROM customers")
if err != nil {
t.Fatalf("Query failed: %v", err)
}
_, err = pgx.CollectExactlyOneRow(rows0Exact, pgx.RowToStructByName[Customer])
if !errors.Is(err, pgx.ErrNoRows) {
t.Fatalf("expected ErrNoRows from CollectExactlyOneRow on 0 rows, got: %v", err)
}
// 3. CollectRows with RowToMap gathers every row into a map slice.
connAll, ctxAll := newMockConn(t, 2, nil)
rowsAll, err := connAll.Query(ctxAll, "SELECT id, email FROM customers")
if err != nil {
t.Fatalf("Query failed: %v", err)
}
maps, err := pgx.CollectRows(rowsAll, pgx.RowToMap)
if err != nil {
t.Fatalf("CollectRows(RowToMap) failed: %v", err)
}
if len(maps) != 2 || maps[0]["email"] != "user@example.com" || maps[1]["id"] != int32(2) {
t.Fatalf("unexpected RowToMap result: %+v", maps)
}
// 4. ForEachRow iterates over rows and safely terminates if callback returns an error.
connForEach, ctxForEach := newMockConn(t, 5, nil)
rowsForEach, err := connForEach.Query(ctxForEach, "SELECT id, email FROM customers")
if err != nil {
t.Fatalf("Query failed: %v", err)
}
var visitedCount int
var scannedID int32
var scannedEmail string
errHalt := errors.New("halt iteration")
tag, err := pgx.ForEachRow(rowsForEach, []any{&scannedID, &scannedEmail}, func() error {
visitedCount++
if visitedCount == 2 {
return errHalt
}
return nil
})
if !errors.Is(err, errHalt) {
t.Fatalf("expected ForEachRow to return errHalt, got: %v", err)
}
if visitedCount != 2 {
t.Fatalf("expected 2 visited rows before halting, got visited=%d tag=%v", visitedCount, tag)
}
}
func TestRange_BoundTypesAndEmptyDistinction(t *testing.T) {
tm := pgtype.NewMap()
// 1. Standard inclusive-exclusive range "[10,20)"
var rStd pgtype.Range[int32]
err := tm.Scan(pgtype.Int4rangeOID, pgtype.TextFormatCode, []byte("[10,20)"), &rStd)
if err != nil {
t.Fatalf("failed to scan standard range: %v", err)
}
if !rStd.Valid || rStd.Lower != 10 || rStd.Upper != 20 || rStd.LowerType != pgtype.Inclusive || rStd.UpperType != pgtype.Exclusive {
t.Fatalf("unexpected standard range: %+v", rStd)
}
// 2. Unbounded lower and upper ranges
var rLowerUnbounded pgtype.Range[int32]
err = tm.Scan(pgtype.Int4rangeOID, pgtype.TextFormatCode, []byte("(,50]"), &rLowerUnbounded)
if err != nil {
t.Fatalf("failed to scan lower unbounded range: %v", err)
}
if !rLowerUnbounded.Valid || rLowerUnbounded.LowerType != pgtype.Unbounded || rLowerUnbounded.UpperType != pgtype.Inclusive || rLowerUnbounded.Upper != 50 {
t.Fatalf("unexpected lower unbounded range: %+v", rLowerUnbounded)
}
var rUpperUnbounded pgtype.Range[int32]
err = tm.Scan(pgtype.Int4rangeOID, pgtype.TextFormatCode, []byte("[100,)"), &rUpperUnbounded)
if err != nil {
t.Fatalf("failed to scan upper unbounded range: %v", err)
}
if !rUpperUnbounded.Valid || rUpperUnbounded.LowerType != pgtype.Inclusive || rUpperUnbounded.Lower != 100 || rUpperUnbounded.UpperType != pgtype.Unbounded {
t.Fatalf("unexpected upper unbounded range: %+v", rUpperUnbounded)
}
var rFullyUnbounded pgtype.Range[int32]
err = tm.Scan(pgtype.Int4rangeOID, pgtype.TextFormatCode, []byte("(,)"), &rFullyUnbounded)
if err != nil {
t.Fatalf("failed to scan fully unbounded range: %v", err)
}
if !rFullyUnbounded.Valid || rFullyUnbounded.LowerType != pgtype.Unbounded || rFullyUnbounded.UpperType != pgtype.Unbounded {
t.Fatalf("unexpected fully unbounded range: %+v", rFullyUnbounded)
}
// 3. PostgreSQL "empty" range vs SQL NULL:
// "empty" range is a VALID range with LowerType == Empty and UpperType == Empty.
var rEmpty pgtype.Range[int32]
err = tm.Scan(pgtype.Int4rangeOID, pgtype.TextFormatCode, []byte("empty"), &rEmpty)
if err != nil {
t.Fatalf("failed to scan empty range: %v", err)
}
if !rEmpty.Valid || rEmpty.LowerType != pgtype.Empty || rEmpty.UpperType != pgtype.Empty {
t.Fatalf("expected Valid=true with Empty bound types for 'empty', got %+v", rEmpty)
}
// SQL NULL range yields Valid=false
var rNull pgtype.Range[int32]
err = tm.Scan(pgtype.Int4rangeOID, pgtype.TextFormatCode, nil, &rNull)
if err != nil {
t.Fatalf("failed to scan SQL NULL range: %v", err)
}
if rNull.Valid {
t.Fatalf("expected Valid=false for SQL NULL range, got %+v", rNull)
}
}
func TestInfinityTimestamps_TimeVsPgtype(t *testing.T) {
tm := pgtype.NewMap()
// 1. Scanning PostgreSQL 'infinity' timestamp into standard Go time.Time fails
var stdTime time.Time
err := tm.Scan(pgtype.TimestamptzOID, pgtype.TextFormatCode, []byte("infinity"), &stdTime)
if err == nil || !strings.Contains(err.Error(), "cannot scan Infinity into *time.Time") {
t.Fatalf("expected failure scanning infinity into time.Time, got: %v", err)
}
var stdTimeNeg time.Time
err = tm.Scan(pgtype.TimestamptzOID, pgtype.TextFormatCode, []byte("-infinity"), &stdTimeNeg)
if err == nil || !strings.Contains(err.Error(), "cannot scan -Infinity into *time.Time") {
t.Fatalf("expected failure scanning -infinity into time.Time, got: %v", err)
}
// 2. Scanning 'infinity' into pgtype.Timestamptz succeeds and records InfinityModifier
var tstzInf pgtype.Timestamptz
err = tm.Scan(pgtype.TimestamptzOID, pgtype.TextFormatCode, []byte("infinity"), &tstzInf)
if err != nil {
t.Fatalf("failed to scan infinity into Timestamptz: %v", err)
}
if !tstzInf.Valid || tstzInf.InfinityModifier != pgtype.Infinity {
t.Fatalf("expected Valid=true and InfinityModifier=Infinity, got %+v", tstzInf)
}
// 3. Scanning '-infinity' into pgtype.Timestamp succeeds with NegativeInfinity modifier
var tsNegInf pgtype.Timestamp
err = tm.Scan(pgtype.TimestampOID, pgtype.TextFormatCode, []byte("-infinity"), &tsNegInf)
if err != nil {
t.Fatalf("failed to scan -infinity into Timestamp: %v", err)
}
if !tsNegInf.Valid || tsNegInf.InfinityModifier != pgtype.NegativeInfinity {
t.Fatalf("expected Valid=true and InfinityModifier=NegativeInfinity, got %+v", tsNegInf)
}
// 4. Scanning 'infinity' into pgtype.Date succeeds with Infinity modifier
var dInf pgtype.Date
err = tm.Scan(pgtype.DateOID, pgtype.TextFormatCode, []byte("infinity"), &dInf)
if err != nil {
t.Fatalf("failed to scan infinity into Date: %v", err)
}
if !dInf.Valid || dInf.InfinityModifier != pgtype.Infinity {
t.Fatalf("expected Valid=true and InfinityModifier=Infinity for Date, got %+v", dInf)
}
}
func TestIntervalAndBits_FieldDecomposition(t *testing.T) {
tm := pgtype.NewMap()
// 1. PostgreSQL interval decomposes calendar Months, Days, and Microseconds separately
// "2 years 3 mons 4 days 05:06:07.890123" -> 27 months, 4 days, 18367890123 microseconds
var iv pgtype.Interval
err := tm.Scan(pgtype.IntervalOID, pgtype.TextFormatCode, []byte("2 years 3 mons 4 days 05:06:07.890123"), &iv)
if err != nil {
t.Fatalf("failed to scan interval: %v", err)
}
expectedMicroseconds := int64((5*3600+6*60+7)*1_000_000 + 890123)
if !iv.Valid || iv.Months != 27 || iv.Days != 4 || iv.Microseconds != expectedMicroseconds {
t.Fatalf("unexpected interval decomposition: %+v (expected Months:27, Days:4, Microseconds:%d)", iv, expectedMicroseconds)
}
// Negative interval: "-1 day -2 hours" -> Days: -1, Microseconds: -7200000000
var ivNeg pgtype.Interval
err = tm.Scan(pgtype.IntervalOID, pgtype.TextFormatCode, []byte("-1 days -02:00:00"), &ivNeg)
if err != nil {
t.Fatalf("failed to scan negative interval: %v", err)
}
if !ivNeg.Valid || ivNeg.Days != -1 || ivNeg.Microseconds != -7_200_000_000 {
t.Fatalf("unexpected negative interval: %+v", ivNeg)
}
// 2. PostgreSQL bit string: "1101001" (7 bits) packed MSB-first into byte 0xD2 (11010010)
var bits pgtype.Bits
err = tm.Scan(pgtype.VarbitOID, pgtype.TextFormatCode, []byte("1101001"), &bits)
if err != nil {
t.Fatalf("failed to scan bits: %v", err)
}
if !bits.Valid || bits.Len != 7 || len(bits.Bytes) != 1 || bits.Bytes[0] != 0xd2 {
t.Fatalf("unexpected bits struct: %+v (expected Len:7, Bytes:[0xd2])", bits)
}
}
func TestNestedSavepointTransactions(t *testing.T) {
var executedCommands []string
conn, ctx := newMockConn(t, 1, func(m pgproto3.FrontendMessage, b *pgproto3.Backend) bool {
switch msg := m.(type) {
case *pgproto3.Query:
executedCommands = append(executedCommands, msg.String)
b.Send(&pgproto3.CommandComplete{CommandTag: []byte("OK")})
b.Send(&pgproto3.ReadyForQuery{TxStatus: 'T'})
_ = b.Flush()
return true
}
return false
})
// Begin outer transaction
tx, err := conn.Begin(ctx)
if err != nil {
t.Fatalf("conn.Begin failed: %v", err)
}
// Begin subtransaction (creates savepoint)
subTx, err := tx.Begin(ctx)
if err != nil {
t.Fatalf("tx.Begin subtransaction failed: %v", err)
}
// Rollback subtransaction (rolls back and releases savepoint)
err = subTx.Rollback(ctx)
if err != nil {
t.Fatalf("subTx.Rollback failed: %v", err)
}
// Rolling back again on closed subTx returns pgx.ErrTxClosed
err = subTx.Rollback(ctx)
if !errors.Is(err, pgx.ErrTxClosed) {
t.Fatalf("expected ErrTxClosed on second subTx.Rollback, got: %v", err)
}
// Commit outer transaction
err = tx.Commit(ctx)
if err != nil {
t.Fatalf("tx.Commit failed: %v", err)
}
// Verify the savepoint rollback command sequence
expectedSequence := []string{
"begin",
"savepoint sp_1",
"rollback to savepoint sp_1",
"commit",
}
if len(executedCommands) != len(expectedSequence) {
t.Fatalf("unexpected command sequence count: got %v, expected %v", executedCommands, expectedSequence)
}
for i, expected := range expectedSequence {
if executedCommands[i] != expected {
t.Fatalf("command [%d]: expected %q, got %q", i, expected, executedCommands[i])
}
}
// Subtransaction Commit issues "release savepoint sp_1"
var commitCommands []string
connCommit, ctxCommit := newMockConn(t, 1, func(m pgproto3.FrontendMessage, b *pgproto3.Backend) bool {
switch msg := m.(type) {
case *pgproto3.Query:
commitCommands = append(commitCommands, msg.String)
b.Send(&pgproto3.CommandComplete{CommandTag: []byte("OK")})
b.Send(&pgproto3.ReadyForQuery{TxStatus: 'T'})
_ = b.Flush()
return true
}
return false
})
tx2, err := connCommit.Begin(ctxCommit)
if err != nil {
t.Fatalf("tx2 begin failed: %v", err)
}
subTx2, err := tx2.Begin(ctxCommit)
if err != nil {
t.Fatalf("subTx2 begin failed: %v", err)
}
if err := subTx2.Commit(ctxCommit); err != nil {
t.Fatalf("subTx2 commit failed: %v", err)
}
if err := tx2.Commit(ctxCommit); err != nil {
t.Fatalf("tx2 commit failed: %v", err)
}
expectedCommitSequence := []string{
"begin",
"savepoint sp_1",
"release savepoint sp_1",
"commit",
}
if len(commitCommands) != len(expectedCommitSequence) {
t.Fatalf("unexpected commit sequence count: got %v, expected %v", commitCommands, expectedCommitSequence)
}
for i, expected := range expectedCommitSequence {
if commitCommands[i] != expected {
t.Fatalf("commit command [%d]: expected %q, got %q", i, expected, commitCommands[i])
}
}
}