PostgreSQL PL/Python – How to Return Multiple Columns as Composite Types

plpythonpostgresql

I have created a plpythonu function that should return a table with multiple columns. At present, it returns a single column with multiple components.

I came across this answer which is A) a little old and B) requires me to separate the components into a table outside of the function.

Here's a simple function that illustrates the problem:

CREATE TYPE foo AS (a INT, b INT);
CREATE OR REPLACE FUNCTION bar () RETURNS SETOF foo AS $$
    return [(1,2),(3,4)]
$$ LANGUAGE plpythonu;

SELECT bar();

This returns two records but only a single column. I want it to return a table with two records and two columns. Is this not possible? That would seem odd but an hour's worth of Googling has gotten me nowhere.

Best Answer

The simple way to do that would be to call your bar() function like this:

postgres@[local]:5432:postgres:=# SELECT * FROM bar();
 a | b
---+---
 1 | 2
 3 | 4
(2 rows)

Time: 0.622 ms
postgres@[local]:5432:postgres:=#

Which returns as a record type in this context, with two rows and two columns.

Hope that helps. =)