Skip to content

Numeric value does not fit in a System.Decimal (value less than decimal.MaxValue) #3627

Closed as duplicate

Description

@SomeSpy

I first looked at posts with a similar issues, for example

npgsql/efcore.pg#438
#3238
#448

and didn't find a solution to my issue

Introductory information

There are many type fields in our database: numeric (56,28) and numeric (55,19), everything worked fine in Npgsql 3.7
But when we updated the Npgsql version to 4.0/4.1/5 then some!!! fields have ceased to be correctly retrieved from the database
below is an example of such a value

Steps to reproduce

for example:

  1. database field: numeric (55,19)
  2. save the value in the field: 99999999999
  3. if we make a select from this field, we get: 99999999999.0000000000000000000

simple code for reproduce:

using (var dbConn = new NpgsqlConnection("..."))
{
	dbConn.Open();
	var cmd = new NpgsqlCommand("select 99999999999.0000000000000000000::numeric", dbConn);
	var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
	reader.Read();
	reader.GetValue(0);
}

The issue

We get an exception in any Npgsql above version 3.7
In Npgsql version 3.7 everything works fine

Exception message: System.OverflowException: 'Numeric value does not fit in a System.Decimal'
Stack trace:
Stack trace: 
This exception was originally thrown at this call stack:
    Npgsql.Internal.TypeHandlers.NumericHandlers.DecimalRaw.Multiply(ref Npgsql.Internal.TypeHandlers.NumericHandlers.DecimalRaw, uint) in DecimalRaw.cs
    Npgsql.Internal.TypeHandlers.NumericHandlers.NumericHandler.Read(Npgsql.Internal.NpgsqlReadBuffer, int, Npgsql.BackendMessages.FieldDescription) in NumericHandler.cs
    Npgsql.Internal.TypeHandling.NpgsqlSimpleTypeHandler<TDefault>.Read<TAny>(Npgsql.Internal.NpgsqlReadBuffer, int, Npgsql.BackendMessages.FieldDescription) in NpgsqlSimpleTypeHandler.cs
    Npgsql.Internal.TypeHandling.NpgsqlSimpleTypeHandler<TDefault>.Read<TAny>(Npgsql.Internal.NpgsqlReadBuffer, int, bool, Npgsql.BackendMessages.FieldDescription) in NpgsqlSimpleTypeHandler.cs
    [External Code]
    Npgsql.Internal.TypeHandling.NpgsqlTypeHandler<TDefault>.ReadAsObject(Npgsql.Internal.NpgsqlReadBuffer, int, bool, Npgsql.BackendMessages.FieldDescription) in NpgsqlTypeHandler`.cs
    [External Code]
    Npgsql.NpgsqlDataReader.GetValue(int) in NpgsqlDataReader.cs
    ConsoleApp1.Program.Main(string[]) in Program.cs

Further technical details

Npgsql version: Npgsql 4.0/4.1/5.0
PostgreSQL version: PostgreSQL 10.8
Operating system: Windows 10

https://github.com/npgsql/npgsql/blob/v4.1.4/src/Npgsql/TypeHandlers/NumericHandlers/DecimalRaw.cs
Screenshot with error:
error

Activity

  1. roji commented on Apr 3, 2021

    @roji
    Member

    The value 99999999999.0000000000000000000 has 30 digits, but the .NET decimal type only supports up to 29 digits, so Npgsql cannot read that value correctly (IIRC previous versions of Npgsql sometimes returned values, but which could be wrong in some values).

    You can retrieve the values as strings (either by adding a conversion in the SQL, or by telling Npgsql to fetch it as an unknown type). But if you really want to work with these values in .NET, you may consider cleaning up the data so it's compatible with .NET decimal

    /cc @YohDeadfall to make sure I understood this right. I think we also had a SQL fragment to automatically truncate decimal values in the database, do you remember where that is?

  2. YohDeadfall commented on Apr 3, 2021

    @YohDeadfall
    Contributor

    @roji, it's in the first issue mentioned by the OP: npgsql/efcore.pg#438 (comment)

  3. roji commented on Apr 3, 2021

    @roji
    Member

    Thanks @YohDeadfall!

  4. roji commented on Apr 3, 2021

    @roji
    Member

    Duplicate of #448

  5. SomeSpy commented on Apr 5, 2021

    @SomeSpy
    Author

    @roji, ok, but another example

    using (var dbConn = new NpgsqlConnection("..."))
    {
    dbConn.Open();
    var cmd = new NpgsqlCommand("CREATE TABLE tport_main.test_table (col1 numeric(56,28) NULL);", dbConn); // for numeric(55,19) the same
    cmd.ExecuteNonQuery();
    cmd = new NpgsqlCommand("INSERT INTO tport_main.test_table (col1) VALUES (99999999999);", dbConn);
    cmd.ExecuteNonQuery();
    cmd = new NpgsqlCommand("SELECT col1 FROM tport_main.test_table;", dbConn);
    var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
    reader.Read();
    var value = reader.GetValue(0);
    }

    and I have the same issue.
    So, I can put 99999999999 in the table but can never get it back?
    Is this the expected behavior?

    Thus, if we have a number field in the table, then there is always the possibility that some user will put a correct decimal value that will be successfully saved to the database but will never be received back and the application will be crashed?

    It seems to me that the behavior when we can save but cannot read is wrong behavior

    I see 2 options here:
    1.we do not allow putting the value in the field that we cannot then get back
    2.we should be able to trim fractional values (it is possible to do this optionally) but so that the application does not crash when trying to read a previously saved value

  6. YohDeadfall commented on Apr 5, 2021

    @YohDeadfall
    Contributor

    @SomeSpy, the driver is not responsible for trimming just for one simple reason - it might hurt users wanted to keep precision and for which it matters. If you are personally okay with auto trimming, you can copy the numeric handler to your code and tweak it in a way to round or skip fractional digits which cause an overflow. Then just register it globally in the app startup be happy.

    Otherwise, vote for #448 and perhaps Shay will be okay once day with a type giving an ability to read such values and handle data in user code. I voted for it, but I don't participate in development anymore, so can't help by any means except answering questions or guiding on direct mentions.

  7. roji commented on Apr 5, 2021

    @roji
    Member

    @SomeSpy to add to what @YohDeadfall wrote, note that in your sample you're writing the value as a string, a literal in your SQL (it's never a decimal in .NET), but trying to read it as a decimal; if you try to write it as a decimal you'll encounter the same problems. On the other hand you already have options for reading it as a string as well - as I wrote above.

    We'll continue the discussion on an NpgsqlNumeric type in #448.

  8. YohDeadfall commented on Apr 5, 2021

    @YohDeadfall
    Contributor

    @SomeSpy, you have to change the following method:

    public override decimal Read(NpgsqlReadBuffer buf, int len, FieldDescription? fieldDescription = null)
    {
    var result = new DecimalRaw();
    var groups = buf.ReadInt16();
    var weight = buf.ReadInt16() - groups + 1;
    var sign = buf.ReadUInt16();
    if (sign == SignNan)
    throw new InvalidCastException("Numeric NaN not supported by System.Decimal");
    if (sign == SignNegative)
    DecimalRaw.Negate(ref result);
    var scale = buf.ReadInt16();
    if (scale < 0 is var exponential && exponential)
    scale = (short)(-scale);
    else
    result.Scale = scale;
    if (scale > MaxDecimalScale)
    throw new OverflowException("Numeric value does not fit in a System.Decimal");
    var scaleDifference = exponential
    ? weight * MaxGroupScale
    : weight * MaxGroupScale + scale;
    if (groups == MaxGroupCount)
    {
    while (groups-- > 1)
    {
    DecimalRaw.Multiply(ref result, MaxGroupSize);
    DecimalRaw.Add(ref result, buf.ReadUInt16());
    }
    var group = buf.ReadUInt16();
    var groupSize = DecimalRaw.Powers10[-scaleDifference];
    if (group % groupSize != 0)
    throw new OverflowException("Numeric value does not fit in a System.Decimal");
    DecimalRaw.Multiply(ref result, MaxGroupSize / groupSize);
    DecimalRaw.Add(ref result, group / groupSize);
    }
    else
    {
    while (groups-- > 0)
    {
    DecimalRaw.Multiply(ref result, MaxGroupSize);
    DecimalRaw.Add(ref result, buf.ReadUInt16());
    }
    if (scaleDifference < 0)
    DecimalRaw.Divide(ref result, DecimalRaw.Powers10[-scaleDifference]);
    else
    while (scaleDifference > 0)
    {
    var scaleChunk = Math.Min(DecimalRaw.MaxUInt32Scale, scaleDifference);
    DecimalRaw.Multiply(ref result, DecimalRaw.Powers10[scaleChunk]);
    scaleDifference -= scaleChunk;
    }
    }
    return result.Value;
    }

    As you can see it throws on an overflow, but should not in your case. Therefore, tweak the logic in a such way that reading fractional part after reaching the maximum capacity of decimal will just take the first overflowing group, check that the digit at the overflowing position is less or equal to 5 and add 1 to the result in that case. Otherwise, do nothing. Read left groups till the end, but discard values.

    You should find in other threads how PostgreSQL stores and handles numerics, but to be short, they are stored in groups of 4 decimal digits. Each group is multiplied by 10^(4 * g) where g is the number of groups minus the current group index. So 1234567 can be represented as 0123 and 4567. The scale complicates the logic a bit, but no so much.

  9. alex-kulakov commented on Nov 7, 2024

    @alex-kulakov

    @roji, I apologize, but I thought that the main job of the project is giving access to data, with correct ranges for at least all basic types that PostgreSQL provides for data. Am I wrong?

    There are many types that of greater or smaller range then .NET counterparts, it is OK, database types are primary here. It's the job of provider library to support reading full range of RDBSM types, because the provider is closest layer of abstraction. For instance, MS SQL Server client library provides special types for Decimals, your library provides types which are capable of reading full range of PostgreSQL types as well, e.g. intervals. This is the right way of doing things, and I fully support it. In such cases, the user is able to decide how to map wider range of RDBMS' type into .NET counterpart. I wouldn't say nothing if I had such opportunity for decimals because I already do this for MS SQL Server decimal type. BUT I haven't, and author of the issue neither have it.

    You, on the other hand, decided (and I believe planned) to cut off feature of value range reduction but not planned and implemented anything that would allow people to perform reduction by their own. That should be done it advance to not break thousands or hundreds of thousands of projects. Nothing prevented you from creating, for example, a facade type, a struct similar to NpgsqlInterval with some API to get different parts of the value, to make conversions to and from .NET decimal, and maybe to get info about precision and scale (which are useful in case of scale reduction). Such type would cover all the needs of users, and after that you would have right to say "we switched to another approach to data reading - we don't make any assumptions and conversions but let the user resolve conversion uncertainty". This would be cook.

    Another thing that bothers me in your answer is that cases like in the post can be handled easily if there is an access to raw data and ability to calculate fractional part. If it is full of zeros you can omit many of them without affecting result value. We have 11th grades in school, and this rule is taught in the 5th one. Basic mathematics. It's a shame to not know this. I believe in choice between "exception because of "too many zeros in zero fractional part" option and "reduction of useless zeros" option, the majority of users who knows math basics would choose to get rid of non-meaningful zeros but have value. If there is an access to fractional part you can probably try to convert it to .NET decimal and compare with 0m if it is true, then you can even return only the floor. In case of 99999999999.0000000000000000001 you can say that it is a reduction of data, you're right. But even in this case there are ways to give the user an option of having old behavior, for example have a version of method like

    public decimal GetDecimal(int index, bool reduceFractionsIfNeeded = false)
    {
       if (TryReadAsIs(index, out var result))
         return result;
       else {
          if (!reduceFractionsIfNeeded) {
             throw new InvalidOperationException("Doesn't fit");
          }
          if (TryReadReduced(index, out var reducedResult)) {
            return reducedResult;
          }
       }
       throw new InvalidOperationException("Doesn't fit");
    }

    I believe you wanted user to decide what to do, and by having this extra parameter you would receive permission. But type with full range of decimals would be better because it would give more choices.

    Instead of having proper basic functionality (which you don't have as we can see), your project was busy changing type names (we care more about backwards compatibility than names, everybody got used to them, many of us use var and don't see them, fixing broken behavior, though, costs money; this is why many of us hate useless renames for the sake of rename) and implementing fancy stuff like support for NodaTime which in certain cases provides even smaller range of values than .NET types, for example interval. Words from NpgsqlDataReader.GetInterval summary "while .NET's TimeSpan has a resolution of 100 nanoseconds and ranges from roughly -29247 to 29247 years." and from obsolete attribute "For values outside the range of TimeSpan, consider using NodaTime (range -9998 to 9999)" may lead to conclusion that your project tells and encourages people to have even more reduced range of data. This is bad. And after all you tell "use conversion to strings" (which probably decreases performance) to sweep under the rug results of your irresponsibility.

    The cruelty is in the fact that you can read the whole range of values internally (DecimalRaw type existence gives us a hint) but instead of returning the value to us in some form you forcefully cut it to .NET value when having a basic wrapper type for DecimalRaw instance would be enough and it would be secure enough.

    I want also to point that I understand bugs, mistakes, people do things wrong sometimes because of lack of knowledge, not seeing whole picture, lack of experience, etc., that's OK, but only if they admit that it was a mistake and try to fix it later, but this seems to be thoughtful decision, because it introduced in v4.x.x, it wasn't addressed in v5.x.x, and it wasn't addressed in v6.x.x; two versions along no one cared (I don't have time to experiment further though versions because of lack of backwards compatibility in your project). Apparently, either no one in the team thought about it or some people in the team raised this problem but dictatorship of the main developer didn't let proper support happen. Anyway, this is pity.

  10. roji commented on Nov 7, 2024

    @roji
    Member

    @alex-kulakov that's quite a lot of text, with several different arguments. I'll answer as best as I can:

    First, while I agree that ideally the database driver should strive to allow users to access all data types and all possible values. I do not believe it is the job of the driver to implement, expose and maintain arbitrary data types when these are missing. This has been discussed many times in the past (e.g. see #448), but I'll still repeat some of the arguments below.

    I'll also note that your tone is quite disrespectful in many places, and you show a lack of basic knowledge on some of the subjects about which you write quite confidently and aggressively. I've already pointed out your problematic tone (#4469 (comment)), but you seem to be intent on continuing to express yourself this way. For now, I'll answer your comments nevertheless, but if you continue to be disrespectful at some point we'll probably stop responding.

    You, on the other hand, decided (and I believe planned) to cut off feature of value range reduction but not planned and implemented anything that would allow people to perform reduction by their own.

    This simply isn't true: users can easily truncate or decimals in SQL, using functions such as trunc() and round(). Not everything has to happen at the driver API level: one can use the PG support instead.

    Nothing prevented you from creating, for example, a facade type, a struct similar to NpgsqlInterval with some API to get different parts of the value, to make conversions to and from .NET decimal, and maybe to get info about precision and scale (which are useful in case of scale reduction). Such type would cover all the needs of users, and after that you would have right to say "we switched to another approach to data reading - we don't make any assumptions and conversions but let the user resolve conversion uncertainty".

    Here you're missing a fundamental difference between PG interval and numeric, namely that the on-wire encoding for the former is simply three numbers - each of which makes sense (months, days, time-of-day) - whereas the binary encoding for the latter is an internal format that is simply unusable without parsing/decoding. In other words, while I can imagine some user actually making use of NpgsqlInterval in a productive way, if we were to expose a bare NpgsqlDecimal which simply exposes the on-wire encoding, that type would be largely useless to users. Having said that, if you want access to the raw bytes, you can always e.g. call NpgsqlDataReader.GetStream() (again, I don't think anyone should actually do that).

    But of course, you're not asking for access to the raw on-wire encoding - which is what NpgsqlInterval is - what you want is for us to develop a full-blown NpgsqlDecimal type which actually decodes and exposes the number. But of course, what does that actually mean, what APIs would such a type expose? A number type is of course useless unless you can do stuff with it, like arithmetic; and at that point, you're asking us to develop and maintain a full math library for arbitrary-length numbers, which simply is not a thing that makes sense for a database driver to do. Or if what you're looking for is to simply display the number to the user, just convert it to a string in SQL and load that.

    So it's very easy to come to this repo and say "add support for this type", without fully thinking about what that actually means, and what operations one actually wants to do with the numeric data loaded from the database. At the end of the day, PostgreSQL already allows you to do anything you want with all decimal values - arithmetic, string conversion; make use of that, rather than expecting for the driver to reimplement all of that rich functionality.

    It's a shame to not know this.

    I'd recommend being a bit more polite when writing maintainers of open source projects, and not implying that they don't know basic math. As was previously discussed, the decision to not truncate was a conscious decision.

    Instead of having proper basic functionality (which you don't have as we can see), your project was busy changing type names (we care more about backwards compatibility than names, everybody got used to them, many of us use var and don't see them, fixing broken behavior, though, costs money; this is why many of us hate useless renames for the sake of rename) and implementing fancy stuff like support for NodaTime which in certain cases provides even smaller range of values than .NET types, for example interval.

    I'm not sure exactly what renames you're referring to; but here you simply seem to be questioning our decision-making and priorities. You may consider NodaTime fancy or useless, but that isn't the case for many of our other users; you have your own very narrow vision of what's useful for you, while we successfully maintain Npgsql for a great number of users. So I'd suggest just a bit of respect and confidence in our decision-making (though I do welcome respectful conversations on what should be prioritized).

    Words from NpgsqlDataReader.GetInterval summary "while .NET's TimeSpan has a resolution of 100 nanoseconds and ranges from roughly -29247 to 29247 years." and from obsolete attribute "For values outside the range of TimeSpan, consider using NodaTime (range -9998 to 9999)" may lead to conclusion that your project tells and encourages people to have even more reduced range of data. This is bad.

    Here you've simply missed a very important point, namely that TimeSpan is a fundamental mismatch for PG's interval type: interval is an undefined, human-centric span of time, e.g. 2 months and a week: this by itself has no absolute duration (months can be shorter or longer), and only becomes an such an absolute duration when coupled with a timestamp (e.g. 2 months and a week starting from this point in time). TimeSpan, in comparison, is absolute duration, which is why it also cannot have the concept of months or years. NodaTime's Period, in contrast, is exactly the same concept as PG's interval, and is therefore the perfect match for mapping it.

    So I'd suggest reading up and making yourself familiar before making sweeping, decisive statements.

    And after all you tell "use conversion to strings" (which probably decreases performance) to sweep under the rug results of your irresponsibility.

    That makes no sense; if what the user wants is a textual representation of the numeric value, then it doesn't matter if that conversion happens in PostgreSQL or in the driver - both will have equivalent performance.

    Apparently, either no one in the team thought about it or some people in the team raised this problem but dictatorship of the main developer didn't let proper support happen.

    There's another option - maybe other people in the team also agree with this intentional decision. In any case, going to an open source repo and accusing a maintainer of being a dictator really won't get you anywhere.

  11. alex-kulakov commented on Dec 9, 2024

    @alex-kulakov

    I don't respect developers just by their title of MS/Google/Tesla/etc. developer. I respect them for their actual decisions. If you don't think the same, it's a pity.

    We are talking about the fact that your team reduced ways of reading values to one exact way - only your way, despite the fact that it provides truncated compatibility with RDBMS' type and there are more flexible options for the community. How would you name such behavior when opinion of one or few is the only true way of doing things? I will leave this question for you to answer to yourself. The fact that there are many ways to make it beneficial for many parties, you can't disagree on this.

    I even provided you the way which is already known and which would not have taken much time to implement, probably you didn't think of it or rejected (which is weird because MS itself does it and it is completely fine) - having a wrapper type for raw data of storage decimal + at least scale as property (it could be computable), such as System.Data.SqlTypes.SqlDecimal.

    There is nothing magical in processing raw data, at least for us. We already work with raw array from System.Data.SqlTypes.SqlDecimal to fit value to .NET decimal (if it actually fits, otherwise OverflowException is thrown), we know how to do it, for example

    internal static unsafe decimal TruncateToNetDecimal(SqlDecimal sqlDecimal)
        {
          var inputData = sqlDecimal.Data;
          var scale = sqlDecimal.Scale;
    
          if (inputData[3] == 0) {
            if (scale <= 28) {
              return sqlDecimal.Value;
            }
          }
          else if (scale == 0) {
            return sqlDecimal.Value; // throws OverflowException.
          }
    
          fixed (int* inputS = inputData) {
            var input = (uint*) inputS;
            byte maxZeroCount = 0;
            while (maxZeroCount < scale && (input[maxZeroCount >> 6] & (1 << maxZeroCount)) == 0) {
              maxZeroCount++;
            }
    
            var realScale = scale;
            var outputData = sqlDecimal.Data;
            fixed (int* outputS = outputData) {
              var output = (uint*) outputS;
              var dividerPow = maxZeroCount > 9 ? (byte) 9 : maxZeroCount;
              if (dividerPow > 5) {
                var divider = PowersOf10[dividerPow];
                for (byte length = 4; realScale >= dividerPow; realScale -= dividerPow) {
                  if (DivHasRem(input, ref length, divider)) {
                    break;
                  }
    
                  output[0] = input[0];
                  output[1] = input[1];
                  output[2] = input[2];
                  output[3] = input[3];
                }
              }
    
              for (byte length = 4; realScale > 0 && output[3] != 0; realScale--) {
                _ = DivHasRem(output, ref length, 10);
              }
    
              if (output[3] != 0) {
                return sqlDecimal.Value; // throws OverflowException.
              }
    
              return new decimal(outputS[0], outputS[1], outputS[2], !sqlDecimal.IsPositive, realScale);
            }
          }
        }

    And it works just fine for our purposes, adjusting values on the fly. But thanks to some people in your team we have no such option. Such approach might've also helped original issue creator, he could've googled similar processing algorithm and implemented it within his project but both of us can only helplessly watch your code throwing exception because of meaningless zeros after comma.

    Since I have already worked with raw data, I think and I know that providing special type with access to raw data is good idea, because it doesn't tie down capabilities of community members who can actually do stuff with data. I don't know whether you can provide us scale value (and maybe precision value, for reduction it is not important) of the value (DecimalRaw type shows at least scale property, I believe it is possible, but I'm not sure), but if you can then I can't see any objective reasons to not give people control of reading of their own data which they saved to database.

    Speaking of string conversion, you say that it doesn't matter whether it is on server or client side, I thing it DOES MATTER that such conversion happens at the first place - it degrades performance anyway, unless you internally have to make such string-to-decimal conversion or other numeric type conversions from strings. If you read row values as strings all the time and have no any other way of reading raw representation then I'm wrong here, I admit, I overestimated capabilities of postgres communication protocols. My assumption was that you have more efficient way to pass data back and forth to RDBMS process. If you DO HAVE such way, then recommendation of reading all the values as strings is bad-bad offer.

  12. roji commented on Dec 9, 2024

    @roji
    Member

    @alex-kulakov you're continuing to talk in an offensive tone, calling into question the good faith (and intelligence) and of the Npgsql team. As a result, I won't be answering all your comments.

    I will say this: if you're interested in dealing with the raw data of decimals, you can do so: Npgsql allows you to read the raw byte representation of decimals (and other types) by using NpgsqlDataReader.GetBytes() or GetStream(). At that point you can decode that data or do whatever you want, to your heart's content. Npgsql also exposes an extensive type mapping API: you can easily develop a plugin that would read decimals as whatever type you want. Rather than continuing to post various accusations at the team, you're welcome to simply do that work, and you can even publish that plugin as a nuget for others to use.

    Aside from that, I really suggest thinking about how you communicate in the open source world. Maintainers are not always going to agree with your opinions, that doesn't mean they're stupid or mean; they usually have far more experience than you, and have a much wider and more informed viewpoint on what makes sense and what doesn't.

    Good luck.

  13. jmarsch-celerity commented on Jun 20, 2025

    @jmarsch-celerity

    Is this really a dup of 3559? Is that a typo -- maybe there's a different item that it duplicates? 3559 is a connection lifetime problem. This ticket is a type mapping/overflow issue.

  14. reopened this on Jun 22, 2025
  15. roji commented on Jun 22, 2025

    @roji
    Member

    Yeah, this was the wrong duplicate - #448 should be the right one. Note also #6125 which we could implement as a workaround.

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