You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Allow for registration of custom type handlers #1550
I'm following up with the discussion we had on Gitter with an issue as you suggested.
I propose we open up the internal type handler mechanism or similar to allow for registration of custom types. The use-case for this is the prevalence of 3rd party extensions as well as custom forks of Postgres that require the registration of custom types. In my specific case, we're using a fork Agensgraph that requires the addition of Vertex, Edge, GraphId and Path types. Since this is not a very popular fork, it does not make much sense to include these type handlers directly in the core NpgSql repository. The workarounds is to either Fork the library or to fallback to the text-based encoding which for obvious reasons that is not ideal.
I have not looked deeply at the technical details, but perhaps supplying a registration function that takes as input the type's oid and an ITypeHandler would be sufficient.
Closing as a duplicate of #1475 - the plan is definitely to look into this for 3.3, so not right away but definitely in the horizon. @johnberzy-bazinga please post your specific use case on #1475.
One more note: forking Npgsql to add your specific type handlers is indeed not ideal, but it's not as bad as it sounds. Type handlers are very self-contained, so they will not conflict with any future version of Npgsql. And it's very likely that whatever work you do now will carry over whenever an extensible type handler API is introduced in 3.3. I'd consider going for it in your place.
@johnberzy-bazinga now that #1475 is done, I'm interested in knowing whether the API is sufficient for you and in general working with you to make it happen. Do you plan on taking a stab at the plugin soon?
I created the type handler a while back in my fork johnberzy-bazinga@50ed817 and by the looks of it, it should be relatively simple to follow the JSON plugin example. The only thing that I'm a little unsure about, is in the agensdb fork the Vertex, Edge, and Path types are really just composite types (using record_snd, record_recv) but they are registered as new types, so I ended up just adding additional attribute mappings in the RecordHandler. Would you recommend I just create new handlers instead?
@johnberzy-bazinga well, the first question is whether what typtype the agensdb types have in pg_type (before looking at the send/recv methods).
If it's "c", then they're totally standard composite types, and you actually don't need anything - people can simply use MapComposite<T>() to map them to CLR types you would provide. It would still make sense to create a nuget plugin that would provide the CLR types and also a UseAgensDb() extension method to set up the mappings by doing the proper MapComposite<T>() yourself. But this would be more of a convenience method.
The other option is that your types have a 'b' in their typtype, in which case they're full-fledged "base" types that require the new type mapping extensibility API. It's still possible that they'd have record_snd/record_recv as their I/O functions.
Let me know which one it is and we'll see how to proceed from there.
Do you have any reservation around exposing some of the TypeMappers functionality around getting a typehandler by oid? As it stands, the INpgsqlTypeMapper interface is write-only, so it makes it impossible to create any sort of recursive typehandler. Exposing read functionality would be especially useful when dealing with composite types that don't expose a default ctor (which is the case with a lot of F# types). Also, in the AgensDb case it would be nice if I could create generic versions of the Vertex and Edge types e.g. Vertex<Person>, but the information required to establish the correct generic type parameter is encoded in the graphid (first field in the record's payload), so a custom handler is required. The work around is to create some sort of surrogate or intermediate types, but this creates a lot of unnecessary garbage.
I'd like to better understand your question... Do you mean you want to be able to read existing mappings on INpgsqlTypeMapper - to find out which mappings currently exist - or to extend Npgsql type handlers such as CompositeTypeHandler? Although I plan to do the former, I can't see how it would help you support composite types without a default ctor, generic composite types etc.
I'm guessing you want to be able to inherit from Npgsql's internal CompositeTypeHandler and do you own thing (e.g. somehow instantiate CLR types without a default constructor (although how exactly?)). I've just pushed a change (9e077d8) that makes it possible to map your own custom composite type handlers. However, additional modifications to CompositeTypeHandler itself are probably necessary (making it public, breaking down its work into parts you would be able to reuse etc.), I'll wait for more details from you.
If your type handler actually needs to return arbitrary types (e.g. Vertex<Person>, Vertex<Chair>) you scenario is a bit more complicated than usual - you would have to provide some way to your users to map graphids to CLR types such as Person. This mapping information could be passed to your UseAgensDb() setup method, and from there passed into your handlers.
Regardless, the Json.NET plugin happens to be another example of a handler which returns arbitrary types: you can use it to deserialize any JSON document into any CLR class by calling NpgsqlDataReader.GetValue<T>(column). Take a look at how it overrides the ValueTask<T> Read<T>(NpgsqlReadBuffer buf, int len, bool async, FieldDescription fieldDescription = null) rather than the usual way of implementing INpgsqlSimpleTypeHandler<T>. You would have to think about what such a handler would return by default, though (this is what NpgsqlDataReader.GetValue(column) returns) - in the Json.NET example this is a simple string.
Anyway, keep on going, let me know if I've understood your needs properly. If so, I'm assuming you'll want a CompositeTypeHandler to inherit from, which would take care of the actual reading/writing, and where you'd simply override the creation (instead of new() with the default constructor).
@roji thanks for the guidance. The new api is very intuitive, so I'm sure there will be many more plugins to come.
Essentially, I want to be able to do something like this, where I'm able to obtain the registered type handler instance for a particular oid within another type handler. That would enable both my described scenarios because I can read a composite type's fields one at a time.
I'm able to read all a composite fields first, then pass the field values to a constructor of an immutable type (e.g. F# record).
I can read the graphid field first, then use that information to obtain the generic type parameter to construct a Vertex<T> or Edge<T> generic types.
Hope that makes sense. Feel free to ask for further clarification.
@roji I looked a bit more at the record/composite handler, and I can see now how it's going to be problematic to achieve what I want without the use of ugly reflection hacks. I didn't realize the NpgsqlTypeHandler.ReadAsObject methods were non-public. I guess what I'm really after is a way to invoke a "child" type handler within a composite type handler. Maybe by abstracting this functionality out. thoughts?
@johnberzy-bazinga, I've created a branch where you can inherit from a CompositeHandlerBase, which provides field resolution etc. You should be able to override Read and Write to do the stuff you want.
But here's some stuff I don't understand yet. I understand that you have Vertex and Edge as PostgreSQL composite types, but I'm not sure where Vertex fits in there. Is Person some other arbitrary PostgreSQL composite type (i.e. which you created for your application), and then you have a specific person_vertex which is a composite over that? In other words, are we talking about a composite Person type nested inside another composite Vertex, which you'd like to expose as a generic CLR Vertex? And where does the graphid fix into all of this?
Let me see if I can clarify the Agens strucure a bit.
The GraphId type is just an 8 byte integer. The first 2 bytes represents the vertex or edge label e.g. Person, Likes, FriendsWith, etc. Every label is backed by a separate table behind the scenes. The next 6 bytes represents the row id in that particular table.
Vertices and Edges are both composite type with two fields. (id GraphId, properties jsonb). Edges have an additional two fields (start GraphId, end GraphId) that represent source and target vertices, but that's not very relevant now.
The properties field is the document that stores properties pertaining to that particular vertex or edge. Agens takes a schemaless approach to edges and vertices so there are no other custom columns per edge or vertex.
The main reason I need to implement my own custom composite handler, is that I'm unsure what the "type" (label) of a vertex/edge is without first unpacking the graphid. Without knowing the label first, I can't know what to serialize the properties field into. Since a lot of the graph traversals return heterogeneous results, I also can't rely on a user to be able to supply an explicit type parameter to Read<T> like you suggested earlier.
So the approach I was thinking for the handler was to:
read the graphid for a record.
extract the label from the graphid.
get the clr type from some sort of label to clr type mapper.
serialize the properties field into the type read from previous step
Activity
[-]Add extensibility to typehandler mechanism[/-][+]Allow for registration of custom type handlers[/+]NinoFloris commentedon May 11, 2017
See: #1475 :)
roji commentedon May 17, 2017
Closing as a duplicate of #1475 - the plan is definitely to look into this for 3.3, so not right away but definitely in the horizon. @johnberzy-bazinga please post your specific use case on #1475.
roji commentedon May 17, 2017
One more note: forking Npgsql to add your specific type handlers is indeed not ideal, but it's not as bad as it sounds. Type handlers are very self-contained, so they will not conflict with any future version of Npgsql. And it's very likely that whatever work you do now will carry over whenever an extensible type handler API is introduced in 3.3. I'd consider going for it in your place.
johnberzy-bazinga commentedon May 19, 2017
Thanks @roji and @NinoFloris. Will repost use case in #1475
roji commentedon Jul 3, 2017
@johnberzy-bazinga now that #1475 is done, I'm interested in knowing whether the API is sufficient for you and in general working with you to make it happen. Do you plan on taking a stab at the plugin soon?
johnberzy-bazinga commentedon Jul 3, 2017
@roji certainly.
I created the type handler a while back in my fork johnberzy-bazinga@50ed817 and by the looks of it, it should be relatively simple to follow the JSON plugin example. The only thing that I'm a little unsure about, is in the agensdb fork the Vertex, Edge, and Path types are really just composite types (using record_snd, record_recv) but they are registered as new types, so I ended up just adding additional attribute mappings in the RecordHandler. Would you recommend I just create new handlers instead?
roji commentedon Jul 3, 2017
@johnberzy-bazinga well, the first question is whether what typtype the agensdb types have in pg_type (before looking at the send/recv methods).
If it's "c", then they're totally standard composite types, and you actually don't need anything - people can simply use
MapComposite<T>()to map them to CLR types you would provide. It would still make sense to create a nuget plugin that would provide the CLR types and also aUseAgensDb()extension method to set up the mappings by doing the properMapComposite<T>()yourself. But this would be more of a convenience method.The other option is that your types have a 'b' in their typtype, in which case they're full-fledged "base" types that require the new type mapping extensibility API. It's still possible that they'd have record_snd/record_recv as their I/O functions.
Let me know which one it is and we'll see how to proceed from there.
johnberzy-bazinga commentedon Jul 3, 2017
@roji Just checked the typtype and it is indeed 'c', so I guess I can just
MapComposite<T>like you mentioned.As for the graphid type, it is a 'b' type, so I can just modify the type handler I wrote for that to work with the new type handling mechanism.
So I guess I can make the UseAgensDb method Map the three composite types and register the type handler for the graphid type.
thanks
roji commentedon Jul 3, 2017
Yep, sounds good.
Once you have something working, point me towards it so I can take a look.
johnberzy-bazinga commentedon Jul 3, 2017
Hi @roji
This is a quick and dirty initial take https://github.com/johnberzy-bazinga/Npgsql.AgensGraph. I only did a bit of manual testing (only reads so far), but looks like it works.
thanks
johnberzy-bazinga commentedon Jul 4, 2017
Hi @roji
Do you have any reservation around exposing some of the TypeMappers functionality around getting a typehandler by oid? As it stands, the INpgsqlTypeMapper interface is write-only, so it makes it impossible to create any sort of recursive typehandler. Exposing read functionality would be especially useful when dealing with composite types that don't expose a default ctor (which is the case with a lot of F# types). Also, in the AgensDb case it would be nice if I could create generic versions of the
VertexandEdgetypes e.g.Vertex<Person>, but the information required to establish the correct generic type parameter is encoded in the graphid (first field in the record's payload), so a custom handler is required. The work around is to create some sort of surrogate or intermediate types, but this creates a lot of unnecessary garbage.thanks,
John
More flexible mapping for composite
roji commentedon Jul 4, 2017
Hey @johnberzy-bazinga.
First, the work you've already done definitely looks good, it's nice to see someone coding against the new API.
I'd like to better understand your question... Do you mean you want to be able to read existing mappings on INpgsqlTypeMapper - to find out which mappings currently exist - or to extend Npgsql type handlers such as CompositeTypeHandler? Although I plan to do the former, I can't see how it would help you support composite types without a default ctor, generic composite types etc.
I'm guessing you want to be able to inherit from Npgsql's internal CompositeTypeHandler and do you own thing (e.g. somehow instantiate CLR types without a default constructor (although how exactly?)). I've just pushed a change (9e077d8) that makes it possible to map your own custom composite type handlers. However, additional modifications to CompositeTypeHandler itself are probably necessary (making it public, breaking down its work into parts you would be able to reuse etc.), I'll wait for more details from you.
If your type handler actually needs to return arbitrary types (e.g.
Vertex<Person>,Vertex<Chair>) you scenario is a bit more complicated than usual - you would have to provide some way to your users to map graphids to CLR types such asPerson. This mapping information could be passed to yourUseAgensDb()setup method, and from there passed into your handlers.Regardless, the Json.NET plugin happens to be another example of a handler which returns arbitrary types: you can use it to deserialize any JSON document into any CLR class by calling
NpgsqlDataReader.GetValue<T>(column). Take a look at how it overrides theValueTask<T> Read<T>(NpgsqlReadBuffer buf, int len, bool async, FieldDescription fieldDescription = null)rather than the usual way of implementingINpgsqlSimpleTypeHandler<T>. You would have to think about what such a handler would return by default, though (this is whatNpgsqlDataReader.GetValue(column)returns) - in the Json.NET example this is a simple string.Anyway, keep on going, let me know if I've understood your needs properly. If so, I'm assuming you'll want a CompositeTypeHandler to inherit from, which would take care of the actual reading/writing, and where you'd simply override the creation (instead of new() with the default constructor).
johnberzy-bazinga commentedon Jul 4, 2017
@roji thanks for the guidance. The new api is very intuitive, so I'm sure there will be many more plugins to come.
Essentially, I want to be able to do something like this, where I'm able to obtain the registered type handler instance for a particular oid within another type handler. That would enable both my described scenarios because I can read a composite type's fields one at a time.
I'm able to read all a composite fields first, then pass the field values to a constructor of an immutable type (e.g. F# record).
I can read the
graphidfield first, then use that information to obtain the generic type parameter to construct aVertex<T>orEdge<T>generic types.Hope that makes sense. Feel free to ask for further clarification.
Thanks.
John
johnberzy-bazinga commentedon Jul 5, 2017
@roji I looked a bit more at the record/composite handler, and I can see now how it's going to be problematic to achieve what I want without the use of ugly reflection hacks. I didn't realize the
NpgsqlTypeHandler.ReadAsObjectmethods were non-public. I guess what I'm really after is a way to invoke a "child" type handler within a composite type handler. Maybe by abstracting this functionality out. thoughts?roji commentedon Jul 9, 2017
@johnberzy-bazinga, I've created a branch where you can inherit from a CompositeHandlerBase, which provides field resolution etc. You should be able to override Read and Write to do the stuff you want.
But here's some stuff I don't understand yet. I understand that you have Vertex and Edge as PostgreSQL composite types, but I'm not sure where Vertex fits in there. Is Person some other arbitrary PostgreSQL composite type (i.e. which you created for your application), and then you have a specific person_vertex which is a composite over that? In other words, are we talking about a composite Person type nested inside another composite Vertex, which you'd like to expose as a generic CLR Vertex? And where does the graphid fix into all of this?
johnberzy-bazinga commentedon Jul 12, 2017
@roji thanks. I'll take a look at that.
Let me see if I can clarify the Agens strucure a bit.
The
GraphIdtype is just an 8 byte integer. The first 2 bytes represents thevertexoredgelabel e.g. Person, Likes, FriendsWith, etc. Every label is backed by a separate table behind the scenes. The next 6 bytes represents the row id in that particular table.Vertices and Edges are both composite type with two fields. (id
GraphId, propertiesjsonb). Edges have an additional two fields (startGraphId, endGraphId) that represent source and target vertices, but that's not very relevant now.The
propertiesfield is the document that stores properties pertaining to that particular vertex or edge. Agens takes a schemaless approach to edges and vertices so there are no other custom columns per edge or vertex.The main reason I need to implement my own custom composite handler, is that I'm unsure what the "type" (label) of a vertex/edge is without first unpacking the
graphid. Without knowing the label first, I can't know what to serialize the properties field into. Since a lot of the graph traversals return heterogeneous results, I also can't rely on a user to be able to supply an explicit type parameter toRead<T>like you suggested earlier.So the approach I was thinking for the handler was to:
Thoughts?
thx,
John