0

I have a Postgres database with a stored procedure that returns JSON documents, based on the article here: http://www.sqlines.com/postgresql/npgsql_cs_result_sets

The procedure is represented like this:

-- Procedure that returns a single result set (cursor)
CREATE OR REPLACE FUNCTION get_data_test() RETURNS refcursor AS $$
DECLARE
ref refcursor;              -- Declare a cursor variable
BEGIN
    OPEN ref FOR            -- Open a cursor
        SELECT row_to_json(r) AS data
        FROM 
        (
            SELECT *
            FROM data AS d
        ) r;
    RETURN ref;             -- Return the cursor to the caller
END;
$$ LANGUAGE plpgsql;

I am then running the following code from a .net console app:

// Making connection with Npgsql provider
using (NpgsqlConnection conn = new NpgsqlConnection(connstring))
{
    conn.Open();

    var trans = conn.BeginTransaction();
    var cmd = new NpgsqlCommand("get_data_test", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Transaction = trans;

    using (var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
            Trace.WriteLine(reader[0]);
    }
}

The output is a single instance wit the name of the refcursor, rather than the actual data: < unnamed portal 1 >

If I run the select query directly in the command text, the result set is returned as expected. I've also tried explicitly calling the proc via text using "SELECT get_data_test()" but this also fails with just the cursor name.

I don't believe I am missing a step and this refcursor should be returned unbundled. What am I doing wrong?

1

1 Answer 1

2

As it happens, the tutorial was wrong:

Nice GitHub bug report: https://github.com/npgsql/npgsql/issues/1777

Correct answer:

-- Procedure that returns a single result set (cursor)
CREATE OR REPLACE FUNCTION get_data_test() RETURNS TABLE (data JSON) AS $$
BEGIN
    RETURN query
        SELECT row_to_json(r) AS data
        FROM 
        (
            SELECT *
            FROM data AS d
        ) r;
END;
$$ LANGUAGE plpgsql;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.