mirror of https://github.com/Squidex/squidex.git
committed by
GitHub
34 changed files with 886 additions and 26 deletions
@ -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; |
|||
} |
|||
} |
|||
@ -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(); |
|||
} |
|||
} |
|||
@ -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 }; |
|||
} |
|||
} |
|||
@ -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 |
|||
@ -0,0 +1,3 @@ |
|||
<Solution> |
|||
<Project Path="Generator/Generator.csproj" /> |
|||
</Solution> |
|||
@ -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> |
|||
@ -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(); |
|||
} |
|||
} |
|||
@ -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); |
|||
} |
|||
} |
|||
Loading…
Reference in new issue