diff --git a/ClickHouse.Driver.Tests/ParameterTypeResolutionTests.cs b/ClickHouse.Driver.Tests/ParameterTypeResolutionTests.cs index 05fe8b40b..949376440 100644 --- a/ClickHouse.Driver.Tests/ParameterTypeResolutionTests.cs +++ b/ClickHouse.Driver.Tests/ParameterTypeResolutionTests.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; +using System.Numerics; using ClickHouse.Driver.ADO.Parameters; +using ClickHouse.Driver.Numerics; using NUnit.Framework; namespace ClickHouse.Driver.Tests; @@ -109,6 +111,80 @@ public void ResolveTypeName_DecimalSpecialCase_PreservesScale() Assert.That(result, Is.EqualTo("Decimal128(3)")); } + private static IEnumerable ClickHouseDecimalTypeCases() + { + // Decimal128(9) holds the value exactly + yield return new TestCaseData(new ClickHouseDecimal(123456789, 9)).Returns("Decimal128(9)"); + yield return new TestCaseData(new ClickHouseDecimal(15, 1)).Returns("Decimal128(9)"); + yield return new TestCaseData(new ClickHouseDecimal(BigInteger.Pow(10, 38) - 1, 9)).Returns("Decimal128(9)"); + + // Trailing fractional zeros (all digits of a zero) are not counted + yield return new TestCaseData(new ClickHouseDecimal(BigInteger.Pow(10, 12), 12)).Returns("Decimal128(9)"); + yield return new TestCaseData(new ClickHouseDecimal(BigInteger.Pow(10, 80), 80)).Returns("Decimal128(9)"); + yield return new TestCaseData(new ClickHouseDecimal(0, 100)).Returns("Decimal128(9)"); + yield return new TestCaseData(new ClickHouseDecimal(1900000, 15)).Returns("Decimal128(10)"); + + // More than 9 fractional digits + yield return new TestCaseData(new ClickHouseDecimal(19, 10)).Returns("Decimal128(10)"); + yield return new TestCaseData(new ClickHouseDecimal(-10000000009, 10)).Returns("Decimal128(10)"); + yield return new TestCaseData(new ClickHouseDecimal(BigInteger.Pow(10, 38) - 1, 38)).Returns("Decimal128(38)"); + yield return new TestCaseData(new ClickHouseDecimal(1, 40)).Returns("Decimal256(40)"); + + // More than 29 integer digits: Decimal256, with a scale below 9 above 67 integer digits + yield return new TestCaseData(new ClickHouseDecimal(BigInteger.Pow(10, 29), 0)).Returns("Decimal256(9)"); + yield return new TestCaseData(new ClickHouseDecimal(-(BigInteger.Pow(10, 70) - 1), 0)).Returns("Decimal256(6)"); + yield return new TestCaseData(new ClickHouseDecimal(BigInteger.Pow(10, 76) - 1, 0)).Returns("Decimal256(0)"); + } + + [TestCaseSource(nameof(ClickHouseDecimalTypeCases))] + public string ResolveTypeName_ClickHouseDecimalWithoutType_ReturnsTypeThatHoldsValue(ClickHouseDecimal value) + { + var parameter = new ClickHouseDbParameter + { + ParameterName = "p", + Value = value, + }; + + return ParameterTypeResolution.ResolveTypeName(parameter, null, null); + } + + private static IEnumerable ClickHouseDecimalTooWideCases() + { + yield return new TestCaseData(new ClickHouseDecimal(BigInteger.Pow(10, 76), 0)); + yield return new TestCaseData(new ClickHouseDecimal(BigInteger.Pow(10, 80) + 1, 80)); + } + + [TestCaseSource(nameof(ClickHouseDecimalTooWideCases))] + public void ResolveTypeName_ClickHouseDecimalWiderThanDecimal256_Throws(ClickHouseDecimal value) + { + var parameter = new ClickHouseDbParameter + { + ParameterName = "p", + Value = value, + }; + + var ex = Assert.Throws(() => ParameterTypeResolution.ResolveTypeName(parameter, null, null)); + Assert.That(ex.Message, Does.Contain("'p'").And.Contain("Decimal256")); + } + + [Test] + public void ResolveTypeName_Resolver_WinsOverClickHouseDecimalSpecialCase() + { + var parameter = new ClickHouseDbParameter + { + ParameterName = "p", + Value = new ClickHouseDecimal(19, 10), + }; + var resolver = new DictionaryParameterTypeResolver(new Dictionary + { + [typeof(ClickHouseDecimal)] = "Decimal64(4)", + }); + + var result = ParameterTypeResolution.ResolveTypeName(parameter, null, resolver); + + Assert.That(result, Is.EqualTo("Decimal64(4)")); + } + [Test] public void ResolveTypeName_Resolver_WinsOverDecimalSpecialCase() { diff --git a/ClickHouse.Driver.Tests/SQL/ParameterTypeResolutionIntegrationTests.cs b/ClickHouse.Driver.Tests/SQL/ParameterTypeResolutionIntegrationTests.cs index 240b52311..3b2e324d9 100644 --- a/ClickHouse.Driver.Tests/SQL/ParameterTypeResolutionIntegrationTests.cs +++ b/ClickHouse.Driver.Tests/SQL/ParameterTypeResolutionIntegrationTests.cs @@ -1,8 +1,11 @@ using System; using System.Collections.Generic; +using System.Globalization; +using System.Numerics; using System.Threading.Tasks; using ClickHouse.Driver.ADO; using ClickHouse.Driver.ADO.Parameters; +using ClickHouse.Driver.Numerics; using ClickHouse.Driver.Utility; using NUnit.Framework; @@ -138,6 +141,38 @@ public async Task ExecuteReaderAsync_NoResolver_UsesDefaultInference() Assert.That(reader.GetString(0), Is.EqualTo("Int32")); } + private static IEnumerable ClickHouseDecimalValueCases() + { + yield return new TestCaseData(new ClickHouseDecimal(123456789, 9), "Decimal(38, 9)", "0.123456789"); + yield return new TestCaseData(new ClickHouseDecimal(19, 10), "Decimal(38, 10)", "0.0000000019"); + yield return new TestCaseData(new ClickHouseDecimal(-10000000009, 10), "Decimal(38, 10)", "-1.0000000009"); + yield return new TestCaseData(new ClickHouseDecimal(1, 40), "Decimal(76, 40)", "0.0000000000000000000000000000000000000001"); + yield return new TestCaseData( + new ClickHouseDecimal(BigInteger.Parse("12345678901234567890123456789012345123456789", CultureInfo.InvariantCulture), 9), + "Decimal(76, 9)", + "12345678901234567890123456789012345.123456789"); + yield return new TestCaseData( + new ClickHouseDecimal(BigInteger.Pow(10, 76) - 1, 6), + "Decimal(76, 6)", + new string('9', 70) + "." + new string('9', 6)); + yield return new TestCaseData(new ClickHouseDecimal(1234567891 * BigInteger.Pow(10, 71), 80), "Decimal(38, 9)", "1.234567891"); + } + + [TestCaseSource(nameof(ClickHouseDecimalValueCases))] + public async Task ExecuteReaderAsync_ClickHouseDecimalWithoutType_KeepsFullValue(ClickHouseDecimal value, string expectedType, string expectedValue) + { + var settings = TestUtilities.GetTestClickHouseClientSettings(useFormDataParameters: useFormDataParameters); + using var client = new ClickHouseClient(settings); + + var parameters = new ClickHouseParameterCollection(); + parameters.AddParameter("p", value); + + using var reader = await client.ExecuteReaderAsync("SELECT toTypeName(@p), toString(@p)", parameters); + Assert.That(reader.Read(), Is.True); + Assert.That(reader.GetString(0), Is.EqualTo(expectedType)); + Assert.That(reader.GetString(1), Is.EqualTo(expectedValue)); + } + [Test] public async Task ExecuteReaderAsync_CustomResolver_AppliesValueBasedResolution() diff --git a/ClickHouse.Driver/ADO/Parameters/ParameterTypeResolution.cs b/ClickHouse.Driver/ADO/Parameters/ParameterTypeResolution.cs index 9933cb6ca..c4f5253b0 100644 --- a/ClickHouse.Driver/ADO/Parameters/ParameterTypeResolution.cs +++ b/ClickHouse.Driver/ADO/Parameters/ParameterTypeResolution.cs @@ -1,4 +1,7 @@ using System; +using System.Globalization; +using System.Numerics; +using ClickHouse.Driver.Numerics; using ClickHouse.Driver.Types; namespace ClickHouse.Driver.ADO.Parameters; @@ -51,10 +54,53 @@ internal static string ResolveTypeName( return $"Decimal128({scale})"; } + if (parameter.Value is ClickHouseDecimal chd) + return ResolveClickHouseDecimalTypeName(chd, parameter.ParameterName); + // 5. Default: value-based TypeConverter mapping (inspects the value for ambiguous types like IPAddress or instant-bearing DateTimes) if (parameter.Value is not null and not DBNull) return TypeConverter.ToClickHouseType(parameter.Value).ToString(); return TypeConverter.ToClickHouseType(typeof(DBNull)).ToString(); } + + /// + /// Resolves the type for a value: Decimal128(9) if it holds the value + /// exactly. Otherwise the scale is that of the value without its trailing fractional zeros (which the server + /// parses exactly at a smaller scale), raised to 9 where the width has room, in Decimal128 or, above + /// 38 digits, Decimal256. + /// + /// + /// The value needs more than 76 digits, which exceeds the capacity of ClickHouse's widest Decimal256. + /// + private static string ResolveClickHouseDecimalTypeName(ClickHouseDecimal value, string parameterName) + { + const int defaultScale = 9; + const int decimal128Precision = 38; + const int decimal256Precision = 76; + + var mantissa = BigInteger.Abs(value.Mantissa); + var scale = mantissa.IsZero ? 0 : value.Scale; + while (scale > 0) + { + var quotient = BigInteger.DivRem(mantissa, 10, out var remainder); + if (!remainder.IsZero) + break; + mantissa = quotient; + scale--; + } + + var digits = mantissa.IsZero ? 0 : mantissa.ToString(CultureInfo.InvariantCulture).Length; + var integerDigits = Math.Max(digits - scale, 0); + if (integerDigits + scale > decimal256Precision) + { + throw new ArgumentOutOfRangeException( + nameof(value), + value, + $"Decimal value of parameter '{parameterName}' requires a precision of {integerDigits + scale} digits, which exceeds the maximum of {decimal256Precision} supported by ClickHouse (Decimal256)."); + } + + scale = Math.Max(scale, Math.Min(defaultScale, decimal256Precision - integerDigits)); + return integerDigits + scale <= decimal128Precision ? $"Decimal128({scale})" : $"Decimal256({scale})"; + } } diff --git a/ClickHouse.Driver/AGENTS.md b/ClickHouse.Driver/AGENTS.md index cc6cf5e8d..5ab86d481 100644 --- a/ClickHouse.Driver/AGENTS.md +++ b/ClickHouse.Driver/AGENTS.md @@ -118,7 +118,10 @@ Both refer to parameters by name in `ClickHouseParameterCollection`. A `{name:Ty 1. Explicit `ClickHouseDbParameter.ClickHouseType` on the parameter object 2. SQL type hint from `{name:Type}` in the query 3. Custom `IParameterTypeResolver` (per-query `QueryOptions.ParameterTypeResolver`, then client-level `ClickHouseClientSettings.ParameterTypeResolver`) -4. `decimal` special case: `Decimal128(scale)` where scale is read from the value's bits +4. `decimal` special case: `Decimal128(scale)` where scale is read from the value's bits. + `ClickHouseDecimal` special case: `Decimal128(9)` if it holds the value exactly, else the value's + scale without trailing zeros (raised to 9 where there is room) in `Decimal128` or, above 38 digits, + `Decimal256` 5. `TypeConverter.ToClickHouseType(value)`: inferred from the .NET runtime value (not just the static type, so e.g. `IPAddress` is disambiguated into `IPv4`/`IPv6` by `AddressFamily`) diff --git a/changelog.d/637-clickhousedecimal-parameter-scale.fixes.md b/changelog.d/637-clickhousedecimal-parameter-scale.fixes.md new file mode 100644 index 000000000..d1fe196f9 --- /dev/null +++ b/changelog.d/637-clickhousedecimal-parameter-scale.fixes.md @@ -0,0 +1 @@ +* Fixed scalar `ClickHouseDecimal` query parameters without an explicit type: they were always sent as `Decimal128(9)`, so the server silently truncated digits after the 9th decimal place and rejected values with more than 29 integer digits. The driver now uses a type that holds the value, and throws `ArgumentOutOfRangeException` if it needs more than 76 digits. ([#637](https://github.com/ClickHouse/clickhouse-cs/issues/637)) diff --git a/docs/http.mdx b/docs/http.mdx index dac5be7c7..7848f80c7 100644 --- a/docs/http.mdx +++ b/docs/http.mdx @@ -763,6 +763,8 @@ For `@`-style parameters with no `{name:Type}` hint in the SQL and no `ClickHous Explicit hints (`{name:DateTime}`) take precedence over inference and are the recommended way of building queries. +An inferred `decimal` parameter is sent as `Decimal128(S)`, where `S` is the scale of the value. An inferred `ClickHouseDecimal` parameter is sent as `Decimal128(9)` if that type holds the value exactly. Otherwise the driver uses the scale of the value without its trailing zeros, raised to 9 if the type has room, and `Decimal256` if the value needs more than 38 digits, so the server does not truncate it. A `ClickHouseDecimal` that needs more than 76 digits throws `ArgumentOutOfRangeException`. Decimals inside arrays and other composite parameters are inferred as `Decimal128(9)`; to keep more digits, set `ClickHouseType` or use a `{name:Type}` hint. + To override these defaults, set `ParameterTypeResolver` on `ClickHouseClientSettings`. This is useful when you want all `DateTime` parameters to use `DateTime64(3)` for millisecond precision, or all decimals to use a specific scale, without setting `ClickHouseType` on every individual parameter. **Using `DictionaryParameterTypeResolver` for simple type mappings:**