jackc/pgx · error
cannot encode as element of range
Error message
cannot encode %v as element of range
What it means
No encode plan could be found for the range's lower bound: the value's Go type cannot be encoded as the range's element type. This is the type-map lookup failing (PlanEncode returned nil), not a data error.
Solutions
- Register an encoder for the element type in the TypeMap, or use a Go type pgx supports
- Ensure the bound's Go type matches the range element type declared in the database
- Wrap custom types with a codec and register it via pgtype.Map
Defensive patterns
Strategy: type-guard
When it happens
Trigger: Thrown at pgtype/range_codec.go:118 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/2744185c22fe112c.
Report an issue: GitHub.
Appendix: source
Thrown at pgtype/range_codec.go:118
rangeType |= upperUnboundedMask
case Exclusive:
default:
return nil, fmt.Errorf("unknown UpperType: %v", upperType)
}
buf = append(buf, rangeType)
if lowerType != Unbounded {
if lower == nil {
return nil, fmt.Errorf("Lower cannot be NULL unless LowerType is Unbounded")
}
sp := len(buf)
buf = pgio.AppendInt32(buf, -1)
lowerPlan := plan.m.PlanEncode(plan.rc.ElementType.OID, BinaryFormatCode, lower)
if lowerPlan == nil {
return nil, fmt.Errorf("cannot encode %v as element of range", lower)
}
buf, err = lowerPlan.Encode(lower, buf)
if err != nil {
return nil, fmt.Errorf("failed to encode %v as element of range: %w", lower, err)
}
if buf == nil {
return nil, fmt.Errorf("Lower cannot be NULL unless LowerType is Unbounded")
}
pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4))
}
if upperType != Unbounded {
if upper == nil {
return nil, fmt.Errorf("Upper cannot be NULL unless UpperType is Unbounded")
}
View on GitHub (pinned to ec1a0befd2)