From 58608e88dbe8b191293b6e3875e71ded11a80464 Mon Sep 17 00:00:00 2001
From: Shay Rojansky <roji@roji.org>
Date: Fri, 27 Sep 2024 19:33:16 +0200
Subject: [PATCH] Handle another error code when concurrently creating the
 migrations history table (#3301)

---
 .../Migrations/Internal/NpgsqlHistoryRepository.cs   | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)

diff --git a/src/EFCore.PG/Migrations/Internal/NpgsqlHistoryRepository.cs b/src/EFCore.PG/Migrations/Internal/NpgsqlHistoryRepository.cs
index b0469daa9..3c8513ec3 100644
--- a/src/EFCore.PG/Migrations/Internal/NpgsqlHistoryRepository.cs
+++ b/src/EFCore.PG/Migrations/Internal/NpgsqlHistoryRepository.cs
@@ -98,7 +98,9 @@ bool IHistoryRepository.CreateIfNotExists()
                     GetCreateIfNotExistsCommands(), Dependencies.Connection, new MigrationExecutionState(), commitTransaction: true)
                 != 0;
         }
-        catch (PostgresException e) when (e.SqlState is "23505" or "42P07")
+        catch (PostgresException e) when (e.SqlState is PostgresErrorCodes.UniqueViolation
+                                              or PostgresErrorCodes.DuplicateTable
+                                              or PostgresErrorCodes.DuplicateObject)
         {
             return false;
         }
@@ -116,7 +118,9 @@ async Task<bool> IHistoryRepository.CreateIfNotExistsAsync(CancellationToken can
                     cancellationToken: cancellationToken).ConfigureAwait(false))
                 != 0;
         }
-        catch (PostgresException e) when (e.SqlState is "23505" or "42P07")
+        catch (PostgresException e) when (e.SqlState is PostgresErrorCodes.UniqueViolation
+                                              or PostgresErrorCodes.DuplicateTable
+                                              or PostgresErrorCodes.DuplicateObject)
         {
             return false;
         }
@@ -192,7 +196,7 @@ public override IReadOnlyList<HistoryRow> GetAppliedMigrations()
         {
             return base.GetAppliedMigrations();
         }
-        catch (PostgresException e) when (e.SqlState is "3D000" or "42P01")
+        catch (PostgresException e) when (e.SqlState is PostgresErrorCodes.InvalidCatalogName or PostgresErrorCodes.UndefinedTable)
         {
             return [];
         }
@@ -210,7 +214,7 @@ public override async Task<IReadOnlyList<HistoryRow>> GetAppliedMigrationsAsync(
         {
             return await base.GetAppliedMigrationsAsync(cancellationToken).ConfigureAwait(false);
         }
-        catch (PostgresException e) when (e.SqlState is "3D000" or "42P01")
+        catch (PostgresException e) when (e.SqlState is PostgresErrorCodes.InvalidCatalogName or PostgresErrorCodes.UndefinedTable)
         {
             return [];
         }