Browse Source

Migration job (#1332)

* Migration job.

* The tests

* Fix
pull/1334/head
Sebastian Stehle 2 months ago
committed by GitHub
parent
commit
b62edb1cf4
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 3
      CLAUDE.md
  2. 7
      backend/i18n/frontend_de.json
  3. 7
      backend/i18n/frontend_en.json
  4. 7
      backend/i18n/frontend_fr.json
  5. 7
      backend/i18n/frontend_it.json
  6. 7
      backend/i18n/frontend_nl.json
  7. 7
      backend/i18n/frontend_pt.json
  8. 7
      backend/i18n/frontend_zh.json
  9. 7
      backend/i18n/source/frontend_en.json
  10. 202
      backend/src/Squidex.Domain.Apps.Entities/Contents/Migration/MigrateContentsJob.cs
  11. 1
      backend/src/Squidex.Shared/PermissionIds.cs
  12. 2
      backend/src/Squidex.Web/Resources.cs
  13. 6
      backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/SchemaDto.cs
  14. 49
      backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemaContentsController.cs
  15. 4
      backend/src/Squidex/Config/Messaging/MessagingServices.cs
  16. 255
      backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Migration/MigrateContentsJobTests.cs
  17. 22
      frontend/generator/Generator.sln
  18. 3
      frontend/generator/Generator.slnx
  19. 71
      frontend/generator/Generator/cache.json
  20. 20
      frontend/src/app/features/schemas/pages/schema/common/schema-migrate-form.component.html
  21. 37
      frontend/src/app/features/schemas/pages/schema/common/schema-migrate-form.component.ts
  22. 3
      frontend/src/app/features/schemas/pages/schema/schema-page.component.html
  23. 2
      frontend/src/app/features/schemas/pages/schema/schema-page.component.ts
  24. 4
      frontend/src/app/shared/model/custom.ts
  25. 4
      frontend/src/app/shared/model/generated.ts
  26. 17
      frontend/src/app/shared/services/schemas.service.spec.ts
  27. 9
      frontend/src/app/shared/services/schemas.service.ts
  28. 18
      frontend/src/app/shared/state/schemas.state.spec.ts
  29. 8
      frontend/src/app/shared/state/schemas.state.ts
  30. 100
      tools/TestSuite/TestSuite.ApiTests/ContentMigrationTests.cs
  31. 6
      tools/TestSuite/TestSuite.ApiTests/Verify/AppCreationTests.Should_create_app_from_templates.verified.txt
  32. 3
      tools/TestSuite/TestSuite.ApiTests/Verify/SchemaTests.Should_create_singleton_schema.verified.txt
  33. 3
      tools/TestSuite/TestSuite.ApiTests/Verify/SchemaTests.Should_create_singleton_schema_with_obsolete_property.verified.txt
  34. 4
      tools/TestSuite/TestSuite.Shared/TestSuite.Shared.csproj

3
CLAUDE.md

@ -44,6 +44,9 @@ Some tests need test setup or test containers which are slow. Run the tests like
dotnet test --filter "Category!=Dependencies & Category!=TestContainer" dotnet test --filter "Category!=Dependencies & Category!=TestContainer"
``` ```
- Use xUnit assertions (`Assert.Equal`, `Assert.True`, `Assert.Single`, `Assert.Empty`, ...) for simple properties and values.
- Use FluentAssertions (`Should().BeEquivalentTo(...)`) only for deep, structural comparisons of objects and collections.
### Best Practices ### Best Practices
- Code style is enforced by StyleCop (`backend/stylecop.json`) and `.editorconfig` — follow the surrounding file's conventions. - Code style is enforced by StyleCop (`backend/stylecop.json`) and `.editorconfig` — follow the surrounding file's conventions.

7
backend/i18n/frontend_de.json

@ -1033,6 +1033,13 @@
"schemas.loadFailed": "Fehler beim Laden der Schemas. Bitte neu laden.", "schemas.loadFailed": "Fehler beim Laden der Schemas. Bitte neu laden.",
"schemas.loadSchemaFailed": "Fehler beim Laden des Schemas. Bitte neu laden.", "schemas.loadSchemaFailed": "Fehler beim Laden des Schemas. Bitte neu laden.",
"schemas.lockFieldFailed": "Fehler beim Sperren des Feldes. Bitte neu laden.", "schemas.lockFieldFailed": "Fehler beim Sperren des Feldes. Bitte neu laden.",
"schemas.migrateContents": "Migrate Contents",
"schemas.migrateContentsButton": "Start Migration",
"schemas.migrateContentsConfirmText": "Do you really want to migrate all contents of this schema? This can take a while and creates a new version for every changed content.",
"schemas.migrateContentsConfirmTitle": "Migrate Contents",
"schemas.migrateContentsFailed": "Failed to start the content migration.",
"schemas.migrateContentsHint": "Schema changes are not applied to the stored contents. The API removes invalid values from the responses, but queries and indexes still run over the raw data and can fail. Start a migration to rewrite all contents of this schema so that the stored data matches the current schema. The migration runs as a **job** and its progress is shown on the jobs page.",
"schemas.migrateContentsStarted": "Content migration started, it can take several minutes to complete.",
"schemas.modeComponent": "Komponente", "schemas.modeComponent": "Komponente",
"schemas.modeComponentDescription": "Kann nur in Komponentenfelder eingebettet werden...", "schemas.modeComponentDescription": "Kann nur in Komponentenfelder eingebettet werden...",
"schemas.modeMultiple": "Mehrere Inhalte", "schemas.modeMultiple": "Mehrere Inhalte",

7
backend/i18n/frontend_en.json

@ -1033,6 +1033,13 @@
"schemas.loadFailed": "Failed to load schemas. Please reload.", "schemas.loadFailed": "Failed to load schemas. Please reload.",
"schemas.loadSchemaFailed": "Failed to load schema. Please reload.", "schemas.loadSchemaFailed": "Failed to load schema. Please reload.",
"schemas.lockFieldFailed": "Failed to lock field. Please reload.", "schemas.lockFieldFailed": "Failed to lock field. Please reload.",
"schemas.migrateContents": "Migrate Contents",
"schemas.migrateContentsButton": "Start Migration",
"schemas.migrateContentsConfirmText": "Do you really want to migrate all contents of this schema? This can take a while and creates a new version for every changed content.",
"schemas.migrateContentsConfirmTitle": "Migrate Contents",
"schemas.migrateContentsFailed": "Failed to start the content migration.",
"schemas.migrateContentsHint": "Schema changes are not applied to the stored contents. The API removes invalid values from the responses, but queries and indexes still run over the raw data and can fail. Start a migration to rewrite all contents of this schema so that the stored data matches the current schema. The migration runs as a **job** and its progress is shown on the jobs page.",
"schemas.migrateContentsStarted": "Content migration started, it can take several minutes to complete.",
"schemas.modeComponent": "Component", "schemas.modeComponent": "Component",
"schemas.modeComponentDescription": "Can only be embedded to component fields...", "schemas.modeComponentDescription": "Can only be embedded to component fields...",
"schemas.modeMultiple": "Multiple contents", "schemas.modeMultiple": "Multiple contents",

7
backend/i18n/frontend_fr.json

@ -1033,6 +1033,13 @@
"schemas.loadFailed": "Échec du chargement des schémas. Veuillez recharger.", "schemas.loadFailed": "Échec du chargement des schémas. Veuillez recharger.",
"schemas.loadSchemaFailed": "Échec du chargement du schéma. Veuillez recharger.", "schemas.loadSchemaFailed": "Échec du chargement du schéma. Veuillez recharger.",
"schemas.lockFieldFailed": "Impossible de verrouiller le champ. Veuillez recharger.", "schemas.lockFieldFailed": "Impossible de verrouiller le champ. Veuillez recharger.",
"schemas.migrateContents": "Migrate Contents",
"schemas.migrateContentsButton": "Start Migration",
"schemas.migrateContentsConfirmText": "Do you really want to migrate all contents of this schema? This can take a while and creates a new version for every changed content.",
"schemas.migrateContentsConfirmTitle": "Migrate Contents",
"schemas.migrateContentsFailed": "Failed to start the content migration.",
"schemas.migrateContentsHint": "Schema changes are not applied to the stored contents. The API removes invalid values from the responses, but queries and indexes still run over the raw data and can fail. Start a migration to rewrite all contents of this schema so that the stored data matches the current schema. The migration runs as a **job** and its progress is shown on the jobs page.",
"schemas.migrateContentsStarted": "Content migration started, it can take several minutes to complete.",
"schemas.modeComponent": "Composant", "schemas.modeComponent": "Composant",
"schemas.modeComponentDescription": "Ne peut être intégré qu'aux champs de composant...", "schemas.modeComponentDescription": "Ne peut être intégré qu'aux champs de composant...",
"schemas.modeMultiple": "Contenus multiples", "schemas.modeMultiple": "Contenus multiples",

7
backend/i18n/frontend_it.json

@ -1033,6 +1033,13 @@
"schemas.loadFailed": "Non è stato possibile caricare gli schemi. Per favore ricarica.", "schemas.loadFailed": "Non è stato possibile caricare gli schemi. Per favore ricarica.",
"schemas.loadSchemaFailed": "Non è stato possibile caricare lo schema. Per favore ricarica.", "schemas.loadSchemaFailed": "Non è stato possibile caricare lo schema. Per favore ricarica.",
"schemas.lockFieldFailed": "Non è stato possibile bloccare il campo. Per favore ricarica.", "schemas.lockFieldFailed": "Non è stato possibile bloccare il campo. Per favore ricarica.",
"schemas.migrateContents": "Migrate Contents",
"schemas.migrateContentsButton": "Start Migration",
"schemas.migrateContentsConfirmText": "Do you really want to migrate all contents of this schema? This can take a while and creates a new version for every changed content.",
"schemas.migrateContentsConfirmTitle": "Migrate Contents",
"schemas.migrateContentsFailed": "Failed to start the content migration.",
"schemas.migrateContentsHint": "Schema changes are not applied to the stored contents. The API removes invalid values from the responses, but queries and indexes still run over the raw data and can fail. Start a migration to rewrite all contents of this schema so that the stored data matches the current schema. The migration runs as a **job** and its progress is shown on the jobs page.",
"schemas.migrateContentsStarted": "Content migration started, it can take several minutes to complete.",
"schemas.modeComponent": "Component", "schemas.modeComponent": "Component",
"schemas.modeComponentDescription": "Can only be embedded to component fields...", "schemas.modeComponentDescription": "Can only be embedded to component fields...",
"schemas.modeMultiple": "Contenuti multipli", "schemas.modeMultiple": "Contenuti multipli",

7
backend/i18n/frontend_nl.json

@ -1033,6 +1033,13 @@
"schemas.loadFailed": "Kan schema's niet laden. Laad opnieuw.", "schemas.loadFailed": "Kan schema's niet laden. Laad opnieuw.",
"schemas.loadSchemaFailed": "Kan schema niet laden. Laad opnieuw.", "schemas.loadSchemaFailed": "Kan schema niet laden. Laad opnieuw.",
"schemas.lockFieldFailed": "Kan veld niet vergrendelen. Laad opnieuw.", "schemas.lockFieldFailed": "Kan veld niet vergrendelen. Laad opnieuw.",
"schemas.migrateContents": "Migrate Contents",
"schemas.migrateContentsButton": "Start Migration",
"schemas.migrateContentsConfirmText": "Do you really want to migrate all contents of this schema? This can take a while and creates a new version for every changed content.",
"schemas.migrateContentsConfirmTitle": "Migrate Contents",
"schemas.migrateContentsFailed": "Failed to start the content migration.",
"schemas.migrateContentsHint": "Schema changes are not applied to the stored contents. The API removes invalid values from the responses, but queries and indexes still run over the raw data and can fail. Start a migration to rewrite all contents of this schema so that the stored data matches the current schema. The migration runs as a **job** and its progress is shown on the jobs page.",
"schemas.migrateContentsStarted": "Content migration started, it can take several minutes to complete.",
"schemas.modeComponent": "Component", "schemas.modeComponent": "Component",
"schemas.modeComponentDescription": "Kan alleen worden gebruikt in componentvelden...", "schemas.modeComponentDescription": "Kan alleen worden gebruikt in componentvelden...",
"schemas.modeMultiple": "Meerdere inhoud", "schemas.modeMultiple": "Meerdere inhoud",

7
backend/i18n/frontend_pt.json

@ -1033,6 +1033,13 @@
"schemas.loadFailed": "Falhou em carregar esquemas. Por favor, recarregue.", "schemas.loadFailed": "Falhou em carregar esquemas. Por favor, recarregue.",
"schemas.loadSchemaFailed": "Falhou em carregar o esquema. Por favor, recarregue.", "schemas.loadSchemaFailed": "Falhou em carregar o esquema. Por favor, recarregue.",
"schemas.lockFieldFailed": "Falhou em bloquear o campo. Por favor, recarregue.", "schemas.lockFieldFailed": "Falhou em bloquear o campo. Por favor, recarregue.",
"schemas.migrateContents": "Migrate Contents",
"schemas.migrateContentsButton": "Start Migration",
"schemas.migrateContentsConfirmText": "Do you really want to migrate all contents of this schema? This can take a while and creates a new version for every changed content.",
"schemas.migrateContentsConfirmTitle": "Migrate Contents",
"schemas.migrateContentsFailed": "Failed to start the content migration.",
"schemas.migrateContentsHint": "Schema changes are not applied to the stored contents. The API removes invalid values from the responses, but queries and indexes still run over the raw data and can fail. Start a migration to rewrite all contents of this schema so that the stored data matches the current schema. The migration runs as a **job** and its progress is shown on the jobs page.",
"schemas.migrateContentsStarted": "Content migration started, it can take several minutes to complete.",
"schemas.modeComponent": "Componente", "schemas.modeComponent": "Componente",
"schemas.modeComponentDescription": "Só pode ser incorporado em campos componentes...", "schemas.modeComponentDescription": "Só pode ser incorporado em campos componentes...",
"schemas.modeMultiple": "Vários conteúdos", "schemas.modeMultiple": "Vários conteúdos",

7
backend/i18n/frontend_zh.json

@ -1033,6 +1033,13 @@
"schemas.loadFailed": "加载Schemas失败。请重新加载。", "schemas.loadFailed": "加载Schemas失败。请重新加载。",
"schemas.loadSchemaFailed": "Failed to load schema. Please reload.", "schemas.loadSchemaFailed": "Failed to load schema. Please reload.",
"schemas.lockFieldFailed": "无法锁定字段。请重新加载。", "schemas.lockFieldFailed": "无法锁定字段。请重新加载。",
"schemas.migrateContents": "Migrate Contents",
"schemas.migrateContentsButton": "Start Migration",
"schemas.migrateContentsConfirmText": "Do you really want to migrate all contents of this schema? This can take a while and creates a new version for every changed content.",
"schemas.migrateContentsConfirmTitle": "Migrate Contents",
"schemas.migrateContentsFailed": "Failed to start the content migration.",
"schemas.migrateContentsHint": "Schema changes are not applied to the stored contents. The API removes invalid values from the responses, but queries and indexes still run over the raw data and can fail. Start a migration to rewrite all contents of this schema so that the stored data matches the current schema. The migration runs as a **job** and its progress is shown on the jobs page.",
"schemas.migrateContentsStarted": "Content migration started, it can take several minutes to complete.",
"schemas.modeComponent": "Component", "schemas.modeComponent": "Component",
"schemas.modeComponentDescription": "只能嵌入到组件字段...", "schemas.modeComponentDescription": "只能嵌入到组件字段...",
"schemas.modeMultiple": "多个内容", "schemas.modeMultiple": "多个内容",

7
backend/i18n/source/frontend_en.json

@ -1033,6 +1033,13 @@
"schemas.loadFailed": "Failed to load schemas. Please reload.", "schemas.loadFailed": "Failed to load schemas. Please reload.",
"schemas.loadSchemaFailed": "Failed to load schema. Please reload.", "schemas.loadSchemaFailed": "Failed to load schema. Please reload.",
"schemas.lockFieldFailed": "Failed to lock field. Please reload.", "schemas.lockFieldFailed": "Failed to lock field. Please reload.",
"schemas.migrateContents": "Migrate Contents",
"schemas.migrateContentsButton": "Start Migration",
"schemas.migrateContentsConfirmText": "Do you really want to migrate all contents of this schema? This can take a while and creates a new version for every changed content.",
"schemas.migrateContentsConfirmTitle": "Migrate Contents",
"schemas.migrateContentsFailed": "Failed to start the content migration.",
"schemas.migrateContentsHint": "Schema changes are not applied to the stored contents. The API removes invalid values from the responses, but queries and indexes still run over the raw data and can fail. Start a migration to rewrite all contents of this schema so that the stored data matches the current schema. The migration runs as a **job** and its progress is shown on the jobs page.",
"schemas.migrateContentsStarted": "Content migration started, it can take several minutes to complete.",
"schemas.modeComponent": "Component", "schemas.modeComponent": "Component",
"schemas.modeComponentDescription": "Can only be embedded to component fields...", "schemas.modeComponentDescription": "Can only be embedded to component fields...",
"schemas.modeMultiple": "Multiple contents", "schemas.modeMultiple": "Multiple contents",

202
backend/src/Squidex.Domain.Apps.Entities/Contents/Migration/MigrateContentsJob.cs

@ -0,0 +1,202 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Squidex.Domain.Apps.Core.Apps;
using Squidex.Domain.Apps.Core.ConvertContent;
using Squidex.Domain.Apps.Core.Schemas;
using Squidex.Domain.Apps.Entities.Contents.Commands;
using Squidex.Domain.Apps.Entities.Contents.Repositories;
using Squidex.Domain.Apps.Entities.Jobs;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Commands;
using Squidex.Infrastructure.Json;
using Squidex.Infrastructure.States;
using Squidex.Infrastructure.Tasks;
namespace Squidex.Domain.Apps.Entities.Contents.Migration;
public sealed class MigrateContentsJob(
IAppProvider appProvider,
ICommandBus commandBus,
IContentRepository contentRepository,
IContextProvider contextProvider,
IJsonSerializer jsonSerializer)
: IJobRunner
{
public const string TaskName = "migrateContents";
public const string ArgAppId = "appId";
public const string ArgAppName = "appName";
public const string ArgSchemaId = "schemaId";
public const string ArgSchemaName = "schemaName";
// Schema changes are not applied to the stored contents, therefore a lot of items can be affected.
private const int BatchSize = 100;
public string Name => TaskName;
public static JobRequest BuildRequest(RefToken actor, App app, Schema schema)
{
Guard.NotNull(actor);
Guard.NotNull(app);
Guard.NotNull(schema);
return JobRequest.Create(
actor,
TaskName,
new Dictionary<string, string>
{
[ArgAppId] = app.Id.ToString(),
[ArgAppName] = app.Name,
[ArgSchemaId] = schema.Id.ToString(),
[ArgSchemaName] = schema.Name,
}) with
{
AppId = app.NamedId(),
};
}
public async Task RunAsync(JobRunContext context,
CancellationToken ct)
{
// The other arguments are just there for debugging purposes. Therefore do not validate them.
if (!context.Job.Arguments.TryGetValue(ArgSchemaId, out var schemaIdValue))
{
throw new DomainException($"Argument '{ArgSchemaId}' missing.");
}
if (!context.Job.Arguments.TryGetValue(ArgSchemaName, out var schemaName))
{
throw new DomainException($"Argument '{ArgSchemaName}' missing.");
}
var schemaId = DomainId.Create(schemaIdValue);
var (app, schema) = await appProvider.GetAppWithSchemaAsync(context.OwnerId, schemaId, ct: ct);
if (app == null)
{
throw new DomainObjectNotFoundException(context.OwnerId.ToString());
}
if (schema == null)
{
throw new DomainObjectNotFoundException(schemaIdValue);
}
// Use a readable name to describe the job.
context.Job.Description = $"Schema {schemaName}: Migrate contents";
// The job is not running in the scope of a request, therefore we have to provide the context for the commands.
contextProvider.Context = Context.Admin(app).Clone(b => b
.WithNoEnrichment()
.WithNoCleanup()
.WithUnpublished(true));
var components = await appProvider.GetComponentsAsync(schema, ct);
var converter = BuildConverter(app, schema, components);
// Buffer the batches, so that the next contents are read while the current batch is written.
var batches =
contentRepository.StreamAll(app.Id, [schemaId], SearchScope.All, ct)
.Batch(BatchSize, ct)
.Buffered(2, ct);
var totalCount = 0;
var totalUpdates = 0;
// The progress is a single log line, but it must not overwrite the errors of the previous batch.
var replaceProgress = false;
await foreach (var batch in batches)
{
var jobs = new List<BulkUpdateJob>(batch.Count);
foreach (var content in batch)
{
// The converter takes ownership of the data, therefore the clone is needed for the comparison.
var converted = converter.Convert(content.Data.Clone());
if (converted.Equals(content.Data))
{
continue;
}
jobs.Add(new BulkUpdateJob
{
Id = content.Id,
Data = converted,
Type = BulkUpdateContentType.Update,
});
}
totalCount += batch.Count;
totalUpdates += jobs.Count;
var errors = 0;
if (jobs.Count > 0)
{
errors = await UpdateAsync(context, app, schema, jobs, ct);
}
await context.LogAsync($"Checked contents: {totalCount}, updated: {totalUpdates}", replaceProgress && errors == 0);
replaceProgress = true;
}
await context.LogAsync($"Checked contents: {totalCount}, updated: {totalUpdates}", replaceProgress);
}
private ContentConverter BuildConverter(App app, Schema schema, ResolvedComponents components)
{
// The converter itself removes all fields and components that are not part of the schema anymore.
var converter = new ContentConverter(components, schema);
// Remove all values that are not compatible with the current field type.
converter.Add(new ExcludeChangedTypes(jsonSerializer));
// Move the values over when the partitioning of a field has been changed.
converter.Add(new ResolveFromPreviousPartitioning(app.Languages));
return converter;
}
private async Task<int> UpdateAsync(JobRunContext context, App app, Schema schema, List<BulkUpdateJob> jobs,
CancellationToken ct)
{
// The contents are only converted to the current schema, therefore all custom logic must be skipped.
var command = new BulkUpdateContents
{
Jobs = jobs.ToArray(),
Actor = context.Actor,
AppId = app.NamedId(),
DoNotScript = true,
DoNotValidate = true,
DoNotValidateWorkflow = true,
OptimizeValidation = true,
SchemaId = schema.NamedId(),
};
var commandContext = await commandBus.PublishAsync(command, ct);
// Errors are reported per content item, so that a single invalid item does not stop the migration.
if (commandContext.PlainResult is not BulkUpdateResult result)
{
return 0;
}
var errors = 0;
foreach (var item in result)
{
if (item.Exception != null)
{
await context.LogAsync($"Failed to migrate content {item.Id}: {item.Exception.Message}");
errors++;
}
}
return errors;
}
}

1
backend/src/Squidex.Shared/PermissionIds.cs

@ -206,6 +206,7 @@ public static class PermissionIds
public const string AppSchemasPublish = "squidex.apps.{app}.schemas.{schema}.publish"; public const string AppSchemasPublish = "squidex.apps.{app}.schemas.{schema}.publish";
public const string AppSchemasDelete = "squidex.apps.{app}.schemas.{schema}.delete"; public const string AppSchemasDelete = "squidex.apps.{app}.schemas.{schema}.delete";
public const string AppSchemasIndexes = "squidex.apps.{app}.schemas.{schema}.indexes"; public const string AppSchemasIndexes = "squidex.apps.{app}.schemas.{schema}.indexes";
public const string AppSchemasMigrate = "squidex.apps.{app}.schemas.{schema}.migrate";
// App Contents // App Contents
public const string AppContents = "squidex.apps.{app}.contents.{schema}"; public const string AppContents = "squidex.apps.{app}.contents.{schema}";

2
backend/src/Squidex.Web/Resources.cs

@ -46,6 +46,8 @@ public sealed class Resources(ApiController controller)
public bool CanManageIndexes(string schema) => Can(PermissionIds.AppSchemasIndexes, schema); public bool CanManageIndexes(string schema) => Can(PermissionIds.AppSchemasIndexes, schema);
public bool CanMigrateSchemaContents(string schema) => Can(PermissionIds.AppSchemasMigrate, schema);
public bool CanCreateSchema => Can(PermissionIds.AppSchemasCreate); public bool CanCreateSchema => Can(PermissionIds.AppSchemasCreate);
public bool CanUpdateSettings => Can(PermissionIds.AppUpdateSettings); public bool CanUpdateSettings => Can(PermissionIds.AppUpdateSettings);

6
backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/SchemaDto.cs

@ -174,6 +174,12 @@ public class SchemaDto : Resource
resources.Url<ContentsController>(x => nameof(x.PostContent), values) + "?publish=true"); resources.Url<ContentsController>(x => nameof(x.PostContent), values) + "?publish=true");
} }
if (resources.CanMigrateSchemaContents(Name) && Type != SchemaType.Component)
{
AddPostLink("contents/migrate",
resources.Url<SchemaContentsController>(x => nameof(x.PostContentMigration), values));
}
if (resources.CanPublishSchema(Name)) if (resources.CanPublishSchema(Name))
{ {
if (IsPublished) if (IsPublished)

49
backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemaContentsController.cs

@ -0,0 +1,49 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Microsoft.AspNetCore.Mvc;
using Squidex.Domain.Apps.Entities.Contents.Migration;
using Squidex.Domain.Apps.Entities.Jobs;
using Squidex.Infrastructure.Commands;
using Squidex.Infrastructure.Security;
using Squidex.Shared;
using Squidex.Web;
namespace Squidex.Areas.Api.Controllers.Schemas;
/// <summary>
/// Update and query information about schemas.
/// </summary>
[ApiExplorerSettings(GroupName = nameof(Schemas))]
[ApiModelValidation(true)]
public class SchemaContentsController(ICommandBus commandBus, IJobService jobService) : ApiController(commandBus)
{
/// <summary>
/// Migrate the contents to the current schema.
/// </summary>
/// <param name="app">The name of the app.</param>
/// <param name="schema">The name of the schema.</param>
/// <response code="204">Content migration added to job queue.</response>
/// <response code="404">Schema or app not found.</response>
/// <remarks>
/// Schema changes are not applied to the stored contents. This endpoint starts a job that rewrites all
/// contents of the schema so that the stored data matches the current schema.
/// </remarks>
[HttpPost]
[Route("apps/{app}/schemas/{schema}/contents/migrate")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ApiPermissionOrAnonymous(PermissionIds.AppSchemasMigrate)]
[ApiCosts(1)]
public async Task<IActionResult> PostContentMigration(string app, string schema)
{
var job = MigrateContentsJob.BuildRequest(User.Token()!, App, Schema);
await jobService.StartAsync(App.Id, job, HttpContext.RequestAborted);
return NoContent();
}
}

4
backend/src/Squidex/Config/Messaging/MessagingServices.cs

@ -14,6 +14,7 @@ using Squidex.Domain.Apps.Entities.Backup;
using Squidex.Domain.Apps.Entities.Billing; using Squidex.Domain.Apps.Entities.Billing;
using Squidex.Domain.Apps.Entities.Contents; using Squidex.Domain.Apps.Entities.Contents;
using Squidex.Domain.Apps.Entities.Contents.Indexes; using Squidex.Domain.Apps.Entities.Contents.Indexes;
using Squidex.Domain.Apps.Entities.Contents.Migration;
using Squidex.Domain.Apps.Entities.Jobs; using Squidex.Domain.Apps.Entities.Jobs;
using Squidex.Domain.Apps.Entities.Rules.Runner; using Squidex.Domain.Apps.Entities.Rules.Runner;
using Squidex.Domain.Apps.Entities.Rules.UsageTracking; using Squidex.Domain.Apps.Entities.Rules.UsageTracking;
@ -96,6 +97,9 @@ public static class MessagingServices
services.AddSingletonAs<DropIndexJob>() services.AddSingletonAs<DropIndexJob>()
.As<IJobRunner>(); .As<IJobRunner>();
services.AddSingletonAs<MigrateContentsJob>()
.As<IJobRunner>();
services.AddSingleton<IMessagingSerializer>(c => services.AddSingleton<IMessagingSerializer>(c =>
new SystemTextJsonMessagingSerializer(c.GetRequiredService<JsonSerializerOptions>())); new SystemTextJsonMessagingSerializer(c.GetRequiredService<JsonSerializerOptions>()));

255
backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Migration/MigrateContentsJobTests.cs

@ -0,0 +1,255 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Squidex.Domain.Apps.Core;
using Squidex.Domain.Apps.Core.Contents;
using Squidex.Domain.Apps.Core.Schemas;
using Squidex.Domain.Apps.Entities.Contents.Commands;
using Squidex.Domain.Apps.Entities.Contents.Repositories;
using Squidex.Domain.Apps.Entities.Jobs;
using Squidex.Domain.Apps.Entities.TestHelpers;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Collections;
using Squidex.Infrastructure.Commands;
using Squidex.Infrastructure.States;
using IClock = NodaTime.IClock;
using TestUtils = Squidex.Domain.Apps.Core.TestHelpers.TestUtils;
namespace Squidex.Domain.Apps.Entities.Contents.Migration;
public class MigrateContentsJobTests : GivenContext
{
private readonly ICommandBus commandBus = A.Fake<ICommandBus>();
private readonly IContentRepository contentRepository = A.Fake<IContentRepository>();
private readonly IContextProvider contextProvider = A.Fake<IContextProvider>();
private readonly List<BulkUpdateContents> commands = [];
private readonly MigrateContentsJob sut;
private BulkUpdateResult bulkUpdateResult = new BulkUpdateResult();
public MigrateContentsJobTests()
{
Schema =
Schema
.AddNumber(1, "my-field", Partitioning.Invariant)
.AddString(2, "my-string", Partitioning.Invariant);
A.CallTo(() => commandBus.PublishAsync(A<ICommand>._, A<CancellationToken>._))
.ReturnsLazily(x =>
{
var command = x.GetArgument<ICommand>(0)!;
if (command is BulkUpdateContents bulkUpdate)
{
commands.Add(bulkUpdate);
}
return Task.FromResult(new CommandContext(command, commandBus).Complete(bulkUpdateResult));
});
sut = new MigrateContentsJob(AppProvider, commandBus, contentRepository, contextProvider, TestUtils.DefaultSerializer);
}
[Fact]
public void Should_create_request()
{
var job = MigrateContentsJob.BuildRequest(User, App, Schema);
job.Arguments.Should().BeEquivalentTo(
new Dictionary<string, string>
{
["appId"] = App.Id.ToString(),
["appName"] = App.Name,
["schemaId"] = Schema.Id.ToString(),
["schemaName"] = Schema.Name,
});
}
[Fact]
public async Task Should_throw_exception_if_arguments_do_not_contain_schemaId()
{
var context = CreateRunContext(new Job
{
Arguments = new Dictionary<string, string>
{
["schemaName"] = Schema.Name,
}.ToReadonlyDictionary(),
});
await Assert.ThrowsAsync<DomainException>(() => sut.RunAsync(context, CancellationToken));
}
[Fact]
public async Task Should_throw_exception_if_arguments_do_not_contain_schemaName()
{
var context = CreateRunContext(new Job
{
Arguments = new Dictionary<string, string>
{
["schemaId"] = Schema.Id.ToString(),
}.ToReadonlyDictionary(),
});
await Assert.ThrowsAsync<DomainException>(() => sut.RunAsync(context, CancellationToken));
}
[Fact]
public async Task Should_throw_exception_if_schema_not_found()
{
A.CallTo(() => AppProvider.GetAppWithSchemaAsync(AppId.Id, SchemaId.Id, A<bool>._, A<CancellationToken>._))
.Returns((App, null as Schema));
var context = CreateRunContext(CreateJob());
await Assert.ThrowsAsync<DomainObjectNotFoundException>(() => sut.RunAsync(context, CancellationToken));
}
[Fact]
public async Task Should_not_update_content_if_data_matches_schema()
{
SetupContents(CreateContent(new ContentData()
.AddField("my-field",
new ContentFieldData()
.AddInvariant(42))
.AddField("my-string",
new ContentFieldData()
.AddInvariant("hello"))));
await sut.RunAsync(CreateRunContext(CreateJob()), CancellationToken);
Assert.Empty(commands);
}
[Fact]
public async Task Should_update_content_with_invalid_values()
{
var content = CreateContent(new ContentData()
.AddField("my-field",
new ContentFieldData()
.AddInvariant("invalid"))
.AddField("my-string",
new ContentFieldData()
.AddInvariant("hello"))
.AddField("removed-field",
new ContentFieldData()
.AddInvariant(42)));
SetupContents(content);
await sut.RunAsync(CreateRunContext(CreateJob()), CancellationToken);
var command = Assert.Single(commands);
Assert.Equal(SchemaId, command.SchemaId);
Assert.True(command.DoNotScript);
Assert.True(command.DoNotValidate);
Assert.True(command.DoNotValidateWorkflow);
var job = Assert.Single(command.Jobs!);
Assert.Equal(content.Id, job.Id);
Assert.Equal(BulkUpdateContentType.Update, job.Type);
// The invalid value and the field that is not part of the schema anymore are removed.
job.Data.Should().BeEquivalentTo(
new ContentData()
.AddField("my-string",
new ContentFieldData()
.AddInvariant("hello")));
}
[Fact]
public async Task Should_update_contents_in_batches()
{
var contents = Enumerable.Range(0, 150).Select(_ => CreateContent(new ContentData()
.AddField("my-field",
new ContentFieldData()
.AddInvariant("invalid")))).ToArray();
SetupContents(contents);
await sut.RunAsync(CreateRunContext(CreateJob()), CancellationToken);
Assert.Equal([100, 50], commands.Select(x => x.Jobs!.Length));
}
[Fact]
public async Task Should_log_progress_as_single_line()
{
var contents = Enumerable.Range(0, 150).Select(_ => CreateContent(new ContentData()
.AddField("my-field",
new ContentFieldData()
.AddInvariant("invalid")))).ToArray();
SetupContents(contents);
var context = CreateRunContext(CreateJob());
await sut.RunAsync(context, CancellationToken);
Assert.Equal("Checked contents: 150, updated: 150", Assert.Single(context.Job.Log).Message);
}
[Fact]
public async Task Should_not_overwrite_errors_with_progress()
{
var content = CreateContent(new ContentData()
.AddField("my-field",
new ContentFieldData()
.AddInvariant("invalid")));
SetupContents(content);
bulkUpdateResult = new BulkUpdateResult([new BulkUpdateResultItem(content.Id, 0, new DomainException("Error"))]);
var context = CreateRunContext(CreateJob());
await sut.RunAsync(context, CancellationToken);
Assert.Equal(
[
$"Failed to migrate content {content.Id}: Error",
"Checked contents: 1, updated: 1",
],
context.Job.Log.Select(x => x.Message));
}
private void SetupContents(params Content[] contents)
{
A.CallTo(() => contentRepository.StreamAll(AppId.Id, A<HashSet<DomainId>>._, SearchScope.All, A<CancellationToken>._))
.Returns(contents.ToAsyncEnumerable());
}
private Content CreateContent(ContentData data)
{
var content = CreateContent();
content.Data = data;
return content;
}
private Job CreateJob()
{
return new Job
{
Arguments = new Dictionary<string, string>
{
["appId"] = App.Id.ToString(),
["appName"] = App.Name,
["schemaId"] = Schema.Id.ToString(),
["schemaName"] = Schema.Name,
}.ToReadonlyDictionary(),
};
}
private JobRunContext CreateRunContext(Job job)
{
var state = new SimpleState<JobsState>(A.Fake<IPersistenceFactory<JobsState>>(), GetType(), App.Id);
return new JobRunContext(state, A.Fake<IClock>(), default) { Actor = User, Job = job, OwnerId = App.Id };
}
}

22
frontend/generator/Generator.sln

@ -1,22 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35707.178 d17.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Generator", "Generator\Generator.csproj", "{0BD7AC0B-640B-4D26-A9B9-C1CCEE4C14E7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0BD7AC0B-640B-4D26-A9B9-C1CCEE4C14E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0BD7AC0B-640B-4D26-A9B9-C1CCEE4C14E7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0BD7AC0B-640B-4D26-A9B9-C1CCEE4C14E7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0BD7AC0B-640B-4D26-A9B9-C1CCEE4C14E7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

3
frontend/generator/Generator.slnx

@ -0,0 +1,3 @@
<Solution>
<Project Path="Generator/Generator.csproj" />
</Solution>

71
frontend/generator/Generator/cache.json

@ -1,5 +1,5 @@
{ {
"x-generator": "NSwag v14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))", "x-generator": "NSwag v14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))",
"openapi": "3.0.0", "openapi": "3.0.0",
"info": { "info": {
"title": "Squidex API", "title": "Squidex API",
@ -332,7 +332,7 @@
"security": [ "security": [
{ {
"squidex-oauth-auth": [ "squidex-oauth-auth": [
"squidex.admin.users.unlock" "squidex.admin.users.delete"
] ]
} }
] ]
@ -2088,6 +2088,73 @@
] ]
} }
}, },
"/api/apps/{app}/schemas/{schema}/contents/migrate": {
"post": {
"tags": [
"Schemas"
],
"summary": "Migrate the contents to the current schema.",
"description": "Schema changes are not applied to the stored contents. This endpoint starts a job that rewrites all\ncontents of the schema so that the stored data matches the current schema.",
"operationId": "SchemaContents_PostContentMigration",
"parameters": [
{
"name": "app",
"in": "path",
"required": true,
"description": "The name of the app.",
"schema": {
"type": "string"
},
"x-position": 1
},
{
"name": "schema",
"in": "path",
"required": true,
"description": "The name of the schema.",
"schema": {
"type": "string"
},
"x-position": 2
}
],
"responses": {
"204": {
"description": "Content migration added to job queue."
},
"404": {
"description": "Schema or app not found."
},
"400": {
"description": "Validation error.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorDto"
}
}
}
},
"500": {
"description": "Operation failed.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorDto"
}
}
}
}
},
"security": [
{
"squidex-oauth-auth": [
"squidex.apps.{app}.schemas.{schema}.migrate"
]
}
]
}
},
"/api/apps/{app}/schemas/{schema}/fields": { "/api/apps/{app}/schemas/{schema}/fields": {
"post": { "post": {
"tags": [ "tags": [

20
frontend/src/app/features/schemas/pages/schema/common/schema-migrate-form.component.html

@ -0,0 +1,20 @@
<h5>{{ "schemas.migrateContents" | sqxTranslate }}</h5>
<div class="card">
<div class="card-body">
<span [sqxMarkdown]="'schemas.migrateContentsHint' | sqxTranslate" trusted="true"></span>
</div>
<div class="card-footer">
@if (schema.canContentsMigrate) {
<button
class="float-end btn btn-primary"
confirmText="i18n:schemas.migrateContentsConfirmText"
confirmTitle="i18n:schemas.migrateContentsConfirmTitle"
(sqxConfirmClick)="migrateContents()"
type="button">
{{ "schemas.migrateContentsButton" | sqxTranslate }}
</button>
}
</div>
</div>

37
frontend/src/app/features/schemas/pages/schema/common/schema-migrate-form.component.ts

@ -0,0 +1,37 @@
/*
* Squidex Headless CMS
*
* @license
* Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved.
*/
import { Component, Input } from '@angular/core';
import { ConfirmClickDirective, MarkdownDirective, SchemaDto, SchemasState, TranslatePipe } from '@app/shared';
@Component({
selector: 'sqx-schema-migrate-form',
templateUrl: './schema-migrate-form.component.html',
imports: [
ConfirmClickDirective,
MarkdownDirective,
TranslatePipe,
],
})
export class SchemaMigrateFormComponent {
@Input({ required: true })
public schema!: SchemaDto;
constructor(
private readonly schemasState: SchemasState,
) {
}
public migrateContents() {
if (!this.schema.canContentsMigrate) {
return;
}
this.schemasState.migrateContents(this.schema).subscribe();
}
}

3
frontend/src/app/features/schemas/pages/schema/schema-page.component.html

@ -120,6 +120,9 @@
} }
<sqx-schema-field-rules-form [schema]="schema" /> <sqx-schema-field-rules-form [schema]="schema" />
<sqx-schema-edit-form [languages]="languages" [schema]="schema" /> <sqx-schema-edit-form [languages]="languages" [schema]="schema" />
@if (schema.type !== "Component") {
<sqx-schema-migrate-form [schema]="schema" />
}
</div> </div>
</sqx-list-view> </sqx-list-view>
} }

2
frontend/src/app/features/schemas/pages/schema/schema-page.component.ts

@ -12,6 +12,7 @@ import { map } from 'rxjs/operators';
import { ConfirmClickDirective, defined, DropdownMenuComponent, LanguagesState, LayoutComponent, ListViewComponent, MessageBus, ModalDirective, ModalModel, ModalPlacementDirective, SchemaDto, SchemasState, SidebarMenuDirective, Subscriptions, TitleComponent, TooltipDirective, TourStepDirective, TranslatePipe, UIOptions } from '@app/shared'; import { ConfirmClickDirective, defined, DropdownMenuComponent, LanguagesState, LayoutComponent, ListViewComponent, MessageBus, ModalDirective, ModalModel, ModalPlacementDirective, SchemaDto, SchemasState, SidebarMenuDirective, Subscriptions, TitleComponent, TooltipDirective, TourStepDirective, TranslatePipe, UIOptions } from '@app/shared';
import { SchemaCloning } from '../messages'; import { SchemaCloning } from '../messages';
import { SchemaEditFormComponent } from './common/schema-edit-form.component'; import { SchemaEditFormComponent } from './common/schema-edit-form.component';
import { SchemaMigrateFormComponent } from './common/schema-migrate-form.component';
import { SchemaExportFormComponent } from './export/schema-export-form.component'; import { SchemaExportFormComponent } from './export/schema-export-form.component';
import { SchemaFieldsComponent } from './fields/schema-fields.component'; import { SchemaFieldsComponent } from './fields/schema-fields.component';
import { SchemaIndexesComponent } from './indexes/schema-indexes.component'; import { SchemaIndexesComponent } from './indexes/schema-indexes.component';
@ -40,6 +41,7 @@ import { SchemaUIFormComponent } from './ui/schema-ui-form.component';
SchemaFieldRulesFormComponent, SchemaFieldRulesFormComponent,
SchemaFieldsComponent, SchemaFieldsComponent,
SchemaIndexesComponent, SchemaIndexesComponent,
SchemaMigrateFormComponent,
SchemaPreviewUrlsFormComponent, SchemaPreviewUrlsFormComponent,
SchemaScriptsFormComponent, SchemaScriptsFormComponent,
SchemaUIFormComponent, SchemaUIFormComponent,

4
frontend/src/app/shared/model/custom.ts

@ -486,6 +486,10 @@ export class SchemaDto extends generated.SchemaDto {
return this.compute('canContentsCreateAndPublish', () => hasAnyLink(this._links, 'contents/create/publish')); return this.compute('canContentsCreateAndPublish', () => hasAnyLink(this._links, 'contents/create/publish'));
} }
public get canContentsMigrate() {
return this.compute('canContentsMigrate', () => hasAnyLink(this._links, 'contents/migrate'));
}
public get canContentsRead() { public get canContentsRead() {
return this.compute('canContentsRead', () => hasAnyLink(this._links, 'contents')); return this.compute('canContentsRead', () => hasAnyLink(this._links, 'contents'));
} }

4
frontend/src/app/shared/model/generated.ts

@ -2283,6 +2283,10 @@ export class SchemaDto extends ResourceDto implements ISchemaDto {
return this.compute('canContentsCreateAndPublish', () => hasAnyLink(this._links, 'contents/create/publish')); return this.compute('canContentsCreateAndPublish', () => hasAnyLink(this._links, 'contents/create/publish'));
} }
public get canContentsMigrate() {
return this.compute('canContentsMigrate', () => hasAnyLink(this._links, 'contents/migrate'));
}
public get canContentsRead() { public get canContentsRead() {
return this.compute('canContentsRead', () => hasAnyLink(this._links, 'contents')); return this.compute('canContentsRead', () => hasAnyLink(this._links, 'contents'));
} }

17
frontend/src/app/shared/services/schemas.service.spec.ts

@ -541,6 +541,23 @@ describe('SchemasService', () => {
expect(schema!).toEqual(createSchema(12)); expect(schema!).toEqual(createSchema(12));
})); }));
it('should make post request to migrate contents', inject([SchemasService, HttpTestingController], (schemasService: SchemasService, httpMock: HttpTestingController) => {
const resource: Resource = {
_links: {
'contents/migrate': { method: 'POST', href: '/api/apps/my-app/schemas/my-schema/contents/migrate' },
},
};
schemasService.postContentMigration('my-app', resource).subscribe();
const req = httpMock.expectOne('http://service/p/api/apps/my-app/schemas/my-schema/contents/migrate');
expect(req.request.method).toEqual('POST');
expect(req.request.headers.get('If-Match')).toBeNull();
req.flush({});
}));
it('should make delete request to delete schema', inject([SchemasService, HttpTestingController], (schemasService: SchemasService, httpMock: HttpTestingController) => { it('should make delete request to delete schema', inject([SchemasService, HttpTestingController], (schemasService: SchemasService, httpMock: HttpTestingController) => {
const resource: Resource = { const resource: Resource = {
_links: { _links: {

9
frontend/src/app/shared/services/schemas.service.ts

@ -279,6 +279,15 @@ export class SchemasService {
pretifyError('i18n:schemas.deleteFieldFailed')); pretifyError('i18n:schemas.deleteFieldFailed'));
} }
public postContentMigration(appName: string, resource: Resource): Observable<any> {
const link = resource._links['contents/migrate'];
const url = this.apiUrl.buildUrl(link.href);
return this.http.request(link.method, url).pipe(
pretifyError('i18n:schemas.migrateContentsFailed'));
}
public deleteSchema(appName: string, resource: Resource, version: VersionOrTag): Observable<Versioned<any>> { public deleteSchema(appName: string, resource: Resource, version: VersionOrTag): Observable<Versioned<any>> {
const link = resource._links['delete']; const link = resource._links['delete'];

18
frontend/src/app/shared/state/schemas.state.spec.ts

@ -189,6 +189,24 @@ describe('SchemasState', () => {
expect(schemasState.snapshot.schemas).toEqualIgnoringProps([updated, schema2]); expect(schemasState.snapshot.schemas).toEqualIgnoringProps([updated, schema2]);
}); });
it('should notify if content migration has been started', () => {
schemasService.setup(x => x.postContentMigration(app, schema1))
.returns(() => of({})).verifiable();
schemasState.migrateContents(schema1).subscribe();
dialogs.verify(x => x.notifyInfo(It.isAnyString()), Times.once());
});
it('should not change schemas if content migration has been started', () => {
schemasService.setup(x => x.postContentMigration(app, schema1))
.returns(() => of({})).verifiable();
schemasState.migrateContents(schema1).subscribe();
expect(schemasState.snapshot.schemas).toEqualIgnoringProps([schema1, schema2]);
});
describe('with selection', () => { describe('with selection', () => {
beforeEach(() => { beforeEach(() => {
schemasService.setup(x => x.getSchema(app, schema1.name)) schemasService.setup(x => x.getSchema(app, schema1.name))

8
frontend/src/app/shared/state/schemas.state.ts

@ -175,6 +175,14 @@ export class SchemasState extends State<Snapshot> {
shareSubscribed(this.dialogs)); shareSubscribed(this.dialogs));
} }
public migrateContents(schema: SchemaDto): Observable<any> {
return this.schemasService.postContentMigration(this.appName, schema).pipe(
tap(() => {
this.dialogs.notifyInfo('i18n:schemas.migrateContentsStarted');
}),
shareSubscribed(this.dialogs));
}
public addCategory(name: string) { public addCategory(name: string) {
this.next(s => { this.next(s => {
const categories = new Set([...s.addedCategories, name]); const categories = new Set([...s.addedCategories, name]);

100
tools/TestSuite/TestSuite.ApiTests/ContentMigrationTests.cs

@ -0,0 +1,100 @@
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Squidex.ClientLibrary;
using TestSuite.Fixtures;
using TestSuite.Model;
#pragma warning disable SA1300 // Element should begin with upper-case letter
#pragma warning disable SA1507 // Code should not contain multiple blank lines in a row
namespace TestSuite.ApiTests;
public class ContentMigrationTests(ClientFixture fixture) : IClassFixture<ClientFixture>
{
private readonly string appName = Guid.NewGuid().ToString();
private readonly string schemaName = $"schema-{Guid.NewGuid()}";
public ClientFixture _ { get; } = fixture;
[Fact]
public async Task Should_migrate_contents_with_invalid_values()
{
// STEP 0: Create app, because jobs cannot run in parallel within the same app.
var (app, _) = await _.PostAppAsync(appName);
// STEP 1: Create a schema.
var schema = await TestEntity.CreateSchemaAsync(app.Schemas, schemaName);
var contents = app.Contents<TestEntity, TestEntityData>(schemaName);
// STEP 2: Create a content that becomes invalid and a content that stays valid.
var contentInvalid_1 = await contents.CreateAsync(
new TestEntityData
{
String = "hello",
},
ContentCreateOptions.AsPublish);
var contentValid_1 = await contents.CreateAsync(
new TestEntityData
{
Number = 42,
},
ContentCreateOptions.AsPublish);
// STEP 3: Change the type of the field, so that the stored value is not valid anymore.
await app.Schemas.DeleteFieldAsync(schemaName, schema.Fields.First(x => x.Name == TestEntityData.StringField).FieldId);
await app.Schemas.PostFieldAsync(schemaName, new AddFieldDto
{
Name = TestEntityData.StringField,
Properties = new NumberFieldPropertiesDto
{
IsRequired = false,
},
});
// STEP 4: Start the migration.
await app.Schemas.PostContentMigrationAsync(schemaName);
// STEP 5: Wait for the migration to complete.
var job = await app.Jobs.PollAsync(x => x.TaskName == "migrateContents" && x.Status is JobStatus.Completed or JobStatus.Failed);
Assert.Equal(JobStatus.Completed, job?.Status);
Assert.Equal("Checked contents: 2, updated: 1", Assert.Single(job!.Log).Message);
// STEP 6: Only the invalid content has been updated.
var contentInvalid_2 = await contents.GetAsync(contentInvalid_1.Id);
var contentValid_2 = await contents.GetAsync(contentValid_1.Id);
Assert.Equal(contentInvalid_1.Version + 1, contentInvalid_2.Version);
Assert.Equal(contentValid_1.Version, contentValid_2.Version);
}
[Fact]
public async Task Should_not_start_migration_for_unknown_schema()
{
// STEP 0: Create app.
var (app, _) = await _.PostAppAsync(appName);
// STEP 1: Start the migration.
var ex = await Assert.ThrowsAnyAsync<SquidexException>(() =>
{
return app.Schemas.PostContentMigrationAsync(schemaName);
});
Assert.Equal(404, ex.StatusCode);
}
}

6
tools/TestSuite/TestSuite.ApiTests/Verify/AppCreationTests.Should_create_app_from_templates.verified.txt

@ -152,6 +152,9 @@
contents/create/publish: { contents/create/publish: {
Method: POST Method: POST
}, },
contents/migrate: {
Method: POST
},
delete: { delete: {
Method: DELETE Method: DELETE
}, },
@ -345,6 +348,9 @@
contents/create/publish: { contents/create/publish: {
Method: POST Method: POST
}, },
contents/migrate: {
Method: POST
},
delete: { delete: {
Method: DELETE Method: DELETE
}, },

3
tools/TestSuite/TestSuite.ApiTests/Verify/SchemaTests.Should_create_singleton_schema.verified.txt

@ -10,6 +10,9 @@
contents: { contents: {
Method: GET Method: GET
}, },
contents/migrate: {
Method: POST
},
delete: { delete: {
Method: DELETE Method: DELETE
}, },

3
tools/TestSuite/TestSuite.ApiTests/Verify/SchemaTests.Should_create_singleton_schema_with_obsolete_property.verified.txt

@ -10,6 +10,9 @@
contents: { contents: {
Method: GET Method: GET
}, },
contents/migrate: {
Method: POST
},
delete: { delete: {
Method: DELETE Method: DELETE
}, },

4
tools/TestSuite/TestSuite.Shared/TestSuite.Shared.csproj

@ -18,8 +18,8 @@
<PackageReference Include="Microsoft.Extensions.Configuration.Json" 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="RefactoringEssentials" Version="5.6.0" PrivateAssets="all" />
<PackageReference Include="Squidex.Assets" Version="8.0.0" /> <PackageReference Include="Squidex.Assets" Version="8.0.0" />
<PackageReference Include="Squidex.ClientLibrary" Version="22.2.0" /> <PackageReference Include="Squidex.ClientLibrary" Version="22.3.0" />
<PackageReference Include="Squidex.ClientLibrary.ServiceExtensions" Version="22.2.0" /> <PackageReference Include="Squidex.ClientLibrary.ServiceExtensions" Version="22.3.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" /> <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
<PackageReference Include="Verify" Version="31.12.5" /> <PackageReference Include="Verify" Version="31.12.5" />
<PackageReference Include="xunit.v3.extensibility.core" Version="3.2.2" /> <PackageReference Include="xunit.v3.extensibility.core" Version="3.2.2" />

Loading…
Cancel
Save