Skip to content

Commit

Permalink
Added SchemaUtils to DropSchema with retries
Browse files Browse the repository at this point in the history
  • Loading branch information
oskardudycz committed Feb 5, 2023
1 parent 7164285 commit 33e363a
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using JasperFx.Core;
using CoreTests.Diagnostics;
using CoreTests.Util;
using Marten;
using Marten.Testing.Documents;
using Marten.Testing.Harness;
Expand Down Expand Up @@ -36,15 +38,14 @@ private async Task<string> CreateDatabaseIfNotExists(NpgsqlConnection conn, stri

var connectionString = builder.ConnectionString;

await using var dbConn = new NpgsqlConnection(connectionString);
await dbConn.OpenAsync();
await dbConn.DropSchema("multi_tenancy");
await dbConn.DropSchema("mt_events");
await SchemaUtils.DropSchema(connectionString, "multi_tenancy");
await SchemaUtils.DropSchema(connectionString, "mt_events");

return connectionString;
}



public async Task InitializeAsync()
{
await using var conn = new NpgsqlConnection(ConnectionSource.ConnectionString);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ public async Task InitializeAsync()
await DropDatabaseIfExists("database2");

theTenancy = new SingleServerMultiTenancy(ConnectionSource.ConnectionString, new StoreOptions());

}

public Task DisposeAsync()
Expand Down
49 changes: 49 additions & 0 deletions src/CoreTests/Util/SchemaUtils.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System;
using System.Threading.Tasks;
using Npgsql;
using Weasel.Postgresql;

namespace CoreTests.Util;

public static class SchemaUtils
{
// TODO: This should probably go to Weasel
public static async Task DropSchema(string connectionString, string schemaName)
{
var reconnectionCount = 0;
const int maxReconnectionCount = 3;

var success = false;

do
{
success = await dropSchema(connectionString, schemaName);

if (success || ++reconnectionCount == maxReconnectionCount)
return;

await Task.Delay(reconnectionCount * 50).ConfigureAwait(false);
} while (!success && reconnectionCount < maxReconnectionCount);

throw new InvalidOperationException($"Unable to drop schema: ${schemaName}");
}

private static async Task<bool> dropSchema(string connectionString, string schemaName)
{
try
{
await using var dbConn = new NpgsqlConnection(connectionString);
await dbConn.OpenAsync();
await dbConn.DropSchema(schemaName);

return true;
}
catch (PostgresException pgException)
{
if (pgException.SqlState == PostgresErrorCodes.AdminShutdown)
return false;

throw;
}
}
}

0 comments on commit 33e363a

Please sign in to comment.