Improve NpgsqlCodec whitespace and quotation rules

This commit is contained in:
eelke 2025-09-02 18:50:23 +02:00
parent 18e737e865
commit 4c7a6c2666
2 changed files with 44 additions and 21 deletions

View file

@ -236,24 +236,44 @@ public sealed class NpgsqlCodec : IConnectionStringCodec
private static string FormatPair(string key, string? value)
{
value ??= string.Empty;
var needsQuotes = NeedsQuoting(value);
if (!needsQuotes) return key + "=" + value;
return key + "=\"" + EscapeQuoted(value) + "\"";
// Decide if we need quoting following DbConnectionStringBuilder rules:
// - Empty => quote
// - Leading or trailing whitespace => quote
// - Contains ';' or '=' => quote
// - Otherwise, no quotes, even if it contains internal whitespace
if (!NeedsQuoting(value))
return key + "=" + value;
// Choose single or double quotes. Prefer the one not present in the value; if both present, pick double and escape.
bool hasSingle = value.Contains('\'');
bool hasDouble = value.Contains('"');
if (!hasSingle)
{
// Use single quotes, escape single quotes by doubling when needed (not needed here since !hasSingle)
return key + "='" + value.Replace("'", "''") + "'";
}
if (!hasDouble)
{
// Use double quotes
return key + "=\"" + value.Replace("\"", "\"\"") + "\"";
}
// Value contains both quote types: default to double quotes and escape doubles by doubling
return key + "=\"" + value.Replace("\"", "\"\"") + "\"";
}
private static bool NeedsQuoting(string value)
{
if (value.Length == 0) return true;
foreach (var c in value)
{
if (char.IsWhiteSpace(c) || c == ';' || c == '=' || c == '"') return true;
}
// Leading or trailing whitespace requires quoting
if (char.IsWhiteSpace(value[0]) || char.IsWhiteSpace(value[^1])) return true;
// Special characters
if (value.IndexOf(';') >= 0 || value.IndexOf('=') >= 0) return true;
return false;
}
private static string EscapeQuoted(string value)
{
// Double the quotes per standard DbConnectionString rules
// Retained for compatibility, but not used directly; prefer inlined replacements in FormatPair
return value.Replace("\"", "\"\"");
}
@ -279,19 +299,19 @@ public sealed class NpgsqlCodec : IConnectionStringCodec
// read value
string value;
if (i < input.Length && input[i] == '"')
if (i < input.Length && (input[i] == '"' || input[i] == '\''))
{
i++; // skip opening quote
char quote = input[i++]; // opening quote (' or ")
var sb = new StringBuilder();
while (i < input.Length)
{
char c = input[i++];
if (c == '"')
if (c == quote)
{
if (i < input.Length && input[i] == '"')
if (i < input.Length && input[i] == quote)
{
// doubled quote -> literal quote
sb.Append('"');
sb.Append(quote);
i++;
continue;
}
@ -311,6 +331,7 @@ public sealed class NpgsqlCodec : IConnectionStringCodec
{
int valStart = i;
while (i < input.Length && input[i] != ';') i++;
// Unquoted value: per DbConnectionStringBuilder, leading/trailing whitespace is ignored
value = input.Substring(valStart, i - valStart).Trim();
}