Created
November 16, 2023 10:25
-
-
Save ramonsmits/5ba5c13dfc1340d358240b9d254b6de0 to your computer and use it in GitHub Desktop.
NServiceBus.Persistence.Sql v7.0.3 JSON patch for saga tables
This file contains 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
// <PackageReference Include="Microsoft.Data.SqlClient" Version="5.1.2" /> | |
// <PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> | |
using Microsoft.Data.SqlClient; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Linq; | |
using System.Data; | |
internal class Program | |
{ | |
static async Task Main(string[] args) | |
{ | |
bool whatIf = true; | |
var tableName = "Samples_SqlPersistence_EndpointSqlServer_OrderSaga"; | |
using var con = new SqlConnection(Environment.GetEnvironmentVariable("SQLServerConnectionString")); | |
await con.OpenAsync(); | |
await con.ChangeDatabaseAsync("NsbSamplesSqlPersistence"); | |
var cmd = con.CreateCommand(); | |
cmd.CommandText = $"SELECT Id, Data FROM {tableName} WHERE PersistenceVersion = '7.0.3.0' and LEN(Data)=4000 ORDER BY Id"; | |
using var reader = cmd.ExecuteReader(); | |
{ | |
while (reader.Read()) | |
{ | |
var id = (Guid)reader[0]; | |
var json = (string)reader[1]; | |
json = json.Trim('\0'); | |
try | |
{ | |
JObject.Parse(json); | |
} | |
catch (JsonReaderException) | |
{ | |
var open = json.Where(c => c == '{').Count(); | |
var close = json.Where(c => c == '}').Count(); | |
if (close <= open) | |
{ | |
Console.WriteLine("Closing / open bracket count condition: Cannot patch json for {0}, manual patching required. Please contact Particular if assistance is required.", id); | |
} | |
var diff = close - open; | |
var i = json.Length; | |
for (var iteration = 0; iteration <= diff; iteration++) | |
{ | |
i = json.LastIndexOf('}', --i); | |
} | |
var patchedJson = json.Substring(0, ++i); | |
try | |
{ | |
JObject.Parse(patchedJson); | |
if (!whatIf) | |
{ | |
using var update = con.CreateCommand(); | |
update.CommandText = $"UPDATE {tableName} SET Data = left(Data, @len) WHERE Id=@id"; | |
update.Parameters.Add("@id", SqlDbType.UniqueIdentifier).Value = id; | |
update.Parameters.Add("@len", SqlDbType.Int).Value = i; | |
await update.ExecuteNonQueryAsync(); | |
} | |
Console.WriteLine($"Truncated json `{id}` from {json.Length} to {i:N0} characters, original data size was 4.000 nvarchar (8.000 bytes)"); | |
} | |
catch (JsonReaderException) | |
{ | |
Console.WriteLine("Invalided json after truncate: cannot patch json for {0}, manual patching required. Please contact Particular if assistance is required.", id); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment