fix(pgsql): make CommandVisitor parameter index instance-scoped

Resolves SonarQube S2696 in CommandVisitor.cs.

The static _parameterIndex field was mutated from an instance method,
causing every new CommandVisitor to inherit the previous instance's
counter and never reset. Parameter indices now restart at $1 per
visitor, which is the intended PostgreSQL behavior.

Adds CommandVisitorTests.TwoVisitors_HaveIndependentParameterIndices to
lock in the contract via reflection (FormatParameterName is protected).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Thom Lamb
2026-05-19 16:21:17 -05:00
co-authored by Claude Opus 4.7
parent e2bfe3906a
commit acfe29ee98
2 changed files with 35 additions and 1 deletions
@@ -9,7 +9,7 @@ namespace Strata.SqlTools.Visitors.PostgreSql;
/// </summary>
public class CommandVisitor : SqlServerCommandVisitor
{
private static int _parameterIndex = 1;
private int _parameterIndex = 1;
/// <summary>
/// Formats an identifier for PostgreSQL using double-quote quoting.
@@ -0,0 +1,34 @@
using Strata.SqlTools.Visitors.PostgreSql;
namespace Strata.SqlTools.PostgreSql.Tests.PostgreSql;
[TestFixture]
public class CommandVisitorTests
{
[Test]
public void TwoVisitors_HaveIndependentParameterIndices()
{
var visitor1 = new CommandVisitor();
var visitor2 = new CommandVisitor();
var param1a = InvokeFormatParameterName(visitor1, "p");
var param1b = InvokeFormatParameterName(visitor1, "p");
var param2a = InvokeFormatParameterName(visitor2, "p");
Assert.That(param1a, Is.EqualTo("$1"), "first visitor's first parameter should be $1");
Assert.That(param1b, Is.EqualTo("$2"), "first visitor's second parameter should be $2");
Assert.That(param2a, Is.EqualTo("$1"), "second visitor must start at $1, not inherit visitor1's counter");
}
private static string InvokeFormatParameterName(CommandVisitor visitor, string name)
{
var method = typeof(CommandVisitor).GetMethod(
"FormatParameterName",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)
?? typeof(Strata.SqlTools.Visitors.SqlServer.CommandVisitor).GetMethod(
"FormatParameterName",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
Assert.That(method, Is.Not.Null, "FormatParameterName must exist as a protected method on the visitor hierarchy");
return (string)method!.Invoke(visitor, new object[] { name })!;
}
}