Skip to content

Add a connection string parameter to return nullable arrays by default #3386

Description

@roji

See discussion in #443 and the analysis of options in #443 (comment).

Am opening this issue to gather a bit more feedback from users who are hitting this issue - please upvote this if you're running into this and need a solution.

Activity

  1. added this to the vNext milestone on Dec 2, 2020
  2. ABildstein commented on Dec 2, 2020

    @ABildstein

    For posterity: I'm hitting the issue with Dapper
    Details in my original comment: #443 (comment)

  3. Brar commented on Dec 4, 2020

    @Brar
    Member

    @calexander3 and @JBildstein,
    can you try this PR and tell me if adding "ValueTypeArrayNullability=Always" or "ValueTypeArrayNullability=PerInstance" solves your issue?

    Please look at

    public async Task ValueTypeArrayNullabilities(ValueTypeArrayNullability mode)
    for the behavior of the different modes.

  4. ABildstein commented on Dec 4, 2020

    @ABildstein

    thank you @Brar, it works for me for the most part, here's the code I used:

    Click to expand!
    using System;
    using System.Data;
    using System.Linq;
    using System.Threading.Tasks;
    using Dapper;
    using Npgsql;
    
    namespace Test
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                const string connString = "Server=127.0.0.1;Port=5432;User Id=postgres;";
    
                using (var connection = SetupForAlways(connString))
                {
                    Console.WriteLine("Always Nullable:");
                    await Run(connection);
                }
    
                using (var connection = SetupForPerInstance(connString))
                {
                    Console.WriteLine("PerInstance Nullable:");
                    await Run(connection);
                }
            }
    
            static NpgsqlConnection SetupForAlways(string connString)
            {
                connString += "ValueTypeArrayNullability=Always;";
                var connection = new NpgsqlConnection(connString);
    
                SqlMapper.ResetTypeHandlers();
                SqlMapper.AddTypeHandler(typeof(int[]), new ToNonNullableMap<int>());
    
                return connection;
            }
    
            static NpgsqlConnection SetupForPerInstance(string connString)
            {
                connString += "ValueTypeArrayNullability=PerInstance;";
                var connection = new NpgsqlConnection(connString);
    
                SqlMapper.ResetTypeHandlers();
                SqlMapper.AddTypeHandler(typeof(int[]), new ToNonNullableMap<int>());
                SqlMapper.AddTypeHandler(typeof(int?[]), new ToNullableMap<int>());
    
                return connection;
            }
    
            static async Task Run(NpgsqlConnection connection)
            {
                const string sql = @"SELECT * FROM (VALUES 
                    ('{1, NULL}'::INTEGER[], '{2, NULL}'::INTEGER[]),
                    ('{3, 4}'::INTEGER[], '{5, 6}'::INTEGER[])
                    ) as foo(NonNullArray, NullArray)";
    
                var result = await connection.QueryAsync<Model>(sql);
                foreach (var item in result)
                {
                    Console.Write("{ ");
                    Console.Write(string.Join(", ", item.NonNullArray));
                    Console.Write(" }, { ");
                    Console.Write(string.Join(", ", item.NullArray.Select(t => t?.ToString() ?? "NULL")));
                    Console.WriteLine(" }");
                }
            }
    
            class Model
            {
                public int[] NonNullArray { get; set; }
                public int?[] NullArray { get; set; }
            }
    
            // with ValueTypeArrayNullability=Always, mapping the nullable array to non-nullable
            // with ValueTypeArrayNullability=PerInstance, mapping to non-nullable as necessary
            class ToNonNullableMap<T> : SqlMapper.ITypeHandler
                where T : struct
            {
                public object Parse(Type destinationType, object value)
                {
                    if (value is not Nullable<T>[] array) { return value; }
    
                    return Array.ConvertAll(array, t => t ?? default);
                }
    
                public void SetValue(IDbDataParameter parameter, object value)
                {
                    parameter.Value = value;
                }
            }
    
            // with ValueTypeArrayNullability=PerInstance, mapping to nullable as necessary
            class ToNullableMap<T> : SqlMapper.ITypeHandler
                where T : struct
            {
                public object Parse(Type destinationType, object value)
                {
                    if (value is not T[] array) { return value; }
    
                    return Array.ConvertAll<T, T?>(array, t => t);
                }
    
                public void SetValue(IDbDataParameter parameter, object value)
                {
                    parameter.Value = value;
                }
            }
        }
    }

    About the "for the most part": The code as I posted it fails with the second query with the following:

    Unhandled exception. System.Data.DataException: Error parsing column 1 (nullarray=System.Int32[] - Object)
    ---> System.InvalidCastException: Unable to cast object of type 'System.Int32[]' to type 'System.Nullable`1[System.Int32][]'.
    at Deserializeb4fb46e4-eb42-4051-86c7-4a652582976a(IDataReader )
    --- End of inner exception stack trace ---
    at Dapper.SqlMapper.ThrowDataException(Exception ex, Int32 index, IDataReader reader, Object value) in /_/Dapper/SqlMapper.cs:line 3665
    at Deserializeb4fb46e4-eb42-4051-86c7-4a652582976a(IDataReader )
    at Dapper.SqlMapper.QueryAsync[T](IDbConnection cnn, Type effectiveType, CommandDefinition command)
    at Test.Program.Run(NpgsqlConnection connection)
    at Test.Program.Main(String[] args)
    at Test.Program.<Main>(String[] args)

    It works if I run each query on their own or if I switch the order (i.e. first PerInstance, then Always).
    I'm not entirely sure if that's my mistake, a problem with Dapper or Npgsql, can you see something?
    It's not that important though since typically you'd always use the same connection string.

  5. Brar commented on Dec 4, 2020

    @Brar
    Member

    I'm not entirely sure if that's my mistake, a problem with Dapper or Npgsql, can you see something?

    I just played around with your sample code a bit to find out what's going on.

    It turns out that Dapper has a TypeHandlerCache<T> that caches the type handler per query and column which is perfectly reasonable since it should be pretty safe to assume that the type of data you get for the same column after calling NpgsqlDataReader.Read() stays the same during the execution of the query.

    What I implemented with ValueTypeArrayNullability.PerInstance is really a uncommon behavior that changes the actual type that gets returned from NpgsqlDataReader.GetValue() on the fly depending on the actual content of the array.

    The fact that the exception goes away if you move parts of your code probably comes from Dapper caching the handler for whatever data it happens to see first.

    Basically this probably means that "ValueTypeArrayNullability=PerInstance" is not supported by Dapper and that you'd have to use "ValueTypeArrayNullability=Always" if you're using Dapper, but that shouldn't be much of a problem.
    I didn't investigate whether it's possible to disable the type handler cache in Dapper but this probably wouldn't be a good idea anyways.

  6. calexander3 commented on Dec 4, 2020

    @calexander3
  7. calexander3 commented on Dec 4, 2020

    @calexander3
  8. Brar commented on Dec 4, 2020

    @Brar
  9. calexander3 commented on Dec 4, 2020

    @calexander3
  10. ABildstein commented on Dec 5, 2020

    @ABildstein

    cool, thank you @Brar, that makes sense. I was planning on using the Always mode anyway since it makes way more sense but I just wanted to try everything out.

  11. added a commit that references this issue on Dec 9, 2020
    c9e1444
  12. calexander3 commented on Dec 9, 2020

    @calexander3
    Contributor

    Thanks @Brar and @roji !!

  13. added a commit that references this issue on Dec 10, 2020
    da8d794
  14. added theissue type on Jun 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions