refactor(data): pin server output settings and guard busy connections

Pin bytea_output=hex and standard_conforming_strings=on in the startup
packet instead of tracking ParameterStatus values nobody read, so the
legacy bytea escape decoder goes away. A PostgreSQL connection now
refuses a new command while a row stream is still open, and the pool
discards such a connection. Drop unused SQLite declarations.

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 10:13:09 +00:00
1 parent 49fa8c5214
commit 8d9b04c713
7 files changed
+51 -51

No files matched your search

+12 -9
View File
@@ -36,7 +36,6 @@ internal sealed class PgConnector : IAsyncDisposable
private readonly Dictionary<string, LinkedListNode<PgStatement>> _statements = new(StringComparer.Ordinal); private readonly Dictionary<string, LinkedListNode<PgStatement>> _statements = new(StringComparer.Ordinal);
private readonly LinkedList<PgStatement> _statementLru = new(); private readonly LinkedList<PgStatement> _statementLru = new();
private readonly List<string> _statementsToClose = []; private readonly List<string> _statementsToClose = [];
private readonly Dictionary<string, string> _serverParameters = new(StringComparer.Ordinal);
private byte[] _read = new byte[16 * 1024]; private byte[] _read = new byte[16 * 1024];
private int _readPos; private int _readPos;
private int _readEnd; private int _readEnd;
@@ -48,6 +47,7 @@ internal sealed class PgConnector : IAsyncDisposable
private int _disposed; private int _disposed;
private CancellationTokenSource _ioAbort = new(); private CancellationTokenSource _ioAbort = new();
private Task _pendingCancel = Task.CompletedTask; private Task _pendingCancel = Task.CompletedTask;
private Operation? _active;
private PgConnector(PostgresSettings settings, Socket socket, Stream stream) private PgConnector(PostgresSettings settings, Socket socket, Stream stream)
{ {
@@ -64,9 +64,10 @@ internal sealed class PgConnector : IAsyncDisposable
/// <summary>Last ReadyForQuery status: 'I' idle, 'T' in transaction, 'E' failed transaction.</summary> /// <summary>Last ReadyForQuery status: 'I' idle, 'T' in transaction, 'E' failed transaction.</summary>
public char TransactionStatus { get; private set; } = 'I'; public char TransactionStatus { get; private set; } = 'I';
public TimeSpan IdleTime => TimeSpan.FromMilliseconds(Environment.TickCount64 - _idleSince); /// <summary>A command's response is still being read (an enumeration that was neither finished nor disposed).</summary>
public bool IsBusy => _active is not null;
public IReadOnlyDictionary<string, string> ServerParameters => _serverParameters; public TimeSpan IdleTime => TimeSpan.FromMilliseconds(Environment.TickCount64 - _idleSince);
/// <summary>Receives NotificationResponse messages (listener connections).</summary> /// <summary>Receives NotificationResponse messages (listener connections).</summary>
public Action<PgNotification>? NotificationReceived { get; set; } public Action<PgNotification>? NotificationReceived { get; set; }
@@ -379,6 +380,9 @@ internal sealed class PgConnector : IAsyncDisposable
Parameter("TimeZone", "UTC"); Parameter("TimeZone", "UTC");
Parameter("DateStyle", "ISO, MDY"); Parameter("DateStyle", "ISO, MDY");
Parameter("extra_float_digits", "3"); Parameter("extra_float_digits", "3");
Parameter("bytea_output", "hex");
// LIKE … ESCAPE '\' in the repositories needs backslashes to be literal in string constants.
Parameter("standard_conforming_strings", "on");
if (_settings.SearchPath is { } searchPath) Parameter("search_path", searchPath); if (_settings.SearchPath is { } searchPath) Parameter("search_path", searchPath);
_write.WriteByte(0); _write.WriteByte(0);
_write.EndMessage(); _write.EndMessage();
@@ -469,8 +473,10 @@ internal sealed class PgConnector : IAsyncDisposable
private Operation StartOperation(string sql, DbParam[] parameters, bool decodeRows, CancellationToken cancellationToken) private Operation StartOperation(string sql, DbParam[] parameters, bool decodeRows, CancellationToken cancellationToken)
{ {
if (IsBroken) throw new DatabaseConnectionException("The connection is broken."); if (IsBroken) throw new DatabaseConnectionException("The connection is broken.");
if (IsBusy) throw new InvalidOperationException("A command is still running on this session; finish or dispose its enumeration first.");
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
var op = new Operation(this, sql, parameters, decodeRows, cancellationToken); var op = new Operation(this, sql, parameters, decodeRows, cancellationToken);
_active = op;
if (cancellationToken.CanBeCanceled) if (cancellationToken.CanBeCanceled)
op.Registration = cancellationToken.UnsafeRegister(static state => ((Operation)state!).Owner.RequestCancel((Operation)state!), op); op.Registration = cancellationToken.UnsafeRegister(static state => ((Operation)state!).Owner.RequestCancel((Operation)state!), op);
return op; return op;
@@ -545,6 +551,7 @@ internal sealed class PgConnector : IAsyncDisposable
_ioAbort.Dispose(); _ioAbort.Dispose();
_ioAbort = new CancellationTokenSource(); _ioAbort = new CancellationTokenSource();
} }
_active = null;
MarkIdle(); MarkIdle();
} }
} }
@@ -846,12 +853,8 @@ internal sealed class PgConnector : IAsyncDisposable
LogNotice(); LogNotice();
continue; continue;
case (byte)'S': case (byte)'S':
{ // ParameterStatus: the settings the decoder relies on are pinned in the startup packet.
var pos = 0; continue;
var name = ReadCString(Payload, ref pos);
_serverParameters[name] = ReadCString(Payload, ref pos);
continue;
}
case (byte)'A': case (byte)'A':
{ {
var pos = 4; var pos = 4;
+2 -2
View File
@@ -52,11 +52,11 @@ internal sealed class PgPool : IAsyncDisposable
} }
} }
/// <summary>Takes a connection back; a broken one, or one not idle at transaction level, is closed instead.</summary> /// <summary>Takes a connection back; a broken or busy one, or one inside a transaction, is closed instead.</summary>
public void Return(PgConnector connector) public void Return(PgConnector connector)
{ {
PgConnector? discard = connector; PgConnector? discard = connector;
if (!connector.IsBroken && connector.TransactionStatus == 'I') if (!connector.IsBroken && !connector.IsBusy && connector.TransactionStatus == 'I')
{ {
connector.MarkIdle(); connector.MarkIdle();
lock (_gate) lock (_gate)
+18 -33
View File
@@ -10,22 +10,16 @@ internal static class PgTypes
{ {
public const uint Bool = 16; public const uint Bool = 16;
public const uint Bytea = 17; public const uint Bytea = 17;
public const uint Char = 18;
public const uint Name = 19;
public const uint Int8 = 20; public const uint Int8 = 20;
public const uint Int2 = 21; public const uint Int2 = 21;
public const uint Int4 = 23; public const uint Int4 = 23;
public const uint Text = 25; public const uint Text = 25;
public const uint Oid = 26; public const uint Oid = 26;
public const uint Json = 114;
public const uint Float4 = 700; public const uint Float4 = 700;
public const uint Float8 = 701; public const uint Float8 = 701;
public const uint Bpchar = 1042;
public const uint Varchar = 1043;
public const uint Date = 1082; public const uint Date = 1082;
public const uint Timestamp = 1114; public const uint Timestamp = 1114;
public const uint TimestampTz = 1184; public const uint TimestampTz = 1184;
public const uint Numeric = 1700;
public const uint Uuid = 2950; public const uint Uuid = 2950;
public const uint Jsonb = 3802; public const uint Jsonb = 3802;
@@ -151,7 +145,10 @@ internal static class PgTypes
} }
} }
/// <summary>Decodes a text-format result value by its type OID; unknown types stay strings.</summary> /// <summary>
/// Decodes a text-format result value by its type OID. Every other type (text, varchar, bpchar, name, json,
/// jsonb, numeric, …) stays a string, which is also how numeric is meant to be read.
/// </summary>
public static object Decode(uint oid, ReadOnlySpan<byte> utf8) public static object Decode(uint oid, ReadOnlySpan<byte> utf8)
{ {
var inv = CultureInfo.InvariantCulture; var inv = CultureInfo.InvariantCulture;
@@ -185,35 +182,23 @@ internal static class PgTypes
} }
} }
/// <summary>bytea output: hex (<c>\x0a0b</c>, the default since 9.0) or the legacy escape format.</summary> /// <summary>bytea in hex output format (<c>\x0a0b</c>), which the startup packet pins with <c>bytea_output=hex</c>.</summary>
private static byte[] DecodeBytea(ReadOnlySpan<byte> text) private static byte[] DecodeBytea(ReadOnlySpan<byte> text)
{ {
if (text.Length >= 2 && text[0] == '\\' && text[1] == 'x') if (text.Length < 2 || text[0] != '\\' || text[1] != 'x' || text.Length % 2 != 0)
return Convert.FromHexString(Encoding.ASCII.GetString(text[2..])); throw new FormatException("A bytea value is not in hex output format.");
var result = new List<byte>(text.Length); var result = new byte[(text.Length - 2) / 2];
for (var i = 0; i < text.Length; i++) for (var i = 0; i < result.Length; i++) result[i] = (byte)((HexValue(text[2 + 2 * i]) << 4) | HexValue(text[3 + 2 * i]));
{ return result;
if (text[i] != '\\')
{
result.Add(text[i]);
}
else if (i + 1 < text.Length && text[i + 1] == '\\')
{
result.Add((byte)'\\');
i++;
}
else if (i + 3 < text.Length)
{
result.Add((byte)(((text[i + 1] - '0') << 6) | ((text[i + 2] - '0') << 3) | (text[i + 3] - '0')));
i += 3;
}
else
{
throw new FormatException("Malformed bytea escape sequence.");
}
}
return [.. result];
} }
private static int HexValue(byte c) => c switch
{
>= (byte)'0' and <= (byte)'9' => c - '0',
>= (byte)'a' and <= (byte)'f' => c - 'a' + 10,
>= (byte)'A' and <= (byte)'F' => c - 'A' + 10,
_ => throw new FormatException("Invalid hex digit in a bytea value."),
};
private static ReadOnlySpan<byte> HexDigits => "0123456789abcdef"u8; private static ReadOnlySpan<byte> HexDigits => "0123456789abcdef"u8;
} }
-2
View File
@@ -14,7 +14,6 @@ internal static unsafe class SqliteNative
private static int _resolverInstalled; private static int _resolverInstalled;
public const int SQLITE_OK = 0; public const int SQLITE_OK = 0;
public const int SQLITE_ERROR = 1;
public const int SQLITE_INTERRUPT = 9; public const int SQLITE_INTERRUPT = 9;
public const int SQLITE_BUSY = 5; public const int SQLITE_BUSY = 5;
public const int SQLITE_LOCKED = 6; public const int SQLITE_LOCKED = 6;
@@ -70,7 +69,6 @@ internal static unsafe class SqliteNative
[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 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 void sqlite3_free(void* p);
[DllImport(Library, ExactSpelling = true)] public static extern byte* sqlite3_errmsg(nint db); [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 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_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_total_changes(nint db);
+2 -2
View File
@@ -6,8 +6,8 @@ namespace Titano.Data.Sqlite;
/// <summary> /// <summary>
/// A pooled SQLite connection. Statements that write take the database write lock for their duration when no /// 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 /// transaction holds it already; lock conflicts are retried (see <see cref="StepAsync"/>). Cancellation
/// transactions. Cancellation interrupts the running statement with <c>sqlite3_interrupt</c>. /// interrupts the running statement with <c>sqlite3_interrupt</c>.
/// </summary> /// </summary>
internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection connection) : IDbSession internal sealed class SqliteSession(SqliteDatabase database, SqliteConnection connection) : IDbSession
{ {
@@ -61,10 +61,13 @@ public sealed class PgProtocolUnitTests
} }
[Test] [Test]
public void DecodesByteaInHexAndEscapeFormats() public void DecodesHexByteaAndRejectsOtherForms()
{ {
Assert.BytesEqual(new byte[] { 0xDE, 0xAD }, (byte[])PgTypes.Decode(PgTypes.Bytea, "\\xdead"u8)); Assert.BytesEqual(new byte[] { 0xDE, 0xAD, 0x01 }, (byte[])PgTypes.Decode(PgTypes.Bytea, "\\xdeAD01"u8));
Assert.BytesEqual(new byte[] { (byte)'a', 0, (byte)'\\', 0xFF }, (byte[])PgTypes.Decode(PgTypes.Bytea, "a\\000\\\\\\377"u8)); Assert.Equal(0, ((byte[])PgTypes.Decode(PgTypes.Bytea, "\\x"u8)).Length);
Assert.Throws<FormatException>(() => PgTypes.Decode(PgTypes.Bytea, "a\\000"u8));
Assert.Throws<FormatException>(() => PgTypes.Decode(PgTypes.Bytea, "\\xabc"u8));
Assert.Throws<FormatException>(() => PgTypes.Decode(PgTypes.Bytea, "\\xzz"u8));
} }
[Theory] [Theory]
@@ -260,6 +260,17 @@ public sealed class PgWireTests(TestContext context) : DatabaseTest(context)
Assert.Equal("x", second.GetString("b")); Assert.Equal("x", second.GetString("b"));
} }
[Test]
public async Task ACommandCannotStartWhileARowStreamIsOpen()
{
await using var session = await (await OpenAsync()).OpenAsync(Ct);
var rows = session.QueryAsync("SELECT generate_series(1, 1000)", [], Ct).GetAsyncEnumerator(Ct);
Assert.True(await rows.MoveNextAsync());
await Assert.ThrowsAsync<InvalidOperationException>(() => session.ExecuteAsync("SELECT 1", [], Ct));
await rows.DisposeAsync();
Assert.Equal(1, await session.ScalarAsync<int>("SELECT 1", [], Ct));
}
[Test] [Test]
public async Task NoticesAndScriptsDoNotDisturbTheSession() public async Task NoticesAndScriptsDoNotDisturbTheSession()
{ {