Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move unique constraint check to extension method #10216

Merged
merged 1 commit into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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