Files
Chronos/src/Titano.Data/DbRow.cs
T
Claude a09aa16876 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
2026-10-02 09:40:33 +00:00

201 lines
8.5 KiB
C#

using System.Globalization;
namespace Titano.Data;
/// <summary>Column names of a result set, shared by all of its rows.</summary>
internal sealed class DbColumns(string[] names)
{
private Dictionary<string, int>? _ordinals;
public string[] Names { get; } = names;
public int GetOrdinal(string name)
{
if (_ordinals is null)
{
var map = new Dictionary<string, int>(Names.Length, StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < Names.Length; i++) map.TryAdd(Names[i], i);
_ordinals = map;
}
return _ordinals.TryGetValue(name, out var ordinal)
? ordinal
: throw new IndexOutOfRangeException($"No column named '{name}' in the result.");
}
}
/// <summary>
/// One materialised result row. Values keep the provider's natural CLR type (SQLite: long, double, string,
/// byte[]; PostgreSQL: decoded by type OID) and the typed getters convert between compatible forms, so the
/// same mapping code reads both dialects (e.g. a SQLite TEXT uuid through <see cref="GetGuid(int)"/>).
/// Rows stay valid after the enumeration that produced them ends.
/// </summary>
public sealed class DbRow
{
private readonly DbColumns _columns;
private readonly object?[] _values;
internal DbRow(DbColumns columns, object?[] values)
{
_columns = columns;
_values = values;
}
public int FieldCount => _values.Length;
public string GetName(int ordinal) => _columns.Names[ordinal];
/// <summary>Case-insensitive column lookup; the first column with that name wins.</summary>
public int GetOrdinal(string name) => _columns.GetOrdinal(name);
public bool IsNull(int ordinal) => _values[ordinal] is null;
public object? GetValue(int ordinal) => _values[ordinal];
public string GetString(int ordinal) => GetStringOrNull(ordinal) ?? throw NullValue(ordinal);
public int GetInt32(int ordinal) => GetInt32OrNull(ordinal) ?? throw NullValue(ordinal);
public long GetInt64(int ordinal) => GetInt64OrNull(ordinal) ?? throw NullValue(ordinal);
public double GetDouble(int ordinal) => GetDoubleOrNull(ordinal) ?? throw NullValue(ordinal);
public bool GetBool(int ordinal) => GetBoolOrNull(ordinal) ?? throw NullValue(ordinal);
public Guid GetGuid(int ordinal) => GetGuidOrNull(ordinal) ?? throw NullValue(ordinal);
public DateTimeOffset GetDateTimeOffset(int ordinal) => GetDateTimeOffsetOrNull(ordinal) ?? throw NullValue(ordinal);
public DateTime GetDateTime(int ordinal) => GetDateTimeOrNull(ordinal) ?? throw NullValue(ordinal);
public byte[] GetBytes(int ordinal) => GetBytesOrNull(ordinal) ?? throw NullValue(ordinal);
public string? GetStringOrNull(int ordinal) => _values[ordinal] switch
{
null => null,
string s => s,
Guid g => TextValues.FormatGuid(g),
DateTimeOffset o => TextValues.FormatTimestamp(o),
DateTime d => TextValues.FormatLocal(d),
byte[] => throw Mismatch(ordinal, "string"),
var v => Convert.ToString(v, CultureInfo.InvariantCulture),
};
public int? GetInt32OrNull(int ordinal) => _values[ordinal] switch
{
null => null,
int i => i,
var v => checked((int)ToInt64(ordinal, v)),
};
public long? GetInt64OrNull(int ordinal) => _values[ordinal] is { } v ? ToInt64(ordinal, v) : null;
public double? GetDoubleOrNull(int ordinal) => _values[ordinal] switch
{
null => null,
double d => d,
long l => l,
int i => i,
float f => f,
string s => double.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture),
_ => throw Mismatch(ordinal, "double"),
};
public bool? GetBoolOrNull(int ordinal) => _values[ordinal] switch
{
null => null,
bool b => b,
long l => l != 0,
int i => i != 0,
_ => throw Mismatch(ordinal, "bool"),
};
public Guid? GetGuidOrNull(int ordinal) => _values[ordinal] switch
{
null => null,
Guid g => g,
string s => Guid.Parse(s),
_ => throw Mismatch(ordinal, "Guid"),
};
/// <summary>Instants: timestamptz values, ISO-8601 text, or <c>timestamp</c> values taken as UTC.</summary>
public DateTimeOffset? GetDateTimeOffsetOrNull(int ordinal) => _values[ordinal] switch
{
null => null,
DateTimeOffset o => o,
string s => TextValues.ParseTimestamp(s),
DateTime d => new DateTimeOffset(DateTime.SpecifyKind(d, DateTimeKind.Utc)),
_ => throw Mismatch(ordinal, "DateTimeOffset"),
};
/// <summary>Wall-clock date-times (unspecified kind); instants are returned as UTC.</summary>
public DateTime? GetDateTimeOrNull(int ordinal) => _values[ordinal] switch
{
null => null,
DateTime d => d,
string s => TextValues.ParseLocal(s),
DateTimeOffset o => o.UtcDateTime,
DateOnly d => d.ToDateTime(TimeOnly.MinValue),
_ => throw Mismatch(ordinal, "DateTime"),
};
public byte[]? GetBytesOrNull(int ordinal) => _values[ordinal] switch
{
null => null,
byte[] b => b,
_ => throw Mismatch(ordinal, "byte[]"),
};
public string GetString(string name) => GetString(GetOrdinal(name));
public string? GetStringOrNull(string name) => GetStringOrNull(GetOrdinal(name));
public int GetInt32(string name) => GetInt32(GetOrdinal(name));
public int? GetInt32OrNull(string name) => GetInt32OrNull(GetOrdinal(name));
public long GetInt64(string name) => GetInt64(GetOrdinal(name));
public long? GetInt64OrNull(string name) => GetInt64OrNull(GetOrdinal(name));
public double GetDouble(string name) => GetDouble(GetOrdinal(name));
public double? GetDoubleOrNull(string name) => GetDoubleOrNull(GetOrdinal(name));
public bool GetBool(string name) => GetBool(GetOrdinal(name));
public bool? GetBoolOrNull(string name) => GetBoolOrNull(GetOrdinal(name));
public Guid GetGuid(string name) => GetGuid(GetOrdinal(name));
public Guid? GetGuidOrNull(string name) => GetGuidOrNull(GetOrdinal(name));
public DateTimeOffset GetDateTimeOffset(string name) => GetDateTimeOffset(GetOrdinal(name));
public DateTimeOffset? GetDateTimeOffsetOrNull(string name) => GetDateTimeOffsetOrNull(GetOrdinal(name));
public DateTime GetDateTime(string name) => GetDateTime(GetOrdinal(name));
public DateTime? GetDateTimeOrNull(string name) => GetDateTimeOrNull(GetOrdinal(name));
public byte[] GetBytes(string name) => GetBytes(GetOrdinal(name));
public byte[]? GetBytesOrNull(string name) => GetBytesOrNull(GetOrdinal(name));
/// <summary>
/// Generic read used by scalar helpers: string, int, long, double, bool, Guid, DateTimeOffset, DateTime,
/// byte[], their nullable forms and enums (from integers). A null reads as <c>default</c>.
/// </summary>
public T? Get<T>(int ordinal)
{
if (_values[ordinal] is null) return default;
var target = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
object value = target switch
{
_ when target == typeof(string) => GetString(ordinal),
_ when target == typeof(int) => GetInt32(ordinal),
_ when target == typeof(long) => GetInt64(ordinal),
_ when target == typeof(double) => GetDouble(ordinal),
_ when target == typeof(bool) => GetBool(ordinal),
_ when target == typeof(Guid) => GetGuid(ordinal),
_ when target == typeof(DateTimeOffset) => GetDateTimeOffset(ordinal),
_ when target == typeof(DateTime) => GetDateTime(ordinal),
_ when target == typeof(byte[]) => GetBytes(ordinal),
{ IsEnum: true } => Enum.ToObject(target, GetInt64(ordinal)),
_ => _values[ordinal] is T ? _values[ordinal]! : throw Mismatch(ordinal, target.Name),
};
return (T)value;
}
private long ToInt64(int ordinal, object value) => value switch
{
long l => l,
int i => i,
short s => s,
bool b => b ? 1 : 0,
double d when d == Math.Floor(d) && d is >= long.MinValue and < long.MaxValue => (long)d,
string s => long.Parse(s, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture),
_ => throw Mismatch(ordinal, "integer"),
};
private InvalidCastException NullValue(int ordinal) =>
new($"Column '{_columns.Names[ordinal]}' is NULL.");
private InvalidCastException Mismatch(int ordinal, string target) =>
new($"Column '{_columns.Names[ordinal]}' holds {_values[ordinal]!.GetType().Name}, which cannot be read as {target}.");
}