diff --git a/src/Titano.Data/DatabaseOptions.cs b/src/Titano.Data/DatabaseOptions.cs
new file mode 100644
index 00000000..6d857a27
--- /dev/null
+++ b/src/Titano.Data/DatabaseOptions.cs
@@ -0,0 +1,54 @@
+using Titano.Data.Postgres;
+using Titano.Data.Sqlite;
+
+namespace Titano.Data;
+
+/// Which engine to open and how to reach it.
+///
+/// SQLite: Data Source=<path>|:memory:;Pool Size=4.
+/// PostgreSQL: Host=…;Port=5432;Database=…;Username=…;Password=…;SslMode=disable|prefer|require|verify-full
+/// plus the optional keys listed on .
+///
+public sealed record DatabaseOptions
+{
+ public required Dialect Dialect { get; init; }
+
+ public required string ConnectionString { get; init; }
+
+ public static DatabaseOptions Sqlite(string path) => new()
+ {
+ Dialect = Dialect.Sqlite,
+ ConnectionString = "Data Source='" + path.Replace("'", "''", StringComparison.Ordinal) + "'",
+ };
+
+ /// A private in-memory SQLite database that lives until the is disposed.
+ public static DatabaseOptions SqliteInMemory() => new() { Dialect = Dialect.Sqlite, ConnectionString = "Data Source=:memory:" };
+
+ public static DatabaseOptions Postgres(string connectionString) => new() { Dialect = Dialect.Postgres, ConnectionString = connectionString };
+
+ ///
+ /// Infers the dialect: a string with Host/Server is PostgreSQL; Data Source or a bare
+ /// path (no =) is SQLite.
+ ///
+ public static DatabaseOptions Parse(string connectionString)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(connectionString);
+ if (!connectionString.Contains('=', StringComparison.Ordinal)) return Sqlite(connectionString.Trim());
+ var cs = new ConnectionString(connectionString);
+ if (cs.Contains("Host") || cs.Contains("Server")) return Postgres(connectionString);
+ if (cs.Contains("Data Source") || cs.Contains("Filename")) return new() { Dialect = Dialect.Sqlite, ConnectionString = connectionString };
+ throw new FormatException("The connection string names neither a PostgreSQL host nor a SQLite data source.");
+ }
+}
+
+/// Builds the implementation for a set of options.
+public static class DatabaseFactory
+{
+ /// Creates the database object; SQLite opens the file now, PostgreSQL connects on the first session.
+ public static IDatabase Open(DatabaseOptions options) => options.Dialect switch
+ {
+ Dialect.Sqlite => SqliteDatabase.Open(SqliteSettings.Parse(options.ConnectionString)),
+ Dialect.Postgres => new PostgresDatabase(PostgresSettings.Parse(options.ConnectionString)),
+ _ => throw new ArgumentOutOfRangeException(nameof(options), options.Dialect, "Unknown dialect."),
+ };
+}
diff --git a/src/Titano.Data/Postgres/PgAuthentication.cs b/src/Titano.Data/Postgres/PgAuthentication.cs
new file mode 100644
index 00000000..f3933958
--- /dev/null
+++ b/src/Titano.Data/Postgres/PgAuthentication.cs
@@ -0,0 +1,137 @@
+using System.Globalization;
+using System.Security.Authentication;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace Titano.Data.Postgres;
+
+///
+/// Client side of SCRAM-SHA-256 (RFC 5802 / RFC 7677) as PostgreSQL uses it: no channel binding
+/// (n,, GS2 header) and an empty user name, since the server takes the user from the startup packet.
+///
+internal sealed class ScramSha256
+{
+ private readonly string _password;
+ private readonly string _username;
+ private readonly string _clientNonce;
+ private string? _clientFirstBare;
+ private byte[]? _expectedServerSignature;
+
+ public ScramSha256(string password, string username = "", string? clientNonce = null)
+ {
+ _password = password;
+ _username = username.Replace("=", "=3D", StringComparison.Ordinal).Replace(",", "=2C", StringComparison.Ordinal);
+ _clientNonce = clientNonce ?? Convert.ToBase64String(RandomNumberGenerator.GetBytes(18));
+ }
+
+ public const string Mechanism = "SCRAM-SHA-256";
+
+ public byte[] ClientFirstMessage()
+ {
+ _clientFirstBare = $"n={_username},r={_clientNonce}";
+ return Encoding.UTF8.GetBytes("n,," + _clientFirstBare);
+ }
+
+ /// Checks the server-first message and returns client-final with the proof.
+ public byte[] ClientFinalMessage(ReadOnlySpan serverFirst)
+ {
+ if (_clientFirstBare is null) throw new InvalidOperationException("ClientFirstMessage must be sent first.");
+ var serverFirstText = Encoding.UTF8.GetString(serverFirst);
+ string? nonce = null, salt = null, iterations = null;
+ foreach (var part in serverFirstText.Split(','))
+ {
+ if (part.StartsWith("r=", StringComparison.Ordinal)) nonce = part[2..];
+ else if (part.StartsWith("s=", StringComparison.Ordinal)) salt = part[2..];
+ else if (part.StartsWith("i=", StringComparison.Ordinal)) iterations = part[2..];
+ }
+ if (nonce is null || salt is null || iterations is null
+ || !nonce.StartsWith(_clientNonce, StringComparison.Ordinal) || nonce.Length == _clientNonce.Length
+ || !int.TryParse(iterations, NumberStyles.None, CultureInfo.InvariantCulture, out var count) || count < 1)
+ throw new AuthenticationException("Invalid SCRAM server-first message.");
+
+ var saltedPassword = Rfc2898DeriveBytes.Pbkdf2(
+ Encoding.UTF8.GetBytes(SaslPrep(_password)), Convert.FromBase64String(salt), count, HashAlgorithmName.SHA256, 32);
+ var clientKey = HMACSHA256.HashData(saltedPassword, "Client Key"u8);
+ var storedKey = SHA256.HashData(clientKey);
+ var withoutProof = "c=biws,r=" + nonce;
+ var authMessage = Encoding.UTF8.GetBytes(_clientFirstBare + "," + serverFirstText + "," + withoutProof);
+ var proof = HMACSHA256.HashData(storedKey, authMessage);
+ for (var i = 0; i < proof.Length; i++) proof[i] ^= clientKey[i];
+ _expectedServerSignature = HMACSHA256.HashData(HMACSHA256.HashData(saltedPassword, "Server Key"u8), authMessage);
+ return Encoding.UTF8.GetBytes(withoutProof + ",p=" + Convert.ToBase64String(proof));
+ }
+
+ /// Verifies the server signature, proving the server knows the password too.
+ public void VerifyServerFinal(ReadOnlySpan serverFinal)
+ {
+ var text = Encoding.UTF8.GetString(serverFinal);
+ if (text.StartsWith("e=", StringComparison.Ordinal)) throw new AuthenticationException("SCRAM authentication failed: " + text[2..]);
+ var end = text.IndexOf(',', StringComparison.Ordinal);
+ var value = text.StartsWith("v=", StringComparison.Ordinal) ? text[2..(end < 0 ? text.Length : end)] : null;
+ if (_expectedServerSignature is null || value is null
+ || !CryptographicOperations.FixedTimeEquals(Convert.FromBase64String(value), _expectedServerSignature))
+ throw new AuthenticationException("The server's SCRAM signature is invalid.");
+ }
+
+ ///
+ /// SASLprep (RFC 4013) as PostgreSQL applies it: non-ASCII spaces become U+0020, "mapped to nothing"
+ /// characters are dropped, then NFKC; a result with prohibited code points falls back to the raw password.
+ /// The unassigned-code-point and bidi checks are omitted.
+ ///
+ internal static string SaslPrep(string password)
+ {
+ var ascii = true;
+ foreach (var c in password)
+ {
+ if (c > 0x7F)
+ {
+ ascii = false;
+ break;
+ }
+ }
+ // Printable ASCII is unchanged by SASLprep; ASCII controls are prohibited, which also means "use raw".
+ if (ascii) return password;
+
+ var mapped = new StringBuilder(password.Length);
+ foreach (var rune in password.EnumerateRunes())
+ {
+ var v = rune.Value;
+ if (v is 0x00A0 or 0x1680 or (>= 0x2000 and <= 0x200B) or 0x202F or 0x205F or 0x3000) mapped.Append(' ');
+ else if (v is 0x00AD or 0x034F or 0x1806 or (>= 0x180B and <= 0x180D) or (>= 0x200C and <= 0x200D) or 0x2060
+ or (>= 0xFE00 and <= 0xFE0F) or 0xFEFF) continue;
+ else mapped.Append(rune.ToString());
+ }
+ var normalized = mapped.ToString().Normalize(NormalizationForm.FormKC);
+ foreach (var rune in normalized.EnumerateRunes())
+ {
+ if (IsProhibited(rune.Value)) return password;
+ }
+ return normalized;
+ }
+
+ private static bool IsProhibited(int v) =>
+ v < 0x20 || v is >= 0x7F and <= 0x9F // C.2.1, C.2.2 controls
+ || v is 0x06DD or 0x070F or 0x180E or 0x2028 or 0x2029 or (>= 0x2060 and <= 0x2063) // C.2.2
+ || v is >= 0x1D173 and <= 0x1D17A
+ || v is >= 0xE000 and <= 0xF8FF || v >= 0xF0000 // C.3 private use
+ || v is >= 0xFDD0 and <= 0xFDEF || (v & 0xFFFE) == 0xFFFE // C.4 non-characters
+ || v is >= 0xFFF9 and <= 0xFFFD // C.6
+ || v is >= 0x2FF0 and <= 0x2FFB // C.7
+ || v is 0x0340 or 0x0341 or 0x200E or 0x200F or (>= 0x202A and <= 0x202E) or (>= 0x206A and <= 0x206F) // C.8
+ || v is 0xE0001 or (>= 0xE0020 and <= 0xE007F); // C.9
+}
+
+/// PostgreSQL's MD5 password response: "md5" + md5hex(md5hex(password + user) + salt).
+internal static class PgMd5
+{
+ public static string Response(string username, string password, ReadOnlySpan salt)
+ {
+ var inner = Hex(MD5.HashData(Encoding.UTF8.GetBytes(password + username)));
+ var buffer = new byte[inner.Length + salt.Length];
+ Encoding.ASCII.GetBytes(inner, buffer);
+ salt.CopyTo(buffer.AsSpan(inner.Length));
+ return "md5" + Hex(MD5.HashData(buffer));
+ }
+
+ private static string Hex(byte[] bytes) => Convert.ToHexStringLower(bytes);
+}
diff --git a/src/Titano.Data/Postgres/PgConnector.cs b/src/Titano.Data/Postgres/PgConnector.cs
new file mode 100644
index 00000000..59c5f38d
--- /dev/null
+++ b/src/Titano.Data/Postgres/PgConnector.cs
@@ -0,0 +1,1025 @@
+using System.Buffers.Binary;
+using System.Globalization;
+using System.Net.Security;
+using System.Net.Sockets;
+using System.Runtime.CompilerServices;
+using System.Runtime.ExceptionServices;
+using System.Security.Cryptography.X509Certificates;
+using System.Text;
+using Titano.Core.Diagnostics;
+
+namespace Titano.Data.Postgres;
+
+/// A NOTIFY delivered to a listening connection.
+public sealed record PgNotification(int ProcessId, string Channel, string Payload);
+
+///
+/// One physical connection speaking protocol v3 (BRIEF §6.3): startup and authentication, simple and extended
+/// query with a per-connection LRU of named prepared statements, COPY FROM STDIN, notices and notifications,
+/// and cancellation through a CancelRequest on a second socket. Not thread-safe; the pool lends it to one
+/// session at a time.
+///
+internal sealed class PgConnector : IAsyncDisposable
+{
+ private const int ProtocolVersion3 = 196608;
+ private const int SslRequestCode = 80877103;
+ private const int CancelRequestCode = 80877102;
+ private const int CopyChunkBytes = 64 * 1024;
+ private const string LogCategory = "Data.Postgres";
+ private static readonly TimeSpan CancelGracePeriod = TimeSpan.FromSeconds(5);
+ private static readonly DbColumns NoColumns = new([]);
+
+ private readonly PostgresSettings _settings;
+ private readonly Socket _socket;
+ private readonly Stream _stream;
+ private readonly PgWriteBuffer _write = new();
+ private readonly Dictionary> _statements = new(StringComparer.Ordinal);
+ private readonly LinkedList _statementLru = new();
+ private readonly List _statementsToClose = [];
+ private readonly Dictionary _serverParameters = new(StringComparer.Ordinal);
+ private byte[] _read = new byte[16 * 1024];
+ private int _readPos;
+ private int _readEnd;
+ private int _messageStart;
+ private int _messageLength;
+ private int _statementCounter;
+ private int _secretKey;
+ private long _idleSince;
+ private int _disposed;
+ private CancellationTokenSource _ioAbort = new();
+ private Task _pendingCancel = Task.CompletedTask;
+
+ private PgConnector(PostgresSettings settings, Socket socket, Stream stream)
+ {
+ _settings = settings;
+ _socket = socket;
+ _stream = stream;
+ }
+
+ public int ProcessId { get; private set; }
+
+ /// The connection failed or the server ended the session; it must be discarded.
+ public bool IsBroken { get; private set; }
+
+ /// Last ReadyForQuery status: 'I' idle, 'T' in transaction, 'E' failed transaction.
+ public char TransactionStatus { get; private set; } = 'I';
+
+ public TimeSpan IdleTime => TimeSpan.FromMilliseconds(Environment.TickCount64 - _idleSince);
+
+ public IReadOnlyDictionary ServerParameters => _serverParameters;
+
+ /// Receives NotificationResponse messages (listener connections).
+ public Action? NotificationReceived { get; set; }
+
+ private ReadOnlySpan Payload => _read.AsSpan(_messageStart, _messageLength);
+
+ public static async Task OpenAsync(PostgresSettings settings, CancellationToken cancellationToken)
+ {
+ using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ timeout.CancelAfter(settings.ConnectTimeout);
+ var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
+ Stream? stream = null;
+ try
+ {
+ await socket.ConnectAsync(settings.Host, settings.Port, timeout.Token).ConfigureAwait(false);
+ stream = new NetworkStream(socket, ownsSocket: false);
+ if (settings.SslMode != SslMode.Disable)
+ stream = await NegotiateTlsAsync(stream, settings, timeout.Token).ConfigureAwait(false);
+ var connector = new PgConnector(settings, socket, stream);
+ await connector.StartupAsync(timeout.Token).ConfigureAwait(false);
+ connector.MarkIdle();
+ return connector;
+ }
+ catch (Exception ex)
+ {
+ if (stream is not null) await stream.DisposeAsync().ConfigureAwait(false);
+ socket.Dispose();
+ if (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested)
+ throw new DatabaseConnectionException($"Timed out connecting to {settings.Host}:{settings.Port}.", ex);
+ if (ex is SocketException or IOException)
+ throw new DatabaseConnectionException($"Cannot connect to {settings.Host}:{settings.Port}: {ex.Message}", ex);
+ throw;
+ }
+ }
+
+ public void MarkIdle() => _idleSince = Environment.TickCount64;
+
+ /// Runs one statement with the extended protocol and returns the rows it changed.
+ public async Task ExecuteAsync(string sql, DbParam[] parameters, CancellationToken cancellationToken)
+ {
+ var op = StartOperation(sql, parameters, decodeRows: false, cancellationToken);
+ try
+ {
+ await SendExtendedAsync(op).ConfigureAwait(false);
+ while (await ReadRowAsync(op).ConfigureAwait(false) is not null)
+ {
+ }
+ return op.Affected;
+ }
+ finally
+ {
+ await EndOperationAsync(op).ConfigureAwait(false);
+ }
+ }
+
+ /// Streams the rows of one statement; abandoning the enumeration drains the rest of the response.
+ public async IAsyncEnumerable QueryAsync(string sql, DbParam[] parameters, [EnumeratorCancellation] CancellationToken cancellationToken)
+ {
+ var op = StartOperation(sql, parameters, decodeRows: true, cancellationToken);
+ try
+ {
+ await SendExtendedAsync(op).ConfigureAwait(false);
+ while (await ReadRowAsync(op).ConfigureAwait(false) is { } row) yield return row;
+ }
+ finally
+ {
+ await EndOperationAsync(op).ConfigureAwait(false);
+ }
+ }
+
+ /// Runs a simple-protocol query (scripts, transaction control) and returns the last command tag.
+ public async Task SimpleQueryAsync(string sql, CancellationToken cancellationToken)
+ {
+ var op = StartOperation(sql, [], decodeRows: false, cancellationToken);
+ try
+ {
+ WriteQuery(sql);
+ await FlushAsync(op).ConfigureAwait(false);
+ await DrainAsync(op).ConfigureAwait(false);
+ return op.Tag;
+ }
+ finally
+ {
+ await EndOperationAsync(op).ConfigureAwait(false);
+ }
+ }
+
+ /// True when SELECT 1 succeeds within the connect timeout; marks the connection broken otherwise.
+ public async Task PingAsync(CancellationToken cancellationToken)
+ {
+ using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ timeout.CancelAfter(_settings.ConnectTimeout);
+ try
+ {
+ await SimpleQueryAsync("SELECT 1", timeout.Token).ConfigureAwait(false);
+ return true;
+ }
+ catch (Exception ex) when (ex is DatabaseException or OperationCanceledException && !cancellationToken.IsCancellationRequested)
+ {
+ IsBroken = true;
+ return false;
+ }
+ }
+
+ ///
+ /// Streams rows through COPY … FROM STDIN in text format. A failing producer aborts the copy with
+ /// CopyFail, so the table is left untouched, and its exception is rethrown.
+ ///
+ public async Task CopyInAsync(string copySql, int columnCount, IAsyncEnumerable