-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseHelper.cs
More file actions
196 lines (167 loc) · 6.64 KB
/
DatabaseHelper.cs
File metadata and controls
196 lines (167 loc) · 6.64 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
using System;
using System.Data;
using System.Data.SqlClient;
namespace IntegrationTestSample
{
internal static class DatabaseHelper
{
#region SQL Scripts
private const string ExistsDatabaseCommand = "SELECT COUNT(*) FROM sys.databases WHERE NAME=@dbName";
private const string CreateDatabaseCommand = @"
IF NOT EXISTS (SELECT * FROM sys.databases WHERE NAME=@dbName)
BEGIN
DECLARE @sql nvarchar(500);
SET @sql = N'CREATE DATABASE ' + QUOTENAME(@dbName)
EXECUTE sp_executesql @sql;
END
";
private const string DropDatabaseCommand = @"
IF EXISTS (SELECT * FROM sys.databases WHERE NAME=@dbName)
BEGIN
DECLARE @sql nvarchar(500);
SET @sql = N'ALTER DATABASE ' + QUOTENAME(@dbName) + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DROP DATABASE '+ QUOTENAME(@dbName)
EXECUTE sp_executesql @sql;
END
";
#endregion
public static bool Exists(string connectionString)
{
// If we can get the database name we'll check the Master database as it's faster than trying to connect to non existing databases
if (TryGetDatabaseName(connectionString, out string databaseName))
{
try
{
using (var con = new SqlConnection(MasterConnectionString(connectionString)))
{
con.Open();
using (var cmd = con.CreateCommand())
{
cmd.CommandText = ExistsDatabaseCommand;
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 300;
cmd.Parameters.Add(new SqlParameter { ParameterName = "dbName", Value = databaseName });
var masterCheck = Convert.ToInt32(cmd.ExecuteScalar());
return masterCheck == 1;
}
}
}
catch (SqlException)
{
// Checking for the exact type of SqlException here could help when troubleshooting
}
}
// If we couldn't use the Master database, try connecting directly (slow!)
try
{
using (var con = new SqlConnection(connectionString))
{
con.Open();
return true;
}
}
catch (SqlException ex)
{
// Login failed is thrown when the database does not exist
if (ex.Number == 4060)
{
return false;
}
throw;
}
}
public static void Create(string connectionString)
{
if (!TryGetDatabaseName(connectionString, out string databaseName))
{
throw new ArgumentException($"Unabled to extract the database name from the provided connection string '{connectionString}'.");
}
using (var con = new SqlConnection(MasterConnectionString(connectionString)))
{
con.Open();
using (var cmd = con.CreateCommand())
{
cmd.CommandText = CreateDatabaseCommand;
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 300;
cmd.Parameters.Add(new SqlParameter { ParameterName = "dbName", Value = databaseName });
cmd.ExecuteNonQuery();
}
}
// Clearing the connection pool seems to help avoid login errors directly after creation
SqlConnection.ClearAllPools();
}
public static void Drop(string connectionString)
{
if (!TryGetDatabaseName(connectionString, out string databaseName))
{
return;
}
SqlConnection.ClearAllPools();
using (var con = new SqlConnection(MasterConnectionString(connectionString)))
{
con.Open();
using (var cmd = con.CreateCommand())
{
cmd.CommandText = DropDatabaseCommand;
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 300;
cmd.Parameters.Add(new SqlParameter { ParameterName = "dbName", Value = databaseName });
cmd.ExecuteNonQuery();
}
}
SqlConnection.ClearAllPools();
}
/// <summary>
/// Create a temporary database that will be dropped when this class is disposed.
/// </summary>
public static IDisposable Temporary(string connectionString, bool throwIfExists = true, bool onlyDropIfCreated = true)
{
return new TemporaryDatabase(connectionString, throwIfExists, onlyDropIfCreated);
}
private static bool TryGetDatabaseName(string connectionString, out string name)
{
var builder = new SqlConnectionStringBuilder(connectionString);
if (!string.IsNullOrEmpty(builder.AttachDBFilename))
{
name = null;
return false;
}
name = builder.InitialCatalog;
return !string.IsNullOrWhiteSpace(name);
}
private static string MasterConnectionString(string connectionString)
{
return new SqlConnectionStringBuilder(connectionString) { InitialCatalog = "master" }.ConnectionString;
}
private class TemporaryDatabase : IDisposable
{
private readonly string _connectionString;
private readonly bool _shouldDrop;
public TemporaryDatabase(string connectionString, bool throwIfExists, bool onlyDropIfCreated)
{
_connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
if (Exists(connectionString))
{
if (throwIfExists)
{
throw new ArgumentException($"A database already exist for the provided connection '{connectionString}'.", nameof(connectionString));
}
_shouldDrop = !onlyDropIfCreated;
}
else
{
Create(connectionString);
_shouldDrop = true;
}
}
public void Dispose()
{
if (_shouldDrop)
{
Drop(_connectionString);
}
}
}
}
}