|
| 1 | +using Microsoft.Data.SqlClient; |
| 2 | +using Microsoft.Extensions.Logging; |
| 3 | +using System.Data; |
| 4 | +using System.Security.Cryptography; |
| 5 | + |
| 6 | +namespace CommunityToolkit.Aspire.Hosting.SqlDatabaseProjects; |
| 7 | + |
| 8 | +internal class DacpacChecksumService : IDacpacChecksumService |
| 9 | +{ |
| 10 | + public async Task<string?> CheckIfDeployedAsync(string dacpacPath, string targetConnectionString, ILogger logger, CancellationToken cancellationToken) |
| 11 | + { |
| 12 | + var targetDatabaseName = GetDatabaseName(targetConnectionString); |
| 13 | + |
| 14 | + var dacpacPathChecksum = GetStringChecksum(dacpacPath); |
| 15 | + |
| 16 | + var dacpacChecksum = await GetChecksumAsync(dacpacPath); |
| 17 | + |
| 18 | + using var connection = new SqlConnection(targetConnectionString); |
| 19 | + |
| 20 | + try |
| 21 | + { |
| 22 | + // Try to connect to the target database to see if it exists and fail fast if it does not. |
| 23 | + await connection.OpenAsync(SqlConnectionOverrides.OpenWithoutRetry, cancellationToken); |
| 24 | + } |
| 25 | + catch (Exception ex) when (ex is InvalidOperationException || ex is SqlException) |
| 26 | + { |
| 27 | + logger.LogWarning(ex, "Target database {TargetDatabase} is not available.", targetDatabaseName); |
| 28 | + return dacpacChecksum; |
| 29 | + } |
| 30 | + |
| 31 | + var deployed = await CheckExtendedPropertyAsync(connection, dacpacPathChecksum, dacpacChecksum, cancellationToken); |
| 32 | + |
| 33 | + if (deployed) |
| 34 | + { |
| 35 | + logger.LogInformation("The .dacpac with checksum {DacpacChecksum} has already been deployed to database {TargetDatabaseName}.", dacpacChecksum, targetDatabaseName); |
| 36 | + return null; |
| 37 | + } |
| 38 | + |
| 39 | + logger.LogInformation("The .dacpac with checksum {DacpacChecksum} has not been deployed to database {TargetDatabaseName}.", dacpacChecksum, targetDatabaseName); |
| 40 | + |
| 41 | + return dacpacChecksum; |
| 42 | + } |
| 43 | + |
| 44 | + public async Task SetChecksumAsync(string dacpacPath, string targetConnectionString, string dacpacChecksum, ILogger logger, CancellationToken cancellationToken) |
| 45 | + { |
| 46 | + var targetDatabaseName = GetDatabaseName(targetConnectionString); |
| 47 | + |
| 48 | + var dacpacPathChecksum = GetStringChecksum(dacpacPath); |
| 49 | + |
| 50 | + using var connection = new SqlConnection(targetConnectionString); |
| 51 | + |
| 52 | + await connection.OpenAsync(SqlConnectionOverrides.OpenWithoutRetry, cancellationToken); |
| 53 | + |
| 54 | + await UpdateExtendedPropertyAsync(connection, dacpacPathChecksum, dacpacChecksum, cancellationToken); |
| 55 | + |
| 56 | + logger.LogInformation("The .dacpac with checksum {DacpacChecksum} has been registered in database {TargetDatabaseName}.", dacpacChecksum, targetDatabaseName); |
| 57 | + } |
| 58 | + |
| 59 | + private static string GetDatabaseName(string connectionString) |
| 60 | + { |
| 61 | + var builder = new SqlConnectionStringBuilder(connectionString); |
| 62 | + return builder.InitialCatalog; |
| 63 | + } |
| 64 | + |
| 65 | + private static async Task<string> GetChecksumAsync(string file) |
| 66 | + { |
| 67 | + var output = Path.Join(Path.GetTempPath(), Path.GetRandomFileName()); |
| 68 | + |
| 69 | + System.IO.Compression.ZipFile.ExtractToDirectory(file, output); |
| 70 | + |
| 71 | + var bytes = await File.ReadAllBytesAsync(Path.Join(output, "model.xml")); |
| 72 | + |
| 73 | + var predeployPath = Path.Join(output, "predeploy.sql"); |
| 74 | + |
| 75 | + if (File.Exists(predeployPath)) |
| 76 | + { |
| 77 | + var predeployBytes = await File.ReadAllBytesAsync(predeployPath); |
| 78 | + bytes = bytes.Concat(predeployBytes).ToArray(); |
| 79 | + } |
| 80 | + |
| 81 | + var postdeployPath = Path.Join(output, "postdeploy.sql"); |
| 82 | + |
| 83 | + if (File.Exists(postdeployPath)) |
| 84 | + { |
| 85 | + var postdeployBytes = await File.ReadAllBytesAsync(postdeployPath); |
| 86 | + bytes = bytes.Concat(postdeployBytes).ToArray(); |
| 87 | + } |
| 88 | + |
| 89 | + using var sha = SHA256.Create(); |
| 90 | + var checksum = sha.ComputeHash(bytes); |
| 91 | + |
| 92 | + // Clean up the extracted files |
| 93 | + try |
| 94 | + { |
| 95 | + Directory.Delete(output, true); |
| 96 | + } |
| 97 | + catch |
| 98 | + { |
| 99 | + // Ignore any errors during cleanup |
| 100 | + } |
| 101 | + |
| 102 | + return BitConverter.ToString(checksum).Replace("-", string.Empty); |
| 103 | + } |
| 104 | + |
| 105 | + private static string GetStringChecksum(string text) |
| 106 | + { |
| 107 | + var bytes = System.Text.Encoding.UTF8.GetBytes(text); |
| 108 | + using var sha = SHA256.Create(); |
| 109 | + var checksum = sha.ComputeHash(bytes); |
| 110 | + return BitConverter.ToString(checksum).Replace("-", string.Empty); |
| 111 | + } |
| 112 | + |
| 113 | + private static async Task<bool> CheckExtendedPropertyAsync(SqlConnection connection, string dacpacPathChecksum, string dacpacChecksum, CancellationToken cancellationToken) |
| 114 | + { |
| 115 | + var command = new SqlCommand( |
| 116 | + @$"SELECT CAST(1 AS BIT) FROM fn_listextendedproperty(NULL, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT) |
| 117 | + WHERE [value] = @Expected |
| 118 | + AND [name] = @dacpacId;", |
| 119 | + connection); |
| 120 | + |
| 121 | + command.Parameters.AddRange(GetParameters(dacpacChecksum, dacpacPathChecksum)); |
| 122 | + |
| 123 | + var result = await command.ExecuteScalarAsync(cancellationToken); |
| 124 | + |
| 125 | + return result == null ? false : (bool)result; |
| 126 | + } |
| 127 | + |
| 128 | + private static async Task UpdateExtendedPropertyAsync(SqlConnection connection, string dacpacPathChecksum, string dacpacChecksum, CancellationToken cancellationToken) |
| 129 | + { |
| 130 | + var command = new SqlCommand($@" |
| 131 | + IF EXISTS |
| 132 | + ( |
| 133 | + SELECT 1 FROM fn_listextendedproperty(null, default, default, default, default, default, default) |
| 134 | + WHERE [name] = @dacpacId |
| 135 | + ) |
| 136 | + BEGIN |
| 137 | + EXEC sp_updateextendedproperty @name = @dacpacId, @value = @Expected; |
| 138 | + END |
| 139 | + ELSE |
| 140 | + BEGIN |
| 141 | + EXEC sp_addextendedproperty @name = @dacpacId, @value = @Expected; |
| 142 | + END;", |
| 143 | + connection); |
| 144 | + |
| 145 | + command.Parameters.AddRange(GetParameters(dacpacChecksum, dacpacPathChecksum)); |
| 146 | + |
| 147 | + await command.ExecuteNonQueryAsync(cancellationToken); |
| 148 | + } |
| 149 | + |
| 150 | + private static SqlParameter[] GetParameters(string dacpacChecksum, string dacpacPathChecksum) |
| 151 | + { |
| 152 | + return |
| 153 | + [ |
| 154 | + new SqlParameter("@Expected", SqlDbType.VarChar) |
| 155 | + { |
| 156 | + Value = dacpacChecksum |
| 157 | + }, |
| 158 | + new SqlParameter("@dacpacId", SqlDbType.NVarChar, 128) |
| 159 | + { |
| 160 | + Value = dacpacPathChecksum |
| 161 | + }, |
| 162 | + ]; |
| 163 | + } |
| 164 | +} |
0 commit comments