Skip to content

Commit 099427b

Browse files
authored
Move unique constraint check to extension method (#10216)
1 parent 61e5c18 commit 099427b

2 files changed

Lines changed: 37 additions & 15 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
using System;
5+
using System.Data;
6+
using System.Data.SqlClient;
7+
8+
namespace NuGet.Services.Entities
9+
{
10+
public static class ExceptionExtensions
11+
{
12+
public static bool IsSqlUniqueConstraintViolation(this DataException exception)
13+
{
14+
Exception current = exception;
15+
while (current is not null)
16+
{
17+
if (current is SqlException sqlException)
18+
{
19+
switch (sqlException.Number)
20+
{
21+
case 547: // Constraint check violation: https://learn.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-events-and-errors-0-to-999
22+
case 2601: // Duplicated key row error: https://learn.microsoft.com/en-us/sql/relational-databases/replication/mssql-eng002601
23+
case 2627: // Unique constraint error: https://learn.microsoft.com/en-us/sql/relational-databases/replication/mssql-eng002627
24+
return true;
25+
}
26+
}
27+
28+
current = current.InnerException;
29+
}
30+
31+
return false;
32+
}
33+
}
34+
}

src/NuGetGallery/Services/PackageUploadService.cs

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) .NET Foundation. All rights reserved.
1+
// Copyright (c) .NET Foundation. All rights reserved.
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

44
using System;
@@ -283,21 +283,9 @@ private bool IsConflict(Exception ex)
283283
{
284284
return true;
285285
}
286-
else if (ex is DbUpdateException dbUpdateEx)
286+
else if (ex is DbUpdateException dbUpdateEx && dbUpdateEx.IsSqlUniqueConstraintViolation())
287287
{
288-
if (dbUpdateEx.InnerException?.InnerException != null)
289-
{
290-
if (dbUpdateEx.InnerException.InnerException is SqlException sqlException)
291-
{
292-
switch (sqlException.Number)
293-
{
294-
case 547: // Constraint check violation
295-
case 2601: // Duplicated key row error
296-
case 2627: // Unique constraint error
297-
return true;
298-
}
299-
}
300-
}
288+
return true;
301289
}
302290

303291
return false;

0 commit comments

Comments
 (0)