Browse Source

Custom indexes (#1353)

* Custom indexes

* Add missing files

* Improve tests

* Fix tests

* Update resize service.

* Cleanup settings.
pull/1372/head
Sebastian Stehle 4 weeks ago
committed by GitHub
parent
commit
8a345bb750
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 4
      .github/workflows/claude-daily-review.yml
  2. 4
      .github/workflows/claude.yml
  3. 2
      CLAUDE.md
  4. 13
      backend/extensions/Squidex.Extensions/Actions/Kafka/KafkaProducer.cs
  5. 8
      backend/src/Migrations/MigrationPath.cs
  6. 13
      backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/ContentSqlQueryBuilder.cs
  7. 172
      backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/CustomIndexes.cs
  8. 18
      backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository.cs
  9. 59
      backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository_Indexes.cs
  10. 9
      backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository_SnapshotStore.cs
  11. 4
      backend/src/Squidex.Data.EntityFramework/Infrastructure/PooledDbNamedContextFactory.cs
  12. 22
      backend/src/Squidex.Data.EntityFramework/Infrastructure/PrefixModelCacheKeyFactory.cs
  13. 26
      backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlDialect.cs
  14. 19
      backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlIndexKey.cs
  15. 99
      backend/src/Squidex.Data.EntityFramework/Migrations/RebuildDedicatedContentTables.cs
  16. 67
      backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlDialect.cs
  17. 59
      backend/src/Squidex.Data.EntityFramework/Providers/Postgres/PostgresDialect.cs
  18. 83
      backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerDialect.cs
  19. 5
      backend/src/Squidex.Data.EntityFramework/ServiceExtensions.cs
  20. 14
      backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj
  21. 39
      backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Schemas/MongoSchemasHash.cs
  22. 12
      backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj
  23. 2
      backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj
  24. 4
      backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj
  25. 23
      backend/src/Squidex.Domain.Apps.Entities/Contents/GraphQL/CachingGraphQLResolver.cs
  26. 14
      backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj
  27. 22
      backend/src/Squidex/Squidex.csproj
  28. 265
      backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/EFContentRepositoryDedicatedTests.cs
  29. 29
      backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/EFContentRepositoryTests.cs
  30. 42
      backend/tests/Squidex.Data.Tests/MongoDb/Domain/Schemas/MongoSchemasHashTests.cs
  31. 338
      backend/tests/Squidex.Data.Tests/Shared/ContentRepositoryTests.cs
  32. 120
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/GraphQL/CachingGraphQLResolverTests.cs
  33. 8
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/GraphQL/GraphQLTestBase.cs
  34. 37
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Extensions/Kafka/KafkaProducerTests.cs
  35. 56
      tools/TestSuite/TestSuite.ApiTests/AssetFormatTests.cs
  36. 4
      tools/TestSuite/TestSuite.ApiTests/TestSuite.ApiTests.csproj
  37. 6
      tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_fix_orientation.verified.txt
  38. 6
      tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_upload_image_jpg_and_resize.verified.txt
  39. 6
      tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_upload_image_tiff_and_resize.verified.txt
  40. 2
      tools/TestSuite/TestSuite.Shared/TestSuite.Shared.csproj
  41. 2
      tools/TestSuite/docker-compose.yml

4
.github/workflows/claude-daily-review.yml

@ -67,6 +67,7 @@ jobs:
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
github_token: ${{ secrets.GITHUB_TOKEN }}
settings: .github/claude/settings-daily-review.json
prompt: |
You are doing a daily automated review of this repository (Squidex).
Today's focus area is: ${{ steps.focus.outputs.area }}
@ -88,7 +89,7 @@ jobs:
`--filter "Category!=Dependencies & Category!=TestContainer"`.
- frontend: run `npm run lint` and `npm test` in `frontend/`.
5. Write the PR description to ${{ runner.temp }}/pr-body.md: first line is the
PR title (prefix it with "[${{ steps.focus.outputs.area }}]"), then category,
PR title, then category,
severity, affected files, explanation of the problem, how it could be
triggered, and what the fix does.
@ -96,7 +97,6 @@ jobs:
claude_args: >-
--model ${{ vars.CLAUDE_MODEL || 'claude-opus-5-5' }}
--max-turns 80
--allowedTools "Read,Grep,Glob,Edit,Write,Bash(gh pr list:*),Bash(git log:*),Bash(git diff:*),Bash(dotnet build:*),Bash(dotnet test:*),Bash(npm run lint:*),Bash(npm test:*),Bash(npx vitest:*)"
- name: Enforce size limit and open PR
env:

4
.github/workflows/claude.yml

@ -46,8 +46,8 @@ jobs:
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
github_token: ${{ secrets.GITHUB_TOKEN }}
settings: .github/claude/settings.json
claude_args: >-
--model ${{ vars.CLAUDE_MODEL || 'claude-opus-5-5' }}
--max-turns 40
--append-system-prompt "Follow CLAUDE.md. Before committing, verify your changes: for backend changes run dotnet build on the affected project and the related tests with --filter \"Category!=Dependencies & Category!=TestContainer\"; for frontend changes run npm run lint and npm test in frontend/. Never commit frontend/package-lock.json."
--allowedTools "Read,Grep,Glob,Edit,Write,Bash(git status:*),Bash(git log:*),Bash(git diff:*),Bash(gh pr view:*),Bash(gh pr diff:*),Bash(gh pr list:*),Bash(gh issue view:*),Bash(dotnet build:*),Bash(dotnet test:*),Bash(npm run lint:*),Bash(npm test:*),Bash(npx vitest:*)"
--append-system-prompt-file .github/claude/prompt.md

2
CLAUDE.md

@ -65,7 +65,9 @@ dotnet test --filter "Category!=Dependencies & Category!=TestContainer"
- Do not write conditions that span multiple lines. Split them into multiple `if` statements (e.g. early returns) instead.
- Try to keep files under 300 lines. Split larger classes by responsibility. This does not apply to tests.
- Do not put a blank line between a variable assignment and an `if` statement that checks this variable.
- Use the same prefix for related variables, e.g. `postsAll` and `postsTaken` instead of `allPosts` and `taken`.
- Use primary constructors whenever possible.
- In test classes, put helper methods after all tests.
## Maintaining this file

13
backend/extensions/Squidex.Extensions/Actions/Kafka/KafkaProducer.cs

@ -6,6 +6,8 @@
// ==========================================================================
#if INCLUDE_KAFKA
using System.Buffers.Binary;
using System.Security.Cryptography;
using System.Text;
using Avro;
using Avro.Generic;
@ -143,7 +145,7 @@ public sealed class KafkaProducer
if (!string.IsNullOrWhiteSpace(job.PartitionKey) && job.PartitionCount > 0)
{
var partition = Math.Abs(job.PartitionKey.GetHashCode(StringComparison.Ordinal)) % job.PartitionCount;
var partition = GetPartition(job.PartitionKey, job.PartitionCount);
await producer.ProduceAsync(new TopicPartition(job.TopicName, partition), message, ct);
}
@ -153,6 +155,15 @@ public sealed class KafkaProducer
}
}
public static int GetPartition(string partitionKey, int partitionCount)
{
// string.GetHashCode is randomized per process, so the same key would end up in different
// partitions after a restart or on another instance.
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(partitionKey));
return (int)(BinaryPrimitives.ReadUInt32LittleEndian(hash) % (uint)partitionCount);
}
private GenericRecord CreateAvroRecord(string json, string avroSchema)
{
try

8
backend/src/Migrations/MigrationPath.cs

@ -16,7 +16,7 @@ namespace Migrations;
public sealed class MigrationPath(IServiceProvider serviceProvider) : IMigrationPath
{
private const int CurrentVersion = 28;
private const int CurrentVersion = 29;
public (int Version, IEnumerable<IMigration>? Migrations) GetNext(int version)
{
@ -132,5 +132,11 @@ public sealed class MigrationPath(IServiceProvider serviceProvider) : IMigration
{
yield return serviceProvider.GetService<Squidex.Migrations.DropOldAssetIndex>();
}
// Version 29: Move contents into the correct dedicated tables (Entity Framework only).
if (version < 29)
{
yield return serviceProvider.GetKeyedService<IMigration>("RebuildDedicatedContentTables");
}
}
}

13
backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/ContentSqlQueryBuilder.cs

@ -23,6 +23,17 @@ public class ContentSqlQueryBuilder(SqlDialect dialect, string table, SqlParams?
public override bool IsJsonPath(PropertyPath path)
{
return path.Count > 1 && string.Equals(path[0], "data", StringComparison.OrdinalIgnoreCase);
if (path.Count <= 1)
{
return false;
}
// These properties are stored as JSON columns, therefore the nested fields are queried with JSON functions.
if (string.Equals(path[0], nameof(EFContentEntity.Data), StringComparison.OrdinalIgnoreCase))
{
return true;
}
return string.Equals(path[0], nameof(EFContentEntity.TranslationStatus), StringComparison.OrdinalIgnoreCase);
}
}

172
backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/CustomIndexes.cs

@ -0,0 +1,172 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.EntityFrameworkCore;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Queries;
using Squidex.Infrastructure.States;
namespace Squidex.Domain.Apps.Entities.Contents;
internal static partial class CustomIndexes
{
// Fields inside JSON columns are indexed with JSON functions, the other columns must be scalar.
private static readonly HashSet<string> IndexableColumns =
[
nameof(EFContentEntity.Created),
nameof(EFContentEntity.CreatedBy),
nameof(EFContentEntity.Id),
nameof(EFContentEntity.IsDeleted),
nameof(EFContentEntity.LastModified),
nameof(EFContentEntity.LastModifiedBy),
nameof(EFContentEntity.NewStatus),
nameof(EFContentEntity.ScheduledAt),
nameof(EFContentEntity.Status),
nameof(EFContentEntity.Version),
];
[GeneratedRegex("^[a-zA-Z0-9_\\-]+(\\.[a-zA-Z0-9_\\-]+)*$")]
private static partial Regex FieldNameRegex();
public static async Task CreateCustomIndexAsync<T>(this ContentDbContext dbContext, IndexDefinition index,
CancellationToken ct) where T : EFContentEntity
{
var table = GetTableName<T>(dbContext);
var queryBuilder = dbContext.ContentQuery<T>();
var indexKeys = new List<SqlIndexKey>();
foreach (var field in index)
{
if (!FieldNameRegex().IsMatch(field.Name))
{
throw new DomainException($"Invalid index field '{field.Name}'.");
}
var fieldPath = queryBuilder.Visit(field.Name);
var fieldIsJson = queryBuilder.IsJsonPath(fieldPath);
if (!fieldIsJson && (fieldPath.Count > 1 || !IndexableColumns.Contains(fieldPath[0])))
{
throw new DomainException($"Field '{field.Name}' cannot be indexed.");
}
indexKeys.AddRange(dbContext.Dialect.IndexKeys(fieldPath, field.Order, fieldIsJson));
}
if (indexKeys.Count == 0)
{
throw new DomainException("Index does not contain a field.");
}
var indexName = GetIndexName(table, index.ToName());
var indexesExisting = await dbContext.Dialect.QueryIndexesAsync(dbContext, table, ct);
if (indexesExisting.Any(x => x.Name == indexName))
{
return;
}
foreach (var sql in dbContext.Dialect.CreateIndex(indexName, table, indexKeys, Describe(index)))
{
await dbContext.Database.ExecuteSqlRawAsync(sql, ct);
}
}
public static async Task<List<IndexDefinition>> GetCustomIndexesAsync<T>(this ContentDbContext dbContext,
CancellationToken ct) where T : EFContentEntity
{
var table = GetTableName<T>(dbContext);
var result = new List<IndexDefinition>();
foreach (var index in await dbContext.Dialect.QueryIndexesAsync(dbContext, table, ct))
{
if (!index.Name.StartsWith(GetIndexPrefix(table), StringComparison.Ordinal))
{
continue;
}
if (TryParse(index.Description, out var definition))
{
result.Add(definition);
}
}
return result;
}
public static async Task DropCustomIndexAsync<T>(this ContentDbContext dbContext, string name,
CancellationToken ct) where T : EFContentEntity
{
var table = GetTableName<T>(dbContext);
var indexName = GetIndexName(table, name);
var indexesExisting = await dbContext.Dialect.QueryIndexesAsync(dbContext, table, ct);
if (!indexesExisting.Any(x => x.Name == indexName))
{
return;
}
foreach (var sql in dbContext.Dialect.DropIndex(indexName, table))
{
await dbContext.Database.ExecuteSqlRawAsync(sql, ct);
}
}
private static string GetTableName<T>(DbContext dbContext)
{
return dbContext.Model.FindEntityType(typeof(T))?.GetTableName()
?? throw new InvalidOperationException("Unknown model.");
}
private static string GetIndexPrefix(string table)
{
return $"IX_{table}_cx_";
}
private static string GetIndexName(string table, string name)
{
// Index names are limited to 63 characters in Postgres, therefore the readable name is only stored as description.
var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(name)))[..16].ToLowerInvariant();
return $"{GetIndexPrefix(table)}{hash}";
}
private static string Describe(IndexDefinition index)
{
return string.Join(',', index.Select(x => $"{x.Name} {(x.Order == SortOrder.Ascending ? "asc" : "desc")}"));
}
private static bool TryParse(string? description, out IndexDefinition index)
{
index = [];
if (string.IsNullOrWhiteSpace(description))
{
return false;
}
foreach (var part in description.Split(','))
{
var partTokens = part.Split(' ');
if (partTokens.Length != 2)
{
return false;
}
var partOrder = partTokens[1] == "desc" ? SortOrder.Descending : SortOrder.Ascending;
index.Add(new IndexField(partTokens[0], partOrder));
}
return index.Count > 0;
}
}

18
backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository.cs

@ -136,24 +136,6 @@ public sealed partial class EFContentRepository<TContext, TContentContext>(
ct);
}
public Task CreateIndexAsync(DomainId appId, DomainId schemaId, IndexDefinition index,
CancellationToken ct = default)
{
return Task.CompletedTask;
}
public Task<List<IndexDefinition>> GetIndexesAsync(DomainId appId, DomainId schemaId,
CancellationToken ct = default)
{
return Task.FromResult<List<IndexDefinition>>([]);
}
public Task DropIndexAsync(DomainId appId, DomainId schemaId, string name,
CancellationToken ct = default)
{
return Task.CompletedTask;
}
private async Task<TContext> CreateDbContextAsync(
CancellationToken ct)
{

59
backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository_Indexes.cs

@ -0,0 +1,59 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Microsoft.EntityFrameworkCore;
using Squidex.Infrastructure;
using Squidex.Infrastructure.States;
#pragma warning disable MA0048 // File name must match type name
namespace Squidex.Domain.Apps.Entities.Contents;
public sealed partial class EFContentRepository<TContext, TContentContext>
{
public async Task CreateIndexAsync(DomainId appId, DomainId schemaId, IndexDefinition index,
CancellationToken ct = default)
{
// Custom indexes are only supported for dedicated tables, like the dedicated collections in MongoDB.
if (!dedicatedTables)
{
return;
}
await using var dbContext = await dynamicTables.CreateDbContextAsync(appId, schemaId, ct);
await dbContext.CreateCustomIndexAsync<EFContentCompleteEntity>(index, ct);
await dbContext.CreateCustomIndexAsync<EFContentPublishedEntity>(index, ct);
}
public async Task<List<IndexDefinition>> GetIndexesAsync(DomainId appId, DomainId schemaId,
CancellationToken ct = default)
{
if (!dedicatedTables)
{
return [];
}
await using var dbContext = await dynamicTables.CreateDbContextAsync(appId, schemaId, ct);
return await dbContext.GetCustomIndexesAsync<EFContentCompleteEntity>(ct);
}
public async Task DropIndexAsync(DomainId appId, DomainId schemaId, string name,
CancellationToken ct = default)
{
if (!dedicatedTables)
{
return;
}
await using var dbContext = await dynamicTables.CreateDbContextAsync(appId, schemaId, ct);
await dbContext.DropCustomIndexAsync<EFContentCompleteEntity>(name, ct);
await dbContext.DropCustomIndexAsync<EFContentPublishedEntity>(name, ct);
}
}

9
backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentRepository_SnapshotStore.cs

@ -185,7 +185,7 @@ public sealed partial class EFContentRepository<TContext, TContentContext> : ISn
// The existing entity is only valid if we use dedicated tables.
if (existing != null)
{
var contentDbContext = await dynamicTables.CreateDbContextAsync(existing.AppId.Id, existing.AppId.Id, ct);
var contentDbContext = await dynamicTables.CreateDbContextAsync(existing.AppId.Id, existing.SchemaId.Id, ct);
await RemoveCoreAsync(contentDbContext, key, ct);
}
@ -351,8 +351,11 @@ public sealed partial class EFContentRepository<TContext, TContentContext> : ISn
.Where(x => x.AppId.Id == bySchema.Key.AppId && x.SchemaId.Id == bySchema.Key.SchemaId)
.ToList();
await contentDbContext.BulkInsertAsync(bySchema.ToList(), ct);
await contentDbContext.BulkInsertAsync(publishedContents, ct);
// The bulk inserter caches the table names per context type and would ignore the prefix.
contentDbContext.AddRange(bySchema);
contentDbContext.AddRange(publishedContents);
await contentDbContext.SaveChangesAsync(ct);
}
}

4
backend/src/Squidex.Data.EntityFramework/Infrastructure/PooledDbNamedContextFactory.cs

@ -7,6 +7,7 @@
using System.Collections.Concurrent;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
#pragma warning disable EF1001 // Internal EF Core API usage.
@ -48,6 +49,9 @@ public sealed class PooledDbNamedContextFactory<TContext>(
builder.UsePoolSize(128);
builder.UsePrefix(name);
// All prefixes share the internal service provider, therefore the model must be cached per prefix.
builder.ReplaceService<IModelCacheKeyFactory, PrefixModelCacheKeyFactory>();
var pool = new DbContextPool<TContext>(builder.Options, serviceProvider);
return pool;
}

22
backend/src/Squidex.Data.EntityFramework/Infrastructure/PrefixModelCacheKeyFactory.cs

@ -0,0 +1,22 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace Squidex.Infrastructure;
public sealed class PrefixModelCacheKeyFactory : IModelCacheKeyFactory
{
public object Create(DbContext context, bool designTime)
{
// The table names depend on the prefix, therefore each prefix needs its own model.
var prefix = context.GetService<IDbContextOptions>().FindExtension<PrefixExtension>()?.Prefix;
return (context.GetType(), prefix, designTime);
}
}

26
backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlDialect.cs

@ -74,6 +74,27 @@ public class SqlDialect
return string.Empty;
}
public virtual IEnumerable<SqlIndexKey> IndexKeys(PropertyPath path, SortOrder order, bool isJson)
{
yield return new SqlIndexKey(FormatField(path, isJson), FormatOrder(order), isJson);
}
public virtual IEnumerable<string> CreateIndex(string name, string table, IReadOnlyList<SqlIndexKey> keys, string description)
{
throw new NotSupportedException();
}
public virtual IEnumerable<string> DropIndex(string name, string table)
{
throw new NotSupportedException();
}
public virtual Task<List<SqlIndexInfo>> QueryIndexesAsync(DbContext dbContext, string table,
CancellationToken ct)
{
throw new NotSupportedException();
}
public virtual string FormatLimitOffset(long limit, long offset, bool hasOrder)
{
var hasLimit = limit > 0 && limit < long.MaxValue;
@ -258,6 +279,11 @@ public class SqlDialect
return tableName;
}
protected static string FormatLiteral(string value)
{
return $"'{value.Replace("'", "''", StringComparison.Ordinal)}'";
}
protected virtual string FormatField(PropertyPath path, bool isJson)
{
if (isJson)

19
backend/src/Squidex.Data.EntityFramework/Infrastructure/Queries/SqlIndexKey.cs

@ -0,0 +1,19 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
#pragma warning disable MA0048 // File name must match type name
namespace Squidex.Infrastructure.Queries;
public sealed record SqlIndexKey(string Expression, string Order, bool IsExpression);
public sealed class SqlIndexInfo
{
public string Name { get; set; }
public string? Description { get; set; }
}

99
backend/src/Squidex.Data.EntityFramework/Migrations/RebuildDedicatedContentTables.cs

@ -0,0 +1,99 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Squidex.Domain.Apps.Entities.Contents;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Migrations;
namespace Squidex.Migrations;
public sealed class RebuildDedicatedContentTables<TContext, TContentContext>(
IDbContextFactory<TContext> dbContextFactory,
IDbContextNamedFactory<TContentContext> dbContentContextFactory,
IOptions<ContentsOptions> options,
ILogger<RebuildDedicatedContentTables<TContext, TContentContext>> log)
: IMigration
where TContext : DbContext where TContentContext : ContentDbContext
{
public const string Key = "RebuildDedicatedContentTables";
public async Task UpdateAsync(
CancellationToken ct)
{
if (!options.Value.OptimizeForSelfHosting)
{
return;
}
var dynamicTables = new DynamicTables<TContext, TContentContext>(dbContextFactory, dbContentContextFactory);
// All dedicated tables shared the model of the first table, therefore the contents are in the wrong tables.
var names = await dynamicTables.GetContextNames(ct).ToHashSetAsync(cancellationToken: ct);
await using (var dbContext = await dbContextFactory.CreateDbContextAsync(ct))
{
var schemas =
await dbContext.Set<EFContentCompleteEntity>()
.Select(x => new { x.IndexedAppId, x.IndexedSchemaId }).Distinct()
.ToListAsync(ct);
foreach (var schema in schemas)
{
names.Add(new DynamicContextName(schema.IndexedAppId, schema.IndexedSchemaId));
}
}
foreach (var name in names)
{
await using var contentContext = await dynamicTables.CreateDbContextAsync(name, ct);
await using var dbContext = await dbContextFactory.CreateDbContextAsync(ct);
await using var transaction = await contentContext.Database.BeginTransactionAsync(ct);
await RebuildAsync<EFContentCompleteEntity>(dbContext, contentContext, name, ct);
await RebuildAsync<EFContentPublishedEntity>(dbContext, contentContext, name, ct);
await transaction.CommitAsync(ct);
log.LogInformation("Rebuilt dedicated content tables for app {appId} and schema {schemaId}.", name.AppId, name.SchemaId);
}
}
private static async Task RebuildAsync<T>(DbContext dbContext, DbContext contentContext, DynamicContextName name,
CancellationToken ct) where T : EFContentEntity
{
await contentContext.Set<T>().ExecuteDeleteAsync(ct);
var sourceType = dbContext.Model.FindEntityType(typeof(T))!;
var sourceTable = StoreObjectIdentifier.Table(sourceType.GetTableName()!, sourceType.GetSchema());
var targetType = contentContext.Model.FindEntityType(typeof(T))!;
var targetTable = StoreObjectIdentifier.Table(targetType.GetTableName()!, targetType.GetSchema());
var sqlHelper = contentContext.GetService<ISqlGenerationHelper>();
// The column order can differ between the tables, therefore the columns are listed explicitly.
var sqlColumns = string.Join(", ", targetType.GetProperties().Select(x => sqlHelper.DelimitIdentifier(x.GetColumnName(targetTable)!)));
var sqlAppId = sqlHelper.DelimitIdentifier(sourceType.FindProperty(nameof(EFContentEntity.IndexedAppId))!.GetColumnName(sourceTable)!);
var sqlSchemaId = sqlHelper.DelimitIdentifier(sourceType.FindProperty(nameof(EFContentEntity.IndexedSchemaId))!.GetColumnName(sourceTable)!);
var sqlInsert = $$"""
INSERT INTO {{sqlHelper.DelimitIdentifier(targetTable.Name, targetTable.Schema)}} ({{sqlColumns}})
SELECT {{sqlColumns}}
FROM {{sqlHelper.DelimitIdentifier(sourceTable.Name, sourceTable.Schema)}}
WHERE {{sqlAppId}} = {0} AND {{sqlSchemaId}} = {1}
""";
await contentContext.Database.ExecuteSqlRawAsync(sqlInsert, [name.AppId.ToString(), name.SchemaId.ToString()], ct);
}
}

67
backend/src/Squidex.Data.EntityFramework/Providers/MySql/MySqlDialect.cs

@ -85,25 +85,74 @@ public sealed class MySqlDialect : SqlDialect
}
}
public override IEnumerable<string> CreateIndex(string name, string table, IReadOnlyList<SqlIndexKey> keys, string description)
{
var sqlColumns = string.Join(", ", keys.Select(x => x.IsExpression ? $"({x.Expression}) {x.Order}" : $"{x.Expression} {x.Order}"));
yield return $"CREATE INDEX {FormatTable(name)} ON {FormatTable(table)} ({sqlColumns}) COMMENT {FormatLiteral(description)};";
}
public override IEnumerable<string> DropIndex(string name, string table)
{
yield return $"DROP INDEX {FormatTable(name)} ON {FormatTable(table)};";
}
public override Task<List<SqlIndexInfo>> QueryIndexesAsync(DbContext dbContext, string table,
CancellationToken ct)
{
var sqlQuery = $"""
SELECT INDEX_NAME AS {nameof(SqlIndexInfo.Name)}, MAX(INDEX_COMMENT) AS {nameof(SqlIndexInfo.Description)}
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = {FormatLiteral(table)}
GROUP BY INDEX_NAME
""";
return dbContext.Database.SqlQueryRaw<SqlIndexInfo>(sqlQuery).ToListAsync(ct);
}
public override IEnumerable<SqlIndexKey> IndexKeys(PropertyPath path, SortOrder order, bool isJson)
{
if (isJson)
{
var sqlOrder = FormatOrder(order);
// Must match the expressions of the ORDER BY clause, otherwise the index is not used.
yield return new SqlIndexKey(SortNumber(path), sqlOrder, true);
yield return new SqlIndexKey(SortText(path), sqlOrder, true);
yield break;
}
foreach (var key in base.IndexKeys(path, order, isJson))
{
yield return key;
}
}
public override string OrderBy(PropertyPath path, SortOrder order, bool isJson)
{
if (isJson)
{
var sqlOrder = FormatOrder(order);
var sqlPath = path.JsonPath();
return $"""
IF (JSON_TYPE(JSON_EXTRACT({sqlPath})) IN ('INTEGER', 'DOUBLE', 'DECIMAL'),
CAST(JSON_VALUE({sqlPath}) AS DOUBLE),
NULL
) {sqlOrder},
JSON_VALUE({sqlPath}) {sqlOrder}
""";
return $"{SortNumber(path)} {sqlOrder}, {SortText(path)} {sqlOrder}";
}
return base.OrderBy(path, order, isJson);
}
private static string SortNumber(PropertyPath path)
{
var sqlPath = path.JsonPath();
return $"IF(JSON_TYPE(JSON_EXTRACT({sqlPath})) IN ('INTEGER', 'DOUBLE', 'DECIMAL'), CAST(JSON_VALUE({sqlPath}) AS DOUBLE), NULL)";
}
private static string SortText(PropertyPath path)
{
// Long texts would exceed the maximum size of index keys.
return $"LEFT(JSON_VALUE({path.JsonPath()}), 200)";
}
public override string WhereMatch(PropertyPath path, string query, SqlParams queryParameters)
{
return $"MATCH({FormatField(path, false)}) AGAINST({queryParameters.AddPositional(query)})";

59
backend/src/Squidex.Data.EntityFramework/Providers/Postgres/PostgresDialect.cs

@ -51,19 +51,74 @@ public class PostgresDialect : SqlDialect
return $"\"{tableName}\"";
}
public override IEnumerable<string> CreateIndex(string name, string table, IReadOnlyList<SqlIndexKey> keys, string description)
{
var sqlColumns = string.Join(", ", keys.Select(x => x.IsExpression ? $"({x.Expression}) {x.Order}" : $"{x.Expression} {x.Order}"));
yield return $"CREATE INDEX {FormatTable(name)} ON {FormatTable(table)} ({sqlColumns});";
yield return $"COMMENT ON INDEX {FormatTable(name)} IS {FormatLiteral(description)};";
}
public override IEnumerable<string> DropIndex(string name, string table)
{
yield return $"DROP INDEX IF EXISTS {FormatTable(name)};";
}
public override Task<List<SqlIndexInfo>> QueryIndexesAsync(DbContext dbContext, string table,
CancellationToken ct)
{
var sqlQuery = $"""
SELECT i.relname AS "{nameof(SqlIndexInfo.Name)}", obj_description(i.oid, 'pg_class') AS "{nameof(SqlIndexInfo.Description)}"
FROM pg_index x
JOIN pg_class i ON i.oid = x.indexrelid
JOIN pg_class t ON t.oid = x.indrelid
WHERE t.relname = {FormatLiteral(table)} AND t.relnamespace = current_schema()::regnamespace
""";
return dbContext.Database.SqlQueryRaw<SqlIndexInfo>(sqlQuery).ToListAsync(ct);
}
public override IEnumerable<SqlIndexKey> IndexKeys(PropertyPath path, SortOrder order, bool isJson)
{
if (isJson)
{
var sqlOrder = FormatOrder(order);
// Must match the expressions of the ORDER BY clause, otherwise the index is not used.
yield return new SqlIndexKey(SortNumber(path), $"{sqlOrder} NULLS LAST", true);
yield return new SqlIndexKey(SortText(path), sqlOrder, true);
yield break;
}
foreach (var key in base.IndexKeys(path, order, isJson))
{
yield return key;
}
}
public override string OrderBy(PropertyPath path, SortOrder order, bool isJson)
{
if (isJson)
{
var sqlOrder = FormatOrder(order);
var sqlPath = path.JsonPath(true);
return $"CASE WHEN jsonb_typeof({path.JsonPath(false)}) = 'number' THEN ({sqlPath})::numeric END {sqlOrder} NULLS LAST, {sqlPath} {sqlOrder}";
return $"{SortNumber(path)} {sqlOrder} NULLS LAST, {SortText(path)} {sqlOrder}";
}
return base.OrderBy(path, order, isJson);
}
private static string SortNumber(PropertyPath path)
{
return $"CASE WHEN jsonb_typeof({path.JsonPath(false)}) = 'number' THEN ({path.JsonPath(true)})::numeric END";
}
private static string SortText(PropertyPath path)
{
// Long texts would exceed the maximum size of btree index entries and the writes would fail.
return $"left({path.JsonPath(true)}, 200)";
}
public override string WhereMatch(PropertyPath path, string query, SqlParams queryParameters)
{
if (query.Contains(' ', StringComparison.OrdinalIgnoreCase))

83
backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/SqlServerDialect.cs

@ -67,19 +67,98 @@ public sealed class SqlServerDialect : SqlDialect
return $"[{tableName}]";
}
public override IEnumerable<string> CreateIndex(string name, string table, IReadOnlyList<SqlIndexKey> keys, string description)
{
// SQL Server cannot index expressions, therefore we have to create computed columns first.
var sqlComputed = keys.Select((x, i) => (Key: x, Column: $"{name}_{i}")).Where(x => x.Key.IsExpression).ToList();
if (sqlComputed.Count > 0)
{
yield return $"ALTER TABLE {FormatTable(table)} ADD {string.Join(", ", sqlComputed.Select(x => $"{FormatTable(x.Column)} AS ({x.Key.Expression})"))};";
}
var sqlColumns = string.Join(", ", keys.Select((x, i) => x.IsExpression ? $"{FormatTable($"{name}_{i}")} {x.Order}" : $"{x.Expression} {x.Order}"));
yield return $"CREATE INDEX {FormatTable(name)} ON {FormatTable(table)} ({sqlColumns});";
yield return $"""
DECLARE @schema sysname = SCHEMA_NAME();
EXEC sp_addextendedproperty
@name = N'squidex', @value = {FormatLiteral(description)},
@level0type = N'SCHEMA', @level0name = @schema,
@level1type = N'TABLE', @level1name = {FormatLiteral(table)},
@level2type = N'INDEX', @level2name = {FormatLiteral(name)};
""";
}
public override IEnumerable<string> DropIndex(string name, string table)
{
yield return $"DROP INDEX IF EXISTS {FormatTable(name)} ON {FormatTable(table)};";
yield return $"""
DECLARE @sql NVARCHAR(MAX) = N'';
SELECT @sql = @sql + N'ALTER TABLE {FormatTable(table)} DROP COLUMN ' + QUOTENAME(name) + N';'
FROM sys.computed_columns
WHERE object_id = OBJECT_ID({FormatLiteral(FormatTable(table))}) AND name LIKE {FormatLiteral($"{name}[_]%")};
EXEC sp_executesql @sql;
""";
}
public override Task<List<SqlIndexInfo>> QueryIndexesAsync(DbContext dbContext, string table,
CancellationToken ct)
{
var sqlQuery = $"""
SELECT i.name AS {nameof(SqlIndexInfo.Name)}, CAST(p.value AS NVARCHAR(4000)) AS {nameof(SqlIndexInfo.Description)}
FROM sys.indexes i
LEFT JOIN sys.extended_properties p ON p.class = 7 AND p.major_id = i.object_id AND p.minor_id = i.index_id AND p.name = N'squidex'
WHERE i.object_id = OBJECT_ID({FormatLiteral(FormatTable(table))}) AND i.name IS NOT NULL
""";
return dbContext.Database.SqlQueryRaw<SqlIndexInfo>(sqlQuery).ToListAsync(ct);
}
public override IEnumerable<SqlIndexKey> IndexKeys(PropertyPath path, SortOrder order, bool isJson)
{
if (isJson)
{
var sqlOrder = FormatOrder(order);
// Must match the expressions of the ORDER BY clause, otherwise the index is not used.
yield return new SqlIndexKey(SortNumber(path), sqlOrder, true);
yield return new SqlIndexKey(SortText(path), sqlOrder, true);
yield break;
}
foreach (var key in base.IndexKeys(path, order, isJson))
{
yield return key;
}
}
public override string OrderBy(PropertyPath path, SortOrder order, bool isJson)
{
if (isJson)
{
var sqlOrder = FormatOrder(order);
var sqlPath = path.JsonPath();
return $"IIF(ISNUMERIC(JSON_VALUE({sqlPath})) = 1, CAST(JSON_VALUE({sqlPath}) AS NUMERIC), NULL) {sqlOrder}, JSON_VALUE({sqlPath}) {sqlOrder}";
return $"{SortNumber(path)} {sqlOrder}, {SortText(path)} {sqlOrder}";
}
return base.OrderBy(path, order, isJson);
}
private static string SortNumber(PropertyPath path)
{
var sqlPath = path.JsonPath();
// Use TRY_CAST, because ISNUMERIC also accepts values like '$' that cannot be converted.
return $"IIF(ISNUMERIC(JSON_VALUE({sqlPath})) = 1, TRY_CAST(JSON_VALUE({sqlPath}) AS NUMERIC), NULL)";
}
private static string SortText(PropertyPath path)
{
// Long texts would exceed the maximum size of index keys and the writes would fail.
return $"CAST(JSON_VALUE({path.JsonPath()}) AS NVARCHAR(200))";
}
public override string WhereMatch(PropertyPath path, string query, SqlParams queryParameters)
{
if (query.Contains(' ', StringComparison.OrdinalIgnoreCase))

5
backend/src/Squidex.Data.EntityFramework/ServiceExtensions.cs

@ -48,6 +48,7 @@ using Squidex.Infrastructure;
using Squidex.Infrastructure.Caching;
using Squidex.Infrastructure.Log;
using Squidex.Infrastructure.Migrations;
using Squidex.Migrations;
using Squidex.Infrastructure.Queries;
using Squidex.Infrastructure.States;
using Squidex.Infrastructure.UsageTracking;
@ -218,6 +219,10 @@ public static class ServiceExtensions
services.AddSingletonAs<EFMigrationStatus<TContext>>()
.As<IMigrationStatus>();
// The migration path cannot reference the generic type, therefore it is resolved by key.
services.AddKeyedTransient<IMigration, RebuildDedicatedContentTables<TContext, TContextContext>>(
RebuildDedicatedContentTables<TContext, TContextContext>.Key);
services.AddSingletonAs<EFDistributedCache<TContext>>()
.As<IDistributedCache>();

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.5" />
<PackageReference Include="Squidex.Assets.EntityFramework" Version="8.0.5" />
<PackageReference Include="Squidex.Assets.TusAdapter" Version="8.0.5" />
<PackageReference Include="Squidex.Events.EntityFramework" Version="8.0.5" />
<PackageReference Include="Squidex.Flows.EntityFramework" Version="8.0.5" />
<PackageReference Include="Squidex.Hosting" Version="8.0.5" />
<PackageReference Include="Squidex.Messaging.EntityFramework" Version="8.0.5" />
<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.OpenIdDict.EntityFramework" Version="7.2.1" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
<PackageReference Include="System.ValueTuple" Version="4.6.2" />

39
backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Schemas/MongoSchemasHash.cs

@ -8,6 +8,7 @@
using MongoDB.Driver;
using Squidex.Domain.Apps.Core.Apps;
using Squidex.Domain.Apps.Events;
using Squidex.Domain.Apps.Events.Schemas;
using Squidex.Events;
using Squidex.Infrastructure;
using Squidex.Infrastructure.EventSourcing;
@ -44,18 +45,29 @@ public sealed class MongoSchemasHash(IMongoDatabase database) : MongoRepositoryB
continue;
}
if (@event.Payload is SchemaEvent schemaEvent)
if (@event.Payload is not SchemaEvent schemaEvent)
{
writes.Add(
new UpdateOneModel<MongoSchemasHashEntity>(
Filter.Eq(x => x.AppId, schemaEvent.AppId.Id),
Update
.Set($"s.{schemaEvent.SchemaId.Id}", @event.Headers.EventStreamNumber())
.Set(x => x.Updated, @event.Headers.TimestampAsInstant()))
{
IsUpsert = true,
});
continue;
}
var timestamp = @event.Headers.TimestampAsInstant();
var fieldName = $"s.{schemaEvent.SchemaId.Id}";
// Deleted schemas are not returned by the schema index, so they must not be part of the hash either.
var update = Update.Set(fieldName, @event.Headers.EventStreamNumber());
if (schemaEvent is SchemaDeleted)
{
update = Update.Unset(fieldName);
}
writes.Add(
new UpdateOneModel<MongoSchemasHashEntity>(
Filter.Eq(x => x.AppId, schemaEvent.AppId.Id),
update.Set(x => x.Updated, timestamp))
{
IsUpsert = true,
});
}
if (writes.Count == 0)
@ -63,7 +75,8 @@ public sealed class MongoSchemasHash(IMongoDatabase database) : MongoRepositoryB
return Task.CompletedTask;
}
return Collection.BulkWriteAsync(writes, BulkUnordered);
// The writes for the same app must be applied in order, for example a deletion after a creation.
return Collection.BulkWriteAsync(writes);
}
public async Task<SchemasHashKey> GetCurrentHashAsync(App app,
@ -74,7 +87,9 @@ public sealed class MongoSchemasHash(IMongoDatabase database) : MongoRepositoryB
var entity = await Collection.Find(x => x.AppId == app.Id).FirstOrDefaultAsync(ct);
if (entity == null)
{
return SchemasHashKey.Empty;
// Apps without schema events since a restore have no document. The app version must still be part of
// the key, otherwise app changes would not be detected.
return SchemasHashKey.Create(app, new Dictionary<DomainId, long>());
}
return SchemasHashKey.Create(

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.5" />
<PackageReference Include="Squidex.Assets.Mongo" Version="8.0.5" />
<PackageReference Include="Squidex.Events.Mongo" Version="8.0.5" />
<PackageReference Include="Squidex.Flows.Mongo" Version="8.0.5" />
<PackageReference Include="Squidex.Hosting" Version="8.0.5" />
<PackageReference Include="Squidex.Messaging.Mongo" Version="8.0.5" />
<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.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.5" />
<PackageReference Include="Squidex.Flows" Version="8.0.6" />
<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.5" />
<PackageReference Include="Squidex.Messaging.Subscriptions" Version="8.0.5" />
<PackageReference Include="Squidex.AI" Version="8.0.6" />
<PackageReference Include="Squidex.Messaging.Subscriptions" Version="8.0.6" />
<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" />

23
backend/src/Squidex.Domain.Apps.Entities/Contents/GraphQL/CachingGraphQLResolver.cs

@ -23,6 +23,7 @@ namespace Squidex.Domain.Apps.Entities.Contents.GraphQL;
public sealed class CachingGraphQLResolver(
IBackgroundCache cache,
ILocalCache localCache,
ISchemasHash schemasHash,
IServiceProvider serviceProvider,
IOptions<GraphQLOptions> options)
@ -43,8 +44,9 @@ public sealed class CachingGraphQLResolver(
{
var context = ((GraphQLExecutionContext)options.UserContext!).Context;
options.Schema = await GetSchemaAsync(context.App);
// Register the error handler first, so that errors when building the model are logged.
options.HandleError(serviceProvider);
options.Schema = await GetSchemaAsync(context.App);
return await next(options);
}
@ -60,7 +62,7 @@ public sealed class CachingGraphQLResolver(
{
if (options.CacheDuration <= TimeSpan.Zero)
{
return CreateModelAsync(app);
return CreateModelAsync(app, SchemasHashKey.Empty);
}
// The version is not part of the key. Building the schema is expensive and the version
@ -71,7 +73,17 @@ public sealed class CachingGraphQLResolver(
return cache.GetOrCreateAsync(cacheKey, options.CacheDuration, async entry =>
{
return await CreateModelAsync(app);
// Compare the hash with the same source in the validator. A key computed from the schemas would never
// match if the hash store is incomplete, for example for restored apps. The hash is read before the
// schemas, so a change in between only causes another rebuild.
var hashKey = await schemasHash.GetCurrentHashAsync(app);
// The model is shared between requests. Therefore it must not use schemas from the request-local
// cache, which might have been loaded with the cancellation token of another request.
using (localCache.StartContext())
{
return await CreateModelAsync(app, hashKey);
}
},
async entry =>
{
@ -81,11 +93,10 @@ public sealed class CachingGraphQLResolver(
});
}
private async Task<CacheEntry> CreateModelAsync(App app)
private async Task<CacheEntry> CreateModelAsync(App app, SchemasHashKey hashKey)
{
var schemasList = await serviceProvider.GetRequiredService<IAppProvider>().GetSchemasAsync(app.Id);
var schemasKey = SchemasHashKey.Create(app, schemasList);
return new CacheEntry(new Builder(app, options).BuildSchema(schemasList), schemasKey);
return new CacheEntry(new Builder(app, options).BuildSchema(schemasList), hashKey);
}
}

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.5" />
<PackageReference Include="Squidex.Caching" Version="8.0.5" />
<PackageReference Include="Squidex.Events" Version="8.0.5" />
<PackageReference Include="Squidex.Hosting.Abstractions" Version="8.0.5" />
<PackageReference Include="Squidex.Log" Version="8.0.5" />
<PackageReference Include="Squidex.Messaging" Version="8.0.5" />
<PackageReference Include="Squidex.Text" Version="8.0.5" />
<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="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.5" />
<PackageReference Include="Squidex.Assets.GoogleCloud" Version="8.0.5" />
<PackageReference Include="Squidex.Assets.FTP" Version="8.0.5" />
<PackageReference Include="Squidex.Assets.ImageSharp" Version="8.0.5" />
<PackageReference Include="Squidex.Assets.S3" Version="8.0.5" />
<PackageReference Include="Squidex.Assets.TusAdapter" Version="8.0.5" />
<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.ClientLibrary" Version="22.6.0" />
<PackageReference Include="Squidex.Hosting" Version="8.0.5" />
<PackageReference Include="Squidex.Messaging.All" Version="8.0.5" />
<PackageReference Include="Squidex.Messaging.Subscriptions" Version="8.0.5" />
<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="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.5" />
<PackageReference Include="Squidex.Assets.ImageMagick" Version="8.0.6" />
<PackageReference Include="Magick.NET-Q8-AnyCPU" Version="14.16.0" />
</ItemGroup>
<ItemGroup Condition="'$(IncludeKafka)' == 'true'">
<PackageReference Include="Squidex.Messaging.Kafka" Version="8.0.5" />
<PackageReference Include="Squidex.Messaging.Kafka" Version="8.0.6" />
</ItemGroup>
<PropertyGroup>

265
backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/EFContentRepositoryDedicatedTests.cs

@ -5,12 +5,23 @@
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Squidex.Domain.Apps.Core.Contents;
using Squidex.Domain.Apps.Entities;
using Squidex.Domain.Apps.Entities.Contents;
using Squidex.Domain.Apps.Entities.Contents.Repositories;
using Squidex.EntityFramework.TestHelpers;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Queries;
using Squidex.Infrastructure.States;
using Squidex.Migrations;
using Squidex.Providers.MySql;
using Squidex.Providers.Postgres;
using Squidex.Providers.SqlServer;
using Squidex.Shared;
namespace Squidex.EntityFramework.Domain.Contents;
@ -20,6 +31,13 @@ public abstract class EFContentRepositoryDedicatedTests<TContext, TContentContex
: ContentRepositoryTests
where TContext : DbContext, IDbContextWithDialect where TContentContext : ContentDbContext
{
private readonly IOptions<ContentsOptions> options = Options.Create(new ContentsOptions { OptimizeForSelfHosting = true });
private readonly NamedId<DomainId> appId = NamedId.Of(DomainId.NewGuid(), "my-app");
private readonly NamedId<DomainId> schemaId1 = NamedId.Of(DomainId.NewGuid(), "my-schema1");
private readonly NamedId<DomainId> schemaId2 = NamedId.Of(DomainId.NewGuid(), "my-schema2");
protected override bool SupportsCustomIndexes => true;
protected override Task<IContentRepository> CreateSutAsync()
{
var sut =
@ -27,8 +45,253 @@ public abstract class EFContentRepositoryDedicatedTests<TContext, TContentContex
fixture.DbContextFactory,
fixture.DbContextNamedFactory,
AppProvider,
Options.Create(new ContentsOptions { OptimizeForSelfHosting = true }));
options);
return Task.FromResult<IContentRepository>(sut);
}
[Fact]
public async Task Should_use_own_model_for_each_prefix()
{
await using var context1 = await fixture.DbContextNamedFactory.CreateDbContextAsync("__cTest1_");
await using var context2 = await fixture.DbContextNamedFactory.CreateDbContextAsync("__cTest2_");
var table1 = context1.Model.FindEntityType(typeof(EFContentCompleteEntity))!.GetTableName();
var table2 = context2.Model.FindEntityType(typeof(EFContentCompleteEntity))!.GetTableName();
Assert.Equal("__cTest1_ContentsAll", table1);
Assert.Equal("__cTest2_ContentsAll", table2);
}
[Fact]
public async Task Should_move_contents_into_correct_dedicated_tables()
{
var content1 = CreateWriteContent() with { Id = DomainId.NewGuid(), AppId = appId, SchemaId = schemaId1 };
var content2 = CreateWriteContent() with { Id = DomainId.NewGuid(), AppId = appId, SchemaId = schemaId2 };
var sut = await CreateSutAsync();
await ((ISnapshotStore<WriteContent>)sut).WriteManyAsync(
[
new SnapshotWriteJob<WriteContent>(content1.UniqueId, content1, 0),
new SnapshotWriteJob<WriteContent>(content2.UniqueId, content2, 0),
]);
// Simulate the old behavior, where all contents were written to the first dedicated table.
var dynamicTables = new DynamicTables<TContext, TContentContext>(fixture.DbContextFactory, fixture.DbContextNamedFactory);
await using (var context1 = await dynamicTables.CreateDbContextAsync(appId.Id, schemaId1.Id, default))
{
await using var context2 = await dynamicTables.CreateDbContextAsync(appId.Id, schemaId2.Id, default);
var misplaced = await context2.Set<EFContentCompleteEntity>().ToListAsync();
await context2.Set<EFContentCompleteEntity>().ExecuteDeleteAsync();
await context2.Set<EFContentPublishedEntity>().ExecuteDeleteAsync();
context1.AddRange(misplaced);
await context1.SaveChangesAsync();
}
var migration =
new RebuildDedicatedContentTables<TContext, TContentContext>(
fixture.DbContextFactory,
fixture.DbContextNamedFactory,
options,
NullLogger<RebuildDedicatedContentTables<TContext, TContentContext>>.Instance);
await migration.UpdateAsync(default);
var schema1 = Schema with { AppId = appId, Id = schemaId1.Id, Name = schemaId1.Name };
var schema2 = Schema with { AppId = appId, Id = schemaId2.Id, Name = schemaId2.Name };
var app = App with { Id = appId.Id, Name = appId.Name };
var result1All = await sut.QueryAsync(app, schema1, Q.Empty, SearchScope.All);
var result2All = await sut.QueryAsync(app, schema2, Q.Empty, SearchScope.All);
var result2Published = await sut.QueryAsync(app, schema2, Q.Empty, SearchScope.Published);
Assert.Equal([content1.Id], result1All.Select(x => x.Id).ToArray());
Assert.Equal([content2.Id], result2All.Select(x => x.Id).ToArray());
Assert.Equal([content2.Id], result2Published.Select(x => x.Id).ToArray());
}
[Theory]
[InlineData("data.field1.iv", SortOrder.Ascending)]
[InlineData("data.field1.iv", SortOrder.Descending)]
[InlineData("translationStatus.en", SortOrder.Ascending)]
[InlineData("lastModified", SortOrder.Descending)]
public async Task Should_sort_with_custom_index(string field, SortOrder order)
{
var index = new IndexDefinition
{
new IndexField(field, order),
};
var sut = await CreateSutAsync();
await sut.CreateIndexAsync(appId.Id, schemaId1.Id, index);
try
{
var dynamicTables = new DynamicTables<TContext, TContentContext>(fixture.DbContextFactory, fixture.DbContextNamedFactory);
await using var dbContext = await dynamicTables.CreateDbContextAsync(appId.Id, schemaId1.Id, default);
var table = GetTableName<EFContentCompleteEntity>(dbContext);
var indexesCustom = await GetCustomIndexNamesAsync(dbContext, table);
var indexName = Assert.Single(indexesCustom);
// Use the same query builder as the repository, otherwise the ORDER BY clause could be different.
var sqlQuery =
new ContentSqlQueryBuilder(dbContext.Dialect, table)
.Order(field, order)
.Limit(20)
.CompileQuery();
var (plan, sortMarker) = await ExplainAsync(dbContext, table, indexName, sqlQuery);
Assert.Contains(indexName, plan, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(sortMarker, plan, StringComparison.OrdinalIgnoreCase);
}
finally
{
await sut.DropIndexAsync(appId.Id, schemaId1.Id, index.ToName());
}
}
[Fact]
public async Task Should_create_and_drop_custom_index_in_all_and_published_table()
{
var sut = await CreateSutAsync();
await sut.CreateIndexAsync(appId.Id, schemaId1.Id, [new IndexField("data.field1.iv", SortOrder.Ascending)]);
var dynamicTables = new DynamicTables<TContext, TContentContext>(fixture.DbContextFactory, fixture.DbContextNamedFactory);
await using var dbContext = await dynamicTables.CreateDbContextAsync(appId.Id, schemaId1.Id, default);
var tableAll = GetTableName<EFContentCompleteEntity>(dbContext);
var tablePublished = GetTableName<EFContentPublishedEntity>(dbContext);
var createdAll = await GetCustomIndexNamesAsync(dbContext, tableAll);
var createdPublished = await GetCustomIndexNamesAsync(dbContext, tablePublished);
Assert.Single(createdAll);
Assert.Single(createdPublished);
await sut.DropIndexAsync(appId.Id, schemaId1.Id, "data.field1.iv_asc");
var droppedAll = await GetCustomIndexNamesAsync(dbContext, tableAll);
var droppedPublished = await GetCustomIndexNamesAsync(dbContext, tablePublished);
Assert.Empty(droppedAll);
Assert.Empty(droppedPublished);
}
private static string GetTableName<T>(DbContext dbContext)
{
return dbContext.Model.FindEntityType(typeof(T))!.GetTableName()!;
}
private static async Task<List<string>> GetCustomIndexNamesAsync(TContentContext dbContext, string table)
{
var indexes = await dbContext.Dialect.QueryIndexesAsync(dbContext, table, default);
return indexes.Select(x => x.Name).Where(x => x.StartsWith($"IX_{table}_cx_", StringComparison.Ordinal)).ToList();
}
private static async Task<(string Plan, string SortMarker)> ExplainAsync(TContentContext dbContext, string table, string indexName, string sqlQuery)
{
// The tables are almost empty, therefore the planners are pushed to the index. They can still sort, if the index does not match.
switch (dbContext.Dialect)
{
case PostgresDialect:
{
await using var transaction = await dbContext.Database.BeginTransactionAsync();
try
{
await dbContext.Database.ExecuteSqlRawAsync("SET LOCAL enable_sort = off;");
var plan = await ReadAllAsync(dbContext, $"EXPLAIN {sqlQuery}");
return (plan, "Sort");
}
finally
{
await transaction.RollbackAsync();
}
}
case MySqlDialect:
{
var sqlHinted = sqlQuery.Replace($"FROM `{table}`", $"FROM `{table}` FORCE INDEX (`{indexName}`)", StringComparison.Ordinal);
var plan = await ReadAllAsync(dbContext, $"EXPLAIN {sqlHinted}");
return (plan, "filesort");
}
case SqlServerDialect:
{
var sqlHinted = sqlQuery.Replace($"FROM [{table}]", $"FROM [{table}] WITH (INDEX([{indexName}]))", StringComparison.Ordinal);
await dbContext.Database.OpenConnectionAsync();
try
{
await ReadAllAsync(dbContext, "SET SHOWPLAN_XML ON;");
try
{
var plan = await ReadAllAsync(dbContext, sqlHinted);
return (plan, "PhysicalOp=\"Sort\"");
}
finally
{
await ReadAllAsync(dbContext, "SET SHOWPLAN_XML OFF;");
}
}
finally
{
await dbContext.Database.CloseConnectionAsync();
}
}
default:
throw new NotSupportedException();
}
}
private static async Task<string> ReadAllAsync(DbContext dbContext, string sql)
{
await dbContext.Database.OpenConnectionAsync();
try
{
await using var command = dbContext.Database.GetDbConnection().CreateCommand();
command.CommandText = sql;
command.Transaction = dbContext.Database.CurrentTransaction?.GetDbTransaction();
await using var reader = await command.ExecuteReaderAsync();
var result = new StringBuilder();
do
{
while (await reader.ReadAsync())
{
for (var i = 0; i < reader.FieldCount; i++)
{
result.AppendLine(reader.GetValue(i)?.ToString());
}
}
}
while (await reader.NextResultAsync());
return result.ToString();
}
finally
{
await dbContext.Database.CloseConnectionAsync();
}
}
}

29
backend/tests/Squidex.Data.Tests/EntityFramework/Domain/Contents/EFContentRepositoryTests.cs

@ -11,6 +11,8 @@ using Squidex.Domain.Apps.Entities.Contents;
using Squidex.Domain.Apps.Entities.Contents.Repositories;
using Squidex.EntityFramework.TestHelpers;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Queries;
using Squidex.Infrastructure.States;
using Squidex.Shared;
namespace Squidex.EntityFramework.Domain.Contents;
@ -19,6 +21,9 @@ public abstract class EFContentRepositoryTests<TContext, TContentContext>(ISqlCo
: ContentRepositoryTests
where TContext : DbContext, IDbContextWithDialect where TContentContext : ContentDbContext
{
private readonly NamedId<DomainId> appId = NamedId.Of(DomainId.NewGuid(), "my-app");
private readonly NamedId<DomainId> schemaId = NamedId.Of(DomainId.NewGuid(), "my-schema1");
protected override Task<IContentRepository> CreateSutAsync()
{
var sut =
@ -30,4 +35,28 @@ public abstract class EFContentRepositoryTests<TContext, TContentContext>(ISqlCo
return Task.FromResult<IContentRepository>(sut);
}
[Fact]
public async Task Should_ignore_custom_indexes_without_dedicated_tables()
{
var index = new IndexDefinition
{
new IndexField("data.field1.iv", SortOrder.Ascending),
};
var sut = await CreateSutAsync();
await sut.CreateIndexAsync(appId.Id, schemaId.Id, index);
try
{
var indexesCreated = await sut.GetIndexesAsync(appId.Id, schemaId.Id);
// Custom indexes would apply to the contents of all schemas in the shared table.
Assert.Empty(indexesCreated);
}
finally
{
await sut.DropIndexAsync(appId.Id, schemaId.Id, index.ToName());
}
}
}

42
backend/tests/Squidex.Data.Tests/MongoDb/Domain/Schemas/MongoSchemasHashTests.cs

@ -62,4 +62,46 @@ public class MongoSchemasHashTests(MongoFixture fixture) : GivenContext, IAsyncL
Assert.NotEmpty(hashKey);
Assert.Equal(hashKey.Timestamp, timestamp);
}
[Fact]
public async Task Should_remove_deleted_schemas_from_hash()
{
var schema1 = Schema.WithId(DomainId.NewGuid(), "my-schema1");
var schema2 = Schema.WithId(DomainId.NewGuid(), "my-schema2");
var timestamp = SystemClock.Instance.GetCurrentInstant().WithoutMs();
await sut.On(
[
Envelope.Create<IEvent>(new SchemaCreated
{
AppId = AppId,
SchemaId = schema1.NamedId(),
}).SetEventStreamNumber(schema1.Version).SetTimestamp(timestamp),
Envelope.Create<IEvent>(new SchemaCreated
{
AppId = AppId,
SchemaId = schema2.NamedId(),
}).SetEventStreamNumber(schema2.Version).SetTimestamp(timestamp),
Envelope.Create<IEvent>(new SchemaDeleted
{
AppId = AppId,
SchemaId = schema2.NamedId(),
}).SetEventStreamNumber(schema2.Version + 1).SetTimestamp(timestamp),
]);
var hashKey = await sut.GetCurrentHashAsync(App, CancellationToken);
Assert.Equal(SchemasHashKey.Create(App, [schema1]), hashKey);
}
[Fact]
public async Task Should_include_app_version_if_app_has_no_hash()
{
var hashKey = await sut.GetCurrentHashAsync(App, CancellationToken);
Assert.Equal(SchemasHashKey.Create(App, Array.Empty<Schema>()), hashKey);
}
}

338
backend/tests/Squidex.Data.Tests/Shared/ContentRepositoryTests.cs

@ -85,96 +85,7 @@ public abstract class ContentRepositoryTests : GivenContext
protected abstract Task<IContentRepository> CreateSutAsync();
private async Task<IContentRepository> CreateAndPrepareSutAsync(params WriteContent[] contents)
{
var sut = await CreateSutAsync();
if (sut is not ISnapshotStore<WriteContent> store)
{
return sut;
}
// Write the contents of the test itself, because the shared contents are only written once.
await WriteAsync(store, contents);
if (await sut.StreamAll(AppIds[0].Id, [schema.Id], SearchScope.All).AnyAsync())
{
return sut;
}
var batch = new List<SnapshotWriteJob<WriteContent>>();
async Task ExecuteBatchAsync(WriteContent? state)
{
if (state != null)
{
batch.Add(new SnapshotWriteJob<WriteContent>(state.UniqueId, state, 0));
}
if ((state == null || batch.Count >= 1000) && batch.Count > 0)
{
await store.WriteManyAsync(batch, default);
batch.Clear();
}
}
foreach (var forAppId in AppIds)
{
foreach (var forSchemaId in SchemaIds)
{
var previousIds = new List<DomainId>();
for (var i = 0; i < NumValues; i++)
{
var contentId = DomainId.NewGuid();
if (i == 0)
{
previousIds = [contentId];
}
var content = CreateWriteContent() with
{
Id = contentId,
CurrentVersion = new ContentVersion(
Status.Published,
new ContentData()
.AddField("field1",
new ContentFieldData()
.AddInvariant(JsonValue.Create(i)))
.AddField("field2",
new ContentFieldData()
.AddInvariant(JsonValue.Create(Lorem.Paragraph(200, 20))))
.AddField("references",
new ContentFieldData()
.AddInvariant(
JsonValue.Array(previousIds.ToArray())))),
SchemaId = forSchemaId,
ScheduleJob =
i > NumValues / 2
? new ScheduleJob(DomainId.NewGuid(), Status.Archived, User, now.Plus(Duration.FromDays(i)))
: null,
AppId = forAppId,
};
await ExecuteBatchAsync(content);
}
}
}
await ExecuteBatchAsync(null);
return sut;
}
private static async Task WriteAsync(ISnapshotStore<WriteContent> store, WriteContent[] contents)
{
if (contents.Length == 0)
{
return;
}
await store.WriteManyAsync(contents.Select(x => new SnapshotWriteJob<WriteContent>(x.UniqueId, x, 0)).ToList(), default);
}
protected virtual bool SupportsCustomIndexes => false;
[Fact]
public async Task Should_find_by_id()
@ -398,6 +309,21 @@ public abstract class ContentRepositoryTests : GivenContext
Assert.Single(contents);
}
[Fact]
public async Task Should_query_by_translation_status()
{
var query = new ClrQuery
{
Filter = ClrFilter.Eq("translationStatus.en", 100),
Sort = [new SortNode("translationStatus.en", SortOrder.Ascending)],
};
var contents = await QueryAsync(query, 1000, 0);
// The schema has no localized fields, therefore all contents are fully translated.
Assert.Equal(NumValues, contents.Count);
}
[Fact]
public async Task Should_query_scheduled()
{
@ -722,6 +648,238 @@ public abstract class ContentRepositoryTests : GivenContext
Assert.Empty(scheduled);
}
[Fact]
public async Task Should_create_get_and_drop_custom_index()
{
if (!SupportsCustomIndexes)
{
return;
}
var (otherApp, otherSchema) = CreateOtherApp();
var index = new IndexDefinition
{
new IndexField("data.field1.iv", SortOrder.Ascending),
new IndexField("translationStatus.en", SortOrder.Ascending),
new IndexField("lastModified", SortOrder.Descending),
};
var sut = await CreateAndPrepareSutAsync();
await sut.CreateIndexAsync(otherApp.Id, otherSchema.Id, index);
// Creating the same index twice must not fail.
await sut.CreateIndexAsync(otherApp.Id, otherSchema.Id, index);
var created = await sut.GetIndexesAsync(otherApp.Id, otherSchema.Id);
created.Should().BeEquivalentTo([index]);
await sut.DropIndexAsync(otherApp.Id, otherSchema.Id, index.ToName());
var dropped = await sut.GetIndexesAsync(otherApp.Id, otherSchema.Id);
Assert.Empty(dropped);
}
[Fact]
public async Task Should_not_fail_to_drop_unknown_custom_index()
{
if (!SupportsCustomIndexes)
{
return;
}
var (otherApp, otherSchema) = CreateOtherApp();
var sut = await CreateAndPrepareSutAsync();
await sut.DropIndexAsync(otherApp.Id, otherSchema.Id, "data.unknown.iv_asc");
var indexes = await sut.GetIndexesAsync(otherApp.Id, otherSchema.Id);
Assert.Empty(indexes);
}
[Fact]
public async Task Should_write_and_sort_contents_with_custom_index()
{
if (!SupportsCustomIndexes)
{
return;
}
var (otherApp, otherSchema) = CreateOtherApp();
var index = new IndexDefinition
{
new IndexField("data.field1.iv", SortOrder.Descending),
new IndexField("data.field2.iv", SortOrder.Ascending),
};
var sut = await CreateAndPrepareSutAsync();
await sut.CreateIndexAsync(otherApp.Id, otherSchema.Id, index);
try
{
// Long texts and values that look like numbers must not break the writes.
var contents = new[]
{
CreateContent(otherApp, Status.Published, 1, new string('a', 5000)),
CreateContent(otherApp, Status.Published, 3, "$"),
CreateContent(otherApp, Status.Published, 2, "1e400"),
};
await WriteAsync((ISnapshotStore<WriteContent>)sut, contents);
var query = new ClrQuery
{
Sort = [new SortNode("data.field1.iv", SortOrder.Descending)],
};
var result = await sut.QueryAsync(otherApp, otherSchema, Q.Empty.WithQuery(query), SearchScope.All);
Assert.Equal([contents[1].Id, contents[2].Id, contents[0].Id], result.Select(x => x.Id).ToArray());
}
finally
{
await sut.DropIndexAsync(otherApp.Id, otherSchema.Id, index.ToName());
}
}
[Fact]
public async Task Should_not_create_custom_index_for_invalid_field()
{
if (!SupportsCustomIndexes)
{
return;
}
var (otherApp, otherSchema) = CreateOtherApp();
var sut = await CreateAndPrepareSutAsync();
foreach (var field in new[] { "data.field1'; DROP TABLE x; --", "newData", "lastModified.x" })
{
var index = new IndexDefinition
{
new IndexField(field, SortOrder.Ascending),
};
await Assert.ThrowsAsync<DomainException>(() => sut.CreateIndexAsync(otherApp.Id, otherSchema.Id, index));
}
}
private async Task<IContentRepository> CreateAndPrepareSutAsync(params WriteContent[] contents)
{
var sut = await CreateSutAsync();
if (sut is not ISnapshotStore<WriteContent> store)
{
return sut;
}
// Write the contents of the test itself, because the shared contents are only written once.
await WriteAsync(store, contents);
if (await sut.StreamAll(AppIds[0].Id, [schema.Id], SearchScope.All).AnyAsync())
{
return sut;
}
var batch = new List<SnapshotWriteJob<WriteContent>>();
async Task ExecuteBatchAsync(WriteContent? state)
{
if (state != null)
{
batch.Add(new SnapshotWriteJob<WriteContent>(state.UniqueId, state, 0));
}
if ((state == null || batch.Count >= 1000) && batch.Count > 0)
{
await store.WriteManyAsync(batch, default);
batch.Clear();
}
}
foreach (var forAppId in AppIds)
{
foreach (var forSchemaId in SchemaIds)
{
var previousIds = new List<DomainId>();
for (var i = 0; i < NumValues; i++)
{
var contentId = DomainId.NewGuid();
if (i == 0)
{
previousIds = [contentId];
}
var content = CreateWriteContent() with
{
Id = contentId,
CurrentVersion = new ContentVersion(
Status.Published,
new ContentData()
.AddField("field1",
new ContentFieldData()
.AddInvariant(JsonValue.Create(i)))
.AddField("field2",
new ContentFieldData()
.AddInvariant(JsonValue.Create(Lorem.Paragraph(200, 20))))
.AddField("references",
new ContentFieldData()
.AddInvariant(
JsonValue.Array(previousIds.ToArray())))),
SchemaId = forSchemaId,
ScheduleJob =
i > NumValues / 2
? new ScheduleJob(DomainId.NewGuid(), Status.Archived, User, now.Plus(Duration.FromDays(i)))
: null,
AppId = forAppId,
};
await ExecuteBatchAsync(content);
}
}
}
await ExecuteBatchAsync(null);
return sut;
}
private static async Task WriteAsync(ISnapshotStore<WriteContent> store, WriteContent[] contents)
{
if (contents.Length == 0)
{
return;
}
await store.WriteManyAsync(contents.Select(x => new SnapshotWriteJob<WriteContent>(x.UniqueId, x, 0)).ToList(), default);
}
private WriteContent CreateContent(App forApp, Status status, int number, string text)
{
var content = CreateContent(forApp, status);
return content with
{
CurrentVersion = new ContentVersion(
status,
new ContentData()
.AddField("field1",
new ContentFieldData()
.AddInvariant(JsonValue.Create(number)))
.AddField("field2",
new ContentFieldData()
.AddInvariant(JsonValue.Create(text)))),
};
}
private (App, Schema) CreateOtherApp()
{
// Use another app to not change the results of the other tests.

120
backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/GraphQL/CachingGraphQLResolverTests.cs

@ -0,0 +1,120 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using GraphQL;
using GraphQL.Execution;
using GraphQL.Validation;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Squidex.Caching;
using Squidex.Domain.Apps.Core.TestHelpers;
using Squidex.Domain.Apps.Entities.Apps.Indexes;
using Squidex.Domain.Apps.Entities.Contents.TestData;
using Squidex.Domain.Apps.Entities.Rules.Indexes;
using Squidex.Domain.Apps.Entities.Schemas;
using Squidex.Domain.Apps.Entities.Schemas.Indexes;
using Squidex.Domain.Apps.Entities.Teams.Indexes;
using Squidex.Infrastructure;
namespace Squidex.Domain.Apps.Entities.Contents.GraphQL;
public class CachingGraphQLResolverTests : GraphQLTestBase
{
[Fact]
public async Task Should_not_use_schemas_from_request_cache_to_build_model()
{
using var cts = new CancellationTokenSource();
await cts.CancelAsync();
var schemasIndex = A.Fake<ISchemasIndex>();
A.CallTo(() => schemasIndex.GetSchemasAsync(TestApp.Default.Id, cts.Token))
.ThrowsAsync(new OperationCanceledException(cts.Token));
A.CallTo(() => schemasIndex.GetSchemasAsync(TestApp.Default.Id, default))
.Returns([TestSchemas.Default]);
var localCache = new AsyncLocalCache();
var appProvider = new AppProvider(
A.Fake<IAppsIndex>(),
A.Fake<IRulesIndex>(),
schemasIndex,
A.Fake<ITeamsIndex>(),
localCache);
var sut = CreateSut(appProvider);
using (localCache.StartContext())
{
// The request has loaded the schemas with its own token, but has been canceled.
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => appProvider.GetSchemasAsync(TestApp.Default.Id, cts.Token));
var model = await sut.GetSchemaAsync(TestApp.Default);
Assert.NotNull(model);
}
}
[Fact]
public async Task Should_not_rebuild_model_if_hash_has_not_changed()
{
var appProvider = A.Fake<IAppProvider>();
A.CallTo(() => appProvider.GetSchemasAsync(TestApp.Default.Id, default))
.Returns([TestSchemas.Default]);
// The hash store does not know the schema, for example after a restore.
var hashKey = SchemasHashKey.Create(TestApp.Default, new Dictionary<DomainId, long>());
var schemasHash = A.Fake<ISchemasHash>();
A.CallTo(() => schemasHash.GetCurrentHashAsync(TestApp.Default, default))
.Returns(hashKey);
var sut = CreateSut(appProvider, schemasHash);
await sut.GetSchemaAsync(TestApp.Default);
await sut.GetSchemaAsync(TestApp.Default);
// Wait for the validation in the background.
await Task.Delay(500);
await sut.GetSchemaAsync(TestApp.Default);
A.CallTo(() => appProvider.GetSchemasAsync(TestApp.Default.Id, default))
.MustHaveHappenedOnceExactly();
}
[Fact]
public async Task Should_log_error_if_model_cannot_be_created()
{
var appProvider = A.Fake<IAppProvider>();
A.CallTo(() => appProvider.GetSchemasAsync(TestApp.Default.Id, default))
.ThrowsAsync(new InvalidOperationException());
var sut = CreateSut(appProvider);
var options = new TestQuery { Query = "{ __typename }" }.ToOptions(sut.Services);
var executer = new DocumentExecuter(
new GraphQLDocumentBuilder(),
new DocumentValidator(),
new DefaultExecutionStrategySelector(),
[sut]);
var result = await executer.ExecuteAsync(options);
Assert.NotEmpty(result.Errors!);
var loggerFactory = sut.Services.GetRequiredService<ILoggerFactory>();
A.CallTo(() => loggerFactory.CreateLogger("GraphQL"))
.MustHaveHappened();
}
}

8
backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/GraphQL/GraphQLTestBase.cs

@ -116,6 +116,11 @@ public abstract class GraphQLTestBase : IClassFixture<TranslationsFixture>
A.CallTo(() => appProvider.GetSchemasAsync(TestApp.Default.Id, default))
.Returns(schemas.ToList());
return CreateSut(appProvider);
}
protected CachingGraphQLResolver CreateSut(IAppProvider appProvider, ISchemasHash? schemasHash = null)
{
var serviceProvider =
new ServiceCollection()
.AddSingleton(TimeProvider.System)
@ -145,9 +150,10 @@ public abstract class GraphQLTestBase : IClassFixture<TranslationsFixture>
.AddSingleton(
A.Fake<ILoggerFactory>())
.AddSingleton(
A.Fake<ISchemasHash>())
schemasHash ?? A.Fake<ISchemasHash>())
.AddMemoryCache()
.AddBackgroundCache()
.AddAsyncLocalCache()
.AddSingleton(appProvider)
.AddSingleton(assetQuery)
.AddSingleton(commandBus)

37
backend/tests/Squidex.Domain.Apps.Entities.Tests/Extensions/Kafka/KafkaProducerTests.cs

@ -0,0 +1,37 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
#if INCLUDE_KAFKA
using Squidex.Extensions.Actions.Kafka;
namespace Squidex.Domain.Apps.Entities.Extensions.Kafka;
public class KafkaProducerTests
{
[Theory]
[InlineData("key1", 12, 5)]
[InlineData("key2", 12, 5)]
[InlineData("key3", 12, 1)]
public void Should_calculate_stable_partition(string partitionKey, int partitionCount, int expected)
{
var partition = KafkaProducer.GetPartition(partitionKey, partitionCount);
Assert.Equal(expected, partition);
}
[Fact]
public void Should_calculate_partition_in_range()
{
for (var i = 0; i < 1000; i++)
{
var partition = KafkaProducer.GetPartition($"key{i}", 7);
Assert.InRange(partition, 0, 6);
}
}
}
#endif

56
tools/TestSuite/TestSuite.ApiTests/AssetFormatTests.cs

@ -59,7 +59,7 @@ public class AssetFormatTests(CreatedAppFixture fixture) : IClassFixture<Created
{
var asset = await _.Client.Assets.UploadFileAsync("Assets/SampleImage_62kb.jpg", "image/jpeg");
await AssertImageAsync(asset);
await AssertImageAsync(asset, isReencoded: true);
Assert.Equal(79L, asset.Metadata["imageQuality"]);
}
@ -77,7 +77,7 @@ public class AssetFormatTests(CreatedAppFixture fixture) : IClassFixture<Created
{
var asset = await _.Client.Assets.UploadFileAsync("Assets/SampleImage_400kb.tiff", "image/jpeg");
await AssertImageAsync(asset);
await AssertImageAsync(asset, isReencoded: true);
}
[Fact]
@ -128,23 +128,6 @@ public class AssetFormatTests(CreatedAppFixture fixture) : IClassFixture<Created
}
}
private async Task AssertImageAsync(AssetDto asset)
{
await Verify(asset);
// Should parse image metadata.
Assert.True(asset.IsImage);
Assert.Equal(600L, (long)asset.PixelWidth!);
Assert.Equal(600L, asset.Metadata["pixelWidth"]);
Assert.Equal(400L, (long)asset.PixelHeight!);
Assert.Equal(400L, asset.Metadata["pixelHeight"]);
Assert.Equal(AssetType.Image, asset.Type);
var resized = await GetResizedLengthAsync(asset.Id, 100, 100);
Assert.True(resized < asset.FileSize * .25);
}
[Fact]
public async Task Should_fix_orientation()
{
@ -159,7 +142,7 @@ public class AssetFormatTests(CreatedAppFixture fixture) : IClassFixture<Created
Assert.Equal(79L, asset.Metadata["imageQuality"]);
Assert.Equal(AssetType.Image, asset.Type);
await Verify(asset);
await VerifyReencoded(asset);
}
[Fact]
@ -220,6 +203,39 @@ public class AssetFormatTests(CreatedAppFixture fixture) : IClassFixture<Created
await Verify(asset);
}
private async Task AssertImageAsync(AssetDto asset, bool isReencoded = false)
{
if (isReencoded)
{
await VerifyReencoded(asset);
}
else
{
await Verify(asset);
}
// Should parse image metadata.
Assert.True(asset.IsImage);
Assert.Equal(600L, (long)asset.PixelWidth!);
Assert.Equal(600L, asset.Metadata["pixelWidth"]);
Assert.Equal(400L, (long)asset.PixelHeight!);
Assert.Equal(400L, asset.Metadata["pixelHeight"]);
Assert.Equal(AssetType.Image, asset.Type);
var resized = await GetResizedLengthAsync(asset.Id, 100, 100);
Assert.True(resized < asset.FileSize * .25);
}
private static SettingsTask VerifyReencoded(AssetDto asset)
{
// The JPEG encoder produces slightly different bytes on each platform.
return Verify(asset)
.ScrubMember<AssetDto>(x => x.FileHash)
.ScrubMember<AssetDto>(x => x.FileSize)
.ScrubMember<AssetDto>(x => x.MetadataText);
}
private async Task<long> GetResizedLengthAsync(string imageId, int width, int height)
{
var url = $"{_.Client.GenerateImageUrl(imageId)}?width={width}&height={height}";

4
tools/TestSuite/TestSuite.ApiTests/TestSuite.ApiTests.csproj

@ -17,8 +17,8 @@
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
<PackageReference Include="ModelContextProtocol.Core" Version="2.3.0" />
<PackageReference Include="NSwag.Core" Version="14.6.3" />
<PackageReference Include="Squidex.Assets" Version="8.0.5" />
<PackageReference Include="Squidex.Assets.ImageSharp" Version="8.0.5" />
<PackageReference Include="Squidex.Assets" Version="8.0.6" />
<PackageReference Include="Squidex.Assets.ImageSharp" Version="8.0.6" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
<PackageReference Include="Verify.XunitV3" Version="28.12.0" />
<PackageReference Include="xunit.v3" Version="3.2.2" />

6
tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_fix_orientation.verified.txt

@ -2,12 +2,12 @@
Id: Guid_1,
ParentId: Guid_Empty,
FileName: logo-wide-rotated.jpg,
FileHash: XFoH3mp4QW9EIWjF50vJkm8IwnrjjO+ZiqV2GnH1GGw=,
FileHash: {Scrubbed},
IsProtected: false,
Slug: logo-wide-rotated.jpg,
MimeType: image/jpeg,
FileType: jpg,
MetadataText: 600x135px, 15.2 kB,
MetadataText: {Scrubbed},
EditToken: {Scrubbed},
Metadata: {
description: JFIF File,
@ -20,7 +20,7 @@
image,
image/medium
],
FileSize: 15598,
FileSize: {Scrubbed},
Type: Image,
CreatedBy: {Scrubbed},
LastModifiedBy: {Scrubbed},

6
tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_upload_image_jpg_and_resize.verified.txt

@ -2,12 +2,12 @@
Id: Guid_1,
ParentId: Guid_Empty,
FileName: SampleImage_62kb.jpg,
FileHash: ss/g3yq5dO3jYbWzJ9j2psJo1Nrk5TjSi78LJfCma38=,
FileHash: {Scrubbed},
IsProtected: false,
Slug: sampleimage-62kb.jpg,
MimeType: image/jpeg,
FileType: jpg,
MetadataText: 600x400px, 59.2 kB,
MetadataText: {Scrubbed},
EditToken: {Scrubbed},
Metadata: {
description: JFIF File,
@ -20,7 +20,7 @@
image,
image/medium
],
FileSize: 60603,
FileSize: {Scrubbed},
Type: Image,
CreatedBy: {Scrubbed},
LastModifiedBy: {Scrubbed},

6
tools/TestSuite/TestSuite.ApiTests/Verify/AssetFormatTests.Should_upload_image_tiff_and_resize.verified.txt

@ -2,12 +2,12 @@
Id: Guid_1,
ParentId: Guid_Empty,
FileName: SampleImage_400kb.tiff,
FileHash: f+ZdTDOoK23jmThbfPhWhXL8Q9+KIQajHeFfT/MtWFU=,
FileHash: {Scrubbed},
IsProtected: false,
Slug: sampleimage-400kb.tiff,
MimeType: image/jpeg,
FileType: tiff,
MetadataText: 600x400px, 473.6 kB,
MetadataText: {Scrubbed},
EditToken: {Scrubbed},
Metadata: {
description: TIFF File,
@ -19,7 +19,7 @@
image,
image/medium
],
FileSize: 485012,
FileSize: {Scrubbed},
Type: Image,
CreatedBy: {Scrubbed},
LastModifiedBy: {Scrubbed},

2
tools/TestSuite/TestSuite.Shared/TestSuite.Shared.csproj

@ -17,7 +17,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="10.0.5" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="10.0.5" />
<PackageReference Include="RefactoringEssentials" Version="5.6.0" PrivateAssets="all" />
<PackageReference Include="Squidex.Assets" Version="8.0.5" />
<PackageReference Include="Squidex.Assets" Version="8.0.6" />
<PackageReference Include="Squidex.ClientLibrary" Version="22.6.0" />
<PackageReference Include="Squidex.ClientLibrary.ServiceExtensions" Version="22.6.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />

2
tools/TestSuite/docker-compose.yml

@ -80,7 +80,7 @@ services:
restart: unless-stopped
resizer:
image: squidex/resizer:1.3.0
image: squidex/resizer:1.7.0
webhookcatcher:
image: tarampampam/webhook-tester:2

Loading…
Cancel
Save