types
– Types information and adapters¶
The psycopg.types
package exposes:
objects to describe PostgreSQL types, such as
TypeInfo
,TypesRegistry
, to help or customise the types conversion;concrete implementations of
Loader
andDumper
protocols to handle builtin data types;helper objects to represent PostgreSQL data types which don’t have a straightforward Python representation, such as
Range
.
Types information¶
The TypeInfo
object describes simple information about a PostgreSQL data
type, such as its name, oid and array oid. TypeInfo
subclasses may hold more
information, for instance the components of a composite type.
You can use TypeInfo.fetch()
to query information from a database catalog,
which is then used by helper functions, such as
register_hstore()
, to register adapters on types whose
OID is not known upfront or to create more specialised adapters.
The TypeInfo
object doesn’t instruct Psycopg to convert a PostgreSQL type
into a Python type: this is the role of a Loader
. However it
can extend the behaviour of other adapters: if you create a loader for
MyType
, using the TypeInfo
information, Psycopg will be able to manage
seamlessly arrays of MyType
or ranges and composite types using MyType
as a subtype.
See also
Data adaptation configuration describes how to convert from Python objects to PostgreSQL types and back.
from psycopg.adapt import Loader
from psycopg.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
conn.adapters.register_loader("mytype", MyTypeLoader)
for record in conn.execute("SELECT mytypearray FROM mytable"):
# records will return lists of MyType instances
- class psycopg.types.TypeInfo(name: str, oid: int, array_oid: int, *, regtype: str = '', delimiter: str = ', ', typemod: type[~psycopg._typemod.TypeModifier] = <class 'psycopg._typemod.TypeModifier'>)¶
Hold information about a PostgreSQL base type.
- classmethod fetch(conn, name)¶
- async classmethod fetch(aconn, name)
Query a system catalog to read information about a type.
- Parameters:
conn (Connection or AsyncConnection) – the connection to query
name (
str
orIdentifier
) – the name of the type to query. It can include a schema name.
- Returns:
a
TypeInfo
object (or subclass) populated with the type information,None
if not found.
If the connection is async,
fetch()
will behave as a coroutine and the caller will need toawait
on it to get the result:t = await TypeInfo.fetch(aconn, "mytype")
- register(context: AdaptContext | None = None) None ¶
Register the type information, globally or in the specified
context
.- Parameters:
context (Optional[AdaptContext]) – the context where the type is registered, for instance a
Connection
orCursor
.None
registers theTypeInfo
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.
In order to get information about dynamic PostgreSQL types, Psycopg offers a
few TypeInfo
subclasses, whose fetch()
method can extract more complete
information about the type, such as CompositeInfo
,
RangeInfo
, MultirangeInfo
,
EnumInfo
.
TypeInfo
objects are collected in TypesRegistry
instances, which help type
information lookup. Every AdaptersMap
exposes its type map on
its types
attribute.
- class psycopg.types.TypesRegistry(template: TypesRegistry | None = None)¶
Container for the information about types in a database.
TypeRegistry
instances are typically exposed byAdaptersMap
objects in adapt contexts such asConnection
orCursor
(e.g.conn.adapters.types
).The global registry, from which the others inherit from, is available as
psycopg.adapters
.types
.- __getitem__(key: str | int) TypeInfo ¶
- __getitem__(key: tuple[type[T], int]) T
Return info about a type, specified by name or oid
- Parameters:
key – the name or oid of the type to look for.
Raise KeyError if not found.
>>> import psycopg >>> psycopg.adapters.types["text"] <TypeInfo: text (oid: 25, array oid: 1009)> >>> psycopg.adapters.types[23] <TypeInfo: int4 (oid: 23, array oid: 1007)>
- get(key: str | int) TypeInfo | None ¶
- get(key: tuple[type[T], int]) T | None
Return info about a type, specified by name or oid
- Parameters:
key – the name or oid of the type to look for.
Unlike
__getitem__
, return None if not found.
- get_oid(name: str) int ¶
Return the oid of a PostgreSQL type by name.
- Parameters:
key – the name of the type to look for.
Return the array oid if the type ends with “
[]
”Raise KeyError if the name is unknown.
>>> psycopg.adapters.types.get_oid("text[]") 1009
- get_by_subtype(cls: type[T], subtype: int | str) T | None ¶
Return info about a
TypeInfo
subclass by its element name or oid.- Parameters:
cls – the subtype of
TypeInfo
to look for. Currently supported areRangeInfo
andMultirangeInfo
.subtype – The name or OID of the subtype of the element to look for.
- Returns:
The
TypeInfo
object of classcls
whose subtype issubtype
.None
if the element or its range are not found.
JSON adapters¶
See JSON adaptation for details.
Wrappers to signal to convert obj
to a json or jsonb PostgreSQL value.
Any object supported by the underlying dumps()
function can be wrapped.
If a dumps
function is passed to the wrapper, use it to dump the wrapped
object. Otherwise use the function specified by set_json_dumps()
.
- psycopg.types.json.set_json_dumps(dumps: Callable[[Any], str | bytes], context: AdaptContext | None = None) None ¶
Set the JSON serialisation function to store JSON objects in the database.
- Parameters:
dumps (
Callable[[Any], str]
) – The dump function to use.context (
Connection
orCursor
) – Where to use thedumps
function. If not specified, use it globally.
By default dumping JSON uses the builtin
json.dumps
. You can override it to use a different JSON library or to use customised arguments.If the
Json
wrapper specified adumps
function, use it in precedence of the one set by this function.
- psycopg.types.json.set_json_loads(loads: Callable[[str | bytes], Any], context: AdaptContext | None = None) None ¶
Set the JSON parsing function to fetch JSON objects from the database.
- Parameters:
loads (
Callable[[bytes], Any]
) – The load function to use.context (
Connection
orCursor
) – Where to use theloads
function. If not specified, use it globally.
By default loading JSON uses the builtin
json.loads
. You can override it to use a different JSON library or to use customised arguments.