Skip to content

Commit

Permalink
Move unique constraint check to extension method (#10216)
Browse files Browse the repository at this point in the history
  • Loading branch information
joelverhagen authored Oct 11, 2024
1 parent 61e5c18 commit 099427b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 15 deletions.
34 changes: 34 additions & 0 deletions src/NuGet.Services.Entities/Extensions/ExceptionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Data;
using System.Data.SqlClient;

namespace NuGet.Services.Entities
{
public static class ExceptionExtensions
{
public static bool IsSqlUniqueConstraintViolation(this DataException exception)
{
Exception current = exception;
while (current is not null)
{
if (current is SqlException sqlException)
{
switch (sqlException.Number)
{
case 547: // Constraint check violation: https://learn.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-events-and-errors-0-to-999
case 2601: // Duplicated key row error: https://learn.microsoft.com/en-us/sql/relational-databases/replication/mssql-eng002601
case 2627: // Unique constraint error: https://learn.microsoft.com/en-us/sql/relational-databases/replication/mssql-eng002627
return true;
}
}

current = current.InnerException;
}

return false;
}
}
}
18 changes: 3 additions & 15 deletions src/NuGetGallery/Services/PackageUploadService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
Expand Down Expand Up @@ -283,21 +283,9 @@ private bool IsConflict(Exception ex)
{
return true;
}
else if (ex is DbUpdateException dbUpdateEx)
else if (ex is DbUpdateException dbUpdateEx && dbUpdateEx.IsSqlUniqueConstraintViolation())
{
if (dbUpdateEx.InnerException?.InnerException != null)
{
if (dbUpdateEx.InnerException.InnerException is SqlException sqlException)
{
switch (sqlException.Number)
{
case 547: // Constraint check violation
case 2601: // Duplicated key row error
case 2627: // Unique constraint error
return true;
}
}
}
return true;
}

return false;
Expand Down

0 comments on commit 099427b

Please sign in to comment.