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
Add a connection string parameter to return nullable arrays by default #3386
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.
Reacted by ABildstein, Craig Alexander, Brar Piening, Adam Kamor, Jan-Erik Strøm, John Paul R and Douglas Klaus
@calexander3 and @JBildstein,
can you try this PR and tell me if adding "ValueTypeArrayNullability=Always" or "ValueTypeArrayNullability=PerInstance" solves your issue?
thank you @Brar, it works for me for the most part, here's the code I used:
Click to expand!
usingSystem;usingSystem.Data;usingSystem.Linq;usingSystem.Threading.Tasks;usingDapper;usingNpgsql;namespaceTest{classProgram{staticasyncTaskMain(string[]args){conststringconnString="Server=127.0.0.1;Port=5432;User Id=postgres;";using(varconnection=SetupForAlways(connString)){Console.WriteLine("Always Nullable:");awaitRun(connection);}using(varconnection=SetupForPerInstance(connString)){Console.WriteLine("PerInstance Nullable:");awaitRun(connection);}}staticNpgsqlConnectionSetupForAlways(stringconnString){connString+="ValueTypeArrayNullability=Always;";varconnection=newNpgsqlConnection(connString);SqlMapper.ResetTypeHandlers();SqlMapper.AddTypeHandler(typeof(int[]),newToNonNullableMap<int>());returnconnection;}staticNpgsqlConnectionSetupForPerInstance(stringconnString){connString+="ValueTypeArrayNullability=PerInstance;";varconnection=newNpgsqlConnection(connString);SqlMapper.ResetTypeHandlers();SqlMapper.AddTypeHandler(typeof(int[]),newToNonNullableMap<int>());SqlMapper.AddTypeHandler(typeof(int?[]),newToNullableMap<int>());returnconnection;}staticasyncTaskRun(NpgsqlConnectionconnection){conststringsql=@"SELECT * FROM (VALUES ('{1, NULL}'::INTEGER[], '{2, NULL}'::INTEGER[]), ('{3, 4}'::INTEGER[], '{5, 6}'::INTEGER[]) ) as foo(NonNullArray, NullArray)";varresult=awaitconnection.QueryAsync<Model>(sql);foreach(variteminresult){Console.Write("{ ");Console.Write(string.Join(", ",item.NonNullArray));Console.Write(" }, { ");Console.Write(string.Join(", ",item.NullArray.Select(t =>t?.ToString()??"NULL")));Console.WriteLine(" }");}}classModel{publicint[]NonNullArray{get;set;}publicint?[]NullArray{get;set;}}// with ValueTypeArrayNullability=Always, mapping the nullable array to non-nullable// with ValueTypeArrayNullability=PerInstance, mapping to non-nullable as necessaryclassToNonNullableMap<T>:SqlMapper.ITypeHandlerwhereT:struct{publicobjectParse(TypedestinationType,objectvalue){if(valueis not Nullable<T>[]array){returnvalue;}returnArray.ConvertAll(array, t =>t??default);}publicvoidSetValue(IDbDataParameterparameter,objectvalue){parameter.Value=value;}}// with ValueTypeArrayNullability=PerInstance, mapping to nullable as necessaryclassToNullableMap<T>:SqlMapper.ITypeHandlerwhereT:struct{publicobjectParse(TypedestinationType,objectvalue){if(valueis not T[]array){returnvalue;}returnArray.ConvertAll<T,T?>(array, t =>t);}publicvoidSetValue(IDbDataParameterparameter,objectvalue){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.
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.
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.
Activity
ABildstein commentedon Dec 2, 2020
For posterity: I'm hitting the issue with Dapper
Details in my original comment: #443 (comment)
Brar commentedon Dec 4, 2020
@calexander3 and @JBildstein,
can you try this PR and tell me if adding "ValueTypeArrayNullability=Always" or "ValueTypeArrayNullability=PerInstance" solves your issue?
Please look at
npgsql/test/Npgsql.Tests/Types/ArrayTests.cs
Line 145 in be834c5
ABildstein commentedon Dec 4, 2020
thank you @Brar, it works for me for the most part, here's the code I used:
Click to expand!
About the "for the most part": The code as I posted it fails with the second query with the following:
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.
Brar commentedon Dec 4, 2020
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 callingNpgsqlDataReader.Read()stays the same during the execution of the query.What I implemented with
ValueTypeArrayNullability.PerInstanceis really a uncommon behavior that changes the actual type that gets returned fromNpgsqlDataReader.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.
calexander3 commentedon Dec 4, 2020
calexander3 commentedon Dec 4, 2020
Brar commentedon Dec 4, 2020
calexander3 commentedon Dec 4, 2020
ABildstein commentedon Dec 5, 2020
cool, thank you @Brar, that makes sense. I was planning on using the
Alwaysmode anyway since it makes way more sense but I just wanted to try everything out.Add a connection string parameter to return nullable arrays by default
calexander3 commentedon Dec 9, 2020
Thanks @Brar and @roji !!
Add a connection string parameter to return nullable arrays by default