-
Notifications
You must be signed in to change notification settings - Fork 528
/
SqlServerExtensions.cs
402 lines (362 loc) · 18.3 KB
/
SqlServerExtensions.cs
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
using System;
using System.Data;
using System.Data.SqlClient;
using DbUp;
using DbUp.Builder;
using DbUp.Engine.Output;
using DbUp.Engine.Transactions;
using DbUp.SqlServer;
/// <summary>
/// Configuration extension methods for SQL Server.
/// </summary>
// NOTE: DO NOT MOVE THIS TO A NAMESPACE
// Since the class just contains extension methods, we leave it in the global:: namespace so that it is always available
// ReSharper disable CheckNamespace
public static class SqlServerExtensions
// ReSharper restore CheckNamespace
{
/// <summary>
/// Creates an upgrader for SQL Server databases.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <returns>
/// A builder for a database upgrader designed for SQL Server databases.
/// </returns>
public static UpgradeEngineBuilder SqlDatabase(this SupportedDatabases supported, string connectionString)
{
return SqlDatabase(supported, connectionString, null);
}
/// <summary>
/// Creates an upgrader for SQL Server databases.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="schema">The SQL schema name to use. Defaults to 'dbo'.</param>
/// <returns>
/// A builder for a database upgrader designed for SQL Server databases.
/// </returns>
public static UpgradeEngineBuilder SqlDatabase(this SupportedDatabases supported, string connectionString, string schema)
{
return SqlDatabase(new SqlConnectionManager(connectionString), schema);
}
#if SUPPORTS_AZURE_AD
/// <summary>
/// Creates an upgrader for SQL Server databases.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="schema">The SQL schema name to use. Defaults to 'dbo' if null.</param>
/// <param name="useAzureSqlIntegratedSecurity">Whether to use Azure SQL Integrated Security</param>
/// <returns>
/// A builder for a database upgrader designed for SQL Server databases.
/// </returns>
public static UpgradeEngineBuilder SqlDatabase(this SupportedDatabases supported, string connectionString, string schema, bool useAzureSqlIntegratedSecurity)
{
return SqlDatabase(new SqlConnectionManager(connectionString, useAzureSqlIntegratedSecurity), schema);
}
#endif
/// <summary>
/// Creates an upgrader for SQL Server databases.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionManager">The <see cref="IConnectionManager"/> to be used during a database
/// upgrade. See <see cref="SqlConnectionManager"/> for an example implementation</param>
/// <param name="schema">The SQL schema name to use. Defaults to 'dbo'.</param>
/// <returns>
/// A builder for a database upgrader designed for SQL Server databases.
/// </returns>
public static UpgradeEngineBuilder SqlDatabase(this SupportedDatabases supported, IConnectionManager connectionManager, string schema = null)
=> SqlDatabase(connectionManager, schema);
/// <summary>
/// Creates an upgrader for SQL Server databases.
/// </summary>
/// <param name="connectionManager">The <see cref="IConnectionManager"/> to be used during a database
/// upgrade. See <see cref="SqlConnectionManager"/> for an example implementation</param>
/// <param name="schema">The SQL schema name to use. Defaults to 'dbo'.</param>
/// <returns>
/// A builder for a database upgrader designed for SQL Server databases.
/// </returns>
static UpgradeEngineBuilder SqlDatabase(IConnectionManager connectionManager, string schema)
{
var builder = new UpgradeEngineBuilder();
builder.Configure(c => c.ConnectionManager = connectionManager);
builder.Configure(c => c.ScriptExecutor = new SqlScriptExecutor(() => c.ConnectionManager, () => c.Log, schema, () => c.VariablesEnabled, c.ScriptPreprocessors, () => c.Journal));
builder.Configure(c => c.Journal = new SqlTableJournal(() => c.ConnectionManager, () => c.Log, schema, "SchemaVersions"));
return builder;
}
/// <summary>
/// Tracks the list of executed scripts in a SQL Server table.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="schema">The schema.</param>
/// <param name="table">The table.</param>
/// <returns></returns>
public static UpgradeEngineBuilder JournalToSqlTable(this UpgradeEngineBuilder builder, string schema, string table)
{
builder.Configure(c => c.Journal = new SqlTableJournal(() => c.ConnectionManager, () => c.Log, schema, table));
return builder;
}
#if SUPPORTS_SQL_CONTEXT
/// <summary>
/// Logs to SqlContext.Pipe, for use with "context connection=true".
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns>
/// The same builder
/// </returns>
public static UpgradeEngineBuilder LogToSqlContext(this UpgradeEngineBuilder builder)
{
return builder.LogTo(new SqlContextUpgradeLog());
}
#endif
/// <summary>
/// Ensures that the database specified in the connection string exists.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <returns></returns>
public static void SqlDatabase(this SupportedDatabasesForEnsureDatabase supported, string connectionString)
{
SqlDatabase(supported, connectionString, new ConsoleUpgradeLog());
}
/// <summary>
/// Ensures that the database specified in the connection string exists.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="azureDatabaseEdition">Azure edition to Create</param>
/// <returns></returns>
public static void SqlDatabase(this SupportedDatabasesForEnsureDatabase supported, string connectionString, AzureDatabaseEdition azureDatabaseEdition)
{
SqlDatabase(supported, connectionString, new ConsoleUpgradeLog(), -1, azureDatabaseEdition);
}
/// <summary>
/// Ensures that the database specified in the connection string exists.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="commandTimeout">Use this to set the command time out for creating a database in case you're encountering a time out in this operation.</param>
/// <returns></returns>
public static void SqlDatabase(this SupportedDatabasesForEnsureDatabase supported, string connectionString, int commandTimeout)
{
SqlDatabase(supported, connectionString, new ConsoleUpgradeLog(), commandTimeout);
}
/// <summary>
/// Ensures that the database specified in the connection string exists.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="collation">The collation name to set during database creation</param>
/// <returns></returns>
public static void SqlDatabase(this SupportedDatabasesForEnsureDatabase supported, string connectionString, string collation)
{
SqlDatabase(supported, connectionString, new ConsoleUpgradeLog(), collation: collation);
}
/// <summary>
/// Ensures that the database specified in the connection string exists.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="commandTimeout">Use this to set the command time out for creating a database in case you're encountering a time out in this operation.</param>
/// <param name="azureDatabaseEdition">Azure edition to Create</param>
/// <returns></returns>
public static void SqlDatabase(this SupportedDatabasesForEnsureDatabase supported, string connectionString, int commandTimeout, AzureDatabaseEdition azureDatabaseEdition)
{
SqlDatabase(supported, connectionString, new ConsoleUpgradeLog(), commandTimeout, azureDatabaseEdition);
}
/// <summary>
/// Ensures that the database specified in the connection string exists.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="commandTimeout">Use this to set the command time out for creating a database in case you're encountering a time out in this operation.</param>
/// <param name="collation">The collation name to set during database creation</param>
/// <returns></returns>
public static void SqlDatabase(this SupportedDatabasesForEnsureDatabase supported, string connectionString, int commandTimeout, string collation)
{
SqlDatabase(supported, connectionString, new ConsoleUpgradeLog(), commandTimeout, collation: collation);
}
/// <summary>
/// Ensures that the database specified in the connection string exists.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="azureDatabaseEdition">Azure edition to Create</param>
/// <param name="collation">The collation name to set during database creation</param>
/// <returns></returns>
public static void SqlDatabase(this SupportedDatabasesForEnsureDatabase supported, string connectionString, AzureDatabaseEdition azureDatabaseEdition, string collation)
{
SqlDatabase(supported, connectionString, new ConsoleUpgradeLog(), azureDatabaseEdition: azureDatabaseEdition, collation: collation);
}
/// <summary>
/// Ensures that the database specified in the connection string exists.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="commandTimeout">Use this to set the command time out for creating a database in case you're encountering a time out in this operation.</param>
/// <param name="azureDatabaseEdition">Azure edition to Create</param>
/// <param name="collation">The collation name to set during database creation</param>
/// <returns></returns>
public static void SqlDatabase(this SupportedDatabasesForEnsureDatabase supported, string connectionString, int commandTimeout, AzureDatabaseEdition azureDatabaseEdition, string collation)
{
SqlDatabase(supported, connectionString, new ConsoleUpgradeLog(), commandTimeout, azureDatabaseEdition, collation);
}
/// <summary>
/// Ensures that the database specified in the connection string exists.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="logger">The <see cref="DbUp.Engine.Output.IUpgradeLog"/> used to record actions.</param>
/// <param name="timeout">Use this to set the command time out for creating a database in case you're encountering a time out in this operation.</param>
/// <param name="azureDatabaseEdition">Use to indicate that the SQL server database is in Azure</param>
/// <param name="collation">The collation name to set during database creation</param>
/// <returns></returns>
public static void SqlDatabase(
this SupportedDatabasesForEnsureDatabase supported,
string connectionString,
IUpgradeLog logger,
int timeout = -1,
AzureDatabaseEdition azureDatabaseEdition = AzureDatabaseEdition.None,
string collation = null)
{
GetMasterConnectionStringBuilder(connectionString, logger, out var masterConnectionString, out var databaseName);
try
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
if (DatabaseExists(connection, databaseName))
return;
}
}
catch (Exception e)
{
logger.WriteInformation(@"Database not found on server with connection string in settings: {0}", e.Message);
}
using (var connection = new SqlConnection(masterConnectionString))
{
connection.Open();
if (DatabaseExists(connection, databaseName))
return;
var collationString = string.IsNullOrEmpty(collation) ? "" : string.Format(@" COLLATE {0}", collation);
var sqlCommandText = string.Format
(
@"create database [{0}]{1}",
databaseName,
collationString
);
switch (azureDatabaseEdition)
{
case AzureDatabaseEdition.None:
sqlCommandText += ";";
break;
case AzureDatabaseEdition.Basic:
sqlCommandText += " ( EDITION = ''basic'' );";
break;
case AzureDatabaseEdition.Standard:
sqlCommandText += " ( EDITION = ''standard'' );";
break;
case AzureDatabaseEdition.Premium:
sqlCommandText += " ( EDITION = ''premium'' );";
break;
}
// Create the database...
using (var command = new SqlCommand(sqlCommandText, connection)
{
CommandType = CommandType.Text
})
{
if (timeout >= 0)
{
command.CommandTimeout = timeout;
}
command.ExecuteNonQuery();
}
logger.WriteInformation(@"Created database {0}", databaseName);
}
}
/// <summary>
/// Drop the database specified in the connection string.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <returns></returns>
public static void SqlDatabase(this SupportedDatabasesForDropDatabase supported, string connectionString)
{
SqlDatabase(supported, connectionString, new ConsoleUpgradeLog());
}
/// <summary>
/// Drop the database specified in the connection string.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="commandTimeout">Use this to set the command time out for dropping a database in case you're encountering a time out in this operation.</param>
/// <returns></returns>
public static void SqlDatabase(this SupportedDatabasesForDropDatabase supported, string connectionString, int commandTimeout)
{
SqlDatabase(supported, connectionString, new ConsoleUpgradeLog(), commandTimeout);
}
/// <summary>
/// Drop the database specified in the connection string.
/// </summary>
/// <param name="supported">Fluent helper type.</param>
/// <param name="connectionString">The connection string.</param>
/// <param name="logger">The <see cref="DbUp.Engine.Output.IUpgradeLog"/> used to record actions.</param>
/// <param name="timeout">Use this to set the command time out for dropping a database in case you're encountering a time out in this operation.</param>
/// <returns></returns>
public static void SqlDatabase(this SupportedDatabasesForDropDatabase supported, string connectionString, IUpgradeLog logger, int timeout = -1)
{
GetMasterConnectionStringBuilder(connectionString, logger, out var masterConnectionString, out var databaseName);
using (var connection = new SqlConnection(masterConnectionString))
{
connection.Open();
if (!DatabaseExists(connection, databaseName))
return;
var dropDatabaseCommand = new SqlCommand($"ALTER DATABASE [{databaseName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [{databaseName}];", connection) { CommandType = CommandType.Text };
using (var command = dropDatabaseCommand)
{
command.ExecuteNonQuery();
}
logger.WriteInformation("Dropped database {0}", databaseName);
}
}
static void GetMasterConnectionStringBuilder(string connectionString, IUpgradeLog logger, out string masterConnectionString, out string databaseName)
{
if (string.IsNullOrEmpty(connectionString) || connectionString.Trim() == string.Empty)
throw new ArgumentNullException("connectionString");
if (logger == null)
throw new ArgumentNullException("logger");
var masterConnectionStringBuilder = new SqlConnectionStringBuilder(connectionString);
databaseName = masterConnectionStringBuilder.InitialCatalog;
if (string.IsNullOrEmpty(databaseName) || databaseName.Trim() == string.Empty)
throw new InvalidOperationException("The connection string does not specify a database name.");
masterConnectionStringBuilder.InitialCatalog = "master";
var logMasterConnectionStringBuilder = new SqlConnectionStringBuilder(masterConnectionStringBuilder.ConnectionString)
{
Password = string.Empty.PadRight(masterConnectionStringBuilder.Password.Length, '*')
};
logger.WriteInformation("Master ConnectionString => {0}", logMasterConnectionStringBuilder.ConnectionString);
masterConnectionString = masterConnectionStringBuilder.ConnectionString;
}
static bool DatabaseExists(SqlConnection connection, string databaseName)
{
var sqlCommandText = string.Format
(
@"SELECT TOP 1 case WHEN dbid IS NOT NULL THEN 1 ELSE 0 end FROM sys.sysdatabases WHERE name = '{0}';",
databaseName
);
// check to see if the database already exists..
using (var command = new SqlCommand(sqlCommandText, connection)
{
CommandType = CommandType.Text
})
{
var results = (int?)command.ExecuteScalar();
if (results.HasValue && results.Value == 1)
return true;
else
return false;
}
}
}