Skip to content

Commit 01f3d86

Browse files
committed
Moved PostgreSQL delete all to DatabaseTidyHelper
1 parent 0bbdb2c commit 01f3d86

File tree

5 files changed

+100
-88
lines changed

5 files changed

+100
-88
lines changed

ReleaseNotes.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22

33
## 5.1.0-preview002
44

5-
- Updated to support both EF Core 5 and EF Core 6-rc.2 preview
6-
- Added PostgreSQL database helpers, including EnsureClean
7-
- Added the Seed Database feature back in at request of users
8-
- Removed obsolete methods: ...OptionsWithLogging (use ...OptionsWithLogTo), CreateEmptyViaWipe (use EncureClean)
5+
- BREAKING CHANGE: Renamed DeleteAllUnitTestDatabases to DeleteAllSqlServerTestDatabases
6+
- REMOVED obsolete methods: ...OptionsWithLogging (use ...OptionsWithLogTo), CreateEmptyViaWipe (use EnsureClean)
7+
- NET6 Support: Updated to support both EF Core 5 and EF Core 6-rc.2 preview
8+
- New Feature: Added PostgreSQL database helpers, including EnsureClean (see docs)
9+
- Feature: Reinstated the Seed Database feature to this version due to requests from users
910

1011
## 5.1.0-preview001
1112

Test/UnitCommands/DeleteAllUnitTestDatabases.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ public DeleteAllUnitTestDatabases(ITestOutputHelper output)
2323
public void DeleteAllSqlServerTestDatabasesOk() //#B
2424
{
2525
var numDeleted = DatabaseTidyHelper //#C
26-
.DeleteAllUnitTestDatabases();//#C
26+
.DeleteAllSqlServerTestDatabases();//#C
2727
_output.WriteLine( //#D
2828
"This deleted {0} SQL Server databases.", numDeleted); //#D
2929
}
@@ -33,8 +33,8 @@ public void DeleteAllSqlServerTestDatabasesOk() //#B
3333
[RunnableInDebugOnly] //#A
3434
public void DeleteAllPostgreSqlTestDatabasesOk()
3535
{
36-
var numDeleted = PostgreSqlHelpers
37-
.DeleteAllPostgreSqlUnitTestDatabases();
36+
var numDeleted = DatabaseTidyHelper
37+
.DeleteAllPostgreSqlTestDatabases();
3838
_output.WriteLine(
3939
"This deleted {0} PostgreSql databases.", numDeleted);
4040
}

TestSupport/EfHelpers/DatabaseTidyHelper.cs

Lines changed: 80 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System.Reflection;
77
using Microsoft.Data.SqlClient;
88
using Microsoft.Extensions.Configuration;
9+
using Npgsql;
910
using TestSupport.Helpers;
1011

1112
namespace TestSupport.EfHelpers
@@ -20,7 +21,7 @@ public static class DatabaseTidyHelper
2021
/// WARNING: This will delete multiple databases - make sure your DefaultConnection database name is unique!!!
2122
/// </summary>
2223
/// <returns>Number of databases deleted</returns>
23-
public static int DeleteAllUnitTestDatabases()
24+
public static int DeleteAllSqlServerTestDatabases()
2425
{
2526
var config = AppSettings.GetConfiguration(Assembly.GetCallingAssembly());
2627
var builder = new SqlConnectionStringBuilder(config.GetConnectionString(AppSettings.UnitTestConnectionStringName));
@@ -90,5 +91,83 @@ private static void DeleteDatabase(this string databaseName, string connectionSt
9091
//it failed
9192
throw new InvalidOperationException($"Failed to deleted {databaseName}. Did you have SSMS open or something?");
9293
}
94+
95+
96+
//---------------------------------------------------------------------------
97+
//PostgreSQL version
98+
99+
/// <summary>
100+
/// This will delete all PostgreSql databases that start with the database name in the default connection string
101+
/// WARNING: This will delete multiple databases - make sure your <see cref="AppSettings.PostgreSqlConnectionString"/> database name is unique!!!
102+
/// </summary>
103+
/// <returns>Number of databases deleted</returns>
104+
public static int DeleteAllPostgreSqlTestDatabases()
105+
{
106+
var config = AppSettings.GetConfiguration(Assembly.GetCallingAssembly());
107+
var baseConnection = config.GetConnectionString(AppSettings.PostgreSqlConnectionString);
108+
if (string.IsNullOrEmpty(baseConnection))
109+
throw new InvalidOperationException(
110+
$"Your {AppSettings.AppSettingFilename} file isn't set up for the '{AppSettings.PostgreSqlConnectionString}'.");
111+
112+
var databaseNamesToDelete = baseConnection.GetAllPostgreUnitTestDatabases();
113+
114+
var builder = new NpgsqlConnectionStringBuilder(baseConnection);
115+
builder.Database = "postgres";
116+
foreach (var databaseName in databaseNamesToDelete)
117+
{
118+
builder.ToString().ExecuteScalars(
119+
$"REVOKE CONNECT ON DATABASE \"{databaseName}\" FROM PUBLIC",
120+
"SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity " +
121+
$"WHERE datname = '{databaseName}'",
122+
$"DROP DATABASE \"{databaseName}\""
123+
);
124+
}
125+
return databaseNamesToDelete.Count;
126+
}
127+
128+
//------------------------------------
129+
//private methods
130+
131+
private static void ExecuteScalars(this string connectionString, params string[] commands)
132+
{
133+
using (NpgsqlConnection conn = new NpgsqlConnection(connectionString))
134+
{
135+
conn.Open();
136+
foreach (var commandText in commands)
137+
{
138+
using (NpgsqlCommand cmd = new NpgsqlCommand(commandText, conn))
139+
{
140+
var result = cmd.ExecuteScalar();
141+
}
142+
}
143+
}
144+
}
145+
146+
private static List<string> GetAllPostgreUnitTestDatabases(this string connectionString)
147+
{
148+
var builder = new NpgsqlConnectionStringBuilder(connectionString);
149+
var orgDbStartsWith = builder.Database;
150+
builder.Database = "postgres";
151+
var newConnectionString = builder.ToString();
152+
153+
var result = new List<string>();
154+
using (NpgsqlConnection conn = new NpgsqlConnection(newConnectionString))
155+
{
156+
conn.Open();
157+
string cmdText = $"SELECT datName FROM pg_database WHERE datname LIKE '{orgDbStartsWith}%'";
158+
using (NpgsqlCommand cmd = new NpgsqlCommand(cmdText, conn))
159+
{
160+
using (var reader = cmd.ExecuteReader())
161+
{
162+
while (reader.Read())
163+
{
164+
result.Add(reader.GetString(0));
165+
}
166+
}
167+
}
168+
}
169+
170+
return result;
171+
}
93172
}
94173
}

TestSupport/EfHelpers/PostgreSqlHelpers.cs

Lines changed: 7 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
// Licensed under MIT license. See License.txt in the project root for license information.
33

44
using System;
5-
using System.Collections.Generic;
6-
using System.Reflection;
75
using System.Runtime.CompilerServices;
86
using System.Threading.Tasks;
97
using Microsoft.EntityFrameworkCore;
@@ -83,10 +81,6 @@ public static DbContextOptions<T> CreatePostgreSqlUniqueMethodOptions<T>(this ob
8381
//------------------------------------------------------------
8482
//methods to provide empty PostgreSql databases and how to delete all the PostgreSql databases used for unit testing
8583

86-
static Checkpoint EmptyCheckpoint = new Checkpoint
87-
{
88-
DbAdapter = DbAdapter.Postgres
89-
};
9084

9185
/// <summary>
9286
/// This will ensure that there is a PostgreSql database, and that database has no rows in any tables
@@ -99,7 +93,12 @@ public static DbContextOptions<T> CreatePostgreSqlUniqueMethodOptions<T>(this ob
9993
public async static Task EnsureCreatedAndEmptyPostgreSqlAsync<T>(this T context)
10094
where T : DbContext
10195
{
102-
if(!context.Database.EnsureCreated())
96+
Checkpoint EmptyCheckpoint = new Checkpoint
97+
{
98+
DbAdapter = DbAdapter.Postgres
99+
};
100+
101+
if (!context.Database.EnsureCreated())
103102
{
104103
//the database arealy exists, so we just need to empty the tables
105104

@@ -137,52 +136,9 @@ public async static Task EnsureCreatedAndEmptyPostgreSqlAsync<T>(this T context)
137136
};
138137
}
139138

140-
/// <summary>
141-
/// This will delete all PostgreSql databases that start with the database name in the default connection string
142-
/// WARNING: This will delete multiple databases - make sure your <see cref="AppSettings.PostgreSqlConnectionString"/> database name is unique!!!
143-
/// </summary>
144-
/// <returns>Number of databases deleted</returns>
145-
public static int DeleteAllPostgreSqlUnitTestDatabases()
146-
{
147-
var config = AppSettings.GetConfiguration(Assembly.GetCallingAssembly());
148-
var baseConnection = config.GetConnectionString(AppSettings.PostgreSqlConnectionString);
149-
if (string.IsNullOrEmpty(baseConnection))
150-
throw new InvalidOperationException(
151-
$"Your {AppSettings.AppSettingFilename} file isn't set up for the '{AppSettings.PostgreSqlConnectionString}'.");
152-
153-
var databaseNamesToDelete = baseConnection.GetAllPostgreUnitTestDatabases();
154-
155-
var builder = new NpgsqlConnectionStringBuilder(baseConnection);
156-
builder.Database = "postgres";
157-
foreach (var databaseName in databaseNamesToDelete)
158-
{
159-
builder.ToString().ExecuteScalars(
160-
$"REVOKE CONNECT ON DATABASE \"{databaseName}\" FROM PUBLIC",
161-
"SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity " +
162-
$"WHERE datname = '{databaseName}'",
163-
$"DROP DATABASE \"{databaseName}\""
164-
);
165-
}
166-
return databaseNamesToDelete.Count;
167-
}
168-
169-
//------------------------------------
139+
//------------------------------------------------
170140
//private methods
171141

172-
private static void ExecuteScalars(this string connectionString, params string[] commands)
173-
{
174-
using (NpgsqlConnection conn = new NpgsqlConnection(connectionString))
175-
{
176-
conn.Open();
177-
foreach(var commandText in commands)
178-
{
179-
using (NpgsqlCommand cmd = new NpgsqlCommand(commandText, conn))
180-
{
181-
var result = cmd.ExecuteScalar();
182-
}
183-
}
184-
}
185-
}
186142

187143
private static DbContextOptionsBuilder<T> CreatePostgreSqlOptionWithDatabaseName<T>(object callingClass,
188144
string callingMember, Action<DbContextOptionsBuilder<T>> extraOptions)
@@ -197,31 +153,6 @@ private static DbContextOptionsBuilder<T> CreatePostgreSqlOptionWithDatabaseName
197153
return builder;
198154
}
199155

200-
private static List<string> GetAllPostgreUnitTestDatabases(this string connectionString)
201-
{
202-
var builder = new NpgsqlConnectionStringBuilder(connectionString);
203-
var orgDbStartsWith = builder.Database;
204-
builder.Database = "postgres";
205-
var newConnectionString = builder.ToString();
206156

207-
var result = new List<string>();
208-
using (NpgsqlConnection conn = new NpgsqlConnection(newConnectionString))
209-
{
210-
conn.Open();
211-
string cmdText = $"SELECT datName FROM pg_database WHERE datname LIKE '{orgDbStartsWith}%'";
212-
using (NpgsqlCommand cmd = new NpgsqlCommand(cmdText, conn))
213-
{
214-
using (var reader = cmd.ExecuteReader())
215-
{
216-
while (reader.Read())
217-
{
218-
result.Add(reader.GetString(0));
219-
}
220-
}
221-
}
222-
}
223-
224-
return result;
225-
}
226157
}
227158
}

TestSupport/TestSupport.csproj

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,11 @@
5151
<Description>Useful tools when unit testing applications that use Entity Framework Core. See readme file on github.</Description>
5252
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
5353
<PackageReleaseNotes>
54-
- Updated to support both EF Core 5 and EF Core 6-rc.2 preview
55-
- Added PostgreSQL database helpers, including EnsureClean
56-
- Added the Seed Database feature back in at request of users
57-
- Removed obsolete methods: ...OptionsWithLogging (use ...OptionsWithLogTo), CreateEmptyViaWipe (use EncureClean)
54+
- BREAKING CHANGE: Renamed DeleteAllUnitTestDatabases to DeleteAllSqlServerTestDatabases
55+
- REMOVED obsolete methods: ...OptionsWithLogging (use ...OptionsWithLogTo), CreateEmptyViaWipe (use EnsureClean)
56+
- NET6 Support: Updated to support both EF Core 5 and EF Core 6-rc.2 preview (see docs)
57+
- New Feature: Added PostgreSQL database helpers, including EnsureClean
58+
- Feature: Reinstated the Seed Database feature to this version due to requests from users
5859
</PackageReleaseNotes>
5960
<Copyright>Copyright (c) 2020 Jon P Smith. Licenced under MIT licence</Copyright>
6061
<PackageTags>Entity Framework Core, xUnit</PackageTags>

0 commit comments

Comments
 (0)