Skip to content

Types and adapters

Gres converts PostgreSQL values with native binary codecs. PostgreSQL selects each parameter's type from SQL context and Gres encodes the Python value for that type, including inside arrays, composites, and Arrow batches.

Everyday types

PostgreSQL Python result Also accepted as a parameter
boolean bool
smallint, integer, bigint int whole float such as 3.0 (fractions are rejected)
real, double precision float int
numeric decimal.Decimal (exact digits, never rounded to the active decimal context) int; float as its shortest decimal form, matching PostgreSQL's cast
text, varchar, char str
bytea bytes any byte buffer
uuid uuid.UUID 16 bytes (UUID.bytes)
json, jsonb decoded dict, list, str, number, bool, or None JSON text as str or UTF-8 bytes; Json(value) for a JSON string or null
arrays nested list tuple, set, or NumPy array; Array for non-default bounds
enums label str Python Enum with EnumBinding
date datetime.date PgDate
timestamp naive datetime.datetime PgTimestamp
timestamptz UTC datetime.datetime any aware datetime, PgTimestamp
time, timetz datetime.time PgTime
interval gres.Interval datetime.timedelta
inet, cidr ipaddress interface or network ipaddress addresses
ranges, multiranges Range, MultiRange
  • Every parameter except bytea also accepts a str in PostgreSQL's text input form (e.g. '7 days', '192.0.2.0/24', '2026-01-31T12:00:00Z', UUID strings).
  • NumPy scalars bind as their Python equivalents. SQL NULL is None.
  • Keep mutable parameter values (including writable buffers and aliases) unchanged while an operation runs. Immutable values can be shared across event loops.

Exact representations

When a PostgreSQL value cannot fit in the default Python type, Gres raises DecodingError rather than clipping or rounding. Pass Decoding to Connection, Pool, or an individual call to opt into lossless representations; unset fields inherit the connection policy.

Decoding field Default Exact alternative Use for
temporal 'standard' (datetime types) 'exact' (PgDate, PgTimestamp, PgTime, Infinity) BC dates, years > 9999, infinity, 24:00
arrays 'list' (nested lists) 'exact' (Array with dimensions and lower bounds) lower bounds other than 1
json 'parsed' (Python values) 'document' (JsonDocument) JSON null vs. SQL NULL, exact decimals
geometry 'gometry' (gometry objects) 'exact' (EwkbGeometry, EwkbGeography) raw EWKB, or no gometry installed
unknown 'value' (PgValue) 'error' (reject before running) disallowing unmapped types

stream_arrow takes temporal= and geometry= directly; see Arrow column types.

JSON and JSONB

Gres binds and decodes json and jsonb identically:

  • Dictionaries, lists, booleans, and finite numbers (including Decimal with full precision) bind directly.
  • A str or UTF-8 bytes value is treated as JSON source text parsed by PostgreSQL (invalid JSON raises DataError).
  • Wrap strings and null in Json when the bare value would mean something else: Json('text') binds the JSON string "text", and Json(None) binds JSON null (whereas bare None sends SQL NULL).
  • With Decoding(json='document'), JSON columns return JsonDocument while SQL NULL stays None. JsonDocument.text holds the server's text and decode(numbers='decimal') parses non-integers as Decimal (note jsonb discards whitespace and duplicate keys on storage).
  • jsonpath binds and returns as str.

Arrays

  • Bind rectangular lists, tuples, sets, or NumPy arrays for 1-based arrays (None inside is a NULL element).
  • For custom lower bounds, pass flat values in element order to Array: Array([11, None, 37, 42], dimensions=(2, 2), lower_bounds=(0, -3)) places 11 at [0][-3].
  • Rows return nested lists; non-1 lower bounds raise DecodingError unless Decoding(arrays='exact') is set (returning Array; Array.to_list() drops bounds explicitly).
  • Literal(array, type='integer[]') formats SQL array constants using the element delimiter. Under array_nulls=off, arrays containing None are rejected before dispatch (bind as a parameter instead).
  • Enum elements use labels; domain elements use their base type while enforcing domain constraints. Elements without a native codec return PgValue (and bind back as text or binary PgValue in one format per array; copy_from_rows requires binary).
  • geometry[] and geography[] arrays can mix SRIDs; each element decodes in its own frame, or stays EWKB under Decoding(geometry='exact').

Enums and composite types

import asyncio
import enum
from gres import Connection, EnumBinding, Identifier, scalar


class Phase(enum.Enum):
    NEW = 'new'
    DONE = 'done'


async def main() -> None:
    phase = EnumBinding(Identifier('pg_temp', 'phase'), Phase, labels='value')
    async with Connection() as db:
        await db.execute("CREATE TYPE pg_temp.phase AS ENUM ('new', 'done')")
        label = await db.fetch_one(
            "SELECT 'done'::pg_temp.phase", row=scalar()
        )
        print(label)  # done
        value = await db.fetch_one(
            "SELECT 'done'::pg_temp.phase",
            row=scalar(Phase),
            adapters=(phase,),
        )
        print(value)  # Phase.DONE


asyncio.run(main())
  • Unbound enums read and bind as label strings. EnumBinding binds a schema-qualified Identifier to a Python Enum in scalar and array positions (labels='value', 'name', or an explicit {member: label} mapping). Unknown labels raise DecodingError.
  • Unbound named composites return dicts. CompositeBinding(Identifier('app', 'line_item'), Item, fields={'label': 'title'}) constructs Item by keyword argument (mapping SQL attribute label to Python keyword title) and reads parameters/COPY fields by attribute name; pass encode= returning {sql_attr: value} to customize encoding.
  • A NULL composite returns None, distinct from a composite whose fields are all NULL. Domains over composites preserve the composite layout, including in arrays.
  • Pass bindings to Connection(adapters=...) or Pool(adapters=...). Per-call adapters= replaces that set (adapters=() disables bindings for one call).
  • Composite SQL constants work via Literal(value, type=Identifier('app', 'line_item')) when all fields have text encoders.

Dates, times, and intervals

PostgreSQL Bind temporal='standard' temporal='exact'
date date or PgDate date PgDate or Infinity
timestamp naive datetime or PgTimestamp naive datetime PgTimestamp or Infinity
timestamptz aware datetime or PgTimestamp UTC datetime PgTimestamp or Infinity
time naive time or PgTime time PgTime (including PgTime(24))
timetz fixed-offset time or PgTime time with offset PgTime with utc_offset
interval Interval or timedelta Interval Interval or Infinity
# Partial: db is an open connection.
from gres import Decoding, Infinity

row = await db.fetch_one(
    "SELECT 'infinity'::timestamptz AS until, '4713-01-01 BC'::date AS origin",
    decoding=Decoding(temporal='exact'),
)
assert row['until'] is Infinity.POSITIVE
print(row['origin'])  # PgDate(-4712, 1, 1)
  • PgDate uses astronomical year numbering (0 is 1 BC). PgDate.from_date() rejects datetime with TypeError rather than truncating.
  • Aware datetime values bind using their date- and fold-specific UTC offset. PgTimestamp(date, time) normalizes offsets to UTC; to_datetime() raises OverflowError outside years 1–9999.
  • timetz requires a fixed UTC offset (never stripped or inferred from the session time zone). PgTime(24) represents 24:00:00 and raises OverflowError in to_time(). PgTime.utc_offset is whole seconds east of UTC (timedelta(0) differs from None).
  • Interval keeps months, days, and microseconds independent (Interval(days=1) is a calendar day; timedelta(days=1) is 24 elapsed hours). to_timedelta() raises ValueError when months != 0; timedelta values outside signed 64-bit microseconds raise OverflowError.

Ranges and multiranges

  • Range(lower, upper, bounds='[)') binds to range columns or explicitly cast parameters. PostgreSQL canonicalizes discrete subtypes (Range(1, 3, bounds='[]') -> Range(1, 4) for int4range); Gres never reorders endpoints or merges MultiRange entries.
  • Range.empty(), Range() (unbounded), and None (SQL NULL) are distinct; inside a Range, None marks an unbounded endpoint. MultiRange preserves element order and distinguishes empty from NULL.

Network addresses and bit strings

  • inet returns IPv4Interface/IPv6Interface (preserving host bits and prefix length); cidr returns IPv4Network/IPv6Network. Binding an interface with host bits (e.g. 192.0.2.7/24) to cidr raises EncodingError — pass .network. IPv6 scope IDs are rejected.
  • macaddr and macaddr8 return 6 or 8 bytes (fixed-size binary in Arrow). A 6-byte value bound to macaddr8 receives PostgreSQL's EUI-48 expansion.
  • BitString accepts binary digit strings ('101') or packed buffers with bit_length=, most-significant bit first with unused trailing bits zeroed. Equality and hashing include bit_length; indexing yields bool and slicing yields BitString.

XML, text search, and catalog types

  • xml: binds and returns as str (or Arrow string in copy_from_arrow), validated by PostgreSQL; store as bytea if original file bytes/encoding declarations must be preserved.
  • tsvector, tsquery: bind and return as str (use SQL functions like plainto_tsquery for raw user input). Not accepted as binary COPY fields without a binary PgValue or binary Codec.
  • Catalog types: tid/ctid maps to (block, offset). OIDs (regclass, etc.), XIDs, and pg_lsn map to unsigned int. int2vector/oidvector map to tuple[int, ...] (note: PostgreSQL 18.6 rejects empty binary catalog vectors on input; use bound parameters or text COPY there).

Geometric types

PostgreSQL's built-in 2D types (point, line, lseg, box, path, polygon, circle) map to PgPoint, PgLine, PgLineSegment, PgBox, PgPath, PgPolygon, and PgCircle with float64 coordinates, no SRID, and no PostGIS/gometry dependency. For PostGIS types and box2d/box3d, see PostGIS.

  • Fixed-size types support positional pattern matching (case PgCircle(PgPoint(x, y), radius):); variable-length types match attributes (case PgPath(closed=True):).
  • PgBox orders each axis independently (with NaN above finite ordinates). PgPath stays open unless closed=True even when endpoints repeat; paths and polygons require at least one point. PgCircle rejects negative radii; PgLine rejects abs(a) <= 1e-6 and abs(b) <= 1e-6.

Extension types

hstore

  • Recognized by catalog identity in any schema. Binds Mapping[str, str | None] and decodes to dict[str, str | None]. Absent keys, None values, and 'NULL' strings remain distinct; {} and SQL NULL remain distinct.

pgvector

  • vector, halfvec, and sparsevec map to Vector, HalfVector, and SparseVector, discovered by catalog identity without NumPy or third-party packages.
  • Vector (float32) and HalfVector (float16) implement sequence and read-only buffer protocols, reject non-finite values and raw bytes/bytearray, and own their storage after connection close.
  • SparseVector({0: 1.5, 999999: -2.0}, dimensions=1000000) uses 0-based indices in Python and Arrow (PostgreSQL's text syntax is 1-based), sorts indices, drops zeros, rejects duplicates, and keeps empty vectors distinct from NULL.
  • Literal(Vector(...)) resolves the installed extension type even outside search_path.

Qualified PostgreSQL values

Columns without a native codec return PgValue(data, type=Identifier(schema, name)) holding server text (SQL NULL stays None). Set Decoding(unknown='error') to reject them before execution.

  • Bind a PgValue back to a parameter of the same qualified type (cast explicitly in standalone SELECT).
  • Binary PgValue bytes go directly to the type's binary receive function, not bytea.

Custom adapters and codecs

  • Adapter transforms between Gres's native Python type for a SQL type and your application type, including inside arrays.
  • Codec reads/writes raw PostgreSQL 'text' or 'binary' bytes (decoder receives a read-only memoryview; encoder returns a byte buffer). Binary row COPY requires a binary encoder; typed Literal requires a text encoder.
  • column_adapters= overrides decoding for one query's result column by unique name or 0-based index (domains can decode their base type without changing SQL semantics).
# Partial: custom Adapter, Codec, and CompositeBinding registered on a Pool.
from dataclasses import dataclass
from gres import Adapter, Codec, CompositeBinding, Identifier, Pool


@dataclass(frozen=True)
class Money:
    cents: int


@dataclass(frozen=True)
class LineItem:
    title: str
    qty: int


money_codec = Codec(
    Identifier('app', 'cents'),
    Money,
    format='text',
    decode=lambda raw: Money(int(raw.tobytes())),
    encode=lambda m: str(m.cents).encode(),
)
item_binding = CompositeBinding(
    Identifier('app', 'line_item'), LineItem, fields={'label': 'title'}
)
tag_adapter = Adapter(
    Identifier('pg_catalog', 'jsonb'),
    frozenset,
    decode=frozenset,
    encode=list,
)
pool = Pool(adapters=(money_codec, item_binding, tag_adapter))

SQL NULL bypasses all adapter/codec callbacks. Arrow output uses its schema, not Python callbacks.

Refresh type metadata after a migration

Gres caches custom type catalog metadata per session and refreshes automatically after DDL executed on that same session.

After an external migration commits (or after DDL hidden inside a function like SELECT migrate()), call pool.invalidate_types() on each worker's event loop (or db.invalidate_types() on a Connection). The call is synchronous, sends no SQL, does not interrupt active queries, and marks idle and checked-out connections in that pool to refresh on their next dependent operation (also dropping stale automatic statement signatures on session-affine connections; see PgBouncer transaction pooling for tracked proxies).

  • Gres detects SET commands, including SET ROLE, and parameter changes PostgreSQL reports, such as search_path on PostgreSQL 18 and later. Use SET ROLE to switch roles, or call invalidate_types() after switching roles with set_config(): Gres does not detect that role switch. On PostgreSQL 17, also invalidate after a function changes search_path.
  • Invalidation does not alter an active transaction snapshot, explicit PreparedStatement handles, or already-returned values. If invalidation races with encoding a modified composite, Gres raises QueryShapeError (dispatch_state == 'not_sent').

Arrow column types

stream_arrow emits these Arrow types, and copy_from_arrow accepts them back unless noted. Keep field metadata when round-tripping batches. SQL NULL is always an Arrow null.

PostgreSQL Default Arrow type Notes
numeric(p,s) decimal128 when finite values fit; exact decimal text otherwise numeric(2,-2) -> decimal128(4,0); numeric(2,4) -> decimal128(4,4)
json, jsonb UTF-8 with arrow.json extension metadata no Python object per row
jsonpath, xml UTF-8 no arrow.json metadata
tsvector, tsquery UTF-8 with PostgreSQL type metadata load with text COPY or execute_many, not copy_from_arrow
uuid arrow.uuid on 16-byte fixed-size binary
composites struct with SQL field names NULL record is a null struct; copy_from_arrow matches by name
arrays struct of values, dimensions, lower_bounds unmapped element types cannot round-trip via copy_from_arrow
date date32
timestamp, timestamptz timestamp[us] (UTC for timestamptz) overflow/infinity raises DecodingError
time time64[us]
timetz struct of local microseconds and offset seconds
interval struct of months, days, microseconds
ranges struct of empty, lower, upper, lower_inclusive, upper_inclusive multirange is a large list of these
inet, cidr struct of packed address bytes and uint8 prefix length metadata distinguishes inet vs. cidr
bit, varbit struct of packed data and bit_length
geometric types struct with named fields (x/y, center/radius, points/closed, etc.)
tid struct of unsigned block and offset
int2vector, oidvector large list of int16 or uint32
hstore map of string to nullable string duplicate keys rejected on import
vector, halfvec fixed-size list when dimension is declared; large list otherwise halfvec uses float16
sparsevec struct of dimensions, indices, values
geometry, geography GeoArrow see Read PostGIS columns as GeoArrow
box2d, box3d GeoArrow geoarrow.box PostGIS lacks binary box input; cannot load with copy_from_arrow
other types large_utf8 with gres.postgres.schema, .type, .format metadata not accepted by binary COPY

Layout overrides (using arro3.core.DataType or any Arrow PyCapsule schema):

  • Exact temporal: stream_arrow(..., temporal='exact') preserves infinities and 24:00 (date counts days from 2000-01-01 with infinity in {-1, 0, 1}).
  • Decimal storage: schema= can request large string, decimal128, or decimal256 for numeric (decimal types reject NaN/infinity/rounding; string keeps all values).
  • Nested lists for arrays: request a list type of fixed rank (e.g. DataType.large_list(DataType.list(DataType.int32()))) when every value has that rank and 1-based bounds.
  • Native intervals: schema={'v': DataType.month_day_nano_interval()} (rejects infinity, 64-bit nanosecond overflow, and sub-microsecond inputs on copy_from_arrow).
  • Wider vectors: request float32 elements for halfvec when downstream consumers lack float16.
  • copy_from_arrow also accepts string, large string, and string view fields for hstore.