Skip to content

ExecuteReader.Dispose should not swallow exceptions #4377

Description

@thothothotho

Steps to reproduce

Create two tables like this:

create table pouet (
 id integer PRIMARY key,
 t varchar(40)                                       
);

create table test2 (
  id SERIAL primary key,
  pouet_id integer references pouet(id) INITIALLY DEFERRED
);

Then if you try to do that from the command line psql:

insert into test2 (pouet_id) values (1) returning id;

It fails immediately because the foreign key is not satisfied.

Suppose you have an NpgsqlConnection c correctly setup to that database.

build a command with the same query

 var command = new NpgsqlCommand("insert into test2 (pouet_id) values (1) returning id;");
 command.Connection = c;

Then if you do

await command.ExecuteNonQueryAsync();

then you get the expected exception Npgsql.PostgresException talking about the constraint violation.

However, if instead, you do:

using var reader = await command.ExecuteReaderAsync();
await reader.Read();
int id = (int)(reader.GetValue(0))

Then, no exception is generated at all. We even retrieve the id coming from postgres (from the RETURNING id statement)

The issue

There should be an exception in this case. That would be the expected behavior if we were in a transaction, but we are not.

If we remove the returning id from the end of the query, then an exception is correctly raised. And, as said earlier, there is a correct exception raised when we do ExecuteNonQueryAsync (but this is silly to do that, since we want to read the id in response.)

And of course, this is the INITIALLY DEFERRED on the foreign key that triggers the problem.

It's not totally clear to me whose is at fault. The server is returning an Id, but we are not in a transaction, so that should fail quick and
the server should just return an error.

However the client psql is behaving normally (it reports the error immediately)

Further technical details

Npgsql version: 6.0.3
PostgreSQL version: PostgreSQL 10.14 (Ubuntu 10.14-0ubuntu0.18.04.1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0, 64-bit
Operating system: Ubuntu 20

Activity

  1. vonzshik commented on Mar 11, 2022

    @vonzshik
    Contributor

    psql reports an error immediately because it does read everything PG sends before returning a result set, unlike ExecuteReader, which reads row by row. On the contrary, ExecuteNonQuery and ExecuteScalar both read the whole response before returning result. You should be able to emulate the same behavior (getting an exception) by calling NpgsqlReader.Read after you get an id.

    I'm not sure what exactly we can do on our side here since PG does send us a data row (id in your case) and only after that an error. At some point (#2372) Npgsql did throw in this case while disposing the reader, but since it's considered a bad practice and in case of SqlClient it also swallows any exceptions...

  2. vonzshik commented on Mar 11, 2022

    @vonzshik
    Contributor

    Okay, I was wrong: even calling Read you wouldn't get an exception - you can only get it by calling NextResult. I would have advised to use ExecuteScalar, but it seems it also doesn't call NextResult, unlike ExecuteNonQuery: I've opened #4378 to track this.

  3. thothothotho commented on Mar 11, 2022

    @thothothotho
    Author

    That makes the basic API very unfriendly and dangerous. And your patch against ExecuteScalar does not help if the request ends with

    …
    RETURNING (id, created_at)

    In which case we will have to rely on ExecuteReader (and do a non obvious NextResult to get the exception).

    Even doing a second Read is barely intuitive when you expect just one row. But having to do another NextResult when you issue just one select is just non sense, from a user point of view.

    Ideally, the best semantic is just to throw on the first Read. That way, the caller just can't miss the error situation.

  4. vonzshik commented on Mar 11, 2022

    @vonzshik
    Contributor

    I do agree it's dangerous, but I don't see any way to implement throwing that error on the first Read. Right now PG sends us 3 messages:

    Data Row - That's ID in your case
    Command Completed - That query is done
    Error Response - There was an error on commiting the transaction, since every query run in an implicit transaction
    

    After we receive Command Completed message we treat that specific query as being 'done' and we've read everything related to it. Reading after that would mean that we're reading a response for another query (that happens if you batch multiple queries together, like SELECT 1; SELECT 2; SELECT 3...). There is also the problem that there might be thousands of rows we would have to read and buffer just to make sure there are no errors in the end.

  5. thothothotho commented on Mar 11, 2022

    @thothothotho
    Author

    If I make a query that returns a thousand of rows + a final error that basically invalidate all the rows I have just processed, then I would not mind if the first read does not throw.
    It starts to be the programmer responsability to consume all the rows he asks for and eventually get the error.
    In that kind of scenario, the programmer usually have some form of a loop to consume all the rows, so he'll get the error at the end.

    However, the scenario where the programmer make a query that is guarantee to return just one row is extremely common, and the driver should help for that common case. I'm not sure many programmers loop on the NpgsqlDataReader when they just expect one row. It's easy to get lazy, especially when it works 99% of the time.

    If in my case, the server apparently needs 3 message to answer me, well, that is a technical detail of the protocol with the server. That kind of detail does not have to leak to the user of the driver.

    So IMHO, the driver could look ahead just few more messages from the server (not a thousand, but at least the next one). If the next message is still a Data Row, then just keep it for the next Read invocation and return. So you never need to buffer more than one Data Row.
    And with that kind of lookahead, you could improve the API behavior, and I doubt that would have any negative performance impact.

  6. roji commented on Mar 20, 2022

    @roji
    Member

    We discussed this offline, here are some intermediary options and thoughts:

    1. We can specifically address the single-row case for ExecuteReader by buffering a row ahead (as suggested above by @thothothotho).
      • This doesn't handle cases of early dispose (Dispose when there are still multiple unconsumed rows)
      • The exception is surfaced at the wrong time, i.e. I try to read the first row - which is there and fine - and I get an exception because of what comes afterwards. It prevents the user from consuming the first row.
      • This "breaks" sequential mode, in the sense that we'd have to buffer the entire first row (assuming we implement it there too, which we should if we go in this direction)
    2. We can throw on Dispose.
      • That raises the exception at the right time, and doesn't prevent consuming earlier data because a later command caused an error.
      • Throwing from dispose is considered bad, and can mess up application error handling.
    3. We can say "we don't handle this"
      • Users can still call Close (or NextResult) explicitly to get any exceptions, though this seems like a bad pit of failure.
      • We could still raise the exception if/when we implement the theoretical resultset buffering mode.
        • We don't even know for sure if we're doing it.
        • I'm really not sure I'd want that to be a new default (all existing code would start using lots of memory)
        • Problem stays unaddressed if the user doesn't do resultset buffering
        • Same timing problem: we'd raise the exception early, before the (OK) resultset is consumed.

    I'll think about this some more and try to consult with others.

    Note: regardless of our choice above, we can make sure that if NpgsqlDataReader.Read is called and there are no more rows in the resultset, it would throw rather than return false if there's an error after that.

  7. tamas-nucleus commented on Sep 7, 2022

    @tamas-nucleus

    I've also run into this problem several times already in just a few months working with Postgres, in various constellations with NpgsqlBatches. Fortunately, only during testing so far. I'm afraid of more serious consequences in the future, where some code assumes an operation succeeded when it really didn't, and then moves on to further steps in a workflow that should never have been executed. What makes that really scary is that it can potentially happen many times before it is noticed, since nothing fails.

    With my limited knowledge, of the options proposed by @roji, it is only option 2 that sounds reasonable to me, and I cannot think of any other option either. I understand that throwing from Dispose is dangerous in itself. But I'd still argue that messing up once because of broken exception handling, noticing it and fixing the problem is better than messing up many times without knowing.

    One idea could be to make throwing from Dispose an opt-in behaviour. Then users could take responsibility for ensuring that their cleanup and exception handling code is prepared to handle exceptions from Dispose. In particular, using using statements (as opposed to explicit finally blocks with cleanup logic in them), this is not even that difficult to achieve.

    Another measure to mitigate problems because of exceptions that don't come could be to document the issue (for example somewhere around https://www.npgsql.org/doc/diagnostics/exceptions_notices.html), along with some workarounds/recommendations on how to deal with it.

  8. changed the title [-]bogus query fails to trigger a `Npgsql.PostgresException`[/-] [+]ExecuteReader.Dispose swallows exceptions[/+] on Sep 7, 2022
  9. roji commented on Sep 7, 2022

    @roji
    Member

    @tamas-nucleus I tend to agree that throwing from Dispose seems like the least bad option here, and has the advantage of at least being discoverable (as opposed to swallowing exceptions)... I'm not a fan of making this opt-in though, precisely because that would be very undiscoverable.

    We'll discuss this in an upcoming meeting to see what we want to do in 7.0.

  10. roji commented on Sep 10, 2022

    @roji
    Member

    Decision: we'll start throwing exceptions from Dispose, as the least bad option here. As "inspiration", FileStream also throws from Dispose.

  11. self-assigned this
    on Sep 10, 2022
  12. added this to the 7.0.0 milestone on Sep 10, 2022
  13. added a commit that references this issue on Sep 25, 2022
    25d7b5c
  14. added a commit that references this issue on Sep 25, 2022
    cc70a3b
  15. changed the title [-]ExecuteReader.Dispose swallows exceptions[/-] [+]ExecuteReader.Dispose should not swallow exceptions[/+] on Nov 6, 2022
  16. added theissue type on Jun 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions