Skip to content

Remove automatic dereferencing of cursors #438

Closed

Description

@roji

While working on the read_refactor branch I came across something strange. The current Npgsql code has a feature, where if one sends a StoredProcedure query which returns a single column, and that column is a cursor, then it is "dereferenced": the cursor is traversed as if it is the result set. You can see the consumer side of this in this test.

I was wondering if there was a special reason for this feature, and whether it makes sense. It's odd to have a special case for one column (i.e. what happens if the stored procedure returns two cursors?). Also, if a stored procedure is written to return a cursor rather than a direct resultset, there's probably a reason for that and there doesn't seem to be any reason to deny the user access to the cursor (they may use it later to read only part of the resultset). We may even develop this later and add programmatic mechanisms to allow the user to traverse the cursor.

Wanted to hear if anyone has any insight on this (I'm definitely inclined to removing this special case).

Activity

  1. self-assigned this
    on Dec 25, 2014
  2. added this to the milestone on Dec 25, 2014
  3. roji commented on Dec 25, 2014

    @roji
    MemberAuthor

    Note: test MultipleRefCursorSupport shows a possible motivation: a query of function that returns a resultset of cursors is treated as a query with multiple resultsets (as if the user sent "SELECT 1; SELECT 2").

    I can see the logic but it still doesn't seem right to me to map the idea of cursors to resultsets in this simple way, for the reasons detailed above.

  4. roji commented on Dec 27, 2014

    @roji
    MemberAuthor

    This functionality has been removed, along with its tests. If anyone thinks it should stay or whatever I can bring it back.

  5. Emill commented on Dec 27, 2014

    @Emill
    Contributor

    Can the same functionality be achieved by running FETCH ALL queries?

  6. franciscojunior commented on Dec 27, 2014

    @franciscojunior
    Member

    Hi all!
    Sorry for late reply.

    @roji , this functionality exists to mimic the sql server idea of using functions which return a resultset and are consumed directly from the client with a executereader.

    We used to receive a lot of requests for this feature because people was used to and had code which worked this way with sql server.

  7. roji commented on Jan 13, 2015

    @roji
    MemberAuthor

    Reopening, not sure this removal is a good idea

  8. reopened this on Jan 13, 2015
  9. Emill commented on Jan 13, 2015

    @Emill
    Contributor

    What do you think about a connection parameter to either enable (default) or disable this feature?
    Maybe it's a bit useless since the user can just write select * from func_returning_refcursor() and this refcursor-thing will not be triggered...

  10. roji commented on Jan 15, 2015

    @roji
    MemberAuthor

    I don't know... I'm not a big fan of connection parameters, especially when it's not very easy for the user to understand exactly what the parameter does...

    The example with the SELECT * FROM func_returning_refcursor() is exactly why I don't like this feature so much, it's very ad-hoc and makes Npgsql behave a little inconsistently.

    But if people are used to returning resultsets in a transparent way from functions and code already depends on this maybe we should keep it... If we do maybe a param isn't so bad (with default=true) as you suggest...

  11. Emill commented on Mar 22, 2015

    @Emill
    Contributor

    Any new opinions on this?
    I think we can keep it since it might be a nice feature...

  12. 46 remaining items

  13. mikebeaton commented on Feb 16, 2017

    @mikebeaton

    I think this code IS needed. Cursors exist, the Postgres docs say:

    PL/pgSQL functions can return cursors to the caller. This is useful to return multiple rows or columns, especially with very large result sets.

    Maybe that advice is wrong, in the case of Npgsql. Now the user is very likely to come across a clear warning to that effect, if they use the above code (see the detailed exception messages).

    But when a user DOES have to read back from the kind of function which Postgres recommends (and some users will!), then it's an [expletive deleted] to work out how to do it yourself, and then you're not really sure if you have done it right yourself.

    Which to me really is a sign that the layer below you, which knows (knew!) how to do it, really can and should offer nicely to do it. :)

  14. mikebeaton commented on Feb 16, 2017

    @mikebeaton

    Also, there are no corner cases in the above. It supports everything reasonable. When it's on, you just can't read back from mixed result sets: it stops with an exception (with a meaningful message). When it's off, you can (of course) do whatever you want.

  15. roji commented on Feb 16, 2017

    @roji
    MemberAuthor

    I think this code IS needed. Cursors exist, the Postgres docs say:

    PL/pgSQL functions can return cursors to the caller. This is useful to return multiple rows or columns, especially with very large result sets.
    Maybe that advice is wrong, in the case of Npgsql. Now the user is very likely to come across a clear warning to that effect, if they use the above code (see the detailed exception messages).

    As I explained above, that advice isn't wrong - it's just wrong with the context of this discussion. If there's no client-side resultset buffering going on, and you're traversing the resultset in simple forward-only fashion, I can't think of a single thing cursors bring to the table. But if you're convinced otherwise, please provide an actual scenario that shows this.

    But when a user DOES have to read back from the kind of function which Postgres recommends (and some users will!), then it's an [expletive deleted] to work out how to do it yourself, and then you're not really sure if you have done it right yourself.

    I don't see why using cursors is any harder than using any other SQL... If you expect your programmer to write SQL queries and JOINs, why on earth can't they do FETCH? Also, don't forget that when a user writes it, they don't do generic support like you're doing - it's just code for the specific function they're invoking.


    Regarding your updated code, it indeed looks better than before. About opt-in/opt-out. I don't much like the idea of having this feature on by default - I'd be more comfortable with this being opt-in. The main reason is that the user may want to actually deal with cursors their own way with FETCH (this may be why they're using cursors in the first place!), and I wouldn't want to force automatic dereferencing on them even with an opt-out. Another reason is that the mixed cursor/non-cursor scenario triggers an exception, which doesn't seem like good behavior in the default scenario

    Putting DereferenceCursors on NpgsqlCommand means you have to access an Npgsql-specific type just to access this functionality, which isn't amazing. So I'd see this more as a Dereference Cursors connection string parameter that's false by default.

    Some additional minor points to think about:

    • It may make sense to CLOSE the cursor after the FETCH ALL, to release the cursor's resources immediately after its resultset is sent. Some research on the exact behavior of PostgreSQL cursors is needed here.
    • Do you activate this logic in ExecuteScalar or only in ExecuteReader? It's probably mostly useless for ExecuteScalar but for coherency/correctness it may be good to apply it.
    • Similar to the above: what happens when I do ExecuteNonQuery on a cursor-returning function? If we don't dereference, the cursor stays open until the end of the transaction, which seems like a pretty bad idea. So it may be advisable to apply the dereferencing logic for all Execute* methods (i.e. in Npgsql's internal Execute() method which is called from them).

    Let me think about it some more, I'll write again soon.

  16. mikebeaton commented on Feb 17, 2017

    @mikebeaton
  17. roji commented on Feb 17, 2017

    @roji
    MemberAuthor

    @mikebeaton, I've commented a little on that issue, some people are saying some nonsense there unfortunately.

    But where I admit to learning something new, is about PostgreSQL's current limitation of buffering the resultset returned by a function... That's a pretty sad surprise - and it does indeed provide a good case for returning cursors from functions (even if there's only a single resultset). I do hope they fix this at some point and allow results to be streamed to the client as the function is running, much like a regular query.

    So... I guess I'll accept a PR that adds back dereferencing as you've described it above. Please cleanly separate all the logic into its own method, which would probably be invoked from NpgsqlCommand.Execute() (we'll work out the specifics a bit later), and also try thinking about the questions raised above (especially closing the cursor immediately after the FETCH ALL.

    Thanks for all the discussion and arguments.

  18. mikebeaton commented on Feb 17, 2017

    @mikebeaton

    Yes, I was feeling that both (I guess!) of our interpretations of the reason for using cursor return values given on the PostgreSQL cursor docs page was missing something - it slowly started to hit me as to what (after a bunch of reading around on the Postgres mail archives etc.). Okay - and thank you.

  19. jonwagner commented on May 17, 2017

    @jonwagner

    I ran across the same issue porting Insight.Database to npgsql 3.x.

    A common multi-recordset pattern with our micro-orm is:

    -- imagine this as two cursors...
    SELECT * from Beer where id = 1; SELECT * from Glass where beerid = 1
    -- receive two recordsets and the ORM creates the parent/child relationship automatically
    

    It would be very, very convenient to continue to support cursor dereferencing in the driver, but only if you can do it in a consistent way.

    There is a consistency argument for implementing the feature, as NextRecordset is the ADO.NET standard pattern for accessing multiple recordsets returned from a database.

    • SqlServer supports multiple recordsets, accessible with NextRecordset
    • Oracle chose to emulate multiple recordsets with refcursors, and their driver dereferences the cursors with NextRecordset

    That being said, I can understand the desire to allow cursors to be manipulated raw, and I can build a wrapper command around the NpgsqlCommand that uses Mike's ideas above.

  20. roji commented on May 17, 2017

    @roji
    MemberAuthor

    @jonwagner, there's nothing preventing you from fetching multiple resultsets (or recordsets) in a single query - simple put multiple SQL queries in your NpgsqlCommand's CommandText exactly as you proposed above (SELECT * from beer; SELECT * from glass). Resultsets are not the same as (server-side) cursors. You can then use NpgsqlDataReader.NextResult() to pass from one resultset to the next. Read the entire discussion to understand the distinction between resultsets and cursors.

    (Regardless, for your specific example a simple join seems much better than multiple queries)

  21. jonwagner commented on May 17, 2017

    @jonwagner

    Correct. I wasn't referring to the use cases of multiple results from commandtext, but the ability to return multiple results from a stored procedure / function. For that case, Postgres documentation recommends returning multiple cursors.

    I was pointing out the Npgsql v2.x took the opinion of both SqlServer and Oracle that the most common use case for cursors in a .NET application is to fetch the data from the cursors, and they all handled it automatically.

    It does seem that Postgres users are more likely to use CommandText than a function in this case, and having access to cursor manipulation could be useful in some scenarios. So it does make sense that Npgsql 3.x tries to stay more true to the protocol.

    In any case, it wasn't hard to write an automatic handler for this case. I just adapted Mike's code. :)

    (For the record, the example was abbreviated. Of course you could do a join in commandtext for that trivial case.)

  22. funny-falcon commented on Oct 18, 2017

    @funny-falcon
    Contributor

    We have a customer that in doubts to migrate from MSSQL to PostgreSQL, or not to migrate.
    Ease of .Net application porting is main decision factor.
    And this removed feature complicates migration a lot.
    So, by removing this feature you greatly reduce number of users who will decide to migrate to PostgreSQL.

  23. lqxchad commented on Jan 30, 2018

    @lqxchad

    What is the status of this? It looks like it was getting added back; but not sure. If so, what version? I just upgraded to 3.2.6 from 2.1.3 (to fix one bug) and then ran into this issue.

    I have functions that are returning a single refcursor. I read this entire thread, and understand why and how there are more ideal ways to return data from a function, but I have a function that uses dynamic sql to generate a series in a crosstab function. My table structure varies. The ways to avoid using cursors mentioned above seemed to mean you had to define your table structure. I don't have that luxury. Returning a refcursor seemed to be the only way around it. Please let me know if there is a way to do that in pg that I am missing.

    I wrote your typical generic report engine that holds sql statements, a child table defining the parameters, etc. The query table has a column with a commandtype. The code knows it's a stored procedure makes it's call as such:

    DataTable tbl = null;
    NpgsqlConnection connection = new NpgsqlConnection(Adapter.ConnectionString);
    NpgsqlCommand command = null;
    NpgsqlDataAdapter adapter = new NpgsqlDataAdapter();
    tbl = new DataTable(report.SubReportName);
    command = new NpgsqlCommand(report.QueryText, connection);
    command.CommandType = (CommandType)report.CommandType;
    command.CommandTimeout = report.CommandTimeout;
    adapter.SelectCommand = command;
    connection.Open();
    NpgsqlTransaction t = connection.BeginTransaction();
    adapter.Fill(tbl);
    t.Commit();
    connection.Close();
    ds.Tables.Add(tbl);
    

    It was pretty nice to be able to just let the adapter fill a datatable. This is killing me because I thought this driver upgrade was going to be simple.

    Here is a sample function (I made up the sql, might not be correct, but it emulates getting balances for a customer for a specified date range, by month):

    CREATE OR REPLACE FUNCTION ops.get_customer_balance_by_month(
    	currency character varying,
    	statementdatestart timestamp without time zone,
    	statementdateend timestamp without time zone)
    RETURNS refcursor 
    AS $BODY$
    DECLARE 
    	ref1 refcursor := 'seller_ad_balances';
    	columnList varchar;
    	mainQuery varchar;
    BEGIN
    EXECUTE
    	'SELECT string_agg(''"'' || to_char(date_trunc(''month'', dates), ''YYYY-MM'') || ''" numeric(19,2)'', '','')  monthof 
    	from generate_series(''' || to_char(StatementDateStart, 'YYYY-MM-DD') || '''::timestamp, ''' || to_char(StatementDateEnd, 'YYYY-MM-DD') || '''::timestamp, ''1 month''::interval) dates'
    INTO columnList;
    
    columnList = '"Name (' || Currency || ')" varchar,' || columnList; 
    
    mainQuery = 'SELECT * FROM crosstab(
    ''with dates as (SELECT date_trunc(''''month'''', dates) + INTERVAL ''''1 MONTH - 1 SECOND''''  monthof
    
    from generate_series(''''' || to_char(StatementDateStart, 'YYYY-MM-DD') || '''''::timestamp, ''''' || to_char(StatementDateEnd, 'YYYY-MM-DD') || '''''::timestamp, ''''1 month''''::interval) dates)
    
    	SELECT
        CustomerName,
    	monthof,
    	SUM(Amount) Balance
    	FROM 
    	dates
    	JOIN Ledger ON statementdate <= dates.monthof 
        WHERE CurrencyCode = ''''' || Currency || '''''
        GROUP BY CustomerName, monthof
        ORDER BY 1 -- ALWAYS ORDER BY 1 to make sure the crosstab works!
    ''
    ,
    ''
    SELECT date_trunc(''''month'''', dates)  monthof
    from generate_series(''''' || to_char(StatementDateStart, 'YYYY-MM-DD') || '''''::timestamp, ''''' || to_char(StatementDateEnd, 'YYYY-MM-DD') || '''''::timestamp, ''''1 month''''::interval) dates
    ''
    )
    AS 
    (' || columnList || ');';
    
    OPEN ref1 FOR EXECUTE mainQuery;
    RETURN ref1;
    END;
    $BODY$;
    

    So, you are looking at a result that can be any number of columns, with any column name, depending on the currency being reported, the months for each column.

    This is just one example; there are others where a customer name may be represented in a column.
    Because of the ever evolving report types that go through the system, I had this great solution that allowed me to do everything with postgres functions and not have to recompile/deploy .net code.

    So please, if you guys have written a nice wrapper for this, please share.
    If you know of a way to return a TABLE in postgres that you aren't required to define the columns, share that as well. I'd love to not have to use the refcursor.

  24. roji commented on Jan 30, 2018

    @roji
    MemberAuthor

    I've opened #1785 to consider bringing this feature back for the next version, in light of popular demand.

    In the meantime, wrapping this yourselves really isn't that hard.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions