diff --git a/CLAUDE.md b/CLAUDE.md index 04a90f9a0..ff0af2c9c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -60,6 +60,10 @@ dotnet test --filter "Category!=Dependencies & Category!=TestContainer" - Do not comment a class or a method, only put comments inside functions or above variables. - Do not comment properties in general (for example event properties). Only comment behavior inside classes. - Exception: properties of API models (DTOs) keep their XML comments, because they are used for the OpenAPI documentation. +- 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 primary constructors whenever possible. ## Maintaining this file diff --git a/backend/.editorconfig b/backend/.editorconfig index 04394bcaa..abca6d2ff 100644 --- a/backend/.editorconfig +++ b/backend/.editorconfig @@ -10,6 +10,7 @@ indent_size = 4 [*.cs] charset = utf-8-bom insert_final_newline = true +trim_trailing_whitespace = true indent_style = space indent_size = 4 diff --git a/backend/extensions/Squidex.Extensions/Actions/CreateContent/CreateContentFlowStep.cs b/backend/extensions/Squidex.Extensions/Actions/CreateContent/CreateContentFlowStep.cs index 9d009b5ea..89126427b 100644 --- a/backend/extensions/Squidex.Extensions/Actions/CreateContent/CreateContentFlowStep.cs +++ b/backend/extensions/Squidex.Extensions/Actions/CreateContent/CreateContentFlowStep.cs @@ -104,7 +104,7 @@ public sealed record CreateContentFlowStep : FlowStep, IConvertibleToAction EnrichDefaults = true, EnrichRequiredFields = false, Patch = Patch, - Status = status + Status = status, }; } else diff --git a/backend/extensions/Squidex.Extensions/Text/Azure/CommandFactory.cs b/backend/extensions/Squidex.Extensions/Text/Azure/CommandFactory.cs index 7c75d6a59..b492a0763 100644 --- a/backend/extensions/Squidex.Extensions/Text/Azure/CommandFactory.cs +++ b/backend/extensions/Squidex.Extensions/Text/Azure/CommandFactory.cs @@ -92,7 +92,8 @@ public static class CommandFactory } } - if (upsert.Texts is { Count: > 0 }) + var weightedTexts = upsert.GetWeightedTexts(); + if (weightedTexts is { Count: > 0 }) { var document = new SearchDocument { @@ -106,7 +107,7 @@ public static class CommandFactory ["servePublished"] = upsert.ServePublished, }; - foreach (var (key, value) in upsert.Texts) + foreach (var (key, value) in weightedTexts) { var textMerged = value; var textLanguage = AzureIndexDefinition.GetFieldName(key); diff --git a/backend/extensions/Squidex.Extensions/Text/ElasticSearch/CommandFactory.cs b/backend/extensions/Squidex.Extensions/Text/ElasticSearch/CommandFactory.cs index 89bf8c197..0d0076911 100644 --- a/backend/extensions/Squidex.Extensions/Text/ElasticSearch/CommandFactory.cs +++ b/backend/extensions/Squidex.Extensions/Text/ElasticSearch/CommandFactory.cs @@ -103,11 +103,12 @@ public static class CommandFactory } } - if (upsert.Texts is { Count: > 0 }) + var weightedTexts = upsert.GetWeightedTexts(); + if (weightedTexts is { Count: > 0 }) { var texts = new Dictionary(); - foreach (var (key, value) in upsert.Texts) + foreach (var (key, value) in weightedTexts) { var textMerged = value; var textLanguage = ElasticSearchIndexDefinition.GetFieldName(key); diff --git a/backend/i18n/frontend_de.json b/backend/i18n/frontend_de.json index 7572c9c38..e6e4826cb 100644 --- a/backend/i18n/frontend_de.json +++ b/backend/i18n/frontend_de.json @@ -684,6 +684,11 @@ "jobs.restoreStoppedLabel": "Gestoppt", "jobs.restoreTitle": "Backup wiederherstellen", "jobs.started": "Job gestartet, es kann einige Minuten dauern.", + "jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.", + "jobs.textIndexConfirmTitle": "Rebuild Full Text Index", + "jobs.textIndexFailed": "Failed to start the rebuild of the full text index.", + "jobs.textIndexStart": "Rebuild Full Text Index", + "jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.", "languages.add": "Sprache hinzufügen", "languages.add.description": "Fügen Sie eine neue Sprache hinzu, die Sie für Ihre Inhalte unterstützen möchten.", "languages.add.title": "Eine neue Sprache hinzufügen", @@ -949,6 +954,13 @@ "schemas.field.placeholderHint": "Definieren Sie den Platzhalter für das Eingabesteuerelement.", "schemas.field.required": "Erforderlich", "schemas.field.requiredOnPublish": "Beim Veröffentlichen erforderlich", + "schemas.field.searchMode": "Full Text Search", + "schemas.field.searchModeDefault": "Default", + "schemas.field.searchModeExclude": "Exclude", + "schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.", + "schemas.field.searchModeTitle": "Title", + "schemas.field.searchPaths": "Search Paths", + "schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.", "schemas.field.show": "In API anzeigen", "schemas.field.tabCommon": "Allgemein", "schemas.field.tabEditing": "Bearbeitung", diff --git a/backend/i18n/frontend_en.json b/backend/i18n/frontend_en.json index fa40c36a5..ef4e094c1 100644 --- a/backend/i18n/frontend_en.json +++ b/backend/i18n/frontend_en.json @@ -684,6 +684,11 @@ "jobs.restoreStoppedLabel": "Stopped", "jobs.restoreTitle": "Restore Backup", "jobs.started": "Job started, it can take several minutes to complete.", + "jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.", + "jobs.textIndexConfirmTitle": "Rebuild Full Text Index", + "jobs.textIndexFailed": "Failed to start the rebuild of the full text index.", + "jobs.textIndexStart": "Rebuild Full Text Index", + "jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.", "languages.add": "Add Language", "languages.add.description": "Add a new language that you want to support for your content.", "languages.add.title": "Add a new Language", @@ -949,6 +954,13 @@ "schemas.field.placeholderHint": "Define the placeholder for the input control.", "schemas.field.required": "Required", "schemas.field.requiredOnPublish": "Required when publishing", + "schemas.field.searchMode": "Full Text Search", + "schemas.field.searchModeDefault": "Default", + "schemas.field.searchModeExclude": "Exclude", + "schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.", + "schemas.field.searchModeTitle": "Title", + "schemas.field.searchPaths": "Search Paths", + "schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.", "schemas.field.show": "Show in API", "schemas.field.tabCommon": "Common", "schemas.field.tabEditing": "Editing", diff --git a/backend/i18n/frontend_fr.json b/backend/i18n/frontend_fr.json index 08a5196dc..09858e29e 100644 --- a/backend/i18n/frontend_fr.json +++ b/backend/i18n/frontend_fr.json @@ -684,6 +684,11 @@ "jobs.restoreStoppedLabel": "Stopped", "jobs.restoreTitle": "Restore Backup", "jobs.started": "Job started, it can take several minutes to complete.", + "jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.", + "jobs.textIndexConfirmTitle": "Rebuild Full Text Index", + "jobs.textIndexFailed": "Failed to start the rebuild of the full text index.", + "jobs.textIndexStart": "Rebuild Full Text Index", + "jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.", "languages.add": "Ajouter une langue", "languages.add.description": "Ajoutez une nouvelle langue que vous souhaitez prendre en charge pour votre contenu.", "languages.add.title": "Ajouter une nouvelle langue", @@ -949,6 +954,13 @@ "schemas.field.placeholderHint": "Définissez l'espace réservé pour le contrôle d'entrée.", "schemas.field.required": "Requis", "schemas.field.requiredOnPublish": "Obligatoire lors de la publication", + "schemas.field.searchMode": "Full Text Search", + "schemas.field.searchModeDefault": "Default", + "schemas.field.searchModeExclude": "Exclude", + "schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.", + "schemas.field.searchModeTitle": "Title", + "schemas.field.searchPaths": "Search Paths", + "schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.", "schemas.field.show": "Afficher dans l'API", "schemas.field.tabCommon": "Commun", "schemas.field.tabEditing": "Édition", diff --git a/backend/i18n/frontend_it.json b/backend/i18n/frontend_it.json index 6645e8286..b8fe639f3 100644 --- a/backend/i18n/frontend_it.json +++ b/backend/i18n/frontend_it.json @@ -684,6 +684,11 @@ "jobs.restoreStoppedLabel": "Stopped", "jobs.restoreTitle": "Restore Backup", "jobs.started": "Job started, it can take several minutes to complete.", + "jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.", + "jobs.textIndexConfirmTitle": "Rebuild Full Text Index", + "jobs.textIndexFailed": "Failed to start the rebuild of the full text index.", + "jobs.textIndexStart": "Rebuild Full Text Index", + "jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.", "languages.add": "Aggiungi lingua", "languages.add.description": "Add a new language that you want to support for your content.", "languages.add.title": "Add a new Language", @@ -949,6 +954,13 @@ "schemas.field.placeholderHint": "Definisci il segnaposto per la verifica dell'input.", "schemas.field.required": "Obbligatorio", "schemas.field.requiredOnPublish": "Obbligatorio quando pubblichi", + "schemas.field.searchMode": "Full Text Search", + "schemas.field.searchModeDefault": "Default", + "schemas.field.searchModeExclude": "Exclude", + "schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.", + "schemas.field.searchModeTitle": "Title", + "schemas.field.searchPaths": "Search Paths", + "schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.", "schemas.field.show": "Mostra nelle API", "schemas.field.tabCommon": "Comune", "schemas.field.tabEditing": "Modifica", diff --git a/backend/i18n/frontend_nl.json b/backend/i18n/frontend_nl.json index 9f75a32dd..d902d9dbf 100644 --- a/backend/i18n/frontend_nl.json +++ b/backend/i18n/frontend_nl.json @@ -684,6 +684,11 @@ "jobs.restoreStoppedLabel": "Stopped", "jobs.restoreTitle": "Restore Backup", "jobs.started": "Job started, it can take several minutes to complete.", + "jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.", + "jobs.textIndexConfirmTitle": "Rebuild Full Text Index", + "jobs.textIndexFailed": "Failed to start the rebuild of the full text index.", + "jobs.textIndexStart": "Rebuild Full Text Index", + "jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.", "languages.add": "Taal toevoegen", "languages.add.description": "Voeg een nieuwe taal toe die u wilt ondersteunen voor uw inhoud.", "languages.add.title": "Nieuwe taal toevoegen", @@ -949,6 +954,13 @@ "schemas.field.placeholderHint": "Definieer de tijdelijke aanduiding voor het invoerbesturingselement.", "schemas.field.required": "Vereist", "schemas.field.requiredOnPublish": "Verplicht bij het publiceren", + "schemas.field.searchMode": "Full Text Search", + "schemas.field.searchModeDefault": "Default", + "schemas.field.searchModeExclude": "Exclude", + "schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.", + "schemas.field.searchModeTitle": "Title", + "schemas.field.searchPaths": "Search Paths", + "schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.", "schemas.field.show": "Weergeven in API", "schemas.field.tabCommon": "Algemeen", "schemas.field.tabEditing": "Bewerken", diff --git a/backend/i18n/frontend_pt.json b/backend/i18n/frontend_pt.json index 582f90480..b0db79d75 100644 --- a/backend/i18n/frontend_pt.json +++ b/backend/i18n/frontend_pt.json @@ -684,6 +684,11 @@ "jobs.restoreStoppedLabel": "Stopped", "jobs.restoreTitle": "Restore Backup", "jobs.started": "Job started, it can take several minutes to complete.", + "jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.", + "jobs.textIndexConfirmTitle": "Rebuild Full Text Index", + "jobs.textIndexFailed": "Failed to start the rebuild of the full text index.", + "jobs.textIndexStart": "Rebuild Full Text Index", + "jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.", "languages.add": "Adicionar linguagem", "languages.add.description": "Adicione um novo idioma que pretende apoiar para o seu conteúdo.", "languages.add.title": "Adicione uma nova linguagem", @@ -949,6 +954,13 @@ "schemas.field.placeholderHint": "Defina o espaço reservado para o controlo de entrada.", "schemas.field.required": "Necessário", "schemas.field.requiredOnPublish": "Necessário na publicação", + "schemas.field.searchMode": "Full Text Search", + "schemas.field.searchModeDefault": "Default", + "schemas.field.searchModeExclude": "Exclude", + "schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.", + "schemas.field.searchModeTitle": "Title", + "schemas.field.searchPaths": "Search Paths", + "schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.", "schemas.field.show": "Espetáculo em API", "schemas.field.tabCommon": "Comum", "schemas.field.tabEditing": "Edição", diff --git a/backend/i18n/frontend_zh.json b/backend/i18n/frontend_zh.json index f7430b53c..d75a06f8e 100644 --- a/backend/i18n/frontend_zh.json +++ b/backend/i18n/frontend_zh.json @@ -684,6 +684,11 @@ "jobs.restoreStoppedLabel": "Stopped", "jobs.restoreTitle": "Restore Backup", "jobs.started": "Job started, it can take several minutes to complete.", + "jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.", + "jobs.textIndexConfirmTitle": "Rebuild Full Text Index", + "jobs.textIndexFailed": "Failed to start the rebuild of the full text index.", + "jobs.textIndexStart": "Rebuild Full Text Index", + "jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.", "languages.add": "添加语言", "languages.add.description": "Add a new language that you want to support for your content.", "languages.add.title": "Add a new Language", @@ -949,6 +954,13 @@ "schemas.field.placeholderHint": "定义输入控件的占位符。", "schemas.field.required": "Required", "schemas.field.requiredOnPublish": "发布时需要", + "schemas.field.searchMode": "Full Text Search", + "schemas.field.searchModeDefault": "Default", + "schemas.field.searchModeExclude": "Exclude", + "schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.", + "schemas.field.searchModeTitle": "Title", + "schemas.field.searchPaths": "Search Paths", + "schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.", "schemas.field.show": "在 API 中显示", "schemas.field.tabCommon": "通用", "schemas.field.tabEditing": "Editing", diff --git a/backend/i18n/source/frontend_en.json b/backend/i18n/source/frontend_en.json index fa40c36a5..ef4e094c1 100644 --- a/backend/i18n/source/frontend_en.json +++ b/backend/i18n/source/frontend_en.json @@ -684,6 +684,11 @@ "jobs.restoreStoppedLabel": "Stopped", "jobs.restoreTitle": "Restore Backup", "jobs.started": "Job started, it can take several minutes to complete.", + "jobs.textIndexConfirmText": "Do you really want to rebuild the full text index of this app? It updates all contents with the current search settings and can take a while for large apps.", + "jobs.textIndexConfirmTitle": "Rebuild Full Text Index", + "jobs.textIndexFailed": "Failed to start the rebuild of the full text index.", + "jobs.textIndexStart": "Rebuild Full Text Index", + "jobs.textIndexTooltip": "Rebuilds the full text index with the current search settings of the schemas.", "languages.add": "Add Language", "languages.add.description": "Add a new language that you want to support for your content.", "languages.add.title": "Add a new Language", @@ -949,6 +954,13 @@ "schemas.field.placeholderHint": "Define the placeholder for the input control.", "schemas.field.required": "Required", "schemas.field.requiredOnPublish": "Required when publishing", + "schemas.field.searchMode": "Full Text Search", + "schemas.field.searchModeDefault": "Default", + "schemas.field.searchModeExclude": "Exclude", + "schemas.field.searchModeHint": "Defines how the field is used by the full text search. Matches in title fields are ranked higher. By default, the fields shown in references or lists are titles. Changes only apply to contents that are saved afterwards, rebuild the full text index in the jobs settings to update existing contents.", + "schemas.field.searchModeTitle": "Title", + "schemas.field.searchPaths": "Search Paths", + "schemas.field.searchPathsHint": "Optional paths to the values that are indexed for the full text search, for example 'items.label'. Arrays are traversed automatically. Leave it empty to index all texts.", "schemas.field.show": "Show in API", "schemas.field.tabCommon": "Common", "schemas.field.tabEditing": "Editing", diff --git a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentEntity.cs b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentEntity.cs index 8d35fbe07..778bf6769 100644 --- a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentEntity.cs +++ b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/EFContentEntity.cs @@ -188,7 +188,7 @@ public record EFContentEntity : Content, IVersionedEntity if (data.CanHaveReference()) { - var components = await appProvider.GetComponentsAsync(schema, ct); + var components = await appProvider.GetComponentsAsync(schema, ct: ct); data.AddReferencedIds(schema, referencedIds, components); } diff --git a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/Text/EFTextIndex.cs b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/Text/EFTextIndex.cs index d859f60ba..13ca6d5df 100644 --- a/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/Text/EFTextIndex.cs +++ b/backend/src/Squidex.Data.EntityFramework/Domain/Apps/Entities/Contents/Text/EFTextIndex.cs @@ -243,7 +243,8 @@ public sealed class EFTextIndex(IDbContextFactory dbContextF switch (command) { case UpsertIndexEntry upsert: - if (upsert.Texts != null) + var weightedTexts = upsert.GetWeightedTexts(); + if (weightedTexts != null) { insertsText.Add(new EFTextIndexTextEntity { @@ -254,7 +255,7 @@ public sealed class EFTextIndex(IDbContextFactory dbContextF ServeAll = upsert.ServeAll, ServePublished = upsert.ServePublished, Stage = upsert.Stage, - Texts = Tokenizer.Terms(upsert.Texts), + Texts = Tokenizer.Terms(weightedTexts), }); } diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/20260928113636_AddTextStateVersion.Designer.cs b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/20260928113636_AddTextStateVersion.Designer.cs new file mode 100644 index 000000000..389bac3e4 --- /dev/null +++ b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/20260928113636_AddTextStateVersion.Designer.cs @@ -0,0 +1,1668 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using NetTopologySuite.Geometries; +using Squidex.Providers.MySql.App; + +#nullable disable + +namespace Squidex.Providers.MySql.App.Migrations +{ + [DbContext(typeof(MySqlAppDbContext))] + [Migration("20260928113636_AddTextStateVersion")] + partial class AddTextStateVersion + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.6") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("longtext"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LockoutEnd") + .HasColumnType("datetime(6)"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("longtext"); + + b.Property("PhoneNumber") + .HasColumnType("longtext"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("tinyint(1)"); + + b.Property("SecurityStamp") + .HasColumnType("longtext"); + + b.Property("TwoFactorEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("longtext"); + + b.Property("ClaimValue") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("ProviderKey") + .HasColumnType("varchar(255)"); + + b.Property("ProviderDisplayName") + .HasColumnType("longtext"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("RoleId") + .HasColumnType("varchar(255)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("varchar(255)"); + + b.Property("LoginProvider") + .HasColumnType("varchar(255)"); + + b.Property("Name") + .HasColumnType("varchar(255)"); + + b.Property("Value") + .HasColumnType("longtext"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreAuthorization", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("varchar(255)"); + + b.Property("ApplicationId") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyToken") + .IsConcurrencyToken() + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("CreationDate") + .HasColumnType("datetime(6)"); + + b.Property("Properties") + .HasColumnType("longtext"); + + b.Property("Scopes") + .HasColumnType("longtext"); + + b.Property("Status") + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("Subject") + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("Type") + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("ApplicationId", "Status", "Subject", "Type"); + + b.ToTable("OpenIddictAuthorizations", (string)null); + }); + + modelBuilder.Entity("OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("varchar(255)"); + + b.Property("ApplicationId") + .HasColumnType("varchar(255)"); + + b.Property("AuthorizationId") + .HasColumnType("varchar(255)"); + + b.Property("ConcurrencyToken") + .IsConcurrencyToken() + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("CreationDate") + .HasColumnType("datetime(6)"); + + b.Property("ExpirationDate") + .HasColumnType("datetime(6)"); + + b.Property("Payload") + .HasColumnType("longtext"); + + b.Property("Properties") + .HasColumnType("longtext"); + + b.Property("RedemptionDate") + .HasColumnType("datetime(6)"); + + b.Property("ReferenceId") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Status") + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("Subject") + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("Type") + .HasMaxLength(150) + .HasColumnType("varchar(150)"); + + b.HasKey("Id"); + + b.HasIndex("AuthorizationId"); + + b.HasIndex("ReferenceId") + .IsUnique(); + + b.HasIndex("ApplicationId", "Status", "Subject", "Type") + .HasAnnotation("MySql:IndexPrefixLength", new[] { 0, 0, 0, 50 }); + + b.ToTable("OpenIddictTokens", (string)null); + }); + + modelBuilder.Entity("Squidex.AI.EntityFramework.EFChatEntity", b => + { + b.Property("Id") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("LastUpdated") + .HasColumnType("datetime(6)"); + + b.Property("LastVersion") + .IsConcurrencyToken() + .HasColumnType("char(36)") + .HasColumnName("Version"); + + b.Property("Value") + .IsRequired() + .HasColumnType("longtext"); + + b.HasKey("Id"); + + b.HasIndex("LastUpdated"); + + b.ToTable("Chats", (string)null); + }); + + modelBuilder.Entity("Squidex.Assets.EntityFramework.EFAssetKeyValueEntity", b => + { + b.Property("Key") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("Value") + .IsRequired() + .HasColumnType("longtext"); + + b.HasKey("Key"); + + b.HasIndex("Expires"); + + b.ToTable("AssetKeyValueStore_TusMetadata", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Core.Scripting.ScriptLogRecord", b => + { + b.Property("Id") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Entries") + .IsRequired() + .HasColumnType("json"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Timestamp") + .HasColumnType("datetime(6)"); + + b.Property("TotalEntries") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("Timestamp"); + + b.HasIndex("AppId", "Timestamp"); + + b.ToTable("ScriptLogs", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Apps.EFAppEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Document") + .HasColumnType("json"); + + b.Property("IndexedCreated") + .HasColumnType("datetime(6)") + .HasColumnName("Created"); + + b.Property("IndexedDeleted") + .HasColumnType("tinyint(1)") + .HasColumnName("Deleted"); + + b.Property("IndexedName") + .IsRequired() + .HasColumnType("longtext") + .HasColumnName("Name"); + + b.Property("IndexedTeamId") + .HasMaxLength(255) + .HasColumnType("varchar(255)") + .HasColumnName("TeamId"); + + b.Property("IndexedUserIds") + .IsRequired() + .HasColumnType("longtext") + .HasColumnName("UserIds"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_App", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Assets.EFAssetEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("FileHash") + .HasColumnType("longtext"); + + b.Property("FileName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("FileSize") + .HasColumnType("bigint"); + + b.Property("FileVersion") + .HasColumnType("bigint"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IsDeleted") + .HasColumnType("tinyint(1)"); + + b.Property("IsProtected") + .HasColumnType("tinyint(1)"); + + b.Property("LastModified") + .HasColumnType("datetime(6)"); + + b.Property("LastModifiedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Metadata") + .IsRequired() + .HasColumnType("json"); + + b.Property("MimeType") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("ParentId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Slug") + .HasColumnType("longtext"); + + b.Property("Tags") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("TotalSize") + .HasColumnType("bigint"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.HasIndex("IndexedAppId", "Id"); + + b.ToTable("Assets"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Assets.EFAssetFolderEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("FolderName") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IsDeleted") + .HasColumnType("tinyint(1)"); + + b.Property("LastModified") + .HasColumnType("datetime(6)"); + + b.Property("LastModifiedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("ParentId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.HasIndex("IndexedAppId", "Id"); + + b.ToTable("AssetFolders"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.EFContentCompleteEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Data") + .IsRequired() + .HasColumnType("json"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IndexedSchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IsDeleted") + .HasColumnType("tinyint(1)"); + + b.Property("LastModified") + .HasColumnType("datetime(6)"); + + b.Property("LastModifiedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("NewData") + .HasColumnType("json"); + + b.Property("NewStatus") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("ScheduleJob") + .HasColumnType("json"); + + b.Property("ScheduledAt") + .HasColumnType("datetime(6)"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("TranslationStatus") + .HasColumnType("json"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("ContentsAll", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.EFContentPublishedEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Data") + .IsRequired() + .HasColumnType("json"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IndexedSchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IsDeleted") + .HasColumnType("tinyint(1)"); + + b.Property("LastModified") + .HasColumnType("datetime(6)"); + + b.Property("LastModifiedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("NewData") + .HasColumnType("json"); + + b.Property("NewStatus") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("ScheduleJob") + .HasColumnType("json"); + + b.Property("ScheduledAt") + .HasColumnType("datetime(6)"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("TranslationStatus") + .HasColumnType("json"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("ContentsPublished", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.EFContentTableEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("AppId", "SchemaId") + .IsUnique(); + + b.ToTable("ContentTables", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.EFReferenceCompleteEntity", b => + { + b.Property("AppId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("FromKey") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("ToId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("FromSchema") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(255) + .HasColumnType("varchar(255)") + .HasDefaultValue("00000000-0000-0000-0000-000000000000"); + + b.HasKey("AppId", "FromKey", "ToId"); + + b.ToTable("ContentReferencesAll", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.EFReferencePublishedEntity", b => + { + b.Property("AppId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("FromKey") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("ToId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("FromSchema") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(255) + .HasColumnType("varchar(255)") + .HasDefaultValue("00000000-0000-0000-0000-000000000000"); + + b.HasKey("AppId", "FromKey", "ToId"); + + b.ToTable("ContentReferencesPublished", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.Text.EFTextIndexGeoEntity", b => + { + b.Property("Id") + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("ContentId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("GeoField") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("GeoObject") + .IsRequired() + .HasColumnType("geometry"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("ServeAll") + .HasColumnType("tinyint(1)"); + + b.Property("ServePublished") + .HasColumnType("tinyint(1)"); + + b.Property("Stage") + .HasColumnType("tinyint unsigned"); + + b.HasKey("Id"); + + b.ToTable("Geos"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.Text.EFTextIndexTextEntity", b => + { + b.Property("Id") + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("ContentId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("ServeAll") + .HasColumnType("tinyint(1)"); + + b.Property("ServePublished") + .HasColumnType("tinyint(1)"); + + b.Property("Stage") + .HasColumnType("tinyint unsigned"); + + b.Property("Texts") + .IsRequired() + .HasColumnType("longtext"); + + b.HasKey("Id"); + + b.ToTable("Texts"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.Text.EFTextIndexUserInfoEntity", b => + { + b.Property("Id") + .HasMaxLength(400) + .HasColumnType("varchar(400)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("ContentId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("ServeAll") + .HasColumnType("tinyint(1)"); + + b.Property("ServePublished") + .HasColumnType("tinyint(1)"); + + b.Property("Stage") + .HasColumnType("tinyint unsigned"); + + b.Property("UserInfoApiKey") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("UserInfoRole") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("UserInfoApiKey"); + + b.ToTable("UserInfos"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.Text.State.TextContentState", b => + { + b.Property("UniqueContentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("State") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("UniqueContentId"); + + b.ToTable("TextState", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.History.HistoryEvent", b => + { + b.Property("Id") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Actor") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Channel") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("EventType") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("OwnerId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Parameters") + .IsRequired() + .HasColumnType("json"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.ToTable("HistoryEvent"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Rules.EFRuleEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Document") + .HasColumnType("json"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)") + .HasColumnName("AppId"); + + b.Property("IndexedDeleted") + .HasColumnType("tinyint(1)") + .HasColumnName("Deleted"); + + b.Property("IndexedId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)") + .HasColumnName("Id"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Rule", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Schemas.EFSchemaEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Document") + .HasColumnType("json"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)") + .HasColumnName("AppId"); + + b.Property("IndexedDeleted") + .HasColumnType("tinyint(1)") + .HasColumnName("Deleted"); + + b.Property("IndexedId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)") + .HasColumnName("Id"); + + b.Property("IndexedName") + .IsRequired() + .HasColumnType("longtext") + .HasColumnName("Name"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Schema", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Teams.EFTeamEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Document") + .HasColumnType("json"); + + b.Property("IndexedAuthDomain") + .HasColumnType("longtext") + .HasColumnName("AuthDomain"); + + b.Property("IndexedDeleted") + .HasColumnType("tinyint(1)") + .HasColumnName("Deleted"); + + b.Property("IndexedUserIds") + .IsRequired() + .HasColumnType("longtext") + .HasColumnName("UserIds"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Team", (string)null); + }); + + modelBuilder.Entity("Squidex.Events.EntityFramework.EFEventCommit", b => + { + b.Property("Id") + .HasColumnType("char(36)"); + + b.Property("EventStream") + .IsRequired() + .HasMaxLength(750) + .HasColumnType("varchar(750)"); + + b.Property("EventStreamOffset") + .HasColumnType("bigint"); + + b.PrimitiveCollection("Events") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("EventsCount") + .HasColumnType("bigint"); + + b.Property("Position") + .HasColumnType("bigint"); + + b.Property("Timestamp") + .HasColumnType("datetime(6)"); + + b.HasKey("Id"); + + b.HasIndex("EventStream", "EventStreamOffset") + .IsUnique(); + + b.HasIndex("EventStream", "Position"); + + b.HasIndex("EventStream", "Timestamp"); + + b.ToTable("Events"); + }); + + modelBuilder.Entity("Squidex.Events.EntityFramework.EFPosition", b => + { + b.Property("Id") + .HasColumnType("bigint"); + + b.Property("Position") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.ToTable("EventPosition"); + }); + + modelBuilder.Entity("Squidex.Flows.EntityFramework.EFCronJobEntity", b => + { + b.Property("Id") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Data") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("DueTime") + .HasColumnType("datetime(6)"); + + b.HasKey("Id"); + + b.HasIndex("DueTime"); + + b.ToTable("CronJobs", (string)null); + }); + + modelBuilder.Entity("Squidex.Flows.EntityFramework.EFFlowStateEntity", b => + { + b.Property("Id") + .HasColumnType("char(36)"); + + b.Property("Created") + .HasColumnType("datetime(6)"); + + b.Property("DefinitionId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("DueTime") + .HasColumnType("datetime(6)"); + + b.Property("OwnerId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("SchedulePartition") + .HasColumnType("int"); + + b.Property("State") + .IsRequired() + .HasColumnType("longtext"); + + b.HasKey("Id"); + + b.HasIndex("DueTime", "SchedulePartition"); + + b.ToTable("Flows", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.Caching.EFCacheEntity", b => + { + b.Property("Key") + .HasColumnType("varchar(255)"); + + b.Property("Expires") + .HasColumnType("datetime(6)"); + + b.Property("Value") + .IsRequired() + .HasColumnType("longblob"); + + b.HasKey("Key"); + + b.ToTable("Cache", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.Log.EFRequestEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("Key") + .IsRequired() + .HasColumnType("varchar(255)"); + + b.Property("Properties") + .IsRequired() + .HasColumnType("json"); + + b.Property("Timestamp") + .HasColumnType("datetime(6)"); + + b.HasKey("Id"); + + b.HasIndex("Key"); + + b.ToTable("Requests", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.Migrations.EFMigrationEntity", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("IsLocked") + .HasColumnType("tinyint(1)"); + + b.Property("Version") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Migrations", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Document") + .HasColumnType("json"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_UISettings", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Document") + .HasColumnType("json"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Index_TagHistory", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Document") + .HasColumnType("json"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_UsageNotifications", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Document") + .HasColumnType("json"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Counters", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Document") + .HasColumnType("json"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_JobsState", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Document") + .HasColumnType("json"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_UsageTracker", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Document") + .HasColumnType("json"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Index_Tags", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Document") + .HasColumnType("json"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Identity_Keys", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Document") + .HasColumnType("json"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Identity_Xml", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Document") + .HasColumnType("json"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_EventConsumerState", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Document") + .HasColumnType("json"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Names", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.UsageTracking.EFUsageCounterEntity", b => + { + b.Property("Key") + .HasColumnType("varchar(255)"); + + b.Property("Date") + .HasColumnType("datetime(6)"); + + b.Property("Category") + .HasColumnType("varchar(255)"); + + b.Property("CounterKey") + .HasColumnType("varchar(255)"); + + b.Property("CounterValue") + .HasColumnType("double"); + + b.HasKey("Key", "Date", "Category", "CounterKey"); + + b.ToTable("Counter", (string)null); + }); + + modelBuilder.Entity("Squidex.Messaging.EntityFramework.EFMessage", b => + { + b.Property("Id") + .HasColumnType("varchar(255)"); + + b.Property("ChannelName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("MessageData") + .IsRequired() + .HasColumnType("longblob"); + + b.Property("MessageHeaders") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("varchar(2000)"); + + b.Property("QueueName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("TimeHandled") + .HasColumnType("datetime(6)"); + + b.Property("TimeToLive") + .HasColumnType("datetime(6)"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.HasIndex("ChannelName", "TimeHandled"); + + b.ToTable("Messages", (string)null); + }); + + modelBuilder.Entity("Squidex.Messaging.EntityFramework.EFMessagingDataEntity", b => + { + b.Property("Group") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Key") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("Expiration") + .HasColumnType("datetime(6)"); + + b.Property("ValueData") + .IsRequired() + .HasColumnType("longblob"); + + b.Property("ValueFormat") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("ValueType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.HasKey("Group", "Key"); + + b.HasIndex("Expiration"); + + b.ToTable("MessagingData", (string)null); + }); + + modelBuilder.Entity("YDotNet.Server.EntityFramework.YDotNetDocument", b => + { + b.Property("Id") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Data") + .IsRequired() + .HasColumnType("longblob"); + + b.Property("Expiration") + .HasColumnType("datetime(6)"); + + b.HasKey("Id"); + + b.ToTable("YDotNetDocument", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreToken", b => + { + b.HasOne("OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreAuthorization", "Authorization") + .WithMany("Tokens") + .HasForeignKey("AuthorizationId"); + + b.Navigation("Authorization"); + }); + + modelBuilder.Entity("OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreAuthorization", b => + { + b.Navigation("Tokens"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/20260928113636_AddTextStateVersion.cs b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/20260928113636_AddTextStateVersion.cs new file mode 100644 index 000000000..f94e75e22 --- /dev/null +++ b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/20260928113636_AddTextStateVersion.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Squidex.Providers.MySql.App.Migrations +{ + /// + public partial class AddTextStateVersion : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Version", + table: "TextState", + type: "bigint", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "Version", + table: "TextState"); + } + } +} diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/MySqlDbContextModelSnapshot.cs b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/MySqlDbContextModelSnapshot.cs index 79a6d994a..f5ea0a67f 100644 --- a/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/MySqlDbContextModelSnapshot.cs +++ b/backend/src/Squidex.Data.EntityFramework/Providers/MySql/App/Migrations/MySqlDbContextModelSnapshot.cs @@ -981,6 +981,9 @@ namespace Squidex.Providers.MySql.Migrations .HasMaxLength(100) .HasColumnType("varchar(100)"); + b.Property("Version") + .HasColumnType("bigint"); + b.HasKey("UniqueContentId"); b.ToTable("TextState", (string)null); diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/20260928113645_AddTextStateVersion.Designer.cs b/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/20260928113645_AddTextStateVersion.Designer.cs new file mode 100644 index 000000000..62812926d --- /dev/null +++ b/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/20260928113645_AddTextStateVersion.Designer.cs @@ -0,0 +1,1668 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using NetTopologySuite.Geometries; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using Squidex.Providers.Postgres.App; + +#nullable disable + +namespace Squidex.Providers.Postgres.App.Migrations +{ + [DbContext(typeof(PostgresAppDbContext))] + [Migration("20260928113645_AddTextStateVersion")] + partial class AddTextStateVersion + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.6") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "postgis"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("AccessFailedCount") + .HasColumnType("integer"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("text"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("boolean"); + + b.Property("LockoutEnabled") + .HasColumnType("boolean"); + + b.Property("LockoutEnd") + .HasColumnType("timestamp with time zone"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("PasswordHash") + .HasColumnType("text"); + + b.Property("PhoneNumber") + .HasColumnType("text"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("boolean"); + + b.Property("SecurityStamp") + .HasColumnType("text"); + + b.Property("TwoFactorEnabled") + .HasColumnType("boolean"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("text"); + + b.Property("ClaimValue") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("ProviderKey") + .HasColumnType("text"); + + b.Property("ProviderDisplayName") + .HasColumnType("text"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("RoleId") + .HasColumnType("text"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("text"); + + b.Property("LoginProvider") + .HasColumnType("text"); + + b.Property("Name") + .HasColumnType("text"); + + b.Property("Value") + .HasColumnType("text"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreAuthorization", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("text"); + + b.Property("ApplicationId") + .HasColumnType("text"); + + b.Property("ConcurrencyToken") + .IsConcurrencyToken() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreationDate") + .HasColumnType("timestamp with time zone"); + + b.Property("Properties") + .HasColumnType("text"); + + b.Property("Scopes") + .HasColumnType("text"); + + b.Property("Status") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Subject") + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("Type") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.HasKey("Id"); + + b.HasIndex("ApplicationId", "Status", "Subject", "Type"); + + b.ToTable("OpenIddictAuthorizations", (string)null); + }); + + modelBuilder.Entity("OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("text"); + + b.Property("ApplicationId") + .HasColumnType("text"); + + b.Property("AuthorizationId") + .HasColumnType("text"); + + b.Property("ConcurrencyToken") + .IsConcurrencyToken() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("CreationDate") + .HasColumnType("timestamp with time zone"); + + b.Property("ExpirationDate") + .HasColumnType("timestamp with time zone"); + + b.Property("Payload") + .HasColumnType("text"); + + b.Property("Properties") + .HasColumnType("text"); + + b.Property("RedemptionDate") + .HasColumnType("timestamp with time zone"); + + b.Property("ReferenceId") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Status") + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Subject") + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("Type") + .HasMaxLength(150) + .HasColumnType("character varying(150)"); + + b.HasKey("Id"); + + b.HasIndex("AuthorizationId"); + + b.HasIndex("ReferenceId") + .IsUnique(); + + b.HasIndex("ApplicationId", "Status", "Subject", "Type"); + + b.ToTable("OpenIddictTokens", (string)null); + }); + + modelBuilder.Entity("Squidex.AI.EntityFramework.EFChatEntity", b => + { + b.Property("Id") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("LastUpdated") + .HasColumnType("timestamp with time zone"); + + b.Property("LastVersion") + .IsConcurrencyToken() + .HasColumnType("uuid") + .HasColumnName("Version"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("LastUpdated"); + + b.ToTable("Chats", (string)null); + }); + + modelBuilder.Entity("Squidex.Assets.EntityFramework.EFAssetKeyValueEntity", b => + { + b.Property("Key") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Key"); + + b.HasIndex("Expires"); + + b.ToTable("AssetKeyValueStore_TusMetadata", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Core.Scripting.ScriptLogRecord", b => + { + b.Property("Id") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Entries") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.Property("TotalEntries") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Timestamp"); + + b.HasIndex("AppId", "Timestamp"); + + b.ToTable("ScriptLogs", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Apps.EFAppEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Document") + .HasColumnType("jsonb"); + + b.Property("IndexedCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("Created"); + + b.Property("IndexedDeleted") + .HasColumnType("boolean") + .HasColumnName("Deleted"); + + b.Property("IndexedName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("Name"); + + b.Property("IndexedTeamId") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("TeamId"); + + b.Property("IndexedUserIds") + .IsRequired() + .HasColumnType("text") + .HasColumnName("UserIds"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_App", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Assets.EFAssetEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("FileHash") + .HasColumnType("text"); + + b.Property("FileName") + .IsRequired() + .HasColumnType("text"); + + b.Property("FileSize") + .HasColumnType("bigint"); + + b.Property("FileVersion") + .HasColumnType("bigint"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("IsProtected") + .HasColumnType("boolean"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("LastModifiedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Metadata") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("MimeType") + .IsRequired() + .HasColumnType("text"); + + b.Property("ParentId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Slug") + .HasColumnType("text"); + + b.Property("Tags") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("TotalSize") + .HasColumnType("bigint"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.HasIndex("IndexedAppId", "Id"); + + b.ToTable("Assets"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Assets.EFAssetFolderEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("FolderName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("LastModifiedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ParentId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.HasIndex("IndexedAppId", "Id"); + + b.ToTable("AssetFolders"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.EFContentCompleteEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Data") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("IndexedSchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("LastModifiedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("NewData") + .HasColumnType("jsonb"); + + b.Property("NewStatus") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ScheduleJob") + .HasColumnType("jsonb"); + + b.Property("ScheduledAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("TranslationStatus") + .HasColumnType("jsonb"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("ContentsAll", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.EFContentPublishedEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Data") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("IndexedSchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("IsDeleted") + .HasColumnType("boolean"); + + b.Property("LastModified") + .HasColumnType("timestamp with time zone"); + + b.Property("LastModifiedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("NewData") + .HasColumnType("jsonb"); + + b.Property("NewStatus") + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ScheduleJob") + .HasColumnType("jsonb"); + + b.Property("ScheduledAt") + .HasColumnType("timestamp with time zone"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("TranslationStatus") + .HasColumnType("jsonb"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("ContentsPublished", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.EFContentTableEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.HasKey("Id"); + + b.HasIndex("AppId", "SchemaId") + .IsUnique(); + + b.ToTable("ContentTables", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.EFReferenceCompleteEntity", b => + { + b.Property("AppId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("FromKey") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("ToId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("FromSchema") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasDefaultValue("00000000-0000-0000-0000-000000000000"); + + b.HasKey("AppId", "FromKey", "ToId"); + + b.ToTable("ContentReferencesAll", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.EFReferencePublishedEntity", b => + { + b.Property("AppId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("FromKey") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("ToId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("FromSchema") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasDefaultValue("00000000-0000-0000-0000-000000000000"); + + b.HasKey("AppId", "FromKey", "ToId"); + + b.ToTable("ContentReferencesPublished", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.Text.EFTextIndexGeoEntity", b => + { + b.Property("Id") + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("ContentId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("GeoField") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("GeoObject") + .IsRequired() + .HasColumnType("geometry"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("ServeAll") + .HasColumnType("boolean"); + + b.Property("ServePublished") + .HasColumnType("boolean"); + + b.Property("Stage") + .HasColumnType("smallint"); + + b.HasKey("Id"); + + b.ToTable("Geos"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.Text.EFTextIndexTextEntity", b => + { + b.Property("Id") + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("ContentId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("ServeAll") + .HasColumnType("boolean"); + + b.Property("ServePublished") + .HasColumnType("boolean"); + + b.Property("Stage") + .HasColumnType("smallint"); + + b.Property("Texts") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Texts"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.Text.EFTextIndexUserInfoEntity", b => + { + b.Property("Id") + .HasMaxLength(400) + .HasColumnType("character varying(400)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("ContentId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("ServeAll") + .HasColumnType("boolean"); + + b.Property("ServePublished") + .HasColumnType("boolean"); + + b.Property("Stage") + .HasColumnType("smallint"); + + b.Property("UserInfoApiKey") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("UserInfoRole") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.HasKey("Id"); + + b.HasIndex("UserInfoApiKey"); + + b.ToTable("UserInfos"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.Text.State.TextContentState", b => + { + b.Property("UniqueContentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("State") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("UniqueContentId"); + + b.ToTable("TextState", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.History.HistoryEvent", b => + { + b.Property("Id") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Actor") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("Channel") + .IsRequired() + .HasColumnType("text"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("EventType") + .IsRequired() + .HasColumnType("text"); + + b.Property("OwnerId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Parameters") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.ToTable("HistoryEvent"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Rules.EFRuleEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Document") + .HasColumnType("jsonb"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("AppId"); + + b.Property("IndexedDeleted") + .HasColumnType("boolean") + .HasColumnName("Deleted"); + + b.Property("IndexedId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("Id"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Rule", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Schemas.EFSchemaEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Document") + .HasColumnType("jsonb"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("AppId"); + + b.Property("IndexedDeleted") + .HasColumnType("boolean") + .HasColumnName("Deleted"); + + b.Property("IndexedId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("Id"); + + b.Property("IndexedName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("Name"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Schema", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Teams.EFTeamEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Document") + .HasColumnType("jsonb"); + + b.Property("IndexedAuthDomain") + .HasColumnType("text") + .HasColumnName("AuthDomain"); + + b.Property("IndexedDeleted") + .HasColumnType("boolean") + .HasColumnName("Deleted"); + + b.Property("IndexedUserIds") + .IsRequired() + .HasColumnType("text") + .HasColumnName("UserIds"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Team", (string)null); + }); + + modelBuilder.Entity("Squidex.Events.EntityFramework.EFEventCommit", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("EventStream") + .IsRequired() + .HasMaxLength(750) + .HasColumnType("character varying(750)"); + + b.Property("EventStreamOffset") + .HasColumnType("bigint"); + + b.PrimitiveCollection("Events") + .IsRequired() + .HasColumnType("text[]"); + + b.Property("EventsCount") + .HasColumnType("bigint"); + + b.Property("Position") + .HasColumnType("bigint"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("EventStream", "EventStreamOffset") + .IsUnique(); + + b.HasIndex("EventStream", "Position"); + + b.HasIndex("EventStream", "Timestamp"); + + b.ToTable("Events"); + }); + + modelBuilder.Entity("Squidex.Events.EntityFramework.EFPosition", b => + { + b.Property("Id") + .HasColumnType("bigint"); + + b.Property("Position") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.ToTable("EventPosition"); + }); + + modelBuilder.Entity("Squidex.Flows.EntityFramework.EFCronJobEntity", b => + { + b.Property("Id") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Data") + .IsRequired() + .HasColumnType("text"); + + b.Property("DueTime") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("DueTime"); + + b.ToTable("CronJobs", (string)null); + }); + + modelBuilder.Entity("Squidex.Flows.EntityFramework.EFFlowStateEntity", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("Created") + .HasColumnType("timestamp with time zone"); + + b.Property("DefinitionId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("DueTime") + .HasColumnType("timestamp with time zone"); + + b.Property("OwnerId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("SchedulePartition") + .HasColumnType("integer"); + + b.Property("State") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("DueTime", "SchedulePartition"); + + b.ToTable("Flows", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.Caching.EFCacheEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("Expires") + .HasColumnType("timestamp with time zone"); + + b.Property("Value") + .IsRequired() + .HasColumnType("bytea"); + + b.HasKey("Key"); + + b.ToTable("Cache", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.Log.EFRequestEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Key") + .IsRequired() + .HasColumnType("text"); + + b.Property("Properties") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Key"); + + b.ToTable("Requests", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.Migrations.EFMigrationEntity", b => + { + b.Property("Id") + .HasColumnType("integer"); + + b.Property("IsLocked") + .HasColumnType("boolean"); + + b.Property("Version") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("Migrations", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Document") + .HasColumnType("jsonb"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_UISettings", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Document") + .HasColumnType("jsonb"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Index_TagHistory", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Document") + .HasColumnType("jsonb"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_UsageNotifications", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Document") + .HasColumnType("jsonb"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Counters", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Document") + .HasColumnType("jsonb"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_JobsState", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Document") + .HasColumnType("jsonb"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_UsageTracker", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Document") + .HasColumnType("jsonb"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Index_Tags", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Document") + .HasColumnType("jsonb"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Identity_Keys", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Document") + .HasColumnType("jsonb"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Identity_Xml", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Document") + .HasColumnType("jsonb"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_EventConsumerState", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Document") + .HasColumnType("jsonb"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Names", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.UsageTracking.EFUsageCounterEntity", b => + { + b.Property("Key") + .HasColumnType("text"); + + b.Property("Date") + .HasColumnType("timestamp with time zone"); + + b.Property("Category") + .HasColumnType("text"); + + b.Property("CounterKey") + .HasColumnType("text"); + + b.Property("CounterValue") + .HasColumnType("double precision"); + + b.HasKey("Key", "Date", "Category", "CounterKey"); + + b.ToTable("Counter", (string)null); + }); + + modelBuilder.Entity("Squidex.Messaging.EntityFramework.EFMessage", b => + { + b.Property("Id") + .HasColumnType("text"); + + b.Property("ChannelName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("MessageData") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("MessageHeaders") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("QueueName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("TimeHandled") + .HasColumnType("timestamp with time zone"); + + b.Property("TimeToLive") + .HasColumnType("timestamp with time zone"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ChannelName", "TimeHandled"); + + b.ToTable("Messages", (string)null); + }); + + modelBuilder.Entity("Squidex.Messaging.EntityFramework.EFMessagingDataEntity", b => + { + b.Property("Group") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Key") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("Expiration") + .HasColumnType("timestamp with time zone"); + + b.Property("ValueData") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("ValueFormat") + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.Property("ValueType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)"); + + b.HasKey("Group", "Key"); + + b.HasIndex("Expiration"); + + b.ToTable("MessagingData", (string)null); + }); + + modelBuilder.Entity("YDotNet.Server.EntityFramework.YDotNetDocument", b => + { + b.Property("Id") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("Data") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("Expiration") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.ToTable("YDotNetDocument", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreToken", b => + { + b.HasOne("OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreAuthorization", "Authorization") + .WithMany("Tokens") + .HasForeignKey("AuthorizationId"); + + b.Navigation("Authorization"); + }); + + modelBuilder.Entity("OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreAuthorization", b => + { + b.Navigation("Tokens"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/20260928113645_AddTextStateVersion.cs b/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/20260928113645_AddTextStateVersion.cs new file mode 100644 index 000000000..15b57afd7 --- /dev/null +++ b/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/20260928113645_AddTextStateVersion.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Squidex.Providers.Postgres.App.Migrations +{ + /// + public partial class AddTextStateVersion : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Version", + table: "TextState", + type: "bigint", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "Version", + table: "TextState"); + } + } +} diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/PostgresDbContextModelSnapshot.cs b/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/PostgresDbContextModelSnapshot.cs index 13631a53e..26d350e93 100644 --- a/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/PostgresDbContextModelSnapshot.cs +++ b/backend/src/Squidex.Data.EntityFramework/Providers/Postgres/App/Migrations/PostgresDbContextModelSnapshot.cs @@ -981,6 +981,9 @@ namespace Squidex.Providers.Postgres.Migrations .HasMaxLength(100) .HasColumnType("character varying(100)"); + b.Property("Version") + .HasColumnType("bigint"); + b.HasKey("UniqueContentId"); b.ToTable("TextState", (string)null); diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/20260928113653_AddTextStateVersion.Designer.cs b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/20260928113653_AddTextStateVersion.Designer.cs new file mode 100644 index 000000000..0473e2880 --- /dev/null +++ b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/20260928113653_AddTextStateVersion.Designer.cs @@ -0,0 +1,1670 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using NetTopologySuite.Geometries; +using Squidex.Providers.SqlServer.App; + +#nullable disable + +namespace Squidex.Providers.SqlServer.App.Migrations +{ + [DbContext(typeof(SqlServerAppDbContext))] + [Migration("20260928113653_AddTextStateVersion")] + partial class AddTextStateVersion + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.6") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex") + .HasFilter("[NormalizedName] IS NOT NULL"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("AccessFailedCount") + .HasColumnType("int"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("EmailConfirmed") + .HasColumnType("bit"); + + b.Property("LockoutEnabled") + .HasColumnType("bit"); + + b.Property("LockoutEnd") + .HasColumnType("datetimeoffset"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("PasswordHash") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumber") + .HasColumnType("nvarchar(max)"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("bit"); + + b.Property("SecurityStamp") + .HasColumnType("nvarchar(max)"); + + b.Property("TwoFactorEnabled") + .HasColumnType("bit"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex") + .HasFilter("[NormalizedUserName] IS NOT NULL"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClaimType") + .HasColumnType("nvarchar(max)"); + + b.Property("ClaimValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderKey") + .HasColumnType("nvarchar(450)"); + + b.Property("ProviderDisplayName") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("RoleId") + .HasColumnType("nvarchar(450)"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("nvarchar(450)"); + + b.Property("LoginProvider") + .HasColumnType("nvarchar(450)"); + + b.Property("Name") + .HasColumnType("nvarchar(450)"); + + b.Property("Value") + .HasColumnType("nvarchar(max)"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreAuthorization", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("nvarchar(450)"); + + b.Property("ApplicationId") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyToken") + .IsConcurrencyToken() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("CreationDate") + .HasColumnType("datetime2"); + + b.Property("Properties") + .HasColumnType("nvarchar(max)"); + + b.Property("Scopes") + .HasColumnType("nvarchar(max)"); + + b.Property("Status") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Subject") + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("Type") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("ApplicationId", "Status", "Subject", "Type"); + + b.ToTable("OpenIddictAuthorizations", (string)null); + }); + + modelBuilder.Entity("OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("nvarchar(450)"); + + b.Property("ApplicationId") + .HasColumnType("nvarchar(450)"); + + b.Property("AuthorizationId") + .HasColumnType("nvarchar(450)"); + + b.Property("ConcurrencyToken") + .IsConcurrencyToken() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("CreationDate") + .HasColumnType("datetime2"); + + b.Property("ExpirationDate") + .HasColumnType("datetime2"); + + b.Property("Payload") + .HasColumnType("nvarchar(max)"); + + b.Property("Properties") + .HasColumnType("nvarchar(max)"); + + b.Property("RedemptionDate") + .HasColumnType("datetime2"); + + b.Property("ReferenceId") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Status") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Subject") + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("Type") + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.HasKey("Id"); + + b.HasIndex("AuthorizationId"); + + b.HasIndex("ReferenceId") + .IsUnique() + .HasFilter("[ReferenceId] IS NOT NULL"); + + b.HasIndex("ApplicationId", "Status", "Subject", "Type"); + + b.ToTable("OpenIddictTokens", (string)null); + }); + + modelBuilder.Entity("Squidex.AI.EntityFramework.EFChatEntity", b => + { + b.Property("Id") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("LastUpdated") + .HasColumnType("datetime2"); + + b.Property("LastVersion") + .IsConcurrencyToken() + .HasColumnType("uniqueidentifier") + .HasColumnName("Version"); + + b.Property("Value") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("LastUpdated"); + + b.ToTable("Chats", (string)null); + }); + + modelBuilder.Entity("Squidex.Assets.EntityFramework.EFAssetKeyValueEntity", b => + { + b.Property("Key") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Expires") + .HasColumnType("datetimeoffset"); + + b.Property("Value") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Key"); + + b.HasIndex("Expires"); + + b.ToTable("AssetKeyValueStore_TusMetadata", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Core.Scripting.ScriptLogRecord", b => + { + b.Property("Id") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Entries") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Timestamp") + .HasColumnType("datetimeoffset"); + + b.Property("TotalEntries") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("Timestamp"); + + b.HasIndex("AppId", "Timestamp"); + + b.ToTable("ScriptLogs", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Apps.EFAppEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Document") + .HasColumnType("nvarchar(max)"); + + b.Property("IndexedCreated") + .HasColumnType("datetimeoffset") + .HasColumnName("Created"); + + b.Property("IndexedDeleted") + .HasColumnType("bit") + .HasColumnName("Deleted"); + + b.Property("IndexedName") + .IsRequired() + .HasColumnType("nvarchar(max)") + .HasColumnName("Name"); + + b.Property("IndexedTeamId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)") + .HasColumnName("TeamId"); + + b.Property("IndexedUserIds") + .IsRequired() + .HasColumnType("nvarchar(max)") + .HasColumnName("UserIds"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_App", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Assets.EFAssetEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Created") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("FileHash") + .HasColumnType("nvarchar(max)"); + + b.Property("FileName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("FileSize") + .HasColumnType("bigint"); + + b.Property("FileVersion") + .HasColumnType("bigint"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("IsProtected") + .HasColumnType("bit"); + + b.Property("LastModified") + .HasColumnType("datetimeoffset"); + + b.Property("LastModifiedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Metadata") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("MimeType") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ParentId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Slug") + .HasColumnType("nvarchar(max)"); + + b.Property("Tags") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("nvarchar(1000)"); + + b.Property("TotalSize") + .HasColumnType("bigint"); + + b.Property("Type") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.HasIndex("IndexedAppId", "Id"); + + b.ToTable("Assets"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Assets.EFAssetFolderEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Created") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("FolderName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("LastModified") + .HasColumnType("datetimeoffset"); + + b.Property("LastModifiedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ParentId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.HasIndex("IndexedAppId", "Id"); + + b.ToTable("AssetFolders"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.EFContentCompleteEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Created") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Data") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("IndexedSchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("LastModified") + .HasColumnType("datetimeoffset"); + + b.Property("LastModifiedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("NewData") + .HasColumnType("nvarchar(max)"); + + b.Property("NewStatus") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ScheduleJob") + .HasColumnType("nvarchar(max)"); + + b.Property("ScheduledAt") + .HasColumnType("datetimeoffset"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("TranslationStatus") + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("ContentsAll", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.EFContentPublishedEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Created") + .HasColumnType("datetimeoffset"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Data") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Id") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("IndexedSchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("IsDeleted") + .HasColumnType("bit"); + + b.Property("LastModified") + .HasColumnType("datetimeoffset"); + + b.Property("LastModifiedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("NewData") + .HasColumnType("nvarchar(max)"); + + b.Property("NewStatus") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("ScheduleJob") + .HasColumnType("nvarchar(max)"); + + b.Property("ScheduledAt") + .HasColumnType("datetimeoffset"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("TranslationStatus") + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("ContentsPublished", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.EFContentTableEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.HasKey("Id"); + + b.HasIndex("AppId", "SchemaId") + .IsUnique(); + + b.ToTable("ContentTables", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.EFReferenceCompleteEntity", b => + { + b.Property("AppId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("FromKey") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ToId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("FromSchema") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)") + .HasDefaultValue("00000000-0000-0000-0000-000000000000"); + + b.HasKey("AppId", "FromKey", "ToId"); + + b.ToTable("ContentReferencesAll", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.EFReferencePublishedEntity", b => + { + b.Property("AppId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("FromKey") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ToId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("FromSchema") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)") + .HasDefaultValue("00000000-0000-0000-0000-000000000000"); + + b.HasKey("AppId", "FromKey", "ToId"); + + b.ToTable("ContentReferencesPublished", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.Text.EFTextIndexGeoEntity", b => + { + b.Property("Id") + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ContentId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("GeoField") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("GeoObject") + .IsRequired() + .HasColumnType("geography"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ServeAll") + .HasColumnType("bit"); + + b.Property("ServePublished") + .HasColumnType("bit"); + + b.Property("Stage") + .HasColumnType("tinyint"); + + b.HasKey("Id"); + + b.ToTable("Geos"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.Text.EFTextIndexTextEntity", b => + { + b.Property("Id") + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ContentId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ServeAll") + .HasColumnType("bit"); + + b.Property("ServePublished") + .HasColumnType("bit"); + + b.Property("Stage") + .HasColumnType("tinyint"); + + b.Property("Texts") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Texts"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.Text.EFTextIndexUserInfoEntity", b => + { + b.Property("Id") + .HasMaxLength(400) + .HasColumnType("nvarchar(400)"); + + b.Property("AppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ContentId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("SchemaId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ServeAll") + .HasColumnType("bit"); + + b.Property("ServePublished") + .HasColumnType("bit"); + + b.Property("Stage") + .HasColumnType("tinyint"); + + b.Property("UserInfoApiKey") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("UserInfoRole") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("UserInfoApiKey"); + + b.ToTable("UserInfos"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Contents.Text.State.TextContentState", b => + { + b.Property("UniqueContentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("State") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("UniqueContentId"); + + b.ToTable("TextState", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.History.HistoryEvent", b => + { + b.Property("Id") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Actor") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("Channel") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Created") + .HasColumnType("datetimeoffset"); + + b.Property("EventType") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OwnerId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Parameters") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.ToTable("HistoryEvent"); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Rules.EFRuleEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Document") + .HasColumnType("nvarchar(max)"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)") + .HasColumnName("AppId"); + + b.Property("IndexedDeleted") + .HasColumnType("bit") + .HasColumnName("Deleted"); + + b.Property("IndexedId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)") + .HasColumnName("Id"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Rule", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Schemas.EFSchemaEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Document") + .HasColumnType("nvarchar(max)"); + + b.Property("IndexedAppId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)") + .HasColumnName("AppId"); + + b.Property("IndexedDeleted") + .HasColumnType("bit") + .HasColumnName("Deleted"); + + b.Property("IndexedId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)") + .HasColumnName("Id"); + + b.Property("IndexedName") + .IsRequired() + .HasColumnType("nvarchar(max)") + .HasColumnName("Name"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Schema", (string)null); + }); + + modelBuilder.Entity("Squidex.Domain.Apps.Entities.Teams.EFTeamEntity", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Document") + .HasColumnType("nvarchar(max)"); + + b.Property("IndexedAuthDomain") + .HasColumnType("nvarchar(max)") + .HasColumnName("AuthDomain"); + + b.Property("IndexedDeleted") + .HasColumnType("bit") + .HasColumnName("Deleted"); + + b.Property("IndexedUserIds") + .IsRequired() + .HasColumnType("nvarchar(max)") + .HasColumnName("UserIds"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Team", (string)null); + }); + + modelBuilder.Entity("Squidex.Events.EntityFramework.EFEventCommit", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("EventStream") + .IsRequired() + .HasMaxLength(750) + .HasColumnType("nvarchar(750)"); + + b.Property("EventStreamOffset") + .HasColumnType("bigint"); + + b.PrimitiveCollection("Events") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("EventsCount") + .HasColumnType("bigint"); + + b.Property("Position") + .HasColumnType("bigint"); + + b.Property("Timestamp") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.HasIndex("EventStream", "EventStreamOffset") + .IsUnique(); + + b.HasIndex("EventStream", "Position"); + + b.HasIndex("EventStream", "Timestamp"); + + b.ToTable("Events"); + }); + + modelBuilder.Entity("Squidex.Events.EntityFramework.EFPosition", b => + { + b.Property("Id") + .HasColumnType("bigint"); + + b.Property("Position") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.ToTable("EventPosition"); + }); + + modelBuilder.Entity("Squidex.Flows.EntityFramework.EFCronJobEntity", b => + { + b.Property("Id") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Data") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DueTime") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("DueTime"); + + b.ToTable("CronJobs", (string)null); + }); + + modelBuilder.Entity("Squidex.Flows.EntityFramework.EFFlowStateEntity", b => + { + b.Property("Id") + .HasColumnType("uniqueidentifier"); + + b.Property("Created") + .HasColumnType("datetimeoffset"); + + b.Property("DefinitionId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("DueTime") + .HasColumnType("datetimeoffset"); + + b.Property("OwnerId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("SchedulePartition") + .HasColumnType("int"); + + b.Property("State") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.HasIndex("DueTime", "SchedulePartition"); + + b.ToTable("Flows", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.Caching.EFCacheEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("Expires") + .HasColumnType("datetime2"); + + b.Property("Value") + .IsRequired() + .HasColumnType("varbinary(max)"); + + b.HasKey("Key"); + + b.ToTable("Cache", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.Log.EFRequestEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Key") + .IsRequired() + .HasColumnType("nvarchar(450)"); + + b.Property("Properties") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Timestamp") + .HasColumnType("datetimeoffset"); + + b.HasKey("Id"); + + b.HasIndex("Key"); + + b.ToTable("Requests", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.Migrations.EFMigrationEntity", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("IsLocked") + .HasColumnType("bit"); + + b.Property("Version") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Migrations", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Document") + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_UISettings", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Document") + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Index_TagHistory", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Document") + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_UsageNotifications", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Document") + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Counters", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Document") + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_JobsState", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Document") + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_UsageTracker", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Document") + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Index_Tags", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Document") + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Identity_Keys", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Document") + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Identity_Xml", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Document") + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_EventConsumerState", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.States.EFState", b => + { + b.Property("DocumentId") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Document") + .HasColumnType("nvarchar(max)"); + + b.Property("Version") + .HasColumnType("bigint"); + + b.HasKey("DocumentId"); + + b.ToTable("States_Names", (string)null); + }); + + modelBuilder.Entity("Squidex.Infrastructure.UsageTracking.EFUsageCounterEntity", b => + { + b.Property("Key") + .HasColumnType("nvarchar(450)"); + + b.Property("Date") + .HasColumnType("datetime2"); + + b.Property("Category") + .HasColumnType("nvarchar(450)"); + + b.Property("CounterKey") + .HasColumnType("nvarchar(450)"); + + b.Property("CounterValue") + .HasColumnType("float"); + + b.HasKey("Key", "Date", "Category", "CounterKey"); + + b.ToTable("Counter", (string)null); + }); + + modelBuilder.Entity("Squidex.Messaging.EntityFramework.EFMessage", b => + { + b.Property("Id") + .HasColumnType("nvarchar(450)"); + + b.Property("ChannelName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("MessageData") + .IsRequired() + .HasColumnType("varbinary(max)"); + + b.Property("MessageHeaders") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("QueueName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("TimeHandled") + .HasColumnType("datetime2"); + + b.Property("TimeToLive") + .HasColumnType("datetime2"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("uniqueidentifier"); + + b.HasKey("Id"); + + b.HasIndex("ChannelName", "TimeHandled"); + + b.ToTable("Messages", (string)null); + }); + + modelBuilder.Entity("Squidex.Messaging.EntityFramework.EFMessagingDataEntity", b => + { + b.Property("Group") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Key") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Expiration") + .HasColumnType("datetime2"); + + b.Property("ValueData") + .IsRequired() + .HasColumnType("varbinary(max)"); + + b.Property("ValueFormat") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ValueType") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.HasKey("Group", "Key"); + + b.HasIndex("Expiration"); + + b.ToTable("MessagingData", (string)null); + }); + + modelBuilder.Entity("YDotNet.Server.EntityFramework.YDotNetDocument", b => + { + b.Property("Id") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("Data") + .IsRequired() + .HasColumnType("varbinary(max)"); + + b.Property("Expiration") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.ToTable("YDotNetDocument", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreToken", b => + { + b.HasOne("OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreAuthorization", "Authorization") + .WithMany("Tokens") + .HasForeignKey("AuthorizationId"); + + b.Navigation("Authorization"); + }); + + modelBuilder.Entity("OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreAuthorization", b => + { + b.Navigation("Tokens"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/20260928113653_AddTextStateVersion.cs b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/20260928113653_AddTextStateVersion.cs new file mode 100644 index 000000000..bd697e642 --- /dev/null +++ b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/20260928113653_AddTextStateVersion.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Squidex.Providers.SqlServer.App.Migrations +{ + /// + public partial class AddTextStateVersion : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Version", + table: "TextState", + type: "bigint", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "Version", + table: "TextState"); + } + } +} diff --git a/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/SqlServerDbContextModelSnapshot.cs b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/SqlServerDbContextModelSnapshot.cs index 63eab56a7..ba2d97fa0 100644 --- a/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/SqlServerDbContextModelSnapshot.cs +++ b/backend/src/Squidex.Data.EntityFramework/Providers/SqlServer/App/Migrations/SqlServerDbContextModelSnapshot.cs @@ -983,6 +983,9 @@ namespace Squidex.Providers.SqlServer.Migrations .HasMaxLength(100) .HasColumnType("nvarchar(100)"); + b.Property("Version") + .HasColumnType("bigint"); + b.HasKey("UniqueContentId"); b.ToTable("TextState", (string)null); diff --git a/backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj b/backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj index b1bb616c7..e88032ba6 100644 --- a/backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj +++ b/backend/src/Squidex.Data.EntityFramework/Squidex.Data.EntityFramework.csproj @@ -43,13 +43,13 @@ - - - - - - - + + + + + + + diff --git a/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Contents/Text/CommandFactory.cs b/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Contents/Text/CommandFactory.cs index a2e083538..1d71bb033 100644 --- a/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Contents/Text/CommandFactory.cs +++ b/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Contents/Text/CommandFactory.cs @@ -115,7 +115,9 @@ public sealed class CommandFactory(Func, T> textBu private T? BuildTexts(UpsertIndexEntry upsert) { - return upsert.Texts == null ? null : textBuilder(upsert.Texts); + var weightedTexts = upsert.GetWeightedTexts(); + + return weightedTexts == null ? null : textBuilder(weightedTexts); } private static void UpdateEntry(UpdateIndexEntry update, List>> writes) diff --git a/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Contents/Text/MongoTextStateClassMap.cs b/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Contents/Text/MongoTextStateClassMap.cs index 0c60a4168..840dffab3 100644 --- a/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Contents/Text/MongoTextStateClassMap.cs +++ b/backend/src/Squidex.Data.MongoDb/Domain/Apps/Entities/Contents/Text/MongoTextStateClassMap.cs @@ -20,6 +20,10 @@ internal static class MongoTextStateClassMap cm.MapProperty(x => x.State) .SetElementName("s"); + + cm.MapProperty(x => x.Version) + .SetElementName("v") + .SetIgnoreIfNull(true); }); } } diff --git a/backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj b/backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj index 8609dfa0f..241f3152b 100644 --- a/backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj +++ b/backend/src/Squidex.Data.MongoDb/Squidex.Data.MongoDb.csproj @@ -25,12 +25,12 @@ - - - - - - + + + + + + diff --git a/backend/src/Squidex.Domain.Apps.Core.Model/Schemas/FieldProperties.cs b/backend/src/Squidex.Domain.Apps.Core.Model/Schemas/FieldProperties.cs index c17c8e946..d6d740104 100644 --- a/backend/src/Squidex.Domain.Apps.Core.Model/Schemas/FieldProperties.cs +++ b/backend/src/Squidex.Domain.Apps.Core.Model/Schemas/FieldProperties.cs @@ -25,6 +25,10 @@ public abstract record FieldProperties : NamedElementPropertiesBase public ReadonlyList? Tags { get; init; } + public FieldSearchMode SearchMode { get; init; } + + public ReadonlyList? SearchPaths { get; init; } + public abstract T Accept(IFieldPropertiesVisitor visitor, TArgs args); public abstract T Accept(IFieldVisitor visitor, IField field, TArgs args); diff --git a/backend/src/Squidex.Domain.Apps.Core.Model/Schemas/FieldSearchMode.cs b/backend/src/Squidex.Domain.Apps.Core.Model/Schemas/FieldSearchMode.cs new file mode 100644 index 000000000..edd6f075d --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Core.Model/Schemas/FieldSearchMode.cs @@ -0,0 +1,15 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +namespace Squidex.Domain.Apps.Core.Schemas; + +public enum FieldSearchMode +{ + Default, + Title, + Exclude, +} diff --git a/backend/src/Squidex.Domain.Apps.Core.Model/Schemas/SchemaScripts.cs b/backend/src/Squidex.Domain.Apps.Core.Model/Schemas/SchemaScripts.cs index e803893b0..92efe89e1 100644 --- a/backend/src/Squidex.Domain.Apps.Core.Model/Schemas/SchemaScripts.cs +++ b/backend/src/Squidex.Domain.Apps.Core.Model/Schemas/SchemaScripts.cs @@ -20,4 +20,6 @@ public sealed record SchemaScripts public string? Query { get; init; } public string? QueryPre { get; init; } + + public string? Index { get; init; } } diff --git a/backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj b/backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj index 2887139e2..f151adf42 100644 --- a/backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj +++ b/backend/src/Squidex.Domain.Apps.Core.Model/Squidex.Domain.Apps.Core.Model.csproj @@ -20,7 +20,7 @@ - + diff --git a/backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj b/backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj index ce9470016..21f8b8195 100644 --- a/backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj +++ b/backend/src/Squidex.Domain.Apps.Core.Operations/Squidex.Domain.Apps.Core.Operations.csproj @@ -29,8 +29,8 @@ - - + + diff --git a/backend/src/Squidex.Domain.Apps.Entities/AppProviderExtensions.cs b/backend/src/Squidex.Domain.Apps.Entities/AppProviderExtensions.cs index 7c535bb1a..df454d6ca 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/AppProviderExtensions.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/AppProviderExtensions.cs @@ -13,7 +13,7 @@ namespace Squidex.Domain.Apps.Entities; public static class AppProviderExtensions { - public static async Task GetComponentsAsync(this IAppProvider appProvider, Schema schema, + public static async Task GetComponentsAsync(this IAppProvider appProvider, Schema schema, bool canCache = false, CancellationToken ct = default) { Dictionary? result = null; @@ -36,7 +36,7 @@ public static class AppProviderExtensions } else if (result == null || !result.ContainsKey(schemaId)) { - var resolvedEntity = await appProvider.GetSchemaAsync(appId, schemaId, false, ct); + var resolvedEntity = await appProvider.GetSchemaAsync(appId, schemaId, canCache, ct); if (resolvedEntity != null) { diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Migration/MigrateContentsJob.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Migration/MigrateContentsJob.cs index 731dfa602..9276a857d 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Contents/Migration/MigrateContentsJob.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Migration/MigrateContentsJob.cs @@ -110,7 +110,7 @@ public sealed class MigrateContentsJob( .WithNoCleanup() .WithUnpublished(true)); - var components = await appProvider.GetComponentsAsync(schema, ct); + var components = await appProvider.GetComponentsAsync(schema, ct: ct); await MigrateAsync( new MigrationContext diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentEnricher.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentEnricher.cs index 03636e3f7..e50516b4e 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentEnricher.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentEnricher.cs @@ -69,7 +69,6 @@ public sealed class ContentEnricher(IEnumerable steps, IAp } await RunStepsAsync(steps, results, context, ct); - activity?.SetTag("numItems", results.Count); return results; @@ -103,7 +102,7 @@ public sealed class ContentEnricher(IEnumerable steps, IAp var schema = await appProvider.GetSchemaAsync(context.App.Id, x, false, ct) ?? throw new DomainObjectNotFoundException(x.ToString()); - var components = await appProvider.GetComponentsAsync(schema, ct); + var components = await appProvider.GetComponentsAsync(schema, ct: ct); return (schema, components); }); diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentQueryParser.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentQueryParser.cs index 60f9fa1de..d88ec64bb 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentQueryParser.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Queries/ContentQueryParser.cs @@ -92,7 +92,7 @@ public class ContentQueryParser( var textQuery = new TextQuery(query.FullText, options.MaxFullTextResults) { - PreferredSchemaId = schema.Id, + RequiredSchemaIds = [schema.Id], }; var fullTextIds = await textIndex.SearchAsync(context.App, textQuery, context.Scope(), ct); @@ -143,7 +143,7 @@ public class ContentQueryParser( if (schema != null) { - components = await appprovider.GetComponentsAsync(schema, ct); + components = await appprovider.GetComponentsAsync(schema, ct: ct); } var query = q.Query; diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extensions.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extensions.cs index 4c3690f45..0f01c926f 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extensions.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extensions.cs @@ -10,8 +10,6 @@ using NetTopologySuite.Geometries; using Squidex.Domain.Apps.Core.Contents; using Squidex.Infrastructure; using Squidex.Infrastructure.Json; -using Squidex.Infrastructure.Json.Objects; -using Squidex.Infrastructure.ObjectPool; namespace Squidex.Domain.Apps.Entities.Contents.Text; @@ -65,84 +63,35 @@ public static class Extensions return result; } - public static Dictionary? ToTexts(this ContentData data) + public static Dictionary? GetWeightedTexts(this UpsertIndexEntry upsert, int titleWeight = 3) { - Dictionary? result = null; - - if (data != null) + // Not all text indexes support field weights, therefore they can boost the titles by repeating them. + if (upsert.Titles is not { Count: > 0 } titles) { - var languages = new Dictionary(); - try - { - foreach (var (_, value) in data) - { - if (value != null) - { - foreach (var (key, jsonValue) in value) - { - AppendJsonText(languages, key, jsonValue); - } - } - } - - foreach (var (key, sb) in languages) - { - if (sb.Length > 0) - { - result ??= []; - result[key] = sb.ToString(); - } - } - } - finally - { - foreach (var (_, sb) in languages) - { - DefaultPools.StringBuilder.Return(sb); - } - } + return upsert.Texts; } - return result; - } + var result = new Dictionary(upsert.Texts ?? []); - private static void AppendJsonText(Dictionary languages, string language, JsonValue value) - { - switch (value.Value) + foreach (var (language, title) in titles) { - case string s: - AppendText(languages, language, s); - break; - case JsonArray a: - foreach (var item in a) - { - AppendJsonText(languages, language, item); - } + var sb = new StringBuilder(); - break; - case JsonObject o: - foreach (var (_, item) in o) - { - AppendJsonText(languages, language, item); - } - - break; - } - } - - private static void AppendText(Dictionary languages, string language, string text) - { - if (!string.IsNullOrWhiteSpace(text)) - { - if (!languages.TryGetValue(language, out var sb)) + for (var i = 0; i < titleWeight; i++) { - sb = DefaultPools.StringBuilder.Get(); + sb.AppendIfNotEmpty(' '); + sb.Append(title); + } - languages[language] = sb; + if (result.TryGetValue(language, out var text)) + { + sb.Append(' '); + sb.Append(text); } - sb.AppendIfNotEmpty(' '); - sb.Append(text); + result[language] = sb.ToString(); } + + return result; } } diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ArrayFieldTextStrategy.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ArrayFieldTextStrategy.cs new file mode 100644 index 000000000..4b4ca9f0a --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ArrayFieldTextStrategy.cs @@ -0,0 +1,34 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Schemas; +using Squidex.Infrastructure.Json.Objects; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public sealed class ArrayFieldTextStrategy : ITextFieldStrategy +{ + public int Order => 0; + + public bool TryExtract(IField? field, JsonValue value, ContentTextWalker walker) + { + if (field is not IArrayField arrayField || value.Value is not JsonArray items) + { + return false; + } + + foreach (var item in items) + { + if (item.Value is JsonObject obj) + { + walker.AppendObject(obj, arrayField.FieldsByName); + } + } + + return true; + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ComponentTextStrategy.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ComponentTextStrategy.cs new file mode 100644 index 000000000..7ed66b2c7 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ComponentTextStrategy.cs @@ -0,0 +1,30 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Contents; +using Squidex.Domain.Apps.Core.Schemas; +using Squidex.Infrastructure; +using Squidex.Infrastructure.Json.Objects; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public sealed class ComponentTextStrategy : ITextFieldStrategy +{ + // Components are detected by value, because they can also be nested in other values. + public int Order => 100; + + public bool TryExtract(IField? field, JsonValue value, ContentTextWalker walker) + { + if (!Component.IsValid(value, out var discriminator) || !walker.Context.Components.TryGetValue(DomainId.Create(discriminator), out var schema)) + { + return false; + } + + walker.AppendObject(value.AsObject, schema.FieldsByName); + return true; + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ContentTextWalker.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ContentTextWalker.cs new file mode 100644 index 000000000..c89323ba8 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ContentTextWalker.cs @@ -0,0 +1,147 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Contents; +using Squidex.Domain.Apps.Core.Schemas; +using Squidex.Infrastructure.Json.Objects; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +// Walks through a single content and passes the texts to the collector. +public sealed class ContentTextWalker( + IReadOnlyList strategies, + IReadOnlyList normalizers, + TextExtractionContext context, + TextCollector collector) +{ + private static readonly object TitleFieldsKey = new object(); + private string language = string.Empty; + private bool isTitle; + + public TextExtractionContext Context => context; + + public void Walk(ContentData data) + { + var schema = context.Schema; + + var titleFields = context.GetOrAdd(TitleFieldsKey, schema, static x => GetTitleFields(x)); + foreach (var (fieldName, fieldData) in data) + { + if (fieldData == null) + { + continue; + } + + RootField? field = null; + schema?.FieldsByName.TryGetValue(fieldName, out field); + + isTitle = titleFields.Contains(fieldName); + + foreach (var (fieldLanguage, value) in fieldData) + { + // When the text is later appended we need the current language. + language = fieldLanguage; + + AppendField(field, value); + } + } + } + + public void AppendField(IField? field, JsonValue value) + { + var searchMode = field?.RawProperties.SearchMode ?? FieldSearchMode.Default; + if (searchMode == FieldSearchMode.Exclude) + { + return; + } + + var wasTitle = isTitle; + try + { + isTitle |= searchMode == FieldSearchMode.Title; + foreach (var strategy in strategies) + { + if (strategy.TryExtract(field, value, this)) + { + return; + } + } + } + finally + { + // The title mode only applies to the field and its nested values. + isTitle = wasTitle; + } + } + + public void AppendValue(JsonValue value) + { + AppendField(null, value); + } + + public void AppendObject(JsonObject obj, IReadOnlyDictionary fields) where T : IField + { + foreach (var (key, value) in obj) + { + if (key is Component.Discriminator or Component.Descriptor) + { + continue; + } + + AppendField(fields.GetValueOrDefault(key), value); + } + } + + public void AppendText(string text, IField? field = null) + { + foreach (var normalizer in normalizers) + { + var normalized = normalizer.Normalize(text, field); + if (string.IsNullOrWhiteSpace(normalized)) + { + return; + } + + text = normalized; + } + + collector.Append(text, language, isTitle); + } + + private static HashSet GetTitleFields(Schema? schema) + { + var result = new HashSet(); + + if (schema == null) + { + return result; + } + + // The fields in the references are used to identify a content, so they are the best candidates for titles. + var names = schema.FieldsInReferences.Count > 0 ? schema.FieldsInReferences : schema.FieldsInLists; + + foreach (var name in names) + { + if (FieldNames.IsDataField(name, out var dataField)) + { + result.Add(dataField); + } + else if (!FieldNames.IsMetaField(name)) + { + result.Add(name); + } + } + + // Use the same fallback as the UI, which shows the first field if nothing is configured. + if (result.Count == 0 && schema.Fields.Count > 0) + { + result.Add(schema.Fields[0].Name); + } + + return result; + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ExtractedTexts.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ExtractedTexts.cs new file mode 100644 index 000000000..4d17a777c --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ExtractedTexts.cs @@ -0,0 +1,12 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +#pragma warning disable SA1313 // Parameter names should begin with lower-case letter + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public sealed record ExtractedTexts(Dictionary? Texts, Dictionary? Titles); diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/HtmlTextNormalizer.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/HtmlTextNormalizer.cs new file mode 100644 index 000000000..1aeb06b44 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/HtmlTextNormalizer.cs @@ -0,0 +1,54 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Schemas; +using Squidex.Text; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public sealed class HtmlTextNormalizer : ITextNormalizer +{ + public int Order => 0; + + public string? Normalize(string text, IField? field) + { + if (!IsHtmlField(field) && !LooksLikeHtml(text)) + { + return text; + } + + try + { + return text.Html2Text(); + } + catch + { + // The parser fails for some invalid documents. + return text; + } + } + + private static bool IsHtmlField(IField? field) + { + if (field?.RawProperties is not StringFieldProperties properties) + { + return false; + } + + return properties.Editor is StringFieldEditor.Html or StringFieldEditor.RichText || properties.ContentType == StringContentType.Html; + } + + private static bool LooksLikeHtml(string text) + { + if (!text.Contains('<', StringComparison.Ordinal)) + { + return false; + } + + return text.Contains("", StringComparison.Ordinal); + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ITextExtractionStrategy.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ITextExtractionStrategy.cs new file mode 100644 index 000000000..c555d8952 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ITextExtractionStrategy.cs @@ -0,0 +1,18 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Contents; +using Squidex.Infrastructure; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public interface ITextExtractionStrategy +{ + int Order { get; } + + ExtractedTexts? Extract(TextExtractionContext context, DomainId contentId, ContentData data); +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ITextFieldStrategy.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ITextFieldStrategy.cs new file mode 100644 index 000000000..bc546a43b --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ITextFieldStrategy.cs @@ -0,0 +1,18 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Schemas; +using Squidex.Infrastructure.Json.Objects; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public interface ITextFieldStrategy +{ + int Order { get; } + + bool TryExtract(IField? field, JsonValue value, ContentTextWalker walker); +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ITextNormalizer.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ITextNormalizer.cs new file mode 100644 index 000000000..1eab6ff2a --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ITextNormalizer.cs @@ -0,0 +1,17 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Schemas; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public interface ITextNormalizer +{ + int Order { get; } + + string? Normalize(string text, IField? field); +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/JsonTextStrategy.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/JsonTextStrategy.cs new file mode 100644 index 000000000..cf06f16a7 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/JsonTextStrategy.cs @@ -0,0 +1,43 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Schemas; +using Squidex.Infrastructure.Json.Objects; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public sealed class JsonTextStrategy : ITextFieldStrategy +{ + // Fallback for all values, e.g. JSON fields or unknown fields, that indexes all strings. + public int Order => int.MaxValue; + + public bool TryExtract(IField? field, JsonValue value, ContentTextWalker walker) + { + switch (value.Value) + { + case string text: + walker.AppendText(text, field); + break; + case JsonArray array: + foreach (var item in array) + { + walker.AppendValue(item); + } + + break; + case JsonObject obj: + foreach (var (_, item) in obj) + { + walker.AppendValue(item); + } + + break; + } + + return true; + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/MarkdownTextNormalizer.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/MarkdownTextNormalizer.cs new file mode 100644 index 000000000..9c154c796 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/MarkdownTextNormalizer.cs @@ -0,0 +1,39 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Schemas; +using Squidex.Text; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public sealed class MarkdownTextNormalizer : ITextNormalizer +{ + // Markdown can contain HTML, therefore it must be converted before the HTML. + public int Order => -100; + + public string? Normalize(string text, IField? field) + { + if (field?.RawProperties is not StringFieldProperties properties) + { + return text; + } + + if (properties.Editor != StringFieldEditor.Markdown && properties.ContentType != StringContentType.Markdown) + { + return text; + } + + try + { + return text.Markdown2Text(); + } + catch + { + return text; + } + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/NoiseTextNormalizer.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/NoiseTextNormalizer.cs new file mode 100644 index 000000000..d3f2973e2 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/NoiseTextNormalizer.cs @@ -0,0 +1,104 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using System.Buffers; +using System.Globalization; +using System.Text.RegularExpressions; +using Squidex.Domain.Apps.Core.Schemas; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public sealed partial class NoiseTextNormalizer : ITextNormalizer +{ + // Strings without whitespaces above this length are usually tokens, hashes or base64 data. + private const int MaxWordLength = 64; + + // Same as char.IsWhiteSpace, but vectorized. + private static readonly SearchValues WhiteSpaces = + SearchValues.Create(Enumerable.Range(char.MinValue, char.MaxValue + 1).Select(x => (char)x).Where(char.IsWhiteSpace).ToArray()); + + // Runs last, because the other normalizers can change the text. + public int Order => 1000; + + public string? Normalize(string text, IField? field) + { + return IsNoise(text) ? null : text; + } + + public static bool IsNoise(string text) + { + // The checks are ordered by costs, most texts are sentences or words and should be handled by the cheap checks. + var span = text.AsSpan().Trim(); + if (span.Length == 0) + { + return true; + } + + // Anything with whitespaces is considered as normal text. + if (span.ContainsAny(WhiteSpaces)) + { + return false; + } + + if (span.Length > MaxWordLength) + { + return true; + } + + if (IsUrl(span)) + { + return true; + } + + // Colors can consist of letters only, e.g. #fff, therefore they are checked before the digits. + if (span[0] == '#') + { + return HexColorRegex().IsMatch(span); + } + + // Numbers, dates and IDs contain digits. + if (!span.ContainsAnyInRange('0', '9')) + { + return false; + } + + if (span.Length >= 10 && span[4] == '-' && IsoDateRegex().IsMatch(span)) + { + return true; + } + + // Reference IDs, asset IDs and component schema IDs. + if (Guid.TryParse(span, out _)) + { + return true; + } + + return double.TryParse(span, NumberStyles.Float, CultureInfo.InvariantCulture, out _); + } + + private static bool IsUrl(ReadOnlySpan span) + { + // Only the prefix is checked, because a full validation would be expensive and the URL is not indexed anyway. + if (span.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (span.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + return span.StartsWith("data:", StringComparison.OrdinalIgnoreCase); + } + + [GeneratedRegex("^#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$")] + private static partial Regex HexColorRegex(); + + [GeneratedRegex("^\\d{4}-\\d{2}-\\d{2}(T[0-9:.]+(Z|[+-]\\d{2}:?\\d{2})?)?$")] + private static partial Regex IsoDateRegex(); +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/RichTextFieldTextStrategy.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/RichTextFieldTextStrategy.cs new file mode 100644 index 000000000..f8378eeab --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/RichTextFieldTextStrategy.cs @@ -0,0 +1,28 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Contents; +using Squidex.Domain.Apps.Core.Schemas; +using Squidex.Infrastructure.Json.Objects; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public sealed class RichTextFieldTextStrategy : ITextFieldStrategy +{ + public int Order => 0; + + public bool TryExtract(IField? field, JsonValue value, ContentTextWalker walker) + { + if (field?.RawProperties is not RichTextFieldProperties || !RichTextNode.TryCreate(value, SquidexRichText.Options, out var node)) + { + return false; + } + + walker.AppendText(node.ToText(), field); + return true; + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/SchemaTextExtractionStrategy.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/SchemaTextExtractionStrategy.cs new file mode 100644 index 000000000..87bd56cc2 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/SchemaTextExtractionStrategy.cs @@ -0,0 +1,28 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Contents; +using Squidex.Infrastructure; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public sealed class SchemaTextExtractionStrategy(IEnumerable fieldStrategies, IEnumerable normalizers) : ITextExtractionStrategy +{ + private readonly ITextFieldStrategy[] fieldStrategies = fieldStrategies.OrderBy(x => x.Order).ToArray(); + private readonly ITextNormalizer[] normalizers = normalizers.OrderBy(x => x.Order).ToArray(); + + public int Order => 0; + + public ExtractedTexts? Extract(TextExtractionContext context, DomainId contentId, ContentData data) + { + using var collector = new TextCollector(); + + new ContentTextWalker(fieldStrategies, normalizers, context, collector).Walk(data); + + return collector.Build(); + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ScriptTextExtractionStrategy.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ScriptTextExtractionStrategy.cs new file mode 100644 index 000000000..09c29d909 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/ScriptTextExtractionStrategy.cs @@ -0,0 +1,130 @@ +// ========================================================================== +// 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.Scripting; +using Squidex.Infrastructure; +using Squidex.Infrastructure.Json.Objects; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public sealed class ScriptTextExtractionStrategy(IScriptEngine scriptEngine) : ITextExtractionStrategy +{ + private static readonly object ScriptKey = new object(); + private static readonly ScriptOptions ScriptOptions = new ScriptOptions + { + AsContext = true, + CanDisallow = false, + CanReject = false, + Readonly = true, + }; + + // The script can override the schema, therefore it must run first. + public int Order => -1000; + + public ExtractedTexts? Extract(TextExtractionContext context, DomainId contentId, ContentData data) + { + var script = context.Schema?.Scripts.Index; + if (string.IsNullOrWhiteSpace(script)) + { + return null; + } + + // The context is only used by one thread, therefore the script can be reused for all contents of the schema. + var compiled = context.GetOrAdd(ScriptKey, (ScriptEngine: scriptEngine, Script: script), static x => Compile(x.ScriptEngine, x.Script)); + if (compiled == null) + { + return null; + } + + try + { + // Script vars are just wrappers over dictionaries for better performance. + var vars = new ContentScriptVars + { + AppId = context.AppId.Id, + AppName = context.AppId.Name, + ContentId = contentId, + Data = data, + SchemaId = context.SchemaId.Id, + SchemaName = context.SchemaId.Name, + }; + + return ToTexts(compiled.Execute(vars)); + } + catch + { + // The state of the script is unknown after an error, e.g. a timeout, therefore it is not reused. + context.Remove(ScriptKey); + + // Fallback to the next strategy. + return null; + } + } + + private static IScript? Compile(IScriptEngine scriptEngine, string script) + { + try + { + return scriptEngine.CreateScript(script, ScriptOptions); + } + catch + { + // The contents are indexed without the script. + return null; + } + } + + public static ExtractedTexts? ToTexts(JsonValue result) + { + // The script output is used as it is, therefore the normalizers are not applied. + using var collector = new TextCollector(); + + // Undefined or null means that the script wants to fallback to the next strategy. + switch (result.Value) + { + case string text: + collector.Append(text, InvariantPartitioning.Key, false); + break; + case JsonObject obj: + Append(collector, obj, "title", true); + Append(collector, obj, "body", false); + break; + default: + return null; + } + + // An empty result means that the script has handled the content, therefore the next strategy must not run. + return collector.Build() ?? new ExtractedTexts(null, null); + } + + private static void Append(TextCollector collector, JsonObject obj, string key, bool isTitle) + { + if (!obj.TryGetValue(key, out var value)) + { + return; + } + + switch (value.Value) + { + case string text: + collector.Append(text, InvariantPartitioning.Key, isTitle); + break; + case JsonObject languages: + foreach (var (language, languageValue) in languages) + { + if (languageValue.Value is string languageText) + { + collector.Append(languageText, language, isTitle); + } + } + + break; + } + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/SearchPathsFieldTextStrategy.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/SearchPathsFieldTextStrategy.cs new file mode 100644 index 000000000..004cbbceb --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/SearchPathsFieldTextStrategy.cs @@ -0,0 +1,73 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Schemas; +using Squidex.Infrastructure.Collections; +using Squidex.Infrastructure.Json.Objects; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public sealed class SearchPathsFieldTextStrategy : ITextFieldStrategy +{ + // Search paths are configured explicitly and therefore override all other strategies. + public int Order => -1000; + + public bool TryExtract(IField? field, JsonValue value, ContentTextWalker walker) + { + if (field?.RawProperties.SearchPaths is not { Count: > 0 } paths) + { + return false; + } + + // Parse the paths only once for all contents of the schema. The list is the key, so that no key has to be allocated. + var parsedPaths = walker.Context.GetOrAdd(paths, paths, static x => ParsePaths(x)); + + foreach (var path in parsedPaths) + { + AppendPath(value, path, 0, walker); + } + + return true; + } + + private static void AppendPath(JsonValue value, string[] path, int index, ContentTextWalker walker) + { + if (index == path.Length) + { + walker.AppendValue(value); + return; + } + + switch (value.Value) + { + case JsonArray array: + // Arrays are traversed implicitly, so that users do not have to specify the index. + foreach (var item in array) + { + AppendPath(item, path, index, walker); + } + + break; + case JsonObject obj when obj.TryGetValue(path[index], out var child): + AppendPath(child, path, index + 1, walker); + break; + } + } + + private static string[][] ParsePaths(ReadonlyList paths) + { + return paths.Select(ParsePath).ToArray(); + } + + private static string[] ParsePath(string path) + { + // Also support the JSON path syntax, e.g. '$.items[*].label'. + path = path.Trim().TrimStart('$').Replace("[*]", string.Empty, StringComparison.Ordinal).Replace("[]", string.Empty, StringComparison.Ordinal); + + return path.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/TextCollector.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/TextCollector.cs new file mode 100644 index 000000000..2c0478abd --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/TextCollector.cs @@ -0,0 +1,68 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using System.Text; +using Squidex.Infrastructure; +using Squidex.Infrastructure.ObjectPool; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public sealed class TextCollector : IDisposable +{ + private readonly Dictionary bodies = []; + private readonly Dictionary titles = []; + + public void Dispose() + { + foreach (var sb in bodies.Values.Concat(titles.Values)) + { + DefaultPools.StringBuilder.Return(sb); + } + } + + public void Append(string text, string language, bool isTitle) + { + if (string.IsNullOrWhiteSpace(text)) + { + return; + } + + var target = isTitle ? titles : bodies; + if (!target.TryGetValue(language, out var sb)) + { + sb = DefaultPools.StringBuilder.Get(); + + target[language] = sb; + } + + sb.AppendIfNotEmpty(' '); + sb.Append(text.Trim()); + } + + public ExtractedTexts? Build() + { + var extractedTexts = Build(bodies); + var extractedTitles = Build(titles); + + if (extractedTexts == null && extractedTitles == null) + { + return null; + } + + return new ExtractedTexts(extractedTexts, extractedTitles); + } + + private static Dictionary? Build(Dictionary source) + { + if (source.Count == 0) + { + return null; + } + + return source.ToDictionary(x => x.Key, x => x.Value.ToString()); + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/TextExtractionContext.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/TextExtractionContext.cs new file mode 100644 index 000000000..d56175134 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/TextExtractionContext.cs @@ -0,0 +1,58 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Schemas; +using Squidex.Infrastructure; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +// The context is created for all contents of a schema in a batch and only used by a single thread. +public sealed class TextExtractionContext : IDisposable +{ + private readonly Dictionary items = []; + + required public NamedId AppId { get; init; } + + required public NamedId SchemaId { get; init; } + + public Schema? Schema { get; init; } + + public ResolvedComponents Components { get; init; } = ResolvedComponents.Empty; + + public void Dispose() + { + foreach (var item in items.Values.OfType()) + { + item.Dispose(); + } + + items.Clear(); + } + + public T GetOrAdd(object key, TArg arg, Func factory) + { + // The strategies can store expensive values for the schema, e.g. compiled scripts. + if (items.TryGetValue(key, out var existing)) + { + return (T)existing!; + } + + // The argument allows static factories without closures, because this method is called for every content. + var value = factory(arg); + + items[key] = value; + return value; + } + + public void Remove(object key) + { + if (items.Remove(key, out var existing) && existing is IDisposable disposable) + { + disposable.Dispose(); + } + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/TextExtractor.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/TextExtractor.cs new file mode 100644 index 000000000..e85719dd4 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Extraction/TextExtractor.cs @@ -0,0 +1,31 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Contents; +using Squidex.Infrastructure; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Extraction; + +public sealed class TextExtractor(IEnumerable strategies) +{ + private readonly ITextExtractionStrategy[] strategies = strategies.OrderBy(x => x.Order).ToArray(); + + public ExtractedTexts? Extract(TextExtractionContext context, DomainId contentId, ContentData data) + { + // The first strategy that returns a result wins, e.g. the index script before the schema. + foreach (var strategy in strategies) + { + var result = strategy.Extract(context, contentId, data); + if (result != null) + { + return result; + } + } + + return null; + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Rebuild/RebuildTextIndexJob.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Rebuild/RebuildTextIndexJob.cs new file mode 100644 index 000000000..25e5a7895 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Rebuild/RebuildTextIndexJob.cs @@ -0,0 +1,131 @@ +// ========================================================================== +// 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.Entities.Jobs; +using Squidex.Events; +using Squidex.Infrastructure; +using Squidex.Infrastructure.EventSourcing; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; + +public sealed class RebuildTextIndexJob( + IAppProvider appProvider, + IEventStore eventStore, + IEventFormatter eventFormatter, + TextIndexingProcess textIndexer, + TextIndexRebuildCoordinator coordinator) + : IJobRunner +{ + public const string TaskName = "rebuildTextIndex"; + public const string ArgAppId = "appId"; + public const string ArgAppName = "appName"; + + // Same as the text indexer, the commands only keep the latest version of each content in the batch. + private const int BatchSize = 1000; + + private sealed class Progress + { + // The position of the last event that has been written to the index. + public string? Position { get; set; } + + public long ProcessedEvents { get; set; } + } + + public string Name => TaskName; + + public static JobRequest BuildRequest(RefToken actor, App app) + { + Guard.NotNull(actor); + Guard.NotNull(app); + + var arguments = new Dictionary + { + [ArgAppId] = app.Id.ToString(), + [ArgAppName] = app.Name, + }; + + return JobRequest.Create(actor, TaskName, arguments) with + { + AppId = app.NamedId(), + }; + } + + public async Task RunAsync(JobRunContext context, + CancellationToken ct) + { + var app = await appProvider.GetAppAsync(context.OwnerId, true, ct) + ?? throw new DomainObjectNotFoundException(context.OwnerId.ToString()); + + // Use a readable name to describe the job. + context.Job.Description = "Rebuild full text index"; + + // From now on the text indexer skips the events of the app and only counts them. + await coordinator.TakeOverAsync(app.Id, ct); + + await context.LogAsync("Started rebuild"); + + var progress = new Progress(); + + try + { + await ReplayAsync(context, app.Id, progress, ct); + } + finally + { + // Hand the app back to the text indexer, also when the job has been cancelled or has failed. + await HandBackAsync(context, app.Id, progress); + } + + await context.LogAsync($"Completed rebuild of {progress.ProcessedEvents} events"); + } + + private async Task HandBackAsync(JobRunContext context, DomainId appId, Progress progress) + { + try + { + // The events are replayed in order, therefore the contents could be at an older version when the job has been cancelled. + // So we cannot cancel the handback, but have to replay all remaining events. + while (true) + { + var skippedEvents = await coordinator.GetSkippedEventsAsync(appId); + + await ReplayAsync(context, appId, progress, default); + + // Only hand back if the text indexer has not skipped any event while we were reading the event store. + if (await coordinator.TryHandBackAsync(appId, skippedEvents)) + { + break; + } + } + } + catch + { + // The text indexer must not skip the app forever. The job fails and has to be started again. + await coordinator.ReleaseAsync(appId); + throw; + } + } + + private async Task ReplayAsync(JobRunContext context, DomainId appId, Progress progress, + CancellationToken ct) + { + var streamFilter = StreamFilter.Prefix($"content-{appId}{DomainId.IdSeparator}"); + + // Continue from the last position, e.g. to catch up with the events that have been skipped by the text indexer. + await foreach (var batch in eventStore.QueryAllAsync(streamFilter, progress.Position, ct: ct).Batch(BatchSize, ct)) + { + // The text indexer skips the events of the app, therefore we can replay the events without the version check. + await textIndexer.ApplyAsync(batch.Select(eventFormatter.ParseIfKnown).NotNull().ToList(), true, ct); + + progress.Position = batch[^1].EventPosition; + progress.ProcessedEvents += batch.Count; + + await context.LogAsync($"Rebuilt events: {progress.ProcessedEvents}", true); + } + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Rebuild/TextIndexBatch.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Rebuild/TextIndexBatch.cs new file mode 100644 index 000000000..087f80ce9 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Rebuild/TextIndexBatch.cs @@ -0,0 +1,31 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Infrastructure; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; + +public sealed class TextIndexBatch(IDisposable handle, Dictionary skippedEvents) : IDisposable +{ + public bool TrySkip(DomainId appId) + { + if (!skippedEvents.TryGetValue(appId, out var count)) + { + return false; + } + + // The rebuild reads the event from the event store, but it must know that it has to catch up. + skippedEvents[appId] = count + 1; + return true; + } + + public void Dispose() + { + // The rebuild cannot hand back the app while the batch is processed. + handle.Dispose(); + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Rebuild/TextIndexRebuildCoordinator.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Rebuild/TextIndexRebuildCoordinator.cs new file mode 100644 index 000000000..4fa2e8ba7 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/Rebuild/TextIndexRebuildCoordinator.cs @@ -0,0 +1,74 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Infrastructure; +using Squidex.Infrastructure.Tasks; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; + +// The text indexer and the rebuild jobs both run on the worker node, therefore the coordination can happen in memory. +public sealed class TextIndexRebuildCoordinator +{ + private readonly AsyncLock syncLock = new AsyncLock(); + + // The number of events per app that the text indexer has skipped, because the app is rebuilt. + private readonly Dictionary skippedEvents = []; + + public async Task BeginBatchAsync( + CancellationToken ct = default) + { + // The rebuild only holds the lock for short operations in memory, never for the rebuild itself. + var handle = await syncLock.EnterAsync(ct); + + return new TextIndexBatch(handle, skippedEvents); + } + + public async Task TakeOverAsync(DomainId appId, + CancellationToken ct = default) + { + using (await syncLock.EnterAsync(ct)) + { + if (!skippedEvents.TryAdd(appId, 0)) + { + throw new DomainException("The full text index of the app is already rebuilt."); + } + } + } + + public async Task GetSkippedEventsAsync(DomainId appId, + CancellationToken ct = default) + { + using (await syncLock.EnterAsync(ct)) + { + return skippedEvents.GetValueOrDefault(appId); + } + } + + public async Task TryHandBackAsync(DomainId appId, long expectedSkippedEvents, + CancellationToken ct = default) + { + using (await syncLock.EnterAsync(ct)) + { + // The text indexer has skipped events after the rebuild has read the event store, therefore it has to catch up again. + if (skippedEvents.TryGetValue(appId, out var count) && count != expectedSkippedEvents) + { + return false; + } + + skippedEvents.Remove(appId); + return true; + } + } + + public async Task ReleaseAsync(DomainId appId) + { + using (await syncLock.EnterAsync()) + { + skippedEvents.Remove(appId); + } + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/State/TextContentState.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/State/TextContentState.cs index 1a1ad42cc..0d16fba13 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/State/TextContentState.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/State/TextContentState.cs @@ -12,4 +12,6 @@ public sealed class TextContentState public UniqueContentId UniqueContentId { get; set; } public TextState State { get; set; } + + public long? Version { get; set; } } diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/TextIndexExtraction.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/TextIndexExtraction.cs new file mode 100644 index 000000000..858b2bbd0 --- /dev/null +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/TextIndexExtraction.cs @@ -0,0 +1,67 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Contents; +using Squidex.Domain.Apps.Core.Schemas; +using Squidex.Domain.Apps.Entities.Contents.Text.Extraction; +using Squidex.Domain.Apps.Events.Contents; +using Squidex.Infrastructure; + +namespace Squidex.Domain.Apps.Entities.Contents.Text; + +public sealed class TextIndexExtraction(IAppProvider appProvider, TextExtractor textExtractor) +{ + public async Task> ExtractAsync(IEnumerable<(ContentEvent Event, ContentData Data)> sources, + CancellationToken ct) + { + // Compare by reference, because the events hold the instances and value equality is expensive. + var result = new Dictionary(ReferenceEqualityComparer.Instance); + + // Group by schema, so that the strategies can reuse expensive values for all contents, e.g. compiled scripts. + var groups = sources.GroupBy(x => (AppId: x.Event.AppId.Id, SchemaId: x.Event.SchemaId.Id)); + + foreach (var group in groups) + { + var (schema, components) = await GetSchemaAsync(group.Key.AppId, group.Key.SchemaId, ct); + + var first = group.First().Event; + + using var context = new TextExtractionContext + { + AppId = first.AppId, + Components = components, + Schema = schema, + SchemaId = first.SchemaId, + }; + + foreach (var (@event, data) in group) + { + if (!result.ContainsKey(data)) + { + result[data] = textExtractor.Extract(context, @event.ContentId, data); + } + } + } + + return result; + } + + private async Task<(Schema?, ResolvedComponents)> GetSchemaAsync(DomainId appId, DomainId schemaId, + CancellationToken ct) + { + var schema = await appProvider.GetSchemaAsync(appId, schemaId, true, ct); + if (schema == null) + { + return (null, ResolvedComponents.Empty); + } + + // Slightly outdated components are fine for the index, but loading them for each batch is expensive. + var components = await appProvider.GetComponentsAsync(schema, true, ct); + + return (schema, components); + } +} diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/TextIndexingProcess.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/TextIndexingProcess.cs index 35e8119ad..d9890a25b 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/TextIndexingProcess.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/TextIndexingProcess.cs @@ -6,6 +6,7 @@ // ========================================================================== using Squidex.Domain.Apps.Core.Contents; +using Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; using Squidex.Domain.Apps.Entities.Contents.Text.State; using Squidex.Domain.Apps.Events.Contents; using Squidex.Events; @@ -17,7 +18,9 @@ namespace Squidex.Domain.Apps.Entities.Contents.Text; public sealed class TextIndexingProcess( IJsonSerializer serializer, ITextIndex textIndex, - ITextIndexerState textIndexerState) + ITextIndexerState textIndexerState, + TextIndexExtraction extraction, + TextIndexRebuildCoordinator coordinator) : IEventConsumer { public int BatchSize => 1000; @@ -33,13 +36,35 @@ public sealed class TextIndexingProcess( get => textIndex; } - private sealed class Updates(Dictionary states, IJsonSerializer serializer) + private sealed class Updates( + Dictionary states, + IJsonSerializer serializer, + bool isRebuild) { private readonly Dictionary currentUpdates = []; private readonly Dictionary<(UniqueContentId, byte), IndexCommand> commands = []; + private readonly Dictionary sources = []; - public async Task WriteAsync(ITextIndex textIndex, ITextIndexerState textIndexerState) + public async Task WriteAsync(ITextIndex textIndex, ITextIndexerState textIndexerState, TextIndexExtraction extraction, + CancellationToken ct) { + // Only calculate the values for the final versions, the other versions have been replaced within the batch. + var upserts = commands.Values.OfType().ToList(); + if (upserts.Count > 0) + { + var texts = await extraction.ExtractAsync(upserts.Select(x => sources[x]), ct); + + foreach (var upsert in upserts) + { + var data = sources[upsert].Data; + var text = texts.GetValueOrDefault(data); + + upsert.GeoObjects = data.ToGeo(serializer); + upsert.Texts = text?.Texts; + upsert.Titles = text?.Titles; + } + } + if (commands.Count > 0) { await textIndex.ExecuteAsync(commands.Values.ToArray()); @@ -53,6 +78,21 @@ public sealed class TextIndexingProcess( public void On(Envelope @event) { + if (@event.Payload is not ContentEvent contentEvent) + { + return; + } + + var uniqueId = new UniqueContentId(contentEvent.AppId.Id, contentEvent.ContentId); + + var version = @event.Headers.EventStreamNumber(); + + // A rebuild has already indexed the content up to this version. The rebuild itself replays everything from the start. + if (!isRebuild && states.TryGetValue(uniqueId, out var existing) && existing.Version >= version) + { + return; + } + switch (@event.Payload) { case ContentCreated created: @@ -88,6 +128,13 @@ public sealed class TextIndexingProcess( break; } + + if (states.TryGetValue(uniqueId, out var state)) + { + state.Version = version; + + currentUpdates[uniqueId] = state; + } } private void Create(ContentEvent @event, ContentData data) @@ -103,14 +150,19 @@ public sealed class TextIndexingProcess( new UpsertIndexEntry { UniqueContentId = uniqueId, - GeoObjects = data.ToGeo(serializer), - IsNew = true, + IsNew = !isRebuild, Stage = 0, ServeAll = true, ServePublished = false, - Texts = data.ToTexts(), UserInfos = data.ToUserInfos(), - }); + }, + data); + + // The entries of a rebuild already exist, therefore we also delete the old draft. + if (isRebuild) + { + CoreDelete(@event, uniqueId, 1); + } states[state.UniqueContentId] = state; currentUpdates[state.UniqueContentId] = state; @@ -328,12 +380,11 @@ public sealed class TextIndexingProcess( new UpsertIndexEntry { UniqueContentId = uniqueId, - GeoObjects = data.ToGeo(serializer), Stage = stage, ServeAll = all, ServePublished = published, - Texts = data.ToTexts(), - }); + }, + data); } private void CoreUpdate(ContentEvent @event, UniqueContentId uniqueId, byte stage, bool all, bool published) @@ -358,12 +409,17 @@ public sealed class TextIndexingProcess( }); } - private void Index(ContentEvent @event, IndexCommand command) + private void Index(ContentEvent @event, IndexCommand command, ContentData? data = null) { command.SchemaId = @event.SchemaId; var key = (command.UniqueContentId, command.Stage); + if (command is UpsertIndexEntry newUpsert && data != null) + { + sources[newUpsert] = (@event, data); + } + if (command is UpdateIndexEntry update && commands.TryGetValue(key, out var existing) && existing is UpsertIndexEntry upsert) @@ -385,16 +441,38 @@ public sealed class TextIndexingProcess( } public async Task On(IEnumerable> events) + { + // The rebuild job cannot hand back the app while the batch is handled. + using var batch = await coordinator.BeginBatchAsync(); + + var indexEvents = new List>(); + + foreach (var @event in events) + { + // The events of apps that are rebuilt are replayed by the rebuild job. + if (@event.Payload is ContentEvent contentEvent && batch.TrySkip(contentEvent.AppId.Id)) + { + continue; + } + + indexEvents.Add(@event); + } + + await ApplyAsync(indexEvents, false); + } + + public async Task ApplyAsync(List> events, bool isRebuild, + CancellationToken ct = default) { var textStates = await QueryStatesAsync(events); - var textBatch = new Updates(textStates, serializer); + var textBatch = new Updates(textStates, serializer, isRebuild); foreach (var @event in events) { textBatch.On(@event); } - await textBatch.WriteAsync(textIndex, textIndexerState); + await textBatch.WriteAsync(textIndex, textIndexerState, extraction, ct); } private Task> QueryStatesAsync(IEnumerable> events) diff --git a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/UpsertIndexEntry.cs b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/UpsertIndexEntry.cs index 9431dbd79..85748f73e 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/UpsertIndexEntry.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Contents/Text/UpsertIndexEntry.cs @@ -16,6 +16,8 @@ public sealed class UpsertIndexEntry : IndexCommand public Dictionary? Texts { get; set; } + public Dictionary? Titles { get; set; } + public List? UserInfos { get; set; } public bool ServeAll { get; set; } diff --git a/backend/src/Squidex.Domain.Apps.Entities/Jobs/JobProcessor.cs b/backend/src/Squidex.Domain.Apps.Entities/Jobs/JobProcessor.cs index 3d0c210a5..d9fbcb39a 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/Jobs/JobProcessor.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/Jobs/JobProcessor.cs @@ -54,27 +54,32 @@ public sealed class JobProcessor { await state.LoadAsync(ct); - var pending = state.Value.Jobs.Where(x => x.Stopped == null); - - if (pending.Any()) + var pending = state.Value.Jobs.Where(x => x.Stopped == null).ToList(); + if (pending.Count == 0) { - // This should actually never happen, so we log with warning. - LogMessages.LogRemovedUnfinishedJobs(log, ownerId); + return; + } - foreach (var job in pending.ToList()) - { - var runner = runners.FirstOrDefault(x => x.Name == job.TaskName); + // This happens when the server has been stopped while the job was running, so we log with warning. + LogMessages.LogInterruptedJobs(log, ownerId); - if (runner != null) - { - await runner.CleanupAsync(job); - } + var now = Clock.GetCurrentInstant(); - state.Value.Jobs.Remove(job); - } + foreach (var job in pending) + { + // Keep the job, so that the user can see that it has been interrupted and start it again. + job.Status = JobStatus.Failed; + job.Stopped = now; + job.Log.Add(new JobLogMessage(now, "The job has been interrupted, because the server has been stopped.")); - await state.WriteAsync(ct); + var runner = runners.FirstOrDefault(x => x.Name == job.TaskName); + if (runner != null) + { + await runner.CleanupAsync(job); + } } + + await state.WriteAsync(ct); } public Task DeleteAsync(DomainId jobId) diff --git a/backend/src/Squidex.Domain.Apps.Entities/LogMessages.cs b/backend/src/Squidex.Domain.Apps.Entities/LogMessages.cs index 5359dff42..d7bd69835 100644 --- a/backend/src/Squidex.Domain.Apps.Entities/LogMessages.cs +++ b/backend/src/Squidex.Domain.Apps.Entities/LogMessages.cs @@ -69,8 +69,8 @@ internal static partial class LogMessages [LoggerMessage(Level = LogLevel.Warning, Message = "Failed to invite user: Assignee {assigneeId} not found.")] public static partial void LogInvitationAssigneeNotFound(ILogger logger, string assigneeId); - [LoggerMessage(Level = LogLevel.Warning, Message = "Removed unfinished jobs for owner {ownerId} after start.")] - public static partial void LogRemovedUnfinishedJobs(ILogger logger, DomainId ownerId); + [LoggerMessage(Level = LogLevel.Warning, Message = "Marked interrupted jobs for owner {ownerId} as failed after start.")] + public static partial void LogInterruptedJobs(ILogger logger, DomainId ownerId); [LoggerMessage(Level = LogLevel.Information, Message = "Clearing jobs for owner {ownerId}.")] public static partial void LogClearingJobs(ILogger logger, DomainId ownerId); diff --git a/backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj b/backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj index a00699714..7a718ff20 100644 --- a/backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj +++ b/backend/src/Squidex.Infrastructure/Squidex.Infrastructure.csproj @@ -24,13 +24,13 @@ - - - - - - - + + + + + + + diff --git a/backend/src/Squidex.Shared/PermissionIds.cs b/backend/src/Squidex.Shared/PermissionIds.cs index c341b724f..13c7c0a37 100644 --- a/backend/src/Squidex.Shared/PermissionIds.cs +++ b/backend/src/Squidex.Shared/PermissionIds.cs @@ -25,6 +25,9 @@ public static class PermissionIds // Backup Admin public const string AdminRestore = "squidex.admin.restore"; + // Text Index Admin + public const string AdminTextIndex = "squidex.admin.text-index"; + // Event Admin public const string AdminEvents = "squidex.admin.events"; public const string AdminEventsRead = "squidex.admin.events.read"; diff --git a/backend/src/Squidex.Web/Resources.cs b/backend/src/Squidex.Web/Resources.cs index 4abcd25c8..6e17ed5a7 100644 --- a/backend/src/Squidex.Web/Resources.cs +++ b/backend/src/Squidex.Web/Resources.cs @@ -149,6 +149,8 @@ public sealed class Resources(ApiController controller) // Backups public bool CanRestoreBackup => Can(PermissionIds.AdminRestore); + public bool CanRebuildTextIndex => Can(PermissionIds.AdminTextIndex); + public bool CanCreateBackup => Can(PermissionIds.AppJobs); // Jobs diff --git a/backend/src/Squidex/Areas/Api/Controllers/Contents/Generator/SchemasOpenApiGenerator.cs b/backend/src/Squidex/Areas/Api/Controllers/Contents/Generator/SchemasOpenApiGenerator.cs index 829c1a4ba..cdca86b45 100644 --- a/backend/src/Squidex/Areas/Api/Controllers/Contents/Generator/SchemasOpenApiGenerator.cs +++ b/backend/src/Squidex/Areas/Api/Controllers/Contents/Generator/SchemasOpenApiGenerator.cs @@ -49,7 +49,7 @@ public sealed class SchemasOpenApiGenerator( { if (schema.IsPublished && schema.Type != SchemaDefType.Component && schema.Fields.Count > 0) { - var components = await appProvider.GetComponentsAsync(schema, httpContext.RequestAborted); + var components = await appProvider.GetComponentsAsync(schema, ct: httpContext.RequestAborted); GenerateSchemaOperations(builder.Schema(schema, partitionResolver, components, flat)); } diff --git a/backend/src/Squidex/Areas/Api/Controllers/Jobs/JobsController.cs b/backend/src/Squidex/Areas/Api/Controllers/Jobs/JobsController.cs index d0b5764bf..273fc0c43 100644 --- a/backend/src/Squidex/Areas/Api/Controllers/Jobs/JobsController.cs +++ b/backend/src/Squidex/Areas/Api/Controllers/Jobs/JobsController.cs @@ -7,9 +7,11 @@ using Microsoft.AspNetCore.Mvc; using Squidex.Areas.Api.Controllers.Jobs.Models; +using Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; using Squidex.Domain.Apps.Entities.Jobs; using Squidex.Infrastructure; using Squidex.Infrastructure.Commands; +using Squidex.Infrastructure.Security; using Squidex.Shared; using Squidex.Web; @@ -41,6 +43,28 @@ public class JobsController(ICommandBus commandBus, IJobService jobService) : Ap return Ok(result); } + /// + /// Rebuild the full text index. + /// + /// The name of the app. + /// An optional reference to find the job. + /// Rebuild started. + /// Another job is already running. + /// App not found. + [HttpPost] + [Route("apps/{app}/jobs/text-index/")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ApiPermission(PermissionIds.AdminTextIndex)] + [ApiCosts(0)] + public async Task PostTextIndexRebuild(string app, [FromQuery] string? reference = null) + { + var job = RebuildTextIndexJob.BuildRequest(User.Token()!, App) with { Reference = reference }; + + await jobService.StartAsync(App.Id, job, HttpContext.RequestAborted); + + return NoContent(); + } + /// /// Delete a job. /// diff --git a/backend/src/Squidex/Areas/Api/Controllers/Jobs/Models/JobsDto.cs b/backend/src/Squidex/Areas/Api/Controllers/Jobs/Models/JobsDto.cs index d963cd3a8..77b279d72 100644 --- a/backend/src/Squidex/Areas/Api/Controllers/Jobs/Models/JobsDto.cs +++ b/backend/src/Squidex/Areas/Api/Controllers/Jobs/Models/JobsDto.cs @@ -40,6 +40,12 @@ public sealed class JobsDto : Resource resources.Url(x => nameof(x.PostBackup), values)); } + if (resources.CanRebuildTextIndex) + { + AddPostLink("create/text-index", + resources.Url(x => nameof(x.PostTextIndexRebuild), values)); + } + return this; } } diff --git a/backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/FieldPropertiesDto.cs b/backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/FieldPropertiesDto.cs index 62f125542..b902696d8 100644 --- a/backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/FieldPropertiesDto.cs +++ b/backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/FieldPropertiesDto.cs @@ -63,5 +63,15 @@ public abstract class FieldPropertiesDto /// public ReadonlyList? Tags { get; set; } + /// + /// Defines how the field is used for the full text search. + /// + public FieldSearchMode SearchMode { get; set; } + + /// + /// Optional paths to the values that are indexed for the full text search, e.g. 'items.label'. + /// + public ReadonlyList? SearchPaths { get; set; } + public abstract FieldProperties ToProperties(); } diff --git a/backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/SchemaScriptsDto.cs b/backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/SchemaScriptsDto.cs index c04d9d60b..73dfb1265 100644 --- a/backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/SchemaScriptsDto.cs +++ b/backend/src/Squidex/Areas/Api/Controllers/Schemas/Models/SchemaScriptsDto.cs @@ -43,6 +43,11 @@ public sealed class SchemaScriptsDto /// public string? Change { get; set; } + /// + /// The script that is executed when a content is indexed for the full text search. + /// + public string? Index { get; set; } + public ConfigureScripts ToCommand() { var scripts = SimpleMapper.Map(this, new SchemaScripts()); diff --git a/backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemaContentsController.cs b/backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemaContentsController.cs index 612d18852..a00591054 100644 --- a/backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemaContentsController.cs +++ b/backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemaContentsController.cs @@ -86,8 +86,7 @@ public class SchemaContentsController(ICommandBus commandBus, IJobService jobSer request.Format ?? ExportFormat.Csv, request.Fields, request.Unpublished ?? false) - with - { Reference = reference, }; + with { Reference = reference }; await jobService.StartAsync(App.Id, job, HttpContext.RequestAborted); diff --git a/backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemasController.cs b/backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemasController.cs index 94e4cb091..0a98bd97a 100644 --- a/backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemasController.cs +++ b/backend/src/Squidex/Areas/Api/Controllers/Schemas/SchemasController.cs @@ -392,7 +392,7 @@ public sealed class SchemasController( [ApiExplorerSettings(IgnoreApi = true)] public async Task GetFilters(string app, string schema) { - var components = await appProvider.GetComponentsAsync(Schema, HttpContext.RequestAborted); + var components = await appProvider.GetComponentsAsync(Schema, ct: HttpContext.RequestAborted); var result = ContentQueryModel.Build(Schema, App.PartitionResolver(), components).Flatten(); var response = await QueryModelDto.FromModelAsync(result, App, Schema, workflows); @@ -402,7 +402,7 @@ public sealed class SchemasController( private async Task BuildModel() { - var components = await appProvider.GetComponentsAsync(Schema, HttpContext.RequestAborted); + var components = await appProvider.GetComponentsAsync(Schema, ct: HttpContext.RequestAborted); return Schema.BuildDataSchema(App.PartitionResolver(), components); } diff --git a/backend/src/Squidex/Config/Domain/ContentsServices.cs b/backend/src/Squidex/Config/Domain/ContentsServices.cs index 8012baabc..b32ccf987 100644 --- a/backend/src/Squidex/Config/Domain/ContentsServices.cs +++ b/backend/src/Squidex/Config/Domain/ContentsServices.cs @@ -14,6 +14,8 @@ using Squidex.Domain.Apps.Entities.Contents.Counter; using Squidex.Domain.Apps.Entities.Contents.Queries; using Squidex.Domain.Apps.Entities.Contents.Queries.Steps; using Squidex.Domain.Apps.Entities.Contents.Text; +using Squidex.Domain.Apps.Entities.Contents.Text.Extraction; +using Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; using Squidex.Domain.Apps.Entities.Contents.Validation; using Squidex.Domain.Apps.Entities.History; using Squidex.Domain.Apps.Entities.Search; @@ -112,7 +114,46 @@ public static class ContentsServices .AsOptional(); services.AddSingletonAs() - .As(); + .AsSelf().As(); + + services.AddSingletonAs() + .AsSelf(); + + services.AddSingletonAs() + .AsSelf(); + + services.AddSingletonAs() + .AsSelf(); + + services.AddSingletonAs() + .As(); + + services.AddSingletonAs() + .As(); + + services.AddSingletonAs() + .As(); + + services.AddSingletonAs() + .As(); + + services.AddSingletonAs() + .As(); + + services.AddSingletonAs() + .As(); + + services.AddSingletonAs() + .As(); + + services.AddSingletonAs() + .As(); + + services.AddSingletonAs() + .As(); + + services.AddSingletonAs() + .As(); services.AddSingletonAs() .As(); diff --git a/backend/src/Squidex/Config/Messaging/MessagingServices.cs b/backend/src/Squidex/Config/Messaging/MessagingServices.cs index baa865e2f..4f0cacd93 100644 --- a/backend/src/Squidex/Config/Messaging/MessagingServices.cs +++ b/backend/src/Squidex/Config/Messaging/MessagingServices.cs @@ -16,6 +16,7 @@ using Squidex.Domain.Apps.Entities.Contents; using Squidex.Domain.Apps.Entities.Contents.Export; using Squidex.Domain.Apps.Entities.Contents.Indexes; using Squidex.Domain.Apps.Entities.Contents.Migration; +using Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; using Squidex.Domain.Apps.Entities.Jobs; using Squidex.Domain.Apps.Entities.Rules.Runner; using Squidex.Domain.Apps.Entities.Rules.UsageTracking; @@ -104,6 +105,9 @@ public static class MessagingServices services.AddSingletonAs() .As(); + services.AddSingletonAs() + .As(); + services.AddSingleton(c => new SystemTextJsonMessagingSerializer(c.GetRequiredService())); diff --git a/backend/src/Squidex/Squidex.csproj b/backend/src/Squidex/Squidex.csproj index 7c5319d60..f82704c09 100644 --- a/backend/src/Squidex/Squidex.csproj +++ b/backend/src/Squidex/Squidex.csproj @@ -58,16 +58,16 @@ - - - - - - - - - - + + + + + + + + + + @@ -81,12 +81,12 @@ - + - + diff --git a/backend/tests/Squidex.Data.Tests/Shared/TextIndexerStateTests.cs b/backend/tests/Squidex.Data.Tests/Shared/TextIndexerStateTests.cs index 2fe446245..e40b96320 100644 --- a/backend/tests/Squidex.Data.Tests/Shared/TextIndexerStateTests.cs +++ b/backend/tests/Squidex.Data.Tests/Shared/TextIndexerStateTests.cs @@ -36,7 +36,7 @@ public abstract class TextIndexerStateTests : GivenContext await sut.SetAsync( [ - new TextContentState { UniqueContentId = id1, State = TextState.Stage0_Draft__Stage1_None }, + new TextContentState { UniqueContentId = id1, State = TextState.Stage0_Draft__Stage1_None, Version = 3 }, new TextContentState { UniqueContentId = id2, State = TextState.Stage0_Published__Stage1_Draft }, new TextContentState { UniqueContentId = id3, State = TextState.Stage0_Published__Stage1_None }, ]); @@ -45,7 +45,7 @@ public abstract class TextIndexerStateTests : GivenContext actual.Should().BeEquivalentTo(new Dictionary { - [id1] = new TextContentState { UniqueContentId = id1, State = TextState.Stage0_Draft__Stage1_None }, + [id1] = new TextContentState { UniqueContentId = id1, State = TextState.Stage0_Draft__Stage1_None, Version = 3 }, [id2] = new TextContentState { UniqueContentId = id2, State = TextState.Stage0_Published__Stage1_Draft }, }); } diff --git a/backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Schemas/Schema.json b/backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Schemas/Schema.json index 31be0fee8..92d93c651 100644 --- a/backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Schemas/Schema.json +++ b/backend/tests/Squidex.Domain.Apps.Core.Tests/Model/Schemas/Schema.json @@ -29,7 +29,8 @@ "isRequired": true, "isRequiredOnPublish": true, "isHalfWidth": false, - "isCreateOnly": false + "isCreateOnly": false, + "searchMode": "Default" } }, { @@ -54,7 +55,8 @@ "isRequired": false, "isRequiredOnPublish": false, "isHalfWidth": false, - "isCreateOnly": false + "isCreateOnly": false, + "searchMode": "Default" } }, { @@ -75,7 +77,8 @@ "isRequired": false, "isRequiredOnPublish": false, "isHalfWidth": false, - "isCreateOnly": false + "isCreateOnly": false, + "searchMode": "Default" } }, { @@ -94,7 +97,8 @@ "isRequired": false, "isRequiredOnPublish": false, "isHalfWidth": false, - "isCreateOnly": false + "isCreateOnly": false, + "searchMode": "Default" } }, { @@ -114,7 +118,8 @@ "isRequired": false, "isRequiredOnPublish": false, "isHalfWidth": false, - "isCreateOnly": false + "isCreateOnly": false, + "searchMode": "Default" } }, { @@ -132,7 +137,8 @@ "isRequired": true, "isRequiredOnPublish": true, "isHalfWidth": false, - "isCreateOnly": false + "isCreateOnly": false, + "searchMode": "Default" } }, { @@ -148,7 +154,8 @@ "isRequired": false, "isRequiredOnPublish": false, "isHalfWidth": true, - "isCreateOnly": false + "isCreateOnly": false, + "searchMode": "Default" } }, { @@ -163,7 +170,8 @@ "isRequired": false, "isRequiredOnPublish": false, "isHalfWidth": false, - "isCreateOnly": false + "isCreateOnly": false, + "searchMode": "Default" } }, { @@ -186,7 +194,8 @@ "1", "2", "3" - ] + ], + "searchMode": "Default" } }, { @@ -209,7 +218,8 @@ "isRequired": false, "isRequiredOnPublish": false, "isHalfWidth": false, - "isCreateOnly": false + "isCreateOnly": false, + "searchMode": "Default" } }, { @@ -239,7 +249,8 @@ "isRequired": false, "isRequiredOnPublish": false, "isHalfWidth": false, - "isCreateOnly": false + "isCreateOnly": false, + "searchMode": "Default" } }, { @@ -255,7 +266,8 @@ "isRequired": false, "isRequiredOnPublish": false, "isHalfWidth": false, - "isCreateOnly": false + "isCreateOnly": false, + "searchMode": "Default" }, "children": [ { @@ -275,7 +287,8 @@ "isRequired": false, "isRequiredOnPublish": false, "isHalfWidth": false, - "isCreateOnly": false + "isCreateOnly": false, + "searchMode": "Default" } } ] @@ -293,7 +306,8 @@ "isRequired": false, "isRequiredOnPublish": false, "isHalfWidth": false, - "isCreateOnly": true + "isCreateOnly": true, + "searchMode": "Default" } } ], diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/ContentQueryParserTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/ContentQueryParserTests.cs index 3e901a120..96ca3cf05 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/ContentQueryParserTests.cs +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Queries/ContentQueryParserTests.cs @@ -114,7 +114,7 @@ public class ContentQueryParserTests : GivenContext [Fact] public async Task Should_convert_full_text_query_to_filter_with_other_filter() { - A.CallTo(() => textIndex.SearchAsync(ApiContext.App, A.That.Matches(x => x.Text == "Hello"), ApiContext.Scope(), CancellationToken)) + A.CallTo(() => textIndex.SearchAsync(ApiContext.App, A.That.Matches(x => x.Text == "Hello" && x.RequiredSchemaIds!.SequenceEqual(new[] { SchemaId.Id })), ApiContext.Scope(), CancellationToken)) .Returns([DomainId.Create("1"), DomainId.Create("2")]); var query = Q.Empty.WithODataQuery("$search=Hello&$filter=data/firstName/iv eq 'ABC'"); diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/Rebuild/RebuildTextIndexJobTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/Rebuild/RebuildTextIndexJobTests.cs new file mode 100644 index 000000000..78cd062fd --- /dev/null +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/Rebuild/RebuildTextIndexJobTests.cs @@ -0,0 +1,141 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Domain.Apps.Core.Apps; +using Squidex.Events; +using Squidex.Infrastructure; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; + +public class RebuildTextIndexJobTests : TextIndexTestBase +{ + private readonly TextIndexingProcess process; + private readonly RebuildTextIndexJob sut; + + public RebuildTextIndexJobTests() + { + process = CreateProcess(); + + sut = CreateJob(process); + } + + [Fact] + public void Should_create_request() + { + var job = RebuildTextIndexJob.BuildRequest(User, App); + + job.Arguments.Should().BeEquivalentTo( + new Dictionary + { + ["appId"] = App.Id.ToString(), + ["appName"] = App.Name, + }); + + Assert.Equal(App.NamedId(), job.AppId); + Assert.Equal(RebuildTextIndexJob.TaskName, job.TaskName); + } + + [Fact] + public async Task Should_throw_exception_if_app_not_found() + { + A.CallTo(() => AppProvider.GetAppAsync(AppId.Id, true, A._)) + .Returns(Task.FromResult(null)); + + await Assert.ThrowsAsync(() => sut.RunAsync(CreateRunContext(), CancellationToken)); + } + + [Fact] + public async Task Should_throw_exception_if_app_is_already_rebuilt() + { + await Coordinator.TakeOverAsync(AppId.Id, CancellationToken); + + await Assert.ThrowsAsync(() => sut.RunAsync(CreateRunContext(), CancellationToken)); + } + + [Fact] + public async Task Should_replay_events_of_app() + { + StoreEvents(Created(TextData("field", "Version1"), 0), Updated(TextData("field", "Version2"), 1)); + + await sut.RunAsync(CreateRunContext(), CancellationToken); + + Assert.Equal("Version2", GetText()); + + A.CallTo(() => EventStore.QueryAllAsync(StreamFilter.Prefix($"content-{AppId.Id}{DomainId.IdSeparator}"), A.That.Matches(x => x.Token == null), A._, A._)) + .MustHaveHappened(); + } + + [Fact] + public async Task Should_replay_events_that_have_been_skipped_during_rebuild() + { + var updated = Updated(TextData("field", "Version2"), 1); + + StoreEvents(Created(TextData("field", "Version1"), 0)); + + var isFirst = true; + + A.CallTo(() => TextIndex.ExecuteAsync(A._, A._)) + .ReturnsLazily(async x => + { + Commands.AddRange(x.GetArgument(0)!); + + // The content is changed while the app is rebuilt, therefore the indexer skips the event. + if (isFirst) + { + isFirst = false; + + StoreEvents(updated); + await process.On([updated]); + } + }); + + await sut.RunAsync(CreateRunContext(), CancellationToken); + + Assert.Equal("Version2", GetText()); + } + + [Fact] + public async Task Should_index_app_again_after_rebuild() + { + StoreEvents(Created(TextData("field", "Version1"), 0)); + + await sut.RunAsync(CreateRunContext(), CancellationToken); + + await process.On([Updated(TextData("field", "Version2"), 1)]); + + Assert.Equal("Version2", GetText()); + } + + [Fact] + public async Task Should_replay_events_and_hand_back_if_rebuild_failed() + { + StoreEvents(Created(TextData("field", "Version1"), 0)); + + A.CallTo(() => EventStore.QueryAllAsync(A._, A._, A._, A._)) + .Throws(new OperationCanceledException()).Once(); + + await Assert.ThrowsAsync(() => sut.RunAsync(CreateRunContext(), CancellationToken)); + + await process.On([Updated(TextData("field", "Version2"), 1)]); + + Assert.Equal("Version2", GetText()); + Assert.Equal(2, Commands.OfType().Count()); + } + + [Fact] + public async Task Should_release_app_if_hand_back_failed() + { + A.CallTo(() => EventStore.QueryAllAsync(A._, A._, A._, A._)) + .Throws(new InvalidOperationException()); + + await Assert.ThrowsAsync(() => sut.RunAsync(CreateRunContext(), CancellationToken)); + + await process.On([Created(TextData("field", "Hello"), 0)]); + + Assert.Equal("Hello", GetText()); + } +} diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/Rebuild/TextIndexRebuildCoordinatorTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/Rebuild/TextIndexRebuildCoordinatorTests.cs new file mode 100644 index 000000000..2812892d7 --- /dev/null +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/Rebuild/TextIndexRebuildCoordinatorTests.cs @@ -0,0 +1,114 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using Squidex.Infrastructure; + +namespace Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; + +public class TextIndexRebuildCoordinatorTests +{ + private readonly DomainId appId = DomainId.NewGuid(); + private readonly TextIndexRebuildCoordinator sut = new TextIndexRebuildCoordinator(); + + [Fact] + public async Task Should_throw_exception_if_app_is_already_taken_over() + { + await sut.TakeOverAsync(appId); + + await Assert.ThrowsAsync(() => sut.TakeOverAsync(appId)); + } + + [Fact] + public async Task Should_not_skip_events_if_app_is_not_taken_over() + { + using var batch = await sut.BeginBatchAsync(); + + Assert.False(batch.TrySkip(appId)); + } + + [Fact] + public async Task Should_skip_and_count_events_if_app_is_taken_over() + { + await sut.TakeOverAsync(appId); + + using (var batch = await sut.BeginBatchAsync()) + { + Assert.True(batch.TrySkip(appId)); + Assert.True(batch.TrySkip(appId)); + Assert.False(batch.TrySkip(DomainId.NewGuid())); + } + + var skipped = await sut.GetSkippedEventsAsync(appId); + + Assert.Equal(2, skipped); + } + + [Fact] + public async Task Should_not_hand_back_if_events_have_been_skipped_in_the_meantime() + { + await sut.TakeOverAsync(appId); + + using (var batch = await sut.BeginBatchAsync()) + { + batch.TrySkip(appId); + } + + var handedBack = await sut.TryHandBackAsync(appId, 0); + + Assert.False(handedBack); + } + + [Fact] + public async Task Should_hand_back_if_no_events_have_been_skipped_in_the_meantime() + { + await sut.TakeOverAsync(appId); + + using (var batch = await sut.BeginBatchAsync()) + { + batch.TrySkip(appId); + } + + var handedBack = await sut.TryHandBackAsync(appId, 1); + + using (var batch = await sut.BeginBatchAsync()) + { + Assert.False(batch.TrySkip(appId)); + } + + Assert.True(handedBack); + } + + [Fact] + public async Task Should_not_skip_events_after_release() + { + await sut.TakeOverAsync(appId); + await sut.ReleaseAsync(appId); + + using (var batch = await sut.BeginBatchAsync()) + { + Assert.False(batch.TrySkip(appId)); + } + + await sut.TakeOverAsync(appId); + } + + [Fact] + public async Task Should_not_hand_back_while_batch_is_processed() + { + await sut.TakeOverAsync(appId); + + var batch = await sut.BeginBatchAsync(); + + var handBack = sut.TryHandBackAsync(appId, 0); + + Assert.False(handBack.IsCompleted); + + batch.Dispose(); + + Assert.True(await handBack); + } +} diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextExtractionContextTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextExtractionContextTests.cs new file mode 100644 index 000000000..6ce2d204d --- /dev/null +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextExtractionContextTests.cs @@ -0,0 +1,94 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using System.Globalization; +using Squidex.Domain.Apps.Entities.Contents.Text.Extraction; +using Squidex.Infrastructure; + +namespace Squidex.Domain.Apps.Entities.Contents.Text; + +public class TextExtractionContextTests +{ + private readonly object key = new object(); + private readonly TextExtractionContext sut = new TextExtractionContext + { + AppId = NamedId.Of(DomainId.NewGuid(), "my-app"), + SchemaId = NamedId.Of(DomainId.NewGuid(), "my-schema"), + }; + + [Fact] + public void Should_create_value_only_once() + { + var calls = new List(); + + var value1 = sut.GetOrAdd(key, 42, x => Create(calls, x)); + var value2 = sut.GetOrAdd(key, 13, x => Create(calls, x)); + + Assert.Equal("42", value1); + Assert.Equal("42", value2); + Assert.Equal([42], calls); + } + + [Fact] + public void Should_cache_null_value() + { + var calls = new List(); + + var value1 = sut.GetOrAdd(key, 42, x => CreateNull(calls, x)); + var value2 = sut.GetOrAdd(key, 13, x => CreateNull(calls, x)); + + Assert.Null(value1); + Assert.Null(value2); + + Assert.Equal([42], calls); + } + + [Fact] + public void Should_dispose_value_if_removed() + { + var disposable = A.Fake(); + + sut.GetOrAdd(key, disposable, x => x); + sut.Remove(key); + + var value = sut.GetOrAdd(key, 0, x => "new"); + + Assert.Equal("new", value); + A.CallTo(() => disposable.Dispose()) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public void Should_dispose_values_if_disposed() + { + var disposable1 = A.Fake(); + var disposable2 = A.Fake(); + + sut.GetOrAdd(new object(), disposable1, x => x); + sut.GetOrAdd(new object(), disposable2, x => x); + sut.Dispose(); + + A.CallTo(() => disposable1.Dispose()) + .MustHaveHappenedOnceExactly(); + A.CallTo(() => disposable2.Dispose()) + .MustHaveHappenedOnceExactly(); + } + + private static string Create(List calls, int value) + { + calls.Add(value); + + return value.ToString(CultureInfo.InvariantCulture); + } + + private static string? CreateNull(List calls, int value) + { + calls.Add(value); + + return null; + } +} diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextExtractorTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextExtractorTests.cs new file mode 100644 index 000000000..1e8b55222 --- /dev/null +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextExtractorTests.cs @@ -0,0 +1,682 @@ +// ========================================================================== +// 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.Core.Scripting; +using Squidex.Domain.Apps.Entities.Contents.Text.Extraction; +using Squidex.Infrastructure; +using Squidex.Infrastructure.Collections; +using Squidex.Infrastructure.Json.Objects; + +namespace Squidex.Domain.Apps.Entities.Contents.Text; + +public class TextExtractorTests +{ + private readonly DomainId componentId = DomainId.NewGuid(); + private readonly IScriptEngine scriptEngine = A.Fake(); + private readonly TextExtractor sut; + + public TextExtractorTests() + { + sut = CreateExtractor(scriptEngine); + } + + public static TextExtractor CreateExtractor(IScriptEngine scriptEngine) + { + ITextFieldStrategy[] fieldStrategies = + [ + new ArrayFieldTextStrategy(), + new ComponentTextStrategy(), + new JsonTextStrategy(), + new RichTextFieldTextStrategy(), + new SearchPathsFieldTextStrategy(), + ]; + + ITextNormalizer[] normalizers = + [ + new HtmlTextNormalizer(), + new MarkdownTextNormalizer(), + new NoiseTextNormalizer(), + ]; + + return new TextExtractor( + [ + new SchemaTextExtractionStrategy(fieldStrategies, normalizers), + new ScriptTextExtractionStrategy(scriptEngine), + ]); + } + + [Fact] + public void Should_extract_texts_by_language_without_schema() + { + var data = + new ContentData() + .AddField("field1", + new ContentFieldData() + .AddLocalized("en", "Hello") + .AddLocalized("de", "Hallo")) + .AddField("field2", + new ContentFieldData() + .AddLocalized("en", "World")); + + var actual = Extract(data); + + Assert.Equal("Hello World", actual!.Texts!["en"]); + Assert.Equal("Hallo", actual!.Texts!["de"]); + Assert.Null(actual!.Titles); + } + + [Fact] + public void Should_return_null_if_no_text_found() + { + var data = + new ContentData() + .AddField("field1", + new ContentFieldData() + .AddInvariant(42)); + + var actual = Extract(data); + + Assert.Null(actual); + } + + [Fact] + public void Should_extract_all_strings_from_json_values() + { + var data = + new ContentData() + .AddField("json", + new ContentFieldData() + .AddInvariant( + JsonValue.Object() + .Add("label", "Hello") + .Add("nested", JsonValue.Array(JsonValue.Object().Add("text", "World"))))); + + var actual = Extract(data); + + Assert.Equal("Hello World", actual!.Texts![InvariantPartitioning.Key]); + } + + [Theory] + [InlineData("a3d0e3c8-4c7b-4b54-8c9e-3a7c0d1f2e5b")] + [InlineData("42")] + [InlineData("3.14")] + [InlineData("#ff0000")] + [InlineData("#fff")] + [InlineData("2024-01-15")] + [InlineData("2024-01-15T10:30:00Z")] + [InlineData("https://squidex.io/path?query=1")] + [InlineData("data:image/png;base64,iVBORw0KGgo")] + [InlineData("dGhpc2lzYXZlcnlsb25nYmFzZTY0c3RyaW5ndGhhdHNob3VsZGJlZmlsdGVyZWRvdXRieXRoZWZpbHRlcg==")] + [InlineData(" ")] + public void Should_detect_noise(string text) + { + Assert.True(NoiseTextNormalizer.IsNoise(text)); + } + + [Theory] + [InlineData("Hello")] + [InlineData("my-great-article")] + [InlineData("Visit https://squidex.io for more")] + [InlineData("42 is the answer")] + [InlineData("mail@squidex.io")] + public void Should_not_detect_text_as_noise(string text) + { + Assert.False(NoiseTextNormalizer.IsNoise(text)); + } + + [Fact] + public void Should_skip_reference_ids() + { + var schema = + new Schema { Name = "my-schema" } + .AddString(1, "title", Partitioning.Invariant) + .AddReferences(2, "references", Partitioning.Invariant); + + var data = + new ContentData() + .AddField("title", + new ContentFieldData() + .AddInvariant("Hello")) + .AddField("references", + new ContentFieldData() + .AddInvariant(JsonValue.Array(DomainId.NewGuid().ToString(), DomainId.NewGuid().ToString()))); + + var actual = Extract(data, schema); + + Assert.Equal("Hello", actual!.Titles![InvariantPartitioning.Key]); + Assert.Null(actual!.Texts); + } + + [Fact] + public void Should_use_first_field_as_title_if_nothing_configured() + { + var schema = + new Schema { Name = "my-schema" } + .AddString(1, "title", Partitioning.Invariant) + .AddString(2, "description", Partitioning.Invariant); + + var data = + new ContentData() + .AddField("description", + new ContentFieldData() + .AddInvariant("World")) + .AddField("title", + new ContentFieldData() + .AddInvariant("Hello")); + + var actual = Extract(data, schema); + + Assert.Equal("Hello", actual!.Titles![InvariantPartitioning.Key]); + Assert.Equal("World", actual!.Texts![InvariantPartitioning.Key]); + } + + [Fact] + public void Should_use_fields_in_references_as_title() + { + var schema = + new Schema { Name = "my-schema" } + .AddString(1, "description", Partitioning.Invariant) + .AddString(2, "title", Partitioning.Invariant) + .SetFieldsInReferences(FieldNames.Create("data.title")) + .SetFieldsInLists(FieldNames.Create("data.description")); + + var data = + new ContentData() + .AddField("description", + new ContentFieldData() + .AddInvariant("World")) + .AddField("title", + new ContentFieldData() + .AddInvariant("Hello")); + + var actual = Extract(data, schema); + + Assert.Equal("Hello", actual!.Titles![InvariantPartitioning.Key]); + Assert.Equal("World", actual!.Texts![InvariantPartitioning.Key]); + } + + [Fact] + public void Should_use_fields_with_title_mode_as_title() + { + var schema = + new Schema { Name = "my-schema" } + .AddString(1, "description", Partitioning.Invariant) + .AddJson(2, "json", Partitioning.Invariant, + new JsonFieldProperties { SearchMode = FieldSearchMode.Title }) + .SetFieldsInReferences(FieldNames.Create("data.other")); + + var data = + new ContentData() + .AddField("description", + new ContentFieldData() + .AddInvariant("World")) + .AddField("json", + new ContentFieldData() + .AddInvariant(JsonValue.Object().Add("name", "Hello"))); + + var actual = Extract(data, schema); + + Assert.Equal("Hello", actual!.Titles![InvariantPartitioning.Key]); + Assert.Equal("World", actual!.Texts![InvariantPartitioning.Key]); + } + + [Fact] + public void Should_skip_excluded_fields() + { + var schema = + new Schema { Name = "my-schema" } + .AddString(1, "title", Partitioning.Invariant) + .AddString(2, "internal", Partitioning.Invariant, + new StringFieldProperties { SearchMode = FieldSearchMode.Exclude }); + + var data = + new ContentData() + .AddField("title", + new ContentFieldData() + .AddInvariant("Hello")) + .AddField("internal", + new ContentFieldData() + .AddInvariant("Secret")); + + var actual = Extract(data, schema); + + Assert.Equal("Hello", actual!.Titles![InvariantPartitioning.Key]); + Assert.Null(actual!.Texts); + } + + [Fact] + public void Should_only_index_search_paths() + { + var schema = + new Schema { Name = "my-schema" } + .AddString(1, "title", Partitioning.Invariant) + .AddJson(2, "json", Partitioning.Invariant, + new JsonFieldProperties { SearchPaths = ReadonlyList.Create("$.items[*].label", "author.name") }); + + var data = + new ContentData() + .AddField("json", + new ContentFieldData() + .AddInvariant( + JsonValue.Object() + .Add("items", + JsonValue.Array( + JsonValue.Object().Add("label", "Label1").Add("config", "Hidden1"), + JsonValue.Object().Add("label", "Label2").Add("config", "Hidden2"))) + .Add("author", JsonValue.Object().Add("name", "Sebastian")) + .Add("other", "Hidden3"))); + + var actual = Extract(data, schema); + + Assert.Equal("Label1 Label2 Sebastian", actual!.Texts![InvariantPartitioning.Key]); + } + + [Fact] + public void Should_apply_settings_of_nested_fields() + { + var schema = + new Schema { Name = "my-schema" } + .AddString(1, "title", Partitioning.Invariant) + .AddArray(2, "array", Partitioning.Invariant, a => a + .AddString(21, "nested1") + .AddString(22, "nested2", + new StringFieldProperties { SearchMode = FieldSearchMode.Exclude })); + + var data = + new ContentData() + .AddField("array", + new ContentFieldData() + .AddInvariant( + JsonValue.Array( + JsonValue.Object().Add("nested1", "Hello").Add("nested2", "Hidden")))); + + var actual = Extract(data, schema); + + Assert.Equal("Hello", actual!.Texts![InvariantPartitioning.Key]); + } + + [Fact] + public void Should_apply_settings_of_component_fields() + { + var componentSchema = + new Schema { Name = "my-component" } + .AddString(1, "visible", Partitioning.Invariant) + .AddString(2, "hidden", Partitioning.Invariant, + new StringFieldProperties { SearchMode = FieldSearchMode.Exclude }); + + var schema = + new Schema { Name = "my-schema" } + .AddString(1, "title", Partitioning.Invariant) + .AddComponent(2, "component", Partitioning.Invariant); + + var components = new ResolvedComponents(new Dictionary + { + [componentId] = componentSchema, + }); + + var data = + new ContentData() + .AddField("component", + new ContentFieldData() + .AddInvariant( + JsonValue.Object() + .Add(Component.Discriminator, componentId.ToString()) + .Add("visible", "Hello") + .Add("hidden", "Hidden"))); + + var actual = Extract(data, schema, components); + + Assert.Equal("Hello", actual!.Texts![InvariantPartitioning.Key]); + } + + [Fact] + public void Should_convert_markdown_to_text() + { + var schema = + new Schema { Name = "my-schema" } + .AddString(1, "title", Partitioning.Invariant) + .AddString(2, "markdown", Partitioning.Invariant, + new StringFieldProperties { Editor = StringFieldEditor.Markdown }); + + var data = + new ContentData() + .AddField("markdown", + new ContentFieldData() + .AddInvariant("# Hello **World**")); + + var actual = Extract(data, schema); + + Assert.Equal("Hello World", actual!.Texts![InvariantPartitioning.Key]); + } + + [Fact] + public void Should_use_custom_field_strategy_before_default_strategies() + { + var customStrategy = A.Fake(); + + A.CallTo(() => customStrategy.Order) + .Returns(-1); + + A.CallTo(() => customStrategy.TryExtract(A.That.Matches(x => x != null && x.Name == "custom"), A._, A._)) + .Invokes(x => x.GetArgument(2)!.AppendText("Custom")) + .Returns(true); + + var customExtractor = new TextExtractor([new SchemaTextExtractionStrategy([customStrategy, new JsonTextStrategy()], [])]); + + var schema = + new Schema { Name = "my-schema" } + .AddString(1, "title", Partitioning.Invariant) + .AddJson(2, "custom", Partitioning.Invariant, + new JsonFieldProperties { EditorUrl = "https://editor.io" }); + + var data = + new ContentData() + .AddField("custom", + new ContentFieldData() + .AddInvariant(JsonValue.Object().Add("raw", "Hidden"))); + + var actual = Extract(customExtractor, data, schema); + + Assert.Equal("Custom", actual!.Texts![InvariantPartitioning.Key]); + } + + [Fact] + public void Should_apply_normalizers_in_order_and_exclude_dropped_texts() + { + var normalizer1 = A.Fake(); + var normalizer2 = A.Fake(); + + A.CallTo(() => normalizer1.Order) + .Returns(2); + + A.CallTo(() => normalizer1.Normalize(A._, A._)) + .ReturnsLazily(x => x.GetArgument(0) == "Drop!" ? null : x.GetArgument(0)); + + A.CallTo(() => normalizer2.Order) + .Returns(1); + + A.CallTo(() => normalizer2.Normalize(A._, A._)) + .ReturnsLazily(x => $"{x.GetArgument(0)}!"); + + var customExtractor = new TextExtractor([new SchemaTextExtractionStrategy([new JsonTextStrategy()], [normalizer1, normalizer2])]); + + var data = + new ContentData() + .AddField("field", + new ContentFieldData() + .AddInvariant(JsonValue.Array("Drop", "Keep"))); + + var actual = Extract(customExtractor, data); + + Assert.Equal("Keep!", actual!.Texts![InvariantPartitioning.Key]); + } + + [Fact] + public void Should_not_convert_markdown_if_field_is_not_markdown() + { + var schema = + new Schema { Name = "my-schema" } + .AddString(1, "title", Partitioning.Invariant) + .AddString(2, "input", Partitioning.Invariant); + + var data = + new ContentData() + .AddField("input", + new ContentFieldData() + .AddInvariant("C# **is** great")); + + var actual = Extract(data, schema); + + Assert.Equal("C# **is** great", actual!.Texts![InvariantPartitioning.Key]); + } + + [Fact] + public void Should_convert_html_to_text() + { + var data = + new ContentData() + .AddField("html", + new ContentFieldData() + .AddInvariant("

Hello World & more

")); + + var actual = Extract(data); + + Assert.Equal("Hello World & more", actual!.Texts![InvariantPartitioning.Key]); + } + + [Fact] + public void Should_convert_rich_text_to_text() + { + var schema = + new Schema { Name = "my-schema" } + .AddString(1, "title", Partitioning.Invariant) + .AddRichText(2, "richText", Partitioning.Invariant); + + var data = + new ContentData() + .AddField("richText", + new ContentFieldData() + .AddInvariant( + JsonValue.Object() + .Add("type", "doc") + .Add("content", + JsonValue.Array( + JsonValue.Object() + .Add("type", "paragraph") + .Add("content", + JsonValue.Array( + JsonValue.Object() + .Add("type", "text") + .Add("text", "Hello World"))))))); + + var actual = Extract(data, schema); + + Assert.Equal("Hello World", actual!.Texts![InvariantPartitioning.Key]); + } + + [Fact] + public void Should_return_null_for_undefined_script_result() + { + var actual = ScriptTextExtractionStrategy.ToTexts(JsonValue.Null); + + Assert.Null(actual); + } + + [Fact] + public void Should_convert_string_script_result() + { + var actual = ScriptTextExtractionStrategy.ToTexts(JsonValue.Create("Hello World")); + + Assert.Equal("Hello World", actual!.Texts![InvariantPartitioning.Key]); + Assert.Null(actual!.Titles); + } + + [Fact] + public void Should_convert_object_script_result() + { + var result = + JsonValue.Object() + .Add("title", "Hello") + .Add("body", + JsonValue.Object() + .Add("en", "World") + .Add("de", "Welt")); + + var actual = ScriptTextExtractionStrategy.ToTexts(result); + + Assert.Equal("Hello", actual!.Titles![InvariantPartitioning.Key]); + Assert.Equal("World", actual!.Texts!["en"]); + Assert.Equal("Welt", actual!.Texts!["de"]); + } + + [Fact] + public void Should_use_script_before_schema() + { + var script = A.Fake(); + + A.CallTo(() => scriptEngine.CreateScript("script", A._)) + .Returns(script); + + A.CallTo(() => script.Execute(A._)) + .Returns(JsonValue.Create("Scripted")); + + var actual = Extract(CreateData("Hello"), CreateScriptSchema()); + + Assert.Equal("Scripted", actual!.Texts![InvariantPartitioning.Key]); + Assert.Null(actual!.Titles); + } + + [Fact] + public void Should_fallback_to_schema_if_script_returns_null() + { + var script = A.Fake(); + + A.CallTo(() => scriptEngine.CreateScript("script", A._)) + .Returns(script); + + A.CallTo(() => script.Execute(A._)) + .Returns(JsonValue.Null); + + var actual = Extract(CreateData("Hello"), CreateScriptSchema()); + + Assert.Equal("Hello", actual!.Titles![InvariantPartitioning.Key]); + } + + [Fact] + public void Should_not_fallback_to_schema_if_script_returns_empty_object() + { + var script = A.Fake(); + + A.CallTo(() => scriptEngine.CreateScript("script", A._)) + .Returns(script); + + A.CallTo(() => script.Execute(A._)) + .Returns(JsonValue.Object()); + + var actual = Extract(CreateData("Hello"), CreateScriptSchema()); + + Assert.Null(actual!.Texts); + Assert.Null(actual!.Titles); + } + + [Fact] + public void Should_compile_script_only_once_per_context() + { + var script = A.Fake(); + + A.CallTo(() => scriptEngine.CreateScript("script", A._)) + .Returns(script); + + A.CallTo(() => script.Execute(A._)) + .Returns(JsonValue.Create("Scripted")); + + using (var context = CreateContext(CreateScriptSchema())) + { + sut.Extract(context, DomainId.NewGuid(), CreateData("Hello")); + sut.Extract(context, DomainId.NewGuid(), CreateData("World")); + } + + A.CallTo(() => scriptEngine.CreateScript("script", A._)) + .MustHaveHappenedOnceExactly(); + A.CallTo(() => script.Execute(A._)) + .MustHaveHappenedTwiceExactly(); + A.CallTo(() => script.Dispose()) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public void Should_recompile_script_after_error() + { + var script = A.Fake(); + + A.CallTo(() => scriptEngine.CreateScript("script", A._)) + .Returns(script); + + A.CallTo(() => script.Execute(A._)) + .Throws(new InvalidOperationException()); + + using var context = CreateContext(CreateScriptSchema()); + + var actual1 = sut.Extract(context, DomainId.NewGuid(), CreateData("Hello")); + var actual2 = sut.Extract(context, DomainId.NewGuid(), CreateData("World")); + + Assert.Equal("Hello", actual1!.Titles![InvariantPartitioning.Key]); + Assert.Equal("World", actual2!.Titles![InvariantPartitioning.Key]); + + A.CallTo(() => scriptEngine.CreateScript("script", A._)) + .MustHaveHappenedTwiceExactly(); + A.CallTo(() => script.Dispose()) + .MustHaveHappenedTwiceExactly(); + } + + [Fact] + public void Should_fallback_to_schema_if_script_cannot_be_compiled() + { + A.CallTo(() => scriptEngine.CreateScript("script", A._)) + .Throws(new InvalidOperationException()); + + using var context = CreateContext(CreateScriptSchema()); + + var actual1 = sut.Extract(context, DomainId.NewGuid(), CreateData("Hello")); + var actual2 = sut.Extract(context, DomainId.NewGuid(), CreateData("World")); + + Assert.Equal("Hello", actual1!.Titles![InvariantPartitioning.Key]); + Assert.Equal("World", actual2!.Titles![InvariantPartitioning.Key]); + + A.CallTo(() => scriptEngine.CreateScript("script", A._)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public void Should_return_text_if_html_cannot_be_parsed() + { + var actual = new HtmlTextNormalizer().Normalize("", null); + + Assert.NotNull(actual); + } + + private static Schema CreateScriptSchema() + { + return new Schema { Name = "my-schema" } + .AddString(1, "title", Partitioning.Invariant) + .SetScripts(new SchemaScripts { Index = "script" }); + } + + private static ContentData CreateData(string title) + { + return new ContentData() + .AddField("title", + new ContentFieldData() + .AddInvariant(title)); + } + + private ExtractedTexts? Extract(ContentData data, Schema? schema = null, ResolvedComponents? components = null) + { + return Extract(sut, data, schema, components); + } + + private static ExtractedTexts? Extract(TextExtractor extractor, ContentData data, Schema? schema = null, ResolvedComponents? components = null) + { + using var context = CreateContext(schema, components); + + return extractor.Extract(context, DomainId.NewGuid(), data); + } + + private static TextExtractionContext CreateContext(Schema? schema, ResolvedComponents? components = null) + { + return new TextExtractionContext + { + AppId = NamedId.Of(DomainId.NewGuid(), "my-app"), + Components = components ?? ResolvedComponents.Empty, + Schema = schema, + SchemaId = NamedId.Of(DomainId.NewGuid(), "my-schema"), + }; + } +} diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexTestBase.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexTestBase.cs new file mode 100644 index 000000000..c3cdca00a --- /dev/null +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexTestBase.cs @@ -0,0 +1,171 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +using System.Globalization; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Options; +using Squidex.Domain.Apps.Core; +using Squidex.Domain.Apps.Core.Contents; +using Squidex.Domain.Apps.Core.Scripting; +using Squidex.Domain.Apps.Core.TestHelpers; +using Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; +using Squidex.Domain.Apps.Entities.Contents.Text.State; +using Squidex.Domain.Apps.Entities.Jobs; +using Squidex.Domain.Apps.Entities.TestHelpers; +using Squidex.Domain.Apps.Events.Contents; +using Squidex.Events; +using Squidex.Infrastructure; +using Squidex.Infrastructure.EventSourcing; +using Squidex.Infrastructure.States; +using IClock = NodaTime.IClock; + +namespace Squidex.Domain.Apps.Entities.Contents.Text; + +public abstract class TextIndexTestBase : GivenContext +{ + private readonly List<(StoredEvent Stored, Envelope Parsed)> storedEvents = []; + private long lastVersion = -1; + + protected ITextIndex TextIndex { get; } = A.Fake(); + + protected IEventStore EventStore { get; } = A.Fake(); + + protected IEventFormatter EventFormatter { get; } = A.Fake(); + + protected InMemoryTextIndexerState TextIndexerState { get; } = new InMemoryTextIndexerState(); + + protected TextIndexRebuildCoordinator Coordinator { get; } = new TextIndexRebuildCoordinator(); + + protected List Commands { get; } = []; + + protected DomainId ContentId { get; } = DomainId.NewGuid(); + + protected TextIndexExtraction Extraction { get; } + + protected TextIndexTestBase() + { + A.CallTo(() => TextIndex.ExecuteAsync(A._, A._)) + .Invokes(x => Commands.AddRange(x.GetArgument(0)!)); + + A.CallTo(() => EventStore.QueryAllAsync(A._, A._, A._, A._)) + .ReturnsLazily(x => QueryEvents(x.GetArgument(1).Token)); + + A.CallTo(() => EventFormatter.ParseIfKnown(A._)) + .ReturnsLazily(x => storedEvents.Find(e => e.Stored == x.GetArgument(0)).Parsed); + + var scriptEngine = + new JintScriptEngine(new MemoryCache(Options.Create(new MemoryCacheOptions())), + Options.Create(new JintScriptOptions + { + TimeoutScript = TimeSpan.FromSeconds(2), + TimeoutExecution = TimeSpan.FromSeconds(10), + })); + + Extraction = new TextIndexExtraction(AppProvider, TextExtractorTests.CreateExtractor(scriptEngine)); + } + + protected TextIndexingProcess CreateProcess() + { + return new TextIndexingProcess(TestUtils.DefaultSerializer, TextIndex, TextIndexerState, Extraction, Coordinator); + } + + protected RebuildTextIndexJob CreateJob(TextIndexingProcess process) + { + return new RebuildTextIndexJob(AppProvider, EventStore, EventFormatter, process, Coordinator); + } + + protected JobRunContext CreateRunContext() + { + var state = new SimpleState(A.Fake>(), GetType(), App.Id); + + var jobRequest = RebuildTextIndexJob.BuildRequest(User, App); + + return new JobRunContext(state, A.Fake(), default) + { + Actor = User, + Job = new Job { Id = DomainId.NewGuid(), Arguments = jobRequest.Arguments }, + OwnerId = App.Id, + }; + } + + protected void StoreEvents(params Envelope[] events) + { + foreach (var @event in events) + { + var position = storedEvents.Count.ToString(CultureInfo.InvariantCulture); + + var stored = new StoredEvent("content", position, 0, new EventData("Type", [], "Payload")); + + storedEvents.Add((stored, @event)); + } + } + + protected async Task GetStateAsync() + { + var states = await TextIndexerState.GetAsync([UniqueId()]); + + return states.GetValueOrDefault(UniqueId()); + } + + protected string? GetText() + { + return Commands.OfType().Last().Texts?[InvariantPartitioning.Key]; + } + + protected string? GetTitle() + { + return Commands.OfType().Last().Titles?[InvariantPartitioning.Key]; + } + + protected UniqueContentId UniqueId() + { + return new UniqueContentId(AppId.Id, ContentId); + } + + protected static ContentData TextData(string field, string text) + { + return new ContentData() + .AddField(field, + new ContentFieldData() + .AddInvariant(text)); + } + + protected Envelope Created(ContentData data, long? version = null, NamedId? appId = null) + { + return CreateEnvelope(new ContentCreated { Data = data }, version, appId); + } + + protected Envelope Updated(ContentData data, long? version = null) + { + return CreateEnvelope(new ContentUpdated { Data = data }, version); + } + + protected Envelope Published(long? version = null) + { + return CreateEnvelope(new ContentStatusChanged { Status = Status.Published }, version); + } + + private IAsyncEnumerable QueryEvents(string? position) + { + // The position is the index of the last event that has been read. + var skip = position != null ? int.Parse(position, CultureInfo.InvariantCulture) + 1 : 0; + + return storedEvents.Skip(skip).Select(x => x.Stored).ToList().ToAsyncEnumerable(); + } + + private Envelope CreateEnvelope(ContentEvent @event, long? version, NamedId? appId = null) + { + @event.AppId = appId ?? AppId; + @event.ContentId = ContentId; + @event.SchemaId = SchemaId; + + // The indexer ignores events with versions that have already been indexed, therefore we need increasing versions. + lastVersion = Math.Max(lastVersion, version ?? lastVersion + 1); + + return Envelope.Create(@event).SetEventStreamNumber(version ?? lastVersion); + } +} diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexerTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexerTests.cs index 0b0cee195..116de153b 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexerTests.cs +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexerTests.cs @@ -5,9 +5,13 @@ // All rights reserved. Licensed under the MIT license. // ========================================================================== +using Microsoft.Extensions.Logging; using Squidex.Domain.Apps.Core.Contents; +using Squidex.Domain.Apps.Core.Scripting; using Squidex.Domain.Apps.Core.TestHelpers; +using Squidex.Domain.Apps.Entities.Contents.Text.Rebuild; using Squidex.Domain.Apps.Entities.Contents.Text.State; +using Squidex.Domain.Apps.Entities.Jobs; using Squidex.Domain.Apps.Entities.TestHelpers; using Squidex.Domain.Apps.Events.Contents; using Squidex.Events; @@ -21,6 +25,7 @@ namespace Squidex.Domain.Apps.Entities.Contents.Text; public abstract class TextIndexerTests : GivenContext { + private readonly Dictionary versions = []; private TextIndexingProcess? process; protected List Ids1 { get; } = [DomainId.NewGuid()]; @@ -499,7 +504,12 @@ public abstract class TextIndexerTests : GivenContext contentEvent.AppId = AppId; contentEvent.SchemaId = SchemaId; - await sut.On(Enumerable.Repeat(Envelope.Create(contentEvent), 1)); + // The indexer ignores events with versions that have already been indexed. + var version = versions.GetValueOrDefault(id, -1) + 1; + + versions[id] = version; + + await sut.On([Envelope.Create(contentEvent).SetEventStreamNumber(version)]); } private static ContentData TextData(string language, string text) @@ -627,7 +637,11 @@ public abstract class TextIndexerTests : GivenContext { var index = await CreateSutAsync(); - process = new TextIndexingProcess(TestUtils.DefaultSerializer, index, new InMemoryTextIndexerState()); + var coordinator = new TextIndexRebuildCoordinator(); + + var extraction = new TextIndexExtraction(AppProvider, TextExtractorTests.CreateExtractor(A.Fake())); + + process = new TextIndexingProcess(TestUtils.DefaultSerializer, index, new InMemoryTextIndexerState(), extraction, coordinator); } return process; diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexingProcessTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexingProcessTests.cs new file mode 100644 index 000000000..d1013f211 --- /dev/null +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/TextIndexingProcessTests.cs @@ -0,0 +1,168 @@ +// ========================================================================== +// 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.Text.State; +using Squidex.Infrastructure; + +namespace Squidex.Domain.Apps.Entities.Contents.Text; + +public class TextIndexingProcessTests : TextIndexTestBase +{ + private readonly TextIndexingProcess sut; + + public TextIndexingProcessTests() + { + sut = CreateProcess(); + } + + [Fact] + public async Task Should_use_schema_to_extract_texts() + { + Schema = Schema + .AddString(1, "title", Partitioning.Invariant) + .AddString(2, "internal", Partitioning.Invariant, + new StringFieldProperties { SearchMode = FieldSearchMode.Exclude }); + + await sut.On([Created(TextData("title", "Hello").AddField("internal", new ContentFieldData().AddInvariant("Secret")))]); + + Assert.Equal("Hello", GetTitle()); + Assert.Null(GetText()); + } + + [Fact] + public async Task Should_use_index_script_to_extract_texts() + { + Schema = Schema.SetScripts(new SchemaScripts + { + Index = "complete({ title: ctx.data.title.iv, body: 'World' });", + }); + + await sut.On([Created(TextData("title", "Hello"))]); + + Assert.Equal("Hello", GetTitle()); + Assert.Equal("World", GetText()); + } + + [Fact] + public async Task Should_fallback_to_default_if_index_script_fails() + { + Schema = Schema.SetScripts(new SchemaScripts + { + Index = "throw 'Error';", + }); + + await sut.On([Created(TextData("field", "Hello"))]); + + Assert.Equal("Hello", GetText()); + } + + [Fact] + public async Task Should_store_version_of_last_event() + { + await sut.On([Created(TextData("field", "Hello"), 0), Updated(TextData("field", "World"), 1)]); + + var state = await GetStateAsync(); + + Assert.Equal(1, state?.Version); + } + + [Fact] + public async Task Should_skip_events_that_have_already_been_indexed_by_rebuild() + { + await TextIndexerState.SetAsync([new TextContentState { UniqueContentId = UniqueId(), State = TextState.Stage0_Draft__Stage1_None, Version = 5 }]); + + await sut.On([Updated(TextData("field", "Old"), 4), Updated(TextData("field", "Current"), 5)]); + + Assert.Empty(Commands); + } + + [Fact] + public async Task Should_handle_events_after_version_of_rebuild() + { + await TextIndexerState.SetAsync([new TextContentState { UniqueContentId = UniqueId(), State = TextState.Stage0_Draft__Stage1_None, Version = 5 }]); + + await sut.On([Updated(TextData("field", "Old"), 5), Updated(TextData("field", "New"), 6)]); + + Assert.Equal("New", GetText()); + } + + [Fact] + public async Task Should_ignore_version_of_state_during_rebuild() + { + await TextIndexerState.SetAsync([new TextContentState { UniqueContentId = UniqueId(), State = TextState.Stage0_Draft__Stage1_None, Version = 5 }]); + + await sut.ApplyAsync([Created(TextData("field", "Hello"), 0)], true, CancellationToken); + + var state = await GetStateAsync(); + + Assert.Equal("Hello", GetText()); + Assert.Equal(0, state?.Version); + } + + [Fact] + public async Task Should_only_index_final_version_of_content_in_batch() + { + await sut.On([Created(TextData("field", "Version1"), 0), Updated(TextData("field", "Version2"), 1)]); + + Assert.Equal("Version2", GetText()); + Assert.Single(Commands.OfType()); + } + + [Fact] + public async Task Should_skip_and_count_events_of_app_that_is_rebuilt() + { + await Coordinator.TakeOverAsync(AppId.Id, CancellationToken); + + await sut.On([Created(TextData("field", "Hello"), 0), Updated(TextData("field", "World"), 1)]); + + var skipped = await Coordinator.GetSkippedEventsAsync(AppId.Id, CancellationToken); + + Assert.Empty(Commands); + Assert.Equal(2, skipped); + } + + [Fact] + public async Task Should_index_other_apps_while_app_is_rebuilt() + { + await Coordinator.TakeOverAsync(AppId.Id, CancellationToken); + + var otherApp = NamedId.Of(DomainId.NewGuid(), "other-app"); + + A.CallTo(() => AppProvider.GetSchemaAsync(otherApp.Id, A._, A._, A._)) + .Returns(Task.FromResult(null)); + + await sut.On([Created(TextData("field", "Skipped"), 0), Created(TextData("field", "Other"), 0, otherApp)]); + + Assert.Equal("Other", GetText()); + Assert.Single(Commands); + } + + [Fact] + public async Task Should_index_app_again_after_hand_back() + { + await Coordinator.TakeOverAsync(AppId.Id, CancellationToken); + await Coordinator.TryHandBackAsync(AppId.Id, 0, CancellationToken); + + await sut.On([Created(TextData("field", "Hello"), 0)]); + + Assert.Equal("Hello", GetText()); + } + + [Fact] + public async Task Should_index_app_again_after_release() + { + await Coordinator.TakeOverAsync(AppId.Id, CancellationToken); + await Coordinator.ReleaseAsync(AppId.Id); + + await sut.On([Created(TextData("field", "Hello"), 0)]); + + Assert.Equal("Hello", GetText()); + } +} diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/WeightedTextsTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/WeightedTextsTests.cs new file mode 100644 index 000000000..788f97e10 --- /dev/null +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Contents/Text/WeightedTextsTests.cs @@ -0,0 +1,71 @@ +// ========================================================================== +// Squidex Headless CMS +// ========================================================================== +// Copyright (c) Squidex UG (haftungsbeschraenkt) +// All rights reserved. Licensed under the MIT license. +// ========================================================================== + +namespace Squidex.Domain.Apps.Entities.Contents.Text; + +public class WeightedTextsTests +{ + [Fact] + public void Should_return_texts_if_no_titles_defined() + { + var texts = new Dictionary { ["en"] = "World" }; + + var actual = new UpsertIndexEntry { Texts = texts }.GetWeightedTexts(); + + Assert.Same(texts, actual); + } + + [Fact] + public void Should_return_null_if_nothing_defined() + { + var actual = new UpsertIndexEntry().GetWeightedTexts(); + + Assert.Null(actual); + } + + [Fact] + public void Should_repeat_titles_before_texts() + { + var upsert = new UpsertIndexEntry + { + Texts = new Dictionary + { + ["en"] = "World", + ["de"] = "Welt", + }, + Titles = new Dictionary + { + ["en"] = "Hello", + ["iv"] = "Title", + }, + }; + + var actual = upsert.GetWeightedTexts(); + + actual.Should().BeEquivalentTo( + new Dictionary + { + ["en"] = "Hello Hello Hello World", + ["de"] = "Welt", + ["iv"] = "Title Title Title", + }); + } + + [Fact] + public void Should_not_modify_texts_of_upsert() + { + var upsert = new UpsertIndexEntry + { + Texts = new Dictionary { ["en"] = "World" }, + Titles = new Dictionary { ["en"] = "Hello" }, + }; + + upsert.GetWeightedTexts(); + + Assert.Equal("World", upsert.Texts["en"]); + } +} diff --git a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Jobs/JobProcessorTests.cs b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Jobs/JobProcessorTests.cs index e1e7a0c45..a24c91c00 100644 --- a/backend/tests/Squidex.Domain.Apps.Entities.Tests/Jobs/JobProcessorTests.cs +++ b/backend/tests/Squidex.Domain.Apps.Entities.Tests/Jobs/JobProcessorTests.cs @@ -6,10 +6,12 @@ // ========================================================================== using Microsoft.Extensions.Logging.Abstractions; +using NodaTime; using Squidex.Caching; using Squidex.Domain.Apps.Core; using Squidex.Domain.Apps.Entities.Collaboration; using Squidex.Domain.Apps.Entities.TestHelpers; +using Squidex.Infrastructure; using Squidex.Infrastructure.TestHelpers; namespace Squidex.Domain.Apps.Entities.Jobs; @@ -53,4 +55,41 @@ public class JobProcessorTests : GivenContext Assert.Equal("my-reference", job.Reference); Assert.Equal(JobStatus.Completed, job.Status); } + + [Fact] + public async Task Should_mark_interrupted_jobs_as_failed() + { + var job = new Job { Id = DomainId.NewGuid(), TaskName = "job1", Status = JobStatus.Started }; + + state.Snapshot = new JobsState { Jobs = [job] }; + + await sut.LoadAsync(CancellationToken); + + var actual = Assert.Single(state.Snapshot.Jobs); + + Assert.Equal(JobStatus.Failed, actual.Status); + Assert.NotNull(actual.Stopped); + Assert.Single(actual.Log); + + A.CallTo(() => runner.CleanupAsync(job)) + .MustHaveHappenedOnceExactly(); + } + + [Fact] + public async Task Should_not_change_completed_jobs() + { + var job = new Job { Id = DomainId.NewGuid(), TaskName = "job1", Status = JobStatus.Completed, Stopped = default(Instant) }; + + state.Snapshot = new JobsState { Jobs = [job] }; + + await sut.LoadAsync(CancellationToken); + + var actual = Assert.Single(state.Snapshot.Jobs); + + Assert.Equal(JobStatus.Completed, actual.Status); + Assert.Empty(actual.Log); + + A.CallTo(() => runner.CleanupAsync(A._)) + .MustNotHaveHappened(); + } } diff --git a/frontend/src/app/features/schemas/pages/schema/fields/forms/field-form-common.component.html b/frontend/src/app/features/schemas/pages/schema/fields/forms/field-form-common.component.html index d6bf0c49b..81ffa1bb5 100644 --- a/frontend/src/app/features/schemas/pages/schema/fields/forms/field-form-common.component.html +++ b/frontend/src/app/features/schemas/pages/schema/fields/forms/field-form-common.component.html @@ -15,5 +15,17 @@ + + + + + + + + } diff --git a/frontend/src/app/features/schemas/pages/schema/fields/forms/field-form-common.component.ts b/frontend/src/app/features/schemas/pages/schema/fields/forms/field-form-common.component.ts index c8dd86f39..49e695a02 100644 --- a/frontend/src/app/features/schemas/pages/schema/fields/forms/field-form-common.component.ts +++ b/frontend/src/app/features/schemas/pages/schema/fields/forms/field-form-common.component.ts @@ -8,7 +8,7 @@ import { Component, Input } from '@angular/core'; import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms'; -import { FieldDto, FormRowComponent, SchemaDto, TagEditorComponent } from '@app/shared'; +import { FieldDto, FormRowComponent, SchemaDto, TagEditorComponent, TranslatePipe } from '@app/shared'; @Component({ selector: 'sqx-field-form-common', @@ -19,6 +19,7 @@ import { FieldDto, FormRowComponent, SchemaDto, TagEditorComponent } from '@app/ FormsModule, ReactiveFormsModule, TagEditorComponent, + TranslatePipe, ], }) export class FieldFormCommonComponent { diff --git a/frontend/src/app/features/settings/pages/jobs/jobs-page.component.html b/frontend/src/app/features/settings/pages/jobs/jobs-page.component.html index e6e6985df..7ef822268 100644 --- a/frontend/src/app/features/settings/pages/jobs/jobs-page.component.html +++ b/frontend/src/app/features/settings/pages/jobs/jobs-page.component.html @@ -4,6 +4,17 @@ + @if (jobsState.canRebuildTextIndex | async) { + + } @if (jobsState.canCreateBackup | async) {