/
rezvich
/
Prik
Обзор
Документация
Войти
/
rezvich
/
Prik
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
Infrastructure/Db/MoLogRepository.cs
64 строки
2 KB
waweda299
Прик
08 июн 2026, 15:52
08 июн 2026, 15:52
9ddc25e
Код
Авторство
О чём код?
//prik/Infrastructure/Db/MoLogRepository.cs using Dapper; using Microsoft.Data.SqlClient; using System.Data; namespace prik.Infrastructure.Db { public interface IMoLogRepository { Task<int> InsertAsync(IDbConnection conn, IDbTransaction tx, string fileName, int nrec, int nerr, CancellationToken ct); } public sealed class MoLogRepository : IMoLogRepository { public async Task<int> InsertAsync(IDbConnection conn, IDbTransaction tx, string fileName, int nrec, int nerr, CancellationToken ct) { const string sql = @" INSERT INTO dbo.MO_LOG (FNAME, DT, NREC, NERR, LFILE, EFILE) OUTPUT INSERTED.ID VALUES (@fname, GETDATE(), @nrec, @nerr, NULL, NULL); "; // Пробуем исходное имя, затем _v2 .. _v50 (лимит можно увеличить) const int maxAttempts = 50; for (int attempt = 1; attempt <= maxAttempts; attempt++) { ct.ThrowIfCancellationRequested(); var candidate = attempt == 1 ? fileName : AppendVersionSuffix(fileName, attempt); try { var id = await conn.ExecuteScalarAsync<int>(sql, new { fname = candidate, nrec, nerr }, tx); return id; } catch (SqlException ex) when (IsUniqueViolation(ex)) { // имя занято, пробуем следующее if (attempt == maxAttempts) { throw; } } } // Сюда по идее не попадём throw new InvalidOperationException("Unable to generate unique file name for MO_LOG.FNAME."); } private static bool IsUniqueViolation(SqlException ex) => ex.Number is 2627 or 2601; // 2627: PK/Unique constraint, 2601: unique index private static string AppendVersionSuffix(string fileName, int attempt) { // attempt=2 => _v2, attempt=3 => _v3 ... var dir = Path.GetDirectoryName(fileName); var name = Path.GetFileNameWithoutExtension(fileName); var ext = Path.GetExtension(fileName); var candidateName = $"{name}_v{attempt}{ext}"; return string.IsNullOrEmpty(dir) ? candidateName : Path.Combine(dir, candidateName); } } }