-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseCommand.cs
More file actions
63 lines (50 loc) · 2.07 KB
/
DatabaseCommand.cs
File metadata and controls
63 lines (50 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using DbUp;
using DbUp.Engine;
using DbUp.Helpers;
using Microsoft.Data.SqlClient;
namespace Migratonator;
internal abstract class DatabaseCommand : ICommand
{
// putting this in a constant because it _will_ change someday!
public const string PrimaryDatabaseName = "master";
protected DatabaseCommand(Options configuration)
{
Configuration = configuration;
}
private Options Configuration { get; }
public void Perform()
{
// parse the connection string, so the database name can be extracted
var connectionStringBuilder = new SqlConnectionStringBuilder(Configuration.ConnectionString);
var databaseName = connectionStringBuilder.InitialCatalog;
// change the database name in the connection string
// since creating or dropping a database requires being
// connected to the primary database (`master` circa 2023)
connectionStringBuilder.InitialCatalog = PrimaryDatabaseName;
// create a script to perform the action
var actionScript = new SqlScript(
$"{UserFriendlyAction} Database",
SqlStatement(databaseName)
);
var migrator = DeployChanges.To
.SqlDatabase(connectionStringBuilder.ConnectionString)
.JournalTo(new NullJournal())
.WithScript(actionScript)
.WithExecutionTimeout(Configuration.ExecutionTimeout)
.WithoutTransaction()
.Build();
if (!Configuration.Confirm &&
!BaseCommand.PromptUserToContinue($"{UserFriendlyAction} '{databaseName}' database?"))
return;
Console.WriteLine($"Applying {UserFriendlyAction} '{databaseName}' database...");
var result = migrator.PerformUpgrade();
if (!result.Successful)
{
BaseCommand.ReportFailure(result.Error.ToString());
return;
}
BaseCommand.ReportSuccess($"{UserFriendlyAction} database succeeded!");
}
protected abstract string UserFriendlyAction { get; }
protected abstract string SqlStatement(string databaseName);
}