types – types mapping and adaptation

The psycopg3.types package exposes the concrete implementation of Loader and Dumper to manage builtin objects, together with objects to describe PostgreSQL types and wrappers to help or customise the types conversion.

Types information

The TypeInfo object describes simple information about a PostgreSQL data type, such as its name, oid and array oid. The class can be used to query a database for custom data types: this allows for instance to load automatically arrays of a custom type, once a loader for the base type has been registered.

The TypeInfo object doesn’t instruct psycopg3 to convert a PostgreSQL type into a Python type: this is the role of a Loader. However it can extend the behaviour of the adapters: if you create a loader for MyType, using TypeInfo you will be able to manage seamlessly arrays of MyType or ranges and composite types using it as a subtypes.

See also

Data adaptation configuration describes about how to convert from Python types to PostgreSQL types and back.

from psycopg3.adapt import Loader
from psycopg3.types import TypeInfo

t = TypeInfo.fetch(conn, "mytype")
t.register(conn)

for record in conn.execute("select mytypearray from mytable"):
    # records will return lists of "mytype" as string

class MyTypeLoader(Loader):
    def load(self, data):
        # parse the data and return a MyType instance

MyTypeLoader.register(conn)

for record in conn.execute("select mytypearray from mytable"):
    # records will return lists of MyType instances
class psycopg3.types.TypeInfo(name: str, oid: int, array_oid: int, alt_name: str = '', delimiter: str = ',')

Hold information about a PostgreSQL base type.

The class allows to:

classmethod fetch(conn: Connection, name: Union[str, Identifier]) → Optional[T]

Query a system catalog to read information about a type.

Parameters
  • conn – the connection to query

  • name – the name of the type to query. It can include a schema name.

Returns

a TypeInfo object populated with the type information, None if not found.

async classmethod fetch_async(conn: AsyncConnection, name: Union[str, Identifier]) → Optional[T]

Query a system catalog to read information about a type.

Similar to fetch() but can use an asynchronous connection.

register(context: Optional[AdaptContext] = None)

Register the type information, globally or in the specified context.

The context can be a Connection or Cursor. Specifying no context will register the TypeInfo globally.

Registering the TypeInfo in a context allows the adapters of that context to look up type information: for instance it allows to recognise automatically arrays of that type and load them from the database as a list of the base type (how the base type is converted to Python is demanded to a Loader.

The following TypeInfo subclasses allow to fetch more specialised information from certain class of PostgreSQL types and to create more specialised adapters configurations.

class psycopg3.types.CompositeInfo(name: str, oid: int, array_oid: int, field_names: Sequence[str], field_types: Sequence[int])

Manage information about a composite type.

register(context: Optional[psycopg3.proto.AdaptContext] = None, factory: Optional[Callable[[], Any]] = None)

Register the type information, globally or in the specified context.

Using CompositeInfo.register() will also register a specialised loader to fetch the composite type as a Python named tuple, or a custom object if factory is specified.

class psycopg3.types.RangeInfo(name: str, oid: int, array_oid: int, subtype_oid: int)

Manage information about a range type.

register(context: Optional[psycopg3.proto.AdaptContext] = None)

Register the type information, globally or in the specified context.

Using RangeInfo.register() will also register a specialised loaders and dumpers. For instance, if you create a PostgreSQL range on the type inet, loading these object with the database will use the loader for the inet type to parse the range bounds - either the builtin ones or any one you might have configured.

The type information will also be used by the Range dumper so that if you dump a Range(address1, address2) object it will use the correct oid for your inetrange type.

Objects wrappers

TODO

Document the various objects wrappers

  • Int2, Int4, Int8, …

  • Json, Jsonb

  • Range

JSON adapters

class psycopg3.types.Json(obj: Any)
class psycopg3.types.Jsonb(obj: Any)

Wrappers to signal to convert obj to a json or jsonb PostgreSQL value.

Any object supported by the underlying dumps() function can be wrapped.

psycopg3.types.set_json_dumps(dumps: Callable[[Any], str])

Set a global JSON serialisation function to use by default by JSON dumpers.

Defaults to the builtin json.dumps(). You can override it to use a different JSON library or to use customised arguments.

If you need a non-global customisation you can subclass the JsonDumper family of classes, overriding the get_loads() method, and register your class in the context required.

psycopg3.types.set_json_loads(loads: Callable[[Union[str, bytes, bytearray]], Any])

Set a global JSON parsing function to use by default by the JSON loaders.

Defaults to the builtin json.loads(). You can override it to use a different JSON library or to use customised arguments.

If you need a non-global customisation you can subclass the JsonLoader family of classes, overriding the get_loads() method, and register your class in the context required.

class psycopg3.types.JsonDumper(cls: type, context: Optional[psycopg3.proto.AdaptContext] = None)
get_dumps() → Callable[[Any], str]

Return a json.dumps()-compatible function to serialize the object.

Subclasses can override this function to specify custom JSON serialization per context.

class psycopg3.types.JsonBinaryDumper(cls: type, context: Optional[psycopg3.proto.AdaptContext] = None)
class psycopg3.types.JsonbDumper(cls: type, context: Optional[psycopg3.proto.AdaptContext] = None)
class psycopg3.types.JsonbBinaryDumper(cls: type, context: Optional[psycopg3.proto.AdaptContext] = None)

Dumper subclasses using the function provided by set_json_dumps() function to serialize the Python object wrapped by Json/Jsonb.

If you need to specify different dumps() functions in different contexts you can subclass one/some of these functions to override the get_dumps() method and register() them on the right connection or cursor.

class psycopg3.types.JsonLoader(oid: int, context: Optional[psycopg3.proto.AdaptContext] = None)
get_loads() → Callable[[Union[str, bytes, bytearray]], Any]

Return a json.loads()-compatible function to de-serialize the value.

Subclasses can override this function to specify custom JSON de-serialization per context.

class psycopg3.types.JsonBinaryLoader(oid: int, context: Optional[psycopg3.proto.AdaptContext] = None)
class psycopg3.types.JsonbLoader(oid: int, context: Optional[psycopg3.proto.AdaptContext] = None)
class psycopg3.types.JsonbBinaryLoader(oid: int, context: Optional[psycopg3.proto.AdaptContext] = None)

Loader subclasses using the function provided by set_json_loads() function to de-serialize json/jsonb PostgreSQL values to Python objects.

If you need to specify different loads() functions in different contexts you can subclass one/some of these functions to override the get_loads() method and register() them on the right connection or cursor.