Repository navigation
Description
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
vonzshik commentedon Mar 11, 2022
psqlreports an error immediately because it does read everything PG sends before returning a result set, unlikeExecuteReader, which reads row by row. On the contrary,ExecuteNonQueryandExecuteScalarboth read the whole response before returning result. You should be able to emulate the same behavior (getting an exception) by callingNpgsqlReader.Readafter 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...
vonzshik commentedon Mar 11, 2022
Okay, I was wrong: even calling
Readyou wouldn't get an exception - you can only get it by callingNextResult. I would have advised to useExecuteScalar, but it seems it also doesn't callNextResult, unlikeExecuteNonQuery: I've opened #4378 to track this.thothothotho commentedon Mar 11, 2022
That makes the basic API very unfriendly and dangerous. And your patch against ExecuteScalar does not help if the request ends with
In which case we will have to rely on
ExecuteReader(and do a non obviousNextResultto get the exception).Even doing a second
Readis barely intuitive when you expect just one row. But having to do anotherNextResultwhen you issue just oneselectis 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.vonzshik commentedon Mar 11, 2022
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:After we receive
Command Completedmessage 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, likeSELECT 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.thothothotho commentedon Mar 11, 2022
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
NpgsqlDataReaderwhen 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 nextReadinvocation and return. So you never need to buffer more than oneData Row.And with that kind of lookahead, you could improve the API behavior, and I doubt that would have any negative performance impact.
roji commentedon Mar 20, 2022
We discussed this offline, here are some intermediary options and thoughts:
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.
tamas-nucleus commentedon Sep 7, 2022
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
Disposeis 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
Disposean opt-in behaviour. Then users could take responsibility for ensuring that their cleanup and exception handling code is prepared to handle exceptions fromDispose. In particular, usingusingstatements (as opposed to explicitfinallyblocks 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.
[-]bogus query fails to trigger a `Npgsql.PostgresException`[/-][+]ExecuteReader.Dispose swallows exceptions[/+]roji commentedon Sep 7, 2022
@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.
roji commentedon Sep 10, 2022
Decision: we'll start throwing exceptions from Dispose, as the least bad option here. As "inspiration", FileStream also throws from Dispose.
Stop swallowing exceptions in reader Dispose
Stop swallowing exceptions in reader Dispose (#4677)
[-]ExecuteReader.Dispose swallows exceptions[/-][+]ExecuteReader.Dispose should not swallow exceptions[/+]