Skip to content

Using text parameters for replication #4046

Closed

Description

@marco6

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
  • 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

  1. roji commented on Oct 18, 2021

    @roji
    Member

    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.

    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.

    Yeah - though this is a bit trickier than it looks:

    • While built-in types have a fixed type OID, types added by extension do not (PostGIS, hstore, ltree...). So in the general case we'd need to find a solution for those types in any case. We could still have the NpgsqlDbType values for built-in types have the OID, and assign extension types some arbitrary large value which is recognized internally.
    • Arrays and ranges are currently expressed as NpgsqlDbType.Integer | NpgsqlDbType.Array and NpgsqlDbType.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.
    • However, I'm not a huge fan of having NpgsqlDbType only sometimes have the correct type OID; people may use it with that assumption, only to have the code blow up for extension types. But we could simply add a uint TypeOID property on NpgsqlParameter, which allows specify an OID directly.
    • Note that NpgsqlDbType values for built-in types do have a [BuiltInPostgresType] attribute referencing the type OID, this may be useful.
  2. roji commented on Oct 18, 2021

    @roji
    Member

    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?

  3. roji commented on Oct 18, 2021

    @roji
    Member

    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.

  4. marco6 commented on Oct 18, 2021

    @marco6
    ContributorAuthor

    While built-in types have a fixed type OID, types added by extension do not (PostGIS, hstore, ltree...). So in the general case we'd need to find a solution for those types in any case. We could still have the NpgsqlDbType values for built-in types have the OID, and assign extension types some arbitrary large value which is recognized internally.

    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).

    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.

    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.

    Note that NpgsqlDbType values for built-in types do have a [BuiltInPostgresType] attribute referencing the type OID, this may be useful.

    This attribute is internal so I can't use it without a fair amount of Reflection and risk since is not part of the public interface.

    However, I'm not a huge fan of having NpgsqlDbType only sometimes have the correct type OID; people may use it with that assumption, only to have the code blow up for extension types. But we could simply add a uint TypeOID property on NpgsqlParameter, which allows specify an OID directly.

    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_function which probably expects a different type WTR the string I'm sending.

    You're essentially asking for #4049

    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:

    • custom NpgsqlTypeHandler that writes the 0 + OID to the protocol so that I can specify that is text-based?
    • custom struct/class taking (oid, string) that writes 0 + OID to the protocol so that is just for that type alone?
    • adding support for text-based parameters directly in NpgsqlParameter?

    It would even be fine if this would be an implementation detail in my software, I probably just need the extension point.

    I'd be interested in your scenario which requires this - could you provide a bit more context?

    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:

    • for server-server replication - the main aim is to improve availability and (read) performance. The environment is considered to be safe: there is an inversion of roles here as the server who produces the data is not authenticated, but the one who receives it is.
    • to understand data changes: the current solution is not a good match with this one except for auditing/notification (since we don't have the real type, but just a string). This could be covered by Support PG14 binary logical replication #4049 .
    • there are cases (one of which is what I'm working on) which is not part of these categories. One example would be master-master replication with conflict resolution (not my case BTW).
  5. roji commented on Oct 18, 2021

    @roji
    Member

    Rather than exposing an OID on the columns of RelationMessage, we should simply expose the PostgresType for that type OID. [...]

    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.

    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.

    You're essentially asking for #4049

    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).

    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:

    for server-server replication - the main aim is to improve availability and (read) performance. The environment is considered to be safe: there is an inversion of roles here as the server who produces the data is not authenticated, but the one who receives it is.

    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!

  6. marco6 commented on Oct 18, 2021

    @marco6
    ContributorAuthor

    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)?

    Yeah I'm reading the code to manage the protocol... Here and here is the relevant part. Was there a rationale for hiding PreferTextWrite?

    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.

    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:

    NpgsqlDbType dbType;
    if (!PostgresOids.TryGetDefaultPgType(targetOid, out dbType))
    {
        dbType = (NpgsqlDbType)targetOid; // This is not nice
    }
    ...
    // use the dbType

    And somewhere else in my logic I simply have a Dictionary<unit, unit> oidsMap: once I get a TypeMessage I:

    • check if the type is already there,
    • if not present, ask the target db (by name).

    How could Npgsql do something similar? Or am I missing something?

    In any case, I'd be curious to know more about what you're doing, at whatever point where you're comfortable sharing more!

    Sure, if at any point there will be the chance I will.

  7. marco6 commented on Oct 18, 2021

    @marco6
    ContributorAuthor

    Oh seems like I'm really missing something. NpgsqlParameter.DataTypeName is 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.

  8. roji commented on Oct 18, 2021

    @roji
    Member

    Oh seems like I'm really missing something. NpgsqlParameter.DataTypeName is already a thing!

    Yep. I'll try to work on the issues (and especially on #4049), will let you know how it goes.

  9. roji commented on Oct 25, 2021

    @roji
    Member

    @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.

  10. roji commented on Oct 27, 2021

    @roji
    Member

    @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.

  11. marco6 commented on Oct 27, 2021

    @marco6
    ContributorAuthor

    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!

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions