Path: redb/redb.SQLite/Data/SqliteKeyGenerator.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.SQLite/Data/SqliteKeyGenerator.cs ---- using System; using Microsoft.Data.Sqlite; using redb.Core.Data; using System.Collections.Generic; using System.Threading.Tasks; namespace redb.SQLite.Data { /// /// SQLite implementation of key generator. Ids come from the native /// AUTOINCREMENT table _global_identity; its high-water mark lives in /// sqlite_sequence. A batch of N ids is reserved with one atomic statement: /// UPDATE sqlite_sequence SET seq = seq + @n WHERE name='_global_identity' /// RETURNING seq; /// which returns the new top; the reserved ids are [top-N+1 .. top]. /// No explicit locking is needed — SQLite serializes writers and the /// read-modify-write happens inside the single UPDATE (RETURNING: 3.35+). /// The same sequence is also advanced by the C extension (nextId) and by /// soft-delete (INSERT DEFAULT VALUES); all consumers only ever increase it, /// so ids are globally unique. Caching is static in the base class. /// public class SqliteKeyGenerator : RedbKeyGeneratorBase { private readonly SqliteDataSource _dataSource; // The scope's ambient (connection, transaction) accessor for the single-writer bypass; // null (the connection-string constructor, tests) keeps the plain pooled-refill path. private readonly Func<(Microsoft.Data.Sqlite.SqliteConnection Connection, Microsoft.Data.Sqlite.SqliteTransaction Transaction)?>? _ambientAccessor; // AUTOINCREMENT table whose sqlite_sequence row is the id high-water mark. private const string SEQUENCE_TABLE = "_global_identity"; /// /// The highest id stored in the tables that take their ids from the sequence. Every range starts above it, so /// the sequence never hands out an id a stored row already has, whatever left it behind: a row committed with an /// id the application kept from a rolled-back transaction (the sequence bump went back, the row did not), an id /// another process wrote, a row written with an explicit id. Each term is the last key of a rowid table, read /// from the end of its b-tree. /// internal const string IdSpaceTopSql = "coalesce((SELECT max(_id) FROM _objects), 0), coalesce((SELECT max(_id) FROM _values), 0), " + "coalesce((SELECT max(_id) FROM _schemes), 0), coalesce((SELECT max(_id) FROM _structures), 0), " + "coalesce((SELECT max(_id) FROM _users), 0), coalesce((SELECT max(_id) FROM _roles), 0), " + "coalesce((SELECT max(_id) FROM _users_roles), 0), coalesce((SELECT max(_id) FROM _permissions), 0), " + "coalesce((SELECT max(_id) FROM _lists), 0), coalesce((SELECT max(_id) FROM _list_items), 0)"; /// /// Create SQLite key generator. /// public SqliteKeyGenerator(SqliteDataSource dataSource, string? domain = null, Func<(Microsoft.Data.Sqlite.SqliteConnection Connection, Microsoft.Data.Sqlite.SqliteTransaction Transaction)?>? ambientTransactionAccessor = null) : base(domain) { _dataSource = dataSource; _ambientAccessor = ambientTransactionAccessor; } /// /// Create SQLite key generator from connection string. /// public SqliteKeyGenerator(string connectionString, string? domain = null) : base(domain) { _dataSource = SqliteDataSource.Create(connectionString); } // === DB-SPECIFIC IMPLEMENTATIONS === /// /// Reserve a contiguous batch of ids by bumping the /// AUTOINCREMENT high-water mark in sqlite_sequence via one atomic UPDATE ... RETURNING. /// protected override async Task> GenerateKeysAsync(int count) { var sw = System.Diagnostics.Stopwatch.StartNew(); var tid = System.Environment.CurrentManagedThreadId; // Console.WriteLine($"[Diag-KeyGen] ENTER count={count} thread={tid}"); await using var conn = await _dataSource.OpenConnectionAsync(); var tConn = sw.ElapsedMilliseconds; // Console.WriteLine($"[Diag-KeyGen] OpenConnectionAsync +{tConn}ms thread={tid}"); await using var cmd = conn.CreateCommand(); PrepareReserve(cmd, count); object? scalar; try { scalar = await cmd.ExecuteScalarAsync(); var tScalar = sw.ElapsedMilliseconds - tConn; // Console.WriteLine($"[Diag-KeyGen] UPDATE sqlite_sequence RETURNING +{tScalar}ms (total {sw.ElapsedMilliseconds}ms) thread={tid}"); } catch (Microsoft.Data.Sqlite.SqliteException ex) { // Console.WriteLine($"[Diag-KeyGen] UPDATE FAILED after {sw.ElapsedMilliseconds}ms thread={tid} errno={ex.SqliteErrorCode} msg='{ex.Message}'"); throw; } if (scalar is null || scalar == DBNull.Value) { throw new InvalidOperationException( $"sqlite_sequence row for '{SEQUENCE_TABLE}' not found. " + "Ensure the schema (redbSqlite.sql) was applied — it materializes the sequence row."); } long top = Convert.ToInt64(scalar); RecordIssued(top); var keys = new List(count); for (long id = top - count + 1; id <= top; id++) { keys.Add(id); } // Console.WriteLine($"[Diag-KeyGen] EXIT keys=[{(keys.Count > 0 ? keys[0] : -1)}..{(keys.Count > 0 ? keys[^1] : -1)}] total={sw.ElapsedMilliseconds}ms thread={tid}"); return keys; } /// /// The single-writer bypass: the same atomic sequence bump, but on the scope's own /// connection INSIDE its BEGIN IMMEDIATE - the write lock is already ours, so there is /// no waiting and no self-deadlock. The keys deliberately do NOT enter the shared /// cache. A rollback takes the sequence bump back together with the transaction, but /// the ids stay with whoever got them (an object the application saves again), so /// every later range starts above the highest id handed out (). /// protected override async Task?> TryGenerateKeysInAmbientTransactionAsync(int count) { if (_ambientAccessor?.Invoke() is not { } ambient) return null; await using var cmd = ambient.Connection.CreateCommand(); cmd.Transaction = ambient.Transaction; PrepareReserve(cmd, count); var scalar = await cmd.ExecuteScalarAsync(); if (scalar is null || scalar == DBNull.Value) { throw new InvalidOperationException( $"sqlite_sequence row for '{SEQUENCE_TABLE}' not found. " + "Ensure the schema (redbSqlite.sql) was applied - it materializes the sequence row."); } long top = Convert.ToInt64(scalar); RecordIssued(top); var keys = new List(count); for (long id = top - count + 1; id <= top; id++) keys.Add(id); return keys; } /// /// The reserving statement of both paths. The range starts above the sequence and above every id this process /// handed out before: a range taken inside a transaction that rolled back is gone from sqlite_sequence, yet the /// application may still hold its ids (since 4.0.0 the next range repeated them, and saving such an object again /// overwrote the row of the object that got the id second). One statement, no extra write. /// private void PrepareReserve(SqliteCommand cmd, int count) { cmd.CommandText = "UPDATE sqlite_sequence SET seq = max(seq, @floor, " + IdSpaceTopSql + ") + @n WHERE name = @name RETURNING seq"; cmd.Parameters.AddWithValue("@floor", IssuedHighWater); cmd.Parameters.AddWithValue("@n", count); cmd.Parameters.AddWithValue("@name", SEQUENCE_TABLE); } } }