Skip to content

Commit

Permalink
Fixed exception on Json serialization of ClickHouseDecimal #241 (#258)
Browse files Browse the repository at this point in the history
  • Loading branch information
DarkWanderer authored Dec 21, 2022
1 parent 91093b8 commit 9a2580d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
17 changes: 14 additions & 3 deletions ClickHouse.Client.Tests/Numerics/ClickHouseDecimalTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Threading.Tasks;
using ClickHouse.Client.ADO;
using ClickHouse.Client.Numerics;
Expand Down Expand Up @@ -209,6 +210,7 @@ public void ShouldRoundtripIntoDouble(double @double)
}

[Test]
[TestCase(typeof(bool))]
[TestCase(typeof(byte))]
[TestCase(typeof(sbyte))]
[TestCase(typeof(short))]
Expand All @@ -220,11 +222,20 @@ public void ShouldRoundtripIntoDouble(double @double)
[TestCase(typeof(float))]
[TestCase(typeof(double))]
[TestCase(typeof(decimal))]
[TestCase(typeof(string))]
public void ShouldConvertToType(Type type)
{
ClickHouseDecimal source = 5m;
var result = Convert.ChangeType(source, type);
Assert.AreEqual(source.ToString(), result.ToString());
var expected = Convert.ChangeType(5m, type);
var actual = Convert.ChangeType(new ClickHouseDecimal(5m), type);
Assert.AreEqual(expected, actual);
}

[Test]
public void ShouldConvertToBigInteger()
{
var expected = new BigInteger(123);
var actual = new ClickHouseDecimal(123.45m).ToType(typeof(BigInteger), CultureInfo.InvariantCulture);
Assert.AreEqual(expected, actual);
}

[Test]
Expand Down
11 changes: 8 additions & 3 deletions ClickHouse.Client/Numerics/ClickHouseDecimal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -401,9 +401,14 @@ public static ClickHouseDecimal Parse(string input, IFormatProvider provider)

public object ToType(Type conversionType, IFormatProvider provider)
{
if (conversionType == typeof(int))
return ToInt32(provider);
throw new NotSupportedException();
if (conversionType == typeof(BigInteger))
{
var mantissa = this.Mantissa;
var scale = this.Scale;
Truncate(ref mantissa, ref scale, 0);
return mantissa;
}
return Convert.ChangeType(this, conversionType);
}

public int CompareTo(decimal other) => CompareTo((ClickHouseDecimal)other);
Expand Down

0 comments on commit 9a2580d

Please sign in to comment.