Files
ReC/src/ReC.Application/Common/Procedures/DeleteProcedure/DeleteObjectProcedure.cs
TekH 70dc52139d Refactor SQL param and command construction in procedures
Refactored InsertObject, UpdateObject, and DeleteObject procedure handlers to dynamically build SQL command strings and parameter lists. Introduced local Add functions to include only non-null parameters, improving code clarity and reducing unnecessary SQL parameter passing. The logic for handling stored procedure results and exceptions remains unchanged.
2026-03-27 14:58:56 +01:00

82 lines
2.5 KiB
C#

using DigitalData.Core.Abstraction.Application.Repository;
using DigitalData.Core.Exceptions;
using MediatR;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Options;
using ReC.Application.Common.Exceptions;
using ReC.Application.Common.Options;
using System.Text;
namespace ReC.Application.Common.Procedures.DeleteProcedure;
public record DeleteObjectProcedure : IRequest<int>
{
/// <summary>
/// Target entity: ACTION, ENDPOINT, ENDPOINT_AUTH, ENDPOINT_PARAMS, PROFILE, RESULT
/// </summary>
public string Entity { get; set; } = null!;
/// <summary>
/// Start GUID/ID (inclusive)
/// </summary>
public long Start { get; set; }
/// <summary>
/// End GUID/ID (inclusive). If 0, will be set to Start value.
/// </summary>
public long End { get; set; }
/// <summary>
/// If true, delete even if dependent data exists
/// </summary>
public bool Force { get; set; }
}
public class DeleteObjectProcedureHandler(IRepository repo, IOptionsMonitor<SqlExceptionOptions> sqlExOpt) : IRequestHandler<DeleteObjectProcedure, int>
{
public async Task<int> Handle(DeleteObjectProcedure request, CancellationToken cancel)
{
var execSql = new StringBuilder("EXEC @RC = [dbo].[PRREC_DELETE_OBJECT]");
var parameters = new List<SqlParameter>();
var separator = ' ';
void Add(string name, object? value)
{
if (value is null) return;
execSql.AppendLine($"{separator}@{name} = @{name}");
separator = ',';
parameters.Add(new SqlParameter($"@{name}", value));
}
Add("pENTITY", request.Entity);
Add("pSTART", request.Start.ToString());
Add("pEND", request.End.ToString());
Add("pFORCE", request.Force);
var sql = new StringBuilder()
.AppendLine("DECLARE @RC SMALLINT = 0;")
.Append(execSql).AppendLine(";")
.AppendLine("SELECT @RC;")
.ToString();
try
{
var result = await repo.ExecuteQueryRawAsync(sql, parameters.ToArray(), cancel);
if (result > 0)
{
throw new DeleteObjectFailedException(request, $"DeleteObject stored procedure failed with error code: {result}");
}
return result;
}
catch (SqlException ex)
{
if (sqlExOpt.CurrentValue.BadRequestSqlExceptionNumbers.Contains(ex.Number))
throw new BadRequestException(ex.Message, ex);
else
throw;
}
}
}