Browse Source

Improve logging. (#1366)

* Improve logging.

* Add missing files
pull/1367/head
Sebastian Stehle 3 weeks ago
committed by GitHub
parent
commit
f888c4cb8b
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 7
      backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/Text/EFTextIndex.cs
  2. 22
      backend/src/Squidex.Data.EntityFramework/Infrastructure/LogMessages.cs
  3. 65
      backend/src/Squidex.Data.EntityFramework/Infrastructure/Migrations/DatabaseMigrator.cs
  4. 52
      backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/QueryExtensions.cs
  5. 5
      backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlDialect.cs
  6. 2
      backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/20260512000000_AddJsonFunctions.cs
  7. 4
      backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/MySqlAppDbContextDesignTimeFactory.cs
  8. 16
      backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlDialect.cs
  9. 42
      backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlScriptMigrationsSqlGenerator.cs
  10. 2
      backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/20260512000002_AddJsonFunctions.cs
  11. 6
      backend/src/Squidex.Data.EntityFramework/Providers/Postgres/PostgresDialect.cs
  12. 2
      backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/20260512000001_AddJsonFunctions.cs
  13. 4
      backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/SqlServerAppDbContextDesignTimeFactory.cs
  14. 7
      backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerDialect.cs
  15. 36
      backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerScriptMigrationsSqlGenerator.cs
  16. 3
      backend/src/Squidex.Data.EntityFramework/ServiceExtensions.cs
  17. 14
      backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj
  18. 12
      backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj
  19. 2
      backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj
  20. 4
      backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj
  21. 14
      backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj
  22. 22
      backend/src/Squidex/Squidex.csproj
  23. 3
      backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/Text/EFTextIndexTests.cs
  24. 5
      backend/tests/Squidex.Data.Tests/EntityFramework/Infrastructure/Queries/EFQueryTests.cs
  25. 70
      backend/tests/Squidex.Data.Tests/EntityFramework/Migrations/MySqlMigrationTests.cs
  26. 87
      backend/tests/Squidex.Data.Tests/EntityFramework/Migrations/PostgresMigrationTests.cs
  27. 95
      backend/tests/Squidex.Data.Tests/EntityFramework/Migrations/SqlServerMigrationTests.cs
  28. 31
      backend/tests/Squidex.Data.Tests/EntityFramework/TestHelpers/TestLogger.cs

7
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<TContext>(IDbContextFactory<TContext> dbContextFactory)
public sealed class EFTextIndex<TContext>(IDbContextFactory<TContext> dbContextFactory, ILogger<EFTextIndex<TContext>> log)
: ITextIndex, IInitializable, IDeleter
where TContext : DbContext, IDbContextWithDialect
{
@ -39,8 +40,8 @@ public sealed class EFTextIndex<TContext>(IDbContextFactory<TContext> 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,

22
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);
}

65
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<TContext>(IDbContextFactory<TContext> dbContextFactory, ConnectionStringParser parser) : IInitializable
public sealed class DatabaseMigrator<TContext>(
IDbContextFactory<TContext> dbContextFactory,
ConnectionStringParser parser,
ILogger<DatabaseMigrator<TContext>> log)
: IInitializable
where TContext : DbContext
{
private static readonly TimeSpan WaitTime = TimeSpan.FromSeconds(30);
@ -48,6 +55,60 @@ public sealed class DatabaseMigrator<TContext>(IDbContextFactory<TContext> 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<string?> 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<IMigrator>().GenerateScript(migrationsLast ?? Migration.InitialDatabase);
}
catch
{
// The script is only an additional hint and must not hide the original exception.
return null;
}
}
}

52
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<TContext>(this TContext dbContext, string name, string table, string column,
public static Task CreateGeoIndexAsync<TContext>(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<TContext>(this TContext dbContext, string name, string table, string column,
public static Task CreateTextIndexAsync<TContext>(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<TContext>(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;
}
}
}
}

5
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)
{

2
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)
{

4
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<IMigrationsSqlGenerator, MySqlScriptMigrationsSqlGenerator>();
return new MySqlAppDbContext(builder.Options, new SystemJsonSerializer(JsonSerializerOptions.Default));
}

16
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";

42
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);
}
}

2
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)
{

6
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";

2
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)
{

4
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<IMigrationsSqlGenerator, SqlServerScriptMigrationsSqlGenerator>();
return new SqlServerAppDbContext(builder.Options, new SystemJsonSerializer(JsonSerializerOptions.Default));
}

7
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;";

36
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);
}
}

3
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<IMigrationsSqlGenerator, MySqlScriptMigrationsSqlGenerator>();
});
services.AddNamedDbContext<MySqlContentDbContext>((builder, name) =>
@ -160,6 +162,7 @@ public static class ServiceExtensions
options.UseNetTopologySuite();
});
builder.UseBulkInsertSqlServer();
builder.ReplaceService<IMigrationsSqlGenerator, SqlServerScriptMigrationsSqlGenerator>();
});
services.AddNamedDbContext<SqlServerContentDbContext>((builder, name) =>

14
backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj

@ -43,13 +43,13 @@
<PackageReference Include="Microting.EntityFrameworkCore.MySql.Json.Microsoft" Version="10.0.6" />
<PackageReference Include="Microting.EntityFrameworkCore.MySql.NetTopologySuite" Version="10.0.6" />
<PackageReference Include="RefactoringEssentials" Version="5.6.0" PrivateAssets="all" />
<PackageReference Include="Squidex.AI.EntityFramework" Version="8.0.6" />
<PackageReference Include="Squidex.Assets.EntityFramework" Version="8.0.6" />
<PackageReference Include="Squidex.Assets.TusAdapter" Version="8.0.6" />
<PackageReference Include="Squidex.Events.EntityFramework" Version="8.0.6" />
<PackageReference Include="Squidex.Flows.EntityFramework" Version="8.0.6" />
<PackageReference Include="Squidex.Hosting" Version="8.0.6" />
<PackageReference Include="Squidex.Messaging.EntityFramework" Version="8.0.6" />
<PackageReference Include="Squidex.AI.EntityFramework" Version="8.0.7" />
<PackageReference Include="Squidex.Assets.EntityFramework" Version="8.0.7" />
<PackageReference Include="Squidex.Assets.TusAdapter" Version="8.0.7" />
<PackageReference Include="Squidex.Events.EntityFramework" Version="8.0.7" />
<PackageReference Include="Squidex.Flows.EntityFramework" Version="8.0.7" />
<PackageReference Include="Squidex.Hosting" Version="8.0.7" />
<PackageReference Include="Squidex.Messaging.EntityFramework" Version="8.0.7" />
<PackageReference Include="Squidex.OpenIdDict.EntityFramework" Version="7.2.1" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
<PackageReference Include="System.ValueTuple" Version="4.6.2" />

12
backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj

@ -25,12 +25,12 @@
<PackageReference Include="MongoDB.Driver.Core.Extensions.DiagnosticSources" Version="3.0.0" />
<PackageReference Include="NodaTime.Serialization.SystemTextJson" Version="1.3.1" />
<PackageReference Include="RefactoringEssentials" Version="5.6.0" PrivateAssets="all" />
<PackageReference Include="Squidex.AI.Mongo" Version="8.0.6" />
<PackageReference Include="Squidex.Assets.Mongo" Version="8.0.6" />
<PackageReference Include="Squidex.Events.Mongo" Version="8.0.6" />
<PackageReference Include="Squidex.Flows.Mongo" Version="8.0.6" />
<PackageReference Include="Squidex.Hosting" Version="8.0.6" />
<PackageReference Include="Squidex.Messaging.Mongo" Version="8.0.6" />
<PackageReference Include="Squidex.AI.Mongo" Version="8.0.7" />
<PackageReference Include="Squidex.Assets.Mongo" Version="8.0.7" />
<PackageReference Include="Squidex.Events.Mongo" Version="8.0.7" />
<PackageReference Include="Squidex.Flows.Mongo" Version="8.0.7" />
<PackageReference Include="Squidex.Hosting" Version="8.0.7" />
<PackageReference Include="Squidex.Messaging.Mongo" Version="8.0.7" />
<PackageReference Include="Squidex.OpenIddict.MongoDb" Version="7.2.1" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
<PackageReference Include="System.ValueTuple" Version="4.6.2" />

2
backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj

@ -20,7 +20,7 @@
<PackageReference Include="NetTopologySuite" Version="2.6.0" />
<PackageReference Include="NodaTime.Serialization.SystemTextJson" Version="1.3.1" />
<PackageReference Include="RefactoringEssentials" Version="5.6.0" PrivateAssets="all" />
<PackageReference Include="Squidex.Flows" Version="8.0.6" />
<PackageReference Include="Squidex.Flows" Version="8.0.7" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
</ItemGroup>

4
backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj

@ -29,8 +29,8 @@
<PackageReference Include="NJsonSchema" Version="11.6.1" />
<PackageReference Include="NodaTime.Serialization.SystemTextJson" Version="1.3.1" />
<PackageReference Include="RefactoringEssentials" Version="5.6.0" PrivateAssets="all" />
<PackageReference Include="Squidex.AI" Version="8.0.6" />
<PackageReference Include="Squidex.Messaging.Subscriptions" Version="8.0.6" />
<PackageReference Include="Squidex.AI" Version="8.0.7" />
<PackageReference Include="Squidex.Messaging.Subscriptions" Version="8.0.7" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
<PackageReference Include="System.Linq.Async" Version="7.0.1" />
<PackageReference Include="ValueTaskSupplement" Version="1.1.0" />

14
backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj

@ -24,13 +24,13 @@
<PackageReference Include="NodaTime" Version="3.3.1" />
<PackageReference Include="OpenTelemetry.Api" Version="1.15.3" />
<PackageReference Include="RefactoringEssentials" Version="5.6.0" PrivateAssets="all" />
<PackageReference Include="Squidex.Assets" Version="8.0.6" />
<PackageReference Include="Squidex.Caching" Version="8.0.6" />
<PackageReference Include="Squidex.Events" Version="8.0.6" />
<PackageReference Include="Squidex.Hosting.Abstractions" Version="8.0.6" />
<PackageReference Include="Squidex.Log" Version="8.0.6" />
<PackageReference Include="Squidex.Messaging" Version="8.0.6" />
<PackageReference Include="Squidex.Text" Version="8.0.6" />
<PackageReference Include="Squidex.Assets" Version="8.0.7" />
<PackageReference Include="Squidex.Caching" Version="8.0.7" />
<PackageReference Include="Squidex.Events" Version="8.0.7" />
<PackageReference Include="Squidex.Hosting.Abstractions" Version="8.0.7" />
<PackageReference Include="Squidex.Log" Version="8.0.7" />
<PackageReference Include="Squidex.Messaging" Version="8.0.7" />
<PackageReference Include="Squidex.Text" Version="8.0.7" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
<PackageReference Include="System.Linq.Async" Version="7.0.1" />

22
backend/src/Squidex/Squidex.csproj

@ -59,16 +59,16 @@
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.15.1" />
<PackageReference Include="RefactoringEssentials" Version="5.6.0" PrivateAssets="all" />
<PackageReference Include="ReportGenerator" Version="5.5.6" PrivateAssets="all" />
<PackageReference Include="Squidex.Assets.Azure" Version="8.0.6" />
<PackageReference Include="Squidex.Assets.GoogleCloud" Version="8.0.6" />
<PackageReference Include="Squidex.Assets.FTP" Version="8.0.6" />
<PackageReference Include="Squidex.Assets.ImageSharp" Version="8.0.6" />
<PackageReference Include="Squidex.Assets.S3" Version="8.0.6" />
<PackageReference Include="Squidex.Assets.TusAdapter" Version="8.0.6" />
<PackageReference Include="Squidex.Assets.Azure" Version="8.0.7" />
<PackageReference Include="Squidex.Assets.GoogleCloud" Version="8.0.7" />
<PackageReference Include="Squidex.Assets.FTP" Version="8.0.7" />
<PackageReference Include="Squidex.Assets.ImageSharp" Version="8.0.7" />
<PackageReference Include="Squidex.Assets.S3" Version="8.0.7" />
<PackageReference Include="Squidex.Assets.TusAdapter" Version="8.0.7" />
<PackageReference Include="Squidex.ClientLibrary" Version="22.6.0" />
<PackageReference Include="Squidex.Hosting" Version="8.0.6" />
<PackageReference Include="Squidex.Messaging.All" Version="8.0.6" />
<PackageReference Include="Squidex.Messaging.Subscriptions" Version="8.0.6" />
<PackageReference Include="Squidex.Hosting" Version="8.0.7" />
<PackageReference Include="Squidex.Messaging.All" Version="8.0.7" />
<PackageReference Include="Squidex.Messaging.Subscriptions" Version="8.0.7" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
<PackageReference Include="YDotNet" Version="0.6.0" />
<PackageReference Include="YDotNet.Native" Version="0.6.0" />
@ -82,12 +82,12 @@
</ItemGroup>
<ItemGroup Condition="'$(IncludeMagick)' == 'true'">
<PackageReference Include="Squidex.Assets.ImageMagick" Version="8.0.6" />
<PackageReference Include="Squidex.Assets.ImageMagick" Version="8.0.7" />
<PackageReference Include="Magick.NET-Q8-AnyCPU" Version="14.16.0" />
</ItemGroup>
<ItemGroup Condition="'$(IncludeKafka)' == 'true'">
<PackageReference Include="Squidex.Messaging.Kafka" Version="8.0.6" />
<PackageReference Include="Squidex.Messaging.Kafka" Version="8.0.7" />
</ItemGroup>
<PropertyGroup>

3
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<TContext>(ISqlFixture<TContext> fixture)
public override async Task<ITextIndex> CreateSutAsync()
{
var sut = new EFTextIndex<TContext>(fixture.DbContextFactory);
var sut = new EFTextIndex<TContext>(fixture.DbContextFactory, A.Fake<ILogger<EFTextIndex<TContext>>>());
await sut.InitializeAsync(default);
return sut;

5
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<TContext>(ISqlFixture<TContext> 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<TestEntity>();
if (await set.AnyAsync())

70
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<IMigrationsSqlGenerator, MySqlScriptMigrationsSqlGenerator>();
})
.AddSingleton<ConnectionStringParser, MySqlConnectionStringParser>()
.AddSingleton(TestUtils.DefaultSerializer)
.AddLogging()
.AddSingleton<DatabaseMigrator<MySqlAppDbContext>>()
.BuildServiceProvider();
@ -78,9 +86,12 @@ public class MySqlMigrationTests : IAsyncLifetime
options.UseNetTopologySuite();
options.UseMicrosoftJson(MySqlCommonJsonChangeTrackingOptions.FullHierarchyOptimizedSemantically);
});
b.ReplaceService<IMigrationsSqlGenerator, MySqlScriptMigrationsSqlGenerator>();
})
.AddSingleton<ConnectionStringParser, MySqlConnectionStringParser>()
.AddSingleton(TestUtils.DefaultSerializer)
.AddLogging()
.AddSingleton<DatabaseMigrator<MySqlAppDbContext>>()
.BuildServiceProvider();
@ -113,9 +124,12 @@ public class MySqlMigrationTests : IAsyncLifetime
options.UseNetTopologySuite();
options.UseMicrosoftJson(MySqlCommonJsonChangeTrackingOptions.FullHierarchyOptimizedSemantically);
});
b.ReplaceService<IMigrationsSqlGenerator, MySqlScriptMigrationsSqlGenerator>();
})
.AddSingleton<ConnectionStringParser, MySqlConnectionStringParser>()
.AddSingleton(TestUtils.DefaultSerializer)
.AddLogging()
.AddSingleton<DatabaseMigrator<MySqlAppDbContext>>()
.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<DatabaseMigrator<MySqlAppDbContext>>();
var services =
new ServiceCollection()
.AddDbContextFactory<MySqlAppDbContext>(b =>
{
var connectionString = mysqlRestricted.GetConnectionString();
b.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString), options =>
{
options.UseNetTopologySuite();
options.UseMicrosoftJson(MySqlCommonJsonChangeTrackingOptions.FullHierarchyOptimizedSemantically);
});
b.ReplaceService<IMigrationsSqlGenerator, MySqlScriptMigrationsSqlGenerator>();
})
.AddSingleton<ConnectionStringParser, MySqlConnectionStringParser>()
.AddSingleton(TestUtils.DefaultSerializer)
.AddSingleton<ILogger<DatabaseMigrator<MySqlAppDbContext>>>(log)
.AddSingleton<DatabaseMigrator<MySqlAppDbContext>>()
.BuildServiceProvider();
var databaseMigrator = services.GetRequiredService<DatabaseMigrator<MySqlAppDbContext>>();
var ex = await Assert.ThrowsAsync<MySqlException>(() => 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<IDbContextFactory<MySqlAppDbContext>>().CreateDbContextAsync();
var result = await verifyContext.Database.ExecuteSqlRawAsync(
"SELECT json_exists('{{\"a\":1}}', '$.a')");
Assert.Equal(-1, result);
}
}

87
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<ConnectionStringParser, PostgresConnectionStringParser>()
.AddSingleton(TestUtils.DefaultSerializer)
.AddLogging()
.AddSingleton<DatabaseMigrator<PostgresAppDbContext>>()
.BuildServiceProvider();
@ -75,6 +80,7 @@ public class PostgresMigrationTests : IAsyncLifetime
})
.AddSingleton<ConnectionStringParser, PostgresConnectionStringParser>()
.AddSingleton(TestUtils.DefaultSerializer)
.AddLogging()
.AddSingleton<DatabaseMigrator<PostgresAppDbContext>>()
.BuildServiceProvider();
@ -107,6 +113,7 @@ public class PostgresMigrationTests : IAsyncLifetime
})
.AddSingleton<ConnectionStringParser, PostgresConnectionStringParser>()
.AddSingleton(TestUtils.DefaultSerializer)
.AddLogging()
.AddSingleton<DatabaseMigrator<PostgresAppDbContext>>()
.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<DatabaseMigrator<PostgresAppDbContext>>();
var services =
new ServiceCollection()
.AddDbContextFactory<PostgresAppDbContext>(b =>
{
b.UseNpgsql(connectionString, options =>
{
options.UseNetTopologySuite();
});
})
.AddSingleton<ConnectionStringParser, PostgresConnectionStringParser>()
.AddSingleton(TestUtils.DefaultSerializer)
.AddSingleton<ILogger<DatabaseMigrator<PostgresAppDbContext>>>(log)
.AddSingleton<DatabaseMigrator<PostgresAppDbContext>>()
.BuildServiceProvider();
var databaseMigrator = services.GetRequiredService<DatabaseMigrator<PostgresAppDbContext>>();
// Only a superuser can create the postgis extension.
var ex = await Assert.ThrowsAsync<PostgresException>(() => 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<IDbContextFactory<PostgresAppDbContext>>().CreateDbContextAsync();
var result = await verifyContext.Database.ExecuteSqlRawAsync(
"SELECT jsonb_exists('{{\"a\":1}}'::jsonb)");
Assert.Equal(-1, result);
}
private async Task<string> 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();
}
}

95
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<IMigrationsSqlGenerator, SqlServerScriptMigrationsSqlGenerator>();
})
.AddSingleton<ConnectionStringParser, SqlServerConnectionStringParser>()
.AddSingleton(TestUtils.DefaultSerializer)
.AddLogging()
.AddSingleton<DatabaseMigrator<SqlServerAppDbContext>>()
.BuildServiceProvider();
@ -72,9 +79,12 @@ public class SqlServerMigrationTests : IAsyncLifetime
{
options.UseNetTopologySuite();
});
b.ReplaceService<IMigrationsSqlGenerator, SqlServerScriptMigrationsSqlGenerator>();
})
.AddSingleton<ConnectionStringParser, SqlServerConnectionStringParser>()
.AddSingleton(TestUtils.DefaultSerializer)
.AddLogging()
.AddSingleton<DatabaseMigrator<SqlServerAppDbContext>>()
.BuildServiceProvider();
@ -104,9 +114,12 @@ public class SqlServerMigrationTests : IAsyncLifetime
{
options.UseNetTopologySuite();
});
b.ReplaceService<IMigrationsSqlGenerator, SqlServerScriptMigrationsSqlGenerator>();
})
.AddSingleton<ConnectionStringParser, SqlServerConnectionStringParser>()
.AddSingleton(TestUtils.DefaultSerializer)
.AddLogging()
.AddSingleton<DatabaseMigrator<SqlServerAppDbContext>>()
.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<DatabaseMigrator<SqlServerAppDbContext>>();
var services =
new ServiceCollection()
.AddDbContextFactory<SqlServerAppDbContext>(b =>
{
b.UseSqlServer(connectionString, options =>
{
options.UseNetTopologySuite();
});
b.ReplaceService<IMigrationsSqlGenerator, SqlServerScriptMigrationsSqlGenerator>();
})
.AddSingleton<ConnectionStringParser, SqlServerConnectionStringParser>()
.AddSingleton(TestUtils.DefaultSerializer)
.AddSingleton<ILogger<DatabaseMigrator<SqlServerAppDbContext>>>(log)
.AddSingleton<DatabaseMigrator<SqlServerAppDbContext>>()
.BuildServiceProvider();
var databaseMigrator = services.GetRequiredService<DatabaseMigrator<SqlServerAppDbContext>>();
// The user can create tables, but not functions.
var ex = await Assert.ThrowsAsync<SqlException>(() => 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<IDbContextFactory<SqlServerAppDbContext>>().CreateDbContextAsync();
var result = await verifyContext.Database.ExecuteSqlRawAsync(
"SELECT dbo.json_exists('{{\"a\":1}}', '$.a')");
Assert.Equal(-1, result);
}
private async Task<string> 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;
}
}

31
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<T> : ILogger<T>
{
public List<string> Messages { get; } = [];
public IDisposable? BeginScope<TState>(TState state)
where TState : notnull
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
Messages.Add(formatter(state, exception));
}
}
Loading…
Cancel
Save