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
byteaalso accepts astrin 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
NULLisNone. - 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
Decimalwith full precision) bind directly. - A
stror UTF-8bytesvalue is treated as JSON source text parsed by PostgreSQL (invalid JSON raisesDataError). - Wrap strings and
nullinJsonwhen the bare value would mean something else:Json('text')binds the JSON string"text", andJson(None)binds JSONnull(whereas bareNonesends SQLNULL). - With
Decoding(json='document'), JSON columns returnJsonDocumentwhile SQLNULLstaysNone.JsonDocument.textholds the server's text anddecode(numbers='decimal')parses non-integers asDecimal(notejsonbdiscards whitespace and duplicate keys on storage). jsonpathbinds and returns asstr.
Arrays¶
- Bind rectangular lists, tuples, sets, or NumPy arrays for 1-based arrays (
Noneinside is aNULLelement). - For custom lower bounds, pass flat values in element order to
Array:Array([11, None, 37, 42], dimensions=(2, 2), lower_bounds=(0, -3))places11at[0][-3]. - Rows return nested lists; non-1 lower bounds raise
DecodingErrorunlessDecoding(arrays='exact')is set (returningArray;Array.to_list()drops bounds explicitly). Literal(array, type='integer[]')formats SQL array constants using the element delimiter. Underarray_nulls=off, arrays containingNoneare 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 binaryPgValuein one format per array;copy_from_rowsrequires binary). geometry[]andgeography[]arrays can mix SRIDs; each element decodes in its own frame, or stays EWKB underDecoding(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.
EnumBindingbinds a schema-qualifiedIdentifierto a PythonEnumin scalar and array positions (labels='value','name', or an explicit{member: label}mapping). Unknown labels raiseDecodingError. - Unbound named composites return
dicts.CompositeBinding(constructsIdentifier( 'app', 'line_item'), Item, fields={'label': 'title'}) Itemby keyword argument (mapping SQL attributelabelto Python keywordtitle) and reads parameters/COPY fields by attribute name; passencode=returning{sql_attr: value}to customize encoding. - A
NULLcomposite returnsNone, distinct from a composite whose fields are allNULL. Domains over composites preserve the composite layout, including in arrays. - Pass bindings to
Connection(adapters=...)orPool(adapters=...). Per-calladapters=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)
PgDateuses astronomical year numbering (0is 1 BC).PgDate.from_date()rejectsdatetimewithTypeErrorrather than truncating.- Aware
datetimevalues bind using their date- andfold-specific UTC offset.PgTimestamp(date, time)normalizes offsets to UTC;to_datetime()raisesOverflowErroroutside years 1–9999. timetzrequires a fixed UTC offset (never stripped or inferred from the session time zone).PgTime(24)represents24:00:00and raisesOverflowErrorinto_time().PgTime.utc_offsetis whole seconds east of UTC (timedelta(0)differs fromNone).Intervalkeepsmonths,days, andmicrosecondsindependent (Interval(days=1)is a calendar day;timedelta(days=1)is 24 elapsed hours).to_timedelta()raisesValueErrorwhenmonths != 0;timedeltavalues outside signed 64-bit microseconds raiseOverflowError.
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)forint4range); Gres never reorders endpoints or mergesMultiRangeentries.Range.empty(),Range()(unbounded), andNone(SQLNULL) are distinct; inside aRange,Nonemarks an unbounded endpoint.MultiRangepreserves element order and distinguishes empty fromNULL.
Network addresses and bit strings¶
inetreturnsIPv4Interface/IPv6Interface(preserving host bits and prefix length);cidrreturnsIPv4Network/IPv6Network. Binding an interface with host bits (e.g.192.0.2.7/24) tocidrraisesEncodingError— pass.network. IPv6 scope IDs are rejected.macaddrandmacaddr8return 6 or 8bytes(fixed-size binary in Arrow). A 6-byte value bound tomacaddr8receives PostgreSQL's EUI-48 expansion.BitStringaccepts binary digit strings ('101') or packed buffers withbit_length=, most-significant bit first with unused trailing bits zeroed. Equality and hashing includebit_length; indexing yieldsbooland slicing yieldsBitString.
XML, text search, and catalog types¶
xml: binds and returns asstr(or Arrow string incopy_from_arrow), validated by PostgreSQL; store asbyteaif original file bytes/encoding declarations must be preserved.tsvector,tsquery: bind and return asstr(use SQL functions likeplainto_tsqueryfor raw user input). Not accepted as binary COPY fields without a binaryPgValueor binaryCodec.- Catalog types:
tid/ctidmaps to(block, offset). OIDs (regclass, etc.), XIDs, andpg_lsnmap to unsignedint.int2vector/oidvectormap totuple[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):). PgBoxorders each axis independently (withNaNabove finite ordinates).PgPathstays open unlessclosed=Trueeven when endpoints repeat; paths and polygons require at least one point.PgCirclerejects negative radii;PgLinerejectsabs(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 todict[str, str | None]. Absent keys,Nonevalues, and'NULL'strings remain distinct;{}and SQLNULLremain distinct.
pgvector¶
vector,halfvec, andsparsevecmap toVector,HalfVector, andSparseVector, discovered by catalog identity without NumPy or third-party packages.Vector(float32) andHalfVector(float16) implement sequence and read-only buffer protocols, reject non-finite values and rawbytes/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 fromNULL.Literal(Vector(...))resolves the installed extension type even outsidesearch_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
PgValueback to a parameter of the same qualified type (cast explicitly in standaloneSELECT). - Binary
PgValuebytes go directly to the type's binary receive function, notbytea.
Custom adapters and codecs¶
Adaptertransforms between Gres's native Python type for a SQL type and your application type, including inside arrays.Codecreads/writes raw PostgreSQL'text'or'binary'bytes (decoder receives a read-onlymemoryview; encoder returns a byte buffer). Binary row COPY requires a binary encoder; typedLiteralrequires 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
SETcommands, includingSET ROLE, and parameter changes PostgreSQL reports, such assearch_pathon PostgreSQL 18 and later. UseSET ROLEto switch roles, or callinvalidate_types()after switching roles withset_config(): Gres does not detect that role switch. On PostgreSQL 17, also invalidate after a function changessearch_path. - Invalidation does not alter an active transaction snapshot, explicit
PreparedStatementhandles, or already-returned values. If invalidation races with encoding a modified composite, Gres raisesQueryShapeError(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 and24:00(datecountsdaysfrom 2000-01-01 withinfinityin{-1, 0, 1}). - Decimal storage:
schema=can request large string,decimal128, ordecimal256fornumeric(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.(rejects infinity, 64-bit nanosecond overflow, and sub-microsecond inputs onmonth_day_nano_interval( )} copy_from_arrow). - Wider vectors: request
float32elements forhalfvecwhen downstream consumers lackfloat16. copy_from_arrowalso accepts string, large string, and string view fields forhstore.