Repository navigation
Description
Hi everybody!
I'm playing with the logical decoding feature, but I fail to see how to actually use the data I receive.
I explain a little further.
Messages of type DeleteMessage, FullDeleteMessage, FullUpdateMessage, IndexUpdateMessage, InsertMessage, KeyDeleteMessage, UpdateMessage contain at least one list (actually Memory<>) of TupleData. TupleData contains either:
-
NULL wihth two meaning
- null when
Kind == TupleDataKind.Null - unchanged when
Kind == TupleDataKind.UnchangedToastedValue
- null when
-
the stringified value (when
Kind == TupleDataKind.TextValue).
This follows what pgoutput exports. The stringified version is not the .ToString of C#, but the result of the text output function for the type of the related column (as in CREATE TYPE).
Now if I wanted to replay the transaction to a secondary server I would need to:
- open a connection to the secondary database;
- generate a proper query;
- add the parameters with the values I received;
- execute the command.
This would possibly happen in a transaction. However, I only have the string representation of the parameters, so I can't find a way to pass the non-string parameters as strings.
If I was using libpq, that would be very trivial as I would just call PQexecParams or similar and specifying the OIDS of my types (taken from the RelationMessage), my string values, and 0-initialized array for the paramFormats parameter. This is also guaranteed to work for user-defined types as textual input-output functions are required.
On the other side, I can't find anything in the documentation that allows me to do such a thing with npgsql, except encoding the text directly in the query which implies escaping (with all the problems it brings).
As a last note, to my surprise, NpgsqlDbType enum does not use the well-known type OIDs under the hood, so AFAIK there is no way with Npgsql to map a type OID returned by its own API (in the RelationMessage::Column.DataTypeId field) to a usable NpgsqlDbType. While this is (of course) a minor problem it still makes it difficult to actually use the replication feature.
Activity
roji commentedon Oct 18, 2021
You're essentially asking for #4049, i.e. the ability to have Npgsql read actual .NET objects (decoding them from their PostgreSQL binary representation). We really hope to complete this for the upcoming 6.0 release, but note that on the PG side this only exists starting with version 14.
Once that's available, you should be able to simply assign the .NET instance you get to NpgsqlParameter.Value, and things will work. There is still a problem where the .NET type doesn't by default correspond to the OID you got from replication; for example, a jsonb document would be decoded as a string, but if you simply send that on a parameter it gets sent as text, not jsonb. See below for thoughts on that.
Yeah - though this is a bit trickier than it looks:
NpgsqlDbType.Integer | NpgsqlDbType.ArrayandNpgsqlDbType.Integer | NpgsqlDbType.Range; this yields values which have nothing to do with the actual type OIDs for them. We could change this by adding e.g. NpgsqlDbType.IntegerArray and Npgsql.IntegerRange (the latter was actually just added for 6.0), and give it the actual type OID.But we could simply add a uint TypeOID property on NpgsqlParameter, which allows specify an OID directly.roji commentedon Oct 18, 2021
Stepping back, up to now I don't think we specifically took into account the scenario of a .NET application using logical replication to import data back into a 2nd database; this is usually done by directly setting up replication between two PostgreSQL instances, without .NET in the middle.
I'd be interested in your scenario which requires this - could you provide a bit more context?
roji commentedon Oct 18, 2021
Another thought regarding specifying a type OID directly...
Rather than exposing an OID on the columns of RelationMessage, we should simply expose the PostgresType for that type OID. This would allow users to get the name, and set it directly on NpgsqlParameter.DataTypeName - that seems like the ideal solution to this problem. Npgsql knows internally exactly which type OID corresponds to which type (including extension types), so there's no reason to have users mucking around with OIDs and dealing with extension types themselves... Opened #4051 to track this.
marco6 commentedon Oct 18, 2021
Agreed. Still, there is a TypeMessage that will help in this case (it would of course need an interrogation to the 2nd party database, but I think that the replication works this way in postgres, too).
This is nice, but how would it work for non-standard types (e.g. I create a type that didn't exist - not a well-known extension without a well-known OID)? Wouldn't it need to cast a unit value to a NpgsqlDbType? I think that such a cast is bad as it makes worthless the coverage of a switch statement (e.g. if I switch over all the cases of an enum I would sanely suppose that there are no other cases if I don't update my dependencies). What about a mapping function? This is how I'm handling things right now.
This attribute is
internalso I can't use it without a fair amount of Reflection and risk since is not part of the public interface.Agreed, that is not nice. It could be nice to specify this in a NpgsqlParameter, but that wouldn't be enough since as things are now it would try to use the
receive_functionwhich probably expects a different type WTR the string I'm sending.Uhm... while I could work with that, I would need to limit my code to known types. This set is bigger than the ones supported directly by Npgsql as I could add more, but as big as it could be, it is still a non-generic solution. Moreover, it costs more from the point of view of the computations as it would require a translation from bin => dotnet + one from dotnet => bin, hoping that those steps are not lossy. By the way, limiting my types is not very different from deserializing myself all the types I want to support: once the set is finite is just a matter of writing more code (with the advantage of working for PostgreSQL 10+ and the disadvantage of string manipulation and having to maintain more code).
So ultimately I think this is not #4049, but a different one. Many ideas on how, but I don't think I can right now:
NpgsqlTypeHandlerthat writes the0+ OID to the protocol so that I can specify that is text-based?struct/classtaking (oid, string) that writes0+ OID to the protocol so that is just for that type alone?NpgsqlParameter?It would even be fine if this would be an implementation detail in my software, I probably just need the extension point.
I don't think I can go in too much detail in this part of the project, but still as a rough idea, replication can be used in my mind with different architectures in mind:
roji commentedon Oct 18, 2021
So the idea would be that you get a PostgresType, which has a name on it (as a string); that name can be assigned to an NpgsqlParameter's DataTypeName property, which is an alternative to using NpgsqlDbType. This means that even if you're exporting/importing between different databases, where e.g. PostGIS geometry has different type OIDs, everything works since you're just using type names (
geometry) and not OIDs (the names are the same across databases, the OIDs not necessarily). So no more NpgsqlDbType at all.OK, so you're asking to be able to read and write PG types which Npgsql doesn't know about. I can understand that reasoning, if the idea really is for you to be a "pass-through" between two databases, without needing to look or doing anything with actual opaque data. Since #2756, we allow reading any type as binary on NpgsqlDataReader; we could do something similar for writing (opened #4052 with more details). Then, once #4049 is available, you'd be able to just get out the raw binary representation.
The disadvantage of this approach would be the requirement to have PG14 (for binary data). We indeed could allow you to send text parameters instead of binary - most of the machinery for that is actually already implemented internally, but not exposed; opened #4053 to track. If I'm understanding you correctly, this would be your preferred option since it would work on older PG versions, right? (even though it's likely slower for PG to format/parse text representations)?
I'd like to be able to support the above for 6.0.0, but since we're very close to the release time, I can't make any promises. We do already have a pack of nice improvements to replication, so it would be nice to be able to round it off though.
BTW:
I think that for this, just replicating directly from one PG to another (which is what replication was originally conceived for) is the better/simpler option, no? What's the added value of the .NET application here?
In any case, I'd be curious to know more about what you're doing, at whatever point where you're comfortable sharing more!
marco6 commentedon Oct 18, 2021
Yeah I'm reading the code to manage the protocol... Here and here is the relevant part. Was there a rationale for hiding
PreferTextWrite?Yes that could work, however I'm curious: how could you use it in a NpgsqlCommand? Given a name (e.g.
geometry) you would need to ask the db for the OID, which is a (possibly unwanted) roundtrip. Isn't it something that should be designed in the application instead of the library?Right now I'm doing something like:
And somewhere else in my logic I simply have a
Dictionary<unit, unit> oidsMap: once I get aTypeMessageI:How could Npgsql do something similar? Or am I missing something?
Sure, if at any point there will be the chance I will.
marco6 commentedon Oct 18, 2021
Oh seems like I'm really missing something.
NpgsqlParameter.DataTypeNameis already a thing! This is neat, I will read your code more carefully then. Still, I would love to see #4051, #4052, #4053. If I can be of any help, I can do something during the weekends or I can try during the normal days of work.roji commentedon Oct 18, 2021
Yep. I'll try to work on the issues (and especially on #4049), will let you know how it goes.
roji commentedon Oct 25, 2021
@marco6 FYI I've just submitted #4064 to support binary replication. This allows you to get a decoded .NET type - or raw byte data - directly from the replication API. The former can be set on an NpgsqlParameter, and the DataTypeName can be copied across as well (it's exposed too).
I'll try to look at the other related issues as well.
roji commentedon Oct 27, 2021
@marco6 most of the discussion above seems to be covered by the other linked issues, so I'm going to go ahead and close this one. But we can continue having general conversation here for sure.
marco6 commentedon Oct 27, 2021
Hi @roji ! I read all of your comments but I didn't have time to answer yet. I hope to have a couple of hours during this weekend :-) Thank you for your support and thoughts so far!