Path: redb/redb.Export/Services/SchemaInitService.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.Export/Services/SchemaInitService.cs ---- using System.Text.RegularExpressions; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Extensions; using redb.Export.Providers; using redb.SQLite.Extensions; namespace redb.Export.Services; /// /// Creates the redb schema in a database, as redb init does: the schema an export can be imported into. /// public static class SchemaInitService { /// /// Creates the schema. PostgreSQL and SQL Server run the provider's initialization script, which deploys the module /// too, into a database without the redb schema only: one that holds it is refused before anything runs. SQLite goes through the SQLite service's : the schema script /// and then the file stamp (PRAGMA user_version and the _schema_compat row) that the service and the /// export schema check read. The script alone left the file unstamped, and an import into it was refused as into /// an older file. /// /// postgres, mssql or sqlite (the names redb init takes). /// The database. /// Progress lines, or null. /// Cancellation token. public static async Task InitializeAsync(string provider, string connectionString, Action? log = null, CancellationToken ct = default) { if (IsSqlite(provider)) { var services = new ServiceCollection(); services.AddRedb(options => options.UseSqlite(connectionString)); await using var serviceProvider = services.BuildServiceProvider(); log?.Invoke("Creating the schema through the SQLite service..."); await serviceProvider.GetRequiredService().EnsureDatabaseAsync(); return; } await using var dataProvider = ProviderFactory.Create(provider); await dataProvider.OpenAsync(connectionString, ct); // The scripts create a schema in an empty database. Over an existing one both stop at their guard on _types // before any statement changes it, with a message of their own; refused here first, with the same advice, // before anything is sent. // SQL Server runs its script batch by batch, each committed on its own, so a run that stopped half-way leaves // part of the schema behind; an upgrade cannot finish it. Told apart from a complete schema before the general // refusal, whose first advice is the upgrade. if (IsMssql(provider) && await ReadMssqlSchemaStateAsync(dataProvider, ct) == MssqlSchemaState.Incomplete) throw HalfCreatedMssql(changedNothing: true, cause: null); if (await RedbSchemaProbe.ExistsAsync(dataProvider, ct)) { throw new InvalidOperationException( "The database already holds the redb schema; `redb init` creates it in an empty database only and has " + $"changed nothing. Upgrade an existing schema with `redb schema --upgrade --provider {dataProvider.Name}` " + "or by starting the service; to start over, drop and create the database first."); } // PostgreSQL older than 15 fails in the middle of the script on NULLS NOT DISTINCT: refused first, by name. if (IsPostgres(provider)) { await using var versionCommand = dataProvider.Connection.CreateCommand(); versionCommand.CommandText = redb.Postgres.Data.PostgresServerVersion.Query; redb.Postgres.Data.PostgresServerVersion.EnsureSupported( Convert.ToString(await versionCommand.ExecuteScalarAsync(ct), System.Globalization.CultureInfo.InvariantCulture)); } var sql = GetSchemaScript(provider); log?.Invoke($"Schema script: {sql.Length:N0} characters."); if (IsMssql(provider)) { var executed = 0; try { foreach (var batch in Regex.Split(sql, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase)) { var trimmed = batch.Trim(); if (string.IsNullOrEmpty(trimmed)) continue; await using var command = dataProvider.Connection.CreateCommand(); command.CommandText = trimmed; command.CommandTimeout = 300; await command.ExecuteNonQueryAsync(ct); executed++; } } catch (Exception ex) { // The batches before the failure are committed. Whether they left any of the schema is read from the // catalog: a failure before the first table (the database option batch) leaves an empty database, and // its own error says more. MssqlSchemaState state; try { state = await ReadMssqlSchemaStateAsync(dataProvider, CancellationToken.None); } catch (Exception readError) { throw new InvalidOperationException( $"The creation script failed after {executed} batch(es) ({ex.Message}), and the database could " + "not be read afterwards: it may hold part of the redb schema. `redb init` cannot complete it and " + "an upgrade cannot either: drop and create the database, then run `redb init` again.", new AggregateException(ex, readError)); } if (state == MssqlSchemaState.Empty) throw; throw HalfCreatedMssql(changedNothing: false, cause: ex); } log?.Invoke($"Executed {executed} SQL batches."); } else { await using var command = dataProvider.Connection.CreateCommand(); command.CommandText = sql; command.CommandTimeout = 300; await command.ExecuteNonQueryAsync(ct); } } /// The full schema initialization script of a provider, embedded in its assembly. /// postgres, mssql or sqlite. public static string GetSchemaScript(string provider) { var (assembly, resourceName) = provider.ToLowerInvariant() switch { "postgres" or "postgresql" or "pgsql" => (typeof(redb.Postgres.RedbService).Assembly, "redb.Postgres.sql.redb_init.sql"), "mssql" or "sqlserver" => (typeof(redb.MSSql.RedbService).Assembly, "redb.MSSql.sql.redb_init.sql"), "sqlite" => (typeof(redb.SQLite.RedbService).Assembly, "redb.SQLite.sql.redbSqlite.sql"), _ => throw new ArgumentException($"Unknown provider: {provider}", nameof(provider)) }; using var stream = assembly.GetManifestResourceStream(resourceName) ?? throw new InvalidOperationException( $"Embedded resource '{resourceName}' not found in {assembly.GetName().Name}."); using var reader = new StreamReader(stream); return reader.ReadToEnd(); } private enum MssqlSchemaState { Empty, Incomplete, Complete } /// /// Whether a SQL Server database holds none of the redb schema, part of it, or all of it. The creation script /// creates _types first and deploys dbo.pvt_module_version last (99_module_version.sql; the module init /// drops it before it redeploys the module), so a redb table without that function is a schema the script did not /// finish. /// private static async Task ReadMssqlSchemaStateAsync(IDataProvider provider, CancellationToken ct) { await using var command = provider.Connection.CreateCommand(); command.CommandText = "SELECT CASE WHEN OBJECT_ID(N'dbo._types', N'U') IS NULL AND OBJECT_ID(N'dbo._schemes', N'U') IS NULL THEN 0 " + "WHEN OBJECT_ID(N'dbo.pvt_module_version', N'FN') IS NULL THEN 1 ELSE 2 END"; return (MssqlSchemaState)Convert.ToInt32(await command.ExecuteScalarAsync(ct), System.Globalization.CultureInfo.InvariantCulture); } private static InvalidOperationException HalfCreatedMssql(bool changedNothing, Exception? cause) => new( (cause is null ? "The database holds part of the redb schema: its tables are there, but not dbo.pvt_module_version, which " + "the creation script deploys last. An earlier `redb init` or run of the creation script stopped half-way; " + "an upgrade cannot complete it. " : $"The creation script failed in the middle ({cause.Message}). The database now holds part of the redb " + "schema: SQL Server commits the script batch by batch, and those before the failure stay. An upgrade " + "cannot complete it. ") + (changedNothing ? "`redb init` has changed nothing. " : "") + "To create the schema, drop and create the database first, then run `redb init` again. If it is a database of " + "an old redb version that holds data, start a redb application of this version on it instead.", cause); private static bool IsPostgres(string provider) => provider.ToLowerInvariant() is "postgres" or "postgresql" or "pgsql"; private static bool IsMssql(string provider) => provider.ToLowerInvariant() is "mssql" or "sqlserver"; private static bool IsSqlite(string provider) => provider.ToLowerInvariant() is "sqlite"; }