Skip to content
Merged
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
20 changes: 12 additions & 8 deletions src/Weasel.Postgresql/PostgresqlMigrator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,16 +94,20 @@ public override void WriteSchemaDropSql(IEnumerable<string> schemaNames, TextWri

private static void WriteSql(string databaseSchemaName, TextWriter writer)
{
// Neither the "IF NOT EXISTS(information_schema.schemata) THEN EXECUTE 'CREATE SCHEMA'"
// pattern nor PostgreSQL's own "CREATE SCHEMA IF NOT EXISTS" is concurrent-safe — both
// can have two sessions pass the existence check then race on the insert into pg_namespace,
// surfacing as "23505 duplicate key value violates unique constraint pg_namespace_nspname_index"
// / "42P06 schema X already exists". Wrap the create in a sub-block that swallows those two
// race exceptions specifically; any other error still propagates.
writer.WriteLine(
$"""
IF NOT EXISTS(
SELECT schema_name
FROM information_schema.schemata
WHERE schema_name = '{databaseSchemaName}'
)
THEN
EXECUTE 'CREATE SCHEMA {PostgresqlProvider.Instance.ToQualifiedName(databaseSchemaName)}';
END IF;
BEGIN
EXECUTE 'CREATE SCHEMA IF NOT EXISTS {PostgresqlProvider.Instance.ToQualifiedName(databaseSchemaName)}';
EXCEPTION
WHEN duplicate_schema THEN NULL;
WHEN unique_violation THEN NULL;
END;

""");
}
Expand Down
Loading