Path: redb/redb.MSSql/Data/SqlKeyGenerator.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.MSSql/Data/SqlKeyGenerator.cs ---- using Microsoft.Data.SqlClient; using redb.Core.Data; namespace redb.MSSql.Data; /// /// MS SQL Server implementation of key generator. /// Uses global_identity sequence. Caching is static in base class. /// public class SqlKeyGenerator : RedbKeyGeneratorBase { private readonly string _connectionString; // The scope's connection wrapper: inside a TransactionScope it works on the transaction's connection. private readonly Func? _scopeConnection; private const string SEQUENCE_NAME = "global_identity"; /// /// Create MSSQL key generator from connection string. /// /// MS SQL Server connection string. /// Cache domain for key isolation (optional). /// The owning scope's connection, used for keys inside an ambient transaction. public SqlKeyGenerator(string connectionString, string? domain = null, Func? scopeConnection = null) : base(domain) { _connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); _scopeConnection = scopeConnection; } // === DB-SPECIFIC IMPLEMENTATIONS === /// /// Generate batch of keys from MSSQL sequence. /// Uses sp_sequence_get_range for instant range reservation. /// protected override async Task> GenerateKeysAsync(int count) { await using var conn = new SqlConnection(_connectionString); await conn.OpenAsync(); // sp_sequence_get_range - instant range reservation (1 call for any count) var sql = $@" DECLARE @first SQL_VARIANT; EXEC sp_sequence_get_range @sequence_name = N'{SEQUENCE_NAME}', @range_size = @count, @range_first_value = @first OUTPUT; SELECT CAST(@first AS BIGINT);"; await using var cmd = new SqlCommand(sql, conn); cmd.Parameters.AddWithValue("@count", count); var firstValue = Convert.ToInt64(await cmd.ExecuteScalarAsync()); return Range(firstValue, count); } /// /// Inside a TransactionScope a refill on a connection of its own would be a second connection in the /// transaction, and SQL Server refuses the implicit distributed transaction that makes. The range is /// reserved through the scope's wrapper instead - on the transaction's connection. A sequence range is /// not transactional: a rollback leaves a gap, never a duplicate. /// protected override async Task?> TryGenerateKeysInAmbientTransactionAsync(int count) { if (System.Transactions.Transaction.Current == null || _scopeConnection?.Invoke() is not { } db) return null; var sql = $@" DECLARE @first SQL_VARIANT; EXEC sp_sequence_get_range @sequence_name = N'{SEQUENCE_NAME}', @range_size = $1, @range_first_value = @first OUTPUT; SELECT CAST(@first AS BIGINT);"; var firstValue = await db.ExecuteScalarAsync(sql, new object[] { count }, CancellationToken.None); return Range(firstValue, count); } private static List Range(long firstValue, int count) { // Generate keys from range (in memory - instant) var keys = new List(count); for (int i = 0; i < count; i++) { keys.Add(firstValue + i); } return keys; } }