Pablo
Pablo

Reputation: 8644

psycopg2 + stored procedure + compound type

I have a stored procedure in PostgreSQL that takes a t_document composite type defined as follows:

CREATE TYPE t_document AS (
    title    text,
    metadata text,
    data     text
);

The stored procedure takes other arguments as well, with a signature like:

CREATE or REPLACE  FUNCTION sp_insertItem
(
    name varchar(100) ,
    phone varchar(100) ,
    address varchar(150) ,
    document t_document 
) 

Calling this stored procedure from another stored procedure looks like this:

sp_insertItem('Name','Phone', 'Address', row('Title', 'Metadata', 'Data'));

I know I can call procedures using cursor.callproc and give the required arguments. However, I don't know how to pass compound arguments like t_document. So how do I call a stored procedure from psycopg2 that expects a compound type?

Upvotes: 1

Views: 2623

Answers (1)

piro
piro

Reputation: 13931

You can pass name, phone, and address in a tuple, eventually with an explicit cast to better disambiguate:

cur.execute("sp_insertItem(%s, %s, %s, %s::t_document)",
    ['Name', 'Phone', 'Address', ('Title', 'Metadata', 'Data')])

You could also use a namedtuple: it is adapted the same way.

Document = namedtuple('Document', 'title metadata data')

Upvotes: 3

Related Questions