Path: redb/redb.Tests.Integration/Tests/MsSql/MsSqlSchemaInitTests.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Tests.Integration/Tests/MsSql/MsSqlSchemaInitTests.cs ---- using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core.Extensions; using redb.MSSql.Extensions; using redb.Export.Services; using redb.MSSql.Sql; using redb.Tests.Integration.Tests.Base; namespace redb.Tests.Integration.Tests.MsSql; /// on SQL Server, scratch databases dropped afterwards. public class MsSqlSchemaInitTests : SchemaInitTestsBase, IAsyncLifetime { private string _server = null!; private readonly List _databases = []; protected override string ProviderName => "mssql"; protected override string RequiredVersion => new MsSqlDialect().Query_PvtRequiredVersion()!; private const string UserObjectsSql = "SELECT COUNT(*) FROM sys.objects WHERE is_ms_shipped = 0"; // The SQL Server script runs batch by batch, each committed on its own: a failure in the middle leaves the batches // before it. A table of the script's own name stops it after _types is created. [Fact] public async Task AnInit_ThatFailsHalfWay_NamesTheHalfCreatedDatabase_AndOnlyDropAndCreate() { var cs = await NewDatabaseAsync("half"); await ExecuteAsync(cs, "CREATE TABLE dbo._links (x int)"); var init = async () => await SchemaInitService.InitializeAsync(ProviderName, cs); (await init.Should().ThrowAsync()).Which.Message .Should().Contain("holds part of the redb schema").And.Contain("drop and create the database") .And.NotContain("schema --upgrade"); (await ScalarAsync(cs, "SELECT CASE WHEN OBJECT_ID(N'dbo._types', N'U') IS NULL THEN 0 ELSE 1 END")) .Should().Be("1", "precondition: the batches before the failure stayed"); } [Fact] public async Task AnInit_OverAHalfCreatedDatabase_LeadsWithDropAndCreate_AndTouchesNothing() { var cs = await NewDatabaseAsync("half-again"); await ExecuteAsync(cs, "CREATE TABLE dbo._links (x int)"); await FluentActions.Awaiting(() => SchemaInitService.InitializeAsync(ProviderName, cs)) .Should().ThrowAsync("precondition: the first init stopped half-way"); var before = await ScalarAsync(cs, UserObjectsSql); var again = async () => await SchemaInitService.InitializeAsync(ProviderName, cs); var message = (await again.Should().ThrowAsync()).Which.Message; message.Should().Contain("holds part of the redb schema").And.Contain("has changed nothing"); message.IndexOf("drop and create the database", StringComparison.Ordinal).Should().BeGreaterThan(-1) .And.BeLessThan(IndexOfOrEnd(message, "start a redb"), "drop and create comes first"); message.Should().NotContain("schema --upgrade"); (await ScalarAsync(cs, UserObjectsSql)).Should().Be(before); } [Fact] public async Task AnInit_OverASchemaWithoutItsModuleVersion_IsTakenForIncomplete() { // _schemes is there, the function the script deploys last is not: the probe used to answer "upgrade it". var cs = await NewDatabaseAsync("no-module"); await SchemaInitService.InitializeAsync(ProviderName, cs); await ExecuteAsync(cs, "DROP FUNCTION dbo.pvt_module_version"); var again = async () => await SchemaInitService.InitializeAsync(ProviderName, cs); (await again.Should().ThrowAsync()).Which.Message .Should().Contain("holds part of the redb schema").And.Contain("drop and create the database") .And.NotContain("schema --upgrade"); } private static int IndexOfOrEnd(string text, string value) { var index = text.IndexOf(value, StringComparison.Ordinal); return index < 0 ? text.Length : index; } public Task InitializeAsync() { _server = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetConnectionString("MSSql")!; return Task.CompletedTask; } public async Task DisposeAsync() { SqlConnection.ClearAllPools(); foreach (var database in _databases) await ExecuteAsync(Master(), $"IF DB_ID('{database}') IS NOT NULL BEGIN ALTER DATABASE [{database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [{database}] END"); } protected override async Task NewDatabaseAsync(string suffix) { var name = $"redb_init_{Guid.NewGuid().ToString("N")[..12]}_{suffix}"; _databases.Add(name); await ExecuteAsync(Master(), $"CREATE DATABASE [{name}]"); return new SqlConnectionStringBuilder(_server) { InitialCatalog = name }.ConnectionString; } protected override ServiceProvider Build(string cs) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedb(options => options.UseMsSql(cs).Configure(c => c.CacheDomain = $"init-{Guid.NewGuid():N}")); return services.BuildServiceProvider(); } protected override async Task ScalarAsync(string cs, string sql) { await using var connection = new SqlConnection(cs); await connection.OpenAsync(); await using var command = new SqlCommand(sql, connection); return Convert.ToString(await command.ExecuteScalarAsync()); } protected override async Task> CatalogAsync(string cs) { var lines = new List(); await using var connection = new SqlConnection(cs); await connection.OpenAsync(); foreach (var sql in new[] { "SELECT 'sequence ' + name FROM sys.sequences ORDER BY 1", "SELECT 'fk ' + name + ' disabled=' + CAST(is_disabled AS varchar(1)) FROM sys.foreign_keys ORDER BY 1", "SELECT 'trigger ' + name + ' disabled=' + CAST(is_disabled AS varchar(1)) FROM sys.triggers ORDER BY 1", "SELECT 'module ' + dbo.pvt_module_version()", }) { await using var command = new SqlCommand(sql, connection); await using var reader = await command.ExecuteReaderAsync(); while (await reader.ReadAsync()) lines.Add(reader.GetString(0)); } return lines; } private string Master() => new SqlConnectionStringBuilder(_server) { InitialCatalog = "master" }.ConnectionString; private static async Task ExecuteAsync(string cs, string sql) { await using var connection = new SqlConnection(cs); await connection.OpenAsync(); await using var command = new SqlCommand(sql, connection); await command.ExecuteNonQueryAsync(); } }