From f888c4cb8b04dedc95d26397af5e7550498606cf Mon Sep 17 00:00:00 2001 From: Sebastian Stehle Date: Thu, 5 Nov 2026 13:44:05 +0100 Subject: [PATCH] Improve logging. (#1366) * Improve logging. * Add missing files --- .../Entities/Contents/Text/EFTextIndex.cs | 7 +- .../Infrastructure/LogMessages.cs | 22 +++++ .../Migrations/DatabaseMigrator.cs | 65 ++++++++++++- .../Infrastructure/Queries/QueryExtensions.cs | 52 +++++----- .../Infrastructure/Queries/SqlDialect.cs | 5 + .../20260512000000_AddJsonFunctions.cs | 2 +- .../App/MySqlAppDbContextDesignTimeFactory.cs | 4 +- .../Providers/MySql/MySqlDialect.cs | 16 ++++ .../MySqlScriptMigrationsSqlGenerator.cs | 42 ++++++++ .../20260512000002_AddJsonFunctions.cs | 2 +- .../Providers/Postgres/PostgresDialect.cs | 6 ++ .../20260512000001_AddJsonFunctions.cs | 2 +- .../SqlServerAppDbContextDesignTimeFactory.cs | 4 +- .../Providers/SqlServer/SqlServerDialect.cs | 7 ++ .../SqlServerScriptMigrationsSqlGenerator.cs | 36 +++++++ .../ServiceExtensions.cs | 3 + .../Squidex.Data.EntityFramework.csproj | 14 +-- .../Squidex.Data.MongoDb.csproj | 12 +-- .../Squidex.Domain.Apps.Core.Model.csproj | 2 +- ...Squidex.Domain.Apps.Core.Operations.csproj | 4 +- .../Squidex.Infrastructure.csproj | 14 +-- backend/src/Squidex/Squidex.csproj | 22 ++--- .../Domain/Contents/Text/EFTextIndexTests.cs | 3 +- .../Infrastructure/Queries/EFQueryTests.cs | 5 +- .../Migrations/MySqlMigrationTests.cs | 70 ++++++++++++++ .../Migrations/PostgresMigrationTests.cs | 87 +++++++++++++++++ .../Migrations/SqlServerMigrationTests.cs | 95 +++++++++++++++++++ .../EntityFramework/TestHelpers/TestLogger.cs | 31 ++++++ 28 files changed, 563 insertions(+), 71 deletions(-) create mode 100644 backend/src/Squidex.Data.EntityFramework/Infrastructure/LogMessages.cs create mode 100644 backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlScriptMigrationsSqlGenerator.cs create mode 100644 backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerScriptMigrationsSqlGenerator.cs create mode 100644 backend/tests/Squidex.Data.Tests/EntityFramework/TestHelpers/TestLogger.cs diff --git a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/Text/EFTextIndex.cs b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/Text/EFTextIndex.cs index 13ca6d5df..46134ee3a 100644 --- a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/Text/EFTextIndex.cs +++ b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/Text/EFTextIndex.cs @@ -7,6 +7,7 @@ using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; using NetTopologySuite.Geometries; using Squidex.Domain.Apps.Core.Apps; using Squidex.Domain.Apps.Core.Schemas; @@ -17,7 +18,7 @@ using Squidex.Providers.SqlServer; namespace Squidex.Domain.Apps.Entities.Contents.Text; -public sealed class EFTextIndex(IDbContextFactory dbContextFactory) +public sealed class EFTextIndex(IDbContextFactory dbContextFactory, ILogger> log) : ITextIndex, IInitializable, IDeleter where TContext : DbContext, IDbContextWithDialect { @@ -39,8 +40,8 @@ public sealed class EFTextIndex(IDbContextFactory dbContextF { await using var dbContext = await CreateDbContextAsync(ct); - await dbContext.CreateTextIndexAsync("IDX_Text", "Texts", "Texts", ct); - await dbContext.CreateGeoIndexAsync("IDX_Geo", "Geos", "GeoObject", ct); + await dbContext.CreateTextIndexAsync("IDX_Text", "Texts", "Texts", log, ct); + await dbContext.CreateGeoIndexAsync("IDX_Geo", "Geos", "GeoObject", log, ct); } async Task IDeleter.DeleteAppAsync(App app, diff --git a/backend/src/Squidex.Data.EntityFramework/Infrastructure/LogMessages.cs b/backend/src/Squidex.Data.EntityFramework/Infrastructure/LogMessages.cs new file mode 100644 index 000000000..63d16f6c1 --- /dev/null +++ b/backend/src/Squidex.Data.EntityFramework/Infrastructure/LogMessages.cs @@ -0,0 +1,22 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Microsoft.Extensions.Logging; + +namespace Squidex.Infrastructure; + +internal static partial class LogMessages +{ + [LoggerMessage(Level = LogLevel.Error, Message = "Insufficient privileges to apply the migrations of {context}. Ask an administrator to execute the following script manually and restart the application. Execute it as the application user with temporarily elevated privileges, so that the application remains the owner of the created objects:\n{sql}")] + public static partial void LogMigrationPrivilegesMissing(ILogger logger, Exception exception, string context, string sql); + + [LoggerMessage(Level = LogLevel.Error, Message = "Failed to apply the migrations of {context}. If the problem cannot be solved, ask an administrator to execute the following script manually and restart the application:\n{sql}")] + public static partial void LogMigrationFailed(ILogger logger, Exception exception, string context, string sql); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Insufficient privileges to create index {name}. Ask an administrator to execute the following statements manually:\n{sql}")] + public static partial void LogIndexPrivilegesMissing(ILogger logger, Exception exception, string name, string sql); +} diff --git a/backend/src/Squidex.Data.EntityFramework/Infrastructure/Migrations/DatabaseMigrator.cs b/backend/src/Squidex.Data.EntityFramework/Infrastructure/Migrations/DatabaseMigrator.cs index 003dbf98d..4d8066a98 100644 --- a/backend/src/Squidex.Data.EntityFramework/Infrastructure/Migrations/DatabaseMigrator.cs +++ b/backend/src/Squidex.Data.EntityFramework/Infrastructure/Migrations/DatabaseMigrator.cs @@ -6,13 +6,20 @@ // ========================================================================== using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.Extensions.Logging; using Squidex.Hosting; #pragma warning disable RECS0108 // Warns about static fields in generic types namespace Squidex.Infrastructure.Migrations; -public sealed class DatabaseMigrator(IDbContextFactory dbContextFactory, ConnectionStringParser parser) : IInitializable +public sealed class DatabaseMigrator( + IDbContextFactory dbContextFactory, + ConnectionStringParser parser, + ILogger> log) + : IInitializable where TContext : DbContext { private static readonly TimeSpan WaitTime = TimeSpan.FromSeconds(30); @@ -48,6 +55,60 @@ public sealed class DatabaseMigrator(IDbContextFactory dbCon throw new InvalidOperationException($"Failed to connect to database <{hostName}>"); } - await dbContext.Database.MigrateAsync(ct); + await MigrateAsync(dbContext, ct); + } + + private async Task MigrateAsync(TContext dbContext, + CancellationToken ct) + { + try + { + await dbContext.Database.MigrateAsync(ct); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + // Some migrations need more privileges than the application, e.g. to create functions or extensions. + // The pending migrations are written to the log, so that an administrator can apply them manually. + var sql = await GetPendingScriptAsync(dbContext, ct); + if (string.IsNullOrWhiteSpace(sql)) + { + throw; + } + + var context = typeof(TContext).Name; + + if (dbContext is IDbContextWithDialect withDialect && withDialect.Dialect.IsPrivilegeMissingException(ex)) + { + LogMessages.LogMigrationPrivilegesMissing(log, ex, context, sql); + } + else + { + LogMessages.LogMigrationFailed(log, ex, context, sql); + } + + throw; + } + } + + private static async Task GetPendingScriptAsync(TContext dbContext, + CancellationToken ct) + { + try + { + var migrationsApplied = await dbContext.Database.GetAppliedMigrationsAsync(ct); + var migrationsLast = migrationsApplied.Order(StringComparer.Ordinal).LastOrDefault(); + + // Failed migrations are not recorded, therefore the script starts after the last applied migration. + return dbContext.GetService().GenerateScript(migrationsLast ?? Migration.InitialDatabase); + } + catch + { + // The script is only an additional hint and must not hide the original exception. + return null; + } } } diff --git a/backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/QueryExtensions.cs b/backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/QueryExtensions.cs index 99b57d825..9ce961b90 100644 --- a/backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/QueryExtensions.cs +++ b/backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/QueryExtensions.cs @@ -6,6 +6,7 @@ // ========================================================================== using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; namespace Squidex.Infrastructure.Queries; @@ -24,47 +25,50 @@ public static class QueryExtensions return new SqlQueryBuilder(withDialect.Dialect, tableName, parameters); } - public static async Task CreateGeoIndexAsync(this TContext dbContext, string name, string table, string column, + public static Task CreateGeoIndexAsync(this TContext dbContext, string name, string table, string column, ILogger log, CancellationToken ct = default) where TContext : DbContext, IDbContextWithDialect { - var sql = dbContext.Dialect.GeoIndex(name, table, column); - try - { - await dbContext.Database.ExecuteSqlRawAsync(sql, ct); - } - catch (Exception ex) when (dbContext.Dialect.IsDuplicateIndexException(ex, name)) - { - // NOOP - } + var sqlCreate = dbContext.Dialect.GeoIndex(name, table, column); + + return dbContext.CreateIndexAsync(name, [sqlCreate], log, ct); } - public static async Task CreateTextIndexAsync(this TContext dbContext, string name, string table, string column, + public static Task CreateTextIndexAsync(this TContext dbContext, string name, string table, string column, ILogger log, CancellationToken ct = default) where TContext : DbContext, IDbContextWithDialect { - var prepareSql = dbContext.Dialect.TextIndexPrepare(name); + var sqlPrepare = dbContext.Dialect.TextIndexPrepare(name); + var sqlCreate = dbContext.Dialect.TextIndex(name, table, column); - if (!string.IsNullOrWhiteSpace(prepareSql)) + if (string.IsNullOrWhiteSpace(sqlPrepare)) + { + return dbContext.CreateIndexAsync(name, [sqlCreate], log, ct); + } + + return dbContext.CreateIndexAsync(name, [sqlPrepare, sqlCreate], log, ct); + } + + private static async Task CreateIndexAsync(this TContext dbContext, string name, string[] statements, ILogger log, + CancellationToken ct) + where TContext : DbContext, IDbContextWithDialect + { + for (var i = 0; i < statements.Length; i++) { try { - await dbContext.Database.ExecuteSqlRawAsync(prepareSql, ct); + await dbContext.Database.ExecuteSqlRawAsync(statements[i], ct); } catch (Exception ex) when (dbContext.Dialect.IsDuplicateIndexException(ex, name)) { // NOOP } - } - - var sql = dbContext.Dialect.TextIndex(name, table, column); - try - { - await dbContext.Database.ExecuteSqlRawAsync(sql, ct); - } - catch (Exception ex) when (dbContext.Dialect.IsDuplicateIndexException(ex, name)) - { - // NOOP + catch (Exception ex) when (dbContext.Dialect.IsPrivilegeMissingException(ex)) + { + // Only the queries that use the index fail without it, therefore the application can still start. + LogMessages.LogIndexPrivilegesMissing(log, ex, name, string.Join('\n', statements[i..])); + return; + } } } } diff --git a/backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlDialect.cs b/backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlDialect.cs index 5a3deb718..edcf9f6a3 100644 --- a/backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlDialect.cs +++ b/backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlDialect.cs @@ -20,6 +20,11 @@ public class SqlDialect return false; } + public virtual bool IsPrivilegeMissingException(Exception exception) + { + return false; + } + public virtual Task InitializeAsync(DbContext dbContext, CancellationToken ct) { diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/20260512000000_AddJsonFunctions.cs b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/20260512000000_AddJsonFunctions.cs index e914eeb7c..c8d801e76 100644 --- a/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/20260512000000_AddJsonFunctions.cs +++ b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/20260512000000_AddJsonFunctions.cs @@ -16,7 +16,7 @@ namespace Squidex.Providers.MySql.App.Migrations using var reader = new StreamReader(sqlStream); var sqlText = reader.ReadToEnd(); - var statements = sqlText.Split(";;", System.StringSplitOptions.RemoveEmptyEntries | System.StringSplitOptions.TrimEntries); + var statements = sqlText.Split(";;", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); foreach (var statement in statements) { diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/MySqlAppDbContextDesignTimeFactory.cs b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/MySqlAppDbContextDesignTimeFactory.cs index 1ef286f44..c6a40e47d 100644 --- a/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/MySqlAppDbContextDesignTimeFactory.cs +++ b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/MySqlAppDbContextDesignTimeFactory.cs @@ -8,6 +8,7 @@ using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; +using Microsoft.EntityFrameworkCore.Migrations; using Squidex.Infrastructure.Json.System; namespace Squidex.Providers.MySql.App; @@ -22,7 +23,8 @@ public sealed class MySqlAppDbContextDesignTimeFactory : IDesignTimeDbContextFac .UseMySql(ConnectionString, ServerVersion.AutoDetect(ConnectionString), options => { options.UseNetTopologySuite(); - }); + }) + .ReplaceService(); return new MySqlAppDbContext(builder.Options, new SystemJsonSerializer(JsonSerializerOptions.Default)); } diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlDialect.cs b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlDialect.cs index 1f1b825dd..6c79dd2df 100644 --- a/backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlDialect.cs +++ b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlDialect.cs @@ -30,6 +30,22 @@ public sealed class MySqlDialect : SqlDialect return exception is MySqlException ex && ex.Number == 1061; } + public override bool IsPrivilegeMissingException(Exception exception) + { + if (exception is not MySqlException ex) + { + return false; + } + + // Creating functions with binary logging enabled also needs SUPER, unless log_bin_trust_function_creators is set. + return ex.ErrorCode is + MySqlErrorCode.BinLogCreateRoutineNeedSuper or + MySqlErrorCode.DatabaseAccessDenied or + MySqlErrorCode.PrecedureAccessDenied or + MySqlErrorCode.SpecifiedAccessDeniedError or + MySqlErrorCode.TableAccessDenied; + } + public override string? JsonColumnType() { return "json"; diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlScriptMigrationsSqlGenerator.cs b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlScriptMigrationsSqlGenerator.cs new file mode 100644 index 000000000..df63092e9 --- /dev/null +++ b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlScriptMigrationsSqlGenerator.cs @@ -0,0 +1,42 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations.Operations; +using Microsoft.EntityFrameworkCore.Update; +using Microting.EntityFrameworkCore.MySql.Infrastructure.Internal; +using Microting.EntityFrameworkCore.MySql.Migrations; + +#pragma warning disable EF1001 // Internal EF Core API usage. + +namespace Squidex.Providers.MySql; + +public sealed class MySqlScriptMigrationsSqlGenerator( + MigrationsSqlGeneratorDependencies dependencies, + ICommandBatchPreparer commandBatchPreparer, + IMySqlOptions options) + : MySqlMigrationsSqlGenerator(dependencies, commandBatchPreparer, options) +{ + protected override void Generate(SqlOperation operation, IModel? model, MigrationCommandListBuilder builder) + { + if (!Options.HasFlag(MigrationsSqlGenerationOptions.Script)) + { + base.Generate(operation, model, builder); + return; + } + + // Raw statements like functions contain semicolons and are not terminated, therefore the script would not run in MySQL clients. + builder + .AppendLine("DELIMITER //") + .Append(operation.Sql) + .AppendLine(" //") + .AppendLine("DELIMITER ;"); + + EndStatement(builder, operation.SuppressTransaction); + } +} diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/20260512000002_AddJsonFunctions.cs b/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/20260512000002_AddJsonFunctions.cs index b29198f81..68f849f03 100644 --- a/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/20260512000002_AddJsonFunctions.cs +++ b/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/20260512000002_AddJsonFunctions.cs @@ -16,7 +16,7 @@ namespace Squidex.Providers.Postgres.App.Migrations using var reader = new StreamReader(sqlStream); var sqlText = reader.ReadToEnd(); - var statements = sqlText.Split(";;", System.StringSplitOptions.RemoveEmptyEntries | System.StringSplitOptions.TrimEntries); + var statements = sqlText.Split(";;", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); foreach (var statement in statements) { diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/PostgresDialect.cs b/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/PostgresDialect.cs index 24b72a9fb..c966c1e24 100644 --- a/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/PostgresDialect.cs +++ b/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/PostgresDialect.cs @@ -31,6 +31,12 @@ public class PostgresDialect : SqlDialect return exception is PostgresException ex && ex.SqlState == "42P07"; } + public override bool IsPrivilegeMissingException(Exception exception) + { + // Covers missing CREATE privileges, extensions that need a superuser and functions owned by other users. + return exception is PostgresException { SqlState: PostgresErrorCodes.InsufficientPrivilege }; + } + public override string? JsonColumnType() { return "jsonb"; diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/20260512000001_AddJsonFunctions.cs b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/20260512000001_AddJsonFunctions.cs index ce17a0ce3..fe479d4f9 100644 --- a/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/20260512000001_AddJsonFunctions.cs +++ b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/20260512000001_AddJsonFunctions.cs @@ -16,7 +16,7 @@ namespace Squidex.Providers.SqlServer.App.Migrations using var reader = new StreamReader(sqlStream); var sqlText = reader.ReadToEnd(); - var statements = sqlText.Split(";;", System.StringSplitOptions.RemoveEmptyEntries | System.StringSplitOptions.TrimEntries); + var statements = sqlText.Split(";;", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); foreach (var statement in statements) { diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/SqlServerAppDbContextDesignTimeFactory.cs b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/SqlServerAppDbContextDesignTimeFactory.cs index a19d54b13..2370bb45e 100644 --- a/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/SqlServerAppDbContextDesignTimeFactory.cs +++ b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/SqlServerAppDbContextDesignTimeFactory.cs @@ -8,6 +8,7 @@ using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; +using Microsoft.EntityFrameworkCore.Migrations; using Squidex.Infrastructure.Json.System; namespace Squidex.Providers.SqlServer.App; @@ -22,7 +23,8 @@ public sealed class SqlServerAppDbContextDesignTimeFactory : IDesignTimeDbContex .UseSqlServer(ConnectionString, options => { options.UseNetTopologySuite(); - }); + }) + .ReplaceService(); return new SqlServerAppDbContext(builder.Options, new SystemJsonSerializer(JsonSerializerOptions.Default)); } diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerDialect.cs b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerDialect.cs index bd822d6b5..7adb3e338 100644 --- a/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerDialect.cs +++ b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerDialect.cs @@ -30,6 +30,13 @@ public sealed class SqlServerDialect : SqlDialect return exception is SqlException ex && ex.Number is 1913 or 7642 or 7652; } + public override bool IsPrivilegeMissingException(Exception exception) + { + // 229: Object permission denied, 262: Database permission denied (e.g. CREATE FUNCTION or CREATE FULLTEXT CATALOG), + // 297 and 15247: Action not permitted, 2760: Schema does not exist or permission denied. + return exception is SqlException ex && ex.Number is 229 or 262 or 297 or 2760 or 15247; + } + public override string GeoIndex(string name, string table, string field) { return $"CREATE SPATIAL INDEX {name} ON {FormatTable(table)} ({FormatField(field, false)}) USING GEOGRAPHY_GRID;"; diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerScriptMigrationsSqlGenerator.cs b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerScriptMigrationsSqlGenerator.cs new file mode 100644 index 000000000..e753b143f --- /dev/null +++ b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerScriptMigrationsSqlGenerator.cs @@ -0,0 +1,36 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations.Operations; +using Microsoft.EntityFrameworkCore.Update; + +namespace Squidex.Providers.SqlServer; + +public sealed class SqlServerScriptMigrationsSqlGenerator( + MigrationsSqlGeneratorDependencies dependencies, + ICommandBatchPreparer commandBatchPreparer) + : SqlServerMigrationsSqlGenerator(dependencies, commandBatchPreparer) +{ + protected override void Generate(SqlOperation operation, IModel? model, MigrationCommandListBuilder builder) + { + if (!Options.HasFlag(MigrationsSqlGenerationOptions.Script)) + { + base.Generate(operation, model, builder); + return; + } + + // Raw statements like functions must be the first statement in a batch, therefore the script would not run in SQL Server clients. + builder + .AppendLine("GO") + .AppendLine(operation.Sql) + .AppendLine("GO"); + + EndStatement(builder, operation.SuppressTransaction); + } +} diff --git a/backend/src/Squidex.Data.EntityFramework/ServiceExtensions.cs b/backend/src/Squidex.Data.EntityFramework/ServiceExtensions.cs index 1002681b0..04ceb90fd 100644 --- a/backend/src/Squidex.Data.EntityFramework/ServiceExtensions.cs +++ b/backend/src/Squidex.Data.EntityFramework/ServiceExtensions.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -91,6 +92,7 @@ public static class ServiceExtensions options.UseMicrosoftJson(MySqlCommonJsonChangeTrackingOptions.FullHierarchyOptimizedSemantically); }); builder.UseBulkInsertMySql(); + builder.ReplaceService(); }); services.AddNamedDbContext((builder, name) => @@ -160,6 +162,7 @@ public static class ServiceExtensions options.UseNetTopologySuite(); }); builder.UseBulkInsertSqlServer(); + builder.ReplaceService(); }); services.AddNamedDbContext((builder, name) => diff --git a/backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj b/backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj index ff26122ac..edc76ecdd 100644 --- a/backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj +++ b/backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj @@ -43,13 +43,13 @@ - - - - - - - + + + + + + + diff --git a/backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj b/backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj index b7686144d..a58eb5372 100644 --- a/backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj +++ b/backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj @@ -25,12 +25,12 @@ - - - - - - + + + + + + diff --git a/backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj b/backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj index 1f8315f64..93b6c3ce9 100644 --- a/backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj +++ b/backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj @@ -20,7 +20,7 @@ - + diff --git a/backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj b/backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj index ff1a5730f..f44edb8b1 100644 --- a/backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj +++ b/backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj @@ -29,8 +29,8 @@ - - + + diff --git a/backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj b/backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj index 3fcc8d81a..3f90dc2e2 100644 --- a/backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj +++ b/backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj @@ -24,13 +24,13 @@ - - - - - - - + + + + + + + diff --git a/backend/src/Squidex/Squidex.csproj b/backend/src/Squidex/Squidex.csproj index 8e5e19c74..39cfd1ea9 100644 --- a/backend/src/Squidex/Squidex.csproj +++ b/backend/src/Squidex/Squidex.csproj @@ -59,16 +59,16 @@ - - - - - - + + + + + + - - - + + + @@ -82,12 +82,12 @@ - + - + diff --git a/backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/Text/EFTextIndexTests.cs b/backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/Text/EFTextIndexTests.cs index d50f31157..4f5976534 100644 --- a/backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/Text/EFTextIndexTests.cs +++ b/backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/Text/EFTextIndexTests.cs @@ -6,6 +6,7 @@ // ========================================================================== using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; using Squidex.Domain.Apps.Entities.Contents.Text; using Squidex.EntityFramework.TestHelpers; using Squidex.Infrastructure; @@ -21,7 +22,7 @@ public abstract class EFTextIndexTests(ISqlFixture fixture) public override async Task CreateSutAsync() { - var sut = new EFTextIndex(fixture.DbContextFactory); + var sut = new EFTextIndex(fixture.DbContextFactory, A.Fake>>()); await sut.InitializeAsync(default); return sut; diff --git a/backend/tests/Squidex.Data.Tests/EntityFramework/Infrastructure/Queries/EFQueryTests.cs b/backend/tests/Squidex.Data.Tests/EntityFramework/Infrastructure/Queries/EFQueryTests.cs index 42e2fe093..888a85155 100644 --- a/backend/tests/Squidex.Data.Tests/EntityFramework/Infrastructure/Queries/EFQueryTests.cs +++ b/backend/tests/Squidex.Data.Tests/EntityFramework/Infrastructure/Queries/EFQueryTests.cs @@ -6,6 +6,7 @@ // ========================================================================== using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; using NetTopologySuite.Geometries; using Squidex.EntityFramework.TestHelpers; using Squidex.Infrastructure; @@ -33,8 +34,8 @@ public abstract class EFQueryTests(ISqlFixture fixture) { var dbContext = await CreateDbContextAsync(); - await dbContext.CreateGeoIndexAsync("IDX_GEO", nameof(TestEntity), "Point"); - await dbContext.CreateTextIndexAsync("IDX_Text", nameof(TestEntity), "FullText"); + await dbContext.CreateGeoIndexAsync("IDX_GEO", nameof(TestEntity), "Point", NullLogger.Instance); + await dbContext.CreateTextIndexAsync("IDX_Text", nameof(TestEntity), "FullText", NullLogger.Instance); var set = dbContext.Set(); if (await set.AnyAsync()) diff --git a/backend/tests/Squidex.Data.Tests/EntityFramework/Migrations/MySqlMigrationTests.cs b/backend/tests/Squidex.Data.Tests/EntityFramework/Migrations/MySqlMigrationTests.cs index 2dc723447..afdfee5c8 100644 --- a/backend/tests/Squidex.Data.Tests/EntityFramework/Migrations/MySqlMigrationTests.cs +++ b/backend/tests/Squidex.Data.Tests/EntityFramework/Migrations/MySqlMigrationTests.cs @@ -5,9 +5,14 @@ // All rights reserved. Licensed under the MIT license. // ========================================================================== +using System.Text; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using MySqlConnector; using Squidex.Domain.Apps.Core.TestHelpers; +using Squidex.EntityFramework.TestHelpers; using Squidex.Infrastructure; using Squidex.Infrastructure.Migrations; using Squidex.Providers.MySql; @@ -47,9 +52,12 @@ public class MySqlMigrationTests : IAsyncLifetime options.UseNetTopologySuite(); options.UseMicrosoftJson(MySqlCommonJsonChangeTrackingOptions.FullHierarchyOptimizedSemantically); }); + + b.ReplaceService(); }) .AddSingleton() .AddSingleton(TestUtils.DefaultSerializer) + .AddLogging() .AddSingleton>() .BuildServiceProvider(); @@ -78,9 +86,12 @@ public class MySqlMigrationTests : IAsyncLifetime options.UseNetTopologySuite(); options.UseMicrosoftJson(MySqlCommonJsonChangeTrackingOptions.FullHierarchyOptimizedSemantically); }); + + b.ReplaceService(); }) .AddSingleton() .AddSingleton(TestUtils.DefaultSerializer) + .AddLogging() .AddSingleton>() .BuildServiceProvider(); @@ -113,9 +124,12 @@ public class MySqlMigrationTests : IAsyncLifetime options.UseNetTopologySuite(); options.UseMicrosoftJson(MySqlCommonJsonChangeTrackingOptions.FullHierarchyOptimizedSemantically); }); + + b.ReplaceService(); }) .AddSingleton() .AddSingleton(TestUtils.DefaultSerializer) + .AddLogging() .AddSingleton>() .BuildServiceProvider(); @@ -144,4 +158,60 @@ public class MySqlMigrationTests : IAsyncLifetime "SELECT json_exists('{{\"a\":1}}', '$.a')"); Assert.Equal(-1, result); } + + [Fact] + public async Task Should_log_script_if_privileges_are_missing() + { + // Binary logging is enabled by default, therefore functions can only be created with the SUPER privilege. + await using var mysqlRestricted = new MySqlBuilder("mysql:8.0").Build(); + await mysqlRestricted.StartAsync(TestContext.Current.CancellationToken); + + var log = new TestLogger>(); + + var services = + new ServiceCollection() + .AddDbContextFactory(b => + { + var connectionString = mysqlRestricted.GetConnectionString(); + + b.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString), options => + { + options.UseNetTopologySuite(); + options.UseMicrosoftJson(MySqlCommonJsonChangeTrackingOptions.FullHierarchyOptimizedSemantically); + }); + + b.ReplaceService(); + }) + .AddSingleton() + .AddSingleton(TestUtils.DefaultSerializer) + .AddSingleton>>(log) + .AddSingleton>() + .BuildServiceProvider(); + + var databaseMigrator = services.GetRequiredService>(); + + var ex = await Assert.ThrowsAsync(() => databaseMigrator.InitializeAsync(default)); + Assert.Equal(MySqlErrorCode.BinLogCreateRoutineNeedSuper, ex.ErrorCode); + + var message = Assert.Single(log.Messages); + Assert.Contains("Insufficient privileges", message, StringComparison.Ordinal); + Assert.Contains("DELIMITER //", message, StringComparison.Ordinal); + Assert.Contains("CREATE FUNCTION json_empty", message, StringComparison.Ordinal); + Assert.DoesNotContain("20250204160706_Initial", message, StringComparison.Ordinal); + + // Execute the script like an administrator with the MySQL client to verify that it is executable. + var script = message[(message.IndexOf('\n', StringComparison.Ordinal) + 1)..]; + + await mysqlRestricted.CopyAsync(Encoding.UTF8.GetBytes(script), "/tmp/migration.sql", ct: TestContext.Current.CancellationToken); + + var execResult = await mysqlRestricted.ExecAsync(["sh", "-c", "mysql -uroot -pmysql test < /tmp/migration.sql"], TestContext.Current.CancellationToken); + Assert.True(execResult.ExitCode == 0, execResult.Stdout + execResult.Stderr); + + await databaseMigrator.InitializeAsync(default); + + await using var verifyContext = await services.GetRequiredService>().CreateDbContextAsync(); + var result = await verifyContext.Database.ExecuteSqlRawAsync( + "SELECT json_exists('{{\"a\":1}}', '$.a')"); + Assert.Equal(-1, result); + } } diff --git a/backend/tests/Squidex.Data.Tests/EntityFramework/Migrations/PostgresMigrationTests.cs b/backend/tests/Squidex.Data.Tests/EntityFramework/Migrations/PostgresMigrationTests.cs index 744f07854..896b6373c 100644 --- a/backend/tests/Squidex.Data.Tests/EntityFramework/Migrations/PostgresMigrationTests.cs +++ b/backend/tests/Squidex.Data.Tests/EntityFramework/Migrations/PostgresMigrationTests.cs @@ -5,9 +5,13 @@ // All rights reserved. Licensed under the MIT license. // ========================================================================== +using System.Text; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Npgsql; using Squidex.Domain.Apps.Core.TestHelpers; +using Squidex.EntityFramework.TestHelpers; using Squidex.Infrastructure; using Squidex.Infrastructure.Migrations; using Squidex.Providers.Postgres; @@ -47,6 +51,7 @@ public class PostgresMigrationTests : IAsyncLifetime }) .AddSingleton() .AddSingleton(TestUtils.DefaultSerializer) + .AddLogging() .AddSingleton>() .BuildServiceProvider(); @@ -75,6 +80,7 @@ public class PostgresMigrationTests : IAsyncLifetime }) .AddSingleton() .AddSingleton(TestUtils.DefaultSerializer) + .AddLogging() .AddSingleton>() .BuildServiceProvider(); @@ -107,6 +113,7 @@ public class PostgresMigrationTests : IAsyncLifetime }) .AddSingleton() .AddSingleton(TestUtils.DefaultSerializer) + .AddLogging() .AddSingleton>() .BuildServiceProvider(); @@ -135,4 +142,84 @@ public class PostgresMigrationTests : IAsyncLifetime "SELECT jsonb_exists('{{\"a\":1}}'::jsonb)"); Assert.Equal(-1, result); } + + [Fact] + public async Task Should_log_script_if_privileges_are_missing() + { + var connectionString = await CreateRestrictedDatabaseAsync(); + + var log = new TestLogger>(); + + var services = + new ServiceCollection() + .AddDbContextFactory(b => + { + b.UseNpgsql(connectionString, options => + { + options.UseNetTopologySuite(); + }); + }) + .AddSingleton() + .AddSingleton(TestUtils.DefaultSerializer) + .AddSingleton>>(log) + .AddSingleton>() + .BuildServiceProvider(); + + var databaseMigrator = services.GetRequiredService>(); + + // Only a superuser can create the postgis extension. + var ex = await Assert.ThrowsAsync(() => databaseMigrator.InitializeAsync(default)); + Assert.Equal(PostgresErrorCodes.InsufficientPrivilege, ex.SqlState); + + var message = Assert.Single(log.Messages); + Assert.Contains("Insufficient privileges", message, StringComparison.Ordinal); + Assert.Contains("CREATE EXTENSION IF NOT EXISTS postgis", message, StringComparison.Ordinal); + Assert.Contains("INSERT INTO \"__EFMigrationsHistory\"", message, StringComparison.Ordinal); + + // Execute the script like an administrator with the Postgres client to verify that it is executable. + // The application user executes it with temporarily elevated privileges to remain the owner of the tables. + var script = message[(message.IndexOf('\n', StringComparison.Ordinal) + 1)..]; + + await postgreSql.CopyAsync(Encoding.UTF8.GetBytes(script), "/tmp/migration.sql", ct: TestContext.Current.CancellationToken); + + await ExecuteAsSuperuserAsync("ALTER ROLE restricted SUPERUSER"); + + var execResult = await postgreSql.ExecAsync(["psql", "-v", "ON_ERROR_STOP=1", "-U", "restricted", "-d", "restricted", "-f", "/tmp/migration.sql"], TestContext.Current.CancellationToken); + Assert.True(execResult.ExitCode == 0, execResult.Stdout + execResult.Stderr); + + await ExecuteAsSuperuserAsync("ALTER ROLE restricted NOSUPERUSER"); + + await databaseMigrator.InitializeAsync(default); + + await using var verifyContext = await services.GetRequiredService>().CreateDbContextAsync(); + var result = await verifyContext.Database.ExecuteSqlRawAsync( + "SELECT jsonb_exists('{{\"a\":1}}'::jsonb)"); + Assert.Equal(-1, result); + } + + private async Task CreateRestrictedDatabaseAsync() + { + await ExecuteAsSuperuserAsync("CREATE ROLE restricted LOGIN PASSWORD 'restricted'"); + await ExecuteAsSuperuserAsync("CREATE DATABASE restricted OWNER restricted"); + + var builder = new NpgsqlConnectionStringBuilder(postgreSql.GetConnectionString()) + { + Database = "restricted", + Username = "restricted", + Password = "restricted", + }; + + return builder.ConnectionString; + } + + private async Task ExecuteAsSuperuserAsync(string sql) + { + await using var connection = new NpgsqlConnection(postgreSql.GetConnectionString()); + await connection.OpenAsync(); + + await using var command = connection.CreateCommand(); + + command.CommandText = sql; + await command.ExecuteNonQueryAsync(); + } } diff --git a/backend/tests/Squidex.Data.Tests/EntityFramework/Migrations/SqlServerMigrationTests.cs b/backend/tests/Squidex.Data.Tests/EntityFramework/Migrations/SqlServerMigrationTests.cs index 263acf41a..b66d7ddb2 100644 --- a/backend/tests/Squidex.Data.Tests/EntityFramework/Migrations/SqlServerMigrationTests.cs +++ b/backend/tests/Squidex.Data.Tests/EntityFramework/Migrations/SqlServerMigrationTests.cs @@ -5,9 +5,13 @@ // All rights reserved. Licensed under the MIT license. // ========================================================================== +using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using Squidex.Domain.Apps.Core.TestHelpers; +using Squidex.EntityFramework.TestHelpers; using Squidex.Infrastructure; using Squidex.Infrastructure.Migrations; using Squidex.Providers.SqlServer; @@ -44,9 +48,12 @@ public class SqlServerMigrationTests : IAsyncLifetime { options.UseNetTopologySuite(); }); + + b.ReplaceService(); }) .AddSingleton() .AddSingleton(TestUtils.DefaultSerializer) + .AddLogging() .AddSingleton>() .BuildServiceProvider(); @@ -72,9 +79,12 @@ public class SqlServerMigrationTests : IAsyncLifetime { options.UseNetTopologySuite(); }); + + b.ReplaceService(); }) .AddSingleton() .AddSingleton(TestUtils.DefaultSerializer) + .AddLogging() .AddSingleton>() .BuildServiceProvider(); @@ -104,9 +114,12 @@ public class SqlServerMigrationTests : IAsyncLifetime { options.UseNetTopologySuite(); }); + + b.ReplaceService(); }) .AddSingleton() .AddSingleton(TestUtils.DefaultSerializer) + .AddLogging() .AddSingleton>() .BuildServiceProvider(); @@ -135,4 +148,86 @@ public class SqlServerMigrationTests : IAsyncLifetime "SELECT dbo.json_exists('{{\"a\":1}}', '$.a')"); Assert.Equal(-1, result); } + + [Fact] + public async Task Should_log_script_if_privileges_are_missing() + { + var connectionString = await CreateRestrictedDatabaseAsync(); + + var log = new TestLogger>(); + + var services = + new ServiceCollection() + .AddDbContextFactory(b => + { + b.UseSqlServer(connectionString, options => + { + options.UseNetTopologySuite(); + }); + + b.ReplaceService(); + }) + .AddSingleton() + .AddSingleton(TestUtils.DefaultSerializer) + .AddSingleton>>(log) + .AddSingleton>() + .BuildServiceProvider(); + + var databaseMigrator = services.GetRequiredService>(); + + // The user can create tables, but not functions. + var ex = await Assert.ThrowsAsync(() => databaseMigrator.InitializeAsync(default)); + Assert.Equal(262, ex.Number); + + var message = Assert.Single(log.Messages); + Assert.Contains("Insufficient privileges", message, StringComparison.Ordinal); + Assert.Contains("CREATE OR ALTER FUNCTION dbo.json_empty", message, StringComparison.Ordinal); + Assert.DoesNotContain("20250204160718_Initial", message, StringComparison.Ordinal); + + // Execute the script like an administrator with the SQL Server client to verify that it is executable. + var script = message[(message.IndexOf('\n', StringComparison.Ordinal) + 1)..]; + + var execResult = await sqlServer.ExecScriptAsync($"USE restricted;\nGO\n{script}", TestContext.Current.CancellationToken); + Assert.True(execResult.ExitCode == 0, execResult.Stdout + execResult.Stderr); + + await databaseMigrator.InitializeAsync(default); + + await using var verifyContext = await services.GetRequiredService>().CreateDbContextAsync(); + var result = await verifyContext.Database.ExecuteSqlRawAsync( + "SELECT dbo.json_exists('{{\"a\":1}}', '$.a')"); + Assert.Equal(-1, result); + } + + private async Task CreateRestrictedDatabaseAsync() + { + const string Password = "Sq1dex_Migr4tion!"; + + await using (var connection = new SqlConnection(sqlServer.GetConnectionString())) + { + await connection.OpenAsync(); + + await using var command = connection.CreateCommand(); + + command.CommandText = $"CREATE DATABASE restricted; CREATE LOGIN restricted WITH PASSWORD = '{Password}';"; + await command.ExecuteNonQueryAsync(); + + command.CommandText = @" +USE restricted; +CREATE USER restricted FOR LOGIN restricted; +ALTER ROLE db_datareader ADD MEMBER restricted; +ALTER ROLE db_datawriter ADD MEMBER restricted; +GRANT CREATE TABLE TO restricted; +GRANT ALTER, REFERENCES, EXECUTE ON SCHEMA::dbo TO restricted;"; + await command.ExecuteNonQueryAsync(); + } + + var builder = new SqlConnectionStringBuilder(sqlServer.GetConnectionString()) + { + InitialCatalog = "restricted", + UserID = "restricted", + Password = Password, + }; + + return builder.ConnectionString; + } } diff --git a/backend/tests/Squidex.Data.Tests/EntityFramework/TestHelpers/TestLogger.cs b/backend/tests/Squidex.Data.Tests/EntityFramework/TestHelpers/TestLogger.cs new file mode 100644 index 000000000..5dc7c65b9 --- /dev/null +++ b/backend/tests/Squidex.Data.Tests/EntityFramework/TestHelpers/TestLogger.cs @@ -0,0 +1,31 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Microsoft.Extensions.Logging; + +namespace Squidex.EntityFramework.TestHelpers; + +public sealed class TestLogger : ILogger +{ + public List Messages { get; } = []; + + public IDisposable? BeginScope(TState state) + where TState : notnull + { + return null; + } + + public bool IsEnabled(LogLevel logLevel) + { + return true; + } + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + Messages.Add(formatter(state, exception)); + } +}