diff --git a/.claude/skills/fix-issue/findings/lint-rules/2026-12-02-sec012-microflow-snippet-same-name.json b/.claude/skills/fix-issue/findings/lint-rules/2026-12-02-sec012-microflow-snippet-same-name.json new file mode 100644 index 0000000000..6b67ebf39b --- /dev/null +++ b/.claude/skills/fix-issue/findings/lint-rules/2026-12-02-sec012-microflow-snippet-same-name.json @@ -0,0 +1 @@ +{"area": "lint-rules", "date": "2026-12-02", "refs": ["ako/mxcli#2730", "mendixlabs/mxcli#2004"], "ce": ["CE2729"], "symptom": "a Marketplace module with a microflow and a snippet both named Lib.Overview: a menu item calling the microflow (execute only for Lib.Runner) made SEC012 report CE2729 on every attribute the snippet's nested snippet shows, for every role without Lib.Runner; mx check reported 0 errors. `show references to Lib.Overview` listed the menu item beside the page using the snippet with nothing to tell them apart", "cause": "the SEC012 reach model keyed every document by its bare qualified name: the navigation entry Lib.Overview was taken for the snippet (m.module set, so the entry's execute check was skipped) and the microflow's and snippet's references were merged under one key; showReferences selected no target type", "file": "mdl/linter/rules/reachable_page_read_access.go (node, sourceKinds, flowNode, reach), mdl/executor/cmd_search.go (showReferences)", "fix": "walk nodes are kind+name (PAGE, SNIPPET, MICROFLOW, NANOFLOW): refs by SourceType, menu items and homes by their page/microflow column and HomePageType, execute grants by ElementType; show references adds a TargetType column when the name names more than one kind", "insight": "qualified names are not unique across document kinds in Mendix (Studio Pro accepts a microflow and a snippet of one name; measured on 11.12.6), so any map keyed by qualified name alone conflates them. The catalog's refs carry SourceType/TargetType; a consumer that drops them reintroduces the collision. Grep other name-keyed maps over refs before assuming one fix covers the class", "test": "mdl/linter/rules/reachable_page_same_name_2730_test.go, mdl/executor/show_references_same_name_2730_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-backend/2026-12-02-alter-insert-column-enum-lowercased.json b/.claude/skills/fix-issue/findings/mdl-backend/2026-12-02-alter-insert-column-enum-lowercased.json new file mode 100644 index 0000000000..2e9272ff2f --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-backend/2026-12-02-alter-insert-column-enum-lowercased.json @@ -0,0 +1 @@ +{"area": "mdl-backend", "date": "2026-12-02", "refs": ["ako/mxcli#2718", "mendixlabs/mxcli#1999", "#854", "#1519"], "ce": [], "symptom": "a Data grid 2 column inserted with `alter page \u2026 insert after grid column(X) { column (\u2026, ColumnWidth: autoFit, minWidth: minContent) }` stored width `autofit` (autoFill as `autofill`) and minWidth `auto`; describe printed `ColumnWidth: autofit`; check warned minWidth would be dropped (MDL-WIDGET07); exec and mx check were clean. The widget compares its keys exactly, so the column rendered as auto-fill. create page stored both as written", "cause": "the ALTER column path does not go through the widget engine: widgetobj.BuildDataGrid2Column read every enumeration through colPropString, which lowercases, hard-coded minWidth `auto`, and dropped every other primitive the column schema declares; extractColumnPropertyIDs did not carry the stored type's EnumerationValues. check judged an inserted column with no parent, so not by the column schema", "file": "mdl/backend/widgetobj/datagrid_column.go (colPropEnum, colPropPrimitive), mdl/backend/pagemutator/mutator.go (extractColumnPropertyIDs), mdl/types/widget_property_type.go (EnumerationKeys), mdl/executor/validate_widgets.go (validateAlterFragment)", "fix": "PropertyTypeIDEntry.EnumerationKeys, filled from the grid's stored widget type; enumerations write the declared key the value names (exact, then case-insensitive, as #854 does in the engine); minWidth and any other declared primitive stated under its key are written; an insert or replace addressed `grid column(\u2026)` is validated with a datagrid parent, so its columns are object-list items of the grid's definition (or the embedded column schema)", "insight": "two writers for one widget drift: the engine had #854's enum canonicalization and the full column schema, the alter path a hand list with lowercasing that happened to match the all-lowercase keys (left, yes) and not the camel-case ones. Comparing describe output of a create-built and an alter-built column (re-exec Unchanged) is the cheapest parity check. Measured on 11.12.6: before autofit/autofill; after autoFit/autoFill/minContent, describe re-exec Unchanged, mx check 0 errors; with a project an undeclared column key is now MDL-WIDGET01 as in create page", "test": "mdl/backend/widgetobj/datagrid_column_enum_case_2718_test.go, mdl/executor/validate_alter_insert_column_schema_2718_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-mapping-value-element-stores-member-type.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-mapping-value-element-stores-member-type.json new file mode 100644 index 0000000000..78cf5d9d82 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-mapping-value-element-stores-member-type.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-12-02", "refs": ["ako/mxcli#2714", "mendixlabs/mxcli#2001", "ako/mxcli#2603", "ako/mxcli#1258"], "ce": ["CE5015", "CE6099", "CE0227"], "symptom": "`create import mapping` binding a JSON integer member (`\"code\": 123`) to a String attribute stored the value element as DataTypes$StringType; mx check reported CE5015 \"Attribute type 'String' does not match schema type 'Integer'\". create or modify did not repair it. Since the check-gap sweep (MDL127) check refused the pairing outright, calling it an exact-match rule", "cause": "buildImportMappingElementModel and buildExportMappingElementModel set the value element's DataType from the bound attribute (resolveAttributeType), never from the JSON member it binds; MDL127's 'types must match exactly' table was measured against those writes, so every conversion looked like CE5015", "file": "mdl/executor/cmd_import_mappings.go (mappingValueDataType, mappingTypesAlign), cmd_export_mappings.go, validate_mapping_snippet_gaps.go (mappingValueAccepted, MDL127)", "fix": "the element stores the attribute's type where it aligns with the member's (integer\u2192Integer/Long/AutoNumber, string\u2192String/Enumeration/DateTime, same type) and the member's type otherwise; MDL127 now refuses only what mxbuild refuses with that write: import accepts any member into String and integer into Decimal, export a String attribute into any member and Integer/Long into a decimal; others are CE6099 (import) / CE0227 (export)", "insight": "a check derived from measurements of a writer inherits the writer's bugs: MDL127's table was right about what mxcli's writes built and wrong about Mendix. Neither 'attribute type' nor 'member type' alone is right \u2014 a string member into a DateTime attribute needs the attribute's type (member's type there is CE6099/CE0227). A one-project matrix (5 member types \u00d7 7 attribute types \u00d7 import/export, one element per pairing, attribute name encoding the pairing) settled it in one mx check, and the same matrix run through `check` must give the same set \u2014 it did (22 import, 21 export). Measured on 11.12.6: reporter's mapping CE5015 before, 0 errors after a create or modify, re-run Unchanged", "test": "mdl/executor/mapping_value_type_2714_test.go, mdl/executor/check_gap_mappings_snippets_test.go (TestMappingValueTypes re-measured)"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-modify-local-variable-to-parameter-refused.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-modify-local-variable-to-parameter-refused.json new file mode 100644 index 0000000000..652ad6ea57 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-02-modify-local-variable-to-parameter-refused.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-12-02", "refs": ["ako/mxcli#2726", "mendixlabs/mxcli#2002", "mendixlabs/mxcli#1517"], "ce": [], "symptom": "`create or modify microflow` turning a local list into a parameter of the same name ($SaleList: List of M.Sale, the `create list` and `commit` removed) was refused under mdl 1 (MDL-V1-REBUILD): \"drop $SaleList: $SaleList is still used by: add $NewSale to $SaleList\". Any other parameter name spliced", "cause": "alterFlowContext.checkOutputUnused counted the stored readers of a dropped producer's output, exempting only a variable an operation's fragment declares again; a parameter of the declared header (a.mf.Parameters once planFlowModify sees the header change) was not counted as declaring it", "file": "mdl/executor/cmd_alter_flow.go (checkOutputUnused, isParameter)", "fix": "a variable a parameter of the flow being written declares is not left without its producer; the readers read the parameter", "insight": "a unit test through afRun did NOT reproduce it: Executor.Execute does not apply the program's `mdl 1;` header, and under mdl 0 a refused splice silently falls back to a rebuild. Reproduce splice refusals through ExecuteProgram (or set the language version). Measured on 11.12.6: old binary refuses, new splices (2 dropped, parameter added), re-run Unchanged, mx check 0 errors", "test": "mdl/executor/flow_modify_local_to_parameter_2726_test.go"} diff --git a/.claude/skills/fix-issue/findings/modelsdk/2026-12-02-carry-unexpressed-hidden-widget-value-template.json b/.claude/skills/fix-issue/findings/modelsdk/2026-12-02-carry-unexpressed-hidden-widget-value-template.json new file mode 100644 index 0000000000..2ac6befa71 --- /dev/null +++ b/.claude/skills/fix-issue/findings/modelsdk/2026-12-02-carry-unexpressed-hidden-widget-value-template.json @@ -0,0 +1 @@ +{"area": "modelsdk", "date": "2026-12-02", "refs": ["ako/mxcli#2732", "mendixlabs/mxcli#2006", "ako/mxcli#1897", "#574", "#931", "ako/mxcli#2507"], "ce": ["CE0463"], "symptom": "`create or modify page` turning a Data grid 2 attribute column into `ShowContentAs: customContent` passed check and exec; mx check then reported CE0463 on the grid. The column's `tooltip` (hidden for custom content) kept the empty Forms$ClientTemplate the attribute column had, where create page writes null. fix widgets did not clear it", "cause": "canon.carryUnexpressed puts a stored EMPTY ClientTemplate back where the writer writes null \u2014 added for Studio Pro's unset screen-reader label (#1897). Inside a CustomWidgets$WidgetValue the writer's null is deliberate: the widget's editorConfig hides the property", "file": "modelsdk/canon/unexpressed.go (carryUnexpressed, isWidgetValue)", "fix": "the null-over-empty-template carry skips CustomWidgets$WidgetValue elements; the screen-reader label carry on built-in widgets is unchanged", "insight": "an equivalence a carry assumes (null == empty template) holds for one property family and not for another; in pluggable values null and empty are two editorConfig states. The diff was found with `bson dump --compare Fixed,Broken`: one property differing, everything else identical. A page already broken stays broken on re-run: the stored pluggable passes through when the statement describes the same widget, so repairing stored damage is fix widgets' job (#2507). Measured on 11.12.6: before CE0463, after a fresh create \u2192 modify gives 0 errors on that grid, describe re-exec Unchanged", "test": "modelsdk/canon/unexpressed_widgetvalue_2732_test.go"} diff --git a/.claude/skills/mendix/connect-rapidminer-graph/SKILL.md b/.claude/skills/mendix/connect-rapidminer-graph/SKILL.md index 58c00dbe85..2f13325f12 100644 --- a/.claude/skills/mendix/connect-rapidminer-graph/SKILL.md +++ b/.claude/skills/mendix/connect-rapidminer-graph/SKILL.md @@ -15,10 +15,10 @@ description: "Fetch data from a RapidMiner graph mart or any SPARQL 1.1 HTTP end | 63-83 | SPARQL JSON result shape | | 84-103 | The full pipeline | | 104-243 | Step-by-step template | -| 244-283 | Gotchas (things that burned an hour during development) | -| 284-319 | Exploring the graph | -| 320-323 | Credential management | -| 324-329 | Related skills | +| 244-278 | Gotchas (things that burned an hour during development) | +| 279-314 | Exploring the graph | +| 315-318 | Credential management | +| 319-324 | Related skills | # Connecting Mendix to RapidMiner / AnzoGraph via SPARQL @@ -260,12 +260,7 @@ Body: template '... WHERE {1} ... {2}' ### JSON structure auto-detects ISO strings as DateTime -If your JSLT emits ISO 8601 timestamps (`"2026-04-13T14:00"`) and the target Mendix attribute is `string`, `create json structure ... sample '...'` will infer `datetime` from the sample and mxbuild fails with `CE5015` ("schema type DateTime doesn't match attribute type String"). - -**Solutions:** -- Use a non-ISO sample value in the snippet (e.g. `"2026-04-13 14:00 CET"`). -- Or slice/format the timestamp in JSLT so it doesn't look like ISO 8601 (`$rawTime[11 : 16]` for `HH:MM`). -- Or change the target attribute to `datetime`. +If your JSLT emits ISO 8601 timestamps (`"2026-04-13T14:00"`), `create json structure ... sample '...'` infers `datetime` for the member. Binding it to a `string` attribute is fine: the mapping converts it (it failed with `CE5015` before ako/mxcli#2714). Bind it to a `datetime` attribute when you want the timestamp as a date. ### Non-persistent child lists can't be extracted in microflows diff --git a/.claude/skills/mendix/json-structures-and-mappings/SKILL.md b/.claude/skills/mendix/json-structures-and-mappings/SKILL.md index f637648b64..e10de6372a 100644 --- a/.claude/skills/mendix/json-structures-and-mappings/SKILL.md +++ b/.claude/skills/mendix/json-structures-and-mappings/SKILL.md @@ -13,17 +13,17 @@ description: "Create and manage JSON structures, import mappings and export mapp | 33-110 | Key Concepts | | 111-122 | Export Mappings | | 123-188 | JSON Structures | -| 189-235 | Message Definitions | -| 236-401 | Import Mappings | -| 402-499 | Export Mappings | -| 500-517 | Starting a Mapping Below the Payload Root | -| 518-601 | Microflow Actions | -| 602-614 | Browse | -| 615-662 | Export Workflow: PE → NPE → JSON | -| 663-669 | Realistic Example: Countries REST API | -| 670-693 | Placing Documents in Folders | -| 694-709 | Documentation | -| 710-724 | Common Mistakes | +| 189-234 | Message Definitions | +| 235-400 | Import Mappings | +| 401-498 | Export Mappings | +| 499-516 | Starting a Mapping Below the Payload Root | +| 517-600 | Microflow Actions | +| 601-613 | Browse | +| 614-661 | Export Workflow: PE → NPE → JSON | +| 662-668 | Realistic Example: Countries REST API | +| 669-692 | Placing Documents in Folders | +| 693-708 | Documentation | +| 709-724 | Common Mistakes | # JSON Structures, Import Mappings & Export Mappings @@ -232,7 +232,6 @@ The full vocabulary, the ALTER statements, inherited attributes and what mxcli deliberately does not guess: [reference/message-definitions.md](reference/message-definitions.md). - ## Import Mappings ### Domain Model for Import @@ -722,3 +721,4 @@ create or modify import mapping Sales.IMM_Order | `Param: parameter` with no `parameter Module.Entity` on the header | Declare the mapping's input object, or the build reports CE0279 | | `parameter` on an EXPORT mapping | Export mappings have no input object — their parameter is the root object | | Arrays in import with container entity | Import arrays map directly to item entity, no container | +| A value's JSON type differs from the attribute's (MDL127) | Import converts any member into a String attribute and an integer into a Decimal; export a String attribute into any member and an Integer/Long into a decimal. Anything else: match the types or convert in a microflow (CE6099 / CE0227) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cb6e8ac9e..1769504392 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -99,6 +99,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **An error handler that carries on no longer rejoins before a list operation on the output it never produced** (ako/mxcli#2696) — for `$Rows = on error … end error; $Row = head $Rows; if $Row != empty …`, the handler rejoined right before the `head`. `check` and `exec` passed, and `mx check` reported CE0108 at it. A list operation, an aggregate, a cast, a rollback, a show page and the enumeration and inheritance splits now count as reading their input. The variable a list operation, aggregate or cast computes from the output is skipped too, also in flows that declare their return value. - **`create or modify association` without a delete clause keeps the stored delete behaviour** (ako/mxcli#2713) — a statement written only to set documentation reset `on delete restrict error message '…'` to the default keep-references behaviour and dropped the message, with no warning from `check`, `exec` or `mx check`. An unstated `on delete` now keeps the stored behaviour and its message, the way unstated storage and export level already did. A stated one still replaces them. - **An input's `AriaRequired` and a text box's `AutocompletePurpose` are written and described** (ako/mxcli#2710, upstream mendixlabs/mxcli#1996) — `check` refused both, every text box, text area, date picker and radio button group was stored with Aria required off, and every text box with autocomplete purpose `On`. So rewriting a page or snippet from MDL, `create or modify` as well as `drop` and `create`, reset what Studio Pro had set, without a warning. `AriaRequired: true`, `Autocomplete: false` and `AutocompletePurpose: PostalCode` (any of Studio Pro's purposes) are now written as given and described when they differ from the default. An unknown purpose is refused by `check` and `exec`. +- **A Data grid 2 column inserted with `alter page` keeps its width as written** (ako/mxcli#2718, upstream mendixlabs/mxcli#1999) — `alter page … insert after grid column(X) { column (…, ColumnWidth: autoFit) }` stored the width as `autofit`, and `autoFill` as `autofill`. The widget compares its keys exactly, so the column rendered as auto-fill, and `check`, `exec` and `mx check` reported nothing. `minWidth: minContent` was dropped, with a warning that it was not a column property. An inserted or replacing column now stores enumeration values as the widget declares them, and every column property `create page` accepts, `minWidth` and `minWidthLimit` included. `check` judges such a column by the Data grid 2 column schema: with a project, a key the column does not have is an error (MDL-WIDGET01), as in `create page`. +- **`create or modify page` turning a Data grid 2 column into custom content no longer breaks the grid** (ako/mxcli#2732, upstream mendixlabs/mxcli#2006) — replacing an attribute column with the same column as `ShowContentAs: customContent` kept the column's empty tooltip template. The widget hides that property for custom content, so `mx check` reported CE0463 on the grid after `check` and `exec` had passed. The replaced column is now written as `create page` writes it. A page already in this state is not repaired by re-running the statement. +- **A mapping value can convert between the JSON member's type and the attribute's** (ako/mxcli#2714, upstream mendixlabs/mxcli#2001) — an import mapping binding a JSON integer to a String attribute stored the value with the attribute's type, and `mx check` reported CE5015. Recent builds refused the mapping at `check` instead (MDL127), calling it an exact-type rule. A value now stores the member's type where the mapping converts, as Studio Pro does. `check` accepts what the build accepts, measured over every pairing: on import, any value into a String attribute and an integer into a Decimal; on export, a String attribute into any member and an Integer or Long into a decimal. Other pairings are still refused, now naming CE6099 (import) or CE0227 (export). Re-running `create or modify` repairs a mapping written before. +- **`create or modify microflow` can turn a local variable into a parameter of the same name** (ako/mxcli#2726, upstream mendixlabs/mxcli#2002) — moving a list to the caller meant adding the parameter `$SaleList` and removing the `create list` that declared it. That was refused (MDL-V1-REBUILD) with "drop $SaleList: $SaleList is still used by: add $NewSale to $SaleList", although the new parameter supplies the variable. The change is now spliced into the stored flow. A reader left with no variable at all is still refused. +- **SEC012 tells a microflow from a snippet of the same name** (ako/mxcli#2730, upstream mendixlabs/mxcli#2004) — a Marketplace module can hold a microflow and a snippet both named `Lib.Overview`. A menu item calling the microflow was taken for the snippet, without the check that the role may execute the microflow. `lint` then reported CE2729 on every attribute the snippet shows, for roles that cannot reach it, where `mx check` reported nothing. The reachability walk now keys each document by its kind as well as its name. `show references` adds the target's type when a name belongs to more than one kind of document. ## [0.34.0] - 2026-11-27 diff --git a/mdl-examples/bug-tests/check-gap-mapping-values.fail.mdl b/mdl-examples/bug-tests/check-gap-mapping-values.fail.mdl index 4179c5b226..c06b0c08f2 100644 --- a/mdl-examples/bug-tests/check-gap-mapping-values.fail.mdl +++ b/mdl-examples/bug-tests/check-gap-mapping-values.fail.mdl @@ -1,7 +1,8 @@ --- check-gap f75 f76 f77 (ako/mxcli#1258): mapping values MxBuild 11.16.1 --- rejects. A JSON string into an Integer attribute, and an Integer attribute --- into a JSON string, are CE5015 (the two types must match exactly); a value --- naming an attribute the entity does not have is CE1613. check reports MDL127. +-- check-gap f75 f76 f77 (ako/mxcli#1258): mapping values MxBuild rejects. A +-- JSON string into an Integer attribute is CE6099, and an Integer attribute +-- into a JSON string CE0227 (re-measured on 11.12.6 for ako/mxcli#2714); a +-- value naming an attribute the entity does not have is CE1613. check reports +-- MDL127. mdl 1; create module MvBad; create json structure MvBad.J sample '{"age": "three", "name": "x"}'; diff --git a/mdl-examples/check-gap/README.md b/mdl-examples/check-gap/README.md index 132722a9dc..d1e84a60a2 100644 --- a/mdl-examples/check-gap/README.md +++ b/mdl-examples/check-gap/README.md @@ -108,9 +108,9 @@ while `mx check` rejected the written project — the new backlog: | fixture | mistake | mx check | |---|---|---| -| f75 | an import mapping putting a JSON string (`"three"`) into an Integer attribute | CE5015 the mapping does not align with the schema | — now `check`: MDL127 +| f75 | an import mapping putting a JSON string (`"three"`) into an Integer attribute | CE6099 the schema type is not compatible with the attribute (CE5015 before ako/mxcli#2714) | — now `check`: MDL127 | f76 | an import mapping naming an attribute the entity does not have | CE1613 | — now `check`: MDL127 -| f77 | an export mapping putting an Integer attribute into a JSON string value | CE5015 | — now `check`: MDL127 +| f77 | an export mapping putting an Integer attribute into a JSON string value | CE0227 (CE5015 before ako/mxcli#2714) | — now `check`: MDL127 | f78 | `import from mapping` fed an object instead of a String or file document | CE0239 | — now `check`: MDL128 | f80 | a published REST service path starting with `/` | CE3471 | — now `check`: MDL129 | f81 | a published REST operation path `{id}` with no `$id` microflow parameter | CE1613 | — now `check -p` @@ -139,3 +139,39 @@ Already refused by `check -p`: f86 (a Java action in a nanoflow), f90 (a data gr attribute), f96 (a duplicate enumeration value), f97 (an attribute named like an association). Build clean, so no gap: f87 (an XPath function in a nanoflow retrieve), f94 (an entity-access write grant on an AutoNumber), f98 (`commit` of a non-persistent object in a nanoflow). + +## Fifth sweep: f99–f125, MxBuild 11.16.1, 2026-12-02 + +Fixtures for calculated attributes, validation rules, list operations, file downloads, input +widgets, data grid constraints, menus, user task pages, view entities, indexes and page +parameters. Numbers 103, 106, 107, 109, 118, 121 and 122 were drafts dropped before measuring: +`check` already refused them, or (122, sorting by an association) MDL has no spelling for them. +Rows here passed `check -p` while `mx check` rejected the written project — the new backlog: + +| fixture | mistake | mx check | +|---|---|---| +| f104 | `add` of an object of another entity to a list | CE0117 | +| f105 | `union` of lists of two unrelated entities | CE0024 not (a specialization of) the type | +| f108 | `download file` of an object that is not a System.FileDocument | CE0480 | +| f110 | a database `retrieve` sorted by an attribute the entity does not have | CE1613 | +| f114 | a data grid XPath constraint comparing an Integer attribute with a string | CE0161 error in XPath constraint | +| f117 | a view entity whose OQL selects an attribute the entity does not have | CE0174 error in OQL query | +| f119 | an index on a calculated attribute | CE0083 | + +Check and exec disagree on four, which `check -p` passes and `exec` refuses: + +| fixture | mistake | exec | +|---|---|---| +| f99 | a calculated attribute on a non-persistent entity | calculated attributes need a persistent entity | +| f100 | a calculated attribute whose microflow takes another entity | the calculation microflow's parameter type | +| f120 | `change` of a list variable | validation errors | +| f125 | a calculated attribute naming a microflow the script creates later | microflow not found | + +f125 is the natural order for a calculated attribute, whose microflow takes the entity: the entity +must exist first, so the attribute has to be added afterwards with `alter entity … add attribute`. + +Already refused by `check -p`: f111 (a `create` member of the wrong type), f112 (a date picker on an +Integer), f113 (a combo box on a Decimal), f115 (a menu item opening a page that takes a parameter), +f116 (a user task page for another entity), f124 (a Decimal assigned to an Integer attribute). +Build clean, so no gap: f101 (a range rule on a String attribute), f102 (a regex rule on an Integer +attribute), f123 (a page parameter that is a list). diff --git a/mdl-examples/check-gap/fixtures/f100_calc_attr_wrong_param.mdl b/mdl-examples/check-gap/fixtures/f100_calc_attr_wrong_param.mdl new file mode 100644 index 0000000000..88fa468cc9 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f100_calc_attr_wrong_param.mdl @@ -0,0 +1,3 @@ +mdl 1; +create microflow Sp.Calc100 ($I: Sp.Item) returns Integer as $R begin return 1; end; +create persistent entity Sp.Calc100E ( N: Integer calculated by Sp.Calc100 ); diff --git a/mdl-examples/check-gap/fixtures/f101_range_rule_on_string.mdl b/mdl-examples/check-gap/fixtures/f101_range_rule_on_string.mdl new file mode 100644 index 0000000000..ac077f7559 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f101_range_rule_on_string.mdl @@ -0,0 +1,2 @@ +mdl 1; +create validation rule for Sp.Item.Name range from 1 to 10 error message 'out of range'; diff --git a/mdl-examples/check-gap/fixtures/f102_regex_rule_on_integer.mdl b/mdl-examples/check-gap/fixtures/f102_regex_rule_on_integer.mdl new file mode 100644 index 0000000000..af724a25ea --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f102_regex_rule_on_integer.mdl @@ -0,0 +1,3 @@ +mdl 1; +create regular expression Sp.Digits ( Expression: '^[0-9]+$' ); +create validation rule for Sp.Item.Qty regex Sp.Digits error message 'digits'; diff --git a/mdl-examples/check-gap/fixtures/f104_add_wrong_entity_to_list.mdl b/mdl-examples/check-gap/fixtures/f104_add_wrong_entity_to_list.mdl new file mode 100644 index 0000000000..8f39dba2e4 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f104_add_wrong_entity_to_list.mdl @@ -0,0 +1,3 @@ +mdl 1; +create persistent entity Sp.Other ( L: String(10) ); +create microflow Sp.F104 ($L: List of Sp.Item, $O: Sp.Other) begin add $O to $L; end; diff --git a/mdl-examples/check-gap/fixtures/f105_union_different_entities.mdl b/mdl-examples/check-gap/fixtures/f105_union_different_entities.mdl new file mode 100644 index 0000000000..c9f0366e99 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f105_union_different_entities.mdl @@ -0,0 +1,3 @@ +mdl 1; +create persistent entity Sp.Other ( L: String(10) ); +create microflow Sp.F105 ($A: List of Sp.Item, $B: List of Sp.Other) begin $U = union $A with $B; end; diff --git a/mdl-examples/check-gap/fixtures/f108_download_non_filedocument.mdl b/mdl-examples/check-gap/fixtures/f108_download_non_filedocument.mdl new file mode 100644 index 0000000000..8a1a192850 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f108_download_non_filedocument.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F108 ($I: Sp.Item) begin download file $I; end; diff --git a/mdl-examples/check-gap/fixtures/f110_retrieve_sort_unknown.mdl b/mdl-examples/check-gap/fixtures/f110_retrieve_sort_unknown.mdl new file mode 100644 index 0000000000..2ae8d7b606 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f110_retrieve_sort_unknown.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F110 () begin retrieve $L from Sp.Item sort by Nope asc; end; diff --git a/mdl-examples/check-gap/fixtures/f111_create_member_wrong_type.mdl b/mdl-examples/check-gap/fixtures/f111_create_member_wrong_type.mdl new file mode 100644 index 0000000000..a72ca148c6 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f111_create_member_wrong_type.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F111 () begin $I = create Sp.Item (Qty = 'abc'); end; diff --git a/mdl-examples/check-gap/fixtures/f112_datepicker_on_integer.mdl b/mdl-examples/check-gap/fixtures/f112_datepicker_on_integer.mdl new file mode 100644 index 0000000000..53fed68d04 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f112_datepicker_on_integer.mdl @@ -0,0 +1,2 @@ +mdl 1; +create page Sp.P112 ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $I: Sp.Item ) ) { dataview dv (datasource: $I) { datepicker d (attribute: Qty) } }; diff --git a/mdl-examples/check-gap/fixtures/f113_combobox_on_decimal.mdl b/mdl-examples/check-gap/fixtures/f113_combobox_on_decimal.mdl new file mode 100644 index 0000000000..aabf6ea42e --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f113_combobox_on_decimal.mdl @@ -0,0 +1,2 @@ +mdl 1; +create page Sp.P113 ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $I: Sp.Item ) ) { dataview dv (datasource: $I) { combobox c (attribute: Amount) } }; diff --git a/mdl-examples/check-gap/fixtures/f114_datagrid_xpath_type.mdl b/mdl-examples/check-gap/fixtures/f114_datagrid_xpath_type.mdl new file mode 100644 index 0000000000..97f2f3a5c9 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f114_datagrid_xpath_type.mdl @@ -0,0 +1,2 @@ +mdl 1; +create page Sp.P114 ( title: 'p', layout: Atlas_Core.Atlas_Default ) { datagrid g (datasource: database Sp.Item where [Qty = 'abc']) { column (attribute: Name) } }; diff --git a/mdl-examples/check-gap/fixtures/f115_menu_item_page_with_param.mdl b/mdl-examples/check-gap/fixtures/f115_menu_item_page_with_param.mdl new file mode 100644 index 0000000000..525b9527d8 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f115_menu_item_page_with_param.mdl @@ -0,0 +1,3 @@ +mdl 1; +create page Sp.P115 ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $I: Sp.Item ) ) { dynamictext t (content: 'x') }; +create menu Sp.M115 { menu item 'Go' (OnClick: show page Sp.P115) }; diff --git a/mdl-examples/check-gap/fixtures/f116_usertask_page_wrong_entity.mdl b/mdl-examples/check-gap/fixtures/f116_usertask_page_wrong_entity.mdl new file mode 100644 index 0000000000..8c46b2bc0b --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f116_usertask_page_wrong_entity.mdl @@ -0,0 +1,4 @@ +mdl 1; +create persistent entity Sp.Ctx ( N: String(10) ); +create page Sp.P116 ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $I: Sp.Item ) ) { dynamictext t (content: 'x') }; +create workflow Sp.WF116 parameter $WorkflowContext: Sp.Ctx display 'W' begin user task T1 'Do it' page Sp.P116 outcomes 'Done' { } ; end workflow; diff --git a/mdl-examples/check-gap/fixtures/f117_view_entity_unknown_attr.mdl b/mdl-examples/check-gap/fixtures/f117_view_entity_unknown_attr.mdl new file mode 100644 index 0000000000..93b5020663 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f117_view_entity_unknown_attr.mdl @@ -0,0 +1,2 @@ +mdl 1; +create view entity Sp.V117 ( N: String(100) ) as ( select i.Nope as N from Sp.Item as i ); diff --git a/mdl-examples/check-gap/fixtures/f119_index_on_calculated.mdl b/mdl-examples/check-gap/fixtures/f119_index_on_calculated.mdl new file mode 100644 index 0000000000..5287a1c70d --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f119_index_on_calculated.mdl @@ -0,0 +1,5 @@ +mdl 1; +create persistent entity Sp.Calc119E ( X: Integer ); +create microflow Sp.Calc119 ($C: Sp.Calc119E) returns Integer as $R begin return 1; end; +alter entity Sp.Calc119E add attribute N: Integer calculated by Sp.Calc119; +alter entity Sp.Calc119E add index (N); diff --git a/mdl-examples/check-gap/fixtures/f120_change_list_with_object_op.mdl b/mdl-examples/check-gap/fixtures/f120_change_list_with_object_op.mdl new file mode 100644 index 0000000000..25ec3d2554 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f120_change_list_with_object_op.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F120 ($L: List of Sp.Item) begin change $L (Qty = 1); end; diff --git a/mdl-examples/check-gap/fixtures/f123_page_param_list.mdl b/mdl-examples/check-gap/fixtures/f123_page_param_list.mdl new file mode 100644 index 0000000000..f7e1370e84 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f123_page_param_list.mdl @@ -0,0 +1,2 @@ +mdl 1; +create page Sp.P123 ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $L: List of Sp.Item ) ) { dynamictext t (content: 'x') }; diff --git a/mdl-examples/check-gap/fixtures/f124_decimal_to_integer_assign.mdl b/mdl-examples/check-gap/fixtures/f124_decimal_to_integer_assign.mdl new file mode 100644 index 0000000000..609d41c635 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f124_decimal_to_integer_assign.mdl @@ -0,0 +1,2 @@ +mdl 1; +create microflow Sp.F124 ($I: Sp.Item) begin change $I (Qty = $I/Amount); end; diff --git a/mdl-examples/check-gap/fixtures/f125_calc_attr_forward_ref.mdl b/mdl-examples/check-gap/fixtures/f125_calc_attr_forward_ref.mdl new file mode 100644 index 0000000000..0354169147 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f125_calc_attr_forward_ref.mdl @@ -0,0 +1,3 @@ +mdl 1; +create persistent entity Sp.Calc125E ( N: Integer calculated by Sp.Calc125 ); +create microflow Sp.Calc125 ($C: Sp.Calc125E) returns Integer as $R begin return 1; end; diff --git a/mdl-examples/check-gap/fixtures/f99_calc_attr_returns_string.mdl b/mdl-examples/check-gap/fixtures/f99_calc_attr_returns_string.mdl new file mode 100644 index 0000000000..63580f8d91 --- /dev/null +++ b/mdl-examples/check-gap/fixtures/f99_calc_attr_returns_string.mdl @@ -0,0 +1,3 @@ +mdl 1; +create non-persistent entity Sp.Calc99E ( N: Integer calculated by Sp.Calc99 ); +create microflow Sp.Calc99 ($C: Sp.Calc99E) returns String as $R begin return 'x'; end; diff --git a/mdl/backend/pagemutator/mutator.go b/mdl/backend/pagemutator/mutator.go index 18837c4614..9b4cedaa44 100644 --- a/mdl/backend/pagemutator/mutator.go +++ b/mdl/backend/pagemutator/mutator.go @@ -1014,6 +1014,7 @@ func extractColumnPropertyIDs(widgetDoc bson.D, columnsTypePointerID string) (ob cid := bsonnav.ExtractBinaryIDFromDoc(bsonnav.DGet(cptDoc, "$ID")) cvt := bsonnav.DGetDoc(cptDoc, "ValueType") var vid, vtype, defVal string + var enumKeys []string if cvt != nil { vid = bsonnav.ExtractBinaryIDFromDoc(bsonnav.DGet(cvt, "$ID")) // The discriminator is the inner "Type" field on the @@ -1021,15 +1022,25 @@ func extractColumnPropertyIDs(widgetDoc bson.D, columnsTypePointerID string) (ob // "TextTemplate", "Widgets", "Enumeration", "Boolean". vtype = bsonnav.DGetString(cvt, "Type") defVal = bsonnav.DGetString(cvt, "DefaultValue") + // The declared keys, so the column builder writes the key and + // not a lowercased guess at it (ako/mxcli#2718). + for _, ev := range bsonnav.DGetArrayElements(bsonnav.DGet(cvt, "EnumerationValues")) { + if evDoc, ok := ev.(bson.D); ok { + if k := bsonnav.DGetString(evDoc, "_Key"); k != "" { + enumKeys = append(enumKeys, k) + } + } + } } if key == "" || cid == "" { continue } propIDs[key] = pages.PropertyTypeIDEntry{ - PropertyTypeID: cid, - ValueTypeID: vid, - ValueType: vtype, - DefaultValue: defVal, + PropertyTypeID: cid, + ValueTypeID: vid, + ValueType: vtype, + DefaultValue: defVal, + EnumerationKeys: enumKeys, } } return diff --git a/mdl/backend/widgetobj/datagrid_column.go b/mdl/backend/widgetobj/datagrid_column.go index 5d5ef79ec1..32020d5686 100644 --- a/mdl/backend/widgetobj/datagrid_column.go +++ b/mdl/backend/widgetobj/datagrid_column.go @@ -139,22 +139,23 @@ func BuildDataGrid2Column(childSer ChildSerializer, col *backend.DataGridColumnS properties = append(properties, buildColumnPrimitiveProperty(entry, wrapVal)) case "alignment": - alignVal := colPropString(col.Properties, "Alignment", "left") + alignVal := colPropEnum(entry, col.Properties, "Alignment", "left") properties = append(properties, buildColumnPrimitiveProperty(entry, alignVal)) case "width": - widthVal := colPropString(col.Properties, "ColumnWidth", "autoFill") + widthVal := colPropEnum(entry, col.Properties, "ColumnWidth", "autoFill") properties = append(properties, buildColumnPrimitiveProperty(entry, widthVal)) case "minWidth": - properties = append(properties, buildColumnPrimitiveProperty(entry, "auto")) + minVal := colPropEnum(entry, col.Properties, "minWidth", "auto") + properties = append(properties, buildColumnPrimitiveProperty(entry, minVal)) case "size": sizeVal := colPropInt(col.Properties, "Size", "1") properties = append(properties, buildColumnPrimitiveProperty(entry, sizeVal)) case "hidable": - hidVal := colPropString(col.Properties, "Hidable", "yes") + hidVal := colPropEnum(entry, col.Properties, "Hidable", "yes") properties = append(properties, buildColumnPrimitiveProperty(entry, hidVal)) case "tooltip": @@ -190,6 +191,13 @@ func BuildDataGrid2Column(childSer ChildSerializer, col *backend.DataGridColumnS } default: + // A primitive the column schema declares and the script states + // under its own key (minWidthLimit, …) is written as stated, as + // CREATE PAGE's widget engine writes it (ako/mxcli#2718). + if v, ok := colPropPrimitive(entry, col.Properties, key); ok { + properties = append(properties, buildColumnPrimitiveProperty(entry, v)) + continue + } switch entry.ValueType { case "Expression": properties = append(properties, buildColumnExpressionProperty(entry, "")) @@ -434,6 +442,65 @@ func colPropString(props map[string]any, key string, defaultVal string) string { return defaultVal } +// colPropEnum reads an enumeration property: the declared key the value names, +// exactly or in another case, as the widget engine writes it (#854). The keys +// are compared exactly by the widget, so lowercasing the value wrote +// `autofit` for `autoFit` and the column fell back to auto-fill +// (ako/mxcli#2718). A value that names no key is written as given; without +// declared keys it is lowercased, the form every older key took. +func colPropEnum(entry pages.PropertyTypeIDEntry, props map[string]any, key, defaultVal string) string { + v, ok := lookupColProp(props, key) + sv, isStr := v.(string) + if !ok || !isStr || sv == "" { + return defaultVal + } + if len(entry.EnumerationKeys) == 0 { + return strings.ToLower(sv) + } + for _, k := range entry.EnumerationKeys { + if k == sv { + return k + } + } + for _, k := range entry.EnumerationKeys { + if strings.EqualFold(k, sv) { + return k + } + } + return sv +} + +// colPropPrimitive reads a property the switch in BuildDataGrid2Column has no +// case for, under its schema key: an enumeration through colPropEnum, a +// Boolean, Integer or String as its text. ok is false when the script does not +// state it or the kind is not a plain value. +func colPropPrimitive(entry pages.PropertyTypeIDEntry, props map[string]any, key string) (string, bool) { + v, ok := lookupColProp(props, key) + if !ok || v == nil { + return "", false + } + switch entry.ValueType { + case "Enumeration": + return colPropEnum(entry, props, key, entry.DefaultValue), true + case "Boolean", "Integer", "String": + return fmt.Sprint(v), true + } + return "", false +} + +// lookupColProp finds key in props, exactly or in another case. +func lookupColProp(props map[string]any, key string) (any, bool) { + if v, ok := props[key]; ok { + return v, true + } + for k, v := range props { + if strings.EqualFold(k, key) { + return v, true + } + } + return nil, false +} + func colPropInt(props map[string]any, key string, defaultVal string) string { if props == nil { return defaultVal diff --git a/mdl/backend/widgetobj/datagrid_column_enum_case_2718_test.go b/mdl/backend/widgetobj/datagrid_column_enum_case_2718_test.go new file mode 100644 index 0000000000..d0689f6d14 --- /dev/null +++ b/mdl/backend/widgetobj/datagrid_column_enum_case_2718_test.go @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: Apache-2.0 + +package widgetobj + +import ( + "strings" + "testing" + + "go.mongodb.org/mongo-driver/v2/bson" + + "github.com/mendixlabs/mxcli/mdl/backend" + "github.com/mendixlabs/mxcli/mdl/bsonutil" + "github.com/mendixlabs/mxcli/sdk/pages" +) + +// ako/mxcli#2718 (upstream mendixlabs/mxcli#1999): a column inserted with +// `alter page … insert` stored `ColumnWidth: autoFit` as `autofit`. The column +// builder lowercased every enumeration value, and Data Grid 2's keys are +// case-sensitive (autoFill, autoFit, manual): the client's width getter fell +// through to auto-fill. minWidth was hard-coded `auto`, so `minWidth: +// minContent` was dropped. CREATE PAGE goes through the widget engine and +// stored both as written. + +const ( + col2718Width = "00000000000000000000000000002718" + col2718MinWidth = "00000000000000000000000000002719" + col2718MinLimit = "00000000000000000000000000002720" + col2718Align = "00000000000000000000000000002721" +) + +func col2718PropertyIDs() map[string]pages.PropertyTypeIDEntry { + return map[string]pages.PropertyTypeIDEntry{ + "width": {PropertyTypeID: col2718Width, ValueTypeID: "00000000000000000000000000002800", ValueType: "Enumeration", DefaultValue: "autoFill", EnumerationKeys: []string{"autoFill", "autoFit", "manual"}}, + "minWidth": {PropertyTypeID: col2718MinWidth, ValueTypeID: "00000000000000000000000000002801", ValueType: "Enumeration", DefaultValue: "auto", EnumerationKeys: []string{"auto", "minContent", "manual"}}, + "minWidthLimit": {PropertyTypeID: col2718MinLimit, ValueTypeID: "00000000000000000000000000002802", ValueType: "Integer", DefaultValue: "100"}, + "alignment": {PropertyTypeID: col2718Align, ValueTypeID: "00000000000000000000000000002803", ValueType: "Enumeration", DefaultValue: "left", EnumerationKeys: []string{"left", "center", "right"}}, + } +} + +func primitiveAt(t *testing.T, col bson.D, typePointer string) string { + t.Helper() + for _, e := range col { + if e.Key != "Properties" { + continue + } + for _, p := range e.Value.(bson.A)[1:] { + pd := p.(bson.D) + var tp string + var val bson.D + for _, f := range pd { + switch f.Key { + case "TypePointer": + if b, ok := f.Value.(bson.Binary); ok { + tp = bsonutil.BsonBinaryToID(b) + } + case "Value": + val, _ = f.Value.(bson.D) + } + } + if strings.ReplaceAll(tp, "-", "") != typePointer { + continue + } + for _, f := range val { + if f.Key == "PrimitiveValue" { + s, _ := f.Value.(string) + return s + } + } + } + } + t.Fatalf("no property with type pointer %s", typePointer) + return "" +} + +func TestBuildDataGrid2Column_EnumerationKeysKeepTheirCase_2718(t *testing.T) { + for _, tc := range []struct { + props map[string]any + width, minWidth, limit, al string + }{ + {map[string]any{"ColumnWidth": "autoFit"}, "autoFit", "auto", "100", "left"}, + {map[string]any{"ColumnWidth": "autoFill"}, "autoFill", "auto", "100", "left"}, + // Another case names the declared key, as in the widget engine (#854). + {map[string]any{"ColumnWidth": "AUTOFIT", "Alignment": "Right"}, "autoFit", "auto", "100", "right"}, + {map[string]any{"ColumnWidth": "autoFit", "minWidth": "minContent"}, "autoFit", "minContent", "100", "left"}, + {map[string]any{"minWidth": "manual", "minWidthLimit": 120}, "autoFill", "manual", "120", "left"}, + // Control: unset keeps the defaults. + {nil, "autoFill", "auto", "100", "left"}, + } { + col := BuildDataGrid2Column(nil, &backend.DataGridColumnSpec{Properties: tc.props}, "", col2718PropertyIDs()) + if got := primitiveAt(t, col, col2718Width); got != tc.width { + t.Errorf("%v: width = %q, want %q", tc.props, got, tc.width) + } + if got := primitiveAt(t, col, col2718MinWidth); got != tc.minWidth { + t.Errorf("%v: minWidth = %q, want %q", tc.props, got, tc.minWidth) + } + if got := primitiveAt(t, col, col2718MinLimit); got != tc.limit { + t.Errorf("%v: minWidthLimit = %q, want %q", tc.props, got, tc.limit) + } + if got := primitiveAt(t, col, col2718Align); got != tc.al { + t.Errorf("%v: alignment = %q, want %q", tc.props, got, tc.al) + } + } +} diff --git a/mdl/executor/check_gap_mappings_snippets_test.go b/mdl/executor/check_gap_mappings_snippets_test.go index b853ad0c18..7b1f7e6f13 100644 --- a/mdl/executor/check_gap_mappings_snippets_test.go +++ b/mdl/executor/check_gap_mappings_snippets_test.go @@ -48,33 +48,31 @@ create export mapping MB.EM with json structure MB.J { MB.E { v = V } }; ` } -// f75 f77: the value's JSON type and the attribute's type must match exactly — -// CE5015 "The mapping does not align with the underlying schema anymore." +// f75 f77, re-measured for ako/mxcli#2714 on 11.12.6: a value builds when its +// JSON type and the attribute's align, or the mapping converts in a direction +// mxbuild allows; otherwise CE6099 (import) or CE0227 (export). func TestMappingValueTypes(t *testing.T) { rejected := []struct{ name, src string }{ {"import string to integer", importMappingSrc(`"three"`, "Integer")}, {"import string to long", importMappingSrc(`"x"`, "Long")}, {"import string to decimal", importMappingSrc(`"x"`, "Decimal")}, {"import string to boolean", importMappingSrc(`"yes"`, "Boolean")}, - {"import integer to string", importMappingSrc(`5`, "String(20)")}, - {"import integer to decimal", importMappingSrc(`5`, "Decimal")}, {"import decimal to integer", importMappingSrc(`5.5`, "Integer")}, {"import decimal to long", importMappingSrc(`5.5`, "Long")}, - {"import decimal to string", importMappingSrc(`5.5`, "String(20)")}, - {"import boolean to string", importMappingSrc(`true`, "String(20)")}, {"import boolean to integer", importMappingSrc(`true`, "Integer")}, {"export integer to string value", exportMappingSrc(`"x"`, "Integer")}, - {"export string to integer value", exportMappingSrc(`5`, "String(20)")}, {"export decimal to integer value", exportMappingSrc(`5`, "Decimal")}, - {"export integer to decimal value", exportMappingSrc(`5.5`, "Integer")}, {"export boolean to string value", exportMappingSrc(`"x"`, "Boolean")}, - {"export string to boolean value", exportMappingSrc(`true`, "String(20)")}, } for _, c := range rejected { t.Run(c.name, func(t *testing.T) { got := mbViolations(t, c.src, "MDL127") - if len(got) != 1 || !strings.Contains(got[0], "CE5015") { - t.Errorf("want one MDL127 naming CE5015, got %q", got) + code := "CE6099" + if strings.HasPrefix(c.name, "export") { + code = "CE0227" + } + if len(got) != 1 || !strings.Contains(got[0], code) { + t.Errorf("want one MDL127 naming %s, got %q", code, got) } }) } @@ -92,6 +90,17 @@ func TestMappingValueTypes(t *testing.T) { {"export string", exportMappingSrc(`"x"`, "String(20)")}, {"export enumeration", exportMappingSrc(`"Red"`, "enumeration(MB.Color)")}, {"export boolean", exportMappingSrc(`true`, "Boolean")}, + // The conversions mxbuild allows once the writer stores the member's + // type for them (ako/mxcli#2714): into a String attribute and integer + // into Decimal on import; out of a String attribute, and Integer into + // a decimal, on export. + {"import integer to string", importMappingSrc(`5`, "String(20)")}, + {"import integer to decimal", importMappingSrc(`5`, "Decimal")}, + {"import decimal to string", importMappingSrc(`5.5`, "String(20)")}, + {"import boolean to string", importMappingSrc(`true`, "String(20)")}, + {"export string to integer value", exportMappingSrc(`5`, "String(20)")}, + {"export integer to decimal value", exportMappingSrc(`5.5`, "Integer")}, + {"export string to boolean value", exportMappingSrc(`true`, "String(20)")}, } for _, c := range accepted { t.Run(c.name, func(t *testing.T) { diff --git a/mdl/executor/cmd_alter_flow.go b/mdl/executor/cmd_alter_flow.go index 3c26a98770..f9c3f37ccb 100644 --- a/mdl/executor/cmd_alter_flow.go +++ b/mdl/executor/cmd_alter_flow.go @@ -1661,7 +1661,7 @@ func (a *alterFlowContext) upstreamOf(id model.ID, including bool) map[model.ID] // inserted there and dropped here, and its readers read the inserted one. func (a *alterFlowContext) checkOutputUnused(target mfmutator.Candidate, replacement *backend.MicroflowFragment) error { v := target.OutputVariable - if v == "" || fragmentDeclares(replacement, v) { + if v == "" || fragmentDeclares(replacement, v) || a.isParameter(v) { return nil } var readers []string @@ -1693,6 +1693,21 @@ func (a *alterFlowContext) checkOutputUnused(target mfmutator.Candidate, replace return nil } +// isParameter reports whether the flow the statement writes has a parameter +// named v. A `create or modify` that turns a local variable into a parameter +// of the same name drops the producer while its readers read the parameter; +// counting them as left without their variable refused the change +// (ako/mxcli#2726). a.mf carries the declared parameters once the header +// changes (planFlowModify). +func (a *alterFlowContext) isParameter(v string) bool { + for _, p := range a.mf.Parameters { + if p != nil && p.Name == v { + return true + } + } + return false +} + // checkDeclaredUnclashed refuses a fragment that declares a variable a stored // activity also declares, unless the statement takes that activity away. It // runs once every operation is applied, like checkOutputUnused: a producer diff --git a/mdl/executor/cmd_export_mappings.go b/mdl/executor/cmd_export_mappings.go index e0e7088e52..bd4d682beb 100644 --- a/mdl/executor/cmd_export_mappings.go +++ b/mdl/executor/cmd_export_mappings.go @@ -810,7 +810,7 @@ func buildExportMappingElementModel(moduleName string, def *ast.ExportMappingEle // Value mapping — bind to attribute elem.Kind = "Value" elem.TypeName = "ExportMappings$ValueMappingElement" - elem.DataType = resolveAttributeType(parentEntity, def.Attribute, b) + elem.DataType = mappingValueDataType(jsElem, parentEntity, def.Attribute, b) // See the import twin: the value may pass through a microflow (#266). if err := setMappingConverter(&elem.Converter, def.Converter, moduleName, b); err != nil { return nil, err diff --git a/mdl/executor/cmd_import_mappings.go b/mdl/executor/cmd_import_mappings.go index 8c8e9b687c..2a480d543a 100644 --- a/mdl/executor/cmd_import_mappings.go +++ b/mdl/executor/cmd_import_mappings.go @@ -854,7 +854,7 @@ func buildImportMappingElementModel(moduleName string, def *ast.ImportMappingEle // Value mapping — bind to attribute elem.Kind = "Value" elem.TypeName = "ImportMappings$ValueMappingElement" - elem.DataType = resolveAttributeType(parentEntity, def.Attribute, b) + elem.DataType = mappingValueDataType(jsElem, parentEntity, def.Attribute, b) elem.IsKey = def.IsKey // The value may pass through a microflow on its way to the attribute // (#266). The stored element carries only the microflow — its input is @@ -1056,6 +1056,57 @@ func (i *jsonSchemaIndex) memberNames(parentPath string) []string { return out } +// mappingValueDataType is the type a value mapping element stores. mxbuild +// compares it twice: with the schema member's type (CE5015 when they do not +// align) and with the bound attribute's (CE6099 on import, CE0227 on export). +// The attribute's type was always stored, so every pairing that converts — a +// JSON integer into a String attribute, a decimal into a String — failed the +// first comparison (ako/mxcli#2714). Measured on 11.12.6 over every member × +// attribute pairing, import and export: +// +// - where the member's type takes the attribute's as it is (an integer into +// Integer or Long, a string into String, Enumeration or DateTime, …), the +// attribute's type is stored, as before; a String member bound to a +// DateTime attribute needs it, the member's type there is CE6099/CE0227; +// - otherwise the member's type is stored, and the conversions mxbuild +// allows build: anything into a String attribute, and an integer into a +// Decimal on import; a String attribute into any member, and an Integer +// or Long into a decimal on export (mappingValueAccepted). +// +// The attribute's type is also the fallback when the member's type is not +// known: no structure, or a member whose sample was null. +func mappingValueDataType(member *types.JsonElement, entityQN, attrName string, b backend.DomainModelBackend) string { + attr := resolveAttributeType(entityQN, attrName, b) + if member == nil { + return attr + } + switch member.PrimitiveType { + case "String", "Integer", "Decimal", "Boolean", "DateTime": + default: + return attr + } + if mappingTypesAlign(member.PrimitiveType, attr) { + return attr + } + return member.PrimitiveType +} + +// mappingTypesAlign reports whether a value element of the attribute's type +// aligns with a schema member of type member — the pairings that store the +// attribute's type. +func mappingTypesAlign(member, attr string) bool { + if member == attr { + return true + } + switch member { + case "Integer": + return attr == "Long" || attr == "AutoNumber" + case "String": + return attr == "Enumeration" || attr == "DateTime" + } + return false +} + // resolveAttributeType looks up the data type of an entity attribute from the project. // Returns "String" as default if the attribute cannot be found. func resolveAttributeType(entityQN, attrName string, b backend.DomainModelBackend) string { diff --git a/mdl/executor/cmd_search.go b/mdl/executor/cmd_search.go index 252dc124a3..22fb84cb42 100644 --- a/mdl/executor/cmd_search.go +++ b/mdl/executor/cmd_search.go @@ -250,6 +250,14 @@ func showReferences(ctx *ExecContext, typed string) error { if viaValues { cols, order = cols+", TargetName as Target", order+", Target" } + // A module can hold a microflow and a snippet of one name; without the + // target's type, a menu item calling the microflow read as a use of the + // snippet (ako/mxcli#2730). Shown only when the name names more than one + // kind, so an ordinary listing is unchanged. + if kinds, err := ctx.Catalog.Query(`select count(distinct TargetType) as N from refs where ` + where); err == nil && + len(kinds.Rows) == 1 && len(kinds.Rows[0]) == 1 && fmt.Sprint(kinds.Rows[0][0]) != "1" && fmt.Sprint(kinds.Rows[0][0]) != "0" { + cols, order = cols+", TargetType", order+", TargetType" + } query := `select distinct ` + cols + ` from refs where ` + where + ` order by ` + order result, err := ctx.Catalog.Query(query) diff --git a/mdl/executor/flow_modify_local_to_parameter_2726_test.go b/mdl/executor/flow_modify_local_to_parameter_2726_test.go new file mode 100644 index 0000000000..19413f3251 --- /dev/null +++ b/mdl/executor/flow_modify_local_to_parameter_2726_test.go @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "bytes" + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/visitor" +) + +// ako/mxcli#2726 (upstream mendixlabs/mxcli#2002): moving a local list to the +// caller — a parameter $SaleList of the list's type, and the `create list` +// that declared it removed — was refused by `create or modify microflow` +// (MDL-V1-REBUILD): "drop $SaleList: $SaleList is still used by: add $NewSale +// to $SaleList". The splice counted the stored producer's readers without +// seeing that the flow it writes has a parameter of that name, which is what +// those readers read. Any other parameter name spliced. +// runV1 executes src as a program, so its `mdl 1;` header applies: under mdl 0 +// a refused splice falls back to rebuilding the flow and nothing is refused. +func runV1(t *testing.T, exec *Executor, src string) error { + t.Helper() + prog, errs := visitor.Build(src) + if len(errs) > 0 { + t.Fatalf("parse: %v", errs[0]) + } + return exec.ExecuteProgram(prog) +} + +func TestCreateOrModify_LocalVariableBecomesAParameter_2726(t *testing.T) { + exec, _ := openPedAppFixture(t) + if err := runV1(t, exec, `mdl 1; +create persistent entity FeedbackModule.Sale2726 (Code: String(200)); +create microflow FeedbackModule.Sale2726_Create () +begin + $SaleList = create list of FeedbackModule.Sale2726; + $NewSale = create FeedbackModule.Sale2726 (Code = 'A'); + add $NewSale to $SaleList; + commit $SaleList; +end;`); err != nil { + t.Fatalf("setup: %v", err) + } + if err := runV1(t, exec, `mdl 1; +create or modify microflow FeedbackModule.Sale2726_Create ( + $SaleList: List of FeedbackModule.Sale2726 +) +begin + $NewSale = create FeedbackModule.Sale2726 (Code = 'A'); + add $NewSale to $SaleList; +end;`); err != nil { + t.Fatalf("the local list moved to a parameter of the same name was refused: %v", err) + } + var buf bytes.Buffer + exec.output = &buf + if err := afRun(t, exec, "describe microflow FeedbackModule.Sale2726_Create;"); err != nil { + t.Fatal(err) + } + out := buf.String() + if !strings.Contains(out, "$SaleList: List of FeedbackModule.Sale2726") || strings.Contains(out, "create list") { + t.Errorf("the stored flow is not the declared one:\n%s", out) + } + + // Control: renaming the parameter leaves the reader with no $SaleList, + // and that is still refused. + if err := runV1(t, exec, `mdl 1; +create or modify microflow FeedbackModule.Sale2726_Create ( + $Other: List of FeedbackModule.Sale2726 +) +begin + $NewSale = create FeedbackModule.Sale2726 (Code = 'A'); + add $NewSale to $SaleList; +end;`); err == nil { + t.Error("a reader left without its variable was accepted") + } +} diff --git a/mdl/executor/mapping_fixture_roundtrip_test.go b/mdl/executor/mapping_fixture_roundtrip_test.go index a2ad76e982..88c8fc4701 100644 --- a/mdl/executor/mapping_fixture_roundtrip_test.go +++ b/mdl/executor/mapping_fixture_roundtrip_test.go @@ -59,20 +59,6 @@ var knownLossy = map[string]string{ // accepted — #260 item 1. // #268's wrapper and #261's backup are fixed here; the residue is the export // writer's property set — #277 (IsKey), #279 (MinOccurs). - // #267 is fixed for this one — its `root chunks` clause round-trips — but it - // carries two shapes that have never parsed: an object element with an - // entity and NO association (DESCRIBE prints `./Entity`) and an entity-less - // import container (`= metadata`). Both are #260 describe-only spellings. - // #260's shapes are fixed here — the association-less object element and the - // two-level import array both round-trip now. What is left is ONE value - // element's data type: the document stores DataTypes$IntegerType for - // GenAICommons.KnowledgeBaseChunk.Similarity, and mxcli resolves the - // ATTRIBUTE, which is Decimal. Studio Pro appears to store the SCHEMA - // element's type, but this structure records no type for `similarity`, so - // the rule cannot be established from this document alone — and changing - // resolveAttributeType globally on one marketplace element would risk - // CE5015 ("attribute type does not match schema type") the other way. - "MxGenAIConnector.IM_Collection_RetrieveNearestNeighbors": "value element data type: stored Integer, attribute is Decimal", // Not constructs: the property SET a rebuild writes (#279). #266's converter // and #261's backup are fixed on both of these — what remains is diff --git a/mdl/executor/mapping_value_type_2714_test.go b/mdl/executor/mapping_value_type_2714_test.go new file mode 100644 index 0000000000..11badc4a92 --- /dev/null +++ b/mdl/executor/mapping_value_type_2714_test.go @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "testing" + + "github.com/mendixlabs/mxcli/mdl/backend/mock" + "github.com/mendixlabs/mxcli/mdl/types" + "github.com/mendixlabs/mxcli/model" + "github.com/mendixlabs/mxcli/sdk/domainmodel" +) + +// ako/mxcli#2714 (upstream mendixlabs/mxcli#2001): a mapping value element +// stored the bound attribute's type, so a JSON integer bound to a String +// attribute — a conversion the mapping performs — was stored String against +// its Integer member and mxbuild reported CE5015. Measured on 11.12.6 over +// every member × attribute pairing: an element stores the attribute's type +// where that aligns with the member (a string into DateTime needs it), and +// the member's type otherwise. +func TestMappingValueDataType_2714(t *testing.T) { + b := &mock.MockBackend{ + IsConnectedFunc: func() bool { return true }, + GetModuleByNameFunc: func(name string) (*model.Module, error) { + return &model.Module{BaseElement: model.BaseElement{ID: "m"}, Name: name}, nil + }, + GetDomainModelFunc: func(model.ID) (*domainmodel.DomainModel, error) { + return &domainmodel.DomainModel{Entities: []*domainmodel.Entity{{ + Name: "Sale", + Attributes: []*domainmodel.Attribute{ + {Name: "Text", Type: &domainmodel.StringAttributeType{Length: 200}}, + {Name: "Num", Type: &domainmodel.IntegerAttributeType{}}, + {Name: "Big", Type: &domainmodel.LongAttributeType{}}, + {Name: "Amount", Type: &domainmodel.DecimalAttributeType{}}, + {Name: "When", Type: &domainmodel.DateTimeAttributeType{}}, + }, + }}}, nil + }, + } + member := func(prim string) *types.JsonElement { + return &types.JsonElement{ElementType: "Value", PrimitiveType: prim} + } + for _, tc := range []struct { + member *types.JsonElement + attr string + want string + }{ + {member("Integer"), "Text", "Integer"}, // the reported case: the member's type + {member("Decimal"), "Text", "Decimal"}, // the same, a decimal + {member("String"), "Num", "String"}, // unconvertible either way; the schema's type at least aligns + {member("Integer"), "Amount", "Integer"}, // integer into Decimal + {member("Integer"), "Num", "Integer"}, // aligned: unchanged + {member("Integer"), "Big", "Long"}, // aligned: the attribute's, as before + {member("String"), "When", "DateTime"}, // aligned: a JSON date is a string; the member's type would be CE6099 + {member("Unknown"), "Text", "String"}, // member type unknown: the attribute's + {nil, "Num", "Integer"}, // no structure: the attribute's + } { + prim := "" + if tc.member != nil { + prim = tc.member.PrimitiveType + } + if got := mappingValueDataType(tc.member, "M.Sale", tc.attr, b); got != tc.want { + t.Errorf("member %s → %s: stored %q, want %q", prim, tc.attr, got, tc.want) + } + } +} diff --git a/mdl/executor/show_references_same_name_2730_test.go b/mdl/executor/show_references_same_name_2730_test.go new file mode 100644 index 0000000000..b745e6bcc7 --- /dev/null +++ b/mdl/executor/show_references_same_name_2730_test.go @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/catalog" +) + +// ako/mxcli#2730: `show references to Lib.Overview`, where Lib holds a +// microflow and a snippet of that name, listed the menu item calling the +// microflow beside the page placing the snippet with nothing to tell them +// apart, which reads as both using one document. When the name names more +// than one kind of document, each row says which one it refers to. +func TestShowReferences_NameOfTwoDocumentKinds_2730(t *testing.T) { + run := func(seed string) string { + cat, err := catalog.New() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { cat.Close() }) + if _, err := cat.CatalogDB().Exec(seed); err != nil { + t.Fatal(err) + } + ctx, _ := newMockCtx(t) + ctx.Catalog = cat + if err := showReferences(ctx, "Lib.Overview"); err != nil { + t.Fatal(err) + } + return ctx.Output.(interface{ String() string }).String() + } + out := run(`INSERT INTO refs (SourceType, SourceId, SourceName, TargetType, TargetId, TargetName, RefKind, ProjectId, SnapshotId) VALUES + ('NAVIGATION', '', 'Navigation.Responsive', 'MICROFLOW', '', 'Lib.Overview', 'menu_item', 'p', 's'), + ('PAGE', '', 'App.OverviewForm', 'SNIPPET', '', 'Lib.Overview', 'snippet_call', 'p', 's')`) + for _, row := range []string{"menu_item", "snippet_call"} { + var line string + for _, l := range strings.Split(out, "\n") { + if strings.Contains(l, row) { + line = l + } + } + want := map[string]string{"menu_item": "MICROFLOW", "snippet_call": "SNIPPET"}[row] + if !strings.Contains(line, want) { + t.Errorf("the %s row does not say it refers to the %s:\n%s", row, want, out) + } + } + + // Control: one kind of document, and the output is as it was. + out = run(`INSERT INTO refs (SourceType, SourceId, SourceName, TargetType, TargetId, TargetName, RefKind, ProjectId, SnapshotId) VALUES + ('NAVIGATION', '', 'Navigation.Responsive', 'MICROFLOW', '', 'Lib.Overview', 'menu_item', 'p', 's'), + ('PAGE', '', 'App.Button', 'MICROFLOW', '', 'Lib.Overview', 'action', 'p', 's')`) + if strings.Contains(out, "TargetType") { + t.Errorf("a name of one document kind gained a TargetType column:\n%s", out) + } +} diff --git a/mdl/executor/validate_alter_insert_column_schema_2718_test.go b/mdl/executor/validate_alter_insert_column_schema_2718_test.go new file mode 100644 index 0000000000..518780b511 --- /dev/null +++ b/mdl/executor/validate_alter_insert_column_schema_2718_test.go @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/visitor" +) + +// ako/mxcli#2718: a column inserted next to a Data grid 2 column was judged +// as a widget with no parent, so `minWidth` — a key the column schema +// declares, and CREATE PAGE accepts — drew MDL-WIDGET07 "will be silently +// dropped on write". An insert addressed `grid column(…)` places Data grid 2 +// columns, and is judged by that column schema. +func TestCheckAlterInsertColumn_UsesTheColumnSchema_2718(t *testing.T) { + src := `alter page M.P { + insert after dgSales column(Code) { + column (Attribute: Quantity, Caption: 'Quantity', ColumnWidth: autoFit, minWidth: minContent, bogusKey: 1) + }; +};` + prog, errs := visitor.Build(src) + if len(errs) > 0 { + t.Fatalf("parse: %v", errs) + } + var msgs []string + for _, v := range validateWidgetPropertiesOf(prog.Statements[0], LoadWidgetRegistry("")) { + msgs = append(msgs, v.Message) + } + all := strings.Join(msgs, "\n") + if strings.Contains(all, "`minWidth`") { + t.Errorf("minWidth, a declared column key, was reported:\n%s", all) + } + // Control: a key the column schema does not declare is still reported. + if !strings.Contains(all, "`bogusKey`") { + t.Errorf("an undeclared column key was not reported:\n%s", all) + } +} diff --git a/mdl/executor/validate_mapping_snippet_gaps.go b/mdl/executor/validate_mapping_snippet_gaps.go index b080c1c8f6..72f3ce1eb3 100644 --- a/mdl/executor/validate_mapping_snippet_gaps.go +++ b/mdl/executor/validate_mapping_snippet_gaps.go @@ -21,15 +21,22 @@ const ( // --------------------------------------------------------------------------- // MDL127 — a mapping value the build rejects. // -// Measured on MxBuild 11.16.1, one mapping per project, one value `v` against -// one attribute `V`, import and export alike. The JSON value's type and the -// attribute's must match exactly; every other pairing is CE5015 "The mapping -// does not align with the underlying schema anymore.": +// Measured on MxBuild 11.12.6 over every JSON member type × attribute type, +// import and export, once the writer stored the member's type for a pairing +// that converts (ako/mxcli#2714; the first table here, "must match exactly", +// was measured while the writer stored the attribute's type, which made every +// conversion CE5015). A pairing builds when the types align — // // JSON integer Integer, Long -// JSON decimal Decimal (an integer does NOT widen into it) +// JSON decimal Decimal // JSON boolean Boolean // JSON string String, Enumeration, DateTime +// JSON date DateTime +// +// — or when the mapping converts in a direction mxbuild allows: on import any +// member into a String attribute, and an integer into a Decimal; on export a +// String attribute into any member, and an Integer or Long into a decimal. +// Every other pairing fails, CE6099 on import and CE0227 on export. // // A value naming an attribute the entity does not have is CE1613 "The selected // attribute 'Sp.E.Nope' no longer exists." (f76, and the export twin). @@ -133,24 +140,26 @@ func (r *mappingAttrResolver) attr(entity, name string) mappingAttr { } // mappingValueAccepted is the measured table: may a JSON value of type json meet -// an attribute of type attr. ok is false where either side was not measured. -func mappingValueAccepted(json, attr string) (accepted, ok bool) { +// an attribute of type attr, on import or (export) on export. ok is false where +// either side was not measured. +func mappingValueAccepted(json, attr string, export bool) (accepted, ok bool) { switch attr { case "String", "Integer", "Long", "Decimal", "Boolean", "DateTime", "Enumeration": default: return false, false } switch json { - case "Integer": - return attr == "Integer" || attr == "Long", true - case "Decimal": - return attr == "Decimal", true - case "Boolean": - return attr == "Boolean", true - case "String": - return attr == "String" || attr == "Enumeration" || attr == "DateTime", true + case "Integer", "Decimal", "Boolean", "String", "DateTime": + default: + return false, false } - return false, false + if mappingTypesAlign(json, attr) || attr == "String" { + return true, true + } + if export { + return json == "Decimal" && (attr == "Integer" || attr == "Long"), true + } + return json == "Integer" && attr == "Decimal", true } func ValidateMappingValues(prog *ast.Program, open func() backend.FullBackend) []linter.Violation { @@ -196,16 +205,20 @@ func ValidateMappingValues(prog *ast.Program, open func() backend.FullBackend) [ return } json := memberPrimitiveType(elems, member) - accepted, judged := mappingValueAccepted(json, a.kind) + export := kind == "export mapping" + accepted, judged := mappingValueAccepted(json, a.kind, export) if !judged || accepted { return } + code, converts := "CE6099", "An import mapping converts any value into a String attribute, and an integer into a Decimal" + if export { + code, converts = "CE0227", "An export mapping converts a String attribute into any member, and an Integer or Long into a decimal" + } out = append(out, linter.Violation{RuleID: mappingValueRule, Severity: linter.SeverityError, Location: loc, - Message: fmt.Sprintf("%s %s maps the JSON %s value %s to %s.%s, %s — the two types must match exactly "+ - "(a JSON integer meets Integer or Long, a decimal Decimal, a boolean Boolean, a string String, "+ - "Enumeration or DateTime); mxbuild reports CE5015 \"The mapping does not align with the underlying schema anymore.\"", - kind, mapping, strings.ToLower(json), member, entity, attr, withAn(a.kind)), - Suggestion: "Give the attribute the JSON value's type, or convert it in a microflow (`attr = Module.Convert(json)`)."}) + Message: fmt.Sprintf("%s %s maps the JSON %s value %s to %s.%s, %s — mxbuild reports %s, the attribute's type "+ + "not being compatible with the schema's. %s; otherwise the types must match.", + kind, mapping, strings.ToLower(json), member, entity, attr, withAn(a.kind), code, converts), + Suggestion: "Give the attribute a type the JSON value converts to, or convert it in a microflow (`attr = Module.Convert(json)`)."}) } for _, stmt := range prog.Statements { switch m := stmt.(type) { diff --git a/mdl/executor/validate_widgets.go b/mdl/executor/validate_widgets.go index 2acdd6803a..abdc605f42 100644 --- a/mdl/executor/validate_widgets.go +++ b/mdl/executor/validate_widgets.go @@ -175,9 +175,9 @@ func validateWidgetPropertiesOf(stmt ast.Statement, registry *WidgetRegistry) [] for _, op := range s.Operations { switch o := op.(type) { case *ast.InsertWidgetOp: - out = append(out, validateWidgetSubtree(o.Widgets, registry, "alter "+s.PageName.String())...) + out = append(out, validateAlterFragment(o.Widgets, o.Target, registry, "alter "+s.PageName.String())...) case *ast.ReplaceWidgetOp: - out = append(out, validateWidgetSubtree(o.NewWidgets, registry, "alter "+s.PageName.String())...) + out = append(out, validateAlterFragment(o.NewWidgets, o.Target, registry, "alter "+s.PageName.String())...) case *ast.SetPropertyOp: out = append(out, validateAlterSetLegacyExpressionText(o, "alter "+s.PageName.String())...) out = append(out, validateAlterSetColumnVisibleScope(o, "alter "+s.PageName.String())...) @@ -220,6 +220,22 @@ func validateDocumentWidgetTree(widgets []*ast.WidgetV3, registry *WidgetRegistr // into a page this pass never sees — ALTER PAGE's INSERT and REPLACE. What // encloses them is unknown, so rules that depend on the enclosing context stand // down rather than guess. +// validateAlterFragment validates the widgets an INSERT or REPLACE places. A +// fragment addressed `grid column(…)` is Data grid 2 columns, so its columns +// are judged by the column schema, as they are inside the grid in CREATE PAGE; +// judged with no parent, a declared key such as minWidth was reported as +// dropped (ako/mxcli#2718). +func validateAlterFragment(widgets []*ast.WidgetV3, target ast.WidgetRef, registry *WidgetRegistry, locationPrefix string) []linter.Violation { + if !target.IsColumnAddress() { + return validateWidgetSubtree(widgets, registry, locationPrefix) + } + // With a project the grid has a definition, and its columns are its + // object-list items, judged by the item schema (as validateWidgetTreeIn + // passes a widget's own children); without one, by the embedded schema. + grid := &ast.WidgetV3{Type: "datagrid", Name: target.Widget} + return validateWidgetTreeIn(widgets, registry, locationPrefix, objectListMappingSet(lookupWidgetDef(grid, registry)), grid, nil, pageArgContext{}) +} + func validateWidgetSubtree(widgets []*ast.WidgetV3, registry *WidgetRegistry, locationPrefix string) []linter.Violation { return validateWidgetTreeIn(widgets, registry, locationPrefix, nil, nil, nil, pageArgContext{}) } diff --git a/mdl/linter/rules/reachable_page_read_access.go b/mdl/linter/rules/reachable_page_read_access.go index 8a7ff4b4a8..b7a8301e15 100644 --- a/mdl/linter/rules/reachable_page_read_access.go +++ b/mdl/linter/rules/reachable_page_read_access.go @@ -75,23 +75,51 @@ func (r *ReachablePageReadAccessRule) RequiredCatalogMode() linter.CatalogMode { type reachEdge struct{ kind, targetType, target string } +// A node of the walk is a document's kind and name (node). A Marketplace +// module can hold a microflow and a snippet of the same name, and keyed by +// name alone the two were one node: a menu item calling the microflow reached +// the snippet, without the execute check, and the walk followed both +// documents' references (ako/mxcli#2730). +const ( + nodePage = "PAGE" + nodeSnippet = "SNIPPET" + nodeMicroflow = "MICROFLOW" + nodeNanoflow = "NANOFLOW" +) + +func node(kind, name string) string { return kind + "\x00" + name } + +// nodeName is the qualified name of a node. +func nodeName(n string) string { + _, name, _ := strings.Cut(n, "\x00") + return name +} + +// nodeKind is the kind of a node. +func nodeKind(n string) string { + kind, _, _ := strings.Cut(n, "\x00") + return kind +} + // reachModel is the project as the walk needs it. type reachModel struct { - edges map[string][]reachEdge // source document -> refs out of it + edges map[string][]reachEdge // source node -> refs out of it snippets map[string]bool // qualified names of snippets - module map[string]string // page/snippet -> module + pages map[string]bool // qualified names of pages + nanoflows map[string]bool // qualified names of nanoflows + module map[string]string // page/snippet node -> module market map[string]bool // module -> is a Marketplace module views map[string]map[string]bool // page -> module roles that may view it - executes map[string]map[string]bool // microflow/nanoflow -> module roles that may execute it + executes map[string]map[string]bool // microflow/nanoflow node -> module roles that may execute it gen map[string]string // entity -> generalization reads map[string]map[string]bool // entity -> module roles with a READ rule members map[string]map[string]bool // entity+"\x00"+member -> module roles reading it listed map[string]map[string]bool // entity -> module roles whose rule lists members defaultRO map[string]map[string]bool // entity -> module roles whose rule's default reads - entries []string // menu pages and microflows - profileHomes map[string]string // navigation profile -> its home page - roleHomes map[string]map[string][]string // profile -> user role -> role-based home pages/microflows - ids map[string]string // page/snippet -> unit id + entries []string // menu page and flow nodes + profileHomes map[string]string // navigation profile -> its home node + roleHomes map[string]map[string][]string // profile -> user role -> role-based home nodes + ids map[string]string // page/snippet node -> unit id } // Check reports, per page or snippet a user role reaches, each attribute or @@ -183,27 +211,28 @@ func (r *ReachablePageReadAccessRule) Check(ctx *linter.LintContext) []linter.Vi f := found[k] sort.Strings(f.roles) kind := "page" - if m.snippets[f.doc] { + if nodeKind(f.doc) == nodeSnippet { kind = "snippet" } + docName := nodeName(f.doc) v := linter.Violation{ RuleID: r.ID(), Severity: r.DefaultSeverity(), Location: linter.Location{ Module: m.module[f.doc], DocumentType: kind, - DocumentName: docNameFromQualified(f.doc), + DocumentName: docNameFromQualified(docName), }, } who := fmt.Sprintf("user role%s %s", plural(f.roles), quoteList(f.roles)) if f.member == "" { v.Message = fmt.Sprintf("%s %s lists %s, which %s can reach but may not read at all — mxbuild reports CE2729 \"No access to entity '%s'\"", - kind, f.doc, f.entity, who, f.entity) + kind, docName, f.entity, who, f.entity) v.Suggestion = fmt.Sprintf("GRANT READ on %s to a module role those user roles hold, or keep the page out of their reach", f.entity) } else { attr := f.member[strings.LastIndex(f.member, ".")+1:] v.Message = fmt.Sprintf("%s %s shows %s, which %s can reach but may not read on %s — mxbuild reports CE2729 \"No read access to attribute '%s' in entity '%s'\"", - kind, f.doc, f.member, who, f.entity, attr, f.entity) + kind, docName, f.member, who, f.entity, attr, f.entity) v.Suggestion = fmt.Sprintf("Add %s to the READ member list of %s's access rule for a module role those user roles hold (repeat that rule's XPath so the grant merges into it), or keep the page out of their reach", attr, f.entity) } @@ -241,12 +270,13 @@ func (m *reachModel) reach(userRole string, roles map[string]bool) []string { if seen[n] { continue } - page := m.module[n] != "" && !m.snippets[n] + page := nodeKind(n) == nodePage + flow := nodeKind(n) == nodeMicroflow || nodeKind(n) == nodeNanoflow viewable := page && reachAny(m.views[n], held) switch { case page && !viewable && !it.home: continue // a page the role may not view is not reached - case m.module[n] == "" && it.entry && !reachAny(m.executes[n], held): + case flow && it.entry && !reachAny(m.executes[n], held): continue // an entry microflow the role may not execute } seen[n] = true @@ -260,19 +290,21 @@ func (m *reachModel) reach(userRole string, roles map[string]bool) []string { switch { case e.kind == "show_page" && e.targetType == "PAGE", e.kind == "snippet_call" && e.targetType == "SNIPPET": - queue = append(queue, item{name: e.target}) + queue = append(queue, item{name: node(e.targetType, e.target)}) case (e.kind == "action" || e.kind == "datasource") && (e.targetType == "MICROFLOW" || e.targetType == "NANOFLOW"): - if reachAny(m.executes[e.target], held) { - queue = append(queue, item{name: e.target}) + target := node(e.targetType, e.target) + if reachAny(m.executes[target], held) { + queue = append(queue, item{name: target}) } case e.kind == "call" && (e.targetType == "MICROFLOW" || e.targetType == "NANOFLOW"): // A sub-microflow runs whatever its own allowed roles say // (measured). A microflow called from a nanoflow is a call from // the client, which needs execute rights. - if e.targetType == "MICROFLOW" && isNanoflow(m, n) && !reachAny(m.executes[e.target], held) { + target := node(e.targetType, e.target) + if e.targetType == "MICROFLOW" && nodeKind(n) == nodeNanoflow && !reachAny(m.executes[target], held) { continue } - queue = append(queue, item{name: e.target}) + queue = append(queue, item{name: target}) } } } @@ -294,8 +326,6 @@ func (m *reachModel) homesFor(userRole string) []string { return out } -func isNanoflow(m *reachModel, n string) bool { return m.executes[n]["\x00nanoflow"] } - func keys(m map[string]bool) []string { out := make([]string, 0, len(m)) for k := range m { @@ -396,6 +426,7 @@ func loadReachModel(ctx *linter.LintContext) *reachModel { m := &reachModel{ edges: map[string][]reachEdge{}, snippets: map[string]bool{}, module: map[string]string{}, market: map[string]bool{}, views: map[string]map[string]bool{}, executes: map[string]map[string]bool{}, + pages: map[string]bool{}, nanoflows: map[string]bool{}, gen: map[string]string{}, reads: map[string]map[string]bool{}, members: map[string]map[string]bool{}, listed: map[string]map[string]bool{}, defaultRO: map[string]map[string]bool{}, roleHomes: map[string]map[string][]string{}, profileHomes: map[string]string{}, ids: map[string]string{}, @@ -427,58 +458,70 @@ func loadReachModel(ctx *linter.LintContext) *reachModel { } query(`SELECT Name, COALESCE(Source, '') FROM modules`, func(c []string) { m.market[c[0]] = c[1] != "" }) query(`SELECT QualifiedName, ModuleName, Id FROM pages`, func(c []string) { - m.module[c[0]] = c[1] - m.ids[c[0]] = c[2] - if m.views[c[0]] == nil { - m.views[c[0]] = map[string]bool{} + n := node(nodePage, c[0]) + m.pages[c[0]] = true + m.module[n] = c[1] + m.ids[n] = c[2] + if m.views[n] == nil { + m.views[n] = map[string]bool{} } }) query(`SELECT QualifiedName, ModuleName, Id FROM snippets`, func(c []string) { - m.module[c[0]] = c[1] - m.ids[c[0]] = c[2] + n := node(nodeSnippet, c[0]) + m.module[n] = c[1] + m.ids[n] = c[2] m.snippets[c[0]] = true }) - query(`SELECT QualifiedName FROM nanoflows`, func(c []string) { - if m.executes[c[0]] == nil { - m.executes[c[0]] = map[string]bool{} - } - m.executes[c[0]]["\x00nanoflow"] = true - }) + query(`SELECT QualifiedName FROM nanoflows`, func(c []string) { m.nanoflows[c[0]] = true }) query(`SELECT QualifiedName, COALESCE(Generalization, '') FROM entities`, func(c []string) { if c[1] != "" { m.gen[c[0]] = c[1] } }) - query(`SELECT SourceName, RefKind, TargetType, TargetName FROM refs + query(`SELECT SourceType, SourceName, RefKind, TargetType, TargetName FROM refs WHERE RefKind IN ('show_page', 'snippet_call', 'action', 'call', 'member', 'datasource')`, func(c []string) { - m.edges[c[0]] = append(m.edges[c[0]], reachEdge{kind: c[1], targetType: c[2], target: c[3]}) + e := reachEdge{kind: c[2], targetType: c[3], target: c[4]} + for _, kind := range m.sourceKinds(c[0], c[1]) { + src := node(kind, c[1]) + m.edges[src] = append(m.edges[src], e) + } }) query(`SELECT COALESCE(TargetPage, ''), COALESCE(TargetMicroflow, '') FROM navigation_menu_items`, func(c []string) { - for _, t := range c { - if t != "" { - m.entries = append(m.entries, t) - } + if c[0] != "" { + m.entries = append(m.entries, node(nodePage, c[0])) + } + if c[1] != "" { + m.entries = append(m.entries, m.flowNode(c[1])) } }) - query(`SELECT ProfileName, COALESCE(HomePage, '') FROM navigation_profiles`, func(c []string) { - m.profileHomes[c[0]] = c[1] + query(`SELECT ProfileName, COALESCE(HomePage, ''), COALESCE(HomePageType, '') FROM navigation_profiles`, func(c []string) { + if c[1] == "" { + m.profileHomes[c[0]] = "" + return + } + if strings.EqualFold(c[2], nodeMicroflow) || strings.EqualFold(c[2], nodeNanoflow) { + m.profileHomes[c[0]] = m.flowNode(c[1]) + } else { + m.profileHomes[c[0]] = node(nodePage, c[1]) + } }) query(`SELECT ProfileName, UserRole, COALESCE(Page, ''), COALESCE(Microflow, '') FROM navigation_role_homes`, func(c []string) { if m.roleHomes[c[0]] == nil { m.roleHomes[c[0]] = map[string][]string{} } - for _, t := range c[2:] { - if t != "" { - m.roleHomes[c[0]][c[1]] = append(m.roleHomes[c[0]][c[1]], t) - } + if c[2] != "" { + m.roleHomes[c[0]][c[1]] = append(m.roleHomes[c[0]][c[1]], node(nodePage, c[2])) + } + if c[3] != "" { + m.roleHomes[c[0]][c[1]] = append(m.roleHomes[c[0]][c[1]], m.flowNode(c[3])) } }) for p := range ctx.Permissions() { switch { case p.ElementType == "PAGE" && p.AccessType == "VIEW": - reachGrant(m.views, p.ElementName, p.ModuleRoleName) + reachGrant(m.views, node(nodePage, p.ElementName), p.ModuleRoleName) case (p.ElementType == "MICROFLOW" || p.ElementType == "NANOFLOW") && p.AccessType == "EXECUTE": - reachGrant(m.executes, p.ElementName, p.ModuleRoleName) + reachGrant(m.executes, node(p.ElementType, p.ElementName), p.ModuleRoleName) case p.ElementType == "ENTITY" && p.AccessType == "READ" && p.MemberName == "": reachGrant(m.reads, p.ElementName, p.ModuleRoleName) if p.DefaultMemberAccessRights == "ReadOnly" || p.DefaultMemberAccessRights == "ReadWrite" { @@ -492,6 +535,35 @@ func loadReachModel(ctx *linter.LintContext) *reachModel { return m } +// flowNode is the node of a flow a navigation item or home names: the +// nanoflow of that name if there is one, else the microflow. +func (m *reachModel) flowNode(name string) string { + if m.nanoflows[name] { + return node(nodeNanoflow, name) + } + return node(nodeMicroflow, name) +} + +// sourceKinds are the node kinds a reference's source stands for. The +// catalog records its type (refs.SourceType), which is the one kind; a source +// whose type is none of the four is placed by the documents of its name, and +// failing those stands for either kind of flow. +func (m *reachModel) sourceKinds(sourceType, name string) []string { + switch sourceType { + case nodePage, nodeSnippet, nodeMicroflow, nodeNanoflow: + return []string{sourceType} + } + switch { + case m.pages[name]: + return []string{nodePage} + case m.snippets[name]: + return []string{nodeSnippet} + case m.nanoflows[name]: + return []string{nodeNanoflow} + } + return []string{nodeMicroflow, nodeNanoflow} +} + func reachGrant(m map[string]map[string]bool, key, role string) { if m[key] == nil { m[key] = map[string]bool{} diff --git a/mdl/linter/rules/reachable_page_same_name_2730_test.go b/mdl/linter/rules/reachable_page_same_name_2730_test.go new file mode 100644 index 0000000000..1e9710e566 --- /dev/null +++ b/mdl/linter/rules/reachable_page_same_name_2730_test.go @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 + +package rules + +import ( + "strings" + "testing" + + "github.com/mendixlabs/mxcli/sdk/security" +) + +// ako/mxcli#2730 (upstream mendixlabs/mxcli#2004): a Marketplace module held a +// microflow and a snippet both named Lib.Overview. The walk keyed documents +// by name, so a menu item calling the microflow — which the role may not +// execute — reached the snippet instead, and SEC012 reported every attribute +// the snippet's nested snippet shows (CE2729) where mx check reports nothing. + +func (f *readAccessFixture) typedRef(sourceType, source, kind, targetType, target string) { + f.exec(`INSERT INTO refs (SourceType, SourceId, SourceName, TargetType, TargetName, RefKind, ModuleName, ProjectId, SnapshotId) + VALUES (?,?,?,?,?,?,?,?,?)`, sourceType, "s-"+sourceType+source, source, targetType, target, kind, moduleFromQualified(source), "default", "s1") +} + +func (f *readAccessFixture) menuFlow(flow string) { + f.n++ + f.exec(`INSERT INTO navigation_menu_items (ProfileName, ItemPath, Depth, Caption, ActionType, TargetMicroflow, ProjectId, SnapshotId) + VALUES (?,?,?,?,?,?,?,?)`, "Responsive", string(rune('a'+f.n)), 0, flow, "MicroflowAction", flow, "default", "s1") +} + +func sameNameFixture(t *testing.T) *readAccessFixture { + f := reachFixture(t, security.SecurityLevelProduction) + // Probe.SNIP_Timeline shows Title, which ProbeUser may not read. + f.snippetDoc("Probe.SNIP_Timeline") + f.typedRef("SNIPPET", "Probe.SNIP_Timeline", "datasource", "ENTITY", "Probe.Ticket") + f.typedRef("SNIPPET", "Probe.SNIP_Timeline", "member", "ATTRIBUTE", "Probe.Ticket.Title") + // The snippet Probe.Overview holds it; the microflow Probe.Overview opens + // a page ProbeUser may not view, and only Probe.Runner may execute it. + f.snippetDoc("Probe.Overview") + f.typedRef("SNIPPET", "Probe.Overview", "snippet_call", "SNIPPET", "Probe.SNIP_Timeline") + f.pageDoc("Probe.OverviewForm") + f.page("Probe.OverviewForm", "Probe.Runner") + f.typedRef("PAGE", "Probe.OverviewForm", "snippet_call", "SNIPPET", "Probe.Overview") + f.typedRef("MICROFLOW", "Probe.Overview", "show_page", "PAGE", "Probe.OverviewForm") + f.execute("Probe.Overview", "Probe.Runner") + f.menuFlow("Probe.Overview") + return f +} + +func TestReachablePageRead_MicroflowAndSnippetOfOneName_2730(t *testing.T) { + f := sameNameFixture(t) + if vs := f.checkReach(); len(vs) != 0 { + var msgs []string + for _, v := range vs { + msgs = append(msgs, v.Message) + } + t.Errorf("the menu's microflow, which ProbeUser may not execute, reached the snippet of its name:\n%s", strings.Join(msgs, "\n")) + } + + // Control: a page ProbeUser may view that holds the snippet reaches it, + // and the attribute is reported. + f = sameNameFixture(t) + f.pageDoc("Probe.Home") + f.page("Probe.Home", "Probe.User") + f.typedRef("PAGE", "Probe.Home", "snippet_call", "SNIPPET", "Probe.Overview") + f.menuItem("Probe.Home") + got := reported(f.checkReach()) + if len(got) != 1 || got[0] != "Probe.SNIP_Timeline" { + t.Errorf("reported %v, want the snippet Probe.SNIP_Timeline", got) + } +} diff --git a/mdl/types/widget_property_type.go b/mdl/types/widget_property_type.go index 72ded9353b..32a4886cac 100644 --- a/mdl/types/widget_property_type.go +++ b/mdl/types/widget_property_type.go @@ -16,7 +16,11 @@ type PropertyTypeIDEntry struct { ValueTypeID string DefaultValue string // Default value from the template's ValueType ValueType string // Type of value (Boolean, Integer, String, DataSource, etc.) - Required bool // Whether this property is required + // EnumerationKeys are an Enumeration property's declared keys, as the + // widget spells them; the widget compares them exactly (ako/mxcli#2718). + // Empty when not an enumeration or not read from the schema. + EnumerationKeys []string + Required bool // Whether this property is required // DefaultTranslations are the widget-shipped for this property. // A REQUIRED TextTemplate the author leaves unset must be serialized WITH this // text: a null there is CE0463 "the definition of this widget has changed", diff --git a/modelsdk/canon/unexpressed.go b/modelsdk/canon/unexpressed.go index 4f54b5d0ba..550ee5780a 100644 --- a/modelsdk/canon/unexpressed.go +++ b/modelsdk/canon/unexpressed.go @@ -21,6 +21,8 @@ import ( // Forms$ClientTemplate — no text in any language and no parameters. Studio // Pro stores a widget's unset screen-reader label that way; the writer // writes null. Both mean "no label". +// Not inside a pluggable widget's CustomWidgets$WidgetValue: there null +// is a property the widget hides, which must stay null (ako/mxcli#2732). // // and, measured on FactoryManagement's pages (ako/mxcli#2106): // @@ -124,6 +126,14 @@ func carryUnexpressed(contents, stored []byte, patch bool) []byte { changed = true } case nil: + // Not in a pluggable widget's value: there the writer writes + // null for a property the widget's editorConfig hides and an + // empty template for one it shows unset, and putting the + // stored template back on a hidden property is CE0463 + // (ako/mxcli#2732). + if isWidgetValue(d) { + continue + } if t, isDoc := ov.(bson.D); isDoc && isEmptyClientTemplate(t) && !anyIDUsed(t, used) { d[i].Value = t changed = true @@ -200,6 +210,12 @@ func walkElements(v any, fn func(bson.D)) { } } +// isWidgetValue reports whether d is a pluggable widget property's value. +func isWidgetValue(d bson.D) bool { + ty, _ := docLookup(d, "$Type").(string) + return ty == "CustomWidgets$WidgetValue" +} + // isEmptyClientTemplate reports whether t is a Forms$ClientTemplate with no // parameters and no translation in its Template or Fallback. func isEmptyClientTemplate(t bson.D) bool { diff --git a/modelsdk/canon/unexpressed_widgetvalue_2732_test.go b/modelsdk/canon/unexpressed_widgetvalue_2732_test.go new file mode 100644 index 0000000000..f3eb098c05 --- /dev/null +++ b/modelsdk/canon/unexpressed_widgetvalue_2732_test.go @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: Apache-2.0 + +package canon + +import ( + "testing" + + "go.mongodb.org/mongo-driver/v2/bson" +) + +// ako/mxcli#2732 (upstream mendixlabs/mxcli#2006): `create or modify page` +// turning a Data grid 2 attribute column into a customContent column wrote +// the column's `tooltip` null — the property the widget hides for custom +// content, which must be null — and CarryUnexpressed put the stored empty +// ClientTemplate back, because null against an empty template is how it +// recognises an unset screen-reader label. mx check: CE0463 on the grid. +// +// In a pluggable widget's value the writer chooses null or an empty template +// from the widget's editorConfig (#574, #931): null is hidden, empty is shown +// and unset. The two do not mean the same thing there, so nothing is carried. + +func widgetValueTextTemplate(tt any) []byte { + val := bson.D{ + {Key: "$ID", Value: id16(0x41)}, + {Key: "$Type", Value: "CustomWidgets$WidgetValue"}, + {Key: "PrimitiveValue", Value: ""}, + {Key: "TextTemplate", Value: tt}, + } + prop := bson.D{{Key: "$ID", Value: id16(0x40)}, {Key: "$Type", Value: "CustomWidgets$WidgetProperty"}, {Key: "Value", Value: val}} + b, _ := bson.Marshal(bson.D{{Key: "$ID", Value: id16(0xAA)}, {Key: "$Type", Value: "Forms$Page"}, {Key: "Properties", Value: bson.A{int32(2), prop}}}) + return b +} + +func TestUnexpressed_HiddenWidgetValueTemplateStaysNull_2732(t *testing.T) { + assertLands(t, "widget value TextTemplate null over a stored empty template", + widgetValueTextTemplate(nil), widgetValueTextTemplate(emptyTemplate())) + // Control: an unset screen-reader label on a built-in widget is still + // carried — Studio Pro stores it empty, the writer null, both "no label". + assertElided(t, "screen-reader label", widget("x", nil), widget("x", emptyTemplate())) +}