Path: redb/redb.Postgres/Data/NpgsqlKeyGenerator.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.Postgres/Data/NpgsqlKeyGenerator.cs ---- using Npgsql; using redb.Core.Data; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace redb.Postgres.Data { /// /// PostgreSQL implementation of key generator. /// Uses global_identity sequence. Caching is static in base class. /// public class NpgsqlKeyGenerator : RedbKeyGeneratorBase { private readonly NpgsqlDataSource _dataSource; // 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 PostgreSQL key generator. /// /// Npgsql data source. /// Cache domain for key isolation (optional). /// The owning scope's connection, used for keys inside an ambient transaction. public NpgsqlKeyGenerator(NpgsqlDataSource dataSource, string? domain = null, Func? scopeConnection = null) : base(domain) { _dataSource = dataSource; _scopeConnection = scopeConnection; } /// /// Create PostgreSQL key generator from connection string. /// public NpgsqlKeyGenerator(string connectionString, string? domain = null) : base(domain) { _dataSource = NpgsqlDataSource.Create(connectionString); } // === DB-SPECIFIC IMPLEMENTATIONS === /// /// Generate batch of keys from PostgreSQL sequence. /// protected override async Task> GenerateKeysAsync(int count) { var keys = new List(count); await using var conn = await _dataSource.OpenConnectionAsync(); await using var cmd = new NpgsqlCommand( $"SELECT nextval('{SEQUENCE_NAME}') FROM generate_series(1, {count})", conn); await using var reader = await cmd.ExecuteReaderAsync(); while (await reader.ReadAsync()) { keys.Add(reader.GetInt64(0)); } return keys; } /// /// Inside a TransactionScope a refill on a connection of its own would be a second connection in the /// transaction, which PostgreSQL can only commit as a prepared (two-phase) transaction. The values are /// taken through the scope's wrapper instead - on the transaction's connection. nextval 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; return await db.QueryScalarListAsync( $"SELECT nextval('{SEQUENCE_NAME}') FROM generate_series(1, $1)", new object[] { count }, CancellationToken.None); } } }