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:
7 files changed
+51
-51
No files matched your search
@@ -36,7 +36,6 @@ internal sealed class PgConnector : IAsyncDisposable
|
||||
private readonly Dictionary<string, LinkedListNode<PgStatement>> _statements = new(StringComparer.Ordinal);
|
||||
private readonly LinkedList<PgStatement> _statementLru = new();
|
||||
private readonly List<string> _statementsToClose = [];
|
||||
private readonly Dictionary<string, string> _serverParameters = new(StringComparer.Ordinal);
|
||||
private byte[] _read = new byte[16 * 1024];
|
||||
private int _readPos;
|
||||
private int _readEnd;
|
||||
@@ -48,6 +47,7 @@ internal sealed class PgConnector : IAsyncDisposable
|
||||
private int _disposed;
|
||||
private CancellationTokenSource _ioAbort = new();
|
||||
private Task _pendingCancel = Task.CompletedTask;
|
||||
private Operation? _active;
|
||||
|
||||
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>
|
||||
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>
|
||||
public Action<PgNotification>? NotificationReceived { get; set; }
|
||||
@@ -379,6 +380,9 @@ internal sealed class PgConnector : IAsyncDisposable
|
||||
Parameter("TimeZone", "UTC");
|
||||
Parameter("DateStyle", "ISO, MDY");
|
||||
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);
|
||||
_write.WriteByte(0);
|
||||
_write.EndMessage();
|
||||
@@ -469,8 +473,10 @@ internal sealed class PgConnector : IAsyncDisposable
|
||||
private Operation StartOperation(string sql, DbParam[] parameters, bool decodeRows, CancellationToken cancellationToken)
|
||||
{
|
||||
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();
|
||||
var op = new Operation(this, sql, parameters, decodeRows, cancellationToken);
|
||||
_active = op;
|
||||
if (cancellationToken.CanBeCanceled)
|
||||
op.Registration = cancellationToken.UnsafeRegister(static state => ((Operation)state!).Owner.RequestCancel((Operation)state!), op);
|
||||
return op;
|
||||
@@ -545,6 +551,7 @@ internal sealed class PgConnector : IAsyncDisposable
|
||||
_ioAbort.Dispose();
|
||||
_ioAbort = new CancellationTokenSource();
|
||||
}
|
||||
_active = null;
|
||||
MarkIdle();
|
||||
}
|
||||
}
|
||||
@@ -846,12 +853,8 @@ internal sealed class PgConnector : IAsyncDisposable
|
||||
LogNotice();
|
||||
continue;
|
||||
case (byte)'S':
|
||||
{
|
||||
var pos = 0;
|
||||
var name = ReadCString(Payload, ref pos);
|
||||
_serverParameters[name] = ReadCString(Payload, ref pos);
|
||||
continue;
|
||||
}
|
||||
// ParameterStatus: the settings the decoder relies on are pinned in the startup packet.
|
||||
continue;
|
||||
case (byte)'A':
|
||||
{
|
||||
var pos = 4;
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
PgConnector? discard = connector;
|
||||
if (!connector.IsBroken && connector.TransactionStatus == 'I')
|
||||
if (!connector.IsBroken && !connector.IsBusy && connector.TransactionStatus == 'I')
|
||||
{
|
||||
connector.MarkIdle();
|
||||
lock (_gate)
|
||||
|
||||
@@ -10,22 +10,16 @@ internal static class PgTypes
|
||||
{
|
||||
public const uint Bool = 16;
|
||||
public const uint Bytea = 17;
|
||||
public const uint Char = 18;
|
||||
public const uint Name = 19;
|
||||
public const uint Int8 = 20;
|
||||
public const uint Int2 = 21;
|
||||
public const uint Int4 = 23;
|
||||
public const uint Text = 25;
|
||||
public const uint Oid = 26;
|
||||
public const uint Json = 114;
|
||||
public const uint Float4 = 700;
|
||||
public const uint Float8 = 701;
|
||||
public const uint Bpchar = 1042;
|
||||
public const uint Varchar = 1043;
|
||||
public const uint Date = 1082;
|
||||
public const uint Timestamp = 1114;
|
||||
public const uint TimestampTz = 1184;
|
||||
public const uint Numeric = 1700;
|
||||
public const uint Uuid = 2950;
|
||||
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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
if (text.Length >= 2 && text[0] == '\\' && text[1] == 'x')
|
||||
return Convert.FromHexString(Encoding.ASCII.GetString(text[2..]));
|
||||
var result = new List<byte>(text.Length);
|
||||
for (var i = 0; i < text.Length; i++)
|
||||
{
|
||||
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];
|
||||
if (text.Length < 2 || text[0] != '\\' || text[1] != 'x' || text.Length % 2 != 0)
|
||||
throw new FormatException("A bytea value is not in hex output format.");
|
||||
var result = new byte[(text.Length - 2) / 2];
|
||||
for (var i = 0; i < result.Length; i++) result[i] = (byte)((HexValue(text[2 + 2 * i]) << 4) | HexValue(text[3 + 2 * i]));
|
||||
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;
|
||||
}
|
||||
Reference in new issue
Block a user