Skip to content

NpgsqlTypeHandler for derived type #2390

Closed

Description

@zabulus

Steps to reproduce

I implement NpgsqlTypeHandler for System.IO.Stream:

    class StreamTypeHandler : NpgsqlTypeHandler<Stream>
    {
        public override ValueTask<Stream> Read(NpgsqlReadBuffer buf, int len, bool async, FieldDescription fieldDescription = null)
        {
            throw new NotImplementedException();
        }

        public override int ValidateAndGetLength(Stream value, ref NpgsqlLengthCache lengthCache, NpgsqlParameter parameter)
        {
            if (parameter != null && parameter.Size > 0 && parameter.Size < value.Length)
            {
                return parameter.Size;
            }

            return (int)value.Length;
        }

        public override async Task Write(Stream value, NpgsqlWriteBuffer buf, NpgsqlLengthCache lengthCache, NpgsqlParameter parameter, bool async)
        {
            await value.CopyToAsync(buf.GetStream());
        }
    }

Nothing special, I just need to forward Stream object contents to bytea database field. Reading is not needed

The issue

I receive following exception message:

System.InvalidCastException: 'Can't write CLR type System.IO.MemoryStream with handler type StreamTypeHandler'

Exception is thrown from _nonGenericValidateAndGetLength delegate, particulary because of following condition:

Expression.TypeEqual(valueParam, handledType),

Expression.TypeEquals returns false, because Stream != MemoryStream.

If I change

 class StreamTypeHandler : NpgsqlTypeHandler<Stream> 

to

 class StreamTypeHandler : NpgsqlTypeHandler<MemoryStream> 

Everything works as expected.

Further technical details

Npgsql version: 4.0.5
PostgreSQL version: 11.2
Operating system: Win 10 1803 Build

Other details about my project setup:

Activity

  1. YohDeadfall commented on Mar 24, 2019

    @YohDeadfall
    Contributor

    Yes, it's by design. There are a few reasons why it isn't implemented out of the box:

    • performance (routing a parameter value to the right handler);
    • complexity of type handling (what if a derived class should be handled by a different type handler?);
    • it's a very rare case.

    So if you want to support the provided scenario, override the Read<TAny>, WriteWithLength<TAny> and ValidateAndGetLength<TAny> methods, check that TAny is a stream, and do what you want after.

    I'm closing this issue, but don't hesitate to continue the discussion.

  2. roji commented on Mar 25, 2019

    @roji
    Member

    @zabulus while it's great to see people interested enough to implement type handlers, be aware that it's a pretty internal and therefore unstable API (even though it's in the public namespace). We may change it as our type handler model evolves, so it's not really recommended to do this unless you're willing to keep up over time. For this specific case, unless you have some very specific perf requirements, I'd recommend just using the normal API and handing over a byte[].

  3. zabulus commented on Mar 26, 2019

    @zabulus
    ContributorAuthor

    Actually, yes, it's about performance requirements. We receive unmanaged memory from underlying code and I try to avoid copying between IntPtr and byte[] by wrapping it to UnmanagedMemoryStream.

  4. roji commented on Mar 26, 2019

    @roji
    Member

    In that case, it would seem we should add support for writing Memory<byte> - this seems like a better way to allow writing arbitrary binary data you PostgreSQL bytea. I've opened #2392 to track this, in the meantime you can have a workaround by specifically making sure MemoryStream is routed to your handler, see the [TypeMapping] attribute on ByteaHandler.

  5. zabulus commented on Mar 26, 2019

    @zabulus
    ContributorAuthor

    Writing must be supported from ReadOnlyMemory<byte>.
    both Memory<T> and ReadOnlyMemory<T> take T[] as constructor parameters. Though, it would be greate to use these types, but not in my scenario with native allocated memory.
    On the other hand there are Span<T> and ReadOnlySpan<T>, that do work with native allocated memory. But our code is a mix of C++, C++/CLI, C# and I have doubts that I'll forward everything right in interfaces, so currently my best option is to stick with UnmanagedMemoryStream, reference class that wraps native memory.

  6. roji commented on Mar 26, 2019

    @roji
    Member

    Writing must be supported from ReadOnlyMemory.

    Yes of course, ReadOnlyMemory<byte>, not Memory<byte> (updated #2392).

    both Memory and ReadOnlyMemory take T[] as constructor parameters. Though, it would be greate to use these types, but not in my scenario with native allocated memory.

    You're right, I forgot that Memory can't point to unmanaged memory.

    The problem with Span<T> and ReadOnlySpan<T> is that the ADO.NET API is (probably) incompatible with writing it, at least at the moment - you must assign NpgsqlParameter.Value to point to the value to be written, but it's not possible to reference Span<T> from the heap.

    You can certainly set up your own type handler which would accept UnmanagedMemoryStream - just be aware that the type handler API is pretty volatile.

  7. roji commented on Mar 26, 2019

    @roji
    Member

    One more thing: Memory can't directly wrap a pointer, but apparently there is a way to make that happen. From Stephen Toub's article on Span and Memory:

    You’ll notice that Memory’s _object field isn’t strongly typed as T[]; rather, it’s stored as an object. This highlights that Memory can wrap things other than arrays, like System.Buffers.OwnedMemory. OwnedMemory is an abstract class that can be used to wrap data that needs to have its lifetime tightly managed, such as memory retrieved from a pool. That’s a more advanced topic beyond the scope of this article, but it’s how Memory can be used to, for example, wrap pointers into native memory. ReadOnlyMemory can also be used with strings, just as can ReadOnlySpan.

    I don't know exactly how this would work, but it seems like if Npgsql added support for ReadOnlyMemory<byte> that would at least in principle allow users to pass in native memory.

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