|
| 1 | +using DbUp.Engine.Output; |
| 2 | +using DbUp.SqlServer; |
| 3 | +using Microsoft.Azure.Services.AppAuthentication; |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Data; |
| 7 | +using System.Data.SqlClient; |
| 8 | +using System.Text; |
| 9 | + |
| 10 | +namespace DbUp.Cli.DbUpCustomization |
| 11 | +{ |
| 12 | + static class AzureSqlDatabaseWithIntegratedSecurity |
| 13 | + { |
| 14 | + /* |
| 15 | + * CAUTION!!! This code is copied from original file https://github.com/DbUp/DbUp/blob/master/src/dbup-sqlserver/SqlServerExtensions.cs |
| 16 | + * The reason is that the DbUp does not fully support AzureSQL. |
| 17 | + * More discussions see in https://github.com/drwatson1/dbup-cli/issues/16 |
| 18 | + */ |
| 19 | + |
| 20 | + /// <summary> |
| 21 | + /// Ensures that the database specified in the connection string exists. |
| 22 | + /// </summary> |
| 23 | + /// <param name="supported">Fluent helper type.</param> |
| 24 | + /// <param name="connectionString">The connection string.</param> |
| 25 | + /// <param name="logger">The <see cref="DbUp.Engine.Output.IUpgradeLog"/> used to record actions.</param> |
| 26 | + /// <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> |
| 27 | + /// <param name="azureDatabaseEdition">Use to indicate that the SQL server database is in Azure</param> |
| 28 | + /// <param name="collation">The collation name to set during database creation</param> |
| 29 | + /// <returns></returns> |
| 30 | + public static void AzureSqlDatabase( |
| 31 | + this SupportedDatabasesForEnsureDatabase supported, |
| 32 | + string connectionString, |
| 33 | + IUpgradeLog logger, |
| 34 | + int timeout = -1, |
| 35 | + AzureDatabaseEdition azureDatabaseEdition = AzureDatabaseEdition.None, |
| 36 | + string collation = null) |
| 37 | + { |
| 38 | + GetMasterConnectionStringBuilder(connectionString, logger, out var masterConnectionString, out var databaseName); |
| 39 | + |
| 40 | + using (var connection = new SqlConnection(masterConnectionString)) |
| 41 | + { |
| 42 | + connection.AccessToken = GetAccessToken(); |
| 43 | + try |
| 44 | + { |
| 45 | + connection.Open(); |
| 46 | + } |
| 47 | + catch (SqlException) |
| 48 | + { |
| 49 | + // Failed to connect to master, lets try direct |
| 50 | + if (DatabaseExistsIfConnectedToDirectly(logger, connectionString, databaseName)) |
| 51 | + return; |
| 52 | + |
| 53 | + throw; |
| 54 | + } |
| 55 | + |
| 56 | + if (DatabaseExists(connection, databaseName)) |
| 57 | + return; |
| 58 | + |
| 59 | + var collationString = string.IsNullOrEmpty(collation) ? "" : $@" COLLATE {collation}"; |
| 60 | + var sqlCommandText = $@"create database [{databaseName}]{collationString}"; |
| 61 | + |
| 62 | + switch (azureDatabaseEdition) |
| 63 | + { |
| 64 | + case AzureDatabaseEdition.None: |
| 65 | + sqlCommandText += ";"; |
| 66 | + break; |
| 67 | + case AzureDatabaseEdition.Basic: |
| 68 | + sqlCommandText += " ( EDITION = ''basic'' );"; |
| 69 | + break; |
| 70 | + case AzureDatabaseEdition.Standard: |
| 71 | + sqlCommandText += " ( EDITION = ''standard'' );"; |
| 72 | + break; |
| 73 | + case AzureDatabaseEdition.Premium: |
| 74 | + sqlCommandText += " ( EDITION = ''premium'' );"; |
| 75 | + break; |
| 76 | + } |
| 77 | + |
| 78 | + // Create the database... |
| 79 | + using (var command = new SqlCommand(sqlCommandText, connection) |
| 80 | + { |
| 81 | + CommandType = CommandType.Text |
| 82 | + }) |
| 83 | + { |
| 84 | + if (timeout >= 0) |
| 85 | + { |
| 86 | + command.CommandTimeout = timeout; |
| 87 | + } |
| 88 | + |
| 89 | + command.ExecuteNonQuery(); |
| 90 | + } |
| 91 | + |
| 92 | + logger.WriteInformation(@"Created database {0}", databaseName); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + /// <summary> |
| 97 | + /// Drop the database specified in the connection string. |
| 98 | + /// </summary> |
| 99 | + /// <param name="supported">Fluent helper type.</param> |
| 100 | + /// <param name="connectionString">The connection string.</param> |
| 101 | + /// <param name="logger">The <see cref="DbUp.Engine.Output.IUpgradeLog"/> used to record actions.</param> |
| 102 | + /// <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> |
| 103 | + /// <returns></returns> |
| 104 | + public static void AzureSqlDatabase(this SupportedDatabasesForDropDatabase supported, string connectionString, IUpgradeLog logger, int timeout = -1) |
| 105 | + { |
| 106 | + GetMasterConnectionStringBuilder(connectionString, logger, out var masterConnectionString, out var databaseName); |
| 107 | + |
| 108 | + using (var connection = new SqlConnection(masterConnectionString)) |
| 109 | + { |
| 110 | + connection.AccessToken = GetAccessToken(); |
| 111 | + |
| 112 | + connection.Open(); |
| 113 | + if (!DatabaseExists(connection, databaseName)) |
| 114 | + return; |
| 115 | + |
| 116 | + // Actually we should call ALTER DATABASE [{databaseName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; |
| 117 | + // before DROP as for the SQL Server, |
| 118 | + // but it does not work with the following error message: |
| 119 | + // |
| 120 | + // ODBC error: State: 42000: Error: 1468 Message:'[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The operation cannot be performed on database "MYNEWDB" because it is involved in a database mirroring session or an availability group. Some operations are not allowed on a database that is participating in a database mirroring session or in an availability group.'. |
| 121 | + // ALTER DATABASE statement failed. |
| 122 | + // |
| 123 | + // Experiment shows that DROP works fine even the other user is connected. |
| 124 | + // So single user mode is not necessary for Azure SQL |
| 125 | + var dropDatabaseCommand = new SqlCommand($"DROP DATABASE [{databaseName}];", connection) { CommandType = CommandType.Text }; |
| 126 | + using (var command = dropDatabaseCommand) |
| 127 | + { |
| 128 | + command.ExecuteNonQuery(); |
| 129 | + } |
| 130 | + |
| 131 | + logger.WriteInformation("Dropped database {0}", databaseName); |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + static void GetMasterConnectionStringBuilder(string connectionString, IUpgradeLog logger, out string masterConnectionString, out string databaseName) |
| 136 | + { |
| 137 | + if (string.IsNullOrEmpty(connectionString) || connectionString.Trim() == string.Empty) |
| 138 | + throw new ArgumentNullException("connectionString"); |
| 139 | + |
| 140 | + if (logger == null) |
| 141 | + throw new ArgumentNullException("logger"); |
| 142 | + |
| 143 | + var masterConnectionStringBuilder = new SqlConnectionStringBuilder(connectionString); |
| 144 | + databaseName = masterConnectionStringBuilder.InitialCatalog; |
| 145 | + |
| 146 | + if (string.IsNullOrEmpty(databaseName) || databaseName.Trim() == string.Empty) |
| 147 | + throw new InvalidOperationException("The connection string does not specify a database name."); |
| 148 | + |
| 149 | + masterConnectionStringBuilder.InitialCatalog = "master"; |
| 150 | + var logMasterConnectionStringBuilder = new SqlConnectionStringBuilder(masterConnectionStringBuilder.ConnectionString) |
| 151 | + { |
| 152 | + Password = string.Empty.PadRight(masterConnectionStringBuilder.Password.Length, '*') |
| 153 | + }; |
| 154 | + |
| 155 | + logger.WriteInformation("Master ConnectionString => {0}", logMasterConnectionStringBuilder.ConnectionString); |
| 156 | + masterConnectionString = masterConnectionStringBuilder.ConnectionString; |
| 157 | + } |
| 158 | + |
| 159 | + static bool DatabaseExists(SqlConnection connection, string databaseName) |
| 160 | + { |
| 161 | + var sqlCommandText = string.Format |
| 162 | + ( |
| 163 | + @"SELECT TOP 1 case WHEN dbid IS NOT NULL THEN 1 ELSE 0 end FROM sys.sysdatabases WHERE name = '{0}';", |
| 164 | + databaseName |
| 165 | + ); |
| 166 | + |
| 167 | + // check to see if the database already exists.. |
| 168 | + using (var command = new SqlCommand(sqlCommandText, connection) |
| 169 | + { |
| 170 | + CommandType = CommandType.Text |
| 171 | + }) |
| 172 | + |
| 173 | + { |
| 174 | + var results = (int?)command.ExecuteScalar(); |
| 175 | + |
| 176 | + if (results.HasValue && results.Value == 1) |
| 177 | + return true; |
| 178 | + else |
| 179 | + return false; |
| 180 | + } |
| 181 | + } |
| 182 | + |
| 183 | + static bool DatabaseExistsIfConnectedToDirectly(IUpgradeLog logger, string connectionString, string databaseName) |
| 184 | + { |
| 185 | + try |
| 186 | + { |
| 187 | + using (var connection = new SqlConnection(connectionString)) |
| 188 | + { |
| 189 | + connection.AccessToken = GetAccessToken(); |
| 190 | + |
| 191 | + connection.Open(); |
| 192 | + return DatabaseExists(connection, databaseName); |
| 193 | + } |
| 194 | + } |
| 195 | + catch |
| 196 | + { |
| 197 | + logger.WriteInformation("Could not connect to the database directly"); |
| 198 | + return false; |
| 199 | + } |
| 200 | + } |
| 201 | + |
| 202 | + static string GetAccessToken(string resource = "https://database.windows.net/", string tenantId = null, string azureAdInstance = "https://login.microsoftonline.com/") |
| 203 | + { |
| 204 | + return new AzureServiceTokenProvider(azureAdInstance: azureAdInstance).GetAccessTokenAsync(resource, tenantId) |
| 205 | + .ConfigureAwait(false) |
| 206 | + .GetAwaiter() |
| 207 | + .GetResult(); |
| 208 | + } |
| 209 | + } |
| 210 | +} |
0 commit comments