jackc/pgx · error

invalid length for polygon

Error message

invalid length for polygon: %w

What it means

While decoding a binary polygon, the pgio.Reader could not derive a valid point count from the payload (r.Err() set after r.Count(16)), meaning the buffer is too short or misaligned to contain whole 16-byte points. The declared point count is therefore unreliable.

Solutions

  1. Reject the value as malformed binary data and propagate the error
  2. Check that the data came from a PostgreSQL polygon column in binary format, not a truncated or re-encoded buffer
  3. Round-trip through text format if a custom serialization layer is corrupting payloads
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at pgtype/polygon.go:170 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of jackc/pgx@ec1a0befd2 (2026-08-04). Data as JSON: /api/errors/7ed68ce66595ad78. Report an issue: GitHub.

Appendix: source

Thrown at pgtype/polygon.go:170

	return nil
}

type scanPlanBinaryPolygonToPolygonScanner struct{}

func (scanPlanBinaryPolygonToPolygonScanner) Scan(src []byte, dst any) error {
	scanner := (dst).(PolygonScanner)

	if src == nil {
		return scanner.ScanPolygon(Polygon{})
	}

	r := pgio.NewReader(src)

	// Each point is two float64s.
	pointCount := r.Count(16)
	if err := r.Err(); err != nil {
		return fmt.Errorf("invalid length for polygon: %w", err)
	}

	points := make([]Vec2, pointCount)
	for i := range points {
		x := r.Uint64()
		y := r.Uint64()
		points[i] = Vec2{math.Float64frombits(x), math.Float64frombits(y)}
	}

	if err := r.Finish(); err != nil {
		return fmt.Errorf("invalid length for Polygon with %d points: %w", pointCount, err)
	}

	return scanner.ScanPolygon(Polygon{
		P:     points,
		Valid: true,
	})
}

View on GitHub (pinned to ec1a0befd2)