Refactor stored procedure SQL construction and execution

Centralize stored procedure SQL generation in StoredProcedureBuilder,
allowing handlers to specify procedure name and return variable.
Removes manual SQL string building from DeleteObjectProcedure and
UpdateObjectProcedure handlers, reducing boilerplate and improving
maintainability.
This commit is contained in:
2026-03-30 09:30:07 +02:00
parent b66a49f74d
commit 93b5f976d3
3 changed files with 21 additions and 28 deletions

View File

@@ -4,22 +4,19 @@ using System.Text;
namespace ReC.Application.Common.Procedures;
internal sealed class StoredProcedureBuilder
internal sealed class StoredProcedureBuilder(string procedureName, string? returnVariable = null)
{
private readonly StringBuilder _sql;
private readonly StringBuilder _execSql = returnVariable is not null
? new StringBuilder($"EXEC @{returnVariable} = {procedureName}")
: new StringBuilder($"EXEC {procedureName}");
private readonly List<SqlParameter> _parameters = [];
private char _separator = ' ';
public StoredProcedureBuilder(string execPrefix)
{
_sql = new StringBuilder(execPrefix);
}
public StoredProcedureBuilder Add(string name, object? value, SqlDbType? dbType = null)
{
if (value is null) return this;
_sql.AppendLine($"{_separator}@{name} = @{name}");
_execSql.AppendLine($"{_separator}@{name} = @{name}");
_separator = ',';
if (dbType.HasValue)
@@ -32,7 +29,7 @@ internal sealed class StoredProcedureBuilder
public StoredProcedureBuilder AddOutput(string name, SqlDbType dbType)
{
_sql.AppendLine($"{_separator}@{name} = @{name} OUTPUT");
_execSql.AppendLine($"{_separator}@{name} = @{name} OUTPUT");
_separator = ',';
_parameters.Add(new SqlParameter
@@ -45,7 +42,17 @@ internal sealed class StoredProcedureBuilder
return this;
}
public string BuildSql() => _sql.ToString();
public string BuildSql()
{
if (returnVariable is null)
return _execSql.ToString();
return new StringBuilder()
.AppendLine($"DECLARE @{returnVariable} SMALLINT = 0;")
.Append(_execSql).AppendLine(";")
.AppendLine($"SELECT @{returnVariable};")
.ToString();
}
public SqlParameter[] BuildParameters() => [.. _parameters];