feat(data): add database abstractions and SQLite binding

IDatabase/IDbSession/IDbTransaction with positional $n parameters, typed
DbParam and DbRow, SqlDialect helpers, and a P/Invoke binding to the
system SQLite (winsqlite3 / libsqlite3) with WAL pragmas, statement
cache, serialized writes, busy retry, interrupt-based cancellation,
VACUUM INTO backups and restore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 09:40:33 +00:00
1 parent 800843d2ae
commit a09aa16876
14 files changed
+1880

No files matched your search

+209
View File
@@ -0,0 +1,209 @@
using System.Text;
using static Titano.Data.Sqlite.SqliteNative;
namespace Titano.Data.Sqlite;
/// <summary>One native SQLite connection with its pragmas and an LRU cache of prepared statements.</summary>
internal sealed unsafe class SqliteConnection : IDisposable
{
private const int StatementCacheCapacity = 64;
private const string Pragmas =
"PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON; PRAGMA temp_store=MEMORY; " +
"PRAGMA cache_size=-65536; PRAGMA mmap_size=268435456;";
private readonly Dictionary<string, LinkedListNode<SqliteStatement>> _cache = new(StringComparer.Ordinal);
private readonly LinkedList<SqliteStatement> _lru = new();
private SqliteConnection(nint handle) => Handle = handle;
public nint Handle { get; private set; }
public bool IsAutoCommit => sqlite3_get_autocommit(Handle) != 0;
/// <summary>Rows changed by INSERT/UPDATE/DELETE since the connection opened (DDL does not count).</summary>
public int TotalChanges => sqlite3_total_changes(Handle);
/// <summary>Rows changed by the most recent INSERT/UPDATE/DELETE.</summary>
public int Changes => sqlite3_changes(Handle);
/// <summary>Opens a read-write connection and applies the BRIEF §6.2 pragmas (WAL only for files).</summary>
public static SqliteConnection Open(string filename, bool isMemory, int busyTimeoutMs)
{
var connection = OpenRaw(filename, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI | SQLITE_OPEN_NOMUTEX);
try
{
sqlite3_busy_timeout(connection.Handle, busyTimeoutMs);
connection.Exec(isMemory ? Pragmas : "PRAGMA journal_mode=WAL; " + Pragmas);
return connection;
}
catch
{
connection.Dispose();
throw;
}
}
public static SqliteConnection OpenReadOnly(string path) =>
OpenRaw(path, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX);
private static SqliteConnection OpenRaw(string filename, int flags)
{
nint db;
int rc;
fixed (byte* p = NullTerminated(filename)) rc = sqlite3_open_v2(p, out db, flags, null);
if (rc != SQLITE_OK)
{
var message = db != 0 ? Utf8(sqlite3_errmsg(db)) : null;
if (db != 0) sqlite3_close_v2(db);
throw new SqliteException($"Cannot open SQLite database '{filename}': {message ?? "error " + rc}", rc);
}
sqlite3_extended_result_codes(db, 1);
return new SqliteConnection(db);
}
/// <summary>Runs one or more parameterless statements.</summary>
public void Exec(string sql)
{
byte* error;
int rc;
fixed (byte* p = NullTerminated(sql)) rc = sqlite3_exec(Handle, p, 0, 0, out error);
if (rc == SQLITE_OK) return;
var message = Utf8(error) ?? $"SQLite error {rc}";
sqlite3_free(error);
throw new SqliteException(message, rc);
}
/// <summary>Takes a statement from the cache (or prepares one); give it back with <see cref="Return"/>.</summary>
public SqliteStatement Rent(string sql)
{
if (_cache.TryGetValue(sql, out var node))
{
if (!node.Value.InUse)
{
_lru.Remove(node);
_lru.AddFirst(node);
node.Value.InUse = true;
return node.Value;
}
// Same SQL already running on this connection (nested enumeration): use a private copy.
var copy = Prepare(sql);
copy.InUse = true;
return copy;
}
var statement = Prepare(sql);
statement.InUse = true;
statement.Cached = true;
_cache[sql] = _lru.AddFirst(statement);
if (_lru.Count > StatementCacheCapacity && _lru.Last is { Value.InUse: false } last)
{
_lru.RemoveLast();
_cache.Remove(last.Value.Sql);
last.Value.Dispose();
}
return statement;
}
public void Return(SqliteStatement statement)
{
statement.InUse = false;
if (statement.Cached) statement.Reset();
else statement.Dispose();
}
public void Interrupt() => sqlite3_interrupt(Handle);
public SqliteException Error(int rc) => new(Utf8(sqlite3_errmsg(Handle)) ?? $"SQLite error {rc}", rc);
public void Dispose()
{
if (Handle == 0) return;
foreach (var statement in _lru) statement.Dispose();
_lru.Clear();
_cache.Clear();
sqlite3_close_v2(Handle);
Handle = 0;
}
private SqliteStatement Prepare(string sql)
{
var bytes = Encoding.UTF8.GetBytes(SqliteSqlText.TranslatePlaceholders(sql));
fixed (byte* p = bytes)
{
var rc = sqlite3_prepare_v2(Handle, p, bytes.Length, out var statement, out var tail);
if (rc != SQLITE_OK) throw Error(rc);
if (statement == 0) throw new ArgumentException("The SQL text contains no statement.", nameof(sql));
var rest = bytes.Length - (int)(tail - p);
if (rest > 0 && HasStatement(tail, rest))
{
sqlite3_finalize(statement);
throw new ArgumentException("Only one statement per command is allowed; use ExecuteScriptAsync for scripts.", nameof(sql));
}
return new SqliteStatement(this, statement, sql);
}
}
/// <summary>True when the remaining text holds more than whitespace and comments.</summary>
private bool HasStatement(byte* text, int length)
{
var rc = sqlite3_prepare_v2(Handle, text, length, out var statement, out _);
if (statement != 0) sqlite3_finalize(statement);
return rc != SQLITE_OK || statement != 0;
}
private static byte[] NullTerminated(string s)
{
var bytes = new byte[Encoding.UTF8.GetByteCount(s) + 1];
Encoding.UTF8.GetBytes(s, bytes);
return bytes;
}
}
/// <summary>Rewrites <c>$n</c> placeholders for SQLite, which numbers <c>$name</c> parameters by first appearance.</summary>
internal static class SqliteSqlText
{
/// <summary>Turns <c>$n</c> into <c>?n</c> outside string literals, quoted identifiers and comments.</summary>
public static string TranslatePlaceholders(string sql)
{
if (!sql.Contains('$', StringComparison.Ordinal)) return sql;
var sb = new StringBuilder(sql.Length);
var i = 0;
while (i < sql.Length)
{
var c = sql[i];
var next = i + 1 < sql.Length ? sql[i + 1] : '\0';
int end;
switch (c)
{
case '\'' or '"' or '`':
end = sql.IndexOf(c, i + 1);
break;
case '[':
end = sql.IndexOf(']', i + 1);
break;
case '-' when next == '-':
end = sql.IndexOf('\n', i + 2);
break;
case '/' when next == '*':
end = sql.IndexOf("*/", i + 2, StringComparison.Ordinal);
if (end >= 0) end++;
break;
case '$' when char.IsAsciiDigit(next) && (i == 0 || !IsIdentifierChar(sql[i - 1])):
sb.Append('?');
i++;
continue;
default:
sb.Append(c);
i++;
continue;
}
// Copy the literal, identifier or comment verbatim (to the end of the text if unterminated).
end = end < 0 ? sql.Length : end + 1;
sb.Append(sql, i, end - i);
i = end;
}
return sb.ToString();
}
private static bool IsIdentifierChar(char c) => char.IsLetterOrDigit(c) || c is '_' or '$';
}
+265
View File
@@ -0,0 +1,265 @@
using System.Globalization;
using System.Text.RegularExpressions;
using Titano.Core.Diagnostics;
using Titano.Core.IO;
using static Titano.Data.Sqlite.SqliteNative;
namespace Titano.Data.Sqlite;
/// <summary>Parsed SQLite connection string: <c>Data Source=&lt;path&gt;|:memory:;Pool Size=4</c>.</summary>
internal sealed record SqliteSettings(string DataSource, int PoolSize)
{
public bool IsMemory => DataSource == ":memory:";
public static SqliteSettings Parse(string connectionString)
{
var cs = new ConnectionString(connectionString);
var source = cs.Get("Data Source", "DataSource", "Filename")
?? throw new FormatException("A SQLite connection string needs 'Data Source'.");
var pool = cs.GetInt(4, "Pool Size", "Max Pool Size");
cs.ThrowOnUnknownKeys();
if (pool < 1) throw new FormatException("'Pool Size' must be at least 1.");
return new SqliteSettings(source, pool);
}
}
/// <summary>
/// SQLite through the system library (BRIEF §6.2). Up to <c>Pool Size</c> connections serve concurrent
/// readers (WAL); writes are serialised in-process by one async write lock, so writers wait in a queue instead
/// of spinning on SQLITE_BUSY. In-memory databases use a single shared-cache connection.
/// </summary>
public sealed class SqliteDatabase : IDatabase
{
/// <summary>3.31.0, the oldest library accepted: it has UPSERT, NULLS LAST and <c>VACUUM INTO</c>.</summary>
public const int MinimumVersionNumber = 3_031_000;
internal const int BusyTimeoutMs = 5000;
private const string LogCategory = "Data.Sqlite";
private readonly string _filename;
private readonly bool _memory;
private readonly int _maxConnections;
private readonly SemaphoreSlim _slots;
private readonly SemaphoreSlim _writeLock = new(1, 1);
private readonly Stack<SqliteConnection> _idle = new();
private readonly Lock _gate = new();
private bool _disposed;
private SqliteDatabase(SqliteSettings settings)
{
_memory = settings.IsMemory;
if (_memory)
{
_filename = $"file:titano-{Guid.NewGuid():N}?mode=memory&cache=shared";
_maxConnections = 1;
}
else
{
Path = System.IO.Path.GetFullPath(settings.DataSource);
var directory = System.IO.Path.GetDirectoryName(Path);
if (!string.IsNullOrEmpty(directory)) Directory.CreateDirectory(directory);
_filename = Path;
_maxConnections = settings.PoolSize;
}
_slots = new SemaphoreSlim(_maxConnections, _maxConnections);
}
public Dialect Dialect => Dialect.Sqlite;
/// <summary>Full path of the database file; null for an in-memory database.</summary>
public string? Path { get; }
/// <summary>Version string of the loaded SQLite library, e.g. "3.45.1".</summary>
public static string LibraryVersion
{
get
{
EnsureLibrary();
unsafe
{
return Utf8(sqlite3_libversion()) ?? "?";
}
}
}
internal static SqliteDatabase Open(SqliteSettings settings)
{
EnsureLibrary();
var database = new SqliteDatabase(settings);
// The first connection validates the path, switches the file to WAL and keeps a memory database alive.
database._idle.Push(database.CreateConnection());
return database;
}
public async Task<IDbSession> OpenAsync(CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
await _slots.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
SqliteConnection? connection;
lock (_gate) _idle.TryPop(out connection);
return new SqliteSession(this, connection ?? CreateConnection());
}
catch
{
_slots.Release();
throw;
}
}
/// <summary>
/// Writes a consistent copy with <c>VACUUM INTO</c> to <paramref name="directory"/> as
/// <c>&lt;name&gt;-yyyyMMdd-HHmmss-fff.db</c> and deletes all but the <paramref name="keep"/> newest copies.
/// Readers and writers continue meanwhile. Returns the new file.
/// </summary>
public async Task<string> BackupAsync(string directory, int keep = 3, CancellationToken cancellationToken = default)
{
ArgumentOutOfRangeException.ThrowIfLessThan(keep, 1);
Directory.CreateDirectory(directory);
var stem = BackupStem;
string target;
while (true)
{
target = System.IO.Path.Combine(directory, string.Create(CultureInfo.InvariantCulture, $"{stem}-{DateTime.UtcNow:yyyyMMdd-HHmmss-fff}.db"));
if (!File.Exists(target)) break;
await Task.Delay(2, cancellationToken).ConfigureAwait(false);
}
var temp = target + ".tmp";
await using (var session = (SqliteSession)await OpenAsync(cancellationToken).ConfigureAwait(false))
await Task.Run(() => session.VacuumInto(temp, cancellationToken), cancellationToken).ConfigureAwait(false);
File.Move(temp, target);
var pattern = new Regex("^" + Regex.Escape(stem) + @"-\d{8}-\d{6}-\d{3}\.db$", RegexOptions.CultureInvariant);
var backups = Directory.EnumerateFiles(directory)
.Where(f => pattern.IsMatch(System.IO.Path.GetFileName(f)))
.OrderByDescending(f => System.IO.Path.GetFileName(f), StringComparer.Ordinal)
.ToList();
foreach (var old in backups.Skip(keep)) File.Delete(old);
Log.Info(LogCategory, $"Backup written to {target}");
return target;
}
/// <summary>
/// Replaces the database file with a backup after checking it with <c>PRAGMA quick_check</c>. Waits until
/// every session of this instance is returned; no other process may have the file open.
/// </summary>
public async Task RestoreAsync(string backupPath, CancellationToken cancellationToken = default)
{
if (Path is null) throw new NotSupportedException("An in-memory database cannot be restored.");
if (!File.Exists(backupPath)) throw new FileNotFoundException("Backup file not found.", backupPath);
Validate(backupPath);
await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
var taken = 0;
try
{
for (; taken < _maxConnections; taken++) await _slots.WaitAsync(cancellationToken).ConfigureAwait(false);
lock (_gate)
{
while (_idle.TryPop(out var connection)) connection.Dispose();
}
var temp = AtomicFile.TempPathFor(Path);
File.Copy(backupPath, temp);
// A WAL left behind belongs to the old file and would be replayed onto the restored one.
File.Delete(Path + "-wal");
File.Delete(Path + "-shm");
AtomicFile.Commit(temp, Path);
Log.Info(LogCategory, $"Database restored from {backupPath}");
}
finally
{
if (taken > 0) _slots.Release(taken);
_writeLock.Release();
}
}
public ValueTask DisposeAsync()
{
lock (_gate)
{
if (_disposed) return ValueTask.CompletedTask;
_disposed = true;
while (_idle.TryPop(out var connection)) connection.Dispose();
}
return ValueTask.CompletedTask;
}
internal Task AcquireWriteAsync(CancellationToken cancellationToken) => _writeLock.WaitAsync(cancellationToken);
internal void ReleaseWrite() => _writeLock.Release();
/// <summary>Takes back a session's connection; one left inside a transaction is rolled back or dropped.</summary>
internal void Return(SqliteConnection connection)
{
try
{
if (!connection.IsAutoCommit)
{
try
{
connection.Exec("ROLLBACK");
}
catch (SqliteException ex)
{
Log.Warning(LogCategory, "Dropping a connection whose transaction could not be rolled back.", ex);
connection.Dispose();
return;
}
}
lock (_gate)
{
if (_disposed) connection.Dispose();
else _idle.Push(connection);
}
}
finally
{
_slots.Release();
}
}
private string BackupStem => Path is null ? "titano" : System.IO.Path.GetFileNameWithoutExtension(Path);
private SqliteConnection CreateConnection() => SqliteConnection.Open(_filename, _memory, BusyTimeoutMs);
private static void EnsureLibrary()
{
EnsureResolver();
int version;
try
{
version = sqlite3_libversion_number();
}
catch (DllNotFoundException ex)
{
throw new NotSupportedException("The system SQLite library was not found (winsqlite3.dll, libsqlite3.so.0 or libsqlite3.dylib).", ex);
}
if (version < MinimumVersionNumber)
throw new NotSupportedException($"SQLite {version / 1_000_000}.{version / 1000 % 1000}.{version % 1000} is too old; 3.31 or newer is required.");
}
private static void Validate(string backupPath)
{
try
{
using var connection = SqliteConnection.OpenReadOnly(backupPath);
var statement = connection.Rent("PRAGMA quick_check");
try
{
var rc = statement.Step();
if (rc != SQLITE_ROW) throw connection.Error(rc);
var result = statement.ReadRow(statement.ReadColumns()).GetStringOrNull(0);
if (result != "ok") throw new InvalidDataException($"The backup failed its integrity check: {result}");
}
finally
{
connection.Return(statement);
}
}
catch (SqliteException ex)
{
throw new InvalidDataException("The file is not a readable SQLite database.", ex);
}
}
}
+19
View File
@@ -0,0 +1,19 @@
namespace Titano.Data.Sqlite;
/// <summary>An error returned by SQLite, with its primary and extended result codes.</summary>
public sealed class SqliteException(string message, int extendedResultCode) : DatabaseException(message)
{
/// <summary>Primary result code (low byte), e.g. 19 = SQLITE_CONSTRAINT.</summary>
public int ResultCode => ExtendedResultCode & 0xFF;
/// <summary>Extended result code, e.g. 2067 = SQLITE_CONSTRAINT_UNIQUE.</summary>
public int ExtendedResultCode { get; } = extendedResultCode;
public override int ErrorCode => ExtendedResultCode;
public override bool IsTransient => ResultCode is SqliteNative.SQLITE_BUSY or SqliteNative.SQLITE_LOCKED;
public override bool IsUniqueViolation => ExtendedResultCode is SqliteNative.SQLITE_CONSTRAINT_UNIQUE or SqliteNative.SQLITE_CONSTRAINT_PRIMARYKEY;
public override bool IsForeignKeyViolation => ExtendedResultCode == SqliteNative.SQLITE_CONSTRAINT_FOREIGNKEY;
}
+104
View File
@@ -0,0 +1,104 @@
using System.Reflection;
using System.Runtime.InteropServices;
namespace Titano.Data.Sqlite;
/// <summary>
/// P/Invoke surface of the system SQLite library: <c>winsqlite3.dll</c> (Windows 10 1709+), <c>libsqlite3.so.0</c>
/// (Linux) or <c>libsqlite3.dylib</c> (macOS). Strings cross the boundary as UTF-8 encoded by hand; the default
/// calling convention matches winsqlite3's <c>__stdcall</c> exports on x86 and is cdecl elsewhere.
/// </summary>
internal static unsafe class SqliteNative
{
private const string Library = "titano-sqlite3";
private static int _resolverInstalled;
public const int SQLITE_OK = 0;
public const int SQLITE_ERROR = 1;
public const int SQLITE_INTERRUPT = 9;
public const int SQLITE_BUSY = 5;
public const int SQLITE_LOCKED = 6;
public const int SQLITE_CONSTRAINT = 19;
public const int SQLITE_ROW = 100;
public const int SQLITE_DONE = 101;
public const int SQLITE_CONSTRAINT_FOREIGNKEY = SQLITE_CONSTRAINT | (3 << 8);
public const int SQLITE_CONSTRAINT_PRIMARYKEY = SQLITE_CONSTRAINT | (6 << 8);
public const int SQLITE_CONSTRAINT_UNIQUE = SQLITE_CONSTRAINT | (8 << 8);
public const int SQLITE_OPEN_READONLY = 0x00000001;
public const int SQLITE_OPEN_READWRITE = 0x00000002;
public const int SQLITE_OPEN_CREATE = 0x00000004;
public const int SQLITE_OPEN_URI = 0x00000040;
public const int SQLITE_OPEN_NOMUTEX = 0x00008000;
public const int SQLITE_INTEGER = 1;
public const int SQLITE_FLOAT = 2;
public const int SQLITE_TEXT = 3;
public const int SQLITE_BLOB = 4;
public const int SQLITE_NULL = 5;
/// <summary>Destructor sentinel that makes SQLite copy bound text/blobs before the call returns.</summary>
public static readonly nint SQLITE_TRANSIENT = -1;
/// <summary>Routes the logical library name to the platform's system SQLite (once per process).</summary>
public static void EnsureResolver()
{
if (Interlocked.Exchange(ref _resolverInstalled, 1) == 0)
NativeLibrary.SetDllImportResolver(typeof(SqliteNative).Assembly, Resolve);
}
private static nint Resolve(string name, Assembly assembly, DllImportSearchPath? searchPath)
{
if (name != Library) return 0;
string[] candidates = OperatingSystem.IsWindows() ? ["winsqlite3.dll"]
: OperatingSystem.IsMacOS() ? ["libsqlite3.dylib", "/usr/lib/libsqlite3.dylib"]
: ["libsqlite3.so.0", "libsqlite3.so"];
foreach (var candidate in candidates)
{
if (NativeLibrary.TryLoad(candidate, assembly, searchPath, out var handle)) return handle;
}
return 0;
}
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_libversion_number();
[DllImport(Library, ExactSpelling = true)] public static extern byte* sqlite3_libversion();
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_open_v2(byte* filename, out nint db, int flags, byte* vfs);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_close_v2(nint db);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_extended_result_codes(nint db, int onoff);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_busy_timeout(nint db, int ms);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_exec(nint db, byte* sql, nint callback, nint arg, out byte* errmsg);
[DllImport(Library, ExactSpelling = true)] public static extern void sqlite3_free(void* p);
[DllImport(Library, ExactSpelling = true)] public static extern byte* sqlite3_errmsg(nint db);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_extended_errcode(nint db);
[DllImport(Library, ExactSpelling = true)] public static extern void sqlite3_interrupt(nint db);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_changes(nint db);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_total_changes(nint db);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_get_autocommit(nint db);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_prepare_v2(nint db, byte* sql, int nBytes, out nint stmt, out byte* tail);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_step(nint stmt);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_reset(nint stmt);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_clear_bindings(nint stmt);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_finalize(nint stmt);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_stmt_readonly(nint stmt);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_parameter_count(nint stmt);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_null(nint stmt, int index);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_int64(nint stmt, int index, long value);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_double(nint stmt, int index, double value);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_text(nint stmt, int index, byte* text, int nBytes, nint destructor);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_bind_blob(nint stmt, int index, void* data, int nBytes, nint destructor);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_column_count(nint stmt);
[DllImport(Library, ExactSpelling = true)] public static extern byte* sqlite3_column_name(nint stmt, int index);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_column_type(nint stmt, int index);
[DllImport(Library, ExactSpelling = true)] public static extern long sqlite3_column_int64(nint stmt, int index);
[DllImport(Library, ExactSpelling = true)] public static extern double sqlite3_column_double(nint stmt, int index);
[DllImport(Library, ExactSpelling = true)] public static extern byte* sqlite3_column_text(nint stmt, int index);
[DllImport(Library, ExactSpelling = true)] public static extern void* sqlite3_column_blob(nint stmt, int index);
[DllImport(Library, ExactSpelling = true)] public static extern int sqlite3_column_bytes(nint stmt, int index);
/// <summary>Decodes a NUL-terminated UTF-8 string owned by SQLite.</summary>
public static string? Utf8(byte* p) => p is null ? null : Marshal.PtrToStringUTF8((nint)p);
}
+315
View File
@@ -0,0 +1,315 @@
using System.Runtime.CompilerServices;
using System.Text;
using static Titano.Data.Sqlite.SqliteNative;
namespace Titano.Data.Sqlite;
/// <summary>
/// A pooled SQLite connection. Statements that write take the database write lock for their duration when no
/// transaction holds it already; SQLITE_BUSY/LOCKED from other processes is retried a few times outside
/// transactions. Cancellation interrupts the running statement with <c>sqlite3_interrupt</c>.
/// </summary>
internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection connection) : IDbSession
{
private const int MaxBusyRetries = 3;
private SqliteTransaction? _transaction;
private bool _disposed;
public Dialect Dialect => Dialect.Sqlite;
public bool InTransaction => _transaction is not null;
public async Task<int> ExecuteAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
cancellationToken.ThrowIfCancellationRequested();
var statement = connection.Rent(sql);
var locked = false;
try
{
statement.Bind(parameters);
if (!statement.IsReadOnly && _transaction is null)
{
await database.AcquireWriteAsync(cancellationToken).ConfigureAwait(false);
locked = true;
}
using var interrupt = RegisterInterrupt(cancellationToken);
var before = connection.TotalChanges;
while (await StepAsync(statement, _transaction is null, cancellationToken).ConfigureAwait(false) == SQLITE_ROW)
{
}
// sqlite3_changes keeps the last DML count across DDL; only trust it when this statement changed rows.
return connection.TotalChanges != before ? connection.Changes : 0;
}
finally
{
connection.Return(statement);
if (locked) database.ReleaseWrite();
}
}
public async IAsyncEnumerable<DbRow> QueryAsync(string sql, DbParam[] parameters, [EnumeratorCancellation] CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
cancellationToken.ThrowIfCancellationRequested();
var statement = connection.Rent(sql);
var locked = false;
try
{
statement.Bind(parameters);
if (!statement.IsReadOnly && _transaction is null)
{
await database.AcquireWriteAsync(cancellationToken).ConfigureAwait(false);
locked = true;
}
using var interrupt = RegisterInterrupt(cancellationToken);
DbColumns? columns = null;
var retry = _transaction is null;
while (await StepAsync(statement, retry, cancellationToken).ConfigureAwait(false) == SQLITE_ROW)
{
retry = false; // restarting after rows were yielded would repeat them
columns ??= statement.ReadColumns();
yield return statement.ReadRow(columns);
cancellationToken.ThrowIfCancellationRequested();
}
}
finally
{
connection.Return(statement);
if (locked) database.ReleaseWrite();
}
}
public async Task ExecuteScriptAsync(string script, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
cancellationToken.ThrowIfCancellationRequested();
var locked = _transaction is null;
if (locked) await database.AcquireWriteAsync(cancellationToken).ConfigureAwait(false);
try
{
using var interrupt = RegisterInterrupt(cancellationToken);
connection.Exec(script);
}
catch (SqliteException ex) when (ex.ResultCode == SQLITE_INTERRUPT && cancellationToken.IsCancellationRequested)
{
throw new OperationCanceledException(ex.Message, ex, cancellationToken);
}
finally
{
if (locked) database.ReleaseWrite();
}
}
public async Task<IDbTransaction> BeginAsync(CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_transaction is not null) throw new InvalidOperationException("A transaction is already active on this session.");
await database.AcquireWriteAsync(cancellationToken).ConfigureAwait(false);
try
{
await RunAsync("BEGIN IMMEDIATE", retryBusy: true, cancellationToken).ConfigureAwait(false);
}
catch
{
database.ReleaseWrite();
throw;
}
return _transaction = new SqliteTransaction(this);
}
public async Task<long> BulkInsertAsync(string table, IReadOnlyList<string> columns, IAsyncEnumerable<object?[]> rows, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (columns.Count == 0) throw new ArgumentException("At least one column is required.", nameof(columns));
// 999 is the variable limit of SQLite builds before 3.32.
var rowsPerStatement = Math.Clamp(999 / columns.Count, 1, 100);
var buffer = new object?[rowsPerStatement * columns.Count];
var ownTransaction = _transaction is null ? await BeginAsync(cancellationToken).ConfigureAwait(false) : null;
try
{
long total = 0;
var buffered = 0;
using (RegisterInterrupt(cancellationToken))
{
await foreach (var row in rows.WithCancellation(cancellationToken).ConfigureAwait(false))
{
if (row.Length != columns.Count)
throw new ArgumentException($"A row has {row.Length} values for {columns.Count} columns.", nameof(rows));
Array.Copy(row, 0, buffer, buffered * columns.Count, row.Length);
if (++buffered == rowsPerStatement)
{
await InsertBufferedAsync(table, columns, buffer, buffered, cancellationToken).ConfigureAwait(false);
total += buffered;
buffered = 0;
}
}
if (buffered > 0)
{
await InsertBufferedAsync(table, columns, buffer, buffered, cancellationToken).ConfigureAwait(false);
total += buffered;
}
}
if (ownTransaction is not null) await ownTransaction.CommitAsync(cancellationToken).ConfigureAwait(false);
return total;
}
finally
{
if (ownTransaction is not null) await ownTransaction.DisposeAsync().ConfigureAwait(false);
}
}
public async ValueTask DisposeAsync()
{
if (_disposed) return;
_disposed = true;
if (_transaction is { } transaction)
{
try
{
await EndTransactionAsync(transaction, commit: false, CancellationToken.None).ConfigureAwait(false);
}
catch (SqliteException)
{
// The pool rolls the connection back or drops it below.
}
if (_transaction is not null)
{
_transaction = null;
database.ReleaseWrite();
}
}
database.Return(connection);
}
/// <summary>Ends <paramref name="transaction"/> if it is still the active one; a failed COMMIT leaves it open for rollback.</summary>
internal async Task EndTransactionAsync(SqliteTransaction transaction, bool commit, CancellationToken cancellationToken)
{
if (_transaction != transaction) return;
try
{
await RunAsync(commit ? "COMMIT" : "ROLLBACK", retryBusy: commit, cancellationToken).ConfigureAwait(false);
}
finally
{
if (connection.IsAutoCommit)
{
_transaction = null;
database.ReleaseWrite();
}
}
}
/// <summary>Runs <c>VACUUM INTO</c> (backups); it only reads, so no write lock is taken.</summary>
internal void VacuumInto(string path, CancellationToken cancellationToken)
{
var statement = connection.Rent("VACUUM INTO $1");
try
{
statement.Bind([path]);
using var interrupt = RegisterInterrupt(cancellationToken);
var rc = statement.Step();
if (rc == SQLITE_DONE) return;
if ((rc & 0xFF) == SQLITE_INTERRUPT && cancellationToken.IsCancellationRequested) throw new OperationCanceledException(cancellationToken);
throw connection.Error(rc);
}
finally
{
connection.Return(statement);
}
}
private async Task InsertBufferedAsync(string table, IReadOnlyList<string> columns, object?[] buffer, int rowCount, CancellationToken cancellationToken)
{
var statement = connection.Rent(InsertSql(table, columns, rowCount));
try
{
for (var i = 0; i < rowCount * columns.Count; i++) statement.BindValue(i + 1, buffer[i]);
await StepAsync(statement, retryBusy: false, cancellationToken).ConfigureAwait(false);
}
finally
{
connection.Return(statement);
}
}
private static string InsertSql(string table, IReadOnlyList<string> columns, int rowCount)
{
var sb = new StringBuilder("INSERT INTO ").Append(SqlDialect.QuoteIdentifier(table)).Append(" (");
for (var c = 0; c < columns.Count; c++) sb.Append(c > 0 ? ", " : string.Empty).Append(SqlDialect.QuoteIdentifier(columns[c]));
sb.Append(") VALUES ");
var n = 1;
for (var r = 0; r < rowCount; r++)
{
sb.Append(r > 0 ? ", (" : "(");
for (var c = 0; c < columns.Count; c++) sb.Append(c > 0 ? ", ?" : "?").Append(n++);
sb.Append(')');
}
return sb.ToString();
}
private async Task RunAsync(string sql, bool retryBusy, CancellationToken cancellationToken)
{
var statement = connection.Rent(sql);
try
{
await StepAsync(statement, retryBusy, cancellationToken).ConfigureAwait(false);
}
finally
{
connection.Return(statement);
}
}
private async ValueTask<int> StepAsync(SqliteStatement statement, bool retryBusy, CancellationToken cancellationToken)
{
for (var attempt = 0; ; attempt++)
{
var rc = statement.Step();
if (rc is SQLITE_ROW or SQLITE_DONE) return rc;
var primary = rc & 0xFF;
if (primary == SQLITE_INTERRUPT && cancellationToken.IsCancellationRequested)
throw new OperationCanceledException(cancellationToken);
if (retryBusy && primary is SQLITE_BUSY or SQLITE_LOCKED && attempt < MaxBusyRetries)
{
// busy_timeout already waited; another process holds the lock for long. Back off and restart.
statement.Rewind();
await Task.Delay(50 * (attempt + 1) + Random.Shared.Next(50), cancellationToken).ConfigureAwait(false);
continue;
}
throw connection.Error(rc);
}
}
private CancellationTokenRegistration RegisterInterrupt(CancellationToken cancellationToken) =>
cancellationToken.CanBeCanceled
? cancellationToken.UnsafeRegister(static state => ((SqliteConnection)state!).Interrupt(), connection)
: default;
}
/// <summary>A <c>BEGIN IMMEDIATE</c> transaction holding the database write lock until it ends.</summary>
internal sealed class SqliteTransaction(SqliteSession session) : IDbTransaction
{
private bool _completed;
public async Task CommitAsync(CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(_completed, this);
await session.EndTransactionAsync(this, commit: true, cancellationToken).ConfigureAwait(false);
_completed = true;
}
public async Task RollbackAsync(CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(_completed, this);
_completed = true;
await session.EndTransactionAsync(this, commit: false, cancellationToken).ConfigureAwait(false);
}
public async ValueTask DisposeAsync()
{
if (_completed) return;
_completed = true;
await session.EndTransactionAsync(this, commit: false, CancellationToken.None).ConfigureAwait(false);
}
}
+170
View File
@@ -0,0 +1,170 @@
using System.Buffers;
using System.Globalization;
using System.Text;
using static Titano.Data.Sqlite.SqliteNative;
namespace Titano.Data.Sqlite;
/// <summary>A prepared statement owned by one <see cref="SqliteConnection"/>; reused through its statement cache.</summary>
internal sealed unsafe class SqliteStatement : IDisposable
{
private const int StackTextBytes = 256;
private readonly SqliteConnection _connection;
public SqliteStatement(SqliteConnection connection, nint handle, string sql)
{
_connection = connection;
Handle = handle;
Sql = sql;
IsReadOnly = sqlite3_stmt_readonly(handle) != 0;
ParameterCount = sqlite3_bind_parameter_count(handle);
}
public nint Handle { get; private set; }
/// <summary>The SQL text as the caller wrote it (cache key).</summary>
public string Sql { get; }
/// <summary>The statement does not write the database (no write lock needed).</summary>
public bool IsReadOnly { get; }
/// <summary>Highest parameter number used by the statement.</summary>
public int ParameterCount { get; }
public bool InUse { get; set; }
public bool Cached { get; set; }
public void Bind(DbParam[] parameters)
{
if (parameters.Length != ParameterCount)
throw new ArgumentException($"The statement uses {ParameterCount} parameter(s) but {parameters.Length} were supplied.", nameof(parameters));
for (var i = 0; i < parameters.Length; i++) Bind(i + 1, parameters[i].Value, parameters[i].Type);
}
/// <summary>Binds a raw CLR value (bulk insert rows); the type is inferred like <see cref="DbParam"/> does.</summary>
public void BindValue(int index, object? value) => Bind(index, value, DbValueType.Auto);
public int Step() => sqlite3_step(Handle);
/// <summary>Rewinds for another execution with the same bindings.</summary>
public void Rewind() => sqlite3_reset(Handle);
/// <summary>Rewinds after an execution; a step error was already reported, so the code is ignored.</summary>
public void Reset()
{
sqlite3_reset(Handle);
sqlite3_clear_bindings(Handle);
}
public DbColumns ReadColumns()
{
var names = new string[sqlite3_column_count(Handle)];
for (var i = 0; i < names.Length; i++) names[i] = Utf8(sqlite3_column_name(Handle, i)) ?? string.Empty;
return new DbColumns(names);
}
public DbRow ReadRow(DbColumns columns)
{
var values = new object?[columns.Names.Length];
for (var i = 0; i < values.Length; i++)
{
values[i] = sqlite3_column_type(Handle, i) switch
{
SQLITE_INTEGER => sqlite3_column_int64(Handle, i),
SQLITE_FLOAT => sqlite3_column_double(Handle, i),
SQLITE_TEXT => ReadText(i),
SQLITE_BLOB => ReadBlob(i),
_ => null,
};
}
return new DbRow(columns, values);
}
public void Dispose()
{
if (Handle != 0)
{
sqlite3_finalize(Handle);
Handle = 0;
}
}
private void Bind(int index, object? value, DbValueType type)
{
var rc = value switch
{
null => sqlite3_bind_null(Handle, index),
string s => BindText(index, s),
long l => sqlite3_bind_int64(Handle, index, l),
int n => sqlite3_bind_int64(Handle, index, n),
double d => sqlite3_bind_double(Handle, index, d),
bool b => sqlite3_bind_int64(Handle, index, b ? 1 : 0),
Guid g => BindFormatted(index, g, "D"),
DateTimeOffset o => BindFormatted(index, o.UtcDateTime, "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'"),
DateTime d when type == DbValueType.LocalDateTime || (type == DbValueType.Auto && d.Kind == DateTimeKind.Unspecified)
=> BindFormatted(index, d, "yyyy-MM-dd'T'HH:mm:ss.ffffff"),
DateTime d => BindFormatted(index, d.ToUniversalTime(), "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'"),
byte[] b => BindBlob(index, b),
_ => BindNormalized(index, new DbParam(value)),
};
if (rc != SQLITE_OK) throw _connection.Error(rc);
}
private int BindNormalized(int index, DbParam p)
{
Bind(index, p.Value, p.Type);
return SQLITE_OK;
}
private int BindText(int index, string s)
{
if (s.Length <= StackTextBytes / 3)
{
var buffer = stackalloc byte[StackTextBytes];
var n = Encoding.UTF8.GetBytes(s, new Span<byte>(buffer, StackTextBytes));
return sqlite3_bind_text(Handle, index, buffer, n, SQLITE_TRANSIENT);
}
var rented = ArrayPool<byte>.Shared.Rent(Encoding.UTF8.GetByteCount(s));
try
{
var n = Encoding.UTF8.GetBytes(s, rented);
fixed (byte* p = rented) return sqlite3_bind_text(Handle, index, p, n, SQLITE_TRANSIENT);
}
finally
{
ArrayPool<byte>.Shared.Return(rented);
}
}
private int BindFormatted<T>(int index, T value, string format) where T : IUtf8SpanFormattable
{
var buffer = stackalloc byte[64];
var span = new Span<byte>(buffer, 64);
if (!value.TryFormat(span, out var n, format, CultureInfo.InvariantCulture))
throw new FormatException($"Cannot format {value} for SQLite.");
return sqlite3_bind_text(Handle, index, buffer, n, SQLITE_TRANSIENT);
}
private int BindBlob(int index, byte[] data)
{
byte empty = 0;
// A null pointer would bind NULL; an empty blob needs any valid address.
if (data.Length == 0) return sqlite3_bind_blob(Handle, index, &empty, 0, SQLITE_TRANSIENT);
fixed (byte* p = data) return sqlite3_bind_blob(Handle, index, p, data.Length, SQLITE_TRANSIENT);
}
private string ReadText(int column)
{
var p = sqlite3_column_text(Handle, column);
var n = sqlite3_column_bytes(Handle, column);
return n == 0 ? string.Empty : Encoding.UTF8.GetString(p, n);
}
private byte[] ReadBlob(int column)
{
var p = (byte*)sqlite3_column_blob(Handle, column);
var n = sqlite3_column_bytes(Handle, column);
return n == 0 ? [] : new ReadOnlySpan<byte>(p, n).ToArray();
}
}