|
5 | 5 | using Aspire.Hosting.ApplicationModel; |
6 | 6 | using Aspire.Hosting.MySql; |
7 | 7 | using Microsoft.Extensions.DependencyInjection; |
| 8 | +using Microsoft.Extensions.Logging; |
| 9 | +using MySqlConnector; |
8 | 10 |
|
9 | 11 | namespace Aspire.Hosting; |
10 | 12 |
|
@@ -48,6 +50,27 @@ public static IResourceBuilder<MySqlServerResource> AddMySql(this IDistributedAp |
48 | 50 | } |
49 | 51 | }); |
50 | 52 |
|
| 53 | + builder.Eventing.Subscribe<ResourceReadyEvent>(resource, async (@event, ct) => |
| 54 | + { |
| 55 | + if (connectionString is null) |
| 56 | + { |
| 57 | + throw new DistributedApplicationException($"ResourceReadyEvent was published for the '{resource.Name}' resource but the connection string was null."); |
| 58 | + } |
| 59 | + |
| 60 | + using var sqlConnection = new MySqlConnection(connectionString); |
| 61 | + await sqlConnection.OpenAsync(ct).ConfigureAwait(false); |
| 62 | + |
| 63 | + if (sqlConnection.State != System.Data.ConnectionState.Open) |
| 64 | + { |
| 65 | + throw new InvalidOperationException($"Could not open connection to '{resource.Name}'"); |
| 66 | + } |
| 67 | + |
| 68 | + foreach (var sqlDatabase in resource.DatabaseResources) |
| 69 | + { |
| 70 | + await CreateDatabaseAsync(sqlConnection, sqlDatabase, @event.Services, ct).ConfigureAwait(false); |
| 71 | + } |
| 72 | + }); |
| 73 | + |
51 | 74 | var healthCheckKey = $"{name}_check"; |
52 | 75 | builder.Services.AddHealthChecks().AddMySql(sp => connectionString ?? throw new InvalidOperationException("Connection string is unavailable"), name: healthCheckKey); |
53 | 76 |
|
@@ -77,9 +100,79 @@ public static IResourceBuilder<MySqlDatabaseResource> AddDatabase(this IResource |
77 | 100 | // Use the resource name as the database name if it's not provided |
78 | 101 | databaseName ??= name; |
79 | 102 |
|
80 | | - builder.Resource.AddDatabase(name, databaseName); |
81 | 103 | var mySqlDatabase = new MySqlDatabaseResource(name, databaseName, builder.Resource); |
82 | | - return builder.ApplicationBuilder.AddResource(mySqlDatabase); |
| 104 | + |
| 105 | + builder.Resource.AddDatabase(mySqlDatabase); |
| 106 | + |
| 107 | + string? connectionString = null; |
| 108 | + |
| 109 | + builder.ApplicationBuilder.Eventing.Subscribe<ConnectionStringAvailableEvent>(mySqlDatabase, async (@event, ct) => |
| 110 | + { |
| 111 | + connectionString = await mySqlDatabase.ConnectionStringExpression.GetValueAsync(ct).ConfigureAwait(false); |
| 112 | + |
| 113 | + if (connectionString is null) |
| 114 | + { |
| 115 | + throw new DistributedApplicationException($"ConnectionStringAvailableEvent was published for the '{name}' resource but the connection string was null."); |
| 116 | + } |
| 117 | + }); |
| 118 | + |
| 119 | + var healthCheckKey = $"{name}_check"; |
| 120 | + builder.ApplicationBuilder.Services.AddHealthChecks().AddMySql(sp => connectionString ?? throw new InvalidOperationException("Connection string is unavailable"), name: healthCheckKey); |
| 121 | + |
| 122 | + return builder.ApplicationBuilder |
| 123 | + .AddResource(mySqlDatabase) |
| 124 | + .WithHealthCheck(healthCheckKey); |
| 125 | + } |
| 126 | + |
| 127 | + private static async Task CreateDatabaseAsync(MySqlConnection sqlConnection, MySqlDatabaseResource sqlDatabase, IServiceProvider serviceProvider, CancellationToken ct) |
| 128 | + { |
| 129 | + var logger = serviceProvider.GetRequiredService<ResourceLoggerService>().GetLogger(sqlDatabase.Parent); |
| 130 | + |
| 131 | + logger.LogDebug("Creating database '{DatabaseName}'", sqlDatabase.DatabaseName); |
| 132 | + |
| 133 | + try |
| 134 | + { |
| 135 | + var scriptAnnotation = sqlDatabase.Annotations.OfType<MySqlCreateDatabaseScriptAnnotation>().LastOrDefault(); |
| 136 | + |
| 137 | + if (scriptAnnotation?.Script is null) |
| 138 | + { |
| 139 | + var quotedDatabaseIdentifier = new MySqlCommandBuilder().QuoteIdentifier(sqlDatabase.DatabaseName); |
| 140 | + using var command = sqlConnection.CreateCommand(); |
| 141 | + command.CommandText = $"CREATE DATABASE IF NOT EXISTS {quotedDatabaseIdentifier};"; |
| 142 | + await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false); |
| 143 | + } |
| 144 | + else |
| 145 | + { |
| 146 | + using var command = sqlConnection.CreateCommand(); |
| 147 | + command.CommandText = scriptAnnotation.Script; |
| 148 | + await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false); |
| 149 | + } |
| 150 | + |
| 151 | + logger.LogDebug("Database '{DatabaseName}' created successfully", sqlDatabase.DatabaseName); |
| 152 | + } |
| 153 | + catch (Exception e) |
| 154 | + { |
| 155 | + logger.LogError(e, "Failed to create database '{DatabaseName}'", sqlDatabase.DatabaseName); |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + /// <summary> |
| 160 | + /// Defines the SQL script used to create the database. |
| 161 | + /// </summary> |
| 162 | + /// <param name="builder">The builder for the <see cref="MySqlDatabaseResource"/>.</param> |
| 163 | + /// <param name="script">The SQL script used to create the database.</param> |
| 164 | + /// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns> |
| 165 | + /// <remarks> |
| 166 | + /// <value>Default script is <code>CREATE DATABASE IF NOT EXISTS `QUOTED_DATABASE_NAME`;</code></value> |
| 167 | + /// </remarks> |
| 168 | + public static IResourceBuilder<MySqlDatabaseResource> WithCreationScript(this IResourceBuilder<MySqlDatabaseResource> builder, string script) |
| 169 | + { |
| 170 | + ArgumentNullException.ThrowIfNull(builder); |
| 171 | + ArgumentNullException.ThrowIfNull(script); |
| 172 | + |
| 173 | + builder.WithAnnotation(new MySqlCreateDatabaseScriptAnnotation(script)); |
| 174 | + |
| 175 | + return builder; |
83 | 176 | } |
84 | 177 |
|
85 | 178 | /// <summary> |
|
0 commit comments