BatchUpdateString.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Runtime.CompilerServices;
  6. namespace Benchmarks.Data
  7. {
  8. internal class BatchUpdateString
  9. {
  10. private const int MaxBatch = 500;
  11. internal static readonly string[] Ids = Enumerable.Range(0, MaxBatch).Select(i => $"@Id_{i}").ToArray();
  12. internal static readonly string[] Randoms = Enumerable.Range(0, MaxBatch).Select(i => $"@Random_{i}").ToArray();
  13. private static string[] _queries = new string[MaxBatch + 1];
  14. public static string Query(int batchSize)
  15. {
  16. if (_queries[batchSize] != null)
  17. {
  18. return _queries[batchSize];
  19. }
  20. var lastIndex = batchSize - 1;
  21. var sb = StringBuilderCache.Acquire();
  22. sb.Append("UPDATE world SET randomNumber = temp.randomNumber FROM (VALUES ");
  23. Enumerable.Range(0, lastIndex).ToList().ForEach(i => sb.Append($"(@Id_{i}, @Random_{i}), "));
  24. sb.Append($"(@Id_{lastIndex}, @Random_{lastIndex}) ORDER BY 1) AS temp(id, randomNumber) WHERE temp.id = world.id");
  25. return _queries[batchSize] = StringBuilderCache.GetStringAndRelease(sb);
  26. }
  27. }
  28. }