how to use factory in psycopg3 register_composite?

184 Views Asked by At

In psycopg2, register_composite you can specify a factory parameter where:

factory – if specified it should be a CompositeCaster subclass: use it to customize how to cast composite types

found in https://www.psycopg.org/docs/extras.html#custom-composite

is there a psycopg 3.0.9 factory subclass that is the equivalent of a CompositeCaster subclass in psycopg2? The docs for psycopg3 are https://www.psycopg.org/psycopg3/docs/basic/pgtypes.html but they dont really say much about the factory parameter and if theres a subclass I can use to customize how to cast the composite types.

1

There are 1 best solutions below

0
On

register_composite can optionally take a factory parameter. factory should be a function that takes as many parameters as fields the custom type defined on your database has. The factory takes the fields as arguments and should return a Python object that will replace the psycopg.types.composite.XXXX instance that you would get otherwise.

For example in my database I have the following type:

CREATE TYPE quaternion AS (
  q0       double precision,
  q1       double precision,
  q2       double precision,
  q3       double precision
);

however when I read quaternions on my Python program I would like them to be the quaternions from the numpy-quaternion library. To achieve that I can do the following:

from quaternion import quaternion

with psycopg.connect(conn_str) as conn:
    quaternion_info = CompositeInfo.fetch(conn, "quaternion")
    register_composite(quaternion_info, conn, factory=lambda q0, q1, q2, q3: quaternion(q0, q1, q2, q3))
    with conn.cursor() as cur:
        rows = retrieve_rows(cur, ["row_id_0", "row_id_1",...])
        # ... do stuff ...