diff --git a/docs/content-migrations.md b/docs/content-migrations.md index b76e21fe4..4683fa241 100644 --- a/docs/content-migrations.md +++ b/docs/content-migrations.md @@ -110,7 +110,7 @@ A command runs before any hosted service starts, so nothing migrates on start, l | `fluentcms schema snapshot [--output ]` | The canonical snapshot of the host's schema, whose SHA-256 is the schema hash. | | `fluentcms schema validate [--schema ]` | Builds the host's schema, or a schema file, and prints every `FCMS12xx` error; exits with 1 when there is one (`FCMS3320`). A schema file is checked by the tool without a host, with core's field types, unless `--project` or `--assembly` is given. | | `fluentcms schema diff --applied \| --schema [--json]` | What differs from the schema in the newest row of the schema history, or from a schema file, to the host's schema, and from the history to a file with both. Destructive changes are marked and possible renames suggested; exits with 1 when anything differs (`FCMS3322`), so CI can gate a deploy. | -| `fluentcms schema apply [--script [--output ]] [--dry-run] [--allow-destructive]` | For a host whose types are data and so have no content migrations, such as the [Docker image](docker.md#apply-a-schema-file) with a schema file: compares the schema with the content tables, applies the difference in one transaction (on SQLite, committed in parts around a table rebuild) and records the schema in the schema history, on every provider. A renamed field with `formerNames` keeps its values and its references, as in a content migration, and a rename whose values are kept in JSON counts as lost; a change that loses data is refused (`FCMS3337`) unless `--allow-destructive` is given. The tables of a plugin the host does not add, whose history table the database has, are left alone and listed, and so is a content text column whose collation is not the model's (`C` on PostgreSQL, `Latin1_General_100_BIN2` on SQL Server), such as one of a table made before `1.0.0-preview.2` on PostgreSQL: its sort follows the collation it has until it is altered by hand. `--dry-run` prints the operations, and `--script` writes their SQL, applying nothing. It refuses a host with content migrations (`FCMS3335`) and runs after `fluentcms migrate` (`FCMS3336`). | +| `fluentcms schema apply [--script [--output ]] [--dry-run] [--allow-destructive]` | For a host whose types are data and so have no content migrations, such as the [Docker image](docker.md#apply-a-schema-file) with a schema file: compares the schema with the content tables, applies the difference in one transaction (on SQLite, committed in parts around a table rebuild) and records the schema in the schema history, on every provider. A renamed field with `formerNames` keeps its values and its references, as in a content migration, and a rename whose values are kept in JSON counts as lost; a change that loses data is refused (`FCMS3337`) unless `--allow-destructive` is given. The tables of a plugin the host does not add, whose history table the database has, are left alone and listed, and so is a content text column whose collation is not the model's (`C` on PostgreSQL, `Latin1_General_100_BIN2` on SQL Server), such as one of a table made before `1.0.0-preview.2` on PostgreSQL: its sort follows the collation it has until it is altered by hand. An index of expressions made by hand on a content table is left alone too, but on SQLite a run that rebuilds the table, which `--script` shows as `CREATE TABLE "ef_temp_..."`, makes it again from the model, so the index is lost: make it again after the run. `--dry-run` prints the operations, and `--script` writes their SQL, applying nothing. It refuses a host with content migrations (`FCMS3335`) and runs after `fluentcms migrate` (`FCMS3336`). | | `fluentcms doctor [--json]` | The startup report without starting the host: providers, plugins, assemblies, pending migrations, schema drift and insecure defaults. Exits with 1 when the host would not start (`FCMS3325`) or a migration is pending (`FCMS3303`). | `schema snapshot`, `schema diff` and `doctor` also take `--url ` with a management API key in `--token` or `FLUENTCMS_TOKEN`: the snapshot and the diagnostics of a running instance, and the diff from that instance to the host's schema, or to a schema file with `--schema`. The key needs `schema.read` for the schema and `system.read` for `doctor`. diff --git a/docs/planning/backend-technical-spec.md b/docs/planning/backend-technical-spec.md index 6cb08a343..e97f62451 100644 --- a/docs/planning/backend-technical-spec.md +++ b/docs/planning/backend-technical-spec.md @@ -572,7 +572,7 @@ At runtime one `CmsDbContext` holds the union model for querying, with the syste **Plugin migration sets per provider as built ([#2711](https://github.com/fluentcms/FluentCMS/issues/2711)).** One plugin assembly holds a set per provider, each in a namespace that ends in the provider's set name, `Sqlite`, `PostgreSql` or `SqlServer` (`PluginMigrationSets`), which is the folder `Migrations/{set}` that `dotnet ef migrations add --output-dir` writes. EF finds a context's migrations by the context type, and supports several providers with a migrations assembly or a context type per provider; a plugin has one of each, so each provider's `ConfigurePluginMigrations` calls `UsePluginMigrationSet` with its set name, which replaces EF's `IMigrationsAssembly` for the plugin's context with one that keeps the migrations and the snapshot of that namespace. The host, the foreign-set check and `dotnet ef` all read the migrations through it. An assembly with no set under any of the three names holds one set, as before, which every provider takes and the check refuses on another provider, now naming the missing set (`stream acme was scaffolded for SQLite and has no set in a namespace ending in .PostgreSql`); an assembly with sets per provider but none for the host's provider is refused as `stream acme has no set in a namespace ending in .SqlServer`. The design-time factory passes the startup project's three providers and `dotnet ef`'s arguments to `PluginDbContextDesignTime.Create`, so `-- PostgreSql` after the command scaffolds into the PostgreSQL set. Each set's snapshot is named after it (`PostgreSqlModelSnapshot`), because `dotnet ef` finds an existing snapshot file by name anywhere in the project and would write one set's snapshot over another's. The PostgreSQL and SQL Server sets call their provider's model builder extensions, so a plugin references the two EF provider packages, and `System.Security.Cryptography.Pkcs` as the SQL Server provider does, with `PrivateAssets="all"`: its package depends on no provider, and a host loads a set, and the provider it calls, only on that provider. The webhooks, media and sample plugins moved their SQLite sets to `Migrations/Sqlite` and have PostgreSQL and SQL Server sets with the same migrations, media's `MediaTransforms` included; the ids differ by the time each was scaffolded, and the history keeps ids only. On SQL Server the sets use `nvarchar(max)`, as the system migrations do, so one SQL Server set serves SQL Server 2019 and 2025; the plugins keep their JSON in text columns. SQL Server adds `IS NOT NULL` on the nullable column of media's unique folder name index, which leaves root folders to the service's check, as on the other providers. Offline tests check that each set matches the model on its provider and makes the same tables, columns, keys and indexes as the SQLite set, and that the reference host on PostgreSQL or SQL Server passes the check. The data tests do not load the first-party plugins, so CI applies no plugin set to a server; the webhooks and media sets were applied by hand, through the reference host, to PostgreSQL 15 and SQL Server 2025 (ADR 0001). -**The migration baseline as built (B-107, [#3052](https://github.com/fluentcms/FluentCMS/issues/3052)).** Each provider's set of the system stream, and each set of the media, webhooks, MCP, multi-site, AI assist and search streams, is one migration, `Initial`, scaffolded from the model as it was at the end of M7 (10.4, H5). It replaced 20 system migrations on SQLite and PostgreSQL and 21 on SQL Server, and nine plugin migrations for each provider, none of which was published. The snapshots did not change, and the hand-written steps of the old chains that no scaffold writes are carried: on SQL Server the statement that turns `READ_COMMITTED_SNAPSHOT` on, now the first step of `Initial`, so that a user without `ALTER` on the database stops it before anything is created; the FTS5 table of the search plugin and its three triggers on SQLite and its GIN index on PostgreSQL. The checks, filtered indexes and collations of the old chains came from the model, so the scaffold writes them too. Left out are what the chain did only to upgrade databases with rows: the defaults of `cms_role.require_two_factor` and `cms_webhooks_delivery.manual`, NOT NULL columns it added to tables with rows, which the model does not have and EF never needs, since it writes every column; and the relative raise of the Author role's `permissions_version` when its seeded grants changed, so a new database seeds every role at stamp 1. Startup and `MigrateAsync` refuse a database whose history of the system stream or of a plugin stream holds migrations but not the stream's first, before anything is applied and whatever `MigrateOnStartup` says, and `doctor` names it among the reasons a host would not start, with `FCMS1307` naming each such stream, the first id it applied and the baseline, and saying to recreate the database; previews make no promise to upgrade a database until 1.0.0. The content stream is the host's and is not checked. `BaselineTests` (data tests, on each provider of CI) builds one database with the SQL that `dotnet ef migrations script` wrote for the old chains, which the test project keeps as test data (`Migrations/BeforeBaseline/{provider}/{stream}.sql`, copied to its output and in no shipped assembly), and one with the baselines through `MigrateAsync`, and compares their tables, columns (type, nullability, default, collation), keys, indexes with their filters, checks, foreign keys, triggers, rows and, on SQL Server, `READ_COMMITTED_SNAPSHOT`, with the differences above listed and checked to exist. The SQL Server scripts have a `GO` after each column a migration adds, because SQL Server compiles a batch before it runs it and EF runs each command as a batch of its own. Applying `Initial` on SQL Server logs EF's `NonTransactionalMigrationOperationWarning` once, for the step that turns `READ_COMMITTED_SNAPSHOT` on outside the transaction; that is expected. The sample plugin of the tests and the plugin template already had one migration each; the reference host and the Blog sample have no content migrations, and the template's content folder is empty, so no host chain needed squashing. A model change before 1.0.0 goes into `Initial` of each provider rather than into a migration of its own, since previews do not upgrade a database: `cms_default_grant` (4.8, [#3103](https://github.com/fluentcms/FluentCMS/issues/3103)) was added to the system baseline so, and `BaselineTests` leaves the tables added since the squash out of the comparison after checking that the baseline made them. A database made by an earlier build of a baseline holds that baseline in its history with nothing pending, so EF applies nothing and the first query of a table added since would fail with a raw missing relation: startup, `MigrateAsync` and `doctor` therefore refuse, before anything is applied, a system or plugin stream whose history holds its baseline, that has nothing pending and that lacks a table of its model or a column of one it has, with `FCMS1308` naming each such stream, its baseline and the missing tables and columns (`table.column`), and saying to recreate the database. The columns of `cms_schema_history` are not compared, since a history that cannot be read or written is logged and the start goes on. Indexes of the model are compared by name on the tables the database has ([#3407](https://github.com/fluentcms/FluentCMS/issues/3407)): a missing unique index is refused with `FCMS1308` as `index {name}`, since it would let in rows the model refuses, and any other missing index, as those folded into the baseline after `1.0.0-preview.1` are on a database it made, is logged (9306, Warning) with the stream, its baseline and the indexes, and the host starts. The schema readers list every index that `CREATE INDEX` made, one whose keys are expressions too, with an empty name for such a key, as the search plugin's GIN index on PostgreSQL ([#3530](https://github.com/fluentcms/FluentCMS/issues/3530)); SQL Server indexes no expression, and its reader lists an index on a computed column or with a filter. Schema apply and the schema sync leave alone an index of a content table with an expression key that the content model lacks, since the content model cannot declare one, so one made by hand is neither dropped nor reported (9303); one of plain columns is, as before. The catalog is read after the histories of all streams ([#3528](https://github.com/fluentcms/FluentCMS/issues/3528), above). Adding an index to an existing database would take a migration, which a preview does not have, so such a database is recreated to get it. +**The migration baseline as built (B-107, [#3052](https://github.com/fluentcms/FluentCMS/issues/3052)).** Each provider's set of the system stream, and each set of the media, webhooks, MCP, multi-site, AI assist and search streams, is one migration, `Initial`, scaffolded from the model as it was at the end of M7 (10.4, H5). It replaced 20 system migrations on SQLite and PostgreSQL and 21 on SQL Server, and nine plugin migrations for each provider, none of which was published. The snapshots did not change, and the hand-written steps of the old chains that no scaffold writes are carried: on SQL Server the statement that turns `READ_COMMITTED_SNAPSHOT` on, now the first step of `Initial`, so that a user without `ALTER` on the database stops it before anything is created; the FTS5 table of the search plugin and its three triggers on SQLite and its GIN index on PostgreSQL. The checks, filtered indexes and collations of the old chains came from the model, so the scaffold writes them too. Left out are what the chain did only to upgrade databases with rows: the defaults of `cms_role.require_two_factor` and `cms_webhooks_delivery.manual`, NOT NULL columns it added to tables with rows, which the model does not have and EF never needs, since it writes every column; and the relative raise of the Author role's `permissions_version` when its seeded grants changed, so a new database seeds every role at stamp 1. Startup and `MigrateAsync` refuse a database whose history of the system stream or of a plugin stream holds migrations but not the stream's first, before anything is applied and whatever `MigrateOnStartup` says, and `doctor` names it among the reasons a host would not start, with `FCMS1307` naming each such stream, the first id it applied and the baseline, and saying to recreate the database; previews make no promise to upgrade a database until 1.0.0. The content stream is the host's and is not checked. `BaselineTests` (data tests, on each provider of CI) builds one database with the SQL that `dotnet ef migrations script` wrote for the old chains, which the test project keeps as test data (`Migrations/BeforeBaseline/{provider}/{stream}.sql`, copied to its output and in no shipped assembly), and one with the baselines through `MigrateAsync`, and compares their tables, columns (type, nullability, default, collation), keys, indexes with their filters, checks, foreign keys, triggers, rows and, on SQL Server, `READ_COMMITTED_SNAPSHOT`, with the differences above listed and checked to exist. The SQL Server scripts have a `GO` after each column a migration adds, because SQL Server compiles a batch before it runs it and EF runs each command as a batch of its own. Applying `Initial` on SQL Server logs EF's `NonTransactionalMigrationOperationWarning` once, for the step that turns `READ_COMMITTED_SNAPSHOT` on outside the transaction; that is expected. The sample plugin of the tests and the plugin template already had one migration each; the reference host and the Blog sample have no content migrations, and the template's content folder is empty, so no host chain needed squashing. A model change before 1.0.0 goes into `Initial` of each provider rather than into a migration of its own, since previews do not upgrade a database: `cms_default_grant` (4.8, [#3103](https://github.com/fluentcms/FluentCMS/issues/3103)) was added to the system baseline so, and `BaselineTests` leaves the tables added since the squash out of the comparison after checking that the baseline made them. A database made by an earlier build of a baseline holds that baseline in its history with nothing pending, so EF applies nothing and the first query of a table added since would fail with a raw missing relation: startup, `MigrateAsync` and `doctor` therefore refuse, before anything is applied, a system or plugin stream whose history holds its baseline, that has nothing pending and that lacks a table of its model or a column of one it has, with `FCMS1308` naming each such stream, its baseline and the missing tables and columns (`table.column`), and saying to recreate the database. The columns of `cms_schema_history` are not compared, since a history that cannot be read or written is logged and the start goes on. Indexes of the model are compared by name on the tables the database has ([#3407](https://github.com/fluentcms/FluentCMS/issues/3407)): a missing unique index is refused with `FCMS1308` as `index {name}`, since it would let in rows the model refuses, and any other missing index, as those folded into the baseline after `1.0.0-preview.1` are on a database it made, is logged (9306, Warning) with the stream, its baseline and the indexes, and the host starts. The schema readers list every index that `CREATE INDEX` made, one whose keys are expressions too, with an empty name for such a key, as the search plugin's GIN index on PostgreSQL ([#3530](https://github.com/fluentcms/FluentCMS/issues/3530)); SQL Server indexes no expression, and its reader lists an index on a computed column or with a filter. Schema apply and the schema sync leave alone an index of a content table with an expression key that the content model lacks, since the content model cannot declare one, so one made by hand is neither dropped nor reported (9303); one of plain columns is, as before. On SQLite a run that rebuilds the table, such as one that adds a JSON column with its check, makes it again from the model, so such an index is lost with the old table and is made again by hand after the run ([#3562](https://github.com/fluentcms/FluentCMS/issues/3562)). The catalog is read after the histories of all streams ([#3528](https://github.com/fluentcms/FluentCMS/issues/3528), above). Adding an index to an existing database would take a migration, which a preview does not have, so such a database is recreated to get it. **Storage follow-ups as built.** From [#2879](https://github.com/fluentcms/FluentCMS/issues/2879) of the review of 7 Nov 2026 ([#2847](https://github.com/fluentcms/FluentCMS/issues/2847)): @@ -1165,7 +1165,7 @@ public sealed class MediaPlugin : IPlugin **Plugin host as built.** The manifest is `[FluentCmsPlugin("name", Version = "1.0.0", SdkRange = "[1.0.0,2.0.0)", DependsOn = ["other"])]` on the plugin class, and the same attribute on an assembly, `[assembly: FluentCmsPlugin(typeof(T))]`, names a plugin class for discovery, as many as the assembly has. A name is lower kebab-case like a content type or a settings area, at most 32 characters, so that `cms_{name}__migrations` and the plugin's tables fit a PostgreSQL identifier. A plugin's name is also its stream's, so `system` and `content`, core's streams, are refused with `FCMS1502`, for a plugin and for a stream registered through `IPluginMigrations` alike. `Version` is a semantic version and, left out, the informational version of the plugin's assembly; `SdkRange` is required. `IPluginServiceBuilder` has the plugin's `Name` and the host's `Services`, and `IPluginAppBuilder` its `Name` and the root `Services`; core implements both and plugins only call them, so the contributions of B-61 are new members that break no plugin. For `IServiceCollection` the SDK references `Microsoft.Extensions.DependencyInjection.Abstractions`, and nothing of EF Core or ASP.NET Core. `cms.AddPlugin(configure)` creates the plugin with its parameterless constructor and hands it to `configure`. Discovery reads the app's deps file (the first of `APP_CONTEXT_DEPS_FILES`, else `{entry}.deps.json`) once per process, loads the runtime assemblies of the libraries that depend on `FluentCMS.Sdk`, directly or through other libraries, and reads their assembly attributes; an app with no deps file on disk, such as a single-file one, discovers nothing and adds its plugins with `AddPlugin`. So does an app that sets the `AppContext` switch `FluentCMS.Plugins.DisableDiscovery` (`` in its project file), which is for an app that references plugins it adds to some of its hosts only, as the data tests do (B-80); such a host says so in the log when it starts (event 9237). A plugin that is added and discovered is registered once, as added and where added; one added twice is a duplicate. **Order.** The plugins are taken as they came, the added ones in the order of their `AddPlugin` calls and then the discovered ones in the order of the deps file, and each is placed after the plugins it depends on, which move ahead of it when they come later; plugins with no dependency between them keep that order unless a dependency pulls one of them forward. `ConfigureServices` runs in this order inside `AddFluentCms`, after the host's callback and before core adds its own services, so a plugin's service replaces one that core adds only when none is there, and `Configure` runs in this order inside `MapFluentCms`, after the endpoint groups of core. The plugin host is the `IHookTiebreaker` (a host that registers its own keeps it): among hooks and event handlers of equal `[HookOrder]`, one of a plugin ranks by the plugin's place, and one of no plugin, the host's or core's, after every plugin's, keeping its registration order. A type belongs to the plugin whose `ConfigureServices` registered it, by implementation type or instance, or else to the plugin whose class is the only plugin class in the type's assembly, which covers a hook registered with a factory; the app's own assembly is left out of that, since its other types are the host's. `Configure` runs once, however many times `MapFluentCms` is called, and a discovered plugin whose constructor throws stops the host with its own exception. **Codes.** `FCMS1501` the type cannot be a plugin (no manifest or several on the class, an assembly attribute with a name instead of a type or one that cannot be read, or a discovered class that is abstract, does not implement `IPlugin` or has no public parameterless constructor), `FCMS1502` the name, `FCMS1503` the version, `FCMS1504` an SDK range that is missing or not interval notation, `FCMS1505` a running SDK outside the range, `FCMS1506` two plugins with one name, `FCMS1507` a missing dependency and `FCMS1508` a dependency cycle, whose message lists the cycle; each message names the plugin and its class. `FCMS1520` to `FCMS1529` are the contributions' (below), `FCMS1540` to `FCMS1544` the provider slots', `FCMS1550` to `FCMS1559` per-site enablement's (below), `FCMS1560` to `FCMS1579` the webhooks plugin's (5.2), `FCMS1580` to `FCMS1599` the media plugin's (5.1), `FCMS1600` to `FCMS1639` the MCP plugin's (5.4), `FCMS1660` to `FCMS1679` the multi-site plugin's (5.6), `FCMS1680` to `FCMS1699` the AI assist plugin's (5.5), and `FCMS1700` to `FCMS1719` the search plugin's (5.7). **SDK versions.** The running version is the informational version of `FluentCMS.Sdk` without its build metadata, and the range is parsed in core. A released SDK is held to the range exactly as NuGet holds a version. A pre-release of the SDK counts as the release it leads to when it is held against a bound that is a release, and is compared in full against a bound that is a pre-release: `1.0.0-preview.3` and `1.0.0-dev` satisfy `[1.0.0,2.0.0)`, `2.0.0-preview.1` does not, and `[1.0.0-preview.2,2.0.0)` refuses `1.0.0-preview.1`. NuGet's own precedence puts `1.0.0-preview` below `1.0.0` and `2.0.0-preview` below `2.0.0`, so a range written against released versions would refuse every dev and preview build of the line it names and take the previews of the next major version, which may break the plugin; the rule turns both around and loosens nothing for a release. The startup report and `/system/diagnostics` list the plugins in this order with name and version; the full manifest is the Management plugin list's. -**Plugin contributions as built.** `IPluginServiceBuilder` mirrors the core builders, each method doing what its `cms.*` counterpart does: `AddFieldType()`, `AddPermissions()` (an `IPermissionProvider`, whose permissions may name built-in roles that get them by default, 4.8), `AddSettings()`, `AddJob(type, attemptTimeout)`, `AddJobQueue(name, workers)`, `AddEventHandler()`, `AddOutboxHandler(name)`, `AddActivity(name, describe)`, `AddErrorCode(code, status, title)` and, for the MCP server, `AddMcpTools()`, `AddMcpResources()` and `AddMcpPrompts()` (5.4), and `Providers` holds the provider slots (4.13, "Provider slots as built"). `AddJobQueue` adds a job queue whose worker count its factory reads from the host's services when the runner's options are built, so that it can come from the plugin's own options; a count the host sets for that queue, in `cms.Jobs.Options.Queues` or under `FluentCms:Jobs:Queues`, wins, and a name that is empty or longer than 64 characters throws. `FluentCMS.Plugins.Abstractions` adds `AddModel()`, `AddMigrations(assembly)`, `MapGroup(prefix)`, `MapManagement(prefix)`, `MapDelivery(prefix)` and `MapProtectedResource(prefix, options)` (4.7, "Protected resources as built") as extension methods ([ADR 0003](../decisions/0003-plugin-contribution-contracts.md)). **Tables.** A model contributor maps the plugin's entities on an EF `ModelBuilder`. Each table and view is named `cms_{plugin}_...`, with the hyphens of the name as underscores, and is neither `cms_{plugin}__migrations` nor a table of core or of another plugin; `AddFluentCms` checks this by mapping the contributor on a model without conventions and stops with `FCMS1523`. The same mapping, with PostgreSQL's limit of 63 set on it, holds the name of every table, view, column, key, foreign key, index and check constraint to 63 bytes in UTF-8 and stops with `FCMS1529` for a longer one: PostgreSQL keeps the first 63 bytes of a name without a word, and the baseline check (4.3) finds the tables, columns and indexes of the model by name, so it would warn or refuse at every start; on every provider, so that a plugin that runs on SQLite does not fail on PostgreSQL later. That is the name the model gives or else the one EF derives, such as the `IX_...` of an index given none, as EF derives it on PostgreSQL: EF cuts a derived name to 63 characters, which is 63 bytes only in ASCII, so a derived name built from a name with other characters is measured too. Columns are read per table, so a column named for one table alone, with entity splitting, TPT or TPC, is measured on it. What only EF's conventions would find, such as a property that no call of the contributor configures, is not on that model and is not measured ([#3533](https://github.com/fluentcms/FluentCMS/issues/3533)). A content type whose table a plugin maps stops the host with `FCMS1206`. The contributors join `CmsDbContext` after the system tables, excluded from its migrations, and build `PluginDbContext`, a scoped context with the provider's conventions that the plugin's code queries. **Streams.** `AddMigrations(assembly)` registers the plugin's stream: the migrations of the assembly that name `PluginDbContext` in `[DbContext]`, with the history table `cms_{plugin}__migrations`, which `IDataProvider.ConfigurePluginMigrations` points at the database. The streams run after the system stream and before the content stream, in plugin order, and a second assembly for one plugin is `FCMS1525`. A model ahead of its migrations stops the migration with EF's pending model changes error. The assembly holds a set per provider, in a namespace ending in `Sqlite`, `PostgreSql` or `SqlServer`, and the host takes the set of its provider (4.3, "Plugin migration sets per provider as built"). **Endpoints.** The groups are relative to the path base and run their endpoints inside the request bridge's `OperationContext`, with no output cache unless an endpoint adds one. `MapManagement(prefix)` is under `/api/management/v1` with what core's Management groups have: the `management` scope (401 without a principal, 403 without the scope), the Management rate limit and CORS policy, and the OpenAPI document. `MapDelivery(prefix)` is under `/api/delivery/v1` with what core's Delivery group has, its output cache included, and an anonymous caller read as its site's Public role (4.10, "Plugin Delivery groups as built"). `MapGroup(prefix)` is under the CMS group with the Delivery rate limit and CORS policy and the plugin's name as its surface, which keeps it out of the OpenAPI document. "CMS auth by default" means that its endpoints need a caller the `FluentCms` scheme signed in, a bearer token or an API key of any class, and answer any other with a 401 problem (`FCMS3102`); an endpoint that is public on purpose, such as the media plugin's asset bytes at `/media/{id}/{filename}`, opts out with ASP.NET Core's `AllowAnonymous()`, on the endpoint or on the group. It is an endpoint filter after the request bridge's, as the `management` scope is, so no host needs `UseAuthorization` for it, and it runs before the per-site gate, so an anonymous caller learns nothing of where the plugin is disabled. Credentials that are sent and refused are a 401 even where anonymous is allowed, as on Delivery. Being signed in is all the group checks: what the caller may do is the plugin's to check with `IPermissionChecker`. The coarse limit before authentication covers these routes as it covers core's (4.10), so a flood of keys sent to them is turned away before any key is looked up. This answers decision 4 of the review of 7 Nov 2026 ([#2847](https://github.com/fluentcms/FluentCMS/issues/2847), [#2859](https://github.com/fluentcms/FluentCMS/issues/2859)): a plugin's group is not anonymous-capable by default. The startup report does not list the endpoints that allow anonymous, because each is a choice written in the plugin's code rather than a setting an operator could change, and a warning at every start for a public media route would teach operators to ignore the warnings; the Management plugin list names every endpoint. A prefix under a group of core, one whose first segment is a route parameter, and one that does not start with a slash or ends with one are `FCMS1524`. So is a `MapDelivery` prefix whose first segment is a route parameter or names a content type. **Codes.** A plugin's code is upper case letters and four digits, neither core's nor another plugin's, with a status from 400 to 599 and a title (`FCMS1522`). A `PluginException(code, message)`, a `HookRejectedException` and a validation error with the code get its status and title; a code the plugin did not add is 422. **Field types.** A plugin type's name is an ASCII letter followed by ASCII letters, digits, `.`, `-` or `_` (`FCMS1528`), as `IFieldType.Name` says, because `generate` writes it into code and refuses a schema snapshot whose field type is not such a name (B-106, [#3051](https://github.com/fluentcms/FluentCMS/issues/3051)), and it is neither core's nor another plugin's (`FCMS1521`). The field type registry holds every `IFieldType` of the container to both rules, with an `ArgumentException`, so a type registered as a service without `AddFieldType` is refused as well. A setting of kind `FieldSettingKind.FieldReference` names a sibling field of the same type, component or block: schema validation refuses one that names no other field (`FCMS1520`), and schema introspection leaves the setting out for a caller who cannot read that field, as it does a slug's `source`. Such a setting is optional, as `source` is, so that a narrowed snapshot still loads; a plugin type that makes one required stops the host (`FCMS1526`). Core's `IFieldTypeRegistry` in the container has the plugins' types, and a host that builds its own `SchemaModel` builds it with that registry, as the test host does. The sample plugin of the tests (`tests/FluentCMS.Plugins.Sample`) uses every contribution and stays the fixture of the plugin host's tests; a plugin starts from the `fluentcms-plugin` template (6.2, B-94), which is not generated from it and uses the permissions, settings, hooks, model, migrations and Management endpoints of this section. +**Plugin contributions as built.** `IPluginServiceBuilder` mirrors the core builders, each method doing what its `cms.*` counterpart does: `AddFieldType()`, `AddPermissions()` (an `IPermissionProvider`, whose permissions may name built-in roles that get them by default, 4.8), `AddSettings()`, `AddJob(type, attemptTimeout)`, `AddJobQueue(name, workers)`, `AddEventHandler()`, `AddOutboxHandler(name)`, `AddActivity(name, describe)`, `AddErrorCode(code, status, title)` and, for the MCP server, `AddMcpTools()`, `AddMcpResources()` and `AddMcpPrompts()` (5.4), and `Providers` holds the provider slots (4.13, "Provider slots as built"). `AddJobQueue` adds a job queue whose worker count its factory reads from the host's services when the runner's options are built, so that it can come from the plugin's own options; a count the host sets for that queue, in `cms.Jobs.Options.Queues` or under `FluentCms:Jobs:Queues`, wins, and a name that is empty or longer than 64 characters throws. `FluentCMS.Plugins.Abstractions` adds `AddModel()`, `AddMigrations(assembly)`, `MapGroup(prefix)`, `MapManagement(prefix)`, `MapDelivery(prefix)` and `MapProtectedResource(prefix, options)` (4.7, "Protected resources as built") as extension methods ([ADR 0003](../decisions/0003-plugin-contribution-contracts.md)). **Tables.** A model contributor maps the plugin's entities on an EF `ModelBuilder`. Each table and view is named `cms_{plugin}_...`, with the hyphens of the name as underscores, and is neither `cms_{plugin}__migrations` nor a table of core or of another plugin; `AddFluentCms` checks this by mapping the contributor on a model without conventions and stops with `FCMS1523`. The same mapping, with PostgreSQL's limit of 63 set on it, holds the name of every table, view, column, key, foreign key, index and check constraint to 63 bytes in UTF-8 and stops with `FCMS1529` for a longer one: PostgreSQL keeps the first 63 bytes of a name without a word, and the baseline check (4.3) finds the tables, columns and indexes of the model by name, so it would warn or refuse at every start; on every provider, so that a plugin that runs on SQLite does not fail on PostgreSQL later. That is the name the model gives or else the one EF derives, such as the `IX_...` of an index given none, as EF derives it on PostgreSQL: EF cuts a derived name to 63 characters, which is 63 bytes only in ASCII, so a derived name built from a name with other characters is measured too, and its refusal says that EF derived it and names the call that gives a shorter one: `HasColumnName`, `HasName` for a key, `HasConstraintName` or `HasDatabaseName` ([#3562](https://github.com/fluentcms/FluentCMS/issues/3562)). EF cuts a check constraint's given name of more than 63 characters to 63 the same way before it is measured, so a longer ASCII name passes, as PostgreSQL keeps it cut, and the refusal of a longer one with other characters names the given name and the one EF cut it to. Columns are read per table, so a column named for one table alone, with entity splitting, TPT or TPC, is measured on it. What only EF's conventions find or make is not on that model and is not measured: a property that no call of the contributor configures, and the foreign key that links the table of a TPT type or of an entity splitting fragment to the table it extends ([#3533](https://github.com/fluentcms/FluentCMS/issues/3533)). Left out too is what that model has and EF never emits: where an owned type maps to its owner's table, or a type to its principal's table by a foreign key on its own primary key, the foreign key of that link and the dependent's columns of it, which are the principal's key columns ([#3562](https://github.com/fluentcms/FluentCMS/issues/3562)). A content type whose table a plugin maps stops the host with `FCMS1206`. The contributors join `CmsDbContext` after the system tables, excluded from its migrations, and build `PluginDbContext`, a scoped context with the provider's conventions that the plugin's code queries. **Streams.** `AddMigrations(assembly)` registers the plugin's stream: the migrations of the assembly that name `PluginDbContext` in `[DbContext]`, with the history table `cms_{plugin}__migrations`, which `IDataProvider.ConfigurePluginMigrations` points at the database. The streams run after the system stream and before the content stream, in plugin order, and a second assembly for one plugin is `FCMS1525`. A model ahead of its migrations stops the migration with EF's pending model changes error. The assembly holds a set per provider, in a namespace ending in `Sqlite`, `PostgreSql` or `SqlServer`, and the host takes the set of its provider (4.3, "Plugin migration sets per provider as built"). **Endpoints.** The groups are relative to the path base and run their endpoints inside the request bridge's `OperationContext`, with no output cache unless an endpoint adds one. `MapManagement(prefix)` is under `/api/management/v1` with what core's Management groups have: the `management` scope (401 without a principal, 403 without the scope), the Management rate limit and CORS policy, and the OpenAPI document. `MapDelivery(prefix)` is under `/api/delivery/v1` with what core's Delivery group has, its output cache included, and an anonymous caller read as its site's Public role (4.10, "Plugin Delivery groups as built"). `MapGroup(prefix)` is under the CMS group with the Delivery rate limit and CORS policy and the plugin's name as its surface, which keeps it out of the OpenAPI document. "CMS auth by default" means that its endpoints need a caller the `FluentCms` scheme signed in, a bearer token or an API key of any class, and answer any other with a 401 problem (`FCMS3102`); an endpoint that is public on purpose, such as the media plugin's asset bytes at `/media/{id}/{filename}`, opts out with ASP.NET Core's `AllowAnonymous()`, on the endpoint or on the group. It is an endpoint filter after the request bridge's, as the `management` scope is, so no host needs `UseAuthorization` for it, and it runs before the per-site gate, so an anonymous caller learns nothing of where the plugin is disabled. Credentials that are sent and refused are a 401 even where anonymous is allowed, as on Delivery. Being signed in is all the group checks: what the caller may do is the plugin's to check with `IPermissionChecker`. The coarse limit before authentication covers these routes as it covers core's (4.10), so a flood of keys sent to them is turned away before any key is looked up. This answers decision 4 of the review of 7 Nov 2026 ([#2847](https://github.com/fluentcms/FluentCMS/issues/2847), [#2859](https://github.com/fluentcms/FluentCMS/issues/2859)): a plugin's group is not anonymous-capable by default. The startup report does not list the endpoints that allow anonymous, because each is a choice written in the plugin's code rather than a setting an operator could change, and a warning at every start for a public media route would teach operators to ignore the warnings; the Management plugin list names every endpoint. A prefix under a group of core, one whose first segment is a route parameter, and one that does not start with a slash or ends with one are `FCMS1524`. So is a `MapDelivery` prefix whose first segment is a route parameter or names a content type. **Codes.** A plugin's code is upper case letters and four digits, neither core's nor another plugin's, with a status from 400 to 599 and a title (`FCMS1522`). A `PluginException(code, message)`, a `HookRejectedException` and a validation error with the code get its status and title; a code the plugin did not add is 422. **Field types.** A plugin type's name is an ASCII letter followed by ASCII letters, digits, `.`, `-` or `_` (`FCMS1528`), as `IFieldType.Name` says, because `generate` writes it into code and refuses a schema snapshot whose field type is not such a name (B-106, [#3051](https://github.com/fluentcms/FluentCMS/issues/3051)), and it is neither core's nor another plugin's (`FCMS1521`). The field type registry holds every `IFieldType` of the container to both rules, with an `ArgumentException`, so a type registered as a service without `AddFieldType` is refused as well. A setting of kind `FieldSettingKind.FieldReference` names a sibling field of the same type, component or block: schema validation refuses one that names no other field (`FCMS1520`), and schema introspection leaves the setting out for a caller who cannot read that field, as it does a slug's `source`. Such a setting is optional, as `source` is, so that a narrowed snapshot still loads; a plugin type that makes one required stops the host (`FCMS1526`). Core's `IFieldTypeRegistry` in the container has the plugins' types, and a host that builds its own `SchemaModel` builds it with that registry, as the test host does. The sample plugin of the tests (`tests/FluentCMS.Plugins.Sample`) uses every contribution and stays the fixture of the plugin host's tests; a plugin starts from the `fluentcms-plugin` template (6.2, B-94), which is not generated from it and uses the permissions, settings, hooks, model, migrations and Management endpoints of this section. **Permission checks of plugins as built.** A plugin's service enforces its own permissions as core's services do, with `IPermissionChecker` (`FluentCMS.Authorization`, in the SDK): `AllowsAsync(permission, site)` and `RequireAsync(permission, site)`, which throws `PermissionDeniedException`, answered with 403, or 401 without a principal. `CanManageAsync()` says whether the principal may manage at all, which is the evaluator's `CanManage` (4.8): one that may not reads content alone, whatever its roles grant ([#3112](https://github.com/fluentcms/FluentCMS/issues/3112)). `HoldsGrantInAsync(site)` says whether some grant of the principal gives it a permission in a site (4.8, "Grants that give something in a site as built"), as `GET /me/sites` decides which sites to list, for a plugin that serves what belongs to a site rather than what a permission names ([#3070](https://github.com/fluentcms/FluentCMS/issues/3070)). A null site is the instance as a whole, which only a grant with no site limit reaches. A call outside an operation is refused with `InvalidOperationException` (`FCMS1408`, 2.3), so host code that acts as the system wraps it in `SystemOperation.Begin`. Core implements it with the checks of its Management services, so the endpoint carries the identity and the service decides. The webhooks plugin checks `webhooks.manage` with it. diff --git a/docs/plugin-migrations.md b/docs/plugin-migrations.md index 819ddd0ed..fb61abd43 100644 --- a/docs/plugin-migrations.md +++ b/docs/plugin-migrations.md @@ -53,6 +53,16 @@ public sealed class WebhooksDbContextFactory : IDesignTimeDbContextFactory _lost.Dispose(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); return; } diff --git a/src/FluentCMS.Core/DependencyInjection/DisposeWait.cs b/src/FluentCMS.Core/DependencyInjection/DisposeWait.cs new file mode 100644 index 000000000..65d209425 --- /dev/null +++ b/src/FluentCMS.Core/DependencyInjection/DisposeWait.cs @@ -0,0 +1,8 @@ +namespace FluentCMS.Core.DependencyInjection; + +// How long a disposal waits for the work it stops, the job runner's loops or the callbacks on a lock's Lost, before it +// returns without them (#3544). +internal static class DisposeWait +{ + public static readonly TimeSpan Bound = TimeSpan.FromSeconds(5); +} diff --git a/src/FluentCMS.Core/Jobs/JobRunner.cs b/src/FluentCMS.Core/Jobs/JobRunner.cs index 1ecfd890b..c1565ef23 100644 --- a/src/FluentCMS.Core/Jobs/JobRunner.cs +++ b/src/FluentCMS.Core/Jobs/JobRunner.cs @@ -1,3 +1,4 @@ +using FluentCMS.Core.DependencyInjection; using FluentCMS.Core.Health; using FluentCMS.Core.Telemetry; using FluentCMS.Jobs; @@ -15,8 +16,6 @@ internal sealed class JobRunner( TimeProvider time, ILogger logger) : IJobRunner, IDisposable { - internal static readonly TimeSpan DisposeWait = TimeSpan.FromSeconds(5); - private readonly CancellationTokenSource _stopping = new(); // One for each worker, whose callbacks CancelAsync runs as a thread-pool work item of their own: a job's await can end @@ -99,7 +98,7 @@ public void Dispose() try { - if (_loops?.Wait(DisposeWait) == false) + if (_loops?.Wait(DisposeWait.Bound) == false) { return; } diff --git a/src/FluentCMS.Core/Plugins/PluginStorage.cs b/src/FluentCMS.Core/Plugins/PluginStorage.cs index fbeaf8714..9e0b12f54 100644 --- a/src/FluentCMS.Core/Plugins/PluginStorage.cs +++ b/src/FluentCMS.Core/Plugins/PluginStorage.cs @@ -84,25 +84,54 @@ public IReadOnlyList AddModel(IPluginModelContributor contributor, Func< // tables, columns and indexes of the model by name, would not find them. Refused on every provider, so that a plugin that // runs on SQLite does not fail on PostgreSQL later (#3533). The names are read as EF gives them on PostgreSQL: the model // has its limit of 63, so a name EF derives, such as IX_..., is cut as EF cuts it there, by characters, and one with - // characters of more than a byte can still be too long. + // characters of more than a byte can still be too long. EF cuts a check constraint's given name the same way. private void CheckLengths(IPluginModelContributor contributor, IMutableEntityType entity) { - foreach (var (what, name) in NamesOnPostgreSql(entity)) + foreach (var name in NamesOnPostgreSql(entity)) { - var bytes = Encoding.UTF8.GetByteCount(name); - if (bytes > StorageNames.MaxIdentifierLength) + var bytes = Encoding.UTF8.GetByteCount(name.Value); + if (bytes <= StorageNames.MaxIdentifierLength) { - throw new FluentCmsConfigurationException( - PluginErrorCodes.NameTooLong, - $"The plugin '{plugin.Name}' ({plugin.Type.FullName}) gives {what} of {entity.DisplayName()} the name '{name}' in {contributor.GetType().FullName}, which has {bytes} bytes in UTF-8; a name has at most {StorageNames.MaxIdentifierLength}, as PostgreSQL keeps no more of it."); + continue; } + + var where = $"The plugin '{plugin.Name}' ({plugin.Type.FullName}) gives {name.What} of {entity.DisplayName()}"; + var limit = $"a name has at most {StorageNames.MaxIdentifierLength}, as PostgreSQL keeps no more of it"; + throw new FluentCmsConfigurationException( + PluginErrorCodes.NameTooLong, + name.Call is { } call ? $"{where} no name in {contributor.GetType().FullName}, and the name EF derives for it, '{name.Value}', has {bytes} bytes in UTF-8; {limit}. Give it a shorter one with {call}." + : name.Given is { } given ? $"{where} the name '{given}' in {contributor.GetType().FullName}, which EF cuts to '{name.Value}', of {bytes} bytes in UTF-8; {limit}." + : $"{where} the name '{name.Value}' in {contributor.GetType().FullName}, which has {bytes} bytes in UTF-8; {limit}."); } } + // A name as EF emits it. Call is how the model gives one where EF derives it, and Given the name the model gives where EF + // cuts it. + private readonly record struct StoreName(string What, string Value, string? Call = null, string? Given = null) + { + public static StoreName Of(string what, string value, string? derived, string call) => + new(what, value, value == derived ? call : null); + } + // Each table or view the entity maps to, the fragments of entity splitting and the tables of TPT and TPC included, with - // the columns, keys and indexes it has there, so that a column named for one table alone is read too. - private static IEnumerable<(string What, string Name)> NamesOnPostgreSql(IMutableEntityType entity) + // the columns, keys and indexes it has there, so that a column named for one table alone is read too. The foreign keys + // that EF adds to link the table of a TPT type or an entity splitting fragment to the main table are made by conventions + // only, so they are not on this model and not measured. + private static IEnumerable NamesOnPostgreSql(IMutableEntityType entity) { + // An owned type on its owner's table, or a type split from its principal's table by a foreign key on its own key, is + // one row with its principal: EF emits no foreign key for that link and maps its properties to the principal's key + // columns, which the principal's names hold. Without conventions the model still has the foreign key, and an owned + // type a key column of its own, such as Address_OrderId, so both are left out here. A foreign key to another table, + // an owned type's on a table of its own included, or to the same table on other columns, is measured. + var table = StoreObjectIdentifier.Create(entity, StoreObjectType.Table); + var links = entity.GetDeclaredForeignKeys() + .Where(foreignKey => table is { } shared + && StoreObjectIdentifier.Create(foreignKey.PrincipalEntityType, StoreObjectType.Table) == shared + && (foreignKey.IsOwnership || (foreignKey.PrincipalKey.IsPrimaryKey() && entity.FindPrimaryKey()?.Properties.SequenceEqual(foreignKey.Properties) == true))) + .ToList(); + var linkColumns = links.SelectMany(foreignKey => foreignKey.Properties).ToHashSet(); + List stores = []; foreach (var type in new[] { StoreObjectType.Table, StoreObjectType.View }) { @@ -115,11 +144,19 @@ private void CheckLengths(IPluginModelContributor contributor, IMutableEntityTyp stores.AddRange(entity.GetMappingFragments().Select(fragment => fragment.StoreObject)); foreach (var store in stores.Distinct()) { - yield return (store.StoreObjectType == StoreObjectType.View ? "the view" : "the table", store.Name); + yield return new(store.StoreObjectType == StoreObjectType.View ? "the view" : "the table", store.Name); - foreach (var column in Properties(entity).Select(property => property.GetColumnName(store)).OfType()) + foreach (var property in Properties(entity)) { - yield return ("the column", column); + if (store == table && linkColumns.Contains(property)) + { + continue; + } + + if (property.GetColumnName(store) is { } column) + { + yield return StoreName.Of("the column", column, property.GetDefaultColumnName(store), "HasColumnName"); + } } if (store.StoreObjectType != StoreObjectType.Table) @@ -127,26 +164,39 @@ private void CheckLengths(IPluginModelContributor contributor, IMutableEntityTyp continue; } - foreach (var key in entity.GetKeys().Select(key => key.GetName(store)).OfType()) + foreach (var key in entity.GetKeys()) { - yield return ("the key", key); + if (key.GetName(store) is { } name) + { + yield return StoreName.Of("the key", name, key.GetDefaultName(store), "HasName"); + } } - foreach (var index in entity.GetIndexes().Select(index => index.GetDatabaseName(store)).OfType()) + foreach (var index in entity.GetIndexes()) { - yield return ("the index", index); + if (index.GetDatabaseName(store) is { } name) + { + yield return StoreName.Of("the index", name, index.GetDefaultDatabaseName(store), "HasDatabaseName"); + } } } - foreach (var foreignKey in entity.GetDeclaredForeignKeys().Select(foreignKey => foreignKey.GetConstraintName()).OfType()) + foreach (var foreignKey in entity.GetDeclaredForeignKeys().Except(links)) { - yield return ("the foreign key", foreignKey); + if (foreignKey.GetConstraintName() is { } name) + { + yield return StoreName.Of("the foreign key", name, foreignKey.GetDefaultName(), "HasConstraintName"); + } } - // The name given, or else the one EF derives from the model's name. - foreach (var check in entity.GetDeclaredCheckConstraints().Select(check => check.Name).OfType()) + // A check constraint always has a name given, and EF cuts one of more than 63 characters to 63 as it cuts a name it + // derives, so an ASCII name of more passes, as PostgreSQL would keep it cut. + foreach (var check in entity.GetDeclaredCheckConstraints()) { - yield return ("the check constraint", check); + if (check.Name is { } name) + { + yield return new("the check constraint", name, Given: name != check.ModelName && name == check.GetDefaultName() ? check.ModelName : null); + } } static IEnumerable Properties(IReadOnlyTypeBase type) => diff --git a/tests/FluentCMS.Core.IntegrationTests/Caching/DistributedLockTests.cs b/tests/FluentCMS.Core.IntegrationTests/Caching/DistributedLockTests.cs index dc719d649..2fbf936c8 100644 --- a/tests/FluentCMS.Core.IntegrationTests/Caching/DistributedLockTests.cs +++ b/tests/FluentCMS.Core.IntegrationTests/Caching/DistributedLockTests.cs @@ -1,9 +1,9 @@ using System.Data.Common; using System.Diagnostics; using FluentCMS.Core.Caching; +using FluentCMS.Core.DependencyInjection; using FluentCMS.Core.IntegrationTests.Diagnostics; using FluentCMS.Core.IntegrationTests.Testing; -using FluentCMS.Core.Jobs; using FluentCMS.Core.Storage; using FluentCMS.Core.Storage.Entities; using FluentCMS.Providers; @@ -704,7 +704,7 @@ await scope.ServiceProvider.GetRequiredService().Set() public async Task ACallbackOnLostThatDoesNotReturnKeepsTheDisposalWaitingOnlyForItsBound() { var clock = new ControllableTimeProvider(); - var bound = new HeldTimers(clock, JobRunner.DisposeWait); + var bound = new HeldTimers(clock, DisposeWait.Bound); var logs = new LogCapture(); var failed = new LoggedSignal(LockLog.LostCallbackFailedId); var renewals = new LeaseRenewalInterceptor(); diff --git a/tests/FluentCMS.Data.Tests/Migrations/SchemaApplyTests.cs b/tests/FluentCMS.Data.Tests/Migrations/SchemaApplyTests.cs index a463f1471..05f38369f 100644 --- a/tests/FluentCMS.Data.Tests/Migrations/SchemaApplyTests.cs +++ b/tests/FluentCMS.Data.Tests/Migrations/SchemaApplyTests.cs @@ -181,6 +181,35 @@ public async Task AnIndexOfAnExpressionMadeByHandIsKeptAndOneOfColumnsIsDropped( indexes.ShouldNotContain("ix_hand_title"); } + // A rebuild makes the table again from the model, which has no index of expressions, so one made by hand is lost with + // the old table and has to be made again after the run, which then keeps it (#3562). + [Fact] + public async Task ATableRebuildOnSqliteLosesAnIndexOfAnExpressionMadeByHand() + { + Assert.SkipUnless(TestProvider.IsSqlite, "Only SQLite rebuilds a table to add a check."); + await MigrateAndApplyAsync(ArticleSchemas.Titled); + InsertArticle("Kept"); + const string Create = "create index ix_hand_lower on cms_article (lower(title))"; + _database.Execute(Create); + var withBody = SampleSchema.NewBuilder() + .AddCollection("article", type => type.Field("title", "text").Field("body", "richText")) + .Build(); + + (await RunAsync(withBody, "schema", "apply", "--script")).Output.ShouldContain("CREATE TABLE \"ef_temp_cms_article\""); + var (exitCode, _, error) = await RunAsync(withBody, "schema", "apply"); + + exitCode.ShouldBe(0, error); + _database.ReadStrings("select title from cms_article").ShouldBe(["Kept"]); + Indexes().ShouldNotContain("ix_hand_lower"); + (await RunAsync(withBody, "schema", "apply")).Output.ShouldStartWith("Nothing to apply;"); + + _database.Execute(Create); + (await RunAsync(withBody, "schema", "apply")).Output.ShouldStartWith("Nothing to apply;"); + Indexes().ShouldContain("ix_hand_lower"); + + List Indexes() => _database.ReadStrings("select name from sqlite_master where type = 'index' and tbl_name = 'cms_article'"); + } + // A content table made before the model gave its text a collation (#2874, #3308) keeps the one it has, which the plan // names; the column's type and nullability are the model's, so nothing is applied (#3476). [Fact] diff --git a/tests/FluentCMS.Plugins.Tests/ContributionPlugins.cs b/tests/FluentCMS.Plugins.Tests/ContributionPlugins.cs index 0b59b584a..e80456f11 100644 --- a/tests/FluentCMS.Plugins.Tests/ContributionPlugins.cs +++ b/tests/FluentCMS.Plugins.Tests/ContributionPlugins.cs @@ -346,9 +346,12 @@ public void Configure(ModelBuilder modelBuilder) var (named, given) = LongNamePlugin.Naming.Value; string Name(string what, string otherwise) => named == what ? given : otherwise; + // A "derived" key or foreign key gets no name, and its table the one the test sets, which EF's name is built from. + var derived = named is "derived key" or "derived foreign key"; + modelBuilder.Entity(note => { - note.ToTable(Name("table", "cms_long_note"), table => + note.ToTable(derived ? given : Name("table", "cms_long_note"), table => { table.HasCheckConstraint(Name("check constraint", "ck_cms_long_note_parent"), "parent_id <> id"); if (named == "table column") @@ -356,19 +359,134 @@ public void Configure(ModelBuilder modelBuilder) table.Property(item => item.ParentId).HasColumnName(given); } }); - note.HasKey(item => item.Id).HasName(Name("key", "pk_cms_long_note")); + if (named == "view") + { + note.ToView(given); + } + + var key = note.HasKey(item => item.Id); + if (named != "derived key") + { + key.HasName(Name("key", "pk_cms_long_note")); + } + note.Property(item => item.Id).HasColumnName("id"); note.Property(item => item.ParentId).HasColumnName(Name("column", "parent_id")); - note.HasOne().WithMany().HasForeignKey(item => item.ParentId).HasConstraintName(Name("foreign key", "fk_cms_long_note_parent")); + var parent = note.HasOne().WithMany().HasForeignKey(item => item.ParentId); + if (named != "derived foreign key") + { + parent.HasConstraintName(Name("foreign key", "fk_cms_long_note_parent")); + } + note.HasIndex(item => item.ParentId).HasDatabaseName(Name("index", "ix_cms_long_note_parent")); note.HasIndex(item => new { item.Id, item.ParentId }, Name("named index", "ix_cms_long_note_id_parent")); - // Named by EF: IX_cms_long_note_parent_id_id, or after the table and the column the test names. - note.HasIndex(item => new { item.ParentId, item.Id }); + // Named by EF: IX_cms_long_note_parent_id_id, or after the table and the column the test names. Left out where + // the test measures the foreign key's name, which comes after it. + if (named != "derived foreign key") + { + note.HasIndex(item => new { item.ParentId, item.Id }); + } }); } } +// Its model maps an order and a second type in the shape the test sets, with the test's name on the table the shape names. +[FluentCmsPlugin("shared", SdkRange = "[1.0.0,2.0.0)")] +public sealed class SharedTablePlugin : IPlugin +{ + public const string Order = "cms_shared_order"; + + public static readonly AsyncLocal<(string Shape, string Table)> Shaping = new(); + + public void ConfigureServices(IPluginServiceBuilder plugin) => plugin.AddModel(); + + public void Configure(IPluginAppBuilder app) + { + } +} + +public sealed class SharedOrder +{ + public Guid Id { get; set; } + + public SharedAddress Address { get; set; } = new(); +} + +public sealed class SharedAddress +{ + public string Street { get; set; } = string.Empty; +} + +public sealed class SharedDetail +{ + public Guid Id { get; set; } + + public string Note { get; set; } = string.Empty; +} + +public sealed class SharedLine +{ + public Guid Id { get; set; } + + public Guid OrderId { get; set; } +} + +public sealed class SharedTableModel : IPluginModelContributor +{ + public void Configure(ModelBuilder modelBuilder) + { + var (shape, table) = SharedTablePlugin.Shaping.Value; + + modelBuilder.Entity(order => + { + order.ToTable(shape is "owned" or "split" ? table : SharedTablePlugin.Order); + order.HasKey(item => item.Id).HasName("pk_cms_shared_order"); + order.Property(item => item.Id).HasColumnName("id"); + switch (shape) + { + case "owned": + order.OwnsOne(item => item.Address, address => address.Property(item => item.Street).HasColumnName("street")); + break; + case "owned table": + order.OwnsOne(item => item.Address, address => + { + address.ToTable(table); + address.Property(item => item.Street).HasColumnName("street"); + }); + break; + default: + order.Ignore(item => item.Address); + break; + } + }); + + if (shape == "split") + { + modelBuilder.Entity(detail => + { + detail.ToTable(table); + detail.HasKey(item => item.Id).HasName("pk_cms_shared_order"); + detail.Property(item => item.Id).HasColumnName("id"); + detail.Property(item => item.Note).HasColumnName("note"); + detail.HasOne().WithOne().HasForeignKey(item => item.Id); + }); + } + + if (shape == "two tables") + { + modelBuilder.Entity(line => + { + line.ToTable(table); + line.HasKey(item => item.Id).HasName("pk_cms_shared_line"); + line.Property(item => item.Id).HasColumnName("id"); + line.Property(item => item.OrderId).HasColumnName("order_id"); + line.HasOne().WithMany().HasForeignKey(item => item.OrderId); + }); + } + } +} + [FluentCmsPlugin("required", SdkRange = "[1.0.0,2.0.0)")] public sealed class RequiredReferencePlugin : IPlugin { diff --git a/tests/FluentCMS.Plugins.Tests/PluginContributionTests.cs b/tests/FluentCMS.Plugins.Tests/PluginContributionTests.cs index 56f4ca17f..b50540537 100644 --- a/tests/FluentCMS.Plugins.Tests/PluginContributionTests.cs +++ b/tests/FluentCMS.Plugins.Tests/PluginContributionTests.cs @@ -139,6 +139,7 @@ public void ATableOutsideThePluginsPrefixStopsTheHost() // passes where EF derives no name from it. [Theory] [InlineData("table", "the table", true)] + [InlineData("view", "the view", false)] [InlineData("column", "the column", true)] [InlineData("table column", "the column", true)] [InlineData("key", "the key", false)] @@ -150,33 +151,84 @@ public void ANameOfAPluginsModelOverSixtyThreeBytesStopsTheHost(string named, st { var tooLong = "cms_long_" + new string('é', 28); LongNamePlugin.Naming.Value = (named, tooLong); - Refused(cms => cms.AddPlugin(), "FCMS1529", "'long'", $"gives {what} of ", $"'{tooLong}'", "65 bytes", "at most 63"); + Refused(cms => cms.AddPlugin(), "FCMS1529", "'long'", $"gives {what} of LongNamedNote the name '{tooLong}' in ", "65 bytes", "at most 63"); - Accepted(named, "cms_long_" + new string('a', 54)); + AcceptedLongName(named, "cms_long_" + new string('a', 54)); if (!derives) { - Accepted(named, "cms_long_" + new string('é', 27)); - } - - static void Accepted(string named, string name) - { - LongNamePlugin.Naming.Value = (named, name); - new ServiceCollection().AddFluentCms(cms => - { - cms.UseSqlite("Data Source=:memory:"); - cms.AddPlugin(); - }); + AcceptedLongName(named, "cms_long_" + new string('é', 27)); } } // EF cuts the names it derives by characters, so the index it names after a column of 63 bytes with é, of 56 characters, - // has 83 bytes, which PostgreSQL would cut. + // has 83 bytes, which PostgreSQL would cut. The refusal says that EF derived it and how to give one (#3562). [Fact] public void ANameThatEFDerivesOverSixtyThreeBytesStopsTheHost() { var column = "cms_long_" + new string('é', 27); LongNamePlugin.Naming.Value = ("column", column); - Refused(cms => cms.AddPlugin(), "FCMS1529", "gives the index of ", $"'IX_cms_long_note_{column}_id'", "83 bytes"); + Refused(cms => cms.AddPlugin(), "FCMS1529", "gives the index of LongNamedNote no name in ", $"the name EF derives for it, 'IX_cms_long_note_{column}_id', has 83 bytes", "Give it a shorter one with HasDatabaseName."); + } + + // The same for a key and a foreign key given no name on a table of 63 bytes with é, which EF's name starts with. + [Theory] + [InlineData("derived key", "the key", "'PK_cms_long_", "66 bytes", "HasName")] + [InlineData("derived foreign key", "the foreign key", "'FK_cms_long_", "103 bytes", "HasConstraintName")] + public void AKeyOrForeignKeyNameThatEFDerivesOverSixtyThreeBytesStopsTheHost(string named, string what, string name, string bytes, string call) + { + LongNamePlugin.Naming.Value = (named, "cms_long_" + new string('é', 27)); + Refused(cms => cms.AddPlugin(), "FCMS1529", $"gives {what} of LongNamedNote no name in ", $"the name EF derives for it, {name}", bytes, $"Give it a shorter one with {call}."); + + AcceptedLongName(named, "cms_long_note"); + } + + // EF cuts a check constraint's given name of more than 63 characters to 63 before it is measured, as it cuts a name it + // derives, so an ASCII name of 70 passes, as PostgreSQL would keep it cut; with é the name it cuts to is too long (#3562). + [Fact] + public void ACheckConstraintNameIsMeasuredAsEFCutsIt() + { + AcceptedLongName("check constraint", "ck_" + new string('c', 67)); + + var given = "ck_" + new string('é', 67); + LongNamePlugin.Naming.Value = ("check constraint", given); + Refused(cms => cms.AddPlugin(), "FCMS1529", $"gives the check constraint of LongNamedNote the name '{given}' in ", $"which EF cuts to 'ck_{new string('é', 59)}~', of 122 bytes"); + } + + // EF emits no foreign key, and no key column of the dependent's own, where an owned type or a type split from its owner + // shares the owner's table by its key, so a long table name with é passes there; the key columns are the owner's (#3562). + [Theory] + [InlineData("owned")] + [InlineData("split")] + public void ATypeOnItsPrincipalsTableByItsKeyIsMeasuredWithoutTheForeignKeyEFDoesNotEmit(string shape) + { + SharedTablePlugin.Shaping.Value = (shape, LongSharedTable); + new ServiceCollection().AddFluentCms(cms => + { + cms.UseSqlite("Data Source=:memory:"); + cms.AddPlugin(); + }); + } + + // A foreign key EF does emit is still measured: between two tables, of an owned type mapped to a table of its own too. + [Theory] + [InlineData("two tables")] + [InlineData("owned table")] + public void AForeignKeyBetweenTwoTablesOverSixtyThreeBytesStopsTheHost(string shape) + { + SharedTablePlugin.Shaping.Value = (shape, LongSharedTable); + Refused(cms => cms.AddPlugin(), "FCMS1529", "'shared'", "gives the foreign key of ", $"'FK_{LongSharedTable}_cms_shared_", "Give it a shorter one with HasConstraintName."); + } + + private static string LongSharedTable => "cms_shared_" + new string('é', 26); + + private static void AcceptedLongName(string named, string name) + { + LongNamePlugin.Naming.Value = (named, name); + new ServiceCollection().AddFluentCms(cms => + { + cms.UseSqlite("Data Source=:memory:"); + cms.AddPlugin(); + }); } [Fact]