-
Notifications
You must be signed in to change notification settings - Fork 720
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
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
f50d0f6
Create SQL Server database automatically
sebastienros 93efeb2
Update tests to ensure new dbs are created
sebastienros 8b88f42
Create SQL Server container folders on Windows
sebastienros 4dda707
Test custom creation script annotations
sebastienros 37a9720
Revert playground changes
sebastienros ab9548d
Ensure special names are encoded in the creation script
sebastienros fa47903
PR feedback
sebastienros c3761c2
Formatting
sebastienros 1d8456c
Feedback
sebastienros 0a97670
Add support for multi-statements scripts
sebastienros 8ef42a6
Improve GO separator support
sebastienros b9d281c
Fix build
sebastienros 61875ef
Regex feedback and tests
sebastienros c5e6841
Update src/Aspire.Hosting.SqlServer/SqlServerBuilderExtensions.cs
sebastienros 98780b4
Fix test and remove private reflection
sebastienros File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,17 +1,27 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Globalization; | ||
| using System.Text.RegularExpressions; | ||
| using System.Text; | ||
| using Aspire.Hosting; | ||
| using Aspire.Hosting.ApplicationModel; | ||
| using Microsoft.Data.SqlClient; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace Aspire.Hosting; | ||
|
|
||
| /// <summary> | ||
| /// Provides extension methods for adding SQL Server resources to the application model. | ||
| /// </summary> | ||
| public static class SqlServerBuilderExtensions | ||
| public static partial class SqlServerBuilderExtensions | ||
| { | ||
| // GO delimiter format: {spaces?}GO{spaces?}{repeat?}{comment?} | ||
| // https://learn.microsoft.com/sql/t-sql/language-elements/sql-server-utilities-statements-go | ||
| [GeneratedRegex(@"^\s*GO(?<repeat>\s+\d{1,6})?(\s*\-{2,}.*)?\s*$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)] | ||
| internal static partial Regex GoStatements(); | ||
|
|
||
| /// <summary> | ||
| /// Adds a SQL Server resource to the application model. A container is used for local development. | ||
| /// </summary> | ||
|
|
@@ -45,6 +55,27 @@ 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); | ||
|
|
||
| if (sqlConnection.State != System.Data.ConnectionState.Open) | ||
| { | ||
| throw new InvalidOperationException($"Could not open connection to '{sqlServer.Name}'"); | ||
| } | ||
|
|
||
| foreach (var sqlDatabase in sqlServer.DatabaseResources) | ||
| { | ||
| await CreateDatabaseAsync(sqlConnection, sqlDatabase, @event.Services, ct).ConfigureAwait(false); | ||
| } | ||
| }); | ||
|
|
||
| var healthCheckKey = $"{name}_check"; | ||
| builder.Services.AddHealthChecks().AddSqlServer(sp => connectionString ?? throw new InvalidOperationException("Connection string is unavailable"), name: healthCheckKey); | ||
|
|
||
|
|
@@ -75,9 +106,28 @@ public static IResourceBuilder<SqlServerDatabaseResource> AddDatabase(this IReso | |
| // 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); | ||
|
|
||
| string? connectionString = null; | ||
|
|
||
| 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 +162,87 @@ public static IResourceBuilder<SqlServerServerResource> WithDataBindMount(this I | |
|
|
||
| return builder.WithBindMount(source, "/var/opt/mssql", isReadOnly); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Defines the SQL script used to create the database. | ||
| /// </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 CreationScriptAnnotation(script)); | ||
|
|
||
| return builder; | ||
| } | ||
|
|
||
| private static async Task CreateDatabaseAsync(SqlConnection sqlConnection, SqlServerDatabaseResource sqlDatabase, IServiceProvider serviceProvider, CancellationToken ct) | ||
| { | ||
| try | ||
| { | ||
| var scriptAnnotation = sqlDatabase.Annotations.OfType<CreationScriptAnnotation>().LastOrDefault(); | ||
|
|
||
| if (scriptAnnotation?.Script == null) | ||
| { | ||
| var quotedDatabaseIdentifier = new SqlCommandBuilder().QuoteIdentifier(sqlDatabase.DatabaseName); | ||
| using var command = sqlConnection.CreateCommand(); | ||
| command.CommandText = $"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); | ||
| } | ||
| else | ||
| { | ||
| using var reader = new StringReader(scriptAnnotation.Script); | ||
| var batchBuilder = new StringBuilder(); | ||
|
|
||
| while (reader.ReadLine() is { } line) | ||
| { | ||
| var matchGo = GoStatements().Match(line); | ||
|
|
||
| if (matchGo.Success) | ||
| { | ||
| // Execute the current batch | ||
| var count = matchGo.Groups["repeat"].Success ? int.Parse(matchGo.Groups["repeat"].Value, CultureInfo.InvariantCulture) : 1; | ||
| var batch = batchBuilder.ToString(); | ||
|
|
||
| for (var i = 0; i < count; i++) | ||
| { | ||
| using var command = sqlConnection.CreateCommand(); | ||
| command.CommandText = batch; | ||
| await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false); | ||
| } | ||
|
|
||
| batchBuilder.Clear(); | ||
| } | ||
| else | ||
| { | ||
| // Prevent batches with only whitespace | ||
| if (!string.IsNullOrWhiteSpace(line)) | ||
| { | ||
| batchBuilder.AppendLine(line); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Process the remaining batch lines | ||
| if (batchBuilder.Length > 0) | ||
| { | ||
| using var command = sqlConnection.CreateCommand(); | ||
| command.CommandText = batchBuilder.ToString(); | ||
| await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false); | ||
| } | ||
| } | ||
| } | ||
| catch (Exception e) | ||
| { | ||
| var logger = serviceProvider.GetRequiredService<ILogger<DistributedApplicationBuilder>>(); | ||
|
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. Are we going to update this to write the log to the resource instead? 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 just got taught how to, yes I will change that right away. |
||
| logger.LogError(e, "Failed to create database '{DatabaseName}'", sqlDatabase.DatabaseName); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
25 changes: 25 additions & 0 deletions
25
src/Aspire.Hosting/ApplicationModel/CreationScriptAnnotation.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 CreationScriptAnnotation : IResourceAnnotation | ||
| { | ||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="CreationScriptAnnotation"/> class. | ||
| /// </summary> | ||
| /// <param name="script">The script used to create the resource.</param> | ||
| public CreationScriptAnnotation(string script) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(script); | ||
| Script = script; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Gets the script used to create the resource. | ||
| /// </summary> | ||
| public string Script { get; } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.