8

I have the following postgresql Function:

CREATE OR REPLACE FUNCTION readMessage(messageFor INT, qid INT = NULL, ctxt INT = NULL, messageFrom INT = NULL, byTimeStamp BOOLEAN = FALSE)
RETURNS SETOF message
AS $$
DECLARE
    sql varchar;
BEGIN
    sql := 'SELECT * FROM message WHERE (receiver_id IS NULL OR receiver_id = $1)';
    IF qid IS NOT NULL THEN
        sql := sql || ' AND queue_id = $2';
    END IF;
    IF ctxt IS NOT NULL THEN
        sql := sql || ' AND context = $3';
    ELSE
        sql := sql || ' AND context IS NULL';
    END IF;

    IF $4 IS NOT NULL THEN
        sql := sql || ' AND sender_id = $4';
    END IF;

    sql := sql || ' ORDER BY';
    IF byTimeStamp THEN
        sql := sql || ' arrive_time ASC';
    ELSE
        sql := sql || ' priority DESC';
    END IF;

    sql := sql || ' LIMIT 1'; 
    RETURN QUERY EXECUTE sql
    USING messageFor, qid, ctxt, messageFrom;
END;
$$
LANGUAGE plpgsql;

Now, the above function works fine but the resultSet does not contain column names (for example: a simple SELECT statement returns results with column names). I need to be able to access the result of the above function in Java code as:

Connection con;
PreparedStatement ps = con.prepareStatement("select readMessage(1, 1, 1, 1, true))";
ResultSet rs = ps.executeQuery(); 
rs.getInt(<column-name>) 

instead of

rs.getInt(<column-index>)

for more readable code. How can I modify my postgresql FUNCTION to achieve this?

Evan Carroll
  • 65,432
  • 50
  • 254
  • 507
gjain
  • 183
  • 1
  • 4

1 Answers1

10

Consider the example below:

CREATE TABLE test.child (
    id    integer,
    p_id1 integer,
    p_id2 integer
);

CREATE OR REPLACE FUNCTION named_cols() 
RETURNS SETOF test.child 
AS $$
  SELECT 0, 12, 23;                                                                                                                                                                                                 
$$ LANGUAGE sql;

SELECT named_cols();
 named_cols 
────────────
 (0,12,23)


SELECT * FROM named_cols();
 id │ p_id1 │ p_id2 
────┼───────┼───────
  0 │    12 │    23

If you call the function the first way, you will get back a record, without the column names. It looks like you are after the second one - you would experience the same behaviour with any programming language, not only Java.

Evan Carroll
  • 65,432
  • 50
  • 254
  • 507
András Váczi
  • 31,778
  • 13
  • 102
  • 151