jackc/pgx · error

cannot be encoded to "char

Error message

%v cannot be encoded to "char"

What it means

Encoding a rune into PostgreSQL's single-byte "char" type fails when the rune's value exceeds 255, since "char" holds exactly one byte. This is an out-of-range check on the Go-side value before it is appended to the buffer.

Solutions

  1. Clamp or validate the rune to the 0-255 range before encoding
  2. Use a text type instead of "char" if multi-byte characters must be stored
  3. Map unsupported runes to a sentinel byte value explicitly
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at pgtype/qchar.go:52 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/a8b3d584cfe7c61f. Report an issue: GitHub.

Appendix: source

Thrown at pgtype/qchar.go:52

	}

	return nil
}

type encodePlanQcharCodecByte struct{}

func (encodePlanQcharCodecByte) Encode(value any, buf []byte) (newBuf []byte, err error) {
	b := value.(byte)
	buf = append(buf, b)
	return buf, nil
}

type encodePlanQcharCodecRune struct{}

func (encodePlanQcharCodecRune) Encode(value any, buf []byte) (newBuf []byte, err error) {
	r := value.(rune)
	if r > math.MaxUint8 {
		return nil, fmt.Errorf(`%v cannot be encoded to "char"`, r)
	}
	b := byte(r)
	buf = append(buf, b)
	return buf, nil
}

func (QCharCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan {
	switch format {
	case TextFormatCode, BinaryFormatCode:
		switch target.(type) {
		case *byte:
			return scanPlanQcharCodecByte{}
		case *rune:
			return scanPlanQcharCodecRune{}
		case *string:
			return scanPlanQcharCodecString{}
		}
	}

View on GitHub (pinned to ec1a0befd2)