Skip to content

Read and Write arrays of nullable value types - #1996

Merged
YohDeadfall merged 3 commits into
npgsql:devfrom
Brar:SupportNullableValueTypesInArrays
Oct 31, 2019
Merged

YohDeadfall merged 3 commits into
npgsql:devfrom
Brar:SupportNullableValueTypesInArrays

Conversation

@Brar

@Brar Brar commented Jun 14, 2018

Copy link
Copy Markdown
Member

After deciding that my extended testing project should not hold this one up forever, I'm finally submitting this one that fixes #443

I've explicitly broken backwards compatibility for NpgsqlDataReader.GetFieldValue<T>() where reading an array containing null values resulted in an array where the null values were replaced with the value types default value.

Another thing to note is that NpgsqlDataReader.GetValue() now returns an array of the value type or an array of its nullable counterpart on a row to row base, depending on the question whether the actual array returned by the backend contains null values or not.

@Brar
Brar force-pushed the SupportNullableValueTypesInArrays branch from 83b6224 to 8eb5eeb Compare June 14, 2018 06:59
@roji

roji commented Jun 14, 2018 •

Copy link
Copy Markdown
Member

Hey @Brar, thanks for the PR.

I'll give this a proper review, but right off the bat:

Another thing to note is that NpgsqlDataReader.GetValue() now returns an array of the value type or an array of its nullable counterpart on a row to row base, depending on the question whether the actual array returned by the backend contains null values or not.

If I understand this correctly, this seems problematic to me. I don't think that the type of the value returned should depend on its contents in this way: it shifts a lot of responsibility on the user and will make it very easy to write buggy code. In effect, it means that whenever a row is read, it's necessary to to check what type was returned. IIRC it would also be the only case where CLR types read change across rows.

Let's revisit our conversation on this. Here's how I see things

  • As a general rule, users are encouraged to use reader.GetFieldValue<T>()).
  • A user should be able to call reader.GetFieldValue<int?[]>(), yielding an array of nullables.
  • A user should also be able to call reader.GetFieldValue<int[]>(), yielding an array of ints. If there are any nulls in the database column, this should throw an exception. I think this makes sense because the user has clearly expressed their intent for a non-nullable array, so in effect they're asserting that there will not be any nulls.
  • The only open question in my mind is what reader.GetValue() returns. Here we have two options:
    • Return int[], silently returning zeros instead of nulls. The only advantage of this seems to be that it's the current behavior and therefore doesn't break backwards compat. However, as array use is somewhat rare I think we can afford to break backwards compat to do the right thing.
    • Return int[], throwing if nulls are present (just like GetFieldValue<int[]>()). The advantage of this is that it seems to correspond to the usual case of storing non-nullable int arrays in the database (unfounded intuition). The downside (as you mentioned earlier) is that GetValue() cannot be used to read some perfectly valid values.
    • Return int?[] (just like GetFieldValue<int?[]>()). The main downside is that it's a bit more complicated to access the more usual case of non-nullable ints (we have those extra nullables). But I think of the three possibilities, this is the right thing to do.

What do you think? @YohDeadfall you may be interested as well.

@Brar

Brar commented Jun 14, 2018 •

Copy link
Copy Markdown
Member Author

If I understand this correctly, this seems problematic to me. I don't think that the type of the value returned should depend on its contents in this way: it shifts a lot of responsibility on the user and will make it very easy to write buggy code. In effect, it means that whenever a row is read, it's necessary to to check what type was returned.

I certainly considered this when thinking about the new interface.

My arguments are the following:

Basically an API is about promises guaranteed by the framework.

  • If you (the user) want to make assumptions about the returned value: use GetFieldValue<T>() and we promise you to give you an object of the type you requested (as GetFieldValue<T>() guarantees) or back out with an exception if it isn't compatible.
  • If you (the user) don't want to make assumptions about the returned value (possibly because you don't know the exact table structure): use GetValue() and we promise you to give you an object (as GetValue() guarantees) that provides the best compatibility to the type returned by the backend. You can even use GetFieldType() to find out that it is an Array type and cast it safely to Array. Afterwards you can use the Array instance methods to find out more about the actual array and cast it safely once more without even having to fall back to reflection.
  • If you (the user) want to make assumptions about the returned value and want to use GetValue() you should be wary that the assumptions you are making when casting the returned object to something else are correct. After all, it's your data that contains the null values and the interface gives you everything you need to check if your assumptions are correct on a row to row base.

This also solves an important problem in our previous discussion:
In most cases, arrays will not contain null values.
Should all users of GetValue() have to pay the price of converting an Nullable<T>[] to T[] even if they know that their database will never have any null value inside an array?
I don't think so.

Finally:
I'm certainly willing to give this fact some documentation love.

@roji

roji commented Jun 14, 2018 •

Copy link
Copy Markdown
Member

I agree with the above, but returning a different type for different rows of the same database type seems to go too far.

In most cases, arrays will not contain null values.
Should all users of GetValue() have to pay the price of converting an Nullable[] to T[] even if they know that their database will never have any null value inside an array?
I don't think so.

It's true that we have this unverified intuition. However, I simply don't see the downside of returning T?[], i.e. the price you're mentioning. If the user knows their database will never have any null value, then they should call GetFieldValue<int?[]>() and not GetValue(). If we're in some sort of dynamic situation where we don't know the type in advance, then I think it's safe to say that we don't know whether it contains nulls or not.

Also, I very much agree with what you wrote above, that with GetValue() "we promise you to give you an object (as GetValue() guarantees) that provides the best compatibility to the type returned by the backend". If we follow that to the letter that means we need to return an array of nullables: that really is what is represented by PostgreSQL arrays. Note that we provide the best compatibility to the type returned by the backend, not to the value.

To summarize, I can see many more downsides to switching returned data types for different rows of the same resultset, than I can see for simply always returning int?[].

@Brar

Brar commented Jun 14, 2018

Copy link
Copy Markdown
Member Author

If we follow that to the letter that means we need to return an array of nullables: that really is what is represented by PostgreSQL arrays. Note that we provide the best compatibility to the type returned by the backend, not to the value.

To summarize, I can see many more downsides to switching returned data types for different rows of the same resultset, than I can see for simply always returning int?[].

I can agree with what you wrote @roji .

I'll modify the code accordingly.

@Brar
Brar force-pushed the SupportNullableValueTypesInArrays branch from a4989c3 to 3bec9ad Compare June 14, 2018 18:37
@Brar

Brar commented Jun 14, 2018

Copy link
Copy Markdown
Member Author

@roji the latest commit changes the implementation according to your comments above (I've squashed the others but left this one to make the changes transparent).

@Brar

Brar commented Jun 14, 2018

Copy link
Copy Markdown
Member Author

Wow!
The number of failed test demonstrably proves the fact that this is a breaking change!
Will fix them.

@roji

roji commented Jun 14, 2018

Copy link
Copy Markdown
Member

Thanks @Brar, drop me a line when you want this reviewed.

@Brar

Brar commented Jun 14, 2018

Copy link
Copy Markdown
Member Author

... but the fixes are quite easy.

@roji ready to review if you want.

@Brar

Brar commented Jun 15, 2018

Copy link
Copy Markdown
Member Author

BTW: I've verified that merging with #1993 currently works automatically so there's no need to worry about which one to apply first, but I'll certainly do a rebase once #1993 is applied.

@Brar

Brar commented Jun 15, 2018

Copy link
Copy Markdown
Member Author

One ugly part that we didn't talk about yet is the fact that ArrayHandler.ReadAsObject() is not only used by NpgsqlDataReader.GetValue() but also by NpgsqlCommand.ExecuteScalar() (see my fix for the failing range test) where the user doesn't have a way to ask for a specific type via generic method.
We might add a generic method to NpgsqlCommand to give people a way to get a non-nullable array that, but it would be non-standard for current ADO.NET.

@roji

roji commented Jun 15, 2018

Copy link
Copy Markdown
Member

One ugly part that we didn't talk about yet is the fact that ArrayHandler.ReadAsObject() is not only used by NpgsqlDataReader.GetValue() but also by NpgsqlCommand.ExecuteScalar() (see my fix for the failing range test) where the user doesn't have a way to ask for a specific type via generic method.

You're absolutely right. I think it makes it even more important to return a single, clear type and not alternate between int[] and int?[] based on whether there are nulls in the particular array.

We might add a generic method to NpgsqlCommand to give people a way to get a non-nullable array that, but it would be non-standard for current ADO.NET.

Good idea. I opened https://github.com/dotnet/corefx/issues/30426 for this, but we can also implement it as an Npgsql-specific feature in the meantime. Feel free to submit a PR on this if you want.

@Brar

Brar commented Jun 15, 2018

Copy link
Copy Markdown
Member Author

@roji after working around all the issues I mentioned at https://github.com/dotnet/corefx/issues/30426 the code would look like this:

public bool TryExecuteScalar<T>(out T result)
{
    var (hasResult, res) = TryExecuteScalar<T>(false, CancellationToken.None).GetAwaiter().GetResult();
    result = res;
    return hasResult;
}


[MethodImpl(MethodImplOptions.AggressiveInlining)]
[ItemCanBeNull]
async ValueTask<(bool hasResult, T result)> TryExecuteScalar<T>(bool async, CancellationToken cancellationToken)
{
    var behavior = CommandBehavior.SingleRow;
    if (!Parameters.HasOutputParameters)
        behavior |= CommandBehavior.SequentialAccess;
    using (var reader = await ExecuteDbDataReader(behavior, async, cancellationToken))
    {
        return reader.Read() && reader.FieldCount != 0 ? (true, reader.GetFieldValue<T>(0)) : (false, default);
    }
}

To be honest this doesn't look like an API to me.

@Brar

Brar commented Jun 19, 2018

Copy link
Copy Markdown
Member Author

@roji I'm uncertain If you recognized the following a few days ago:

@roji ready to review if you want.

@roji

roji commented Jun 19, 2018

Copy link
Copy Markdown
Member

I'll try to get around to this as soon as I can, although I have some very intensive non-Npgsql days coming up. I'll definitely get there eventually!

@Brar
Brar force-pushed the SupportNullableValueTypesInArrays branch from d579cdc to 05aefc1 Compare June 29, 2018 23:35
@Brar
Brar force-pushed the SupportNullableValueTypesInArrays branch from 05aefc1 to a7d33c0 Compare July 15, 2018 04:13
@Brar

Brar commented Jul 15, 2018

Copy link
Copy Markdown
Member Author

Rebased to avoid code drift.
AppVeyor failure is not related to this PR (some sort of dependency issues with GeoAPI.CoordinateSystems).

@YohDeadfall

Copy link
Copy Markdown
Contributor

@Brar The AppVeyor issue was fixed by #2059.

@roji
roji force-pushed the dev branch 2 times, most recently from fe46200 to 1f156c8 Compare July 20, 2018 12:57
@Brar
Brar force-pushed the SupportNullableValueTypesInArrays branch from a7d33c0 to af4f219 Compare July 21, 2018 09:05
@Brar Brar mentioned this pull request Feb 8, 2019
@Brar
Brar force-pushed the SupportNullableValueTypesInArrays branch from af4f219 to adea324 Compare February 11, 2019 08:00
@Brar

Brar commented Oct 29, 2019

Copy link
Copy Markdown
Member Author

After a lot of discussions, reviews and rewriting I now consider this ready for a serious final review.
I've left two commits to reflect the last evolution of the PR.
The first commit reflects my initial work on this, which implemented the full set of functionality.
The second commit reflects the changes @roji and I did in a joint pair programming effort plus some minor changes from me where we left over some side issues.

As @roji already knows most of this, I explicitly request a review from @austindrenski and @YohDeadfall in order to get another couple of eyes to look at it and probably give some completely new feedback.

Below you can find another two benchmark runs.
The first one is without the changes from this PR, the second one is with the changes from this PR.

Click to see the benchmark results

Interpretation hints:

We have four methods

  1. [BeforePR_]ReadIntArray which calls NpgsqlDataReader.GetFieldValue<int[]>() before and after the PR
  2. [BeforePR_]ReadNullableIntArray which calls NpgsqlDataReader.GetFieldValue<int[]>() before, and NpgsqlDataReader.GetFieldValue<int?[]>() after the PR.
  3. [BeforePR_]ReadStringArray which calls NpgsqlDataReader.GetFieldValue<string[]>() before and after the PR

When AllNulls is false the array contains only actual int values otherwise it only contains null values, except for ReadIntArray where the array never contains any null values (AllNulls is ignored).
NumElements is the number of elements in the array.

BenchmarkDotNet=v0.11.5, OS=Windows 10.0.18362
AMD Ryzen 5 2600X, 1 CPU, 12 logical and 6 physical cores
.NET Core SDK=3.0.100
  [Host]     : .NET Core 3.0.0 (CoreCLR 4.700.19.46205, CoreFX 4.700.19.46214), 64bit RyuJIT
  DefaultJob : .NET Core 3.0.0 (CoreCLR 4.700.19.46205, CoreFX 4.700.19.46214), 64bit RyuJIT
Method AllNulls NumElements Mean Error StdDev
BeforePR_ReadIntArray False 1 410.6 ns 0.9145 ns 0.8107 ns
BeforePR_ReadNullableIntArray False 1 410.2 ns 3.2328 ns 3.0240 ns
BeforePR_ReadStringArray False 1 561.1 ns 2.9994 ns 2.8057 ns
BeforePR_ReadIntArray False 10 1,367.0 ns 3.8014 ns 3.5558 ns
BeforePR_ReadNullableIntArray False 10 1,400.3 ns 5.9320 ns 5.5488 ns
BeforePR_ReadStringArray False 10 2,084.8 ns 4.0968 ns 3.8322 ns
BeforePR_ReadIntArray False 1000 101,709.1 ns 133.8482 ns 118.6530 ns
BeforePR_ReadNullableIntArray False 1000 101,319.7 ns 78.1266 ns 65.2392 ns
BeforePR_ReadStringArray False 1000 167,909.3 ns 778.4015 ns 690.0327 ns
BeforePR_ReadIntArray False 100000 10,403,245.7 ns 48,560.5826 ns 45,423.5991 ns
BeforePR_ReadNullableIntArray False 100000 10,451,426.3 ns 80,794.1426 ns 71,621.9030 ns
BeforePR_ReadStringArray False 100000 27,716,898.3 ns 73,197.6963 ns 68,469.1705 ns
BeforePR_ReadIntArray True 1 430.2 ns 10.0778 ns 14.1277 ns
BeforePR_ReadNullableIntArray True 1 351.6 ns 7.0207 ns 6.8952 ns
BeforePR_ReadStringArray True 1 446.2 ns 5.9172 ns 5.5350 ns
BeforePR_ReadIntArray True 10 1,425.1 ns 16.9358 ns 15.0132 ns
BeforePR_ReadNullableIntArray True 10 809.9 ns 12.6105 ns 11.7958 ns
BeforePR_ReadStringArray True 10 1,181.2 ns 8.6565 ns 8.0973 ns
BeforePR_ReadIntArray True 1000 102,055.6 ns 153.8075 ns 143.8716 ns
BeforePR_ReadNullableIntArray True 1000 47,903.4 ns 180.8129 ns 169.1325 ns
BeforePR_ReadStringArray True 1000 79,895.0 ns 66.0380 ns 58.5410 ns
BeforePR_ReadIntArray True 100000 10,419,988.3 ns 134,581.9563 ns 125,888.0455 ns
BeforePR_ReadNullableIntArray True 100000 4,867,496.4 ns 15,627.9646 ns 14,618.4078 ns
BeforePR_ReadStringArray True 100000 8,151,878.0 ns 17,476.1494 ns 16,347.2010 ns
Method AllNulls NumElements Mean Error StdDev
ReadIntArray False 1 358.9 ns 1.1590 ns 1.0842 ns
ReadNullableIntArray False 1 438.2 ns 1.5376 ns 1.4382 ns
ReadStringArray False 1 484.3 ns 0.8036 ns 0.7517 ns
ReadIntArray False 10 1,284.3 ns 1.4725 ns 1.2296 ns
ReadNullableIntArray False 10 2,043.4 ns 8.0207 ns 7.5026 ns
ReadStringArray False 10 2,268.8 ns 5.2173 ns 4.8803 ns
ReadIntArray False 1000 103,898.2 ns 492.2491 ns 460.4501 ns
ReadNullableIntArray False 1000 176,518.5 ns 838.7399 ns 743.5211 ns
ReadStringArray False 1000 199,062.7 ns 532.9325 ns 498.5054 ns
ReadIntArray False 100000 10,512,378.0 ns 29,216.6596 ns 22,810.4460 ns
ReadNullableIntArray False 100000 17,722,589.4 ns 50,355.3856 ns 47,102.4589 ns
ReadStringArray False 100000 29,388,754.4 ns 147,610.4754 ns 138,074.9302 ns
ReadIntArray True 1 356.7 ns 0.8660 ns 0.7232 ns
ReadNullableIntArray True 1 303.6 ns 1.2909 ns 1.1444 ns
ReadStringArray True 1 350.3 ns 0.6431 ns 0.5701 ns
ReadIntArray True 10 1,299.8 ns 3.5177 ns 3.2905 ns
ReadNullableIntArray True 10 934.6 ns 2.5992 ns 2.4313 ns
ReadStringArray True 10 1,135.1 ns 2.2193 ns 2.0759 ns
ReadIntArray True 1000 108,434.3 ns 80.1156 ns 66.9002 ns
ReadNullableIntArray True 1000 71,092.4 ns 788.4061 ns 698.9014 ns
ReadStringArray True 1000 87,305.6 ns 174.1468 ns 154.3766 ns
ReadIntArray True 100000 10,516,978.6 ns 58,233.5149 ns 54,471.6660 ns
ReadNullableIntArray True 100000 7,027,959.4 ns 10,050.7037 ns 8,392.7928 ns
ReadStringArray True 100000 8,958,207.8 ns 16,675.6081 ns 15,598.3742 ns

@YohDeadfall YohDeadfall left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you, Brar!

Comment thread src/Npgsql/TypeHandlers/ArrayHandler.cs Resolved
Comment thread src/Npgsql/TypeHandlers/ArrayHandler.cs Resolved
Comment thread src/Npgsql/TypeHandlers/ArrayHandler.cs Resolved
Comment thread src/Npgsql/TypeHandlers/ArrayHandler.cs Resolved
Comment thread src/Npgsql/TypeHandlers/ArrayHandler.cs Resolved
Comment thread src/Npgsql/TypeHandlers/ArrayHandler.cs Resolved
@Brar
Brar force-pushed the SupportNullableValueTypesInArrays branch from 8474354 to 26d05d8 Compare October 30, 2019 19:21
@Brar

Brar commented Oct 30, 2019

Copy link
Copy Markdown
Member Author

Thank you for the review @YohDeadfall.
I've addressed your feedback where it was possible but there are two unresolved comments left where I think that it's not possible to do what you suggested.
Can you please look at those once again?

Comment thread src/Npgsql/TypeHandlers/ArrayHandler.cs Resolved
Comment thread src/Npgsql/TypeHandlers/ArrayHandler.cs Resolved
Comment thread src/Npgsql/TypeHandlers/ArrayHandler.cs Resolved
Comment thread src/Npgsql/TypeHandlers/ArrayHandler.cs Resolved
@Brar
Brar force-pushed the SupportNullableValueTypesInArrays branch from 38b06e5 to 43919c0 Compare October 30, 2019 21:13
Brar added 2 commits October 31, 2019 15:23
* Use compiled expression trees to avoid boxing
* Also move code to the non-generic base class 'ArrayHandler'
@Brar
Brar force-pushed the SupportNullableValueTypesInArrays branch from 43919c0 to 847ab11 Compare October 31, 2019 15:14
@Brar
Brar force-pushed the SupportNullableValueTypesInArrays branch from 847ab11 to ea0a5a2 Compare October 31, 2019 15:37
@Brar

Brar commented Oct 31, 2019

Copy link
Copy Markdown
Member Author

Thank you @YohDeadfall

@austindrenski and @roji, @YohDeadfall and I have completed the review process. Now it's on you.

@YohDeadfall
YohDeadfall merged commit c95b6ec into npgsql:dev Oct 31, 2019
@roji

roji commented Oct 31, 2019

Copy link
Copy Markdown
Member

Great work @Brar, and thanks @YohDeadfall for the deep review and helpful comments. Very happy this is finally merged :)

@Brar
Brar deleted the SupportNullableValueTypesInArrays branch November 2, 2019 08:34
@lexi-sh

lexi-sh commented Nov 2, 2019

Copy link
Copy Markdown

Hi npgsql team!

Would you be able to kick off a build of the 5.0.0 unstable branch that includes this merge now that it's merged? Would love to try it out.

Thanks!

@roji

roji commented Nov 3, 2019

Copy link
Copy Markdown
Member

Hmm, looks like our appveyor build has some issue and doesn't upload unstable packages anymore... Rather than spending time to debug this, hopefully we'll merge #2717 soon (switch to Github Actions). @christophertrml for now you can clone and build Npgsql (shouldn't be hard).

@Brar

Brar commented Nov 3, 2019

Copy link
Copy Markdown
Member Author

Hmm, looks like our appveyor build has some issue and doesn't upload unstable packages anymore...

I couldn't resist investigating this...

See #2722

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support for nullable arrays

4 participants