Skip to content

Types and adapters

Types and adapters explains when each representation applies.

Decoding and adapters

Decoding dataclass

Decoding(
    *,
    arrays: Literal['list', 'exact'] | None = None,
    geometry: Literal['exact', 'gometry'] | None = None,
    json: Literal['parsed', 'document'] | None = None,
    temporal: Literal['standard', 'exact'] | None = None,
    unknown: Literal['value', 'error'] | None = None,
)

Row decoding policy for a connection or individual call. Unspecified fields inherit the connection policy.

With no overrides, arrays become lists, PostGIS rows use gometry, JSON is parsed, temporal values use standard datetime types, and unknown types return qualified PgValue objects. Use geometry='exact' for EWKB without gometry. Arrow result fields have their own schema and do not use these row defaults.

arrays class-attribute instance-attribute

arrays: Literal['list', 'exact'] | None = None

geometry class-attribute instance-attribute

geometry: Literal['exact', 'gometry'] | None = None

json class-attribute instance-attribute

json: Literal['parsed', 'document'] | None = None

temporal class-attribute instance-attribute

temporal: Literal['standard', 'exact'] | None = None

unknown class-attribute instance-attribute

unknown: Literal['value', 'error'] | None = None

Codec dataclass

Codec(
    type: Identifier,
    python_type: type[_T],
    *,
    format: Literal['text', 'binary'],
    decode: Callable[[memoryview], _T] | None = None,
    encode: Callable[[_T], Buffer] | None = None,
)

Encode or decode raw field bytes in PostgreSQL 'text' or 'binary' format.

type must be a schema-qualified two-part Identifier. Provide decode, encode, or both; omitted directions use native conversion.

type instance-attribute

type: Identifier

python_type instance-attribute

python_type: type[_T]

format instance-attribute

format: Literal['text', 'binary']

decode class-attribute instance-attribute

decode: Callable[[memoryview], _T] | None = None

encode class-attribute instance-attribute

encode: Callable[[_T], Buffer] | None = None

Adapter dataclass

Adapter(
    type: Identifier,
    python_type: type[_T],
    *,
    decode: Callable[[_Native], _T] | None = None,
    encode: Callable[[_T], _Native] | None = None,
)

Map an application value to or from the native Python representation of a SQL type.

type must be a schema-qualified two-part Identifier. Provide decode, encode, or both; omitted directions use native conversion.

type instance-attribute

type: Identifier

python_type instance-attribute

python_type: type[_T]

decode class-attribute instance-attribute

decode: Callable[[_Native], _T] | None = None

encode class-attribute instance-attribute

encode: Callable[[_T], _Native] | None = None

EnumBinding dataclass

EnumBinding(
    type: Identifier,
    enum: type[_E],
    *,
    labels: Literal['name', 'value'] | Mapping[_E, str],
)

Bind a schema-qualified two-part Identifier for a PostgreSQL enum to a Python Enum.

Match members by 'name', by 'value', or via an explicit {member: label} mapping.

type instance-attribute

type: Identifier

enum instance-attribute

enum: type[_E]

CompositeBinding dataclass

CompositeBinding(
    type: Identifier,
    factory: Callable[..., _T],
    *,
    fields: Mapping[str, str] | None = None,
    encode: Callable[[_T], Mapping[str, object]] | None = None,
)

Bind a schema-qualified two-part Identifier for a PostgreSQL composite type to a Python factory.

Decoding passes SQL attributes to factory as keyword arguments. fields, when given, maps {sql_attr: python_kwarg}; encode, when given, returns {sql_attr: value}.

type instance-attribute

type: Identifier

factory instance-attribute

factory: Callable[..., _T]

fields class-attribute instance-attribute

fields: Mapping[str, str] | None = None

encode class-attribute instance-attribute

encode: Callable[[_T], Mapping[str, object]] | None = None

PgValue dataclass

PgValue(data: str | Buffer, /, *, type: Identifier)

Owning text or binary payload labelled with its PostgreSQL schema and type name.

A label identifies the intended type, not an equivalent definition in another database. Text uses the destination's input routine and session settings; binary data must already have the representation expected by that type's receive function.

data instance-attribute

data: str | bytes

type instance-attribute

type: Identifier

format property

format: Literal['text', 'binary']

PostgreSQL protocol format of the owned payload.

Temporal

PgDate

PgDate(year: int, month: int, day: int)

A finite PostgreSQL date, independent of Python's year limits.

year property

year: int

month property

month: int

day property

day: int

from_date staticmethod

from_date(value: date) -> PgDate

Construct from a datetime.date. Rejects datetime.datetime with TypeError to avoid silent truncation.

to_date

to_date() -> date

Convert to a datetime.date. Raises OverflowError outside years 1-9999.

PgTime

PgTime(
    hour: int = 0,
    minute: int = 0,
    second: int = 0,
    microsecond: int = 0,
    *,
    utc_offset: timedelta | None = None,
)

A PostgreSQL time or timetz: a clock reading, including 24:00:00, with an optional UTC offset.

hour property

hour: int

minute property

minute: int

second property

second: int

microsecond property

microsecond: int

utc_offset property

utc_offset: timedelta | None

from_time staticmethod

from_time(value: time) -> PgTime

Construct from a datetime.time. A fixed-offset tzinfo becomes utc_offset; a zone without a fixed offset raises ValueError.

to_time

to_time() -> time

Convert to a datetime.time. Raises OverflowError for 24:00:00.

PgTimestamp

PgTimestamp(date: PgDate, time: PgTime)

A finite PostgreSQL timestamp or timestamptz outside or inside Python's datetime range.

date property

date: PgDate

time property

time: PgTime

from_datetime staticmethod

from_datetime(value: datetime) -> PgTimestamp

Construct from a datetime.datetime. Aware values are normalized to UTC; naive values stay naive.

to_datetime

to_datetime() -> datetime

Convert to a datetime.datetime (UTC-aware when zoned, naive otherwise). Raises OverflowError outside years 1-9999.

Infinity

Use with a temporal SQL destination. Exact temporal decoding preserves both signs.

NEGATIVE class-attribute instance-attribute

NEGATIVE = -1

POSITIVE class-attribute instance-attribute

POSITIVE = 1

Interval

Interval(*, months: int = 0, days: int = 0, microseconds: int = 0)

A finite PostgreSQL interval of months, days, and microseconds, with no normalization between them.

months property

months: int

days property

days: int

microseconds property

microseconds: int

to_timedelta

to_timedelta() -> timedelta

Convert to an elapsed duration, counting each day as 24 hours.

Months have no fixed length, so an interval with months != 0 raises ValueError.

Containers, text, and binary

Range dataclass

Range(
    lower: _T_co | None = None,
    upper: _T_co | None = None,
    *,
    bounds: _Bounds = '[)',
)

A pair of optional endpoints. None means unbounded; only Range.empty() is empty.

lower instance-attribute

lower: _T_co | None

upper instance-attribute

upper: _T_co | None

bounds instance-attribute

bounds: _Bounds

is_empty instance-attribute

is_empty: bool

empty classmethod

empty() -> Self

Return the empty range, distinct from Range() and SQL NULL.

MultiRange dataclass

MultiRange(ranges: Iterable[Range[_T_co]] = ())

An immutable sequence of ranges; input order is preserved without merging or sorting.

Array dataclass

Array(
    values: Iterable[_T_co],
    *,
    dimensions: Sequence[int] | None = None,
    lower_bounds: Sequence[int] | None = None,
)

Shape-preserving PostgreSQL array owning flat elements, dimension lengths, and lower bounds. Empty arrays have no axes.

values instance-attribute

values: tuple[_T_co, ...]

dimensions instance-attribute

dimensions: tuple[int, ...]

lower_bounds instance-attribute

lower_bounds: tuple[int, ...]

to_list

to_list() -> list[_Nested[_T_co]]

Return nested lists in storage order, deliberately discarding lower bounds.

BitString

An immutable PostgreSQL bit or varbit value. Equality and hashing include the bit length.

data property

data: bytes

Packed bytes, most-significant bit first, with unused trailing bits zeroed.

bit_length property

bit_length: int

Number of bits in the string.

Json dataclass

Json(value: _T_co)

Bind a Python value as a JSON value, encoded when the statement is admitted.

Needed only where a bare parameter means something else: Json('text') is a JSON string, whereas a bare str is JSON source text, and Json(None) is JSON null, whereas a bare None is SQL NULL.

value instance-attribute

value: _T_co

JsonDocument dataclass

JsonDocument(text: str | Buffer)

Unparsed JSON source text. JSONB preserves only the server's rendered form.

text instance-attribute

text: str

decode

decode(*, numbers: Literal['python', 'decimal'] = 'python') -> object

Parse the document. Decimal mode retains exact non-integer numeric tokens.

Geometric

PgPoint

PgPoint(x: float, y: float)

A PostgreSQL point: two float8 ordinates, without an SRID or an implicit transformation.

x property

x: float

y property

y: float

PgLine

PgLine(a: float, b: float, c: float)

A PostgreSQL line: coefficients of Ax + By + C = 0, stored without rescaling.

a property

a: float

b property

b: float

c property

c: float

PgLineSegment

PgLineSegment(start: _PointLike, end: _PointLike)

A PostgreSQL lseg: ordered endpoints. Coincident points still represent a segment.

start property

start: PgPoint

end property

end: PgPoint

PgBox

PgBox(lower: _PointLike, upper: _PointLike)

A PostgreSQL box: opposite corners, ordered independently on each axis with NaN above finite ordinates.

lower property

lower: PgPoint

upper property

upper: PgPoint

PgPath

PgPath(points: Iterable[_PointLike], *, closed: bool = False)

A PostgreSQL path: an ordered point sequence. Closed does not imply a repeated endpoint.

points property

points: Sequence[PgPoint]

closed property

closed: bool

PgPolygon

PgPolygon(points: Iterable[_PointLike])

A PostgreSQL polygon's stored vertices, not an OGC topology or a normalized ring.

points property

points: Sequence[PgPoint]

PgCircle

PgCircle(center: _PointLike, radius: float)

A PostgreSQL circle: center and nonnegative radius in the native coordinate units.

center property

center: PgPoint

radius property

radius: float

pgvector

Vector

Vector(values: Iterable[float] | Buffer)

An immutable pgvector vector of finite float32 components.

Supports the sequence and buffer protocols. Rejects non-finite values (at float32 precision) and raw bytes/bytearray inputs.

HalfVector

HalfVector(values: Iterable[float] | Buffer)

An immutable pgvector halfvec of finite float16 components.

Supports the sequence and buffer protocols. Rejects non-finite values (at float16 precision) and raw bytes/bytearray inputs.

SparseVector

An immutable pgvector sparsevec: sorted zero-based indices, finite nonzero float32 components, and a positive dimension count.

dimensions property

dimensions: int

Total number of dimensions in the sparse vector.

indices property

indices: memoryview

Read-only memoryview of sorted zero-based int32 indices.

values property

values: memoryview

Read-only memoryview of finite nonzero float32 components.