-
Notifications
You must be signed in to change notification settings - Fork 940
Create database for Sql Server resource #8022
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 8 commits
f50d0f6
93efeb2
8b88f42
4dda707
37a9720
ab9548d
fa47903
c3761c2
1d8456c
0a97670
8ef42a6
b9d281c
61875ef
c5e6841
98780b4
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,7 +3,9 @@ | |
|
|
||
| using Aspire.Hosting; | ||
| using Aspire.Hosting.ApplicationModel; | ||
| using Microsoft.Data.SqlClient; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace Aspire.Hosting; | ||
|
|
||
|
|
@@ -45,6 +47,42 @@ public static IResourceBuilder<SqlServerServerResource> AddSqlServer(this IDistr | |
| } | ||
| }); | ||
|
|
||
| builder.Eventing.Subscribe<ResourceReadyEvent>(sqlServer, async (@event, ct) => | ||
| { | ||
| if (connectionString is null) | ||
| { | ||
| throw new DistributedApplicationException($"ResourceReadyEvent was published for the '{sqlServer.Name}' resource but the connection string was null."); | ||
| } | ||
|
|
||
| using var sqlConnection = new SqlConnection(connectionString); | ||
| await sqlConnection.OpenAsync(ct).ConfigureAwait(false); | ||
|
|
||
| foreach (var sqlDatabase in sqlServer.DatabaseResources) | ||
| { | ||
| var quotedDatabaseIdentifier = new SqlCommandBuilder().QuoteIdentifier(sqlDatabase.DatabaseName); | ||
|
|
||
| try | ||
| { | ||
| if (sqlConnection.State != System.Data.ConnectionState.Open) | ||
| { | ||
| throw new InvalidOperationException($"Could not open connection to '{sqlServer.Name}'"); | ||
| } | ||
|
|
||
| var scriptAnnotation = sqlDatabase.Annotations.OfType<ScriptAnnotation>().LastOrDefault(); | ||
|
|
||
| using var command = sqlConnection.CreateCommand(); | ||
| command.CommandText = scriptAnnotation?.Script ?? | ||
| $"IF ( NOT EXISTS ( SELECT 1 FROM sys.databases WHERE name = @DatabaseName ) ) CREATE DATABASE {quotedDatabaseIdentifier};"; | ||
| command.Parameters.Add(new SqlParameter("@DatabaseName", sqlDatabase.DatabaseName)); | ||
| await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false); | ||
| } | ||
| catch (Exception e) | ||
| { | ||
| @event.Services.GetRequiredService<ILogger<SqlServerServerResource>>().LogError(e, "Failed to create database '{DatabaseName}'", sqlDatabase.DatabaseName); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we log this to resource's logger? Where does this currently log? To the console of the AppHost?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It currently shows up in the console. Would it be nice if it were in the database resource log in the dashboard? If so what is the way to do it? |
||
| } | ||
| } | ||
| }); | ||
|
|
||
| var healthCheckKey = $"{name}_check"; | ||
| builder.Services.AddHealthChecks().AddSqlServer(sp => connectionString ?? throw new InvalidOperationException("Connection string is unavailable"), name: healthCheckKey); | ||
|
|
||
|
|
@@ -72,12 +110,31 @@ public static IResourceBuilder<SqlServerDatabaseResource> AddDatabase(this IReso | |
| ArgumentNullException.ThrowIfNull(builder); | ||
| ArgumentException.ThrowIfNullOrEmpty(name); | ||
|
|
||
| string? connectionString = null; | ||
|
sebastienros marked this conversation as resolved.
Outdated
|
||
|
|
||
| // Use the resource name as the database name if it's not provided | ||
| databaseName ??= name; | ||
|
|
||
| builder.Resource.AddDatabase(name, databaseName); | ||
| var sqlServerDatabase = new SqlServerDatabaseResource(name, databaseName, builder.Resource); | ||
| return builder.ApplicationBuilder.AddResource(sqlServerDatabase); | ||
|
|
||
| builder.Resource.AddDatabase(sqlServerDatabase); | ||
|
|
||
| builder.ApplicationBuilder.Eventing.Subscribe<ConnectionStringAvailableEvent>(sqlServerDatabase, async (@event, ct) => | ||
| { | ||
| connectionString = await sqlServerDatabase.ConnectionStringExpression.GetValueAsync(ct).ConfigureAwait(false); | ||
|
|
||
| if (connectionString == null) | ||
| { | ||
| throw new DistributedApplicationException($"ConnectionStringAvailableEvent was published for the '{name}' resource but the connection string was null."); | ||
| } | ||
| }); | ||
|
|
||
| var healthCheckKey = $"{name}_check"; | ||
| builder.ApplicationBuilder.Services.AddHealthChecks().AddSqlServer(sp => connectionString ?? throw new InvalidOperationException("Connection string is unavailable"), name: healthCheckKey); | ||
|
|
||
| return builder.ApplicationBuilder | ||
| .AddResource(sqlServerDatabase) | ||
| .WithHealthCheck(healthCheckKey); | ||
| } | ||
|
|
||
| /// <summary> | ||
|
|
@@ -112,4 +169,23 @@ public static IResourceBuilder<SqlServerServerResource> WithDataBindMount(this I | |
|
|
||
| return builder.WithBindMount(source, "/var/opt/mssql", isReadOnly); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Alters the JSON configuration document used by the emulator. | ||
|
sebastienros marked this conversation as resolved.
Outdated
|
||
| /// </summary> | ||
| /// <param name="builder">The builder for the <see cref="SqlServerDatabaseResource"/>.</param> | ||
| /// <param name="script">The SQL script used to create the database.</param> | ||
| /// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns> | ||
| /// <remarks> | ||
| /// <value>Default script is <code>IF ( NOT EXISTS ( SELECT 1 FROM sys.databases WHERE name = @DatabaseName ) ) CREATE DATABASE [<QUOTED_DATABASE_NAME%gt;];</code></value> | ||
| /// </remarks> | ||
| public static IResourceBuilder<SqlServerDatabaseResource> WithCreationScript(this IResourceBuilder<SqlServerDatabaseResource> builder, string script) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(builder); | ||
| ArgumentNullException.ThrowIfNull(script); | ||
|
|
||
| builder.WithAnnotation(new ScriptAnnotation(script)); | ||
|
|
||
| return builder; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| namespace Aspire.Hosting.ApplicationModel; | ||
|
|
||
| /// <summary> | ||
| /// Represents an annotation for defining a script to create a resource. | ||
| /// </summary> | ||
| public sealed class ScriptAnnotation : IResourceAnnotation | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I wonder if we should give this a more specific name.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I was torn between a database specific name or not. But in the end it's only a string. Could have been all the way to NB: To go all the way meta we could have general annotation like
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Given the summary of the class "for defining a script to create a resource." I thought the class would be named more specific.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Changed to
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thinking more about this, we also have a sample for how to customize the initial database:
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As a user I would definitely prefer this extension method (and annotation) to customize the create database script than having to deal with bind mounts and understand how the container is configured. The same way we have Though I would understand if we say we skip this feature (customizing CREATE DATABASE) since there is already a way to do it in the container itself. |
||
| { | ||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="ScriptAnnotation"/> class. | ||
| /// </summary> | ||
| /// <param name="script">The script used to create the resource.</param> | ||
| public ScriptAnnotation(string script) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(script); | ||
| Script = script; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Gets the script used to create the resource. | ||
| /// </summary> | ||
| public string Script { get; } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why the difference between the name in the WHERE and the name used on the Create Database? Shouldn't they both use the same SqlParameter?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Parameters can't be used for object names (such as database names, table names, or column names).
It's used in the query part because in that case it's a string value.