npgsql icon indicating copy to clipboard operation
npgsql copied to clipboard

No way to hook up the Notice handler when using NpgsqlDataSource

Open LaXiS96 opened this issue 2 years ago • 4 comments

The issue

using var pgsql = new NpgsqlDataSourceBuilder("Host=192.168.1.1;Username=postgres;Password=postgres;Database=postgres").Build();
using var cmd = pgsql.CreateCommand();
cmd.Connection.Notice += (sender, e) => Console.WriteLine(e.Notice);

throws:

Unhandled exception. System.NotSupportedException: Connection and transaction access is not supported on commands created from DbDataSource.
   at Npgsql.NpgsqlDataSourceCommand.get_DbConnection()
   at Npgsql.NpgsqlCommand.get_Connection()
   at Program.Main(String[] args) in Program.cs:line 3

There doesn't seem to be a way to configure this Notice handler anywhere else than on an NpgsqlConnection. I would be fine with setting this handler on NpgsqlDataSource itself or through its builder, or even being able to define the notices' log level when logging with UseLoggerFactory (instead of them being at Debug level).

Further technical details

Npgsql version: 8.0.1 PostgreSQL version: 16.1 Operating system: Windows 10 19045.3803

LaXiS96 avatar Dec 20 '23 12:12 LaXiS96

Notices still come on specific physical connections, and using NpgsqlDataSource doesn't mean you stop using NpgsqlConnection; so you can continue registering (and unregistering) callbacks on NpgsqlConnection.OnNotice just as before - have you encountered any problems doing that?

However, I can indeed see the utility in registering a callback at the NpgsqlDataSourceBuilder level, which automatically gets wired up for all connections coming from the data source...

roji avatar Dec 21 '23 16:12 roji

However, I can indeed see the utility in registering a callback at the NpgsqlDataSourceBuilder level, which automatically gets wired up for all connections coming from the data source...

Wouldn't this mean your callback will get called N times for each distinct event? Not sure I see the use in that. I would probably feel more for some bg/mgmt connection that we run this over, if we want to make it a datasource thing at all.

NinoFloris avatar Jan 11 '24 18:01 NinoFloris

@NinoFloris I think this is about PG notices, not notifications - i.e. not about the PG notify/wait pub/sub mechanism... A notice can get received on a specific physical connection e.g. as a result of a command executed on that connection. Or am I confusing things?

roji avatar Jan 11 '24 20:01 roji

No it's me who was confused. For notices I can also see a use :)

NinoFloris avatar Jan 11 '24 21:01 NinoFloris