Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10433,7 +10433,10 @@ private Task TDSExecuteRPCAddParameter(TdsParserStateObject stateObj, SqlParamet
// If Precision is specified, verify value precision vs param precision
if (precision != 0)
{
if (precision < adjustedValue.Precision)
// Precision metadata can overstate zero's required digits.
// Compare magnitudes to recognize negative zero as well.
if (precision < adjustedValue.Precision &&
(SqlDecimal.Abs(adjustedValue) != new SqlDecimal(0)).IsTrue)
{
throw ADP.ParameterValueOutOfRange(adjustedValue);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -532,11 +532,112 @@ public static void TestScaledDecimalParameter_CommandInsert(string connectionStr
Assert.True(ValidateInsertedValues(connection, decimalTable.Name, truncateScaledDecimal), $"Invalid test happened with connection string [{connection.ConnectionString}]");
}

[ConditionalFact(typeof(DataTestUtility), nameof(DataTestUtility.AreConnStringsSetup))]
public static void TestOutOfRangeDecimalParameter_CommandSelect()
/// <summary>
/// CLR and SQL zero values with different representations must round-trip into decimal(p,p) columns.
/// One async case covers command execution parity; scale boundaries use the shared synchronous conversion.
/// </summary>
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.IsTCPConnStringSetup))]
[InlineData(1, false)]
[InlineData(2, false)]
[InlineData(3, false)]
[InlineData(3, true)]
[InlineData(28, false)]
[InlineData(29, false)]
[InlineData(38, false)]
public static async Task ZeroDecimalParameter_CommandInsert(byte scale, bool useAsync)
{
using SqlConnection connection = new(DataTestUtility.TCPConnectionString);
connection.Open();
if (useAsync)
Comment thread
saurabh500 marked this conversation as resolved.
{
await connection.OpenAsync();
}
else
{
connection.Open();
}

using Table table = new(connection, "ZeroDecimalParameter", $"([Value] decimal({scale},{scale}))");
using SqlCommand command = new(
$"INSERT INTO {table.Name} ([Value]) OUTPUT INSERTED.[Value] VALUES (@Value)", connection);
SqlParameter parameter = command.Parameters.Add("@Value", SqlDbType.Decimal);
parameter.Precision = scale;
parameter.Scale = scale;

foreach (object value in new object[]
{
0m, 0.0m, 0.000m, new decimal(0, 0, 0, true, 0),
new SqlDecimal(0m), new SqlDecimal(0.000m),
new SqlDecimal(new decimal(0, 0, 0, true, 0)),
new SqlDecimal(38, scale, true, 0, 0, 0, 0),
new SqlDecimal(38, scale, false, 0, 0, 0, 0)
})
{
parameter.Value = value;
using SqlDataReader reader = useAsync
? await command.ExecuteReaderAsync()
: command.ExecuteReader();
Assert.True(useAsync ? await reader.ReadAsync() : reader.Read());
SqlDecimal actual = reader.GetSqlDecimal(0);
Assert.Equal(scale, actual.Precision);
Assert.Equal(scale, actual.Scale);
Assert.Equal(0, actual.CompareTo(new SqlDecimal(0)));
}
}

/// <summary>
/// Correcting zero precision must not allow nonzero values that exceed the parameter precision.
/// Both command APIs must surface the same exception, including when the async result is awaited.
/// </summary>
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.IsTCPConnStringSetup))]
[InlineData(false)]
[InlineData(true)]
public static async Task DecimalParameter_RejectsInsufficientPrecision(bool useAsync)
{
Comment thread
saurabh500 marked this conversation as resolved.
using SqlConnection connection = new(DataTestUtility.TCPConnectionString);
if (useAsync)
{
await connection.OpenAsync();
}
else
{
connection.Open();
}

using SqlCommand command = new("SELECT @Value", connection);
SqlParameter parameter = command.Parameters.Add("@Value", SqlDbType.Decimal);
parameter.Precision = 3;
parameter.Scale = 3;
foreach (object value in new object[] { 1m, -1m, new SqlDecimal(1m), new SqlDecimal(-1m) })
{
parameter.Value = value;
if (useAsync)
{
await Assert.ThrowsAsync<ArgumentException>(() => command.ExecuteNonQueryAsync());
}
else
{
Assert.Throws<ArgumentException>(() => command.ExecuteNonQuery());
}
}
}

/// <summary>
/// Large decimal values must still round-trip after rescaling beyond the CLR decimal capacity.
/// </summary>
[ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.IsTCPConnStringSetup))]
[InlineData(false)]
[InlineData(true)]
public static async Task TestOutOfRangeDecimalParameter_CommandSelect(bool useAsync)
{
using SqlConnection connection = new(DataTestUtility.TCPConnectionString);
if (useAsync)
{
await connection.OpenAsync();
}
else
{
connection.Open();
}

using SqlCommand cmd = new("SELECT @Value", connection);
// A System.Decimal value has a maximum precision of 29 digits. We specify a Precision of 38 and a Scale of 2 in order
Expand All @@ -550,9 +651,11 @@ public static void TestOutOfRangeDecimalParameter_CommandSelect()

cmd.Parameters.Add(p);

using SqlDataReader reader = cmd.ExecuteReader();
using SqlDataReader reader = useAsync
? await cmd.ExecuteReaderAsync()
: cmd.ExecuteReader();

reader.Read();
Assert.True(useAsync ? await reader.ReadAsync() : reader.Read());
// Read the original value back as a SqlDecimal, with matching scale and precision.
SqlDecimal roundtrippedDecimal = reader.GetSqlDecimal(0);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Data;
using System.Data.SqlTypes;
using System.Globalization;
using System.Reflection;
using Microsoft.Data.SqlClient.Tests.Common;
using Xunit;

namespace Microsoft.Data.SqlClient.UnitTests
{
/// <summary>
/// Verifies decimal scale adjustment and RPC precision validation preserve representable values.
/// </summary>
[Collection(AppContextSwitchTestCollection.Name)]
public class TdsParserDecimalTests
{
/// <summary>
/// CLR and SQL zero must serialize when precision equals scale, regardless of input scale or sign.
/// </summary>
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public void RpcDecimalParameter_ZeroFitsPrecisionEqualToScale(bool isSqlDecimal, bool truncate)
{
using LocalAppContextSwitchesHelper switches = new();
switches.TruncateScaledDecimal = truncate;

for (byte oldScale = 0; oldScale <= 28; oldScale++)
{
foreach (bool negative in new[] { false, true })
{
decimal zero = new(0, 0, 0, negative, oldScale);
object value = isSqlDecimal ? (object)new SqlDecimal(zero) : zero;
for (byte scale = 1; scale <= 38; scale++)
{
WriteDecimalParameter(value, scale, scale);
}
}
}
}

/// <summary>
/// Excess SqlDecimal precision must not reject signed zero or a value that rounds/truncates to zero.
/// </summary>
[Theory]
[InlineData(false)]
[InlineData(true)]
public void RpcDecimalParameter_ZeroWithExcessPrecisionFits(bool negative)
{
using LocalAppContextSwitchesHelper switches = new();
foreach (bool truncate in new[] { false, true })
{
switches.TruncateScaledDecimal = truncate;
WriteDecimalParameter(new SqlDecimal(38, 3, !negative, 0, 0, 0, 0), 3, 3);
WriteDecimalParameter(SqlDecimal.ConvertToPrecScale(
new SqlDecimal(new decimal(0, 0, 0, negative, 3)), 38, 3), 3, 3);
WriteDecimalParameter(new SqlDecimal(38, 4, !negative, 1, 0, 0, 0), 3, 3);
}
}

/// <summary>
/// Exempting zero must not permit nonzero CLR or SQL values with insufficient parameter precision.
/// </summary>
[Theory]
[InlineData(false)]
[InlineData(true)]
public void RpcDecimalParameter_NonzeroExceedingPrecisionThrows(bool isSqlDecimal)
{
foreach (decimal value in new[] { -1m, 1m })
{
object parameterValue = isSqlDecimal ? (object)new SqlDecimal(value) : value;
TargetInvocationException exception = Assert.Throws<TargetInvocationException>(
() => WriteDecimalParameter(parameterValue, 3, 3));
Assert.IsType<ArgumentException>(exception.InnerException);
}
}

/// <summary>
/// Scale adjustment must retain the rounding switch and precision needed for nonzero values.
/// </summary>
[Theory]
[InlineData("0.001", 3, "0.001", "0.001", 3)]
[InlineData("0.01", 3, "0.010", "0.010", 3)]
[InlineData("1", 3, "1.000", "1.000", 4)]
[InlineData("-1", 3, "-1.000", "-1.000", 4)]
[InlineData("1.005", 2, "1.01", "1.00", 3)]
[InlineData("-1.005", 2, "-1.01", "-1.00", 3)]
public void AdjustDecimalScale_NonzeroPreservesValueAndPrecision(
string value, int scale, string rounded, string truncated, int precision)
{
using LocalAppContextSwitchesHelper switches = new();
foreach (bool truncate in new[] { false, true })
{
switches.TruncateScaledDecimal = truncate;
SqlDecimal adjusted = TdsParser.AdjustDecimalScale(
decimal.Parse(value, CultureInfo.InvariantCulture), scale);

Assert.Equal(truncate ? truncated : rounded, adjusted.ToString());
Assert.Equal(scale, adjusted.Scale);
Assert.Equal(precision, adjusted.Precision);
}
}

/// <summary>
/// Rescaling the CLR decimal limits must not reintroduce the overflow fixed by PR #4443.
/// </summary>
[Theory]
[InlineData(2)]
[InlineData(9)]
public void AdjustDecimalScale_LargeValuesRemainSqlDecimal(int scale)
{
foreach (decimal value in new[] { decimal.MinValue, decimal.MaxValue })
{
SqlDecimal adjusted = TdsParser.AdjustDecimalScale(value, scale);

Assert.Equal(value.ToString(CultureInfo.InvariantCulture) + "." + new string('0', scale), adjusted.ToString());
Assert.Equal(scale, adjusted.Scale);
Assert.Equal(29 + scale, adjusted.Precision);
Assert.Throws<OverflowException>(() => adjusted.Value);
}
}

/// <summary>
/// Serializes one RPC parameter into a fresh parser buffer without connecting to a server.
/// </summary>
/// <param name="value">The CLR decimal or SqlDecimal parameter value.</param>
/// <param name="precision">The declared parameter precision.</param>
/// <param name="scale">The declared parameter scale.</param>
private static void WriteDecimalParameter(object value, byte precision, byte scale)
{
const BindingFlags Flags = BindingFlags.Instance | BindingFlags.NonPublic;
TdsParser parser = new(false, false);
object state = typeof(TdsParser).GetField("_physicalStateObj", Flags)!.GetValue(parser)!;
SqlParameter parameter = new("@Value", SqlDbType.Decimal)
{
Value = value,
Precision = precision,
Scale = scale
};
parameter.Validate(0, false);

using SqlCommand command = new();
MethodInfo write = typeof(TdsParser).GetMethod("TDSExecuteRPCAddParameter", Flags)!;
Assert.Null(write.Invoke(parser, new object[]
{
state, parameter, parameter.InternalMetaType, (byte)0, command, false
}));
}
}
}
Loading