Source: https://gres.monicz.dev/api/types/

# Types and adapters

[Types and adapters](https://gres.monicz.dev/guide/types/) explains when each representation applies.

## Decoding and adapters

### Decoding `dataclass`

```python
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`

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

#### geometry `class-attribute` `instance-attribute`

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

#### json `class-attribute` `instance-attribute`

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

#### temporal `class-attribute` `instance-attribute`

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

#### unknown `class-attribute` `instance-attribute`

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

### Codec `dataclass`

```python
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`

```python
type: Identifier
```

#### python\_type `instance-attribute`

```python
python_type: type[_T]
```

#### format `instance-attribute`

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

#### decode `class-attribute` `instance-attribute`

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

#### encode `class-attribute` `instance-attribute`

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

### Adapter `dataclass`

```python
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`

```python
type: Identifier
```

#### python\_type `instance-attribute`

```python
python_type: type[_T]
```

#### decode `class-attribute` `instance-attribute`

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

#### encode `class-attribute` `instance-attribute`

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

### EnumBinding `dataclass`

```python
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`

```python
type: Identifier
```

#### enum `instance-attribute`

```python
enum: type[_E]
```

### CompositeBinding `dataclass`

```python
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`

```python
type: Identifier
```

#### factory `instance-attribute`

```python
factory: Callable[..., _T]
```

#### fields `class-attribute` `instance-attribute`

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

#### encode `class-attribute` `instance-attribute`

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

### PgValue `dataclass`

```python
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`

```python
data: str | bytes
```

#### type `instance-attribute`

```python
type: Identifier
```

#### format `property`

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

PostgreSQL protocol format of the owned payload.

## Temporal

### PgDate

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

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

#### year `property`

```python
year: int
```

#### month `property`

```python
month: int
```

#### day `property`

```python
day: int
```

#### from\_date `staticmethod`

```python
from_date(value: date) -> PgDate
```

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

#### to\_date

```python
to_date() -> date
```

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

### PgTime

```python
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`

```python
hour: int
```

#### minute `property`

```python
minute: int
```

#### second `property`

```python
second: int
```

#### microsecond `property`

```python
microsecond: int
```

#### utc\_offset `property`

```python
utc_offset: timedelta | None
```

#### from\_time `staticmethod`

```python
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

```python
to_time() -> time
```

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

### PgTimestamp

```python
PgTimestamp(date: PgDate, time: PgTime)
```

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

#### date `property`

```python
date: PgDate
```

#### time `property`

```python
time: PgTime
```

#### from\_datetime `staticmethod`

```python
from_datetime(value: datetime) -> PgTimestamp
```

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

#### to\_datetime

```python
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`

```python
NEGATIVE = -1
```

#### POSITIVE `class-attribute` `instance-attribute`

```python
POSITIVE = 1
```

### Interval

```python
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`

```python
months: int
```

#### days `property`

```python
days: int
```

#### microseconds `property`

```python
microseconds: int
```

#### to\_timedelta

```python
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`

```python
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`

```python
lower: _T_co | None
```

#### upper `instance-attribute`

```python
upper: _T_co | None
```

#### bounds `instance-attribute`

```python
bounds: _Bounds
```

#### is\_empty `instance-attribute`

```python
is_empty: bool
```

#### empty `classmethod`

```python
empty() -> Self
```

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

### MultiRange `dataclass`

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

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

### Array `dataclass`

```python
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`

```python
values: tuple[_T_co, ...]
```

#### dimensions `instance-attribute`

```python
dimensions: tuple[int, ...]
```

#### lower\_bounds `instance-attribute`

```python
lower_bounds: tuple[int, ...]
```

#### to\_list

```python
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`

```python
data: bytes
```

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

#### bit\_length `property`

```python
bit_length: int
```

Number of bits in the string.

### Json `dataclass`

```python
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`

```python
value: _T_co
```

### JsonDocument `dataclass`

```python
JsonDocument(text: str | Buffer)
```

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

#### text `instance-attribute`

```python
text: str
```

#### decode

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

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

## Geometric

### PgPoint

```python
PgPoint(x: float, y: float)
```

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

#### x `property`

```python
x: float
```

#### y `property`

```python
y: float
```

### PgLine

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

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

#### a `property`

```python
a: float
```

#### b `property`

```python
b: float
```

#### c `property`

```python
c: float
```

### PgLineSegment

```python
PgLineSegment(start: _PointLike, end: _PointLike)
```

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

#### start `property`

```python
start: PgPoint
```

#### end `property`

```python
end: PgPoint
```

### PgBox

```python
PgBox(lower: _PointLike, upper: _PointLike)
```

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

#### lower `property`

```python
lower: PgPoint
```

#### upper `property`

```python
upper: PgPoint
```

### PgPath

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

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

#### points `property`

```python
points: Sequence[PgPoint]
```

#### closed `property`

```python
closed: bool
```

### PgPolygon

```python
PgPolygon(points: Iterable[_PointLike])
```

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

#### points `property`

```python
points: Sequence[PgPoint]
```

### PgCircle

```python
PgCircle(center: _PointLike, radius: float)
```

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

#### center `property`

```python
center: PgPoint
```

#### radius `property`

```python
radius: float
```

## pgvector

### Vector

```python
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

```python
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`

```python
dimensions: int
```

Total number of dimensions in the sparse vector.

#### indices `property`

```python
indices: memoryview
```

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

#### values `property`

```python
values: memoryview
```

Read-only `memoryview` of finite nonzero `float32` components.
