CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/golang-github-com-jackc-pgx-v5

pgx is a pure Go driver and toolkit for PostgreSQL providing a native high-performance interface with PostgreSQL-specific features plus a database/sql compatibility adapter.

Overview
Eval results
Files

advanced-codec.mddocs/types/

Advanced Codec

Low-level codec implementation details, OID constants, and wrap plan functions.

Import

import "github.com/jackc/pgx/v5/pgtype"

OID Constants

const (
    BoolOID        = 16
    ByteaOID       = 17
    QCharOID       = 18
    NameOID        = 19
    Int8OID        = 20
    Int2OID        = 21
    Int4OID        = 23
    TextOID        = 25
    OIDOID         = 26
    TIDOID         = 27
    XIDOID         = 28
    CIDOID         = 29
    JSONOID        = 114
    XMLOID         = 142
    PointOID       = 600
    LsegOID        = 601
    PathOID        = 602
    BoxOID         = 603
    PolygonOID     = 604
    LineOID        = 628
    CIDROID        = 650
    Float4OID      = 700
    Float8OID      = 701
    CircleOID      = 718
    MacaddrOID     = 829
    InetOID        = 869
    BoolArrayOID   = 1000
    Int2ArrayOID   = 1005
    Int4ArrayOID   = 1007
    TextArrayOID   = 1009
    Int8ArrayOID   = 1016
    Float4ArrayOID = 1021
    Float8ArrayOID = 1022
    BPCharOID      = 1042
    VarcharOID     = 1043
    DateOID        = 1082
    TimeOID        = 1083
    TimestampOID   = 1114
    TimestamptzOID = 1184
    IntervalOID    = 1186
    NumericOID     = 1700
    UnknownOID             = 705
    RecordOID              = 2249
    RecordArrayOID         = 2287
    UUIDOID                = 2950
    UUIDArrayOID           = 2951
    JSONBOID               = 3802
    JSONBArrayOID          = 3807
    JSONArrayOID           = 199
    JSONPathOID            = 4072
    JSONPathArrayOID       = 4073
    ACLItemOID             = 1033
    ACLItemArrayOID        = 1034
    XID8OID                = 5069
    XID8ArrayOID           = 271
    ByteaArrayOID          = 1001
    QCharArrayOID          = 1002
    NameArrayOID           = 1003
    TIDArrayOID            = 1010
    XIDArrayOID            = 1011
    CIDArrayOID            = 1012
    BPCharArrayOID         = 1014
    VarcharArrayOID        = 1015
    PointArrayOID          = 1017
    LsegArrayOID           = 1018
    PathArrayOID           = 1019
    BoxArrayOID            = 1020
    PolygonArrayOID        = 1027
    OIDArrayOID            = 1028
    DateArrayOID           = 1182
    TimeArrayOID           = 1183
    TimestampArrayOID      = 1115
    TimestamptzArrayOID    = 1185
    TimetzOID              = 1266
    TimetzArrayOID         = 1270
    IntervalArrayOID       = 1187
    NumericArrayOID        = 1231
    BitOID                 = 1560
    BitArrayOID            = 1561
    VarbitOID              = 1562
    VarbitArrayOID         = 1563
    XMLArrayOID            = 143
    LineArrayOID           = 629
    CIDRArrayOID           = 651
    CircleArrayOID         = 719
    Macaddr8OID            = 774
    MacaddrArrayOID        = 1040
    InetArrayOID           = 1041
    Int4rangeOID           = 3904
    Int4rangeArrayOID      = 3905
    NumrangeOID            = 3906
    NumrangeArrayOID       = 3907
    TsrangeOID             = 3908
    TsrangeArrayOID        = 3909
    TstzrangeOID           = 3910
    TstzrangeArrayOID      = 3911
    DaterangeOID           = 3912
    DaterangeArrayOID      = 3913
    Int8rangeOID           = 3926
    Int8rangeArrayOID      = 3927
    Int4multirangeOID      = 4451
    NummultirangeOID       = 4532
    TsmultirangeOID        = 4533
    TstzmultirangeOID      = 4534
    DatemultirangeOID      = 4535
    Int8multirangeOID      = 4536
    Int4multirangeArrayOID = 6150
    NummultirangeArrayOID  = 6151
    TsmultirangeArrayOID   = 6152
    TstzmultirangeArrayOID = 6153
    DatemultirangeArrayOID = 6155
    Int8multirangeArrayOID = 6157
)

Codec Types with Configuration Fields

These codecs have configurable struct fields:

// ArrayCodec — codec for any array type
type ArrayCodec struct {
    ElementType *Type
}

// RangeCodec — codec for any range type
type RangeCodec struct {
    ElementType *Type
}

// MultirangeCodec — codec for any multirange type
type MultirangeCodec struct {
    ElementType *Type
}

// CompositeCodec — codec for PostgreSQL composite types
type CompositeCodec struct {
    Fields []CompositeCodecField
}

// TimestampCodec — configurable scan location (affects the instant in time)
type TimestampCodec struct {
    ScanLocation *time.Location
}

// TimestamptzCodec — configurable scan location (does not change instant in time)
type TimestamptzCodec struct {
    ScanLocation *time.Location
}

// JSONCodec — customizable JSON marshaler/unmarshaler (uses encoding/json by default)
type JSONCodec struct {
    Marshal   func(v any) ([]byte, error)
    Unmarshal func(data []byte, v any) error
}

// JSONBCodec — customizable JSONB marshaler/unmarshaler (uses encoding/json by default)
type JSONBCodec struct {
    Marshal   func(v any) ([]byte, error)
    Unmarshal func(data []byte, v any) error
}

// XMLCodec — customizable XML marshaler/unmarshaler (uses encoding/xml by default)
type XMLCodec struct {
    Marshal   func(v any) ([]byte, error)
    Unmarshal func(data []byte, v any) error
}

// TextFormatOnlyCodec — wraps a Codec to only allow text format
type TextFormatOnlyCodec struct {
    Codec
}

// EnumCodec — caches decoded strings to reduce allocations (for types with small cardinality)
type EnumCodec struct{ /* unexported */ }

// RecordCodec — codec for generic PostgreSQL record type (binary decode only)
type RecordCodec struct{}

// LtreeCodec — codec for PostgreSQL ltree extension type (text/binary)
type LtreeCodec struct{}

// MacaddrCodec — codec for PostgreSQL macaddr and macaddr8 types
type MacaddrCodec struct{}

All codec types implement Codec interface (FormatSupported, PreferredFormat, PlanEncode, PlanScan, DecodeDatabaseSQLValue, DecodeValue).

Standard per-type codecs (no configurable fields):

type BoolCodec struct{}
type ByteaCodec struct{}
type QCharCodec struct{}
type Int2Codec struct{}
type Int4Codec struct{}
type Int8Codec struct{}
type Uint32Codec struct{}
type Uint64Codec struct{}
type Float4Codec struct{}
type Float8Codec struct{}
type TextCodec struct{}
type DateCodec struct{}
type TimeCodec struct{}
type IntervalCodec struct{}
type NumericCodec struct{}
type UUIDCodec struct{}
type TIDCodec struct{}
type BitsCodec struct{}
type HstoreCodec struct{}
type InetCodec struct{}
type PointCodec struct{}
type BoxCodec struct{}
type CircleCodec struct{}
type LineCodec struct{}
type LsegCodec struct{}
type PathCodec struct{}
type PolygonCodec struct{}

These are typically used only when registering custom types for specific OIDs. They all implement the Codec interface.

Standard per-type codecs (no configurable fields):

type BoolCodec struct{}
type ByteaCodec struct{}
type QCharCodec struct{}
type Int2Codec struct{}
type Int4Codec struct{}
type Int8Codec struct{}
type Uint32Codec struct{}
type Uint64Codec struct{}
type Float4Codec struct{}
type Float8Codec struct{}
type TextCodec struct{}
type DateCodec struct{}
type TimeCodec struct{}
type IntervalCodec struct{}
type NumericCodec struct{}
type UUIDCodec struct{}
type TIDCodec struct{}
type BitsCodec struct{}
type HstoreCodec struct{}
type InetCodec struct{}
type PointCodec struct{}
type BoxCodec struct{}
type CircleCodec struct{}
type LineCodec struct{}
type LsegCodec struct{}
type PathCodec struct{}
type PolygonCodec struct{}

These are typically used only when registering custom types for specific OIDs. They all implement the Codec interface.

Wrap Plan Functions

These can be prepended to Map.TryWrapEncodePlanFuncs / Map.TryWrapScanPlanFuncs to add custom wrapping behavior:

type TryWrapEncodePlanFunc func(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool)
type TryWrapScanPlanFunc   func(target any) (plan WrappedScanPlanNextSetter, nextTarget any, ok bool)

type WrappedEncodePlanNextSetter interface {
    SetNext(EncodePlan)
    Encode(value any, buf []byte) (newBuf []byte, err error)
}

type WrappedScanPlanNextSetter interface {
    SetNext(ScanPlan)
    Scan(src []byte, target any) error
}

Built-in encode wrappers:

func TryWrapArrayEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool)
func TryWrapSliceEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool)
func TryWrapMultiDimSliceEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool)
func TryWrapBuiltinTypeEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool)
func TryWrapDerefPointerEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool)
func TryWrapFindUnderlyingTypeEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool)
func TryWrapStructEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool)

Built-in scan wrappers:

func TryWrapPtrSliceScanPlan(target any) (plan WrappedScanPlanNextSetter, nextValue any, ok bool)
func TryWrapPtrArrayScanPlan(target any) (plan WrappedScanPlanNextSetter, nextValue any, ok bool)
func TryWrapPtrMultiDimSliceScanPlan(target any) (plan WrappedScanPlanNextSetter, nextValue any, ok bool)
func TryWrapBuiltinTypeScanPlan(target any) (plan WrappedScanPlanNextSetter, nextDst any, ok bool)
func TryFindUnderlyingTypeScanPlan(dst any) (plan WrappedScanPlanNextSetter, nextDst any, ok bool)
func TryPointerPointerScanPlan(target any) (plan WrappedScanPlanNextSetter, nextTarget any, ok bool)
func TryWrapStructScanPlan(target any) (plan WrappedScanPlanNextSetter, nextValue any, ok bool)

Utility Types

type DriverBytes []byte      // for scanning as []byte without copying
type PreallocBytes []byte    // pre-allocated buffer
type UndecodedBytes []byte   // raw encoded bytes, skipping codec

type CompositeFields []any   // for encoding composite values as slices

Advanced Usage

Custom Codec Implementation

To implement a custom codec:

type MyCodec struct{}

func (c *MyCodec) FormatSupported(format int16) bool {
    return format == pgtype.TextFormatCode || format == pgtype.BinaryFormatCode
}

func (c *MyCodec) PreferredFormat() int16 {
    return pgtype.BinaryFormatCode
}

func (c *MyCodec) PlanEncode(m *pgtype.Map, oid uint32, format int16, value any) pgtype.EncodePlan {
    // Return encode plan
    return nil
}

func (c *MyCodec) PlanScan(m *pgtype.Map, oid uint32, format int16, target any) pgtype.ScanPlan {
    // Return scan plan
    return nil
}

func (c *MyCodec) DecodeDatabaseSQLValue(m *pgtype.Map, oid uint32, format int16, src []byte) (driver.Value, error) {
    // Decode for database/sql
    return nil, nil
}

func (c *MyCodec) DecodeValue(m *pgtype.Map, oid uint32, format int16, src []byte) (any, error) {
    // Decode to any
    return nil, nil
}

Register Custom Codec

customType := &pgtype.Type{
    Name:  "my_custom_type",
    OID:   12345,
    Codec: &MyCodec{},
}
conn.TypeMap().RegisterType(customType)

Build Tag: nopgxregisterdefaulttypes

Add //go:build nopgxregisterdefaulttypes to omit default type registration and reduce binary size by ~2MB. You must then manually call RegisterDefaultPgType for each Go type used as a query parameter in Exec/SimpleProtocol modes.

Registering Custom Types

// Example: register a composite type
conn, _ := pgx.ConnectConfig(ctx, config)

// Load the type definition from the database
t, err := conn.LoadType(ctx, "my_composite_type")
conn.TypeMap().RegisterType(t)

// Example: register an array of a custom type
arr, err := conn.LoadType(ctx, "_my_composite_type")
conn.TypeMap().RegisterType(arr)

// Example: register a default PG type for a custom Go type
conn.TypeMap().RegisterDefaultPgType(MyCustomType{}, "my_pg_type")

Install with Tessl CLI

npx tessl i tessl/golang-github-com-jackc-pgx-v5@5.8.0

docs

batch.md

common-patterns.md

connection-pool.md

copy.md

database-sql.md

direct-connection.md

index.md

querying.md

testing.md

tracing.md

transactions.md

tile.json