-
Notifications
You must be signed in to change notification settings - Fork 317
Fixing NullReferenceException issue with SqlDataAdapter #3749
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+259
−1
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
0488e8c
Fixing NullReferenceException issue with SqlDataAdapter
priyankatiwari08 b6bdbaa
Added tests for this scenario
priyankatiwari08 92fc6cb
Update src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.…
priyankatiwari08 ae05d9d
addressed PR comments related fixes.
priyankatiwari08 a8bda9a
Merge branch 'dev/prtiwar/SqlDataAdapterIssue' of https://github.com/…
priyankatiwari08 373693f
Merge branch 'main' into dev/prtiwar/SqlDataAdapterIssue
priyankatiwari08 e1ace34
added this test in AE TestSetup
priyankatiwari08 3696a19
Update src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted…
priyankatiwari08 cbec7a7
Update src/Microsoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted…
priyankatiwari08 522ff97
Commits to ensure table name is properly escaped to prevent potential…
priyankatiwari08 ed45b19
.
priyankatiwari08 e926fb5
.
priyankatiwari08 6137517
Merge remote-tracking branch 'origin/main' into dev/prtiwar/SqlDataAd…
priyankatiwari08 7887c01
Merge branch 'main' of https://github.com/dotnet/SqlClient into dev/p…
priyankatiwari08 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
255 changes: 255 additions & 0 deletions
255
...rosoft.Data.SqlClient/tests/ManualTests/AlwaysEncrypted/SqlDataAdapterBatchUpdateTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,255 @@ | ||
| // 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.Threading.Tasks; | ||
| using System.Collections.Generic; | ||
| using Microsoft.Data.SqlClient; | ||
| using Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted.Setup; | ||
| using Xunit; | ||
|
|
||
| namespace Microsoft.Data.SqlClient.ManualTesting.Tests.AlwaysEncrypted | ||
| { | ||
| public sealed class SqlDataAdapterBatchUpdateTests : IClassFixture<SQLSetupStrategyCertStoreProvider>, IDisposable | ||
| { | ||
| private readonly SQLSetupStrategy _fixture; | ||
| private readonly Dictionary<string, string> tableNames = new(); | ||
|
|
||
| public SqlDataAdapterBatchUpdateTests(SQLSetupStrategyCertStoreProvider context) | ||
| { | ||
| _fixture = context; | ||
|
|
||
priyankatiwari08 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // Provide table names to mirror repo patterns. | ||
| // If your fixture already exposes specific names for BuyerSeller and procs, wire them here. | ||
| // Otherwise use literal names as below. | ||
priyankatiwari08 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| tableNames["BuyerSeller"] = "BuyerSeller"; | ||
| tableNames["ProcInsertBuyerSeller"] = "InsertBuyerSeller"; | ||
| tableNames["ProcUpdateBuyerSeller"] = "UpdateBuyerSeller"; | ||
priyankatiwari08 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| // ---------- TESTS ---------- | ||
|
|
||
| [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.IsTargetReadyForAeWithKeyStore))] | ||
| [ClassData(typeof(AEConnectionStringProvider))] | ||
| public async Task AdapterUpdate_BatchSizeGreaterThanOne_Succeeds(string connectionString) | ||
| { | ||
| // Arrange | ||
| // Ensure baseline rows exist | ||
| TruncateTables("BuyerSeller", connectionString); | ||
| PopulateTable("BuyerSeller", new (int id, string s1, string s2)[] { | ||
| (1, "123-45-6789", "987-65-4321"), | ||
| (2, "234-56-7890", "876-54-3210"), | ||
| (3, "345-67-8901", "765-43-2109"), | ||
| (4, "456-78-9012", "654-32-1098"), | ||
| }, connectionString); | ||
|
|
||
| using var conn = new SqlConnection(GetOpenConnectionString(connectionString, encryptionEnabled: true)); | ||
| await conn.OpenAsync(); | ||
|
|
||
| using var adapter = CreateAdapter(conn, updateBatchSize: 10); // failure repro: > 1 | ||
priyankatiwari08 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| var dataTable = BuildBuyerSellerDataTable(); | ||
| LoadCurrentRowsIntoDataTable(dataTable, conn); | ||
|
|
||
| // Mutate values for update | ||
| MutateForUpdate(dataTable); | ||
|
|
||
| // Act - With batch updates (UpdateBatchSize > 1), this previously threw NullReferenceException due to null systemParams in batch RPC mode | ||
| var updated = await Task.Run(() => adapter.Update(dataTable)); | ||
|
|
||
| // Assert | ||
| Assert.Equal(dataTable.Rows.Count, updated); | ||
|
|
||
priyankatiwari08 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| [ConditionalTheory(typeof(DataTestUtility), nameof(DataTestUtility.IsTargetReadyForAeWithKeyStore))] | ||
| [ClassData(typeof(AEConnectionStringProvider))] | ||
| public async Task AdapterUpdate_BatchSizeOne_Succeeds(string connectionString) | ||
| { | ||
| // Arrange | ||
| TruncateTables("BuyerSeller", connectionString); | ||
| PopulateTable("BuyerSeller", new (int id, string s1, string s2)[] { | ||
| (1, "123-45-6789", "987-65-4321"), | ||
| (2, "234-56-7890", "876-54-3210"), | ||
| (3, "345-67-8901", "765-43-2109"), | ||
| (4, "456-78-9012", "654-32-1098"), | ||
| }, connectionString); | ||
|
|
||
| using var conn = new SqlConnection(GetOpenConnectionString(connectionString, encryptionEnabled: true)); | ||
| await conn.OpenAsync(); | ||
|
|
||
| using var adapter = CreateAdapter(conn, updateBatchSize: 1); // success path | ||
| var dataTable = BuildBuyerSellerDataTable(); | ||
| LoadCurrentRowsIntoDataTable(dataTable, conn); | ||
|
|
||
| MutateForUpdate(dataTable); | ||
|
|
||
| // Act (should not throw) | ||
| var updatedRows = await Task.Run(() => adapter.Update(dataTable)); | ||
|
|
||
| // Assert | ||
| Assert.Equal(dataTable.Rows.Count, updatedRows); | ||
priyankatiwari08 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| } | ||
|
|
||
| // ---------- HELPERS ---------- | ||
|
|
||
| private SqlDataAdapter CreateAdapter(SqlConnection connection, int updateBatchSize) | ||
| { | ||
| // Insert | ||
| var insertCmd = new SqlCommand(tableNames["ProcInsertBuyerSeller"], connection) | ||
| { | ||
| CommandType = CommandType.StoredProcedure | ||
| }; | ||
| insertCmd.Parameters.AddRange(new[] | ||
| { | ||
| new SqlParameter("@BuyerSellerID", SqlDbType.Int) { SourceColumn = "BuyerSellerID" }, | ||
| new SqlParameter("@SSN1", SqlDbType.VarChar, 255) { SourceColumn = "SSN1" }, | ||
| new SqlParameter("@SSN2", SqlDbType.VarChar, 255) { SourceColumn = "SSN2" }, | ||
| }); | ||
| insertCmd.UpdatedRowSource = UpdateRowSource.None; | ||
|
|
||
| // Update | ||
| var updateCmd = new SqlCommand(tableNames["ProcUpdateBuyerSeller"], connection) | ||
| { | ||
| CommandType = CommandType.StoredProcedure | ||
| }; | ||
| updateCmd.Parameters.AddRange(new[] | ||
| { | ||
| new SqlParameter("@BuyerSellerID", SqlDbType.Int) { SourceColumn = "BuyerSellerID" }, | ||
| new SqlParameter("@SSN1", SqlDbType.VarChar, 255) { SourceColumn = "SSN1" }, | ||
| new SqlParameter("@SSN2", SqlDbType.VarChar, 255) { SourceColumn = "SSN2" }, | ||
| }); | ||
| updateCmd.UpdatedRowSource = UpdateRowSource.None; | ||
|
|
||
| return new SqlDataAdapter | ||
| { | ||
| InsertCommand = insertCmd, | ||
| UpdateCommand = updateCmd, | ||
| UpdateBatchSize = updateBatchSize | ||
| }; | ||
| } | ||
|
|
||
| private DataTable BuildBuyerSellerDataTable() | ||
| { | ||
| var dt = new DataTable(tableNames["BuyerSeller"]); | ||
| dt.Columns.AddRange(new[] | ||
| { | ||
| new DataColumn("BuyerSellerID", typeof(int)), | ||
priyankatiwari08 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| new DataColumn("SSN1", typeof(string)), | ||
priyankatiwari08 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| new DataColumn("SSN2", typeof(string)), | ||
priyankatiwari08 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }); | ||
| dt.PrimaryKey = new[] { dt.Columns["BuyerSellerID"] }; | ||
| return dt; | ||
| } | ||
|
|
||
| private void LoadCurrentRowsIntoDataTable(DataTable dt, SqlConnection conn) | ||
| { | ||
| using var cmd = new SqlCommand($"SELECT BuyerSellerID, SSN1, SSN2 FROM [dbo].[{tableNames["BuyerSeller"]}] ORDER BY BuyerSellerID", conn); | ||
| using var reader = cmd.ExecuteReader(); | ||
| while (reader.Read()) | ||
| { | ||
| dt.Rows.Add(reader.GetInt32(0), reader.GetString(1), reader.GetString(2)); | ||
| } | ||
| } | ||
|
|
||
| private void MutateForUpdate(DataTable dt) | ||
| { | ||
| int i = 0; | ||
| var fixedTime = new DateTime(2023, 01, 01, 12, 34, 56); // Use any fixed value | ||
| string timeStr = fixedTime.ToString("HHmm"); | ||
| foreach (DataRow row in dt.Rows) | ||
| { | ||
| i++; | ||
| row["SSN1"] = $"{i:000}-11-{timeStr}"; | ||
| row["SSN2"] = $"{i:000}-22-{timeStr}"; | ||
priyankatiwari08 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
|
|
||
| internal void TruncateTables(string tableName, string connectionString) | ||
| { | ||
| using var connection = new SqlConnection(GetOpenConnectionString(connectionString, encryptionEnabled: true)); | ||
| connection.Open(); | ||
| SilentRunCommand($@"TRUNCATE TABLE [dbo].[{tableNames[tableName]}]", connection); | ||
| } | ||
|
|
||
| internal void ExecuteQuery(SqlConnection connection, string commandText) | ||
| { | ||
| // Mirror AE-enabled command execution style used in repo tests | ||
| using var cmd = new SqlCommand( | ||
| commandText, | ||
| connection: connection, | ||
| transaction: null, | ||
| columnEncryptionSetting: SqlCommandColumnEncryptionSetting.Enabled); | ||
| cmd.ExecuteNonQuery(); | ||
paulmedynski marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| internal void PopulateTable(string tableName, (int id, string s1, string s2)[] rows, string connectionString) | ||
| { | ||
| using var connection = new SqlConnection(GetOpenConnectionString(connectionString, encryptionEnabled: true)); | ||
| connection.Open(); | ||
|
|
||
| foreach (var (id, s1, s2) in rows) | ||
| { | ||
| using var cmd = new SqlCommand( | ||
| $@"INSERT INTO [dbo].[{tableNames[tableName]}] (BuyerSellerID, SSN1, SSN2) VALUES (@id, @s1, @s2)", | ||
| connection, | ||
| null, | ||
| SqlCommandColumnEncryptionSetting.Enabled); | ||
|
|
||
| cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int) { Value = id }); | ||
| cmd.Parameters.Add(new SqlParameter("@s1", SqlDbType.VarChar, 255) { Value = s1 }); | ||
| cmd.Parameters.Add(new SqlParameter("@s2", SqlDbType.VarChar, 255) { Value = s2 }); | ||
|
|
||
| cmd.ExecuteNonQuery(); | ||
| } | ||
| } | ||
|
|
||
| public string GetOpenConnectionString(string baseConnectionString, bool encryptionEnabled) | ||
| { | ||
| var builder = new SqlConnectionStringBuilder(baseConnectionString) | ||
| { | ||
| // TrustServerCertificate can be set based on environment; mirror repo’s AE toggling idiom | ||
| ColumnEncryptionSetting = encryptionEnabled | ||
| ? SqlConnectionColumnEncryptionSetting.Enabled | ||
| : SqlConnectionColumnEncryptionSetting.Disabled | ||
| }; | ||
| return builder.ToString(); | ||
| } | ||
|
|
||
| internal void SilentRunCommand(string commandText, SqlConnection connection) | ||
| { | ||
| try | ||
| { ExecuteQuery(connection, commandText); } | ||
| catch (SqlException ex) | ||
| { | ||
| // Only swallow "object does not exist" (error 208), log others | ||
| bool onlyObjectNotExist = true; | ||
| foreach (SqlError err in ex.Errors) | ||
| { | ||
| if (err.Number != 208) | ||
| { | ||
| onlyObjectNotExist = false; | ||
| break; | ||
| } | ||
| } | ||
| if (!onlyObjectNotExist) | ||
| { | ||
| Console.WriteLine($"SilentRunCommand: Unexpected SqlException during cleanup: {ex}"); | ||
| } | ||
| // Swallow all exceptions, but log unexpected ones | ||
| } | ||
priyankatiwari08 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| public void Dispose() | ||
priyankatiwari08 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| { | ||
| foreach (string connectionString in DataTestUtility.AEConnStringsSetup) | ||
| { | ||
| using var connection = new SqlConnection(GetOpenConnectionString(connectionString, encryptionEnabled: true)); | ||
| connection.Open(); | ||
| SilentRunCommand($"DELETE FROM [dbo].[{tableNames["BuyerSeller"]}]", connection); | ||
| } | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.