diff --git a/.claude/skills/fix-issue/findings/mdl-backend/2026-12-01-cdc-association-nullable-not-a-fact.json b/.claude/skills/fix-issue/findings/mdl-backend/2026-12-01-cdc-association-nullable-not-a-fact.json new file mode 100644 index 0000000000..6f71ec77b3 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-backend/2026-12-01-cdc-association-nullable-not-a-fact.json @@ -0,0 +1 @@ +{"area": "mdl-backend", "date": "2026-12-01", "refs": ["ako/mxcli#2672", "ako/mxcli#2612"], "symptom": "A change data capture service whose 11.17 baseline held IsNullable false (or no IsNullable key) for an association member was rated a Major change by `create or modify` with nothing changed: 'Modified change data capture service', and the entity moved to revision 2.0, a new topic cdc...2. mx check stayed at 0 errors throughout, so no build flags it.", "file": "mdl/backend/modelsdk/cdc_write.go factsChanged", "cause": "factsChanged compared IsNullable and MaxLength for every member, but mxcli writes an association's as constants (true, 0) and Studio Pro's editor derives neither for an association (getAssociationProperties), reads a stored isNullable back as undefined for an ArrayOfInt64 member (getProperties) and compares a fact only when both sides have one. Any baseline not written by mxcli could hold other values there.", "fix": "An association's only compared fact is its AssociationMultiplicity; IsNullable and MaxLength are still written (true, 0, the stored defaults) so the property set is unchanged.", "insight": "Settle 'is this a fact?' against mxbuild, not by reading code alone: edit the one key in the stored .mxunit (decode, change, re-encode with mongo-driver) and run mx check. On 11.17.0 an association's IsNullable false, the key removed, or MaxLength 7 are all 0 errors, while the same edit on an attribute is CE1585, which is the control that proves mx check compares facts at all. The damage is a version bump, which mxbuild ignores, so only describe's revision/topic line shows it. When editor.js and the metamodel default disagree with a hard-coded value, the hard-coded side must be excluded from comparison, not just from writing.", "test": "mdl/backend/modelsdk/cdc_baseline_1117_2612_test.go TestBumpCdcVersions_AssociationNullabilityIsNotAFact_2672 (with the guard stubbed: source 2.0, service 2.0, want 1.0)"} diff --git a/.claude/skills/fix-issue/findings/mdl-backend/2026-12-01-cdc-recreated-entity-keeps-topic-version.json b/.claude/skills/fix-issue/findings/mdl-backend/2026-12-01-cdc-recreated-entity-keeps-topic-version.json new file mode 100644 index 0000000000..1736732a90 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-backend/2026-12-01-cdc-recreated-entity-keeps-topic-version.json @@ -0,0 +1 @@ +{"area": "mdl-backend", "date": "2026-12-01", "refs": ["ako/mxcli#2672"], "symptom": "After `drop entity` + `create entity` with the same attributes, re-running `create or modify change data capture service` kept the baseline and the source at 1.0 (topic cdc.App.Order.1.{space}) although every GUID the baseline tracks had changed; mx check 11.17.0 reported 0 errors, so nothing flagged it.", "file": "mdl/backend/modelsdk/cdc_write.go bumpCdcVersions / identityChanged", "cause": "bumpCdcVersions matched baseline members to the domain model by exposed name and compared only type and the 11.17 facts; the entity GUID, PropertyGuid and an association's AssociatedEntityGuid were never compared, so a re-created element with the same name read as unchanged.", "insight": "Settle 'which identity does the version rule key on' in Studio Pro's change-data-capture-editor/editor.js, not in mxcli or mx check: getSourceModificationWithImpact / getPropertyModificationWithImpact compare domainCanonicalGuid !== baselineCanonicalGuid and rate it Major, and mxbuild ignores version numbers entirely, so mx check passes the wrong version and cannot be the oracle. Existing bump tests left every GUID empty on both sides, which is why a GUID-blind rule stayed green; a test fixture that zeroes an identity field cannot detect a rule that ignores it."} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-alter-odata-metadataurl-no-refresh-hint.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-alter-odata-metadataurl-no-refresh-hint.json new file mode 100644 index 0000000000..e2b874c400 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-alter-odata-metadataurl-no-refresh-hint.json @@ -0,0 +1 @@ +{"area":"mdl/executor","date":"2026-12-01","symptom":"alter consumed odata service ... set (MetadataUrl: ...) printed only 'Altered OData client' and did not re-read $metadata; a user who took it for the refresh then dropped the client to force one, which deleted every external entity","cause":"Only create or modify consumed odata service re-fetches $metadata (refreshCachedMetadata); ALTER stores the URL and nothing said so. The refresh flow was documented only in the odata-data-sharing skill, not in mxcli syntax odata.consume or the docs site","file":"mdl/executor/cmd_odata.go (alterODataClient, printMetadataRefreshHint)","insight":"A discoverability gap, not a code defect: the statement that looks like the refresh is a no-op for the contract, so it is the place to name the real one. Check where a user searches (mxcli syntax refresh matched only microflow REFRESH) before assuming a skill line is enough. ALTER prints the hint rather than re-fetching, so a URL edit stays offline and cannot fail on an unreachable service.","refs":["ako/mxcli#2674"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-association-one-spelling.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-association-one-spelling.json new file mode 100644 index 0000000000..b35736f201 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-association-one-spelling.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-12-01", "refs": ["ako/mxcli#2709", "mendixlabs/mxcli#1995"], "ce": ["CE0642"], "symptom": "a combo box bound to an association as `Attribute: Order_Customer` (the spelling describe printed) drew MDL-WIDGET56 'attributeAssociation is required and not set — CE0642' on every describe → check round trip, while exec wrote it and mx check built it; the hint `set attributeAssociation:` was itself refused (MDL-WIDGET01)", "cause": "the association was accepted under two keywords: widget_engine's Association mapping fell back to `Attribute:`, describe printed `Attribute:`, and the required-property check's widgetValueMap read only the `Association` source. requiredSuggestion printed the storage key, not the MDL keyword", "file": "mdl/executor/validate_widgets.go (attributeNamesBoundAssociation, MDL-WIDGET57), widget_engine.go (Association mapping), cmd_pages_describe_parse.go / _output.go (ContentIsAssociation), validate_widget_required.go (mdlKeywordFor), mdl/visitor/visitor_page_v3.go (Association: $Param.Module.Assoc)", "fix": "one spelling: describe prints `Association:`; check and exec refuse `Attribute:` naming the association a widget's mode binds (MDL-WIDGET57, error, message names the rewrite); the MDL-WIDGET56 hint names the MDL keyword; the visitor keeps `Association: $Param.Module.Assoc` as the string the builder reads (it was only reachable through the Attribute alias)", "insight": "an alias is a contract every reader of the script must honour; the check missed it, and that was the whole bug. Removing the alias surfaced a hidden dependency: the parameter-rooted form `$Param.Module.Assoc` parsed as an expression under `Association:` and worked only through the `Attribute:` path, so a visitor test of the new spelling was what caught it. Breaking change by decision: old scripts get an error naming the rewrite", "test": "mdl/executor/validate_attribute_for_association_2709_test.go, mdl/visitor/visitor_widget_attribute_ref_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-check-knows-bulk-import-entities.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-check-knows-bulk-import-entities.json new file mode 100644 index 0000000000..7406b3d0d5 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-check-knows-bulk-import-entities.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-12-01", "symptom": "a script that runs `create external entities from M.Client …` and then `retrieve $S from M.Season` is refused by the reference check exec runs first: `microflow 'M.ACT' has reference errors: - entity not found: M.Season (referenced by retrieve)` … `Refusing to execute`; split into two runs it works", "cause": "the script context registered a bulk import only as `externalEntityModules` (a module-level escape) because the entity names live in the contract, not the statement; the association, alter-target and view checks honoured that escape, the microflow entity check (`sc.entities`) never did", "file": "`mdl/executor/validate_bulk_import_entities.go` (`collectBulkImportEntities`), `mdl/executor/cmd_contract.go` (`bulkImportSelection`, `bulkImportType.mendixName`, shared with `createExternalEntities`)", "insight": "A module-wide 'anything goes here' escape is a per-checker opt-in, so it silently misses every checker that forgot it; reading the contract and registering the real names fixes all of them at once and keeps typos in the same module an error. The selection and naming (ENTITIES filter on type OR set name, entity TYPE name, an older import's set-name entity kept) were extracted out of the executor's loop rather than copied, so check and exec cannot drift. The contract the check reads must be the one exec reads: a client created earlier in the script is read from its MetadataUrl via `normalizeMetadataURL` (project-relative), not the stored client's cache. An unreadable or HTTP contract registers nothing and the error keeps a reason, rather than whitelisting the module. Tests `mdl/executor/validate_bulk_import_entities_2674_test.go`", "refs": ["ako/mxcli#2674"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-create-or-modify-association-unstated-delete-behaviour.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-create-or-modify-association-unstated-delete-behaviour.json new file mode 100644 index 0000000000..e30bd74b8c --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-create-or-modify-association-unstated-delete-behaviour.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-12-01", "refs": ["ako/mxcli#2713"], "ce": [], "symptom": "`create or modify association M.Order_Customer from M.Order to M.Customer;` with no delete clause, run to set documentation, reset a stored `on delete restrict error message '\u2026'` to DeleteMeButKeepReferences and dropped the message; describe then printed no ON DELETE clause, and mx check stayed clean", "cause": "both OR MODIFY branches of execCreateAssociation (same-module and cross-module) wrote ChildDeleteBehavior unconditionally; the AST could not tell an unstated behaviour from `on delete set null`, because DeleteKeepReferences is the zero value", "file": "mdl/ast/ast_association.go (DeleteBehaviorSet), mdl/visitor/visitor_association.go, mdl/executor/cmd_associations.go (execCreateAssociation OR MODIFY)", "fix": "the visitor sets DeleteBehaviorSet for ON DELETE and DELETE_BEHAVIOR; OR MODIFY replaces the stored behaviour and its message only when it is set, as storage (#704) and export level (#1498) already did", "insight": "a zero-valued enum in the AST cannot carry 'unstated'; every OR MODIFY property whose default is a real value needs a stated flag or a pointer. Storage and export level had been fixed one at a time; enumerate the remaining unconditional writes in an OR MODIFY branch rather than wait for each report. Measured on 11.12.6: before, describe lost the clause; after, it kept it, the second exec reported Unchanged, mx check 0 errors", "test": "mdl/executor/cmd_associations_delete_behavior_test.go (TestCreateOrModifyAssociation_*), mdl/visitor/visitor_association_delete_stated_test.go"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-drop-odata-client-silent-cascade-misses-into-module.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-drop-odata-client-silent-cascade-misses-into-module.json new file mode 100644 index 0000000000..9a8e6a57e2 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-drop-odata-client-silent-cascade-misses-into-module.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-12-01", "symptom": "`DROP ODATA CLIENT M.Client` / `DROP CONSUMED ODATA SERVICE` removes every external entity created from that client without saying so, leaving pages and microflows with dangling references; an entity imported `into` another module is not dropped at all and fails mx check with CE1613 \"The selected consumed OData service 'M.Client' no longer exists.\" at Entity 'Other.Race'", "cause": "`dropODataClient` ran its own cascade instead of `drop entity`'s: it scanned only the client's own module's domain model for `RemoteServiceName == M.Client`, called `Backend.DeleteEntity` directly (skipping `warnEntityReferences`, `associationMemberModules` and `reconcileModulesAccess`) and printed one line for the client", "file": "`mdl/executor/cmd_odata.go` (`dropClientExternalEntities`, `entityAssociationNames`, called from `dropODataClient`); test `mdl/executor/cmd_odata_drop_client_cascade_test.go`; repro `mdl-examples/bug-tests/2674-drop-odata-client-lists-entities.mdl`", "insight": "A cascade that re-implements a statement's delete is a second, quieter copy of it: every guard added to `drop entity` since (reference warning, #1449 access reconcile) never reached the copy. Reuse the statement's helpers and read everything that depends on the associations (referrers, member modules, association names) BEFORE the first delete, since DeleteEntity removes the associations. `RemoteServiceName` is the link, not the module: `into` puts an external entity anywhere, so scan `ListDomainModels`, not the client's module. mx check settles which leftover matters: the orphaned cross-module entity is CE1613 at the entity (the defect); after the fix the only error left is CE1613 at the microflow the warning named (the expected cost of the drop). The reference warning reads the catalog and is silent unless it is built, as for `drop entity`, so measure with `refresh catalog full` first or the fixed output looks no different. Rebuild the binary after editing: a `make build` started before the edit measured the old code as the fix", "refs": ["ako/mxcli#2674", "ako/mxcli#1449"], "ce": "CE1613"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-error-handler-one-sided-if-implicit-retry-loop.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-error-handler-one-sided-if-implicit-retry-loop.json new file mode 100644 index 0000000000..8fb6a63afc --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-error-handler-one-sided-if-implicit-retry-loop.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-12-01", "refs": ["ako/mxcli#2733", "mendixlabs/mxcli#2007", "#507", "#506"], "ce": [], "symptom": "a custom error handler whose last statement is an `if` with exactly one branch ending in `raise error`/`return` was wired as a retry loop: the continuing branch flowed to a new merge in front of the guarded call/commit, which ran again while it kept failing; describe printed `merge rejoin1; \u2026 join rejoin1;`. check, exec and mx check reported nothing; one statement after `end if` switched it off", "cause": "finishCustomErrorHandler special-cased isRetryLoopErrorHandler (added in #507 for #506, before merge/join existed) and built buildRetryLoopErrorHandler, redirecting the inbound flow through fb.incomingRedirect", "file": "mdl/executor/cmd_microflows_builder_flows.go (finishCustomErrorHandler), cmd_microflows_builder_graph.go, cmd_microflows_builder.go, layout_lanes.go (rejoinsPastRow)", "fix": "removed the heuristic, buildRetryLoopErrorHandler, bodyTerminates and the incomingRedirect field: a handler that does not end in RETURN/RAISE ERROR rejoins after the activity whatever its last statement is; a retry is written with merge/join, which describe already prints for one", "insight": "a shape heuristic that stood in for missing syntax outlived the syntax arriving: once merge/join could state the loop, the guess only fired on handlers that never asked for one. When a construct gains explicit syntax, delete the inference it replaced. Measured on 11.12.6: before, describe showed the loop; after, A (raise) and C (return false, on commit) rejoin forward, the explicit merge/join control still loops, all re-exec Unchanged, mx check 0 errors", "test": "mdl/executor/cmd_microflows_retry_loop_test.go (TestErrorHandlerEndingInOneSidedIfRejoinsAfterTheActivity), cmd_microflows_merge_join_test.go (TestMergeJoin_BackwardReferenceBuildsRetryLoop, control)"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-input-aria-required-autocomplete-purpose-reset.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-input-aria-required-autocomplete-purpose-reset.json new file mode 100644 index 0000000000..73441a0c1a --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-input-aria-required-autocomplete-purpose-reset.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-12-01", "refs": ["ako/mxcli#2710", "mendixlabs/mxcli#1996", "ako/mxcli#2519"], "ce": [], "symptom": "a text box Studio Pro set to Aria required = Yes and Autocomplete purpose = PostalCode was described without either; check refused both as MDL-WIDGET52, and any create or modify / drop + create of the snippet stored AriaRequired false and AutocompletePurpose On on every text box. alter snippet kept them", "cause": "widget_write.go hard-coded SetAriaRequired(false) on text box, text area, date picker and radio buttons, and SetAutocomplete(true) / SetAutocompletePurpose(\"On\") on text box; sdk/pages had no fields, the builders and describe never read them, and the native-props read lists did not name them", "file": "sdk/pages/pages_widgets_input.go, mdl/backend/modelsdk/widget_write.go, mdl/executor/input_accessibility.go, cmd_pages_builder_v3_widgets.go, cmd_pages_describe_parse.go, cmd_pages_describe_output.go, widget_native_props.go, validate_widgets.go, input_submit_width.go", "fix": "AriaRequired carried on the four described inputs, Autocomplete and AutocompletePurpose on text box: parsed (purpose matched case-insensitively against the metamodel's AutocompletePurposeType, refused otherwise by check and exec alike, MDL-WIDGET18), written as given with Studio Pro's defaults when unset, described only when not the default", "insight": "third report of the same shape after KeyboardType (#1209) and AutoFocus (#2519): the issue named the text box, but SetAriaRequired(false) was on four widget types; grep the writer for literal Set*(false)/Set*(\"Default\") across all widgets instead of fixing the reported one. Forms$DropDown and Forms$CheckBox were left: the drop-down is never described, and the check box writer omits AriaRequired entirely. Live on 11.12.6: exec, describe prints the values, re-exec Unchanged, a label edit keeps them, mx check 0 errors", "test": "mdl/executor/input_accessibility_2710_test.go (build, describe with default control, check), mdl/backend/modelsdk/input_accessibility_2710_test.go (writer with default control)"} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-mapping-values-snippet-params.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-mapping-values-snippet-params.json new file mode 100644 index 0000000000..643a3cfab1 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-mapping-values-snippet-params.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-12-01", "symptom": "An import or export mapping value whose JSON type differs from the attribute's (CE5015) or that names an attribute the entity does not have (CE1613), an `import from mapping` fed an Integer, a list or an ordinary object (CE0239), and a snippet call passing an object of a generalization or an unrelated entity (CE0115) all passed check -p; a snippet call leaving out a parameter with no data context to supply it passed check -p and was refused by exec. Check-gap sweep 4 f75 f76 f77 f78 f88 f89", "cause": "MDL107 compared a mapping's member names with the JSON structure but never its value types, and nothing resolved the mapped attribute itself; the import-from-mapping input was never typed; the snippet call's parameters were checked only by exec's page builder (buildSnippetCallParams), not by the page walk check runs", "file": "mdl/executor/validate_mapping_snippet_gaps.go (MDL127, MDL128, checkSnippetCallParams), validate_program.go, validate_widget_attribute_scope.go (walk), validate.go (scriptContext.snippetDecls)", "insight": "The mapping value rule is an exact match, not a widening: a JSON integer does NOT meet a Decimal attribute (CE5015), though the same pairing is legal in an expression. Measure the whole matrix, import and export, before writing the table; 30 one-project measurements settled it. For an exec-only refusal (f88), reuse exec's own words and its own notion of a supplying context (either direction of a generalization), so check and exec cannot disagree on wording or scope.", "refs": ["ako/mxcli#1258"], "ce": ["CE5015", "CE1613", "CE0239", "CE0115"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-nonpersistent-sources-jsaction.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-nonpersistent-sources-jsaction.json new file mode 100644 index 0000000000..a7c9e3e93e --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-nonpersistent-sources-jsaction.json @@ -0,0 +1 @@ +{"area":"mdl/executor","date":"2026-12-01","symptom":"A JavaScript action called from a microflow (CE0009), a JavaScript action argument of the wrong type (CE0117) or a required one left out (CE0115), a data grid / list view / gallery with a database source on a non-persistent entity (CE8812), and a database retrieve of a non-persistent entity (CE0056) all passed check -p and exec; MxBuild 11.16.1 rejected them. Check-gap sweep 4 f83 f84 f85 f91 f92 f93","cause":"The nanoflow validator refused a Java action (MDL091) but nothing refused the mirror case; JavaScript action arguments were matched by name only, and the missing-required check was disabled for them with the comment 'not measured'; nothing read an entity's persistability for a database source or retrieve","file":"mdl/executor/validate_microflow.go (MDL126), validate.go (JavaScript missing required arguments, javaScriptActionMustPass), typecheck.go + exprcheck/adapters/check.go (JavaScript argument types), validate_nonpersistent_sources.go (CE8812, CE0056)","insight":"A comment saying 'not measured' is an invitation, not a fact: one measurement settled it (a required JavaScript parameter left out is CE0115, an optional one is clean) and the existing Java-action machinery then applied unchanged. Name Go test files carefully: a file ending in _js_test.go is built only for GOOS=js, so the new tests were silently excluded and `go test -run` reported 'no tests to run' rather than failing. For persistability, judge only what is established: a script entity's stated kind, or a stored entity's Persistable flag, and never an external or view entity, whose data is read through a database source without a table.","refs":["ako/mxcli#1258"],"ce":["CE0009","CE0117","CE0115","CE8812","CE0056"]} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-published-rest-workflow-outcomes.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-published-rest-workflow-outcomes.json new file mode 100644 index 0000000000..fa4429c603 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-12-01-published-rest-workflow-outcomes.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-12-01", "symptom": "A published REST service path starting with a slash (CE3471), a resource name starting with one (CE0357) or declared twice (CE0331), two operations with one method and path (CE0358), an operation path naming a parameter its microflow lacks (CE1613, CE0352), and a workflow call microflow or decision whose outcomes are not exactly the result's values (CE6686, or CE1613 for a value the enumeration lacks) all passed check -p and exec; MxBuild 11.16.1 rejected them. Check-gap sweep 4 f80 f81 f82 and the CE6686 half MDL-WF06 left open", "cause": "Nothing compared a published REST service's paths with each other or with the operation microflow's parameters; MDL-WF06 judged only a missing empty outcome, from the statement alone, because the rest of the set needs the enumeration's definition and the microflow's return type, which the statement does not carry", "file": "mdl/executor/validate_published_rest_gaps.go (MDL129, publishedRestPathParamErrors), validate_workflow_outcomes.go (checkWorkflowOutcomes), validate_workflow_call_signature.go (checkDecision), validate_datasource_args.go (flowSignature.ReturnEnum)", "insight": "Measure the whole outcome matrix rather than extrapolating from one rule: a call microflow returning a Boolean may have no outcomes, but a decision on a Boolean may not, and a default outcome neither stands in for a missing value nor hurts when the set is complete. An outcome naming no value of the enumeration is CE1613, not CE6686. For REST conflicts MxBuild normalises a trailing slash and a path parameter's name but not case, so the key is method + path with slashes trimmed and parameters blanked.", "refs": ["ako/mxcli#1258"], "ce": ["CE3471", "CE0357", "CE0331", "CE0358", "CE0352", "CE1613", "CE6686"]} diff --git a/.claude/skills/mendix/change-data-capture/SKILL.md b/.claude/skills/mendix/change-data-capture/SKILL.md index f54f18e6b2..a8da9296f7 100644 --- a/.claude/skills/mendix/change-data-capture/SKILL.md +++ b/.claude/skills/mendix/change-data-capture/SKILL.md @@ -14,10 +14,10 @@ description: "Stream entity changes to a data lake with Mendix change data captu | 38-66 | Commands | | 67-102 | Members Are Named, Not Typed | | 103-125 | The Topic, and Why a Major Bump Is Expensive | -| 126-153 | What You Author, and What Is Computed | -| 154-171 | Version Policy — Inferred, Not Measured | -| 172-225 | Verifying the Whole Chain | -| 226-238 | Checklist | +| 126-157 | What You Author, and What Is Computed | +| 158-184 | Version Policy — Inferred, Not Measured | +| 185-238 | Verifying the Whole Chain | +| 239-251 | Checklist | # Change Data Capture @@ -148,7 +148,11 @@ Consequences worth knowing: `AppName`. From **Mendix 11.17** the baseline also records the project's decimal scale and, per member, its multiplicity, nullability and String length (ako/mxcli#2612); mxcli derives them from the domain model as Studio Pro's - editor does, and a change to one is a major version bump. An *absent* baseline is worse than either: `mx check` crashes with + editor does, and a change to one is a major version bump. For an + **association** only the multiplicity counts: its stored nullability and + length are written (true, 0) but never compared, by the editor or by mxbuild, + so a baseline holding other values there is not a change (ako/mxcli#2672). + An *absent* baseline is worse than either: `mx check` crashes with `The given key '' was not present in the dictionary`. ## Version Policy — Inferred, Not Measured @@ -160,6 +164,7 @@ On modify: | nothing | keeps its stored version | | a member added | minor + 1 | | a member removed, an exposed name renamed, or a type changed | **major + 1**, minor 0 | +| the entity, a member, or an association's TO entity has a **new GUID** — dropped and re-created under the same name | **major + 1**, minor 0 | | a brand-new source | starts at 1.0, and does not bump the service | The service takes the largest bump any source took. @@ -169,6 +174,14 @@ numbers entirely, so a wrong rule never fails a build — it quietly moves a topic. If you can, add, rename and remove a property in Studio Pro, accept the changes, and compare: a disagreement means this table is wrong. +The GUID row is read from Studio Pro 11.17's own CDC editor, which keys every +source and member by GUID and rates a GUID that differs from the baseline's a +Major change (ako/mxcli#2672). So `drop entity` + `create entity` with identical +attributes moves the topic to the next major — as it should, since the runtime +gives the re-created entity a new, empty table. Renaming an attribute (same +GUID) while keeping its exposed name is no change. To keep a topic, **alter** +the entity; never drop and re-create it. + ## Verifying the Whole Chain `mx check` passing proves the document is valid, not that anything is published. diff --git a/.claude/skills/mendix/create-page/SKILL.md b/.claude/skills/mendix/create-page/SKILL.md index cef0ad548d..180e64c64b 100644 --- a/.claude/skills/mendix/create-page/SKILL.md +++ b/.claude/skills/mendix/create-page/SKILL.md @@ -12,15 +12,15 @@ description: "CREATE PAGE syntax reference — parameters, variables, layouts, a |---|---| | 28-43 | Reference files | | 44-46 | Overview | -| 47-222 | Syntax | -| 223-293 | Basic Examples | -| 294-318 | Modifying Existing Pages | -| 319-440 | Conditional Visibility and Editability | -| 441-610 | Known Limitations | -| 611-619 | Tips | -| 620-646 | Related Commands | -| 647-671 | PLUGGABLEWIDGET Escape Hatch | -| 672-675 | See Also | +| 47-223 | Syntax | +| 224-294 | Basic Examples | +| 295-319 | Modifying Existing Pages | +| 320-441 | Conditional Visibility and Editability | +| 442-611 | Known Limitations | +| 612-620 | Tips | +| 621-647 | Related Commands | +| 648-672 | PLUGGABLEWIDGET Escape Hatch | +| 673-676 | See Also | # CREATE PAGE - MDL Syntax Guide @@ -102,6 +102,7 @@ Both are optional and can be changed later with `alter page … { set (Class: ' | Password field | `Password: true` | `textbox tbPw (attribute: Secret, Password: true)` | | Submit while typing | `SubmitBehaviour: WhileEditing` (+ `SubmitOnInputDelay: `) on textbox / textarea | `textbox tbSearch (attribute: Query, SubmitBehaviour: WhileEditing, SubmitOnInputDelay: 500)` — default `OnEndEditing` / `300` | | Native keyboard | `KeyboardType: EmailAddress` (`NumberPad`, `DecimalPad`, `PhonePad`, `URL`) on textbox | `textbox tbEmail (attribute: Email, KeyboardType: EmailAddress)` — default `Default` | +| Accessibility / autofill | `AriaRequired: true` on textbox, textarea, datepicker, radiobuttons; `AutocompletePurpose: PostalCode` (`Off`, `Email`, `StreetAddressLine1`, …) and `Autocomplete: false` on textbox | `textbox tbZip (attribute: Zip, AriaRequired: true, AutocompletePurpose: PostalCode)` — defaults `false`, `On` | | Act on Enter | `OnEnterKeyPress: ` on a textbox only | `textbox tbSearch (attribute: Query, OnEnterKeyPress: call microflow Mod.ACT_Search(Query = $currentObject))` — Studio Pro's "On enter key press"; same action forms as `OnChange:`. No other widget has it (a textarea neither): refused there | | Focus in / out | `OnEnter: `, `OnLeave: ` on any input widget | `datepicker dp (attribute: Due, OnLeave: call microflow Mod.ACT_Validate(Item = $currentObject))` — Studio Pro's "On enter" / "On leave"; focus, not the Enter key | | Layout grid width | `Width: FullWidth \| FixedWidth` on layoutgrid | `layoutgrid lg (Width: FixedWidth) { ... }` — default `FullWidth` | diff --git a/.claude/skills/mendix/custom-widgets/SKILL.md b/.claude/skills/mendix/custom-widgets/SKILL.md index 72a4e17a52..363dc915f3 100644 --- a/.claude/skills/mendix/custom-widgets/SKILL.md +++ b/.claude/skills/mendix/custom-widgets/SKILL.md @@ -190,10 +190,10 @@ Two modes depending on the attribute type: -- Enumeration mode (Attribute is an enum) combobox cbStatus (label: 'Status', attribute: status) --- Association mode (Attribute is an association) +-- Association mode: written `Association:` (`attribute:` is refused, MDL-WIDGET57) combobox cmbCustomer ( label: 'Customer', - attribute: Order_Customer, + Association: Order_Customer, datasource: database Module.Customer, CaptionAttribute: Name ) diff --git a/.claude/skills/mendix/mdl-entities/SKILL.md b/.claude/skills/mendix/mdl-entities/SKILL.md index 638f5abcc8..0c1edfc8eb 100644 --- a/.claude/skills/mendix/mdl-entities/SKILL.md +++ b/.claude/skills/mendix/mdl-entities/SKILL.md @@ -22,7 +22,7 @@ description: "Complete syntax reference for entities, attributes and association | 301-324 | Entity with Index | | 325-386 | Complete Domain Model Example | | 387-404 | Changing an Existing Domain Model | -| 405-447 | Quick Reference | +| 405-449 | Quick Reference | # MDL Entity Syntax Reference @@ -427,8 +427,10 @@ from Module.ChildEntity to Module.ParentEntity ``` Every clause is optional; unstated means `type Reference owner Default storage column -on delete set null`. `describe` prints only the clauses that differ, so a table -association always shows `storage table`. +on delete set null` for a new association. On `create or modify` of an existing one, +unstated `storage` and `on delete` keep what is stored (the delete error message with +it); `type` and `owner` still take the default. `describe` prints only the clauses +that differ, so a table association always shows `storage table`. ### Enumeration Syntax ```mdl diff --git a/.claude/skills/mendix/odata-data-sharing/SKILL.md b/.claude/skills/mendix/odata-data-sharing/SKILL.md index 605245b614..b456c03207 100644 --- a/.claude/skills/mendix/odata-data-sharing/SKILL.md +++ b/.claude/skills/mendix/odata-data-sharing/SKILL.md @@ -13,15 +13,15 @@ description: "Share data between Mendix apps over OData — published services, | 31-43 | Reference files | | 44-53 | When to Use This Skill | | 54-74 | MetadataUrl Formats | -| 75-126 | Refreshing the Cached Contract | -| 127-155 | ServiceUrl Must Be a Constant | -| 156-164 | Writing to an External Entity | -| 165-203 | Architecture Overview | -| 204-236 | API Versioning | -| 237-282 | Folder Organization | -| 283-294 | Module Organization Conventions | -| 295-316 | Checklist | -| 317-344 | Exploration Commands | +| 75-132 | Refreshing the Cached Contract | +| 133-161 | ServiceUrl Must Be a Constant | +| 162-170 | Writing to an External Entity | +| 171-209 | Architecture Overview | +| 210-242 | API Versioning | +| 243-288 | Folder Organization | +| 289-300 | Module Organization Conventions | +| 301-322 | Checklist | +| 323-350 | Exploration Commands | # OData Data Sharing Between Mendix Apps @@ -102,11 +102,17 @@ Read the verb it prints — it tells you which happened: | `Warning: could not refresh $metadata: …` | The contract could not be read; the **previously cached one is kept**, so re-run once it is reachable | Then re-import: `CREATE OR MODIFY EXTERNAL ENTITIES FROM F1Now.NowApi` maps the -new entity sets. Do **not** `DROP CONSUMED ODATA SERVICE` and recreate it to force a -refresh — that invalidates the client ID the existing external entities point at. - -Note that `ALTER CONSUMED ODATA SERVICE … SET ( MetadataUrl: … )` does *not* re-fetch. Use -`CREATE OR MODIFY` when the contract is what changed. +new entity sets and updates the existing external entities in place, so pages and +microflows that use them keep working. Do **not** `DROP CONSUMED ODATA SERVICE` and +recreate it to force a refresh — the drop takes **every external entity imported from +the client** with it, in every module (`into` included), and their associations; it +lists each one and warns about the microflows and pages that use them, which then fail +with CE1613. + +Note that `ALTER CONSUMED ODATA SERVICE … SET ( MetadataUrl: … )` does *not* re-fetch: it +stores the URL and prints a note naming the two statements above. Use +`CREATE OR MODIFY` when the contract is what changed (`DESCRIBE CONSUMED ODATA SERVICE` +prints the client's statement if you do not have it). `describe` prints a client and an external entity as `create or modify …`, and re-running that output changes nothing: the rewrite keeps what it cannot print diff --git a/.claude/skills/mendix/overview-pages/SKILL.md b/.claude/skills/mendix/overview-pages/SKILL.md index 789fb2c0b7..07af08364e 100644 --- a/.claude/skills/mendix/overview-pages/SKILL.md +++ b/.claude/skills/mendix/overview-pages/SKILL.md @@ -482,7 +482,7 @@ Choose input widgets based on attribute type: **ComboBox modes:** - Enum mode: `combobox cb (label: 'status', attribute: status)` -- Association mode: `combobox cb (label: 'Customer', attribute: Order_Customer, datasource: database MyModule.Customer, CaptionAttribute: Name)` +- Association mode: `combobox cb (label: 'Customer', Association: Order_Customer, datasource: database MyModule.Customer, CaptionAttribute: Name)` — `Association:`, not `attribute:`, names the association (MDL-WIDGET57) **Reserved Attribute Names:** Do not use `CreatedDate`, `ChangedDate`, `owner`, `ChangedBy` as attribute names - these are system attributes automatically added to all entities. diff --git a/CHANGELOG.md b/CHANGELOG.md index 0aeb0f1e4e..9cb6e8ac9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,29 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added - **`check` and `lint` flag a decision captioned with its whole condition** (ako/mxcli#2685) — Studio Pro draws a decision's caption inside the diamond, and an `if` with no `@caption` was captioned with its full condition, so `$Stints != empty and length($Stints/json) >= 2` wrapped mid-token there and repeated the Expression field. `check` now reports an `if` or `elsif` with no `@caption` whose condition uses `and`/`or` or is longer than 40 characters (MDL-CAPTION01, info), and lint rule CONV012 reports a stored decision captioned with such a condition. A short single test is still its own caption, and `@caption ''` is not reported. The write-microflows skill and `mxcli syntax microflow.control-flow` now tell authors to caption decisions with a short phrase (`@caption 'Has stints?'`). +### Changed +- **A pluggable widget's association is written `Association:`, the one spelling** (ako/mxcli#2709, upstream mendixlabs/mxcli#1995) — a combo box (or drop-down filter) bound to an association was accepted as `Attribute:` too. `describe` printed that spelling, and `check` then warned that the association was unset (MDL-WIDGET56, CE0642) on every round trip, although `exec` wrote it and the build accepted it. `describe` now prints `Association:`. **Breaking:** `check` and `exec` refuse `Attribute:` naming the association a widget's mode binds (MDL-WIDGET57), with a message naming the rewrite. The MDL-WIDGET56 hint names the MDL keyword (`set Association:`) instead of the widget's internal property name. `Association: $Param.Module.Assoc` now works without the old alias. +- **An error handler ending in an `if` with one terminating branch rejoins after the failing activity** (ako/mxcli#2733, upstream mendixlabs/mxcli#2007) — if one branch ended in `raise error` or `return` and the other did not, the other branch was wired back in front of the guarded activity. The activity then ran again for as long as it kept failing, and `check`, `exec` and `mx check` reported nothing. The handler now continues at the statement after the activity, as the syntax help says and as it already did with any statement after the `end if`. **Breaking:** a script that relied on the implicit loop now builds a handler that carries on. Write the retry explicitly with `merge attempt;` before the activity and `join attempt;` in the branch, which is what `describe` prints for a retry loop. + ### Fixed +- **`check` rejects published REST service and workflow outcome mistakes the build rejects** (ako/mxcli#1258) — these passed `check -p` and `exec`, and MxBuild 11.16.1 then failed the build: + - A published REST service path starting with `/` (CE3471): MDL129. + - A resource name starting with `/` (CE0357), or a resource declared twice (CE0331): MDL129. + - Two operations with the same method and path (CE0358): MDL129. A trailing slash or a different path parameter name does not make two paths different; letter case and the method do. + - An operation path naming a parameter its microflow does not have (CE1613, CE0352). The name must match exactly, including case. + - A workflow call microflow or decision whose outcomes are not exactly the result's values (CE6686): true and false, or each enumeration value plus `''`. A call microflow returning a Boolean may have no outcomes; a decision may not. A microflow returning nothing takes no outcomes. An outcome naming no value of the enumeration is reported as CE1613. +- **`check` rejects mapping and snippet call mistakes the build rejects** (ako/mxcli#1258) — these passed `check -p`, and MxBuild 11.16.1 then failed the build: + - An import or export mapping value whose JSON type does not match the attribute's (CE5015): MDL127. A JSON integer meets an Integer or Long, a decimal a Decimal, a boolean a Boolean, and a string a String, an enumeration or a DateTime. A value passed through a converter microflow is not judged. + - A mapping value naming an attribute the entity does not have (CE1613): MDL127. + - An `import from mapping` fed an Integer, a list or an object of an ordinary entity (CE0239): MDL128. It takes a String or a System.FileDocument (or HttpMessage) specialization. + - A snippet call passing an object of a generalization or an unrelated entity (CE0115). + - A snippet call leaving out a parameter with no data context to supply it. `exec` already refused this; `check -p` now reports it in the same words. +- **`check` rejects JavaScript action and non-persistent entity mistakes the build rejects** (ako/mxcli#1258) — these passed `check -p` and `exec`, and MxBuild 11.16.1 then failed the build: + - A `call javascript action` in a microflow (CE0009): MDL126. JavaScript actions run in the client and only nanoflows can call them. + - A JavaScript action argument of the wrong type (CE0117), using the same rules as microflow and Java action calls. + - A required JavaScript action parameter left out (CE0115). An optional one may still be left out. + - A data grid, list view or gallery with a database source on a non-persistent entity (CE8812). + - A database `retrieve` of a non-persistent entity, in a microflow or a nanoflow (CE0056). - **`check -p` rejects workflow call microflows and decisions the build rejects** (ako/mxcli#1258) — these passed `check -p` and `exec`, and MxBuild 11.16.1 then failed the build: - A workflow `call microflow` whose microflow returns a String, an Integer or an object (CE6678). The microflow must return a Boolean, an enumeration or nothing. - A workflow `call microflow` whose microflow takes a parameter other than the workflow's context object without a mapping (CE0117). The context object is passed automatically. @@ -75,6 +97,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **A call's error handler rejoins before the next call when that call also has a handler** (ako/mxcli#2708, upstream mendixlabs/mxcli#1994) — given `$A = call …` and `$B = call …`, each with a custom error handler, and a later statement reading `$B`, the first handler rejoined after the second call. On its error path the second call was then skipped, and the read of `$B` failed with CE0108 in `mx check`; `check` and `exec` reported nothing. Each pending handler is now deferred only past statements that read its own output, as was already the case inside branches. - **A generic Java action's result takes the entity its own type parameter is bound to** (ako/mxcli#2701, upstream mendixlabs/mxcli#1986) — for `RetrieveFor(ObjectList: List of InputType, RetrieveEntity: entity ) returns List of ResultType`, `exec` typed the result as the input list's entity. It then refused `sum $Result by Amount` after `check` had passed. With only an `entity ` argument the result was untyped, and an aggregate over it was written with an empty attribute (CE0015). The result now follows the type parameter the return names: an `entity ` argument, a `List of T` argument, or an object of `T`. - **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`. ## [0.34.0] - 2026-11-27 diff --git a/cmd/mxcli/syntax/features_integration.go b/cmd/mxcli/syntax/features_integration.go index 649fa207ad..2eb6fec8bc 100644 --- a/cmd/mxcli/syntax/features_integration.go +++ b/cmd/mxcli/syntax/features_integration.go @@ -35,12 +35,14 @@ func init() { Path: "odata.consume", Features: []string{"integration/odata_client", "microflows/call_external_action", "microflows/call_external_action_arguments", "microflows/call_external_action_include_associations"}, - Summary: "Create consumed OData services and external entities", + Summary: "Create consumed OData services and external entities; refresh a changed contract", Keywords: []string{ "create consumed odata service", "create odata client", "odata client", "consume odata", "external entity", "metadata url", "odata4", "headers", "proxy", "configurationmicroflow", "headersmicroflow", "service url", "call external action", "include associations", "associations to include", + "refresh", "refresh contract", "refresh metadata", "update metadata", + "metadata changed", "contract changed", "re-import", }, Syntax: "CREATE CONSUMED ODATA SERVICE Module.Name (\n" + " Version: '1.0',\n" + @@ -60,6 +62,13 @@ func init() { "[HEADERS ('Key': 'Value')];\n\n" + "ALTER CONSUMED ODATA SERVICE Module.Name SET (Key: value, ...); -- CREATE's keys\n" + "ALTER PUBLISHED ODATA SERVICE Module.Name SET (Key: value, ...);\n\n" + + "-- Refreshing a changed contract: ALTER ... SET (MetadataUrl: ...) only\n" + + "-- stores the URL; it does not re-read $metadata. Re-run the client's\n" + + "-- CREATE OR MODIFY CONSUMED ODATA SERVICE (DESCRIBE prints it), which\n" + + "-- re-reads it (\"Refreshed $metadata: ...\", or \"Unchanged\"), then\n" + + "-- CREATE OR MODIFY EXTERNAL ENTITIES FROM Module.Name, which updates the\n" + + "-- external entities in place. Do not DROP the client to refresh: that\n" + + "-- deletes its external entities.\n\n" + "CREATE EXTERNAL ENTITY Module.Name\n" + " FROM CONSUMED ODATA SERVICE Module.Client\n" + " (EntitySet: 'Name', RemoteName: 'Name')\n" + @@ -68,7 +77,7 @@ func init() { "-- import maps it; the key must be listed, and no list takes them all.\n" + "-- A name the contract lacks, a type it does not publish, or a Countable/\n" + "-- Creatable/Deletable it contradicts (CE6630) is refused.\n\n" + - "CREATE EXTERNAL ENTITIES FROM Module.Client\n" + + "CREATE [OR MODIFY] EXTERNAL ENTITIES FROM Module.Client\n" + " [INTO Module] [ENTITIES (Name1, Name2)];\n\n" + "ALTER ENTITY Module.Name SET (AllowCreateChangeLocally: true);\n\n" + "DROP EXTERNAL ENTITY [IF EXISTS] Module.Name; -- refuses a local entity\n\n" + diff --git a/cmd/mxcli/syntax/features_page.go b/cmd/mxcli/syntax/features_page.go index 2bd2ba4e74..6947e0f7fa 100644 --- a/cmd/mxcli/syntax/features_page.go +++ b/cmd/mxcli/syntax/features_page.go @@ -182,6 +182,9 @@ LIST IMPACT OF htmlelement; "-- The keyboard a native app opens (TEXTBOX): Default | NumberPad | DecimalPad |\n" + "-- EmailAddress | PhonePad | URL:\n" + "TEXTBOX name (Attribute: Email, KeyboardType: EmailAddress)\n" + + "-- \"Aria required\" (TEXTBOX, TEXTAREA, DATEPICKER, RADIOBUTTONS) and a text box's autocomplete:\n" + + "-- AutocompletePurpose is the HTML token (On default, Off, PostalCode, Email, StreetAddressLine1, ...).\n" + + "TEXTBOX name (Attribute: PostalCode, AriaRequired: true, AutocompletePurpose: PostalCode)\n" + "-- Run an action when the user presses Enter in a text box (Studio Pro's \"On enter key press\").\n" + "-- Same action forms as OnChange:; the stored name OnEnterKeyPressAction: is the same property.\n" + "-- A TEXTBOX's only: no other widget stores it (TEXTAREA neither), so it is refused there.\n" + diff --git a/docs-site/src/SUMMARY.md b/docs-site/src/SUMMARY.md index 407b952b97..ef00dabafa 100644 --- a/docs-site/src/SUMMARY.md +++ b/docs-site/src/SUMMARY.md @@ -277,6 +277,8 @@ - [CREATE WORKFLOW](reference/workflow/create-workflow.md) - [DROP WORKFLOW](reference/workflow/drop-workflow.md) - [OData and Integration Statements](reference/odata/README.md) + - [DROP CONSUMED ODATA SERVICE](reference/odata/drop-odata-client.md) + - [Refreshing a Changed OData Contract](reference/odata/refresh-odata-contract.md) - [Integration Statements](reference/integration/README.md) - [CREATE JSON STRUCTURE](reference/integration/create-json-structure.md) - [CREATE MESSAGE DEFINITION COLLECTION](reference/integration/create-message-definition-collection.md) diff --git a/docs-site/src/language/widget-types.md b/docs-site/src/language/widget-types.md index e3adc58ff3..6763bba11d 100644 --- a/docs-site/src/language/widget-types.md +++ b/docs-site/src/language/widget-types.md @@ -404,9 +404,17 @@ DATEPICKER dpBirthDate (Label: 'Birth Date', Attribute: BirthDate) Dropdown selection for enumeration values or associations. Uses the pluggable ComboBox widget: ```sql +-- Enumeration mode: Attribute: names an enumeration attribute COMBOBOX cbStatus (Label: 'Status', Attribute: Status) + +-- Association mode: a DataSource: selects it, and the association is written Association: +COMBOBOX cbCustomer (Label: 'Customer', Association: Order_Customer, + DataSource: DATABASE MyModule.Customer, CaptionAttribute: Name) ``` +An association is written `Association:`. `Attribute:` naming it is refused as +**MDL-WIDGET57** by both `check` and `exec`; `DESCRIBE` prints `Association:`. + ### REFERENCESELECTOR The classic reference selector (`Forms$ReferenceSelector`) is a built-in Forms diff --git a/docs-site/src/reference/odata/README.md b/docs-site/src/reference/odata/README.md index eb58239dc3..dc710fd080 100644 --- a/docs-site/src/reference/odata/README.md +++ b/docs-site/src/reference/odata/README.md @@ -10,7 +10,9 @@ Mendix supports consuming and publishing OData services. Consumed services (ODat |-----------|-------------| | [CREATE CONSUMED ODATA SERVICE](create-odata-client.md) | Create a consumed OData service (auto-fetches $metadata) | | [ALTER CONSUMED ODATA SERVICE](alter-odata-client.md) | Modify OData client properties | -| [DROP CONSUMED ODATA SERVICE](drop-odata-client.md) | Remove a consumed OData service | +| [DROP CONSUMED ODATA SERVICE](drop-odata-client.md) | Remove a consumed OData service and its external entities | + +To pick up a changed `$metadata`, see [Refreshing a Changed OData Contract](refresh-odata-contract.md). ## OData Service Statements (Published) diff --git a/docs-site/src/reference/odata/drop-odata-client.md b/docs-site/src/reference/odata/drop-odata-client.md new file mode 100644 index 0000000000..17d3bbc05b --- /dev/null +++ b/docs-site/src/reference/odata/drop-odata-client.md @@ -0,0 +1,36 @@ +# DROP CONSUMED ODATA SERVICE + +## Synopsis + +```sql +drop consumed odata service Module.Name; +``` + +## Description + +Removes a consumed OData service (OData client) from the project. Every external +entity imported from it is deleted with it, in every module (including entities +imported `into` another module), together with their associations. The statement +lists each entity it drops and warns about the microflows and pages that use them; +those are left with broken references (CE1613 in `mx check`). The warnings come +from the catalog, so they appear once `refresh catalog` has been run. + +Dropping and recreating a client is **not** the way to pick up a changed +`$metadata`. To refresh the contract and keep the external entities, see +[Refreshing a Changed OData Contract](refresh-odata-contract.md). + +## Parameters + +`Module.Name` +: The qualified name of the consumed OData service. + +## Examples + +```sql +drop consumed odata service Sales.SalesApi; +``` + +## See Also + +[Refreshing a Changed OData Contract](refresh-odata-contract.md), +[OData and Integration Statements](README.md) diff --git a/docs-site/src/reference/odata/refresh-odata-contract.md b/docs-site/src/reference/odata/refresh-odata-contract.md new file mode 100644 index 0000000000..dfd2820af6 --- /dev/null +++ b/docs-site/src/reference/odata/refresh-odata-contract.md @@ -0,0 +1,56 @@ +# Refreshing a Changed OData Contract + +A consumed OData service keeps a copy of the service's `$metadata` (its +contract), so the project builds without the service running. When the service +changes, for example it gains an entity set or a property, that copy is stale. +Refreshing takes two statements. + +## Steps + +```sql +mdl 1; +-- 1. Re-read $metadata into the client. +create or modify consumed odata service Sales.SalesApi ( + ODataVersion: OData4, + MetadataUrl: 'https://api.example.com/odata/$metadata', + Timeout: 300, + ServiceUrl: Sales.SalesApiLocation +); + +-- 2. Update the external entities from the new contract. +create or modify external entities from Sales.SalesApi; +``` + +Step 1 is the client's own statement, run again. If you do not have it, +`describe consumed odata service Sales.SalesApi` prints it. `MetadataUrl` may +be a URL or a local file such as `'./contracts/sales-metadata.xml'`; refresh the +file first if that is where the contract lives. + +Step 2 takes the same options as the first import: `into Module` and +`entities (Name1, Name2)`. Existing external entities are updated in place and +keep their names, so pages and microflows that use them keep working. New +entity sets in the contract become new external entities. + +## What the output means + +| Output of step 1 | Meaning | +|------------------|---------| +| `Modified OData client: …` and `Refreshed $metadata: N entity types, M actions` | The contract changed. The client now holds the new one. | +| `Unchanged OData client: …` | The contract is the same as the cached one. Nothing was written. | +| `Warning: could not refresh $metadata: …` | The contract could not be read. The old cached contract is kept. Fix the URL or file and run it again. | + +## What does not refresh + +- **`alter consumed odata service … set (MetadataUrl: …)`** only stores the new + URL. It does not read `$metadata`, so the cached contract and the external + entities stay as they were. It prints a note saying so. Run the two steps above + after it. +- **`drop consumed odata service`** followed by `create` is not a refresh. Dropping + the client deletes its external entities, and every page, microflow and + association that used them breaks. See [DROP CONSUMED ODATA + SERVICE](drop-odata-client.md). + +## See Also + +[OData and Integration Statements](README.md), +[DROP CONSUMED ODATA SERVICE](drop-odata-client.md) diff --git a/docs-site/src/reference/page/create-page.md b/docs-site/src/reference/page/create-page.md index a83fa92461..210934b66d 100644 --- a/docs-site/src/reference/page/create-page.md +++ b/docs-site/src/reference/page/create-page.md @@ -67,11 +67,11 @@ The widget tree inside `{ ... }` defines the page content. Widgets are nested hi | Widget | Description | Key Properties | |--------|-------------|----------------| -| `TEXTBOX` | Single-line text input | `Label`, `Attribute`, `Password`, `OnChange`, `OnEnter`, `OnLeave`, `OnEnterKeyPress` (an action run when the user presses Enter in the box; the stored name `OnEnterKeyPressAction` is accepted too), `SubmitBehaviour` (`OnEndEditing` default, `WhileEditing`), `SubmitOnInputDelay` (ms, default 300), `KeyboardType` (the keyboard a native app opens: `Default`, `NumberPad`, `DecimalPad`, `EmailAddress`, `PhonePad`, `URL`) | -| `TEXTAREA` | Multi-line text input | `Label`, `Attribute`, `OnChange`, `OnEnter`, `OnLeave`, `SubmitBehaviour`, `SubmitOnInputDelay` | +| `TEXTBOX` | Single-line text input | `Label`, `Attribute`, `Password`, `OnChange`, `OnEnter`, `OnLeave`, `OnEnterKeyPress` (an action run when the user presses Enter in the box; the stored name `OnEnterKeyPressAction` is accepted too), `SubmitBehaviour` (`OnEndEditing` default, `WhileEditing`), `SubmitOnInputDelay` (ms, default 300), `KeyboardType` (the keyboard a native app opens: `Default`, `NumberPad`, `DecimalPad`, `EmailAddress`, `PhonePad`, `URL`), `AriaRequired` (`true` marks the input required to assistive technology), `Autocomplete` (`false` turns browser autocomplete off), `AutocompletePurpose` (the HTML autocomplete token: `On` default, `Off`, `PostalCode`, `Email`, `StreetAddressLine1`, … — Studio Pro's "Autocomplete purpose" list) | +| `TEXTAREA` | Multi-line text input | `Label`, `Attribute`, `OnChange`, `OnEnter`, `OnLeave`, `SubmitBehaviour`, `SubmitOnInputDelay`, `AriaRequired` | | `CHECKBOX` | Boolean toggle | `Label`, `Attribute`, `OnChange`, `OnEnter`, `OnLeave` | -| `RADIOBUTTONS` | Radio button group | `Label`, `Attribute`, `OnChange`, `OnEnter`, `OnLeave` | -| `DATEPICKER` | Date/time selector | `Label`, `Attribute`, `OnChange`, `OnEnter`, `OnLeave` | +| `RADIOBUTTONS` | Radio button group | `Label`, `Attribute`, `OnChange`, `OnEnter`, `OnLeave`, `AriaRequired` | +| `DATEPICKER` | Date/time selector | `Label`, `Attribute`, `OnChange`, `OnEnter`, `OnLeave`, `AriaRequired` | | `COMBOBOX` | Dropdown selector | `Label`, `Attribute`; association mode adds `DataSource`, `CaptionAttribute`; database mode `optionsSourceDatabaseDataSource`, `CaptionAttribute`, `optionsSourceDatabaseValueAttribute`; custom content as the mode's body block (`optionssourceassociationcustomcontent { … }`, `optionssourcedatabasecustomcontent { … }`) | | `FILEMANAGER` | File upload/download, inside a data view on a `System.FileDocument` specialization | `Label`, `Type` (`Upload`, `Download`, `Both` default), `MaxFileSize` (MB, default 5), `AllowedExtensions`, `ShowFileInBrowser` | diff --git a/mdl-examples/bug-tests/1291-combobox-association-onchange-describe.mdl b/mdl-examples/bug-tests/1291-combobox-association-onchange-describe.mdl index 79b1dadbdb..81426874f4 100644 --- a/mdl-examples/bug-tests/1291-combobox-association-onchange-describe.mdl +++ b/mdl-examples/bug-tests/1291-combobox-association-onchange-describe.mdl @@ -41,7 +41,7 @@ create or modify page MyFirstModule.CustomerOrder_Edit dataview dataView1 (datasource: $CustomerOrder) { combobox comboBox1 ( Label: 'Customer', - Attribute: CustomerOrder_Customer, + Association: CustomerOrder_Customer, DataSource: database from MyFirstModule.Customer where [Active = true] sort by Name asc, CaptionAttribute: Name, OnChange: call microflow MyFirstModule.ACT_CustomerOrder_CustomerChanged(CustomerOrder = $currentObject), diff --git a/mdl-examples/bug-tests/1420-combobox-association-snippet-param.mdl b/mdl-examples/bug-tests/1420-combobox-association-snippet-param.mdl index 590dba6976..a271f97f49 100644 --- a/mdl-examples/bug-tests/1420-combobox-association-snippet-param.mdl +++ b/mdl-examples/bug-tests/1420-combobox-association-snippet-param.mdl @@ -33,7 +33,7 @@ create or modify snippet Bug1420.SN_Asset ( Params: ( $Asset: Bug1420.Asset ) ) { combobox cbParam ( - Attribute: $Asset.Bug1420.Asset_Customer, + Association: $Asset.Bug1420.Asset_Customer, DataSource: database from Bug1420.Customer, CaptionAttribute: CustomerName ) diff --git a/mdl-examples/bug-tests/1440-combobox-attribute-association-check.mdl b/mdl-examples/bug-tests/1440-combobox-attribute-association-check.mdl index bcf71bf9d9..cb02646906 100644 --- a/mdl-examples/bug-tests/1440-combobox-attribute-association-check.mdl +++ b/mdl-examples/bug-tests/1440-combobox-attribute-association-check.mdl @@ -36,7 +36,7 @@ create or modify snippet Bug1440.SN_Asset ( Params: ( $Asset: Bug1440.Asset ) ) { combobox x ( - Attribute: $Asset.Bug1440.Asset_Customer, + Association: $Asset.Bug1440.Asset_Customer, DataSource: database from Bug1440.Customer, CaptionAttribute: CustomerName ) diff --git a/mdl-examples/bug-tests/1563-replace-combobox-keeps-hidden-custom-content.mdl b/mdl-examples/bug-tests/1563-replace-combobox-keeps-hidden-custom-content.mdl index bae92fd7ee..13f5df0c8e 100644 --- a/mdl-examples/bug-tests/1563-replace-combobox-keeps-hidden-custom-content.mdl +++ b/mdl-examples/bug-tests/1563-replace-combobox-keeps-hidden-custom-content.mdl @@ -46,7 +46,7 @@ create page MyFirstModule.Holder_Edit ( dataview dvHolder (DataSource: $Holder) { combobox cbBooking ( Label: 'Booking', - Attribute: MyFirstModule.Holder_Booking, + Association: MyFirstModule.Holder_Booking, DataSource: database from MyFirstModule.Booking, CaptionAttribute: Name ) @@ -65,7 +65,7 @@ create page MyFirstModule.Holder_Edit ( -- replace cbBooking with { -- combobox cbSale ( -- Label: 'Sale', --- Attribute: MyFirstModule.Holder_Sale, +-- Association: MyFirstModule.Holder_Sale, -- DataSource: database from MyFirstModule.Sale, -- CaptionAttribute: Code -- ) @@ -78,7 +78,7 @@ create page MyFirstModule.Holder_Edit ( -- replace cbBooking with { -- combobox cbBooking ( -- Label: 'Booking, renamed label', --- Attribute: MyFirstModule.Holder_Booking, +-- Association: MyFirstModule.Holder_Booking, -- DataSource: database from MyFirstModule.Booking, -- CaptionAttribute: Name, -- optionsSourceAssociationCustomContentType: 'yes' diff --git a/mdl-examples/bug-tests/1586-describe-combobox-filter-expression-props.mdl b/mdl-examples/bug-tests/1586-describe-combobox-filter-expression-props.mdl index 8fff2d4625..af29d1dd9b 100644 --- a/mdl-examples/bug-tests/1586-describe-combobox-filter-expression-props.mdl +++ b/mdl-examples/bug-tests/1586-describe-combobox-filter-expression-props.mdl @@ -33,7 +33,7 @@ create association Bug1586.Rec_Parent from Bug1586.Rec to Bug1586.Parent; create page Bug1586.Edit (Title: 'Edit', Layout: Atlas_Core.Atlas_Default, Params: ($Rec: Bug1586.Rec)) { dataview dv (DataSource: $Rec) { combobox cb ( - Attribute: Bug1586.Rec_Parent, + Association: Bug1586.Rec_Parent, DataSource: database from Bug1586.Parent, CaptionAttribute: Name, customEditability: conditionally, diff --git a/mdl-examples/bug-tests/1648-rewrite-changed-combobox-keeps-custom-content.mdl b/mdl-examples/bug-tests/1648-rewrite-changed-combobox-keeps-custom-content.mdl index 84a5432ce7..f1b80f0641 100644 --- a/mdl-examples/bug-tests/1648-rewrite-changed-combobox-keeps-custom-content.mdl +++ b/mdl-examples/bug-tests/1648-rewrite-changed-combobox-keeps-custom-content.mdl @@ -36,7 +36,7 @@ create page MyFirstModule.Holder_Edit ( dataview dvHolder (DataSource: $Holder) { combobox cbBooking ( Label: 'Booking', - Attribute: MyFirstModule.Holder_Booking, + Association: MyFirstModule.Holder_Booking, DataSource: database from MyFirstModule.Booking, CaptionAttribute: Name ) @@ -60,7 +60,7 @@ create page MyFirstModule.Holder_Edit ( -- dataview dvHolder (DataSource: $Holder) { -- combobox cbBooking ( -- Label: 'Booking (changed)', --- Attribute: MyFirstModule.Holder_Booking, +-- Association: MyFirstModule.Holder_Booking, -- DataSource: database from MyFirstModule.Booking, -- CaptionAttribute: Name -- ) diff --git a/mdl-examples/bug-tests/2672-cdc-association-nullable-not-a-fact.mdl b/mdl-examples/bug-tests/2672-cdc-association-nullable-not-a-fact.mdl new file mode 100644 index 0000000000..3ebd2c5218 --- /dev/null +++ b/mdl-examples/bug-tests/2672-cdc-association-nullable-not-a-fact.mdl @@ -0,0 +1,36 @@ +mdl 1; +-- ako/mxcli#2672 (found while investigating it; not the issue's own symptom): +-- an association's stored IsNullable was compared as a baseline fact, so a +-- change data capture service whose baseline held IsNullable false (or no +-- IsNullable at all) for an association member was rated a Major change on +-- the next `create or modify`, and the unchanged entity moved to a new topic. +-- +-- Studio Pro's CDC editor (11.17.0 editor.js: getAssociationProperties, +-- getProperties, createBaseline) writes isNullable for an attribute only and +-- never compares it for an association. mxbuild agrees. +-- +-- Measured on Mendix 11.17.0 with this script on a `mxcli new --version +-- 11.17.0` project, then the association member's IsNullable edited in the +-- stored unit to false, and separately removed: +-- mx check on the edited unit: 0 errors (the same edit on the attribute +-- Number: CE1585 "There are changes in your 'OrdersCdc' document"). +-- Re-running this script, before the fix: "Modified change data capture +-- service", entity Order revision 2.0, topic cdc..Order.2. +-- After the fix: Order stays at 1.0 (the one write normalises IsNullable to +-- the stored default, true), mx check 0 errors, and the next run is +-- "already in sync", byte-identical. +-- Control: changing Number to String(40) still moves Order to 2.0. +-- +-- Run it (needs a Mendix 11.17.0+ project): +-- mxcli exec mdl-examples/bug-tests/2672-cdc-association-nullable-not-a-fact.mdl -p app.mpr +-- mxcli exec mdl-examples/bug-tests/2672-cdc-association-nullable-not-a-fact.mdl -p app.mpr -- unchanged +-- mxcli docker check -p app.mpr + +create module Issue2672; +create or modify persistent entity Issue2672.Customer ( Name: String(100) ); +create or modify persistent entity Issue2672."Order" ( Number: String(20) ); +create or modify association Issue2672.Order_Customer from Issue2672."Order" to Issue2672.Customer; +create or modify change data capture service Issue2672.OrdersCdc ( ServiceName: 'Issue2672Cdc' ) { + entity Issue2672."Order" as 'Issue2672Order' ( Number as 'Number', Order_Customer as 'Customer' ); + entity Issue2672.Customer as 'Issue2672Customer' ( Name as 'Name' ); +}; diff --git a/mdl-examples/bug-tests/2672-cdc-recreated-entity-keeps-topic-version.mdl b/mdl-examples/bug-tests/2672-cdc-recreated-entity-keeps-topic-version.mdl new file mode 100644 index 0000000000..be3787cdc8 --- /dev/null +++ b/mdl-examples/bug-tests/2672-cdc-recreated-entity-keeps-topic-version.mdl @@ -0,0 +1,47 @@ +mdl 1; +-- Refs ako/mxcli#2672: dropping and re-creating an entity a change data +-- capture service tracks keeps every name but mints new GUIDs, and the next +-- `create or modify change data capture service` kept the topic version at 1.0. +-- +-- Studio Pro 11.17.0's CDC editor keys sources and members by GUID: a +-- domainCanonicalGuid that differs from the baseline's is "Changed", impact +-- Major (getSourceModificationWithImpact / getPropertyModificationWithImpact, +-- ide-client/change-data-capture-editor/editor.js). The runtime agrees: a new +-- GUID is a new table, so a consumer of the old topic sees a different source. +-- +-- Run it on an 11.17.0 project, then `describe change data capture service +-- Issue2672.OrdersCdc`: the baseline version and the Order revision must read +-- 2.0 (topic cdc..Order.2.{space}). Before the fix both read 1.0. +-- +-- Measured on an 11.17.0 project: main reported 1.0 / topic ...Order.1.{space}; +-- the fix reports 2.0 / ...Order.2.{space}. mx check 11.17.0 is 0 errors both +-- ways: mxbuild does not judge the numbers, so the stale 1.0 is silent. A second +-- run of the final statement stays at 2.0 (no repeated bump). + +create module Issue2672; + +create persistent entity Issue2672.Order ( + OrderNumber: string(40), + Amount: decimal +); + +create or modify change data capture service Issue2672.OrdersCdc +{ + entity Issue2672.Order (OrderNumber, Amount); +}; + +-- Same names, same types, new GUIDs. The service document survives the drop +-- and is modified in place below. +drop entity Issue2672.Order; + +create persistent entity Issue2672.Order ( + OrderNumber: string(40), + Amount: decimal +); + +create or modify change data capture service Issue2672.OrdersCdc +{ + entity Issue2672.Order (OrderNumber, Amount); +}; + +describe change data capture service Issue2672.OrdersCdc; diff --git a/mdl-examples/bug-tests/2674-check-knows-bulk-import-entities.mdl b/mdl-examples/bug-tests/2674-check-knows-bulk-import-entities.mdl new file mode 100644 index 0000000000..bb92317e33 --- /dev/null +++ b/mdl-examples/bug-tests/2674-check-knows-bulk-import-entities.mdl @@ -0,0 +1,41 @@ +mdl 1; +-- Bug ako/mxcli#2674 (defect 2): the reference check did not know the entities +-- `create external entities from …` creates. +-- +-- Symptom, verbatim: "`check --references` doesn't know about entities that +-- `create external entities from …` will create, so a script that imports and +-- then uses an entity fails without `--no-check`." +-- +-- Measured with `mxcli exec` on a fresh 11.14.0 project. Before the fix exec +-- refused the script: "microflow 'Issue2674.ACT_Products' has reference errors: +-- - entity not found: Issue2674.Product (referenced by retrieve)" … "Refusing +-- to execute". After it the script runs, and mx check reports 0 errors. The +-- check reads the contract exec imports from (the client's MetadataUrl, +-- resolved against the project directory) and registers the entities it +-- selects, named as the import names them (the entity TYPE name, Product). +-- +-- Run it (MetadataUrl resolves relative to the project directory): +-- +-- mkdir -p /path/to/app/mdl-examples/odata-local-metadata +-- cp mdl-examples/odata-local-metadata/sample-metadata.xml /path/to/app/mdl-examples/odata-local-metadata/ +-- mxcli exec mdl-examples/bug-tests/2674-check-knows-bulk-import-entities.mdl -p app.mpr +-- mxcli docker check -p app.mpr + +create module Issue2674; + +create constant Issue2674.SvcUrl + ( Type: string, DefaultValue: 'https://services.odata.org/V4/Northwind/Northwind.svc/' ); + +create or modify consumed odata service Issue2674.Sample ( + ODataVersion: OData4, + MetadataUrl: './mdl-examples/odata-local-metadata/sample-metadata.xml', + ServiceUrl: '@Issue2674.SvcUrl' +); + +create or modify external entities from Issue2674.Sample into Issue2674 entities (Product); + +create microflow Issue2674.ACT_Products () returns integer begin + retrieve $Products from Issue2674.Product; + $n = count $Products; + return $n; +end; diff --git a/mdl-examples/bug-tests/2674-drop-odata-client-lists-entities.mdl b/mdl-examples/bug-tests/2674-drop-odata-client-lists-entities.mdl new file mode 100644 index 0000000000..a8bd09c87a --- /dev/null +++ b/mdl-examples/bug-tests/2674-drop-odata-client-lists-entities.mdl @@ -0,0 +1,63 @@ +mdl 1; +-- Bug ako/mxcli#2674 (defect 1): `drop consumed odata service` / `drop odata +-- client` deletes the client's external entities without listing them. +-- +-- Symptom, verbatim: "`DROP ODATA CLIENT M.Client` also removes every external +-- entity created from that client, without saying so. Pages and microflows that +-- use those entities are left with dangling references." And from the thread: +-- "It also misses entities that were imported `into` another module." +-- +-- Measured on mx check 11.14.0 (Repro.Season imported into Repro, Other.Race +-- imported `into` Other, Other.Bet_Race to it, microflow Other.ACT_Races +-- retrieving it; 0 errors before the drop). +-- Before the fix the drop printed only "Dropped OData client: Repro.F1", +-- deleted Repro.Season silently and left Other.Race behind: +-- CE1613 "The selected consumed OData service 'Repro.F1' no longer exists." +-- at Entity 'Other.Race' +-- After it, the drop warns "Other.Race is referenced by 2 element(s)" +-- (MICROFLOW Other.ACT_Races, ASSOCIATION Other.Bet_Race), prints +-- "Dropped external entity: Repro.Season" and "Dropped external entity: +-- Other.Race (with association(s) Other.Bet_Race)", then a hint that +-- `create or modify` is how a contract is refreshed. mx check reports only the +-- reference the warning named: +-- CE1613 "The selected entity 'Other.Race' no longer exists." at Retrieve +-- object(s) activity — expected: dropping the entity breaks its users. +-- +-- Run it in three steps (an imported entity is not known to the reference +-- check until the import has run; MetadataUrl resolves relative to the project): +-- +-- mkdir -p /path/to/app/mdl-examples/odata-local-metadata +-- cp mdl-examples/odata-local-metadata/race-season-metadata.xml /path/to/app/mdl-examples/odata-local-metadata/ +-- mxcli exec mdl-examples/bug-tests/2674-drop-odata-client-lists-entities.mdl -p app.mpr +-- then, uncommented, the microflow block, then the drop (after `refresh catalog full` +-- so the warning can list the referrers). + +create module Repro2674; +create module Other2674; + +create constant Repro2674.SvcUrl ( Type: string, DefaultValue: 'http://localhost:18765/' ); + +create consumed odata service Repro2674.F1 ( + ODataVersion: OData4, + MetadataUrl: './mdl-examples/odata-local-metadata/race-season-metadata.xml', + ServiceUrl: '@Repro2674.SvcUrl' +); + +create external entities from Repro2674.F1 into Repro2674 entities (Season); +create external entities from Repro2674.F1 into Other2674 entities (Race); + +-- Step 2: +-- create persistent entity Other2674.Bet ( Amount: integer ); +-- create association Other2674.Bet_Race from Other2674.Bet to Other2674.Race; +-- create microflow Other2674.ACT_Races () returns integer +-- begin +-- retrieve $Races from Other2674.Race; +-- $n = count $Races; +-- return $n; +-- end; + +-- Step 3: expect a warning naming Other2674.ACT_Races and Other2674.Bet_Race, +-- one "Dropped external entity" line for Repro2674.Season and Other2674.Race, +-- and no external entity left naming Repro2674.F1. +-- refresh catalog full; +-- drop consumed odata service Repro2674.F1; diff --git a/mdl-examples/bug-tests/662-inherited-association-module-qualifier.mdl b/mdl-examples/bug-tests/662-inherited-association-module-qualifier.mdl index 7e6bb090db..e81da4a3b1 100644 --- a/mdl-examples/bug-tests/662-inherited-association-module-qualifier.mdl +++ b/mdl-examples/bug-tests/662-inherited-association-module-qualifier.mdl @@ -39,13 +39,13 @@ create or modify page MyFirstModule.Member_Edit -- Bare names, declared on System.User: must be written as System.*. combobox cmbRoles ( label: 'User role(s)', - attribute: UserRoles, + Association: UserRoles, datasource: database System.UserRole, CaptionAttribute: Name ) combobox cmbLanguage ( label: 'Language', - attribute: User_Language, + Association: User_Language, datasource: database System.Language, CaptionAttribute: Description ) diff --git a/mdl-examples/bug-tests/664-combobox-expression-caption.mdl b/mdl-examples/bug-tests/664-combobox-expression-caption.mdl index b63900d3ee..38f8a3e4d9 100644 --- a/mdl-examples/bug-tests/664-combobox-expression-caption.mdl +++ b/mdl-examples/bug-tests/664-combobox-expression-caption.mdl @@ -32,7 +32,7 @@ create or modify page MyFirstModule.Office_Edit dataview dv (datasource: $Office) { combobox cmbRegion ( Label: 'Region', - Attribute: Office_Region, + Association: Office_Region, DataSource: database from MyFirstModule.Region, optionsSourceAssociationCaptionType: expression, optionsSourceAssociationCaptionExpression: '$currentObject/Code + '' — '' + $currentObject/Description' diff --git a/mdl-examples/bug-tests/check-gap-import-from-input.fail.mdl b/mdl-examples/bug-tests/check-gap-import-from-input.fail.mdl new file mode 100644 index 0000000000..c71c632d6a --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-import-from-input.fail.mdl @@ -0,0 +1,10 @@ +-- check-gap f78 (ako/mxcli#1258): `import from mapping` fed an object of an +-- ordinary entity. MxBuild 11.16.1 reports CE0239 (the input must be a String or +-- a System.FileDocument / System.HttpMessage specialization); check reports MDL128. +mdl 1; +create module MiBad; +create json structure MiBad.J sample '{"v": "x"}'; +create non-persistent entity MiBad.E (V: String(20)); +create persistent entity MiBad.Item (N: String(10)); +create import mapping MiBad.IM with json structure MiBad.J { create MiBad.E { V = v } }; +create microflow MiBad.F ($X: MiBad.Item) begin $P = import from mapping MiBad.IM($X); end; diff --git a/mdl-examples/bug-tests/check-gap-mapping-values.fail.mdl b/mdl-examples/bug-tests/check-gap-mapping-values.fail.mdl new file mode 100644 index 0000000000..4179c5b226 --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-mapping-values.fail.mdl @@ -0,0 +1,10 @@ +-- 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. +mdl 1; +create module MvBad; +create json structure MvBad.J sample '{"age": "three", "name": "x"}'; +create non-persistent entity MvBad.Pet (Age: Integer, Name: String(20)); +create import mapping MvBad.IM with json structure MvBad.J { create MvBad.Pet { Age = age, Nope = name } }; +create export mapping MvBad.EM with json structure MvBad.J { MvBad.Pet { age = Age, name = Name } }; diff --git a/mdl-examples/bug-tests/check-gap-mappings-snippets.mdl b/mdl-examples/bug-tests/check-gap-mappings-snippets.mdl new file mode 100644 index 0000000000..38d6451c42 --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-mappings-snippets.mdl @@ -0,0 +1,32 @@ +-- check-gap f75 f76 f77 f78 f88 f89 (ako/mxcli#1258): the forms MxBuild 11.16.1 +-- builds clean, each measured, one project per case. A JSON integer meets an +-- Integer or Long attribute, a decimal a Decimal, a boolean a Boolean, a string a +-- String, an enumeration or a DateTime; `import from mapping` reads a String or a +-- file document; a snippet parameter takes its entity or a specialization, and +-- may be left out inside a data context that supplies it. The rejected twins are +-- check-gap-mapping-values.fail.mdl and check-gap-import-from-input.fail.mdl; the +-- snippet ones need a project and are covered in +-- mdl/executor/check_gap_mappings_snippets_test.go. +mdl 1; +create module MvOk; +create enumeration MvOk.Color (Red 'Red', Blue 'Blue'); +create json structure MvOk.J sample '{"n": 5, "l": 7, "d": 5.5, "b": true, "s": "x", "c": "Red", "t": "2020-01-01T00:00:00"}'; +create non-persistent entity MvOk.E (N: Integer, L: Long, D: Decimal, B: Boolean, S: String(20), C: enumeration(MvOk.Color), T: DateTime); +create import mapping MvOk.IM with json structure MvOk.J { + create MvOk.E { N = n, L = l, D = d, B = b, S = s, C = c, T = t } +}; +create export mapping MvOk.EM with json structure MvOk.J { + MvOk.E { n = N, l = L, d = D, b = B, s = S, c = C } +}; +create microflow MvOk.FromText ($Text: String) begin $E = import from mapping MvOk.IM($Text); end; +create microflow MvOk.FromFile ($File: System.FileDocument) begin $E = import from mapping MvOk.IM($File); end; + +create persistent entity MvOk.Item (N: String(10)); +create persistent entity MvOk.Sub extends MvOk.Item (X: String(10)); +create snippet MvOk.S ( params: ( $I: MvOk.Item ) ) { dynamictext t (content: 'x') }; +create page MvOk.BySub ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $A: MvOk.Sub ) ) { + snippetcall sc ( snippet: MvOk.S, params: (I = $A) ) +}; +create page MvOk.InContext ( title: 'p', layout: Atlas_Core.Atlas_Default, params: ( $A: MvOk.Item ) ) { + dataview dv (datasource: $A) { snippetcall sc (snippet: MvOk.S) } +}; diff --git a/mdl-examples/bug-tests/check-gap-np-jsaction.fail.mdl b/mdl-examples/bug-tests/check-gap-np-jsaction.fail.mdl new file mode 100644 index 0000000000..67107e9d50 --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-np-jsaction.fail.mdl @@ -0,0 +1,7 @@ +-- check-gap f83 (ako/mxcli#1258): a JavaScript action called from a microflow. +-- MxBuild 11.16.1 reports CE0009 "This action is not supported in microflows."; +-- check reports MDL126. +mdl 1; +create module NjBad; +create javascript action NjBad.Beep() returns Boolean as $$ return Promise.resolve(true); $$; +create microflow NjBad.Notify () begin $ok = call javascript action NjBad.Beep(); end; diff --git a/mdl-examples/bug-tests/check-gap-np-jsaction.mdl b/mdl-examples/bug-tests/check-gap-np-jsaction.mdl new file mode 100644 index 0000000000..cf8e28137c --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-np-jsaction.mdl @@ -0,0 +1,29 @@ +-- check-gap f84/f85/f91/f92/f93 (ako/mxcli#1258): the forms MxBuild 11.16.1 +-- builds clean. check -p reports the rejected twins (each measured, one project +-- per case): a JavaScript action argument of the wrong type (CE0117) or a +-- required one left out (CE0115); a data grid, list view or gallery with a +-- database source on a non-persistent entity (CE8812); a database retrieve of a +-- non-persistent entity (CE0056). They need a project, so they are covered in +-- mdl/executor/check_gap_nonpersistent_jsaction_test.go; the microflow form is +-- in check-gap-np-jsaction.fail.mdl. +mdl 1; +create module NjOk; +create persistent entity NjOk.Product (Name: String(100), Stock: Integer); +create non-persistent entity NjOk.Filter (Term: String(50)); +create javascript action NjOk.Clamp( Value: Decimal not null, Max: Integer ) returns Decimal as $$ return Promise.resolve(Value); $$; + +create nanoflow NjOk.Adjust ($P: NjOk.Product) returns Decimal as $R +begin + $R = call javascript action NjOk.Clamp(Value = $P/Stock); + return $R; +end; + +create microflow NjOk.Load () returns List of NjOk.Product as $All +begin + retrieve $All from NjOk.Product; + return $All; +end; + +create page NjOk.Products ( title: 'Products', layout: Atlas_Core.Atlas_Default ) { + datagrid grid (datasource: database NjOk.Product) { column (attribute: Name) } +}; diff --git a/mdl-examples/bug-tests/check-gap-published-rest-shape.fail.mdl b/mdl-examples/bug-tests/check-gap-published-rest-shape.fail.mdl new file mode 100644 index 0000000000..1f9958072b --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-published-rest-shape.fail.mdl @@ -0,0 +1,11 @@ +-- check-gap f80 f82 (ako/mxcli#1258): a published REST service MxBuild 11.16.1 +-- rejects. A service path starting with a slash is CE3471 "The path should not +-- start with a /."; two operations with one method and path (a trailing slash +-- does not tell them apart) are CE0358 "Operation has a conflicting path". +-- check reports MDL129. +mdl 1; +create module PrsBad; +create microflow PrsBad.Get ($httpResponse: System.HttpResponse) begin log info node 'x' 'y'; end; +create published rest service PrsBad.API ( path: '/rest/x/v1', version: '1.0.0', ServiceName: 'X' ) { + resource 'items' { get 'x' microflow PrsBad.Get; get 'x/' microflow PrsBad.Get; } +}; diff --git a/mdl-examples/bug-tests/check-gap-rest-workflow-outcomes.mdl b/mdl-examples/bug-tests/check-gap-rest-workflow-outcomes.mdl new file mode 100644 index 0000000000..9121721d14 --- /dev/null +++ b/mdl-examples/bug-tests/check-gap-rest-workflow-outcomes.mdl @@ -0,0 +1,37 @@ +-- check-gap f80 f81 f82, and the CE6686 outcome sets (ako/mxcli#1258): the forms +-- MxBuild 11.16.1 builds clean, each measured, one project per case. A service +-- path may end in a slash but not start with one; an operation path may start +-- with one; operations differ by method or by case; a path parameter names a +-- microflow parameter exactly. A workflow's outcomes are exactly the result's +-- values: true and false (or none, for a call microflow returning a Boolean), +-- each enumeration value plus '' (a default outcome besides is allowed), and none +-- for a microflow returning nothing. The rejected twins need a project and are +-- covered in mdl/executor/check_gap_rest_outcomes_test.go; the shape ones are +-- also in check-gap-published-rest-shape.fail.mdl. +mdl 1; +create module PrsOk; +create enumeration PrsOk.Color ( Red 'Red', Blue 'Blue' ); +create persistent entity PrsOk.Ctx ( B: Boolean, C: enumeration(PrsOk.Color) ); +create microflow PrsOk.Get ($httpResponse: System.HttpResponse) begin log info node 'x' 'y'; end; +create microflow PrsOk.GetById ($id: Integer, $httpResponse: System.HttpResponse) begin log info node 'x' 'y'; end; +create published rest service PrsOk.API ( path: 'rest/x/v1/', version: '1.0.0', ServiceName: 'X' ) { + resource 'items' { + get '' microflow PrsOk.Get; + post '' microflow PrsOk.Get; + get '/a' microflow PrsOk.Get; + get 'A' microflow PrsOk.Get; + get '{id}' microflow PrsOk.GetById; + } +}; + +create microflow PrsOk.Pick () returns enum PrsOk.Color as $R begin return PrsOk.Color.Red; end; +create microflow PrsOk.Ok () returns Boolean as $R begin return true; end; +create microflow PrsOk.Log () begin log info node 'x' 'y'; end; +create workflow PrsOk.WF parameter $WorkflowContext: PrsOk.Ctx display 'W' begin + call microflow PrsOk.Ok; + call microflow PrsOk.Ok outcomes true -> { } false -> { }; + call microflow PrsOk.Pick outcomes 'PrsOk.Color.Red' -> { } 'PrsOk.Color.Blue' -> { } '' -> { } default -> { }; + call microflow PrsOk.Log; + decision $WorkflowContext/B outcomes true -> { } false -> { }; + decision $WorkflowContext/C outcomes 'PrsOk.Color.Red' -> { } 'PrsOk.Color.Blue' -> { } '' -> { }; +end workflow; diff --git a/mdl-examples/bug-tests/javascript-action-call-persist.mdl b/mdl-examples/bug-tests/javascript-action-call-persist.mdl index 467e2b6fa6..40fd6785b6 100644 --- a/mdl-examples/bug-tests/javascript-action-call-persist.mdl +++ b/mdl-examples/bug-tests/javascript-action-call-persist.mdl @@ -30,13 +30,12 @@ mdl 1; create entity MyFirstModule.Bookmark ( Link: String ); --- Microflow variant. -create or modify microflow MyFirstModule.ACT_OpenLink ($Bookmark: MyFirstModule.Bookmark) -begin - $Opened = call javascript action NanoflowCommons.OpenURL(url = $Bookmark/Link); -end; +-- A microflow cannot call a JavaScript action at all: MxBuild 11.16.1 reports +-- CE0009 "This action is not supported in microflows." and check refuses it as +-- MDL126 (check-gap f83). The persistence fix is the same converter for both +-- flow kinds, so the nanoflow covers it. --- Nanoflow variant (the shape the RSS reader hit). +-- Nanoflow (the shape the RSS reader hit). create or modify nanoflow MyFirstModule.NF_OpenLink ($Bookmark: MyFirstModule.Bookmark) returns boolean as $ok begin @@ -44,5 +43,4 @@ begin return $Opened; end; -describe microflow MyFirstModule.ACT_OpenLink; describe nanoflow MyFirstModule.NF_OpenLink; diff --git a/mdl-examples/check-gap/README.md b/mdl-examples/check-gap/README.md index eb3d897a4d..132722a9dc 100644 --- a/mdl-examples/check-gap/README.md +++ b/mdl-examples/check-gap/README.md @@ -108,26 +108,32 @@ 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 | -| f76 | an import mapping naming an attribute the entity does not have | CE1613 | -| f77 | an export mapping putting an Integer attribute into a JSON string value | CE5015 | -| f78 | `import from mapping` fed an object instead of a String or file document | CE0239 | -| f80 | a published REST service path starting with `/` | CE3471 | -| f81 | a published REST operation path `{id}` with no `$id` microflow parameter | CE1613 | -| f82 | two published REST operations with the same method and path | CE0358 conflicting path | -| f83 | `call javascript action` in a microflow | CE0009 not supported in microflows | -| f84 | a JavaScript action argument of the wrong type | CE0117 | -| f85 | a JavaScript action call leaving out a parameter | CE0115 | -| f89 | a snippet call passing an object of another entity | CE0115 | -| f91 | a data grid with a database source on a non-persistent entity | CE8812 not persistable | -| f92 | a list view with a database source on a non-persistent entity | CE8812 | -| f93 | a database `retrieve` of a non-persistent entity | CE0056 | +| 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 +| 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 +| 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` +| f82 | two published REST operations with the same method and path | CE0358 conflicting path | — now `check`: MDL129 +| f83 | `call javascript action` in a microflow | CE0009 not supported in microflows | — now `check`: MDL126 +| f84 | a JavaScript action argument of the wrong type | CE0117 | — now `check -p` +| f85 | a JavaScript action call leaving out a parameter | CE0115 | — now `check -p` +| f89 | a snippet call passing an object of another entity | CE0115 | — now `check -p` +| f91 | a data grid with a database source on a non-persistent entity | CE8812 not persistable | — now `check -p` +| f92 | a list view with a database source on a non-persistent entity | CE8812 | — now `check -p` +| f93 | a database `retrieve` of a non-persistent entity | CE0056 | — now `check -p` f75 and f77 were controlled: the same mappings with matching types (`"age": 3` into an Integer, or `"three"` into a String) build clean. -Check and exec disagree on f88 (a snippet call leaving out the snippet's parameter): `check -p` -passes it, `exec` refuses it when it builds the page. +Measured with f80–f82: a resource name starting with `/` (CE0357) and a resource declared twice +(CE0331) — now `check`: MDL129. Two operations whose paths differ only by a trailing slash or a path +parameter's name conflict (CE0358); a path parameter must name a microflow parameter exactly, case +included (CE0352). A workflow's outcomes must be exactly the result's values (CE6686): true and false, +or each enumeration value and `''` — now `check -p`. + +Check and exec disagreed on f88 (a snippet call leaving out the snippet's parameter): `check -p` +passed it, `exec` refused it when it built the page. `check -p` now refuses it too, in exec's words. Already refused by `check -p`: f86 (a Java action in a nanoflow), f90 (a data grid column on a missing attribute), f96 (a duplicate enumeration value), f97 (an attribute named like an association). Build diff --git a/mdl-examples/doctype-tests/03-page-examples.mdl b/mdl-examples/doctype-tests/03-page-examples.mdl index c00319c3bf..cdc4d68e36 100644 --- a/mdl-examples/doctype-tests/03-page-examples.mdl +++ b/mdl-examples/doctype-tests/03-page-examples.mdl @@ -2436,7 +2436,7 @@ create page PgTest.P037_GroupBox_Example folder 'GroupBox' * CaptionAttribute is the display attribute on the target entity (shown in dropdown). * * - Enum mode: COMBOBOX name (Attribute: EnumAttr) - * - Association mode: COMBOBOX name (Attribute: AssocName, DataSource: DATABASE TargetEntity, CaptionAttribute: DisplayAttr) + * - Association mode: COMBOBOX name (Association: AssocName, DataSource: DATABASE TargetEntity, CaptionAttribute: DisplayAttr) * * @param $Order The order to edit */ @@ -2453,10 +2453,10 @@ create page PgTest.P036_ComboBox_Association folder 'ComboBox' textbox txtOrderNumber (label: 'Order Number', attribute: OrderNumber) -- ComboBox (association mode) selecting a Customer — shows Name in dropdown - combobox cmbCustomer (label: 'Customer', attribute: Order_Customer, datasource: database PgTest.Customer, CaptionAttribute: Name) + combobox cmbCustomer (label: 'Customer', Association: Order_Customer, datasource: database PgTest.Customer, CaptionAttribute: Name) -- ComboBox (association mode) selecting a Product — shows Name in dropdown - combobox cmbProduct (label: 'Product', attribute: Order_Product, datasource: database PgTest.Product, CaptionAttribute: Name) + combobox cmbProduct (label: 'Product', Association: Order_Product, datasource: database PgTest.Product, CaptionAttribute: Name) textbox txtTotal (label: 'Total Amount', attribute: TotalAmount) diff --git a/mdl-examples/doctype-tests/17-custom-widget-examples.mdl b/mdl-examples/doctype-tests/17-custom-widget-examples.mdl index 1250ab53db..0625a05ea8 100644 --- a/mdl-examples/doctype-tests/17-custom-widget-examples.mdl +++ b/mdl-examples/doctype-tests/17-custom-widget-examples.mdl @@ -194,7 +194,7 @@ create page CWTest.P_ComboBox_Assoc folder 'CustomWidgets' textbox txtTitle (label: 'Title', attribute: title) combobox cmbCategory ( label: 'Category', - attribute: Task_Category, + Association: Task_Category, datasource: database CWTest.Category, CaptionAttribute: Name ) diff --git a/mdl/ast/ast_association.go b/mdl/ast/ast_association.go index c4d2f8b35a..3b32fdd992 100644 --- a/mdl/ast/ast_association.go +++ b/mdl/ast/ast_association.go @@ -110,9 +110,14 @@ type CreateAssociationStmt struct { // Stored as a Texts$Text; without one the runtime fails to START, not to // build (CapTrackV2 §1). DeleteErrorMessage string - Documentation string - DocumentationSet bool // see mendixlabs/mxcli#1018: absent preserves, empty clears - CreateOrModify bool // true for CREATE OR MODIFY / CREATE OR REPLACE + // DeleteBehaviorSet: the statement names a delete behaviour (ON DELETE or + // DELETE_BEHAVIOR). Absent, CREATE OR MODIFY keeps the stored behaviour and + // its message — DeleteKeepReferences is the zero value, so DeleteBehavior + // alone cannot tell "unstated" from "on delete set null" (#2713). + DeleteBehaviorSet bool + Documentation string + DocumentationSet bool // see mendixlabs/mxcli#1018: absent preserves, empty clears + CreateOrModify bool // true for CREATE OR MODIFY / CREATE OR REPLACE // Line anchors from `@anchor(from: (x, y), to: (x, y))` — where the // connector attaches to the FROM and TO entity boxes, as a PERCENTAGE of the diff --git a/mdl/backend/modelsdk/cdc_baseline_1117_2612_test.go b/mdl/backend/modelsdk/cdc_baseline_1117_2612_test.go index 9b23376fad..f1aaa07be5 100644 --- a/mdl/backend/modelsdk/cdc_baseline_1117_2612_test.go +++ b/mdl/backend/modelsdk/cdc_baseline_1117_2612_test.go @@ -203,3 +203,45 @@ func TestResolveCdcMember_OwnerBothFromTheToSide_2613(t *testing.T) { t.Error("an owner Default association was accepted from its TO side") } } + +// An association's IsNullable is not a fact of the baseline (ako/mxcli#2672). +// Studio Pro's editor writes isNullable for an attribute only, and reads it back +// as undefined for an ArrayOfInt64 member, so it never compares it; mxbuild +// agrees — measured on 11.17.0, a stored association IsNullable false, or no +// key at all, is 0 errors, while the same flip on an attribute is CE1585. A +// baseline written that way used to rate the unchanged association a Major +// change, and the rewrite moved the entity to a new topic version. The control: +// an attribute's nullability is still a fact, and so is an association's +// multiplicity. +func TestBumpCdcVersions_AssociationNullabilityIsNotAFact_2672(t *testing.T) { + stored := func(name, typ string, facts *model.ChangePropertyFacts) *model.ChangeBaseline { + return &model.ChangeBaseline{Version: &model.ChangeVersion{Major: 1}, Sources: []*model.VersionedChangeSource{{ + ExposedName: "Order", Version: &model.ChangeVersion{Major: 1}, + Properties: []*model.VersionedChangeProperty{{ExposedName: name, Type: typ, Facts: facts}}, + }}} + } + facts := &cdcBaselineFacts{decimalScale: 8} + ver := func(v cdcVersions) string { s := v.source["Order"]; return s.String() } + + assoc := []resolvedSource{{exposedName: "Order", members: []resolvedMember{ + {exposedName: "Customer", isAssoc: true, cdcType: "ArrayOfInt64", nullable: true, multiplicity: "OneToMany"}}}} + // IsNullable false is also what the reader reports when the key is absent. + // MaxLength is not an association fact either (mxbuild: 0 errors at 7). + if got := bumpCdcVersions(stored("Customer", "ArrayOfInt64", + &model.ChangePropertyFacts{AssociationMultiplicity: "OneToMany", IsNullable: false, MaxLength: 7}), assoc, facts); ver(got) != "1.0" || got.service.String() != "1.0" { + t.Errorf("association with a stored IsNullable false and MaxLength 7, domain unchanged: source %s, service %s, want 1.0 and 1.0", + ver(got), got.service.String()) + } + // A changed multiplicity is still a fact of an association. + if got := bumpCdcVersions(stored("Customer", "ArrayOfInt64", + &model.ChangePropertyFacts{AssociationMultiplicity: "ManyToMany", IsNullable: true}), assoc, facts); ver(got) != "2.0" { + t.Errorf("association multiplicity ManyToMany -> OneToMany: source %s, want a major bump", ver(got)) + } + + attr := []resolvedSource{{exposedName: "Order", members: []resolvedMember{ + {exposedName: "Number", cdcType: "String", maxLength: 20, nullable: true}}}} + if got := bumpCdcVersions(stored("Number", "String", + &model.ChangePropertyFacts{IsNullable: false, MaxLength: 20}), attr, facts); ver(got) != "2.0" { + t.Errorf("attribute nullability false -> true: source %s, want a major bump", ver(got)) + } +} diff --git a/mdl/backend/modelsdk/cdc_recreate_guid_test.go b/mdl/backend/modelsdk/cdc_recreate_guid_test.go new file mode 100644 index 0000000000..888a958434 --- /dev/null +++ b/mdl/backend/modelsdk/cdc_recreate_guid_test.go @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: Apache-2.0 + +package modelsdkbackend + +import ( + "testing" + + "github.com/mendixlabs/mxcli/model" +) + +// A tracked entity that is dropped and re-created keeps every name and type but +// gets new GUIDs, and the GUID is what the baseline — and the runtime — key on. +// Studio Pro 11.17's CDC editor compares domainCanonicalGuid with +// baselineCanonicalGuid for the source and for each property, and rates a +// difference "Changed", impact Major (getSourceModificationWithImpact, +// getPropertyModificationWithImpact); a changed associatedEntityGuid likewise. +// Comparing exposed names and types alone kept the topic at 1.0 (found while +// investigating ako/mxcli#2672). +func TestBumpCdcVersions_GUIDIdentity_2672(t *testing.T) { + const ( + entA, entB = "aaaaaaaa-0000-0000-0000-000000000001", "bbbbbbbb-0000-0000-0000-000000000001" + numA, numB = "aaaaaaaa-0000-0000-0000-000000000002", "bbbbbbbb-0000-0000-0000-000000000002" + assocA = "aaaaaaaa-0000-0000-0000-000000000004" + customerEntity = "cccccccc-0000-0000-0000-000000000001" + otherCustomer = "dddddddd-0000-0000-0000-000000000001" + ) + stored := &model.ChangeBaseline{ + Version: &model.ChangeVersion{Major: 1}, + Sources: []*model.VersionedChangeSource{{ + ExposedName: "Order", EntityGUID: entA, Version: &model.ChangeVersion{Major: 1}, + Properties: []*model.VersionedChangeProperty{ + {ExposedName: "Number", PropertyGUID: numA, AssociatedEntityGUID: zeroGUID, Type: "String"}, + {ExposedName: "Order_Customer", PropertyGUID: assocA, AssociatedEntityGUID: customerEntity, Type: "ArrayOfInt64"}, + }, + }}, + } + order := func(entGUID, numGUID, numQN, assocTo string) []resolvedSource { + return []resolvedSource{{exposedName: "Order", entityGUID: entGUID, members: []resolvedMember{ + {qualified: numQN, exposedName: "Number", guid: numGUID, assocGUID: zeroGUID, cdcType: "String"}, + {qualified: "Shop.Order_Customer", exposedName: "Order_Customer", isAssoc: true, guid: assocA, assocGUID: assocTo, cdcType: "ArrayOfInt64"}, + }}} + } + + for _, tc := range []struct { + name string + sources []resolvedSource + want string + }{ + // Control: without it a test that always bumps would pass the rest. + {"unchanged GUIDs keep the version", + order(entA, numA, "Shop.Order.Number", customerEntity), "1.0"}, + {"entity dropped and re-created: every GUID new, so major", + order(entB, numB, "Shop.Order.Number", customerEntity), "2.0"}, + {"one attribute dropped and re-added under the same name: major", + order(entA, numB, "Shop.Order.Number", customerEntity), "2.0"}, + {"the association's TO entity re-created: major", + order(entA, numA, "Shop.Order.Number", otherCustomer), "2.0"}, + // The editor keys a member by GUID, so a renamed attribute whose + // exposed name stays is the same member: no change. + {"attribute renamed, same GUID and exposed name: no change", + order(entA, numA, "Shop.Order.OrderNumber", customerEntity), "1.0"}, + } { + t.Run(tc.name, func(t *testing.T) { + got := bumpCdcVersions(stored, tc.sources, nil) + src := got.source["Order"] + if g := src.String(); g != tc.want { + t.Errorf("Order version = %s, want %s", g, tc.want) + } + svc := got.service + if g := svc.String(); g != tc.want { + t.Errorf("service version = %s, want %s", g, tc.want) + } + }) + } +} diff --git a/mdl/backend/modelsdk/cdc_write.go b/mdl/backend/modelsdk/cdc_write.go index 3e4cf55061..ae1ad32414 100644 --- a/mdl/backend/modelsdk/cdc_write.go +++ b/mdl/backend/modelsdk/cdc_write.go @@ -367,7 +367,8 @@ func (b *Backend) resolveCdcMember( assocGUID: toGUID, cdcType: "ArrayOfInt64", // The editor writes no isNullable for an association; the stored - // value is the metamodel default, true. + // value is the metamodel default, true. Written, never compared + // (factsChanged, ako/mxcli#2672). nullable: true, multiplicity: cdcAssociationMultiplicity(assoc), }, nil @@ -571,6 +572,12 @@ func (b *Backend) DeleteChangeDataCaptureService(id model.ID) error { // - a source that only gained members takes minor+1; // - a source that lost a member, renamed an exposed name or changed a type // takes major+1, minor 0; +// - so does one whose entity or member GUID differs from the baseline's — +// a dropped and re-created entity or attribute, same names, new GUIDs. +// Studio Pro's editor keys members by GUID (domainCanonicalGuid !== +// baselineCanonicalGuid is "Changed", impact Major, for a source and for a +// property; a changed associatedEntityGuid too), and so does the runtime: +// a new GUID is a new table or column (ako/mxcli#2672); // - a new source starts at 1.0; // - the service takes the largest bump any source took. // @@ -587,16 +594,20 @@ func bumpCdcVersions(stored *model.ChangeBaseline, sources []resolvedSource, fac version model.ChangeVersion members map[string]string // exposed name -> CDC type facts map[string]*model.ChangePropertyFacts + guid string + guids map[string]*model.VersionedChangeProperty // exposed name -> member identity } was := map[string]storedSource{} for _, s := range stored.Sources { - ss := storedSource{members: map[string]string{}, facts: map[string]*model.ChangePropertyFacts{}} + ss := storedSource{members: map[string]string{}, facts: map[string]*model.ChangePropertyFacts{}, + guid: s.EntityGUID, guids: map[string]*model.VersionedChangeProperty{}} if s.Version != nil { ss.version = *s.Version } for _, p := range s.Properties { ss.members[p.ExposedName] = p.Type ss.facts[p.ExposedName] = p.Facts + ss.guids[p.ExposedName] = p } was[s.ExposedName] = ss } @@ -611,6 +622,9 @@ func bumpCdcVersions(stored *model.ChangeBaseline, sources []resolvedSource, fac continue } added, breaking := false, false + if identityChanged(prev.guid, prev.guids, rs) { + breaking = true + } now := map[string]string{} for _, rm := range rs.members { now[rm.exposedName] = rm.cdcType @@ -661,13 +675,52 @@ func bumpCdcVersions(stored *model.ChangeBaseline, sources []resolvedSource, fac return out } +// identityChanged reports whether a source's entity, or a member the baseline +// already tracks under the same exposed name, now has a different GUID than +// the baseline froze — or, for an association, a different TO entity GUID. +// Studio Pro's editor rates each a Major change (getSourceModificationWithImpact, +// getPropertyModificationWithImpact, change-data-capture-editor 11.17.0): the +// names match, but it is a different entity or column to the runtime and to a +// consumer (ako/mxcli#2672). +func identityChanged(entityGUID string, members map[string]*model.VersionedChangeProperty, rs resolvedSource) bool { + if !strings.EqualFold(entityGUID, rs.entityGUID) { + return true + } + for _, rm := range rs.members { + p, had := members[rm.exposedName] + if !had { + continue // an addition, rated elsewhere + } + if !strings.EqualFold(p.PropertyGUID, rm.guid) { + return true + } + if rm.isAssoc && !strings.EqualFold(p.AssociatedEntityGUID, rm.assocGUID) { + return true + } + } + return false +} + // factsChanged reports whether a member's 11.17 facts differ from the ones its // baseline recorded. A baseline that recorded none (stored == nil), or a // project too old to record them (facts == nil), is no change. +// +// An association's only fact is its multiplicity. Studio Pro's editor derives +// no isNullable or maxLength for one (getAssociationProperties), reads a +// stored isNullable back as undefined for an ArrayOfInt64 member (getProperties) +// and compares a fact only when both sides have it; mxbuild agrees — measured on +// 11.17.0, an association's stored IsNullable false, absent, or a MaxLength of +// 7 is 0 errors, the same edit on an attribute CE1585. Comparing them rated a +// baseline written by any tool but mxcli a Major change, and the unchanged +// entity moved to a new topic version (ako/mxcli#2672). They are still WRITTEN, +// as the metamodel defaults Studio Pro stores (CLAUDE.md rule 4). func factsChanged(stored *model.ChangePropertyFacts, rm resolvedMember, storedScale *int, facts *cdcBaselineFacts) bool { if stored == nil || facts == nil { return false } + if rm.isAssoc { + return stored.AssociationMultiplicity != rm.multiplicity + } if stored.AssociationMultiplicity != rm.multiplicity || stored.IsNullable != rm.nullable || stored.MaxLength != int(rm.maxLength) { return true } diff --git a/mdl/backend/modelsdk/input_accessibility_2710_test.go b/mdl/backend/modelsdk/input_accessibility_2710_test.go new file mode 100644 index 0000000000..365bab9482 --- /dev/null +++ b/mdl/backend/modelsdk/input_accessibility_2710_test.go @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: Apache-2.0 + +package modelsdkbackend + +import ( + "testing" + + "go.mongodb.org/mongo-driver/v2/bson" + + "github.com/mendixlabs/mxcli/modelsdk/codec" + "github.com/mendixlabs/mxcli/sdk/pages" +) + +func encodeInput2710(t *testing.T, w pages.Widget) bson.Raw { + t.Helper() + g, err := widgetToGen(w) + if err != nil { + t.Fatal(err) + } + raw, err := (&codec.Encoder{}).Encode(g) + if err != nil { + t.Fatal(err) + } + return bson.Raw(raw) +} + +// ako/mxcli#2710: the writer hard-coded AriaRequired false on every input and +// Autocomplete true / AutocompletePurpose On on every text box. +func TestInputsWriteAriaRequired_2710(t *testing.T) { + no := false + for name, w := range map[string]pages.Widget{ + "textbox": &pages.TextBox{AriaRequired: true, Autocomplete: &no, AutocompletePurpose: "PostalCode"}, + "textarea": &pages.TextArea{AriaRequired: true}, + "datepicker": &pages.DatePicker{AriaRequired: true}, + "radiobuttons": &pages.RadioButtons{AriaRequired: true}, + } { + raw := encodeInput2710(t, w) + if got, ok := raw.Lookup("AriaRequired").BooleanOK(); !ok || !got { + t.Errorf("%s: AriaRequired stored as %v (present %v)", name, got, ok) + } + } + raw := encodeInput2710(t, &pages.TextBox{AriaRequired: true, Autocomplete: &no, AutocompletePurpose: "PostalCode"}) + if got, _ := raw.Lookup("Autocomplete").BooleanOK(); got { + t.Error("Autocomplete false stored as true") + } + if got, _ := raw.Lookup("AutocompletePurpose").StringValueOK(); got != "PostalCode" { + t.Errorf("AutocompletePurpose stored as %q", got) + } + // Control: an unset text box still gets Studio Pro's defaults. + raw = encodeInput2710(t, &pages.TextBox{}) + if got, ok := raw.Lookup("AriaRequired").BooleanOK(); !ok || got { + t.Errorf("default AriaRequired = %v (present %v)", got, ok) + } + if got, ok := raw.Lookup("Autocomplete").BooleanOK(); !ok || !got { + t.Errorf("default Autocomplete = %v (present %v)", got, ok) + } + if got, _ := raw.Lookup("AutocompletePurpose").StringValueOK(); got != "On" { + t.Errorf("default AutocompletePurpose = %q", got) + } +} diff --git a/mdl/backend/modelsdk/widget_write.go b/mdl/backend/modelsdk/widget_write.go index 2b658850f3..2b70724283 100644 --- a/mdl/backend/modelsdk/widget_write.go +++ b/mdl/backend/modelsdk/widget_write.go @@ -593,10 +593,10 @@ func widgetToGen(w pages.Widget) (element.Element, error) { case *pages.TextBox: g := genPg.NewTextBox() applyWidgetBase(g, &x.BaseWidget) - g.SetAriaRequired(false) - g.SetAutoFocus(x.AutoFocus) // ako/mxcli#2519 - g.SetAutocomplete(true) - g.SetAutocompletePurpose("On") + g.SetAriaRequired(x.AriaRequired) // ako/mxcli#2710 + g.SetAutoFocus(x.AutoFocus) // ako/mxcli#2519 + g.SetAutocomplete(x.Autocomplete == nil || *x.Autocomplete) + g.SetAutocompletePurpose(orDefaultStr(x.AutocompletePurpose, "On")) if ref := inputAttributeRefToGen(x.AttributePath, x.AttributeRefSteps); ref != nil { g.SetAttributeRef(ref) } @@ -724,7 +724,7 @@ func widgetToGen(w pages.Widget) (element.Element, error) { case *pages.TextArea: g := genPg.NewTextArea() applyWidgetBase(g, &x.BaseWidget) - g.SetAriaRequired(false) + g.SetAriaRequired(x.AriaRequired) // ako/mxcli#2710 g.SetAutoFocus(false) if ref := inputAttributeRefToGen(x.AttributePath, x.AttributeRefSteps); ref != nil { g.SetAttributeRef(ref) @@ -772,7 +772,7 @@ func widgetToGen(w pages.Widget) (element.Element, error) { case *pages.DatePicker: g := genPg.NewDatePicker() applyWidgetBase(g, &x.BaseWidget) - g.SetAriaRequired(false) + g.SetAriaRequired(x.AriaRequired) // ako/mxcli#2710 if ref := inputAttributeRefToGen(x.AttributePath, x.AttributeRefSteps); ref != nil { g.SetAttributeRef(ref) } @@ -806,7 +806,7 @@ func widgetToGen(w pages.Widget) (element.Element, error) { case *pages.RadioButtons: g := genPg.NewRadioButtonGroup() applyWidgetBase(g, &x.BaseWidget) - g.SetAriaRequired(false) + g.SetAriaRequired(x.AriaRequired) // ako/mxcli#2710 if ref := inputAttributeRefToGen(x.AttributePath, x.AttributeRefSteps); ref != nil { g.SetAttributeRef(ref) } diff --git a/mdl/executor/check_gap_mappings_snippets_test.go b/mdl/executor/check_gap_mappings_snippets_test.go new file mode 100644 index 0000000000..b853ad0c18 --- /dev/null +++ b/mdl/executor/check_gap_mappings_snippets_test.go @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/visitor" +) + +// Check-gap sweep 4, batch B (f75 f76 f77 f78 f88 f89): each passed check -p +// (f88: and was refused by exec), and MxBuild 11.16.1 rejected the project. +// Every case below was measured there, one project per case. + +func mbViolations(t *testing.T, src, rule string) []string { + t.Helper() + prog, errs := visitor.Build(src) + if len(errs) > 0 { + t.Fatalf("parse: %v\n%s", errs[0], src) + } + var out []string + for _, v := range ValidateProgram(prog, "") { + if v.RuleID == rule { + out = append(out, v.Message) + } + } + return out +} + +func importMappingSrc(sample, attrType string) string { + return `mdl 1; +create module MB; +create enumeration MB.Color (Red 'Red', Blue 'Blue'); +create json structure MB.J sample '{"v": ` + sample + `}'; +create non-persistent entity MB.E (V: ` + attrType + `); +create import mapping MB.IM with json structure MB.J { create MB.E { V = v } }; +` +} + +func exportMappingSrc(sample, attrType string) string { + return `mdl 1; +create module MB; +create enumeration MB.Color (Red 'Red', Blue 'Blue'); +create json structure MB.J sample '{"v": ` + sample + `}'; +create non-persistent entity MB.E (V: ` + attrType + `); +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." +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) + } + }) + } + accepted := []struct{ name, src string }{ + {"import integer to integer", importMappingSrc(`5`, "Integer")}, + {"import integer to long", importMappingSrc(`5`, "Long")}, + {"import decimal to decimal", importMappingSrc(`5.5`, "Decimal")}, + {"import boolean to boolean", importMappingSrc(`true`, "Boolean")}, + {"import string to string", importMappingSrc(`"x"`, "String(20)")}, + {"import string to enumeration", importMappingSrc(`"Red"`, "enumeration(MB.Color)")}, + {"import string to datetime", importMappingSrc(`"2020-01-01T00:00:00"`, "DateTime")}, + {"export integer", exportMappingSrc(`5`, "Integer")}, + {"export long", exportMappingSrc(`5`, "Long")}, + {"export decimal", exportMappingSrc(`5.5`, "Decimal")}, + {"export string", exportMappingSrc(`"x"`, "String(20)")}, + {"export enumeration", exportMappingSrc(`"Red"`, "enumeration(MB.Color)")}, + {"export boolean", exportMappingSrc(`true`, "Boolean")}, + } + for _, c := range accepted { + t.Run(c.name, func(t *testing.T) { + if got := mbViolations(t, c.src, "MDL127"); len(got) != 0 { + t.Errorf("control reported %q", got) + } + }) + } +} + +// f76: a mapping naming an attribute the entity does not have — CE1613. +func TestMappingUnknownAttribute(t *testing.T) { + imp := strings.Replace(importMappingSrc(`"x"`, "String(20)"), "{ V = v }", "{ Nope = v }", 1) + exp := strings.Replace(exportMappingSrc(`"x"`, "String(20)"), "{ v = V }", "{ v = Nope }", 1) + for name, src := range map[string]string{"import": imp, "export": exp} { + got := mbViolations(t, src, "MDL127") + if len(got) != 1 || !strings.Contains(got[0], "CE1613") || !strings.Contains(got[0], "Nope") { + t.Errorf("%s: want one MDL127 naming CE1613 and Nope, got %q", name, got) + } + } +} + +func importFromSrc(param string) string { + return `mdl 1; +create module MB; +create json structure MB.J sample '{"v": "x"}'; +create non-persistent entity MB.E (V: String(20)); +create persistent entity MB.Item (N: String(10)); +create import mapping MB.IM with json structure MB.J { create MB.E { V = v } }; +create microflow MB.F (` + param + `) begin $P = import from mapping MB.IM($X); end; +` +} + +// f78: `import from mapping` takes a String or a file document — anything else +// is CE0239 "Variable should be a string or a specialization of type +// 'System.FileDocument' or 'System.HttpMessage'". +func TestImportFromMappingInput(t *testing.T) { + for _, p := range []string{"$X: Integer", "$X: List of MB.Item", "$X: MB.Item"} { + got := mbViolations(t, importFromSrc(p), "MDL128") + if len(got) != 1 || !strings.Contains(got[0], "CE0239") { + t.Errorf("%s: want one MDL128 naming CE0239, got %q", p, got) + } + } + for _, p := range []string{"$X: String", "$X: System.FileDocument"} { + if got := mbViolations(t, importFromSrc(p), "MDL128"); len(got) != 0 { + t.Errorf("%s: control reported %q", p, got) + } + } +} + +const snippetHead = `mdl 1; +create module SNP; +create persistent entity SNP.Base (C: String(10)); +create persistent entity SNP.Item extends SNP.Base (N: String(10)); +create persistent entity SNP.Sub extends SNP.Item (X: String(10)); +create persistent entity SNP.Other (L: String(10)); +create snippet SNP.S ( params: ( $I: SNP.Item ) ) { dynamictext t (content: 'x') }; +` + +func snippetPage(param, body string) string { + return "create page SNP.P ( title: 'p', layout: Atlas_Core.Atlas_Default" + param + " ) { " + body + " };\n" +} + +func snippetCheck(t *testing.T, src string) string { + t.Helper() + exec, _, dir := openPedAppCopy(t) + return strings.Join(agreeCheck(t, exec, dir, src), "\n") +} + +// f89: a snippet argument whose entity is not the parameter's or a +// specialization of it — CE0115. f88: a parameter left out with no data context +// to supply it — exec refuses it, so check must too. +func TestSnippetCallParameters(t *testing.T) { + reported := []struct{ name, src, want string }{ + {"generalization argument", snippetPage(", params: ( $A: SNP.Base )", "snippetcall sc ( snippet: SNP.S, params: (I = $A) )"), "is a SNP.Base"}, + {"unrelated argument", snippetPage(", params: ( $A: SNP.Other )", "snippetcall sc ( snippet: SNP.S, params: (I = $A) )"), "is a SNP.Other"}, + {"left out, no context", snippetPage("", "snippetcall sc (snippet: SNP.S)"), "snippet SNP.S requires parameter $I"}, + } + for _, c := range reported { + t.Run(c.name, func(t *testing.T) { + got := snippetCheck(t, snippetHead+c.src) + if !strings.Contains(got, c.want) { + t.Errorf("check -p must report %q, reported:\n%s", c.want, got) + } + }) + } + accepted := []string{ + snippetPage(", params: ( $A: SNP.Item )", "snippetcall sc ( snippet: SNP.S, params: (I = $A) )"), + snippetPage(", params: ( $A: SNP.Sub )", "snippetcall sc ( snippet: SNP.S, params: (I = $A) )"), + snippetPage(", params: ( $A: SNP.Item )", "dataview dv (datasource: $A) { snippetcall sc (snippet: SNP.S) }"), + } + for _, s := range accepted { + t.Run(s, func(t *testing.T) { + if got := snippetCheck(t, snippetHead+s); got != "" { + t.Errorf("control must pass check -p, reported:\n%s", got) + } + }) + } +} diff --git a/mdl/executor/check_gap_nonpersistent_jsaction_test.go b/mdl/executor/check_gap_nonpersistent_jsaction_test.go new file mode 100644 index 0000000000..9bf733943d --- /dev/null +++ b/mdl/executor/check_gap_nonpersistent_jsaction_test.go @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/linter" + "github.com/mendixlabs/mxcli/mdl/visitor" +) + +// Check-gap sweep 4, batch A (f83 f84 f85 f91 f92 f93): each passed check -p and +// exec, and MxBuild 11.16.1 rejected the project. Every case below was measured +// there, one project per case. +const npjsHead = `mdl 1; +create module NJ; +create persistent entity NJ.Item (Name: String(100), Qty: Integer, Price: Decimal); +create non-persistent entity NJ.NP (L: String(10)); +create javascript action NJ.JAdd( A: Integer not null, B: Integer not null ) returns Integer as $$ return Promise.resolve(A + B); $$; +create javascript action NJ.JDec( D: Decimal not null ) returns Integer as $$ return Promise.resolve(1); $$; +create javascript action NJ.JStr( S: String not null ) returns Integer as $$ return Promise.resolve(1); $$; +create javascript action NJ.JOpt( A: Integer not null, B: Integer ) returns Integer as $$ return Promise.resolve(A); $$; +` + +// npjsCheck is check -p: ValidateProgram, the reference pass and the +// catalog-backed expression tier. +func npjsCheck(t *testing.T, src string) string { + t.Helper() + exec, _, dir := openPedAppCopy(t) + out := agreeCheck(t, exec, dir, src) + prog, _ := visitor.Build(src) + for _, v := range exec.TypeCheckProgram(prog) { + if v.Severity == linter.SeverityError { + out = append(out, v.RuleID+": "+v.Message) + } + } + return strings.Join(out, "\n") +} + +func npjsNanoflow(body string) string { + return "create nanoflow NJ.N ($I: NJ.Item) returns Integer as $R begin " + body + " return 1; end;\n" +} + +func npjsPage(widget string) string { + return "create page NJ.P ( title: 'p', layout: Atlas_Core.Atlas_Default ) { " + widget + " };\n" +} + +func TestCheckGapNpJs_Reported(t *testing.T) { + cases := []struct{ name, src, want string }{ + // f83: a JavaScript action in a microflow — CE0009. + {"javascript action in microflow", "create microflow NJ.F () begin $n = call javascript action NJ.JAdd(A = 1, B = 2); end;\n", + "not supported in a microflow"}, + // f84: an argument of the wrong type — CE0117. + {"js string literal to integer", npjsNanoflow("$n = call javascript action NJ.JAdd(A = 'abc', B = 2);"), "Parameter $A of NJ.JAdd is an Integer"}, + {"js decimal to integer", npjsNanoflow("$n = call javascript action NJ.JAdd(A = $I/Price, B = 2);"), "Parameter $A of NJ.JAdd is an Integer"}, + {"js integer to string", npjsNanoflow("$n = call javascript action NJ.JStr(S = $I/Qty);"), "Parameter $S of NJ.JStr is a String"}, + // f85: a required parameter left out — CE0115. + {"js missing required", npjsNanoflow("$n = call javascript action NJ.JAdd(A = 1);"), "required parameter(s) B"}, + {"js missing required optional given", npjsNanoflow("$n = call javascript action NJ.JOpt(B = 1);"), "required parameter(s) A"}, + // f91 f92: a database source on a non-persistent entity — CE8812. + {"datagrid database non-persistent", npjsPage("datagrid g (datasource: database NJ.NP) { column (attribute: L) }"), "NJ.NP is non-persistent"}, + {"listview database non-persistent", npjsPage("listview lv (datasource: database NJ.NP) { dynamictext t (content: 'x') }"), "NJ.NP is non-persistent"}, + {"gallery database non-persistent", npjsPage("gallery g (datasource: database NJ.NP) { dynamictext t (content: 'x') }"), "NJ.NP is non-persistent"}, + // f93: a database retrieve of a non-persistent entity — CE0056. + {"retrieve non-persistent", "create microflow NJ.F () begin retrieve $L from NJ.NP; end;\n", "NJ.NP is non-persistent"}, + {"retrieve first non-persistent", "create microflow NJ.F () begin retrieve $o from NJ.NP first; end;\n", "NJ.NP is non-persistent"}, + {"retrieve non-persistent in nanoflow", npjsNanoflow("retrieve $L from NJ.NP where [L = 'x'];"), "NJ.NP is non-persistent"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := npjsCheck(t, npjsHead+c.src) + if !strings.Contains(got, c.want) { + t.Errorf("check -p must report %q, reported:\n%s", c.want, got) + } + }) + } +} + +func TestCheckGapNpJs_ControlsAccepted(t *testing.T) { + srcs := []string{ + npjsNanoflow("$n = call javascript action NJ.JAdd(A = $I/Qty, B = 2);"), + npjsNanoflow("$n = call javascript action NJ.JDec(D = $I/Qty);"), + npjsNanoflow("$n = call javascript action NJ.JOpt(A = 1);"), + npjsPage("datagrid g (datasource: database NJ.Item) { column (attribute: Name) }"), + "create microflow NJ.F () begin retrieve $L from NJ.Item; end;\n", + } + for _, s := range srcs { + t.Run(s, func(t *testing.T) { + if got := npjsCheck(t, npjsHead+s); got != "" { + t.Errorf("control must pass check -p, reported:\n%s", got) + } + }) + } +} diff --git a/mdl/executor/check_gap_rest_outcomes_test.go b/mdl/executor/check_gap_rest_outcomes_test.go new file mode 100644 index 0000000000..6511456b47 --- /dev/null +++ b/mdl/executor/check_gap_rest_outcomes_test.go @@ -0,0 +1,125 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" +) + +// Check-gap sweep 4, batch C (f80 f81 f82, and the CE6686 outcome half left +// over from the workflow batch): each passed check -p and exec, and MxBuild +// 11.16.1 rejected the project. Every case below was measured there, one +// project per case. + +const prsHead = `mdl 1; +create module PRS; +create microflow PRS.P ($httpResponse: System.HttpResponse) begin log info node 'x' 'y'; end; +create microflow PRS.Q ($id: Integer, $a: Integer, $httpResponse: System.HttpResponse) begin log info node 'x' 'y'; end; +` + +func prsService(path, body string) string { + return prsHead + "create published rest service PRS.API ( path: '" + path + "', version: '1.0.0', ServiceName: 'X' ) { " + body + " };\n" +} + +// f80 f82, and the two resource-name cases measured alongside them. +func TestPublishedRestShape(t *testing.T) { + reported := []struct{ name, src, want string }{ + {"service path with a leading slash", prsService("/rest/x/v1", "resource 'items' { get '' microflow PRS.P; }"), "CE3471"}, + {"resource with a leading slash", prsService("rest/x/v1", "resource '/items' { get '' microflow PRS.P; }"), "CE0357"}, + {"resource twice", prsService("rest/x/v1", "resource 'items' { get '' microflow PRS.P; } resource 'items' { post '' microflow PRS.P; }"), "CE0331"}, + {"same method and path", prsService("rest/x/v1", "resource 'items' { get '' microflow PRS.P; get '' microflow PRS.P; }"), "CE0358"}, + {"trailing slash", prsService("rest/x/v1", "resource 'items' { get 'x' microflow PRS.P; get 'x/' microflow PRS.P; }"), "CE0358"}, + {"path parameter names", prsService("rest/x/v1", "resource 'items' { get '{id}' microflow PRS.Q; get '{a}' microflow PRS.Q; }"), "CE0358"}, + } + for _, c := range reported { + t.Run(c.name, func(t *testing.T) { + got := mbViolations(t, c.src, "MDL129") + if len(got) != 1 || !strings.Contains(got[0], c.want) { + t.Errorf("want one MDL129 naming %s, got %q", c.want, got) + } + }) + } + accepted := []string{ + prsService("rest/x/v1/", "resource 'items' { get '' microflow PRS.P; }"), + prsService("rest/x/v1", "resource 'items' { get 'a' microflow PRS.P; get 'A' microflow PRS.P; }"), + prsService("rest/x/v1", "resource 'items' { get '' microflow PRS.P; post '' microflow PRS.P; }"), + prsService("rest/x/v1", "resource 'items' { get '/x' microflow PRS.P; }"), + } + for _, src := range accepted { + t.Run(src, func(t *testing.T) { + if got := mbViolations(t, src, "MDL129"); len(got) != 0 { + t.Errorf("control reported %q", got) + } + }) + } +} + +// f81: an operation path naming a parameter its microflow does not have — +// CE1613 or CE0352. The match is case-sensitive. +func TestPublishedRestPathParameters(t *testing.T) { + reported := []struct{ name, src, want string }{ + {"no such parameter", prsService("rest/x/v1", "resource 'items' { get '{id}' microflow PRS.P; }"), "names the path parameter {id}"}, + {"other case", prsService("rest/x/v1", "resource 'items' { get '{Id}' microflow PRS.Q; }"), "names the path parameter {Id}"}, + {"second parameter", prsService("rest/x/v1", "resource 'items' { get '{a}/{b}' microflow PRS.Q; }"), "names the path parameter {b}"}, + } + for _, c := range reported { + t.Run(c.name, func(t *testing.T) { + if got := wfgCheck(t, c.src); !strings.Contains(got, c.want) { + t.Errorf("check -p must report %q, reported:\n%s", c.want, got) + } + }) + } + if got := wfgCheck(t, prsService("rest/x/v1", "resource 'items' { get '{id}' microflow PRS.Q; get '{id}/{a}' microflow PRS.Q; }")); got != "" { + t.Errorf("control must pass check -p, reported:\n%s", got) + } +} + +const outcomeFlows = `create microflow WFG.ME () returns enum WFG.Color as $R begin return WFG.Color.Red; end; +create microflow WFG.MB () returns Boolean as $R begin return true; end; +create microflow WFG.MV () begin log info node 'x' 'y'; end;` + +// The outcomes must be exactly the result's values (CE6686); an enumeration +// outcome that is not a value is CE1613. +func TestWorkflowOutcomeSets(t *testing.T) { + const red, blue, green, empty = "'WFG.Color.Red' -> { } ", "'WFG.Color.Blue' -> { } ", "'WFG.Color.Green' -> { } ", "'' -> { } " + const tr, fa, def = "true -> { } ", "false -> { } ", "default -> { } " + reported := []struct{ name, body, want string }{ + {"boolean call, true only", "call microflow WFG.MB outcomes " + tr + ";", "false is missing"}, + {"boolean call, enumeration outcomes", "call microflow WFG.MB outcomes " + red + empty + ";", "not enumeration values"}, + {"enumeration call, no outcomes", "call microflow WFG.ME;", "has no outcomes"}, + {"enumeration call, boolean outcomes", "call microflow WFG.ME outcomes " + tr + fa + ";", "not true and false"}, + {"enumeration call, value missing", "call microflow WFG.ME outcomes " + red + empty + ";", "leave out 'WFG.Color.Blue'"}, + {"enumeration call, default for a value", "call microflow WFG.ME outcomes " + red + empty + def + ";", "leave out 'WFG.Color.Blue'"}, + {"enumeration call, unknown value", "call microflow WFG.ME outcomes " + red + blue + green + empty + ";", "CE1613"}, + {"void call, outcomes", "call microflow WFG.MV outcomes " + tr + fa + ";", "returns nothing"}, + {"boolean decision, no outcomes", "decision $WorkflowContext/B;", "this decision has none"}, + {"boolean decision, true only", "decision $WorkflowContext/B outcomes " + tr + ";", "false is missing"}, + {"enumeration decision, no outcomes", "decision $WorkflowContext/C;", "has no outcomes"}, + {"enumeration decision, value missing", "decision $WorkflowContext/C outcomes " + red + empty + ";", "leave out 'WFG.Color.Blue'"}, + {"enumeration decision, unknown value", "decision $WorkflowContext/C outcomes " + red + blue + green + empty + ";", "CE1613"}, + } + for _, c := range reported { + t.Run(c.name, func(t *testing.T) { + if got := wfgCheck(t, wfgHead+wfgFlow(outcomeFlows, c.body)); !strings.Contains(got, c.want) { + t.Errorf("check -p must report %q, reported:\n%s", c.want, got) + } + }) + } + accepted := []string{ + "call microflow WFG.MB;", + "call microflow WFG.MB outcomes " + tr + fa + ";", + "call microflow WFG.ME outcomes " + red + empty + blue + ";", + "call microflow WFG.ME outcomes " + red + empty + blue + def + ";", + "call microflow WFG.MV;", + "decision $WorkflowContext/C outcomes " + red + empty + blue + ";", + "decision $WorkflowContext/B outcomes " + tr + fa + ";", + } + for _, body := range accepted { + t.Run(body, func(t *testing.T) { + if got := wfgCheck(t, wfgHead+wfgFlow(outcomeFlows, body)); got != "" { + t.Errorf("control must pass check -p, reported:\n%s", got) + } + }) + } +} diff --git a/mdl/executor/cmd_associations.go b/mdl/executor/cmd_associations.go index 26319c2371..44cabad8cd 100644 --- a/mdl/executor/cmd_associations.go +++ b/mdl/executor/cmd_associations.go @@ -139,7 +139,12 @@ func execCreateAssociation(ctx *ExecContext, s *ast.CreateAssociationStmt) error if s.Storage != ast.StorageDefault { assoc.StorageFormat = storageFormat } - assoc.ChildDeleteBehavior = &domainmodel.DeleteBehavior{Type: deleteBehavior, ErrorMessage: deleteMessage, ErrorMessageLanguage: deleteLang} + // Unstated keeps the stored behaviour and its message: a + // statement written to set documentation reset a restrict + // to keep-references and dropped the message (#2713). + if s.DeleteBehaviorSet { + assoc.ChildDeleteBehavior = &domainmodel.DeleteBehavior{Type: deleteBehavior, ErrorMessage: deleteMessage, ErrorMessageLanguage: deleteLang} + } assoc.Documentation = carriedDocumentation( associationDocumentationStated(s), associationDocumentation(s), assoc.Documentation) if s.ExportLevel != nil { // absent keeps the stored level (#1498) @@ -170,7 +175,9 @@ func execCreateAssociation(ctx *ExecContext, s *ast.CreateAssociationStmt) error if s.Storage != ast.StorageDefault { // as above (#704) ca.StorageFormat = storageFormat } - ca.ChildDeleteBehavior = &domainmodel.DeleteBehavior{Type: deleteBehavior, ErrorMessage: deleteMessage, ErrorMessageLanguage: deleteLang} + if s.DeleteBehaviorSet { // as above (#2713) + ca.ChildDeleteBehavior = &domainmodel.DeleteBehavior{Type: deleteBehavior, ErrorMessage: deleteMessage, ErrorMessageLanguage: deleteLang} + } ca.ChildRef = childRef ca.Documentation = carriedDocumentation( associationDocumentationStated(s), associationDocumentation(s), ca.Documentation) diff --git a/mdl/executor/cmd_associations_delete_behavior_test.go b/mdl/executor/cmd_associations_delete_behavior_test.go index 8e11a7e524..5468677829 100644 --- a/mdl/executor/cmd_associations_delete_behavior_test.go +++ b/mdl/executor/cmd_associations_delete_behavior_test.go @@ -47,12 +47,13 @@ func TestAssociationDeleteBehaviorReachesStorageAsAMendixValue(t *testing.T) { t.Run("create-or-modify/"+tc.name, func(t *testing.T) { ctx, assoc := assocFixture(t) assertNoError(t, execCreateAssociation(ctx, &ast.CreateAssociationStmt{ - Name: ast.QualifiedName{Module: "M", Name: "Child_Parent"}, - Parent: ast.QualifiedName{Module: "M", Name: "Child"}, - Child: ast.QualifiedName{Module: "M", Name: "Parent"}, - Type: ast.AssocReference, - DeleteBehavior: tc.in, - CreateOrModify: true, + Name: ast.QualifiedName{Module: "M", Name: "Child_Parent"}, + Parent: ast.QualifiedName{Module: "M", Name: "Child"}, + Child: ast.QualifiedName{Module: "M", Name: "Parent"}, + Type: ast.AssocReference, + DeleteBehavior: tc.in, + DeleteBehaviorSet: true, + CreateOrModify: true, })) assertStoredBehavior(t, assoc, tc.want) }) @@ -86,12 +87,13 @@ func TestDescribeAssociationDeleteBehaviorRoundTripsThroughTheParser(t *testing. t.Run(want.String(), func(t *testing.T) { ctx, assoc := assocFixture(t) assertNoError(t, execCreateAssociation(ctx, &ast.CreateAssociationStmt{ - Name: ast.QualifiedName{Module: "M", Name: "Child_Parent"}, - Parent: ast.QualifiedName{Module: "M", Name: "Child"}, - Child: ast.QualifiedName{Module: "M", Name: "Parent"}, - Type: ast.AssocReference, - DeleteBehavior: want, - CreateOrModify: true, + Name: ast.QualifiedName{Module: "M", Name: "Child_Parent"}, + Parent: ast.QualifiedName{Module: "M", Name: "Child"}, + Child: ast.QualifiedName{Module: "M", Name: "Parent"}, + Type: ast.AssocReference, + DeleteBehavior: want, + DeleteBehaviorSet: true, + CreateOrModify: true, })) _ = assoc @@ -184,6 +186,7 @@ func TestDescribeAssociation_RoundTripsTheDeleteErrorMessage(t *testing.T) { Child: ast.QualifiedName{Module: "M", Name: "Parent"}, Type: ast.AssocReference, DeleteBehavior: ast.DeleteIfNoReferences, + DeleteBehaviorSet: true, DeleteErrorMessage: msg, CreateOrModify: true, })) @@ -210,12 +213,13 @@ func TestDescribeAssociation_RoundTripsTheDeleteErrorMessage(t *testing.T) { func TestDescribeAssociation_NoMessageEmitsNoClause(t *testing.T) { ctx, _ := assocFixture(t) assertNoError(t, execCreateAssociation(ctx, &ast.CreateAssociationStmt{ - Name: ast.QualifiedName{Module: "M", Name: "Child_Parent"}, - Parent: ast.QualifiedName{Module: "M", Name: "Child"}, - Child: ast.QualifiedName{Module: "M", Name: "Parent"}, - Type: ast.AssocReference, - DeleteBehavior: ast.DeleteCascade, - CreateOrModify: true, + Name: ast.QualifiedName{Module: "M", Name: "Child_Parent"}, + Parent: ast.QualifiedName{Module: "M", Name: "Child"}, + Child: ast.QualifiedName{Module: "M", Name: "Parent"}, + Type: ast.AssocReference, + DeleteBehavior: ast.DeleteCascade, + DeleteBehaviorSet: true, + CreateOrModify: true, })) var buf bytes.Buffer @@ -225,3 +229,47 @@ func TestDescribeAssociation_NoMessageEmitsNoClause(t *testing.T) { t.Errorf("emitted an ERROR_MESSAGE clause for a cascade:\n%s", buf.String()) } } + +// #2713: `create or modify association` with no delete clause reset the stored +// behaviour to DeleteMeButKeepReferences and dropped its error message — the +// statement the reporter wrote only to set documentation. An unstated delete +// behaviour keeps what is stored, the way unstated storage (#704) and export +// level (#1498) already do. +func TestCreateOrModifyAssociation_UnstatedDeleteBehaviourKeepsTheStoredOne(t *testing.T) { + const msg = "A customer with orders cannot be deleted" + ctx, assoc := assocFixture(t) + assoc.ChildDeleteBehavior = &domainmodel.DeleteBehavior{ + Type: domainmodel.DeleteBehaviorTypeDeleteMeIfNoReferences, + ErrorMessage: msg, + ErrorMessageLanguage: "en_US", + } + assertNoError(t, execCreateAssociation(ctx, &ast.CreateAssociationStmt{ + Name: ast.QualifiedName{Module: "M", Name: "Child_Parent"}, + Parent: ast.QualifiedName{Module: "M", Name: "Child"}, + Child: ast.QualifiedName{Module: "M", Name: "Parent"}, + Type: ast.AssocReference, + Documentation: "doc", + DocumentationSet: true, + CreateOrModify: true, + })) + assertStoredBehavior(t, assoc, domainmodel.DeleteBehaviorTypeDeleteMeIfNoReferences) + if got := assoc.ChildDeleteBehavior.ErrorMessage; got != msg { + t.Errorf("error message = %q, want %q (kept)", got, msg) + } +} + +// CONTROL: a stated behaviour still replaces the stored one — the fix must +// gate on the clause being present, not stop writing the behaviour at all. +func TestCreateOrModifyAssociation_StatedDeleteBehaviourReplacesTheStoredOne(t *testing.T) { + ctx, assoc := assocFixture(t) // stored: cascade + assertNoError(t, execCreateAssociation(ctx, &ast.CreateAssociationStmt{ + Name: ast.QualifiedName{Module: "M", Name: "Child_Parent"}, + Parent: ast.QualifiedName{Module: "M", Name: "Child"}, + Child: ast.QualifiedName{Module: "M", Name: "Parent"}, + Type: ast.AssocReference, + DeleteBehavior: ast.DeleteKeepReferences, + DeleteBehaviorSet: true, + CreateOrModify: true, + })) + assertStoredBehavior(t, assoc, domainmodel.DeleteBehaviorTypeDeleteMeButKeepReferences) +} diff --git a/mdl/executor/cmd_associations_delete_message_language_test.go b/mdl/executor/cmd_associations_delete_message_language_test.go index 83a79118e3..28a57e1397 100644 --- a/mdl/executor/cmd_associations_delete_message_language_test.go +++ b/mdl/executor/cmd_associations_delete_message_language_test.go @@ -42,6 +42,7 @@ func restrictStmt(msg string, createOrModify bool) *ast.CreateAssociationStmt { Child: ast.QualifiedName{Module: "M", Name: "Parent"}, Type: ast.AssocReference, DeleteBehavior: ast.DeleteIfNoReferences, + DeleteBehaviorSet: true, DeleteErrorMessage: msg, CreateOrModify: createOrModify, } diff --git a/mdl/executor/cmd_contract.go b/mdl/executor/cmd_contract.go index 5c7b31cfb8..aa8a657ccd 100644 --- a/mdl/executor/cmd_contract.go +++ b/mdl/executor/cmd_contract.go @@ -499,16 +499,8 @@ func createExternalEntities(ctx *ExecContext, s *ast.CreateExternalEntitiesStmt) // Build entity set lookup: entity type qualified name → entity set name esMap := make(map[string]string) - esByType := make(map[string]*types.EdmEntitySet) for _, es := range doc.EntitySets { esMap[es.EntityType] = es.Name - esByType[es.EntityType] = es - } - - // Build filter set if entity names specified - filterSet := make(map[string]bool) - for _, name := range s.EntityNames { - filterSet[strings.ToLower(name)] = true } // Determine target module @@ -555,68 +547,46 @@ func createExternalEntities(ctx *ExecContext, s *ast.CreateExternalEntitiesStmt) // referencing them failed to build (mendixlabs/mxcli#1118). var dropped []string - for _, schema := range doc.Schemas { - for _, et := range schema.EntityTypes { - entitySet := esByType[schema.Namespace+"."+et.Name] - entitySetName := "" - if entitySet != nil { - entitySetName = entitySet.Name - } - isTopLevel := entitySetName != "" - - // Mendix entity name: the entity TYPE name, as Studio Pro names it - // ("Part" for entity set "Parts", "Person" for "People"). Naming it - // after the set broke every script written against Studio Pro's name - // (mendixlabs/mxcli#1432). An entity an older mxcli imported under - // the set name is still found, by its remote identity, and keeps the - // name pages and microflows already use. - existingEntity := importedEntityFor(dm, serviceRef, entitySetName, et.Name) - mendixName := et.Name - if existingEntity != nil { - mendixName = existingEntity.Name - } - - // Apply entity name filter (matched against type name OR entity set name) - if len(filterSet) > 0 && !filterSet[strings.ToLower(et.Name)] && !filterSet[strings.ToLower(entitySetName)] { + for _, sel := range bulkImportSelection(doc, s.EntityNames) { + et, entitySet, entitySetName := sel.et, sel.entitySet, sel.entitySetName + isTopLevel := entitySetName != "" + existingEntity, mendixName := sel.mendixName(dm, serviceRef) + + parts := contractEntityAttributes(ctx, doc, et, typeByQualified, entitySet, isTopLevel, mendixName, module.ID, targetModule, serviceRef, odataEnums) + dropped = append(dropped, parts.dropped...) + renamed = append(renamed, parts.renamed...) + attrs, keyParts := parts.attrs, parts.keyParts + if existingEntity != nil { + if !s.CreateOrModify { + fmt.Fprintf(ctx.Output, " SKIPPED: %s.%s (already exists; use create or modify to update)\n", targetModule, mendixName) + skipped++ continue } - - parts := contractEntityAttributes(ctx, doc, et, typeByQualified, entitySet, isTopLevel, mendixName, module.ID, targetModule, serviceRef, odataEnums) - dropped = append(dropped, parts.dropped...) - renamed = append(renamed, parts.renamed...) - attrs, keyParts := parts.attrs, parts.keyParts - if existingEntity != nil { - if !s.CreateOrModify { - fmt.Fprintf(ctx.Output, " SKIPPED: %s.%s (already exists; use create or modify to update)\n", targetModule, mendixName) - skipped++ - continue - } - applyExternalEntityFields(existingEntity, et, isTopLevel, serviceRef, entitySet, keyParts, attrs) - if err := ctx.Backend.UpdateEntity(dm.ID, existingEntity); err != nil { - fmt.Fprintf(ctx.Output, " FAILED: %s.%s — %v\n", targetModule, mendixName, err) - failed++ - continue - } - updated++ - continue - } - - newEntity := &domainmodel.Entity{Name: mendixName} - newEntity.ID = model.ID(types.GenerateID()) - applyExternalEntityFields(newEntity, et, isTopLevel, serviceRef, entitySet, keyParts, attrs) - // Placed against everything already in the module, including the - // entities this import has just created. The old formula counted only - // this run's entities, so an import into a populated module stacked - // its first entity on whatever sat at (100, 100) (#1479). - newEntity.Location = dmlayout.Place(placed, newEntity) - if err := ctx.Backend.CreateEntity(dm.ID, newEntity); err != nil { + applyExternalEntityFields(existingEntity, et, isTopLevel, serviceRef, entitySet, keyParts, attrs) + if err := ctx.Backend.UpdateEntity(dm.ID, existingEntity); err != nil { fmt.Fprintf(ctx.Output, " FAILED: %s.%s — %v\n", targetModule, mendixName, err) failed++ continue } - placed.Entities = append(placed.Entities, newEntity) - created++ + updated++ + continue } + + newEntity := &domainmodel.Entity{Name: mendixName} + newEntity.ID = model.ID(types.GenerateID()) + applyExternalEntityFields(newEntity, et, isTopLevel, serviceRef, entitySet, keyParts, attrs) + // Placed against everything already in the module, including the + // entities this import has just created. The old formula counted only + // this run's entities, so an import into a populated module stacked + // its first entity on whatever sat at (100, 100) (#1479). + newEntity.Location = dmlayout.Place(placed, newEntity) + if err := ctx.Backend.CreateEntity(dm.ID, newEntity); err != nil { + fmt.Fprintf(ctx.Output, " FAILED: %s.%s — %v\n", targetModule, mendixName, err) + failed++ + continue + } + placed.Entities = append(placed.Entities, newEntity) + created++ } // Second pass: create primitive-collection NPEs (e.g. TripTag for @@ -841,6 +811,62 @@ func importedEntityFor(dm *domainmodel.DomainModel, serviceRef, entitySetName, t return findEntityByName(dm, typeName) } +// bulkImportType is one entity type a `create external entities` imports: +// the type, and its entity set (nil for a type with none). +type bulkImportType struct { + et *types.EdmEntityType + entitySet *types.EdmEntitySet + entitySetName string +} + +// bulkImportSelection lists, in contract order, the entity types a +// `create external entities … [entities (…)]` imports: every type in the +// contract, or those whose type or entity set name the filter lists. The +// executor imports exactly these, and the reference check registers exactly +// these (ako/mxcli#2674), so the two cannot disagree on what the import makes. +func bulkImportSelection(doc *types.EdmxDocument, names []string) []bulkImportType { + esByType := make(map[string]*types.EdmEntitySet) + for _, es := range doc.EntitySets { + esByType[es.EntityType] = es + } + filterSet := make(map[string]bool) + for _, name := range names { + filterSet[strings.ToLower(name)] = true + } + var out []bulkImportType + for _, schema := range doc.Schemas { + for _, et := range schema.EntityTypes { + sel := bulkImportType{et: et, entitySet: esByType[schema.Namespace+"."+et.Name]} + if sel.entitySet != nil { + sel.entitySetName = sel.entitySet.Name + } + // The filter matches the type name OR the entity set name. + if len(filterSet) > 0 && !filterSet[strings.ToLower(et.Name)] && !filterSet[strings.ToLower(sel.entitySetName)] { + continue + } + out = append(out, sel) + } + } + return out +} + +// mendixName is the name the import gives the entity, and the stored entity +// it updates, if any. The entity TYPE name, as Studio Pro names it ("Part" for +// entity set "Parts", "Person" for "People"); naming it after the set broke +// every script written against Studio Pro's name (mendixlabs/mxcli#1432). An +// entity an older mxcli imported under the set name is still found, by its +// remote identity, and keeps the name pages and microflows already use. dm may +// be nil: a module the script has yet to create holds nothing to find. +func (sel bulkImportType) mendixName(dm *domainmodel.DomainModel, serviceRef string) (*domainmodel.Entity, string) { + if dm == nil { + return nil, sel.et.Name + } + if existing := importedEntityFor(dm, serviceRef, sel.entitySetName, sel.et.Name); existing != nil { + return existing, existing.Name + } + return nil, sel.et.Name +} + // findEntityByName returns a domain model entity by name, or nil if not found. func findEntityByName(dm *domainmodel.DomainModel, name string) *domainmodel.Entity { for _, ent := range dm.Entities { diff --git a/mdl/executor/cmd_microflows_builder.go b/mdl/executor/cmd_microflows_builder.go index 34d75e70f7..96f43d444b 100644 --- a/mdl/executor/cmd_microflows_builder.go +++ b/mdl/executor/cmd_microflows_builder.go @@ -102,14 +102,7 @@ type flowBuilder struct { // default, which is the layout mxcli has always drawn. layout *flowLayout nextConnectionPoint model.ID // For compound statements: the exit point differs from entry point - // incomingRedirect, when set, instructs the next enclosing flow emission to - // terminate at this merge/activity ID instead of the most recently emitted - // activity. Used by retry-loop error handlers (where a merge is inserted - // before the source activity so the normal inbound flow enters the merge - // and the error-handler tail loops back to the same merge). Cleared after - // the outer loop consumes it for the next flow. - incomingRedirect model.ID - nextFlowCase string // If set, next connecting flow uses this case value (for merge-less splits) + nextFlowCase string // If set, next connecting flow uses this case value (for merge-less splits) // nextFlowAnchor carries the branch-specific FlowAnchors that should be // applied to the flow created by the NEXT iteration of buildFlowGraph. // Used by guard-pattern IFs (where one branch returns and the other diff --git a/mdl/executor/cmd_microflows_builder_flows.go b/mdl/executor/cmd_microflows_builder_flows.go index 5469894452..981165a1cc 100644 --- a/mdl/executor/cmd_microflows_builder_flows.go +++ b/mdl/executor/cmd_microflows_builder_flows.go @@ -150,15 +150,11 @@ func (fb *flowBuilder) finishCustomErrorHandler(activityID model.ID, activityX i fb.rejoinMergeAt[activityID] = ann.Merge } if len(eh.Body) > 0 { - // Retry-loop pattern: error body ends with an IF whose non-terminating - // branch should loop back to the source activity (Studio Pro authors - // this as a merge placed before the source, with the handler tail - // returning to that merge). MDL cannot express the loop-back directly, - // so we detect the shape and wire the topology ourselves. - if isRetryLoopErrorHandler(eh.Body) { - fb.buildRetryLoopErrorHandler(activityID, activityX, eh.Body) - return - } + // A handler that does not end in RETURN/RAISE ERROR rejoins after the + // activity, whatever its last statement is. An IF with one terminating + // branch used to be wired as an implicit retry loop back in front of + // the activity (#507), which nothing in the source asked for; a retry + // is written with `merge`/`join` (ako/mxcli#2733). mergeID := fb.addErrorHandlerFlow(activityID, activityX, eh.Body) if mergeID.id != "" { fb.rejoinAfterRow(eh, activityID, activityX) @@ -169,99 +165,6 @@ func (fb *flowBuilder) finishCustomErrorHandler(activityID model.ID, activityX i fb.registerEmptyCustomErrorHandlerWithSkip(activityID, eh, outputVar) } -// isRetryLoopErrorHandler reports whether the error-handler body looks like -// a retry loop: the last statement is an IF whose else branch terminates -// (via RAISE ERROR or RETURN) and whose then branch continues. That shape -// mirrors the Studio Pro retry pattern where the non-terminating branch -// loops back to the source activity to re-attempt it. -func isRetryLoopErrorHandler(body []ast.MicroflowStatement) bool { - if len(body) == 0 { - return false - } - ifStmt, ok := body[len(body)-1].(*ast.IfStmt) - if !ok { - return false - } - if len(ifStmt.ThenBody) == 0 || len(ifStmt.ElseBody) == 0 { - return false - } - thenTerminates := bodyTerminates(ifStmt.ThenBody) - elseTerminates := bodyTerminates(ifStmt.ElseBody) - // Exactly one branch must terminate (the "error" branch) and one must - // continue (the "retry" branch). If both or neither terminate, the shape - // is some other IF and the standard merge-forward path still applies. - return thenTerminates != elseTerminates -} - -// bodyTerminates reports whether a statement body ends with a terminator -// (RAISE ERROR, RETURN, or nested IF where every branch terminates). -func bodyTerminates(body []ast.MicroflowStatement) bool { - if len(body) == 0 { - return false - } - last := body[len(body)-1] - switch s := last.(type) { - case *ast.RaiseErrorStmt: - return true - case *ast.ReturnStmt: - return true - case *ast.IfStmt: - if len(s.ElseBody) == 0 { - return false - } - return bodyTerminates(s.ThenBody) && bodyTerminates(s.ElseBody) - } - return false -} - -// buildRetryLoopErrorHandler wires a retry-loop topology for an error handler -// whose body ends with a terminating/continuing IF. The non-terminating -// branch's tail loops back to a new merge placed before the source activity; -// the merge then feeds into the source. The outer loop consumes -// fb.incomingRedirect so the normal inbound flow also terminates at the -// merge instead of directly at the source. -func (fb *flowBuilder) buildRetryLoopErrorHandler(sourceActivityID model.ID, sourceX int, errorBody []ast.MicroflowStatement) { - // Build the handler activities with tracking of where the non-terminating - // branch's tail ends up. We reuse addErrorHandlerFlow; it returns the tail - // that would have forwarded to the next main-path activity. For a retry - // loop, that tail is the continue-branch exit of the trailing IF. - tail := fb.addErrorHandlerFlow(sourceActivityID, sourceX, errorBody) - if tail.id == "" { - // The handler terminates unexpectedly — nothing to loop back. - return - } - - // Insert a merge just left of the source activity, on the main flow row. - merge := µflows.ExclusiveMerge{ - BaseMicroflowObject: microflows.BaseMicroflowObject{ - BaseElement: model.BaseElement{ID: model.ID(types.GenerateID())}, - Position: model.Point{X: sourceX - fb.spacing/2, Y: fb.baseY}, - Size: model.Size{Width: MergeSize, Height: MergeSize}, - }, - } - fb.objects = append(fb.objects, merge) - - // Merge -> source (normal flow into the REST/microflow call) - fb.flows = append(fb.flows, newHorizontalFlow(merge.ID, sourceActivityID)) - - // Handler tail -> merge (loop-back). Authored Studio Pro flows mark this - // edge as a normal SequenceFlow (not IsErrorHandler) — the error flow - // marker only applies to the SOURCE → first-handler-activity edge, which - // addErrorHandlerFlow already emitted. Using a plain horizontal flow here - // avoids triggering spurious CE0136/CE0019 diagnostics that fire when a - // retrieve's start variable is deemed to flow through an error edge. - loopFlow := newHorizontalFlow(tail.id, merge.ID) - if tail.caseValue != "" { - applyDeferredFlowCase(loopFlow, tail.caseValue, tail.flowAnchor) - } else if tail.flowAnchor != nil { - applyDeferredFlowCase(loopFlow, "", tail.flowAnchor) - } - fb.flows = append(fb.flows, loopFlow) - - // Next inbound normal flow must terminate at the merge, not at the source. - fb.incomingRedirect = merge.ID -} - func (fb *flowBuilder) registerEmptyCustomErrorHandlerWithSkip(activityID model.ID, eh *ast.ErrorHandlingClause, skipVar string) { if !isEmptyCustomErrorHandler(eh) { return diff --git a/mdl/executor/cmd_microflows_builder_graph.go b/mdl/executor/cmd_microflows_builder_graph.go index 5f91977909..bb214a4493 100644 --- a/mdl/executor/cmd_microflows_builder_graph.go +++ b/mdl/executor/cmd_microflows_builder_graph.go @@ -143,14 +143,7 @@ func (fb *flowBuilder) buildFlowGraph(stmts []ast.MicroflowStatement, returns *a if activityID != "" { fb.applyPendingAnnotations(activityID) // Connect to previous object with horizontal SequenceFlow. - // When incomingRedirect is set (retry-loop error handler built a - // merge before the activity), the inbound flow terminates at the - // merge instead of the activity itself. inboundTarget := activityID - if fb.incomingRedirect != "" { - inboundTarget = fb.incomingRedirect - fb.incomingRedirect = "" - } var flow *microflows.SequenceFlow if pendingCase != "" { flow = newHorizontalFlowWithCase(lastID, inboundTarget, pendingCase) diff --git a/mdl/executor/cmd_microflows_builder_nested_test.go b/mdl/executor/cmd_microflows_builder_nested_test.go index 93a7e4dfb0..7d57db0f72 100644 --- a/mdl/executor/cmd_microflows_builder_nested_test.go +++ b/mdl/executor/cmd_microflows_builder_nested_test.go @@ -51,7 +51,7 @@ var nestedBuilderInherits = map[string]bool{ "lastReturnEndID": false, "returnValue": false, // Per-statement pending state. - "nextConnectionPoint": false, "incomingRedirect": false, "nextFlowCase": false, + "nextConnectionPoint": false, "nextFlowCase": false, "nextFlowAnchor": false, "atBodyTail": false, "pendingAnnotations": false, "previousStmtAnchor": false, "manualLoopBackTarget": false, "pendingJoin": false, "emptyErrorHandlerFrom": false, "errorHandlerTailFrom": false, "errorHandlerSource": false, diff --git a/mdl/executor/cmd_microflows_retry_loop_test.go b/mdl/executor/cmd_microflows_retry_loop_test.go index d2a1362cbb..6f0b1eec17 100644 --- a/mdl/executor/cmd_microflows_retry_loop_test.go +++ b/mdl/executor/cmd_microflows_retry_loop_test.go @@ -10,143 +10,107 @@ import ( "github.com/mendixlabs/mxcli/sdk/microflows" ) -// Retry-loop error handler: a call activity with a custom error handler -// whose body ends with an IF where the ELSE raises and the THEN performs -// retry actions must produce a merge placed before the source activity, -// with the handler tail looping back to the merge. Without this topology -// the merge falls after the source and subsequent activities referencing -// the call's output variable trigger CE0108 "variable not in scope". -func TestRetryLoopErrorHandlerLoopsBackToSource(t *testing.T) { - fb := &flowBuilder{ - spacing: HorizontalSpacing, - measurer: &layoutMeasurer{}, - declaredVars: map[string]string{"R": "String", "RetryCount": "Integer"}, - } - - oc := fb.buildFlowGraph([]ast.MicroflowStatement{ - &ast.DeclareStmt{ - Variable: "RetryCount", - Type: ast.DataType{Kind: ast.TypeInteger}, - InitialValue: &ast.LiteralExpr{Kind: ast.LiteralInteger, Value: "0"}, - }, - &ast.CallMicroflowStmt{ - MicroflowName: ast.QualifiedName{Module: "M", Name: "Fetch"}, - OutputVariable: "R", - ErrorHandling: &ast.ErrorHandlingClause{ - Type: ast.ErrorHandlingCustomWithoutRollback, - Body: []ast.MicroflowStatement{ - &ast.LogStmt{Level: ast.LogError, Message: &ast.LiteralExpr{Kind: ast.LiteralString, Value: "fetch failed"}}, - &ast.IfStmt{ - Condition: &ast.BinaryExpr{ - Operator: "<", - Left: &ast.VariableExpr{Name: "RetryCount"}, - Right: &ast.LiteralExpr{Kind: ast.LiteralInteger, Value: "3"}, - }, - ThenBody: []ast.MicroflowStatement{ - &ast.MfSetStmt{ - Target: "RetryCount", - Value: &ast.BinaryExpr{ - Operator: "+", +// ako/mxcli#2733 (upstream mendixlabs/mxcli#2007). A handler whose body ends in +// an IF with one terminating branch used to be wired as a retry loop: the other +// branch looped back to a merge placed in front of the call, so the call ran +// again for as long as it kept failing. Nothing in the source asked for a loop; +// the syntax help says a handler that does not end in RETURN/RAISE ERROR +// rejoins at the statement after the failing activity, and a retry is written +// with `merge`/`join` (TestMergeJoin_BackwardReferenceBuildsRetryLoop). One +// statement after the `end if` already switched the loop off. +func TestErrorHandlerEndingInOneSidedIfRejoinsAfterTheActivity(t *testing.T) { + for name, terminator := range map[string]ast.MicroflowStatement{ + "raise error": &ast.RaiseErrorStmt{}, + "return false": &ast.ReturnStmt{Value: &ast.LiteralExpr{Kind: ast.LiteralBoolean, Value: false}}, + } { + t.Run(name, func(t *testing.T) { + fb := &flowBuilder{ + spacing: HorizontalSpacing, + measurer: &layoutMeasurer{}, + declaredVars: map[string]string{"R": "String", "RetryCount": "Integer"}, + } + oc := fb.buildFlowGraph([]ast.MicroflowStatement{ + &ast.DeclareStmt{ + Variable: "RetryCount", + Type: ast.DataType{Kind: ast.TypeInteger}, + InitialValue: &ast.LiteralExpr{Kind: ast.LiteralInteger, Value: "0"}, + }, + &ast.CallMicroflowStmt{ + MicroflowName: ast.QualifiedName{Module: "M", Name: "Fetch"}, + OutputVariable: "R", + ErrorHandling: &ast.ErrorHandlingClause{ + Type: ast.ErrorHandlingCustomWithoutRollback, + Body: []ast.MicroflowStatement{ + &ast.IfStmt{ + Condition: &ast.BinaryExpr{ + Operator: "<", Left: &ast.VariableExpr{Name: "RetryCount"}, - Right: &ast.LiteralExpr{Kind: ast.LiteralInteger, Value: "1"}, + Right: &ast.LiteralExpr{Kind: ast.LiteralInteger, Value: "3"}, + }, + ThenBody: []ast.MicroflowStatement{ + &ast.MfSetStmt{ + Target: "RetryCount", + Value: &ast.LiteralExpr{Kind: ast.LiteralInteger, Value: "1"}, + }, }, + ElseBody: []ast.MicroflowStatement{terminator}, }, }, - ElseBody: []ast.MicroflowStatement{ - &ast.RaiseErrorStmt{}, - }, }, }, - }, - }, - &ast.LogStmt{Level: ast.LogInfo, Message: &ast.LiteralExpr{Kind: ast.LiteralString, Value: "ok"}}, - &ast.ReturnStmt{}, - }, nil) + &ast.LogStmt{Level: ast.LogInfo, Message: &ast.LiteralExpr{Kind: ast.LiteralString, Value: "ok"}}, + &ast.ReturnStmt{Value: &ast.LiteralExpr{Kind: ast.LiteralBoolean, Value: true}}, + }, nil) - // Find the call activity, the retry-body log/set activities, and the merge. - var callID, logAfterID model.ID - var mergeIDs []model.ID - logSeen := 0 - for _, obj := range oc.Objects { - switch o := obj.(type) { - case *microflows.ActionActivity: - if _, ok := o.Action.(*microflows.MicroflowCallAction); ok { - callID = o.ID - } - if _, ok := o.Action.(*microflows.LogMessageAction); ok { - logSeen++ - // logSeen==1 is the error-handler log inside the handler body. - // logSeen==2 is the main-path log after the call. - if logSeen == 2 { - logAfterID = o.ID + var callID, setID, logID model.ID + kind := map[model.ID]string{} + for _, obj := range oc.Objects { + switch o := obj.(type) { + case *microflows.ActionActivity: + switch o.Action.(type) { + case *microflows.MicroflowCallAction: + callID = o.ID + case *microflows.ChangeVariableAction: + setID = o.ID + case *microflows.LogMessageAction: + logID = o.ID + } + case *microflows.ExclusiveMerge: + kind[o.ID] = "merge" } } - case *microflows.ExclusiveMerge: - mergeIDs = append(mergeIDs, o.ID) - } - } - if callID == "" { - t.Fatal("no call activity found") - } - if logAfterID == "" { - t.Fatal("no post-call log activity found") - } - if len(mergeIDs) == 0 { - t.Fatal("no merge node found — retry-loop topology was not built") - } - - // The merge must sit on the call's inbound path: there must be an edge - // prev->merge (not prev->call) and an edge merge->call. The handler - // tail loops back to the merge as a plain SequenceFlow (not marked - // IsErrorHandler — the error marker applies only to the source→first - // handler activity edge, which addErrorHandlerFlow emits separately). - var mergeToCallFound bool - var prevToMergeFound bool - var tailToMergeFound bool - // Find the retry-branch tail activity (the ChangeVariable that - // increments the retry counter in the test fixture). - var tailID model.ID - for _, obj := range oc.Objects { - if a, ok := obj.(*microflows.ActionActivity); ok { - if _, isChange := a.Action.(*microflows.ChangeVariableAction); isChange { - tailID = a.ID + if callID == "" || setID == "" || logID == "" { + t.Fatalf("missing activity: call %q set %q log %q", callID, setID, logID) } - } - } - for _, f := range oc.Flows { - for _, mID := range mergeIDs { - if f.DestinationID == callID && f.OriginID == mID { - mergeToCallFound = true - } - if f.DestinationID == mID && f.OriginID == tailID && !f.IsErrorHandler { - tailToMergeFound = true - } - if f.DestinationID == mID && !f.IsErrorHandler && f.OriginID != mID && f.OriginID != tailID { - prevToMergeFound = true + next := map[model.ID][]model.ID{} + for _, f := range oc.Flows { + next[f.OriginID] = append(next[f.OriginID], f.DestinationID) + if f.DestinationID == callID && kind[f.OriginID] == "merge" { + t.Errorf("a merge feeds the call: the handler loops back and retries it") + } } - } - // No flow should terminate directly at the call from a non-merge origin. - if f.DestinationID == callID && !f.IsErrorHandler { - originIsMerge := false - for _, mID := range mergeIDs { - if f.OriginID == mID { - originIsMerge = true + // The continuing branch reaches the statement after the call. + seen := map[model.ID]bool{} + var reaches func(model.ID) bool + reaches = func(id model.ID) bool { + if id == logID { + return true + } + if seen[id] || id == callID { + return false } + seen[id] = true + for _, n := range next[id] { + if reaches(n) { + return true + } + } + return false } - if !originIsMerge { - t.Errorf("normal inbound flow to call %s came from non-merge origin %s; retry-loop merge was not inserted", - shortID(callID), shortID(f.OriginID)) + if !reaches(setID) { + t.Errorf("the handler's continuing branch does not reach the statement after the call") } - } - } - if !mergeToCallFound { - t.Error("missing merge -> call flow") - } - if !prevToMergeFound { - t.Error("missing prev -> merge normal flow") - } - if !tailToMergeFound { - t.Error("missing handler-tail -> merge (loop-back) flow") + }) } } diff --git a/mdl/executor/cmd_odata.go b/mdl/executor/cmd_odata.go index 87d9733274..2e834ccaae 100644 --- a/mdl/executor/cmd_odata.go +++ b/mdl/executor/cmd_odata.go @@ -1435,6 +1435,29 @@ func refreshCachedMetadata(ctx *ExecContext, svc *model.ConsumedODataService, st return true } +// alterChangesMetadataURL reports whether an ALTER sets the client's MetadataUrl. +func alterChangesMetadataURL(changes map[string]any) bool { + for key := range changes { + if strings.EqualFold(key, "metadataurl") { + return true + } + } + return false +} + +// printMetadataRefreshHint says that ALTER stored the URL but did not re-read +// $metadata, and names the statements that do (ako/mxcli#2674). ALTER reads like +// the refresh, and a user who took it for one went on to drop the client, which +// deletes its external entities. +func printMetadataRefreshHint(ctx *ExecContext, client string) { + fmt.Fprintf(ctx.Output, + " Note: the cached $metadata was not re-read; ALTER only stores the new URL.\n"+ + " To refresh the contract and update the external entities in place, run:\n"+ + " create or modify consumed odata service %[1]s (...); -- describe consumed odata service %[1]s prints it\n"+ + " create or modify external entities from %[1]s;\n", + client) +} + // alterODataClient handles ALTER ODATA CLIENT command. func alterODataClient(ctx *ExecContext, stmt *ast.AlterODataClientStmt) error { @@ -1524,6 +1547,9 @@ func alterODataClient(ctx *ExecContext, stmt *ast.AlterODataClientStmt) error { } invalidateHierarchy(ctx) fmt.Fprintf(ctx.Output, "Altered OData client: %s.%s\n", modName, svc.Name) + if alterChangesMetadataURL(stmt.Changes) { + printMetadataRefreshHint(ctx, modName+"."+svc.Name) + } return nil } } @@ -1552,27 +1578,14 @@ func dropODataClient(ctx *ExecContext, stmt *ast.DropODataClientStmt) error { modID := h.FindModuleID(svc.ContainerID) modName := h.GetModuleName(modID) if strings.EqualFold(modName, stmt.Name.Module) && strings.EqualFold(svc.Name, stmt.Name.Name) { - // Cascade: delete external entities belonging to this service so that - // DeleteEntity can clean up any associations referencing them. + // Cascade: an external entity cannot exist without its client, so + // its entities go with it — in every module, not only the client's + // own (`into` imports them elsewhere), and through the same steps + // `drop entity` takes, listed one by one (ako/mxcli#2674). serviceRef := modName + "." + svc.Name - module, findErr := findModule(ctx, stmt.Name.Module) - if findErr != nil { - return findErr - } - dm, dmErr := ctx.Backend.GetDomainModel(module.ID) - if dmErr != nil { - return mdlerrors.NewBackend("get domain model for cascade", dmErr) - } - var externalEntityIDs []model.ID - for _, entity := range dm.Entities { - if strings.EqualFold(entity.RemoteServiceName, serviceRef) { - externalEntityIDs = append(externalEntityIDs, entity.ID) - } - } - for _, entityID := range externalEntityIDs { - if err := ctx.Backend.DeleteEntity(dm.ID, entityID); err != nil { - return mdlerrors.NewBackend("cascade delete external entity", err) - } + dropped, err := dropClientExternalEntities(ctx, serviceRef) + if err != nil { + return err } if err := ctx.Backend.DeleteConsumedODataService(svc.ID); err != nil { @@ -1580,6 +1593,11 @@ func dropODataClient(ctx *ExecContext, stmt *ast.DropODataClientStmt) error { } invalidateHierarchy(ctx) fmt.Fprintf(ctx.Output, "Dropped OData client: %s.%s\n", modName, svc.Name) + if dropped > 0 { + fmt.Fprintf(ctx.Output, "hint: dropping a client is not how its contract is refreshed — "+ + "`create or modify consumed odata service %s (...)` re-reads $metadata, then "+ + "`create or modify external entities from %s` updates the entities in place.\n", serviceRef, serviceRef) + } return nil } } @@ -2834,3 +2852,119 @@ func printPublishedMicroflowMDL(w io.Writer, pm *model.PublishedMicroflow) { } fmt.Fprintf(w, " expose ( %s );\n", strings.Join(parts, ", ")) } + +// clientExternalEntity is one external entity imported from a consumed OData +// service, found in whichever module's domain model holds it. +type clientExternalEntity struct { + dm *domainmodel.DomainModel + module string + entity *domainmodel.Entity +} + +func (e clientExternalEntity) qualifiedName() string { return e.module + "." + e.entity.Name } + +// dropClientExternalEntities drops every external entity whose +// RemoteServiceName is serviceRef, in every module, the way `drop entity` +// drops one: the references to it are listed first, the associations that go +// with it are named, and the access rules of every module that held a member +// entry for one of those associations are reconciled afterwards (CE1613, +// ako/mxcli#1449). Before ako/mxcli#2674 the cascade looked only in the +// client's own module, skipped the warning and the reconcile, and said nothing: +// pages and microflows were left pointing at entities nobody was told were gone, +// and an entity imported `into` another module kept naming a client that no +// longer existed. +func dropClientExternalEntities(ctx *ExecContext, serviceRef string) (int, error) { + dms, err := ctx.Backend.ListDomainModels() + if err != nil { + return 0, mdlerrors.NewBackend("list domain models", err) + } + h, err := getHierarchy(ctx) + if err != nil { + return 0, mdlerrors.NewBackend("build hierarchy", err) + } + var targets []clientExternalEntity + for _, dm := range dms { + mod := h.GetModuleName(h.FindModuleID(dm.ContainerID)) + for _, ent := range dm.Entities { + if ent.RemoteServiceName != "" && strings.EqualFold(ent.RemoteServiceName, serviceRef) { + targets = append(targets, clientExternalEntity{dm: dm, module: mod, entity: ent}) + } + } + } + if len(targets) == 0 { + return 0, nil + } + + // Everything that has to be read while the entities and their associations + // still exist: what refers to them, which associations go with them, and + // which modules hold member entries for those associations. + assocs := entityAssociationNames(dms, h, targets) + var reconcile []string + for _, t := range targets { + warnEntityReferences(ctx, t.qualifiedName()) + mods, err := associationMemberModules(ctx, t.module, t.entity) + if err != nil { + return 0, err + } + reconcile = append(reconcile, mods...) + } + + for _, t := range targets { + if err := ctx.Backend.DeleteEntity(t.dm.ID, t.entity.ID); err != nil { + return 0, mdlerrors.NewBackend(fmt.Sprintf("drop external entity %s", t.qualifiedName()), err) + } + line := "Dropped external entity: " + t.qualifiedName() + if names := assocs[t.entity.ID]; len(names) > 0 { + line += " (with association(s) " + strings.Join(names, ", ") + ")" + } + fmt.Fprintln(ctx.Output, line) + } + invalidateDomainModelsCache(ctx) + if err := reconcileModulesAccess(ctx, "after dropping the OData client's external entities", reconcile...); err != nil { + return 0, err + } + return len(targets), nil +} + +// entityAssociationNames names, per dropped entity, the associations that +// DeleteEntity removes with it: every association, in any module, with the +// entity at either end. An association between two dropped entities is named +// once, under the first of them. +func entityAssociationNames(dms []*domainmodel.DomainModel, h *ContainerHierarchy, targets []clientExternalEntity) map[model.ID][]string { + byID := map[model.ID]string{} + byQN := map[string]model.ID{} + var order []model.ID + for _, t := range targets { + byID[t.entity.ID] = t.qualifiedName() + byQN[strings.ToLower(t.qualifiedName())] = t.entity.ID + order = append(order, t.entity.ID) + } + rank := map[model.ID]int{} + for i, id := range order { + rank[id] = i + } + first := func(ids ...model.ID) (model.ID, bool) { + best, ok := model.ID(""), false + for _, id := range ids { + if _, hit := byID[id]; hit && (!ok || rank[id] < rank[best]) { + best, ok = id, true + } + } + return best, ok + } + out := map[model.ID][]string{} + for _, dm := range dms { + mod := h.GetModuleName(h.FindModuleID(dm.ContainerID)) + for _, a := range dm.Associations { + if id, ok := first(a.ParentID, a.ChildID); ok { + out[id] = append(out[id], mod+"."+a.Name) + } + } + for _, ca := range dm.CrossAssociations { + if id, ok := first(ca.ParentID, byQN[strings.ToLower(ca.ChildRef)]); ok { + out[id] = append(out[id], mod+"."+ca.Name) + } + } + } + return out +} diff --git a/mdl/executor/cmd_odata_alter_metadata_hint_test.go b/mdl/executor/cmd_odata_alter_metadata_hint_test.go new file mode 100644 index 0000000000..f65b1b8077 --- /dev/null +++ b/mdl/executor/cmd_odata_alter_metadata_hint_test.go @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/backend/mock" + "github.com/mendixlabs/mxcli/model" +) + +// ako/mxcli#2674: `alter consumed odata service … set (MetadataUrl: …)` reads like +// the way to refresh a changed contract, but it only stores the new URL — the +// cached $metadata and the external entities stay as they were. A user who +// expected a refresh got none, and the next thing they tried (dropping the client) +// deleted every external entity. ALTER now says so, and names the statements that +// do refresh. + +func alterODataClientOutput(t *testing.T, mdl string) string { + t.Helper() + mod := mkModule("MyModule") + svc := &model.ConsumedODataService{ + BaseElement: model.BaseElement{ID: nextID("cos")}, + ContainerID: mod.ID, + Name: "Api", + MetadataUrl: "https://old.example.com/odata/$metadata", + } + h := mkHierarchy(mod) + withContainer(h, svc.ContainerID, mod.ID) + mb := &mock.MockBackend{ + IsConnectedFunc: func() bool { return true }, + ListModulesFunc: func() ([]*model.Module, error) { return []*model.Module{mod}, nil }, + ListConsumedODataServicesFunc: func() ([]*model.ConsumedODataService, error) { + return []*model.ConsumedODataService{svc}, nil + }, + UpdateConsumedODataServiceFunc: func(*model.ConsumedODataService) error { return nil }, + } + ctx, out := newMockCtx(t, withBackend(mb), withHierarchy(h)) + prog := parseMDL(t, mdl) + assertNoError(t, alterODataClient(ctx, prog.Statements[0].(*ast.AlterODataClientStmt))) + return out.String() +} + +func TestAlterODataClient_MetadataUrlSaysItDoesNotRefresh(t *testing.T) { + got := alterODataClientOutput(t, + `alter consumed odata service MyModule.Api set (MetadataUrl: 'https://new.example.com/odata/$metadata');`) + for _, want := range []string{ + "Altered OData client: MyModule.Api", + "not re-read", + "describe consumed odata service MyModule.Api", + "create or modify consumed odata service MyModule.Api", + "create or modify external entities from MyModule.Api", + } { + if !strings.Contains(got, want) { + t.Errorf("output lacks %q:\n%s", want, got) + } + } +} + +// Control: an ALTER that does not touch the contract URL prints no hint. +func TestAlterODataClient_OtherKeysPrintNoRefreshHint(t *testing.T) { + got := alterODataClientOutput(t, `alter consumed odata service MyModule.Api set (Timeout: 120);`) + if !strings.Contains(got, "Altered OData client: MyModule.Api") { + t.Fatalf("alter did not report its write:\n%s", got) + } + if strings.Contains(got, "re-read") || strings.Contains(got, "external entities") { + t.Errorf("a Timeout change printed the refresh hint:\n%s", got) + } +} diff --git a/mdl/executor/cmd_odata_drop_client_cascade_test.go b/mdl/executor/cmd_odata_drop_client_cascade_test.go new file mode 100644 index 0000000000..9cde420cfb --- /dev/null +++ b/mdl/executor/cmd_odata_drop_client_cascade_test.go @@ -0,0 +1,197 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "sort" + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/backend/mock" + "github.com/mendixlabs/mxcli/mdl/catalog" + "github.com/mendixlabs/mxcli/model" + "github.com/mendixlabs/mxcli/sdk/domainmodel" +) + +// ako/mxcli#2674: `drop odata client M.Client` removed every external entity +// created from that client without saying so, skipped the reference warning +// and the access-rule reconcile `drop entity` does, and looked only in the +// client's own module — an entity imported `into` another module kept a +// RemoteServiceName naming a client that no longer exists. + +type dropClientFixture struct { + ctx *ExecContext + out func() string + deleted *[]model.ID + reconciled *[]string + svcDropped *bool + ents map[string]*domainmodel.Entity +} + +// newDropClientFixture: module Sales holds the client Sales.Client, its +// external entities Customer and Order (Order_Customer between them), a local +// Note with Note_Customer, and Supplier from another client Sales.Other. Module +// Crm holds Lead, imported from Sales.Client `into` Crm, and a local Contact +// with Contact_Lead. The catalog says microflow Crm.ACT_Leads retrieves +// Crm.Lead and page Sales.Customer_Overview shows Sales.Customer. +func newDropClientFixture(t *testing.T, withCatalog bool) *dropClientFixture { + t.Helper() + sales, crm := mkModule("Sales"), mkModule("Crm") + ext := func(mod *model.Module, name, svc string) *domainmodel.Entity { + e := mkEntity(mod.ID, name) + e.Source = "Rest$ODataRemoteEntitySource" + e.RemoteServiceName = svc + return e + } + customer, order := ext(sales, "Customer", "Sales.Client"), ext(sales, "Order", "Sales.Client") + supplier := ext(sales, "Supplier", "Sales.Other") + note := mkEntity(sales.ID, "Note") + lead := ext(crm, "Lead", "Sales.Client") + contact := mkEntity(crm.ID, "Contact") + + salesDM := mkDomainModel(sales.ID, customer, order, note, supplier) + salesDM.Associations = []*domainmodel.Association{ + mkAssociation(sales.ID, "Order_Customer", order.ID, customer.ID), + mkAssociation(sales.ID, "Note_Customer", note.ID, customer.ID), + } + crmDM := mkDomainModel(crm.ID, lead, contact) + crmDM.Associations = []*domainmodel.Association{mkAssociation(crm.ID, "Contact_Lead", contact.ID, lead.ID)} + + mods := []*model.Module{sales, crm} + dms := map[model.ID]*domainmodel.DomainModel{sales.ID: salesDM, crm.ID: crmDM} + client := &model.ConsumedODataService{ContainerID: sales.ID, Name: "Client"} + client.ID = nextID("cos") + other := &model.ConsumedODataService{ContainerID: sales.ID, Name: "Other"} + other.ID = nextID("cos") + + var deleted []model.ID + var reconciled []string + svcDropped := false + mb := &mock.MockBackend{ + IsConnectedFunc: func() bool { return true }, + ListModulesFunc: func() ([]*model.Module, error) { return mods, nil }, + ListConsumedODataServicesFunc: func() ([]*model.ConsumedODataService, error) { + return []*model.ConsumedODataService{client, other}, nil + }, + GetDomainModelFunc: func(id model.ID) (*domainmodel.DomainModel, error) { return dms[id], nil }, + ListDomainModelsFunc: func() ([]*domainmodel.DomainModel, error) { + return []*domainmodel.DomainModel{salesDM, crmDM}, nil + }, + DeleteEntityFunc: func(_ model.ID, id model.ID) error { + deleted = append(deleted, id) + return nil + }, + ReconcileMemberAccessesFunc: func(_ model.ID, moduleName string) (int, error) { + reconciled = append(reconciled, moduleName) + return 0, nil + }, + DeleteConsumedODataServiceFunc: func(id model.ID) error { + if id == client.ID { + svcDropped = true + } + return nil + }, + } + ctx, buf := newMockCtx(t, withBackend(mb), withHierarchy(mkHierarchy(mods...))) + if withCatalog { + cat, err := catalog.New() + if err != nil { + t.Fatalf("catalog.New: %v", err) + } + t.Cleanup(func() { cat.Close() }) + if _, err := cat.CatalogDB().Exec(`INSERT INTO refs (SourceType, SourceId, SourceName, TargetType, TargetId, TargetName, RefKind, ProjectId, SnapshotId) VALUES + ('MICROFLOW', '', 'Crm.ACT_Leads', 'ENTITY', '', 'Crm.Lead', 'retrieve', 'p', 's'), + ('PAGE', '', 'Sales.Customer_Overview', 'ENTITY', '', 'Sales.Customer', 'datasource', 'p', 's')`); err != nil { + t.Fatalf("seed: %v", err) + } + cat.SetBuilt(true) + ctx.Catalog = cat + } + return &dropClientFixture{ctx: ctx, out: buf.String, deleted: &deleted, reconciled: &reconciled, svcDropped: &svcDropped, + ents: map[string]*domainmodel.Entity{"Customer": customer, "Order": order, "Supplier": supplier, "Note": note, + "Lead": lead, "Contact": contact}} +} + +func dropSalesClient(t *testing.T, f *dropClientFixture) string { + t.Helper() + assertNoError(t, dropODataClient(f.ctx, &ast.DropODataClientStmt{Name: ast.QualifiedName{Module: "Sales", Name: "Client"}})) + if !*f.svcDropped { + t.Fatalf("the client itself was not deleted") + } + return f.out() +} + +func TestDropODataClient_DropsItsExternalEntitiesInEveryModule(t *testing.T) { + f := newDropClientFixture(t, false) + dropSalesClient(t, f) + byID := map[model.ID]string{} + for n, e := range f.ents { + byID[e.ID] = n + } + var got []string + for _, id := range *f.deleted { + got = append(got, byID[id]) + } + sort.Strings(got) + // Lead is the entity imported `into` Crm: it was left behind, naming a + // client that no longer exists. Note, Contact (local) and Supplier (another + // client) are the control: they stay. + if strings.Join(got, ",") != "Customer,Lead,Order" { + t.Fatalf("deleted entities %v, want [Customer Lead Order]", got) + } +} + +func TestDropODataClient_ListsWhatItDropsAndWhatBreaks(t *testing.T) { + f := newDropClientFixture(t, true) + out := dropSalesClient(t, f) + for _, want := range []string{ + "Dropped external entity: Sales.Customer", + "Dropped external entity: Sales.Order", + "Dropped external entity: Crm.Lead", + // associations that went with the entities + "Sales.Order_Customer", "Sales.Note_Customer", "Crm.Contact_Lead", + // what refers to them — the dangling references the reporter hit + "warning: Crm.Lead is referenced by 1 element(s)", "MICROFLOW Crm.ACT_Leads", + "warning: Sales.Customer is referenced by 1 element(s)", "PAGE Sales.Customer_Overview", + "Dropped OData client: Sales.Client", + // a drop is not how a contract is refreshed + "create or modify consumed odata service", "create or modify external entities", + } { + if !strings.Contains(out, want) { + t.Errorf("output lacks %q:\n%s", want, out) + } + } + for _, notWant := range []string{"Sales.Supplier", "Sales.Note:", "Crm.Contact:"} { + if strings.Contains(out, "Dropped external entity: "+strings.TrimSuffix(notWant, ":")) { + t.Errorf("output reports %s as dropped:\n%s", notWant, out) + } + } +} + +func TestDropODataClient_ReconcilesEveryModuleItDroppedFrom(t *testing.T) { + f := newDropClientFixture(t, false) + dropSalesClient(t, f) + seen := map[string]bool{} + for _, m := range *f.reconciled { + seen[m] = true + } + // Crm.Contact keeps a member entry for Crm.Contact_Lead (CE1613) unless Crm + // is reconciled; Sales.Note likewise for Sales.Note_Customer. + if !seen["Sales"] || !seen["Crm"] { + t.Fatalf("reconciled modules %v, want Sales and Crm", *f.reconciled) + } +} + +// Control: a client with no external entities says so plainly and lists none. +func TestDropODataClient_NoEntities(t *testing.T) { + f := newDropClientFixture(t, true) + assertNoError(t, dropODataClient(f.ctx, &ast.DropODataClientStmt{Name: ast.QualifiedName{Module: "Sales", Name: "Other"}})) + out := f.out() + if strings.Contains(out, "Sales.Customer") || strings.Contains(out, "Crm.Lead") { + t.Fatalf("dropping Sales.Other touched Sales.Client's entities:\n%s", out) + } + if !strings.Contains(out, "Dropped external entity: Sales.Supplier") || !strings.Contains(out, "Dropped OData client: Sales.Other") { + t.Fatalf("unexpected output:\n%s", out) + } +} diff --git a/mdl/executor/cmd_pages_builder_inherited_assoc_test.go b/mdl/executor/cmd_pages_builder_inherited_assoc_test.go index e9c3c6c69b..16bd95ffce 100644 --- a/mdl/executor/cmd_pages_builder_inherited_assoc_test.go +++ b/mdl/executor/cmd_pages_builder_inherited_assoc_test.go @@ -16,7 +16,7 @@ import ( // // Administration.Account extends System.User, and UserRoles is declared on // System.User. `DESCRIBE PAGE Administration.Account_New` emits -// `combobox (Attribute: UserRoles, DataSource: database from System.UserRole)`, +// `combobox (Association: UserRoles, DataSource: database from System.UserRole)`, // and exec qualified the bare name with the page entity's module, writing // `Administration.UserRoles`: // @@ -120,7 +120,7 @@ func TestResolveMapping_Association_InheritedFromGeneralization(t *testing.T) { engine := &PluggableWidgetEngine{pageBuilder: pb, outerEntityContext: "Administration.Account"} mapping := PropertyMapping{PropertyKey: "attributeAssociation", Source: "Association", Operation: "association"} - w := &ast.WidgetV3{Properties: map[string]any{"Attribute": "UserRoles"}} + w := &ast.WidgetV3{Properties: map[string]any{"Association": "UserRoles"}} ctx, err := engine.resolveMapping(mapping, w) if err != nil { diff --git a/mdl/executor/cmd_pages_builder_input.go b/mdl/executor/cmd_pages_builder_input.go index bb9fc001e4..b4c19ad9c3 100644 --- a/mdl/executor/cmd_pages_builder_input.go +++ b/mdl/executor/cmd_pages_builder_input.go @@ -252,7 +252,8 @@ func (pb *pageBuilder) rejectAssociationAsAttributeOn(w *ast.WidgetV3, param, na "`Attribute:` and no `DataSource:` is in enumeration mode, whose attribute property cannot hold a "+ "reference, and the build fails CE1613 \"The selected attribute '%s.%s' no longer exists\". "+ "To pick the associated object, use the combo box's association mode, which a `DataSource:` "+ - "selects: `combobox %s (Attribute: %s, DataSource: database %s, CaptionAttribute: )`", + "selects, with the association written `Association:`: "+ + "`combobox %s (Association: %s, DataSource: database %s, CaptionAttribute: )`", where, name, fromEntity, toEntity, entityContext, name, w.Name, binding, toEntity, toEntity) } diff --git a/mdl/executor/cmd_pages_builder_v3_widgets.go b/mdl/executor/cmd_pages_builder_v3_widgets.go index 823ecc0b30..7ce41f7e1f 100644 --- a/mdl/executor/cmd_pages_builder_v3_widgets.go +++ b/mdl/executor/cmd_pages_builder_v3_widgets.go @@ -538,6 +538,14 @@ func (pb *pageBuilder) buildTextBoxV3(w *ast.WidgetV3) (*pages.TextBox, error) { }, } + // "Aria required"; unset keeps false (ako/mxcli#2710). + if err := applyAriaRequired(w, &tb.AriaRequired); err != nil { + return nil, err + } + if err := applyTextBoxAutocomplete(w, tb); err != nil { + return nil, err + } + // Handle Attribute (attribute path) if attr := inputAttributeText(w); attr != "" { path, steps, sv, err := pb.resolveInputBinding(w, attr) @@ -648,6 +656,11 @@ func (pb *pageBuilder) buildTextAreaV3(w *ast.WidgetV3) (*pages.TextArea, error) }, } + // "Aria required"; unset keeps false (ako/mxcli#2710). + if err := applyAriaRequired(w, &ta.AriaRequired); err != nil { + return nil, err + } + // Handle Attribute if attr := inputAttributeText(w); attr != "" { path, steps, sv, err := pb.resolveInputBinding(w, attr) @@ -735,6 +748,11 @@ func (pb *pageBuilder) buildDatePickerV3(w *ast.WidgetV3) (*pages.DatePicker, er }, } + // "Aria required"; unset keeps false (ako/mxcli#2710). + if err := applyAriaRequired(w, &dp.AriaRequired); err != nil { + return nil, err + } + // Handle Attribute if attr := inputAttributeText(w); attr != "" { path, steps, sv, err := pb.resolveInputBinding(w, attr) @@ -1007,6 +1025,11 @@ func (pb *pageBuilder) buildRadioButtonsV3(w *ast.WidgetV3) (*pages.RadioButtons Label: inputLabel(w), } + // "Aria required"; unset keeps false (ako/mxcli#2710). + if err := applyAriaRequired(w, &rb.AriaRequired); err != nil { + return nil, err + } + // Get attribute path from Attribute property if attr := inputAttributeText(w); attr != "" { path, steps, sv, err := pb.resolveInputBinding(w, attr) diff --git a/mdl/executor/cmd_pages_describe.go b/mdl/executor/cmd_pages_describe.go index cd0f1aa808..47479a9b4d 100644 --- a/mdl/executor/cmd_pages_describe.go +++ b/mdl/executor/cmd_pages_describe.go @@ -888,6 +888,10 @@ type rawWidget struct { Type string Name string Content string + // ContentIsAssociation says Content is the association a pluggable widget + // binds (a combo box or drop-down filter in association mode), printed + // `Association:` rather than `Attribute:` (ako/mxcli#2709). + ContentIsAssociation bool // SnippetParams is a snippet call's argument list, `P = $v, …`, printed as // `Params: ( … )` (ako/mxcli#826). SnippetParams string @@ -948,7 +952,11 @@ type rawWidget struct { // NumberOfLines and Autocomplete are a text area's; nil when not stored // (ako/mxcli#977). NumberOfLines *int64 - Autocomplete *bool + Autocomplete *bool // a text box's too (ako/mxcli#2710) + // AriaRequired is an attribute input's "Aria required"; AutocompletePurpose + // a text box's, "" when not stored (ako/mxcli#2710). + AriaRequired bool + AutocompletePurpose string // UnsayableOutputMappings counts the output mappings (Mendix 11.5) of a // button's flow call that describe could not print as `returns ( … )` // (ako/mxcli#977). diff --git a/mdl/executor/cmd_pages_describe_combobox_onchange_test.go b/mdl/executor/cmd_pages_describe_combobox_onchange_test.go index 6cc69e12d3..3b7515509a 100644 --- a/mdl/executor/cmd_pages_describe_combobox_onchange_test.go +++ b/mdl/executor/cmd_pages_describe_combobox_onchange_test.go @@ -32,11 +32,11 @@ func TestDescribeComboboxWithOnChangeKeepsItsBinding(t *testing.T) { w: rawWidget{ Type: "CustomWidgets$CustomWidget", RenderMode: "combobox", Name: "cbEmp", WidgetID: "com.mendix.widget.web.combobox.Combobox", - Content: "M.Task_Employee", CaptionAttribute: "Name", + Content: "M.Task_Employee", ContentIsAssociation: true, CaptionAttribute: "Name", DataSource: &rawDataSource{Type: "database", Reference: "M.Employee"}, OnChange: "microflow M.OnEmp", }, - want: []string{"combobox cbEmp", "Attribute: M.Task_Employee", "CaptionAttribute: Name", "OnChange: microflow M.OnEmp"}, + want: []string{"combobox cbEmp", "Association: M.Task_Employee", "CaptionAttribute: Name", "OnChange: microflow M.OnEmp"}, }, } { t.Run(tc.name, func(t *testing.T) { diff --git a/mdl/executor/cmd_pages_describe_output.go b/mdl/executor/cmd_pages_describe_output.go index a8b5f3d8d3..b610bf5aed 100644 --- a/mdl/executor/cmd_pages_describe_output.go +++ b/mdl/executor/cmd_pages_describe_output.go @@ -693,6 +693,7 @@ func outputWidgetMDLV3(ctx *ExecContext, w rawWidget, indent int) { props = append(props, fmt.Sprintf("Placeholder: %s", mdlQuote(ctx, w.Placeholder))) } props = describeKeyboardType(props, w) + props = describeInputAccessibility(props, w, true) if w.OnChange != "" { props = append(props, actionProp("OnChange", w.OnChange)) } @@ -732,6 +733,7 @@ func outputWidgetMDLV3(ctx *ExecContext, w rawWidget, indent int) { if w.Autocomplete != nil && !*w.Autocomplete { props = append(props, "Autocomplete: false") } + props = describeInputAccessibility(props, w, false) props = appendAppearanceProps(ctx, props, w) formatWidgetProps(ctx.Output, prefix, header, props, "\n") @@ -762,6 +764,7 @@ func outputWidgetMDLV3(ctx *ExecContext, w rawWidget, indent int) { props = append(props, actionProp("OnChange", w.OnChange)) } props = appendFocusEventProps(props, w) + props = describeInputAccessibility(props, w, false) props = appendAppearanceProps(ctx, props, w) formatWidgetProps(ctx.Output, prefix, header, props, "\n") @@ -782,6 +785,7 @@ func outputWidgetMDLV3(ctx *ExecContext, w rawWidget, indent int) { props = append(props, actionProp("OnChange", w.OnChange)) } props = appendFocusEventProps(props, w) + props = describeInputAccessibility(props, w, false) props = appendAppearanceProps(ctx, props, w) formatWidgetProps(ctx.Output, prefix, header, props, "\n") @@ -1048,7 +1052,11 @@ func outputWidgetMDLV3(ctx *ExecContext, w rawWidget, indent int) { props = append(props, fmt.Sprintf("Label: %s", mdlQuote(ctx, w.Caption))) } if w.Content != "" { - props = append(props, fmt.Sprintf("Attribute: %s", w.Content)) + key := "Attribute" + if w.ContentIsAssociation { + key = "Association" // ako/mxcli#2709 + } + props = append(props, fmt.Sprintf("%s: %s", key, w.Content)) } // Show DataSource and CaptionAttribute for the association modes. // The drop-down filter's ref mode has the same three parts as the diff --git a/mdl/executor/cmd_pages_describe_parse.go b/mdl/executor/cmd_pages_describe_parse.go index 5782dce16f..c166eec293 100644 --- a/mdl/executor/cmd_pages_describe_parse.go +++ b/mdl/executor/cmd_pages_describe_parse.go @@ -450,6 +450,12 @@ func parseRawWidget(ctx *ExecContext, w map[string]any, parentEntityContext ...s widget.IsPassword, _ = w["IsPasswordBox"].(bool) widget.KeyboardType, _ = w["KeyboardType"].(string) widget.AutoFocus, _ = w["AutoFocus"].(bool) // ako/mxcli#2519 + // ako/mxcli#2710 + widget.AriaRequired, _ = w["AriaRequired"].(bool) + widget.AutocompletePurpose, _ = w["AutocompletePurpose"].(string) + if b, ok := w["Autocomplete"].(bool); ok { + widget.Autocomplete = &b + } widget.ValidationExpression, widget.ValidationMessage = extractWidgetValidation(ctx, w) widget.SubmitBehaviour, widget.SubmitOnInputDelay = extractSubmitBehaviour(w) widget.OnChange = extractOnChangeAction(ctx, w) @@ -468,6 +474,7 @@ func parseRawWidget(ctx *ExecContext, w map[string]any, parentEntityContext ...s widget.Placeholder = extractPlaceholderText(ctx, w) widget.Editable = extractEditable(ctx, w) widget.ReadOnlyStyle = extractReadOnlyStyle(ctx, w) // ako/mxcli#977 + widget.AriaRequired, _ = w["AriaRequired"].(bool) // ako/mxcli#2710 widget.SubmitBehaviour, widget.SubmitOnInputDelay = extractSubmitBehaviour(w) widget.OnChange = extractOnChangeAction(ctx, w) widget.OnEnter, widget.OnLeave = extractFocusEventActions(ctx, w) @@ -493,6 +500,7 @@ func parseRawWidget(ctx *ExecContext, w map[string]any, parentEntityContext ...s widget.Content = extractInputAttribute(ctx, w) widget.Editable = extractEditable(ctx, w) widget.ReadOnlyStyle = extractReadOnlyStyle(ctx, w) // ako/mxcli#977 + widget.AriaRequired, _ = w["AriaRequired"].(bool) // ako/mxcli#2710 widget.OnChange = extractOnChangeAction(ctx, w) widget.OnEnter, widget.OnLeave = extractFocusEventActions(ctx, w) widget.Formatting = describeInputFormatting(ctx, "datepicker", w) @@ -507,6 +515,7 @@ func parseRawWidget(ctx *ExecContext, w map[string]any, parentEntityContext ...s widget.Content = extractInputAttribute(ctx, w) widget.Editable = extractEditable(ctx, w) widget.ReadOnlyStyle = extractReadOnlyStyle(ctx, w) // ako/mxcli#977 + widget.AriaRequired, _ = w["AriaRequired"].(bool) // ako/mxcli#2710 widget.OnChange = extractOnChangeAction(ctx, w) widget.OnEnter, widget.OnLeave = extractFocusEventActions(ctx, w) return []rawWidget{widget} @@ -540,6 +549,7 @@ func parseRawWidget(ctx *ExecContext, w map[string]any, parentEntityContext ...s widget.DataSource = extractComboBoxDataSource(ctx, w) if widget.DataSource != nil { widget.Content = associationRefForContext(extractCustomWidgetPropertyAssociationQN(ctx, w, "attributeAssociation"), inheritedCtx) + widget.ContentIsAssociation = true // The association starts at a page or snippet parameter: // `$Param.Module.Assoc`, qualified, since no entity is in scope // to shorten it against. @@ -583,6 +593,7 @@ func parseRawWidget(ctx *ExecContext, w map[string]any, parentEntityContext ...s extractCustomWidgetPropertyString(ctx, w, "baseType") == "ref" { widget.DataSource = extractCustomWidgetPropertyDataSource(ctx, w, "refOptions") widget.Content = associationRefForContext(extractCustomWidgetPropertyAssociationQN(ctx, w, "refEntity"), inheritedCtx) + widget.ContentIsAssociation = true widget.CaptionAttribute = extractCustomWidgetPropertyAttributeRef(ctx, w, "refCaption") } // For DataGrid2, also extract datasource, columns, CONTROLBAR widgets, paging, and selection diff --git a/mdl/executor/cmd_pages_hidden_content_rebuild_1648_test.go b/mdl/executor/cmd_pages_hidden_content_rebuild_1648_test.go index ba4e434325..2c93eee93e 100644 --- a/mdl/executor/cmd_pages_hidden_content_rebuild_1648_test.go +++ b/mdl/executor/cmd_pages_hidden_content_rebuild_1648_test.go @@ -43,7 +43,7 @@ func storedComboWithContent(content ...string) (typ, obj bson.D) { const describedCombo = `combobox cbBooking ( Label: 'Booking', - Attribute: Holder_Booking, + Association: Holder_Booking, DataSource: database from MyFirstModule.Booking, CaptionAttribute: Name, optionsSourceAssociationCustomContentType: 'yes' diff --git a/mdl/executor/combobox_association_object_test.go b/mdl/executor/combobox_association_object_test.go index d49ba247b7..43152b52c8 100644 --- a/mdl/executor/combobox_association_object_test.go +++ b/mdl/executor/combobox_association_object_test.go @@ -94,7 +94,7 @@ func TestCheck1420_ComboBoxAssociationAtDocumentRoot(t *testing.T) { // Controls: the parameter spelling, a data view around it, and the // enumeration mode are not this rule's. for _, src := range []string{ - `create snippet M.S (Params: ($Asset: M.Asset)) { combobox x (Attribute: $Asset.M.Asset_Customer, DataSource: database M.Customer, CaptionAttribute: CustomerName) };`, + `create snippet M.S (Params: ($Asset: M.Asset)) { combobox x (Association: $Asset.M.Asset_Customer, DataSource: database M.Customer, CaptionAttribute: CustomerName) };`, `create snippet M.S (Params: ($Asset: M.Asset)) { dataview dv (DataSource: $Asset) { ` + unanchoredComboBox + ` } };`, `create snippet M.S (Params: ($Asset: M.Asset)) { dataview dv (DataSource: $Asset) { combobox x (Attribute: Status) } };`, } { @@ -142,7 +142,7 @@ func TestCheck1420_AlterReplaceAtSnippetRoot(t *testing.T) { t.Fatalf("want one CE7007 refusal for combobox x, got %v", errs) } for _, ok := range []string{ - `combobox x (Attribute: $Asset.M.Asset_Customer, DataSource: database M.Customer, CaptionAttribute: CustomerName)`, + `combobox x (Association: $Asset.M.Asset_Customer, DataSource: database M.Customer, CaptionAttribute: CustomerName)`, `dataview dv (DataSource: $Asset) { ` + unanchoredComboBox + ` }`, } { if errs := check(ok); len(errs) != 0 { diff --git a/mdl/executor/input_accessibility.go b/mdl/executor/input_accessibility.go new file mode 100644 index 0000000000..e2f7726a99 --- /dev/null +++ b/mdl/executor/input_accessibility.go @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "strings" + + "github.com/mendixlabs/mxcli/mdl/ast" + mdlerrors "github.com/mendixlabs/mxcli/mdl/errors" + "github.com/mendixlabs/mxcli/sdk/pages" +) + +// An input's "Aria required" and a text box's autocomplete (ako/mxcli#2710). +// +// AriaRequired is stored on every attribute input (text box, text area, date +// picker, radio buttons); Autocomplete and AutocompletePurpose on a text box. +// The writer hard-coded Studio Pro's defaults — false, true, On — and describe +// printed nothing, so a rewrite of a page or snippet from MDL reset what Studio +// Pro had set. The MDL spelling is the stored property and enum member: +// +// textbox txtPostalCode (Attribute: PostalCode, AriaRequired: true, AutocompletePurpose: PostalCode) + +// applyAriaRequired reads an input's AriaRequired into dst; unset leaves it +// false. +func applyAriaRequired(w *ast.WidgetV3, dst *bool) error { + raw, ok := lookupPropCI(w, "AriaRequired") + if !ok { + return nil + } + v, err := propBool(raw) + if err != nil { + return mdlerrors.NewBackend(w.Type+" AriaRequired", err) + } + *dst = v + return nil +} + +// autocompletePurposeProblem validates a text box's AutocompletePurpose; "" +// means valid or absent. The builder refuses with the same message, so check +// and exec agree. +func autocompletePurposeProblem(w *ast.WidgetV3) string { + if w == nil || !strings.EqualFold(w.Type, "textbox") { + return "" + } + v, ok := lookupPropCI(w, "AutocompletePurpose") + if !ok { + return "" + } + if s, isStr := v.(string); isStr { + if _, valid := pages.CanonicalAutocompletePurpose(s); valid { + return "" + } + } + return fmt.Sprintf("AutocompletePurpose must be one of %s, got %v", strings.Join(pages.AutocompletePurposes, ", "), v) +} + +// applyTextBoxAutocomplete reads a text box's Autocomplete and +// AutocompletePurpose; unset leaves nil / "", which the writer fills with +// Studio Pro's defaults. +func applyTextBoxAutocomplete(w *ast.WidgetV3, tb *pages.TextBox) error { + if msg := autocompletePurposeProblem(w); msg != "" { + return mdlerrors.NewValidationf("textbox %q: %s", w.Name, msg) + } + if v, ok := lookupPropCI(w, "AutocompletePurpose"); ok { + s, _ := v.(string) + tb.AutocompletePurpose, _ = pages.CanonicalAutocompletePurpose(s) + } + if raw, ok := lookupPropCI(w, "Autocomplete"); ok { + v, err := propBool(raw) + if err != nil { + return mdlerrors.NewBackend("textbox Autocomplete", err) + } + tb.Autocomplete = &v + } + return nil +} + +// describeInputAccessibility appends AriaRequired, and a text box's +// autocomplete settings, when they differ from Studio Pro's defaults — so an +// ordinary input describes as it did. +func describeInputAccessibility(props []string, w rawWidget, textBox bool) []string { + if w.AriaRequired { + props = append(props, "AriaRequired: true") + } + if !textBox { + return props + } + if w.Autocomplete != nil && !*w.Autocomplete { + props = append(props, "Autocomplete: false") + } + if w.AutocompletePurpose != "" && w.AutocompletePurpose != "On" { + props = append(props, "AutocompletePurpose: "+w.AutocompletePurpose) + } + return props +} diff --git a/mdl/executor/input_accessibility_2710_test.go b/mdl/executor/input_accessibility_2710_test.go new file mode 100644 index 0000000000..18ee7346fa --- /dev/null +++ b/mdl/executor/input_accessibility_2710_test.go @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/visitor" + "github.com/mendixlabs/mxcli/model" +) + +// ako/mxcli#2710 (mendixlabs/mxcli#1996): an input's "Aria required" and a +// text box's "Autocomplete purpose" were hard-coded by the writer (false, On), +// refused by check (MDL-WIDGET52) and never described, so every rewrite of a +// page or snippet from MDL reset what Studio Pro had set — the same shape as +// AutoFocus (#2519). + +func TestBuildTextBox_AriaAndAutocomplete_2710(t *testing.T) { + pb := &pageBuilder{widgetScope: map[string]model.ID{}} + tb, err := pb.buildTextBoxV3(&ast.WidgetV3{Name: "tb", Type: "textbox", Properties: map[string]any{ + "AriaRequired": true, "Autocomplete": false, "AutocompletePurpose": "postalcode", + }}) + if err != nil { + t.Fatal(err) + } + if !tb.AriaRequired || tb.Autocomplete == nil || *tb.Autocomplete || tb.AutocompletePurpose != "PostalCode" { + t.Errorf("built AriaRequired=%v Autocomplete=%v Purpose=%q", tb.AriaRequired, tb.Autocomplete, tb.AutocompletePurpose) + } + // Control: unset stays at the defaults the writer fills in. + tb, err = pb.buildTextBoxV3(&ast.WidgetV3{Name: "tb2", Type: "textbox", Properties: map[string]any{}}) + if err != nil { + t.Fatal(err) + } + if tb.AriaRequired || tb.Autocomplete != nil || tb.AutocompletePurpose != "" { + t.Errorf("unset built AriaRequired=%v Autocomplete=%v Purpose=%q", tb.AriaRequired, tb.Autocomplete, tb.AutocompletePurpose) + } + w := &ast.WidgetV3{Name: "tb3", Type: "textbox", Properties: map[string]any{"AutocompletePurpose": "Zipcode"}} + if _, err := pb.buildTextBoxV3(w); err == nil || !strings.Contains(err.Error(), "PostalCode") { + t.Errorf("AutocompletePurpose: Zipcode = %v, want a refusal naming the members", err) + } + found := false + for _, v := range validateInputSubmitAndGridWidth(w, "page M.P") { + found = found || strings.Contains(v.Message, "AutocompletePurpose") + } + if !found { + t.Error("check does not refuse AutocompletePurpose: Zipcode, which exec refuses") + } +} + +func TestBuildInputs_AriaRequired_2710(t *testing.T) { + props := func() map[string]any { return map[string]any{"AriaRequired": true} } + pb := &pageBuilder{widgetScope: map[string]model.ID{}} + ta, err := pb.buildTextAreaV3(&ast.WidgetV3{Name: "ta", Type: "textarea", Properties: props()}) + if err != nil || !ta.AriaRequired { + t.Errorf("textarea: %v %v", err, ta) + } + dp, err := pb.buildDatePickerV3(&ast.WidgetV3{Name: "dp", Type: "datepicker", Properties: props()}) + if err != nil || !dp.AriaRequired { + t.Errorf("datepicker: %v %v", err, dp) + } + rb, err := pb.buildRadioButtonsV3(&ast.WidgetV3{Name: "rb", Type: "radiobuttons", Properties: props()}) + if err != nil || !rb.AriaRequired { + t.Errorf("radiobuttons: %v %v", err, rb) + } + if _, err := pb.buildTextAreaV3(&ast.WidgetV3{Name: "tb", Type: "textarea", + Properties: map[string]any{"AriaRequired": "maybe"}}); err == nil { + t.Error("AriaRequired: maybe was accepted") + } +} + +func TestDescribeInputs_AriaAndAutocomplete_2710(t *testing.T) { + stored := []map[string]any{ + {"$Type": "Forms$TextBox", "Name": "txtPostalCode", "AriaRequired": true, "Autocomplete": false, "AutocompletePurpose": "PostalCode"}, + {"$Type": "Forms$TextArea", "Name": "ta", "AriaRequired": true}, + {"$Type": "Forms$DatePicker", "Name": "dp", "AriaRequired": true}, + {"$Type": "Forms$RadioButtonGroup", "Name": "rb", "AriaRequired": true}, + } + ctx, buf := newMockCtx(t) + for _, m := range stored { + for _, rw := range parseRawWidget(ctx, m) { + outputWidgetMDLV3(ctx, rw, 0) + } + } + out := buf.String() + if n := strings.Count(out, "AriaRequired: true"); n != 4 { + t.Errorf("AriaRequired printed %d times, want 4:\n%s", n, out) + } + for _, want := range []string{"Autocomplete: false", "AutocompletePurpose: PostalCode"} { + if !strings.Contains(out, want) { + t.Errorf("describe dropped %q, so a rewrite resets it:\n%s", want, out) + } + } + prog, errs := visitor.Build("create page M.P (Title: 'x', Layout: A.L) {\n" + out + "}\n") + if len(errs) > 0 { + t.Fatalf("describe output does not parse: %v\n%s", errs, out) + } + for _, w := range prog.Statements[0].(*ast.CreatePageStmtV3).Widgets { + for _, v := range validateNativeWidgetProps(strings.ToLower(w.Type), w, "page M.P") { + t.Errorf("check refuses describe's own output: %s", v.Message) + } + } + + // Control: Studio Pro's defaults are every ordinary input and are not printed. + ctx, buf = newMockCtx(t) + for _, rw := range parseRawWidget(ctx, map[string]any{ + "$Type": "Forms$TextBox", "Name": "tb", "AriaRequired": false, "Autocomplete": true, "AutocompletePurpose": "On", + }) { + outputWidgetMDLV3(ctx, rw, 0) + } + if s := buf.String(); strings.Contains(s, "Aria") || strings.Contains(s, "Autocomplete") { + t.Errorf("describe printed a default: %s", s) + } +} diff --git a/mdl/executor/input_submit_width.go b/mdl/executor/input_submit_width.go index 32d8048575..1c0748b7a3 100644 --- a/mdl/executor/input_submit_width.go +++ b/mdl/executor/input_submit_width.go @@ -146,6 +146,9 @@ func validateInputSubmitAndGridWidth(w *ast.WidgetV3, locationPrefix string) []l if msg := keyboardTypeProblem(w); msg != "" { // ako/mxcli#1209 out = append(out, violation18(locationPrefix, w, msg)) } + if msg := autocompletePurposeProblem(w); msg != "" { // ako/mxcli#2710 + out = append(out, violation18(locationPrefix, w, msg)) + } if msg := layoutGridWidthProblem(w); msg != "" { out = append(out, violation18(locationPrefix, w, msg)) } diff --git a/mdl/executor/layout_lanes.go b/mdl/executor/layout_lanes.go index 2467f168d5..fe203579e8 100644 --- a/mdl/executor/layout_lanes.go +++ b/mdl/executor/layout_lanes.go @@ -119,7 +119,7 @@ func rejoinsPastRow(eh *ast.ErrorHandlingClause, row int) bool { if !isCustomErrorHandling(eh) || len(eh.Body) == 0 || row <= ActivityWidth { return false } - return !lastStmtIsReturn(eh.Body) && !isRetryLoopErrorHandler(eh.Body) + return !lastStmtIsReturn(eh.Body) } // rejoinAfterRow makes the main line wait for the merge a falling-through handler diff --git a/mdl/executor/roundtrip_mxcheck_test.go b/mdl/executor/roundtrip_mxcheck_test.go index ec125ae5d8..7037411892 100644 --- a/mdl/executor/roundtrip_mxcheck_test.go +++ b/mdl/executor/roundtrip_mxcheck_test.go @@ -824,7 +824,7 @@ end;` textbox txtName (Attribute: FullName, Label: 'Full Name') combobox cmbCompany ( Label: 'Company', - Attribute: MxCheckContact_MxCheckCompany, + Association: MxCheckContact_MxCheckCompany, DataSource: database ` + companyEntity + `, CaptionAttribute: Name ) diff --git a/mdl/executor/typecheck.go b/mdl/executor/typecheck.go index 255106052e..8f595c1ad7 100644 --- a/mdl/executor/typecheck.go +++ b/mdl/executor/typecheck.go @@ -265,6 +265,20 @@ func declareJavaActionParams(ctx *ExecContext, reader *exprcatalog.Reader, prog } } reader.DeclareFlow(s.Name.String(), params) + case *ast.CreateJavaScriptActionStmt: + // The same declaration for a JavaScript action (check-gap f84, + // measured: the same call-argument matrix applies). + scripted[s.Name.String()] = true + var params []exprcatalog.FlowParam + for _, p := range s.Parameters { + if p.Type.EntityRef != nil || p.Type.EnumRef != nil { + continue + } + if k, ok := adapters.DataTypeKind(p.Type.Kind); ok && javaPrimitiveKind(k) { + params = append(params, exprcatalog.FlowParam{Name: p.Name, Kind: k}) + } + } + reader.DeclareFlow(s.Name.String(), params) case *ast.CreateMicroflowStmt: collectJavaActionCalls(s.Body, called) case *ast.CreateNanoflowStmt: @@ -278,12 +292,16 @@ func declareJavaActionParams(ctx *ExecContext, reader *exprcatalog.Reader, prog if scripted[qn] || isBuiltinModuleEntity(qualifiedNameModule(qn)) { continue } - ja, err := ctx.Backend.ReadJavaActionByName(qn) - if err != nil || ja == nil { + var stored []*javaactions.JavaActionParameter + if ja, err := ctx.Backend.ReadJavaActionByName(qn); err == nil && ja != nil { + stored = ja.Parameters + } else if jsa, err := ctx.Backend.ReadJavaScriptActionByName(qn); err == nil && jsa != nil { + stored = jsa.Parameters + } else { continue } var params []exprcatalog.FlowParam - for _, p := range ja.Parameters { + for _, p := range stored { if p == nil { continue } @@ -297,8 +315,15 @@ func declareJavaActionParams(ctx *ExecContext, reader *exprcatalog.Reader, prog func collectJavaActionCalls(body []ast.MicroflowStatement, into map[string]bool) { forEachMicroflowStatement(body, func(s ast.MicroflowStatement) { - if c, ok := s.(*ast.CallJavaActionStmt); ok && c.ActionName.Module != "" { - into[c.ActionName.String()] = true + switch c := s.(type) { + case *ast.CallJavaActionStmt: + if c.ActionName.Module != "" { + into[c.ActionName.String()] = true + } + case *ast.CallJavaScriptActionStmt: + if c.ActionName.Module != "" { + into[c.ActionName.String()] = true + } } }) } diff --git a/mdl/executor/validate.go b/mdl/executor/validate.go index 7694a59adf..42a282c82d 100644 --- a/mdl/executor/validate.go +++ b/mdl/executor/validate.go @@ -36,6 +36,10 @@ type scriptContext struct { // association endpoint check from refusing what exec will find (#555). indirectEntities map[string]bool externalEntityModules map[string]bool + // unreadableImports are the target modules of a bulk import whose contract + // the check could not read, with the reason, for the entity-not-found it + // then leaves standing (ako/mxcli#2674). + unreadableImports map[string]string // externalEntities are the external entities the script creates one by one, // with the service each comes from (CE6612 on add attribute, #2477). externalEntities map[string]string @@ -59,10 +63,13 @@ type scriptContext struct { nanoflows map[string]bool // Nanoflows created (Module.Nanoflow) pages map[string]bool // Pages created (Module.Page) snippets map[string]bool // Snippets created (Module.Snippet) - layouts map[string]bool // Layouts created (Module.Layout) - menus map[string]bool // Menu documents created (Module.Menu) - constants map[string]bool // Constants created (Module.Constant) - workflows map[string]bool // Workflows created (Module.Workflow) + // snippetDecls are the script's snippet declarations, by qualified name, + // for the snippet call parameter check (validate_mapping_snippet_gaps.go). + snippetDecls map[string]*ast.CreateSnippetStmtV3 + layouts map[string]bool // Layouts created (Module.Layout) + menus map[string]bool // Menu documents created (Module.Menu) + constants map[string]bool // Constants created (Module.Constant) + workflows map[string]bool // Workflows created (Module.Workflow) // Task queues created (Module.Queue, lower-cased — a queue is resolved // case-insensitively, like buildQueueQualifiedNames). Missing, a queue the // script creates was "not found" for every `in queue` call to it @@ -91,7 +98,10 @@ type scriptContext struct { // The parameters a call to a Java action the script creates must pass: // its entity-type and its required ones (ako/mxcli#2464, #2577). javaActionMustPass map[string]codeActionMustPass - customDocuments map[string]bool + // javaScriptActionMustPass is the same for the JavaScript actions the + // script creates (check-gap f85). + javaScriptActionMustPass map[string]codeActionMustPass + customDocuments map[string]bool // Entities the script declares, and those it alters, for resolving the // bare members of a retrieve constraint on an entity the project does not @@ -179,12 +189,14 @@ func newScriptContext() *scriptContext { indirectEntities: make(map[string]bool), externalEntityModules: make(map[string]bool), + unreadableImports: make(map[string]string), externalEntities: make(map[string]string), microflows: make(map[string]bool), nanoflows: make(map[string]bool), pages: make(map[string]bool), workflows: make(map[string]bool), snippets: make(map[string]bool), + snippetDecls: make(map[string]*ast.CreateSnippetStmtV3), layouts: make(map[string]bool), menus: make(map[string]bool), constants: make(map[string]bool), @@ -195,6 +207,7 @@ func newScriptContext() *scriptContext { javaActionFlowParams: make(map[string]map[string]bool), javaActionTemplateParams: make(map[string]map[string]bool), javaActionMustPass: make(map[string]codeActionMustPass), + javaScriptActionMustPass: make(map[string]codeActionMustPass), customDocuments: make(map[string]bool), entityDecls: make(map[string]*ast.CreateEntityStmt), viewEntityDecls: make(map[string]*ast.CreateViewEntityStmt), @@ -420,6 +433,7 @@ func (sc *scriptContext) collectSingle(stmt ast.Statement) { case *ast.CreateSnippetStmtV3: if s.Name.Module != "" { sc.snippets[s.Name.String()] = true + sc.snippetDecls[s.Name.String()] = s } case *ast.AlterPageStmt: if s.ContainerType == "PAGE" && s.PageName.Module != "" { @@ -467,6 +481,7 @@ func (sc *scriptContext) collectSingle(stmt ast.Statement) { case *ast.CreateJavaScriptActionStmt: if s.Name.Module != "" { sc.javaScriptActions[s.Name.String()] = codeActionParamNames(s.Parameters) + sc.javaScriptActionMustPass[s.Name.String()] = mustPassParams(s.Parameters) } } } @@ -573,6 +588,9 @@ func validateProgramWithWarnings(ctx *ExecContext, prog *ast.Program) ([]error, // Collect all objects defined in the script sc := newScriptContext() sc.collectDefinitions(prog) + // The entities a bulk external-entity import creates come from its + // contract, which needs the project to resolve (ako/mxcli#2674). + sc.collectBulkImportEntities(ctx, prog) // Validate each statement var errors []error @@ -1223,7 +1241,13 @@ func validateWithContext(ctx *ExecContext, stmt ast.Statement, sc *scriptContext return flowValidationError("javascript action", s.Name.String(), nil, errs) } case *ast.CreatePublishedRestServiceStmt: - return validatePublishedRestAuthMicroflow(ctx, s.Authentication, sc) + if err := validatePublishedRestAuthMicroflow(ctx, s.Authentication, sc); err != nil { + return err + } + if errs := publishedRestPathParamErrors(ctx, sc, s); len(errs) > 0 { + return mdlerrors.NewValidation(strings.Join(errs, "\n - ")) + } + return nil case *ast.CreateConsumedMCPServiceStmt: return validateConsumedMCPRefs(ctx, sc, s.Name, s.Endpoint, s.AuthenticationMicroflow) case *ast.AlterConsumedMCPServiceStmt: @@ -1837,6 +1861,8 @@ func validateFlowBodyReferences(ctx *ExecContext, body []ast.MicroflowStatement, } if declared, inScript := sc.javaScriptActions[ref.name]; inScript { errors = append(errors, validateCodeActionParams("javascript action", ref, declared)...) + must := sc.javaScriptActionMustPass[ref.name] + errors = append(errors, missingCodeActionArgs("javascript action", ref, declared, must.entityType, must.required)...) continue } if !known[ref.name] { @@ -1845,17 +1871,22 @@ func validateFlowBodyReferences(ctx *ExecContext, body []ast.MicroflowStatement, } if jsa, err := ctx.Backend.ReadJavaScriptActionByName(ref.name); err == nil && jsa != nil { declared := []string{} // read: an action with no parameters is known to have none - var entityTypeParams []string + var entityTypeParams, requiredParams []string for _, p := range jsa.Parameters { declared = append(declared, p.Name) + if p.IsRequired { + requiredParams = append(requiredParams, p.Name) + } if _, ok := p.ParameterType.(*javaactions.EntityTypeParameterType); ok { entityTypeParams = append(entityTypeParams, p.Name) } } errors = append(errors, validateCodeActionParams("javascript action", ref, declared)...) - // A JavaScript action's required parameter left out is not - // measured; only the entity-type rule applies there. - errors = append(errors, missingCodeActionArgs("javascript action", ref, declared, entityTypeParams, nil)...) + // A required parameter left out is CE0115 "The arguments that are + // passed to JavaScript action … do not match the expected + // parameters"; an optional one left out builds clean (measured + // on MxBuild 11.16.1, check-gap f85). + errors = append(errors, missingCodeActionArgs("javascript action", ref, declared, entityTypeParams, requiredParams)...) } } } @@ -1872,7 +1903,7 @@ func validateFlowBodyReferences(ctx *ExecContext, body []ast.MicroflowStatement, known := buildEntityQualifiedNames(ctx) for _, ref := range refs.entities { if !known[ref.name] && !sc.entities[ref.name] { - errors = append(errors, fmt.Sprintf("entity not found: %s (referenced by %s)", ref.name, ref.source)) + errors = append(errors, fmt.Sprintf("entity not found: %s (referenced by %s)%s", ref.name, ref.source, sc.unreadableImportHint(ref.name))) } } } diff --git a/mdl/executor/validate_assoc_as_attribute_test.go b/mdl/executor/validate_assoc_as_attribute_test.go index 7b05fb7078..be01bf1459 100644 --- a/mdl/executor/validate_assoc_as_attribute_test.go +++ b/mdl/executor/validate_assoc_as_attribute_test.go @@ -102,7 +102,7 @@ func TestCheck1440_AlterComboBoxAttributeNamingAnAssociation(t *testing.T) { msg := errs[0].Error() for _, want := range []string{"alter snippet M.S", "attributeEnumeration", "`Asset_Customer`", "association (M.Asset → M.Customer)", "CE1613", - "`combobox x (Attribute: $Asset.M.Asset_Customer, DataSource: database M.Customer"} { + "`combobox x (Association: $Asset.M.Asset_Customer, DataSource: database M.Customer"} { if !strings.Contains(msg, want) { t.Errorf("error does not name %q:\n%s", want, msg) } @@ -115,7 +115,7 @@ func TestCheck1440_AlterComboBoxControls(t *testing.T) { ctx := assocAsAttributeCtx(t) for _, w := range []string{ `combobox x (Attribute: $Asset.Code)`, - `combobox x (Attribute: $Asset.M.Asset_Customer, DataSource: database M.Customer, CaptionAttribute: CustomerName)`, + `combobox x (Association: $Asset.M.Asset_Customer, DataSource: database M.Customer, CaptionAttribute: CustomerName)`, } { if errs := checkAssocAsAttributeAlter(t, ctx, w); len(errs) != 0 { t.Errorf("%s: unexpected refusal %v", w, errs) diff --git a/mdl/executor/validate_attribute_for_association_2709_test.go b/mdl/executor/validate_attribute_for_association_2709_test.go new file mode 100644 index 0000000000..c4c8fbf038 --- /dev/null +++ b/mdl/executor/validate_attribute_for_association_2709_test.go @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "bytes" + "strings" + "testing" +) + +// ako/mxcli#2709 (mendixlabs/mxcli#1995): a combo box bound to an association +// was accepted under two spellings, `Association:` and `Attribute:`, and the +// readers of the script disagreed on the second: exec wrote the association, +// describe printed `Attribute:`, and the required-property check saw +// attributeAssociation unset and warned CE0642 (MDL-WIDGET56) on every +// describe → check round trip. `Association:` is now the one spelling: +// describe prints it, and check and exec refuse `Attribute:` naming the +// association with a message that names the fix. + +func TestAttributeNamingTheBoundAssociationIsRefused_2709(t *testing.T) { + def := comboBoxDefinition() + if def == nil { + t.Fatal("no built-in combo box definition") + } + cases := []struct { + name, props string + refused bool + }{ + {"association mode, Attribute: spelling (the report)", `Attribute: AreaPicker_District, DataSource: database Bm.District, CaptionAttribute: Name`, true}, + {"association mode, Association: (control)", `Association: AreaPicker_District, DataSource: database Bm.District, CaptionAttribute: Name`, false}, + {"enumeration mode, Attribute: names an attribute (control)", `Attribute: Kind`, false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + w := parseOneComboBox(t, c.props) + vs := validateAttributeForAssociation(def, w, "page Bm.P") + if got := len(vs) > 0; got != c.refused { + t.Fatalf("refused = %v, want %v: %v", got, c.refused, vs) + } + if !c.refused { + return + } + v := vs[0] + if v.RuleID != attributeForAssociationRule || v.Severity.String() != "error" { + t.Errorf("rule %s severity %v, want %s error", v.RuleID, v.Severity, attributeForAssociationRule) + } + for _, want := range []string{"`cb`", "`Attribute: AreaPicker_District`", "`Association: AreaPicker_District`"} { + if !strings.Contains(v.Message+" "+v.Suggestion, want) { + t.Errorf("refusal does not name %s:\n%s\n%s", want, v.Message, v.Suggestion) + } + } + }) + } +} + +// describe prints the spelling check and exec accept: `Association:` for a +// binding read from an association. +func TestDescribePrintsAssociationForAnAssociationBinding_2709(t *testing.T) { + for _, tc := range []struct { + assoc bool + want string + }{{true, "Association: Order_Customer"}, {false, "Attribute: Order_Customer"}} { + w := rawWidget{Type: "CustomWidgets$CustomWidget", Name: "cb", RenderMode: "combobox", Content: "Order_Customer", ContentIsAssociation: tc.assoc} + var buf bytes.Buffer + outputWidgetMDLV3(&ExecContext{Output: &buf}, w, 0) + if got := buf.String(); !strings.Contains(got, tc.want) { + t.Errorf("association=%v: describe printed\n%s\nwant %q", tc.assoc, got, tc.want) + } + } +} diff --git a/mdl/executor/validate_bulk_import_entities.go b/mdl/executor/validate_bulk_import_entities.go new file mode 100644 index 0000000000..05aecf9f0d --- /dev/null +++ b/mdl/executor/validate_bulk_import_entities.go @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "os" + "strings" + + "github.com/mendixlabs/mxcli/internal/pathutil" + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/types" + "github.com/mendixlabs/mxcli/sdk/domainmodel" +) + +// collectBulkImportEntities registers the entities each `create external +// entities from …` in the script will create, read from the service's +// contract with the executor's own selection and naming (bulkImportSelection). +// Without it a script that imports and then uses an entity was refused as +// "entity not found" by the check exec runs first (ako/mxcli#2674). +// +// The contract is the one exec will import from: a client the script creates +// before the import is read from its MetadataUrl, resolved against the +// project directory as exec resolves it; otherwise the stored client's cached +// $metadata. Only a local contract file is read here — exec fetches an HTTP +// one, the check does not go to the network. A contract the check cannot read +// registers nothing, so the reference stays an error, and the reason is kept +// to explain it (unreadableImports): the check cannot vouch for an entity it +// has not seen, and exec would report the same failure to import. +func (sc *scriptContext) collectBulkImportEntities(ctx *ExecContext, prog *ast.Program) { + clients := map[string]string{} // lower-cased Module.Client -> MetadataUrl, as the script declares it + for _, stmt := range prog.Statements { + switch s := stmt.(type) { + case *ast.CreateODataClientStmt: + clients[strings.ToLower(s.Name.String())] = s.MetadataUrl + case *ast.CreateExternalEntitiesStmt: + target := s.TargetModule + if target == "" { + target = s.ServiceRef.Module + } + if target == "" { + continue + } + doc, err := bulkImportContract(ctx, s.ServiceRef, clients) + if err != nil { + if sc.unreadableImports[target] == "" { + sc.unreadableImports[target] = fmt.Sprintf("create external entities from %s: %v", s.ServiceRef.String(), err) + } + continue + } + dm := storedDomainModel(ctx, target) + for _, sel := range bulkImportSelection(doc, s.EntityNames) { + _, name := sel.mendixName(dm, s.ServiceRef.String()) + sc.entities[target+"."+name] = true + } + } + } +} + +// bulkImportContract is the contract a bulk import reads: from the script's +// own client if it declares one earlier, else from the project. +func bulkImportContract(ctx *ExecContext, ref ast.QualifiedName, clients map[string]string) (*types.EdmxDocument, error) { + if rawURL, inScript := clients[strings.ToLower(ref.String())]; inScript { + if rawURL == "" { + return nil, fmt.Errorf("the client declares no MetadataUrl") + } + normalized, err := normalizeMetadataURL(ctx, rawURL) + if err != nil { + return nil, err + } + path := pathutil.PathFromURL(normalized) + if path == "" { + return nil, fmt.Errorf("the contract at %s is fetched by exec; the check does not fetch it", normalized) + } + body, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("read contract: %w", err) + } + return types.ParseEdmx(string(body)) + } + doc, _, err := parseServiceContract(ctx, ref) + return doc, err +} + +// storedDomainModel is the module's stored domain model, or nil when the +// module does not exist yet (the script creates it). +func storedDomainModel(ctx *ExecContext, module string) *domainmodel.DomainModel { + mod, err := findModule(ctx, module) + if err != nil || mod == nil { + return nil + } + dm, err := ctx.Backend.GetDomainModel(mod.ID) + if err != nil { + return nil + } + return dm +} + +// unreadableImportHint explains an entity-not-found in a module a bulk import +// targets whose contract the check could not read. +func (sc *scriptContext) unreadableImportHint(entityQN string) string { + if sc == nil { + return "" + } + if reason := sc.unreadableImports[qualifiedNameModule(entityQN)]; reason != "" { + return " — the script imports external entities into this module, but the check could not read the contract (" + + reason + "), so it cannot tell whether the import creates it" + } + return "" +} diff --git a/mdl/executor/validate_bulk_import_entities_2674_test.go b/mdl/executor/validate_bulk_import_entities_2674_test.go new file mode 100644 index 0000000000..dfc715f99a --- /dev/null +++ b/mdl/executor/validate_bulk_import_entities_2674_test.go @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/backend/mock" + "github.com/mendixlabs/mxcli/mdl/visitor" + "github.com/mendixlabs/mxcli/model" + "github.com/mendixlabs/mxcli/sdk/domainmodel" +) + +// ako/mxcli#2674 (defect 2): "`check --references` doesn't know about entities +// that `create external entities from …` will create, so a script that +// imports and then uses an entity fails without `--no-check`." Measured on +// main: exec refused the script with "microflow 'R3.ACT_Seasons' has +// reference errors: - entity not found: R3.Season (referenced by retrieve)". +const contract2674 = ` + + + + + + + + + + + + + + + + + + +` + +const useSeason2674 = ` +create microflow R3.ACT_Seasons () returns integer begin + retrieve $S from R3.Season; + $n = count($S); + return $n; +end;` + +// ctx2674 is a project holding module R3 and, when cached is set, a consumed +// service R3.Stored whose cached contract is contract2674. The contract file +// sits at contracts/live.xml next to the .mpr. +func ctx2674(t *testing.T, cached bool) *ExecContext { + t.Helper() + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "contracts"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "contracts", "live.xml"), []byte(contract2674), 0o644); err != nil { + t.Fatal(err) + } + mod := mkModule("R3") + h := mkHierarchy(mod) + var services []*model.ConsumedODataService + if cached { + svc := &model.ConsumedODataService{BaseElement: model.BaseElement{ID: nextID("cos")}, ContainerID: mod.ID, + Name: "Stored", MetadataUrl: "http://localhost/$metadata", ODataVersion: "4.0", Metadata: contract2674} + withContainer(h, svc.ContainerID, mod.ID) + services = append(services, svc) + } + dm := &domainmodel.DomainModel{} + dm.ID = nextID("dm") + mb := &mock.MockBackend{ + IsConnectedFunc: func() bool { return true }, + ListModulesFunc: func() ([]*model.Module, error) { return []*model.Module{mod}, nil }, + ListConsumedODataServicesFunc: func() ([]*model.ConsumedODataService, error) { + return services, nil + }, + GetDomainModelFunc: func(model.ID) (*domainmodel.DomainModel, error) { return dm, nil }, + ListDomainModelsFunc: func() ([]*domainmodel.DomainModel, error) { return []*domainmodel.DomainModel{dm}, nil }, + } + ctx, _ := newMockCtx(t, withBackend(mb), withHierarchy(h), withMprPath(filepath.Join(dir, "App.mpr"))) + return ctx +} + +func validate2674(t *testing.T, ctx *ExecContext, src string) string { + t.Helper() + prog, errs := visitor.Build(src) + if len(errs) > 0 { + t.Fatalf("parse: %v", errs) + } + var msgs []string + for _, e := range validateProgram(ctx, prog) { + msgs = append(msgs, e.Error()) + } + return strings.Join(msgs, "\n") +} + +// The client is created earlier in the same script: its MetadataUrl contract, +// resolved against the project directory as exec resolves it, names the +// entities the import will create. +func TestCheckKnowsBulkImportEntities_ClientInScript_2674(t *testing.T) { + ctx := ctx2674(t, false) + got := validate2674(t, ctx, ` +create or modify consumed odata service R3.Client (ODataVersion: OData4, MetadataUrl: './contracts/live.xml'); +create or modify external entities from R3.Client into R3 entities (Season);`+useSeason2674) + if got != "" { + t.Fatalf("want no reference errors, got:\n%s", got) + } +} + +// The client already exists in the project: its cached contract is read. +func TestCheckKnowsBulkImportEntities_StoredClient_2674(t *testing.T) { + ctx := ctx2674(t, true) + got := validate2674(t, ctx, ` +create or modify external entities from R3.Stored;`+useSeason2674) + if got != "" { + t.Fatalf("want no reference errors, got:\n%s", got) + } +} + +// Control: the ENTITIES filter leaves Season out, so it stays not found. +func TestCheckKnowsBulkImportEntities_FilterRespected_2674(t *testing.T) { + ctx := ctx2674(t, true) + got := validate2674(t, ctx, ` +create or modify external entities from R3.Stored entities (Driver);`+useSeason2674) + if !strings.Contains(got, "entity not found: R3.Season") { + t.Fatalf("want entity not found: R3.Season, got:\n%s", got) + } +} + +// Control: INTO places the entities in the target module, not the service's. +func TestCheckKnowsBulkImportEntities_IntoRespected_2674(t *testing.T) { + ctx := ctx2674(t, true) + got := validate2674(t, ctx, ` +create module Other; +create or modify external entities from R3.Stored into Other;`+useSeason2674) + if !strings.Contains(got, "entity not found: R3.Season") { + t.Fatalf("want entity not found: R3.Season, got:\n%s", got) + } +} + +// A contract the check cannot read registers nothing: the reference stays an +// error (the check cannot vouch for an entity it has not seen), and says why. +func TestCheckKnowsBulkImportEntities_UnreadableContract_2674(t *testing.T) { + ctx := ctx2674(t, false) + got := validate2674(t, ctx, ` +create or modify consumed odata service R3.Client (ODataVersion: OData4, MetadataUrl: './contracts/missing.xml'); +create or modify external entities from R3.Client into R3;`+useSeason2674) + if !strings.Contains(got, "entity not found: R3.Season") || !strings.Contains(got, "could not read the contract") { + t.Fatalf("want entity not found with the unreadable-contract reason, got:\n%s", got) + } +} diff --git a/mdl/executor/validate_combobox_caption_test.go b/mdl/executor/validate_combobox_caption_test.go index c7292ef837..8339b6a7bc 100644 --- a/mdl/executor/validate_combobox_caption_test.go +++ b/mdl/executor/validate_combobox_caption_test.go @@ -27,7 +27,6 @@ func TestMDLWIDGET16_ComboBoxCaptionRequired(t *testing.T) { // Association mode (the def selects it on a data source), no caption. {"database source, no caption", `Association: Bm.AreaPicker_District, DataSource: database Bm.District`, true}, {"microflow source, no caption", `Association: Bm.AreaPicker_District, DataSource: microflow Bm.DS_Districts`, true}, - {"Attribute: spelling of the association, no caption", `Attribute: AreaPicker_District, DataSource: database Bm.District`, true}, {"caption type expression, no expression", `Association: Bm.AreaPicker_District, DataSource: database Bm.District, optionsSourceAssociationCaptionType: expression`, true}, {"caption type expression, only an attribute", `Association: Bm.AreaPicker_District, DataSource: database Bm.District, optionsSourceAssociationCaptionType: expression, CaptionAttribute: Name`, true}, {"expression without the type", `Association: Bm.AreaPicker_District, DataSource: database Bm.District, optionsSourceAssociationCaptionExpression: '$currentObject/Name'`, true}, diff --git a/mdl/executor/validate_datasource_args.go b/mdl/executor/validate_datasource_args.go index db9e49dc87..9a5340b915 100644 --- a/mdl/executor/validate_datasource_args.go +++ b/mdl/executor/validate_datasource_args.go @@ -132,6 +132,9 @@ type flowSignature struct { // ReturnName is the return type as a message names it ("String", // "M.Entity", …), "" for nothing or unknown. ReturnName string + // ReturnEnum is the enumeration an enumeration-returning flow returns, "" + // otherwise (validate_workflow_outcomes.go). + ReturnEnum string } // paramNames returns the parameter names in declaration order, which is what the @@ -666,6 +669,9 @@ func buildFlowSignatures(ctx *ExecContext) map[string]*flowSignature { func sdkFlowSignature(params []*microflows.MicroflowParameter, ret microflows.DataType) *flowSignature { sig := &flowSignature{Returns: sdkDataTypeEntity(ret), ReturnKind: sdkReturnKind(ret)} + if et, ok := ret.(*microflows.EnumerationType); ok && et != nil { + sig.ReturnEnum = et.EnumerationQualifiedName + } switch { case ret == nil: case isSDKListType(ret): @@ -741,6 +747,9 @@ func astFlowSignature(params []ast.MicroflowParam, ret *ast.MicroflowReturnType) if ret != nil { sig.Returns = astDataTypeEntity(ret.Type) sig.ReturnKind = ret.Type.Kind + if ret.Type.Kind == ast.TypeEnumeration && ret.Type.EnumRef != nil { + sig.ReturnEnum = ret.Type.EnumRef.String() + } switch { case ret.Type.Kind == ast.TypeVoid: case ret.Type.Kind == ast.TypeListOf: diff --git a/mdl/executor/validate_flow_member_refs.go b/mdl/executor/validate_flow_member_refs.go index 5c52e37a4b..ef1630e7e3 100644 --- a/mdl/executor/validate_flow_member_refs.go +++ b/mdl/executor/validate_flow_member_refs.go @@ -138,6 +138,7 @@ func (r *flowMemberRefs) statementMembers(flowQN string, st ast.MicroflowStateme report(r.feedbackMember(s, vars)) case *ast.RetrieveStmt: report(r.bareRetrieveAssociation(s, vars)) + report(r.retrieveNonPersistent(s)) report(r.retrieveAssociationStart(s, vars)) case *ast.CreateObjectStmt: for _, ch := range s.Changes { diff --git a/mdl/executor/validate_mapping_snippet_gaps.go b/mdl/executor/validate_mapping_snippet_gaps.go new file mode 100644 index 0000000000..b080c1c8f6 --- /dev/null +++ b/mdl/executor/validate_mapping_snippet_gaps.go @@ -0,0 +1,458 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "strings" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/backend" + "github.com/mendixlabs/mxcli/mdl/linter" + "github.com/mendixlabs/mxcli/mdl/types" +) + +// Check-gap sweep 4, batch B (mdl-examples/check-gap f75 f76 f77 f78 f88 f89). +const ( + mappingValueRule = "MDL127" + importFromMappingRule = "MDL128" +) + +// --------------------------------------------------------------------------- +// 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.": +// +// JSON integer Integer, Long +// JSON decimal Decimal (an integer does NOT widen into it) +// JSON boolean Boolean +// JSON string String, Enumeration, DateTime +// +// 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). +// +// Judged only where both sides are known: a JSON member of one type wherever its +// name occurs (memberPrimitiveType), an attribute of a measured type. A value +// that goes through a converter microflow is not judged — the converter's +// parameter is what meets the JSON. + +type mappingAttr struct { + kind string // as astAttributeKind / attributeKind spell it + found bool // the attribute exists + known bool // the entity's members could be read +} + +// mappingAttrResolver answers an entity attribute's type from the script's +// declarations, then the project, through generalizations. +type mappingAttrResolver struct { + script map[string]*ast.CreateEntityStmt // lower-cased QN + altered map[string]bool + added map[string]map[string]string // lower-cased QN -> lower attr -> kind + open func() backend.FullBackend + b entityLookupBackend + opened bool +} + +func newMappingAttrResolver(prog *ast.Program, open func() backend.FullBackend) *mappingAttrResolver { + r := &mappingAttrResolver{script: map[string]*ast.CreateEntityStmt{}, altered: map[string]bool{}, + added: map[string]map[string]string{}, open: open} + for _, stmt := range prog.Statements { + switch s := stmt.(type) { + case *ast.CreateEntityStmt: + r.script[strings.ToLower(s.Name.String())] = s + case *ast.AlterEntityStmt: + key := strings.ToLower(s.Name.String()) + if s.Operation == ast.AlterEntityAddAttribute && s.Attribute != nil { + if r.added[key] == nil { + r.added[key] = map[string]string{} + } + r.added[key][strings.ToLower(s.Attribute.Name)] = astAttributeKind(s.Attribute.Type) + continue + } + r.altered[key] = true + } + } + return r +} + +func (r *mappingAttrResolver) project() entityLookupBackend { + if !r.opened { + r.opened = true + if r.open != nil { + if b := r.open(); b != nil { + r.b, _ = b.(entityLookupBackend) + } + } + } + return r.b +} + +func (r *mappingAttrResolver) attr(entity, name string) mappingAttr { + lname := strings.ToLower(name) + seen := map[string]bool{} + for cur := entity; cur != ""; { + key := strings.ToLower(cur) + if seen[key] || r.altered[key] { + return mappingAttr{} + } + seen[key] = true + if k, ok := r.added[key][lname]; ok { + return mappingAttr{kind: k, found: true, known: true} + } + if decl := r.script[key]; decl != nil { + for _, a := range decl.Attributes { + if strings.EqualFold(a.Name, name) { + return mappingAttr{kind: astAttributeKind(a.Type), found: true, known: true} + } + } + cur = "" + if decl.Generalization != nil { + cur = qualifyIn(decl.Name.Module, decl.Generalization.String()) + } + continue + } + b := r.project() + if b == nil { + return mappingAttr{} + } + ent, ok := findEntityByQN(b, cur) + if !ok || ent == nil { + return mappingAttr{} + } + for _, a := range ent.Attributes { + if a != nil && strings.EqualFold(a.Name, name) { + return mappingAttr{kind: attributeKind(a.Type), found: true, known: true} + } + } + cur = ent.GeneralizationRef + } + return mappingAttr{known: true} +} + +// 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) { + 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 + } + return false, false +} + +func ValidateMappingValues(prog *ast.Program, open func() backend.FullBackend) []linter.Violation { + if prog == nil { + return nil + } + samples := map[string]string{} + for _, stmt := range prog.Statements { + if s, ok := stmt.(*ast.CreateJsonStructureStmt); ok { + samples[s.Name.String()] = s.JsonSnippet + } + } + elemsOf := func(ref ast.QualifiedName) []*types.JsonElement { + if sample, ok := samples[ref.String()]; ok { + elems, _ := types.BuildJsonElementsFromSnippet(sample, nil, nil) + return elems + } + if open != nil { + if b := open(); b != nil { + if js, err := b.GetJsonStructureByQualifiedName(ref.Module, ref.Name); err == nil && js != nil { + return js.Elements + } + } + } + return nil + } + r := newMappingAttrResolver(prog, open) + var out []linter.Violation + judge := func(kind string, mapping ast.QualifiedName, entity, attr, member string, elems []*types.JsonElement) { + if entity == "" || attr == "" || member == "" { + return + } + loc := linter.Location{Module: mapping.Module, DocumentType: kind, DocumentName: mapping.Name} + a := r.attr(entity, attr) + if !a.known { + return + } + if !a.found { + out = append(out, linter.Violation{RuleID: mappingValueRule, Severity: linter.SeverityError, Location: loc, + Message: fmt.Sprintf("%s %s maps %s to the attribute %s.%s, which the entity does not have — mxbuild reports "+ + "CE1613 \"The selected attribute '%s.%s' no longer exists.\"", kind, mapping, member, entity, attr, entity, attr), + Suggestion: "Name an attribute of " + entity + " (or an entity it extends)."}) + return + } + json := memberPrimitiveType(elems, member) + accepted, judged := mappingValueAccepted(json, a.kind) + if !judged || accepted { + return + } + 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)`)."}) + } + for _, stmt := range prog.Statements { + switch m := stmt.(type) { + case *ast.CreateImportMappingStmt: + if m.RootElement == nil || m.SchemaKind != "JSON_STRUCTURE" || m.SchemaRef.Module == "" { + continue + } + elems := elemsOf(m.SchemaRef) + var walk func(e *ast.ImportMappingElementDef, entity string) + walk = func(e *ast.ImportMappingElementDef, entity string) { + if e.Entity != "" { + entity = qualifyIn(m.Name.Module, e.Entity) + } else if e.Attribute != "" && e.Converter == "" { + judge("import mapping", m.Name, entity, e.Attribute, e.JsonName, elems) + } + for _, c := range e.Children { + if c != nil { + walk(c, entity) + } + } + } + walk(m.RootElement, "") + case *ast.CreateExportMappingStmt: + if m.RootElement == nil || m.SchemaKind != "JSON_STRUCTURE" || m.SchemaRef.Module == "" { + continue + } + elems := elemsOf(m.SchemaRef) + var walk func(e *ast.ExportMappingElementDef, entity string) + walk = func(e *ast.ExportMappingElementDef, entity string) { + if e.Entity != "" { + entity = qualifyIn(m.Name.Module, e.Entity) + } else if e.Attribute != "" && e.Converter == "" { + judge("export mapping", m.Name, entity, e.Attribute, e.JsonName, elems) + } + for _, c := range e.Children { + if c != nil { + walk(c, entity) + } + } + } + walk(m.RootElement, "") + } + } + return out +} + +// --------------------------------------------------------------------------- +// MDL128 — `import from mapping` fed something that is not text (f78). +// +// Measured on MxBuild 11.16.1: a String or a System.FileDocument builds; an +// Integer, a list or an object of an ordinary entity is CE0239 "Variable should +// be a string or a specialization of type 'System.FileDocument' or +// 'System.HttpMessage', but is …". The variable's type comes from the flow's +// parameters and declarations; an object is judged through its generalization +// chain, and one whose chain cannot be read completely is not judged. + +func ValidateImportFromMappingInputs(prog *ast.Program, open func() backend.FullBackend) []linter.Violation { + if prog == nil { + return nil + } + chains := newScriptProjectChains(prog, open) + var out []linter.Violation + judge := func(kind string, name ast.QualifiedName, params []ast.MicroflowParam, body []ast.MicroflowStatement) { + vars := map[string]ast.DataType{} + for _, p := range params { + vars[p.Name] = p.Type + } + forEachMicroflowStatement(body, func(s ast.MicroflowStatement) { + switch st := s.(type) { + case *ast.DeclareStmt: + vars[st.Variable] = st.Type + case *ast.ImportFromMappingStmt: + t, ok := vars[strings.TrimPrefix(st.SourceVariable, "$")] + if !ok { + return + } + what := "" + switch { + case t.Kind == ast.TypeString: + return + case t.Kind == ast.TypeListOf: + what = "a list" + case t.EntityRef != nil: + entity := qualifyIn(name.Module, t.EntityRef.String()) + chain, complete := chains.chain(entity) + for _, e := range chain { + if strings.EqualFold(e, "System.FileDocument") || strings.EqualFold(e, "System.HttpMessage") { + return + } + } + if !complete { + return + } + what = "a " + entity + case t.Kind == ast.TypeInteger || t.Kind == ast.TypeLong || t.Kind == ast.TypeDecimal || + t.Kind == ast.TypeBoolean || t.Kind == ast.TypeDateTime: + what = withAn(t.Kind.String()) + default: + return + } + out = append(out, linter.Violation{RuleID: importFromMappingRule, Severity: linter.SeverityError, + Location: linter.Location{Module: name.Module, DocumentType: kind, DocumentName: name.Name}, + Message: fmt.Sprintf("%s %s: import from mapping %s reads $%s, which is %s — an import mapping reads text: "+ + "a String or a System.FileDocument (or HttpMessage) specialization; mxbuild reports CE0239", + kind, name, st.Mapping, strings.TrimPrefix(st.SourceVariable, "$"), what), + Suggestion: "Pass the JSON text: a String variable, or the file document holding it."}) + } + }) + } + for _, stmt := range prog.Statements { + switch s := stmt.(type) { + case *ast.CreateMicroflowStmt: + judge("microflow", s.Name, s.Parameters, s.Body) + case *ast.CreateNanoflowStmt: + judge("nanoflow", s.Name, s.Parameters, s.Body) + } + } + return out +} + +// --------------------------------------------------------------------------- +// Snippet call parameters (f88, f89), in the page walk. +// +// Measured on MxBuild 11.16.1, a snippet with ($I: Sp.Item), Sp.Item extends +// Sp.Base, Sp.Sub extends Sp.Item: passing a Sp.Item or a Sp.Sub builds; a +// Sp.Base (a generalization) or an unrelated entity is CE0115 "The arguments +// that are passed to snippet … do not match the expected parameters". A +// parameter left out is legal exactly when the data context supplies its entity +// — exec refuses it otherwise (buildSnippetCallParams); this is that refusal, in +// check, with exec's words. + +type snippetParamDecl struct { + name, entity, primitive string +} + +func (v *attributeScopeValidator) snippetParams(qn string) ([]snippetParamDecl, bool) { + if v.snippetSigs == nil { + v.snippetSigs = map[string][]snippetParamDecl{} + if v.sc != nil { + for name, decl := range v.sc.snippetDecls { + var ps []snippetParamDecl + for _, p := range decl.Parameters { + d := snippetParamDecl{name: p.Name} + if e := p.EntityType.String(); e != "" && e != "." { + d.entity = e + } else { + d.primitive = p.Type.Kind.String() + } + ps = append(ps, d) + } + v.snippetSigs[strings.ToLower(name)] = ps + } + } + if ctx := v.pb.ctx; ctx != nil && ctx.Backend != nil { + if h, err := getHierarchy(ctx); err == nil && h != nil { + if all, err := ctx.Backend.ListSnippets(); err == nil { + for _, s := range all { + if s == nil { + continue + } + key := strings.ToLower(h.GetQualifiedName(s.ContainerID, s.Name)) + if _, scripted := v.snippetSigs[key]; scripted || key == "" { + continue + } + var ps []snippetParamDecl + for _, p := range s.Parameters { + if p != nil { + ps = append(ps, snippetParamDecl{name: p.Name, entity: p.EntityName, primitive: p.Type}) + } + } + v.snippetSigs[key] = ps + } + } + } + } + } + ps, ok := v.snippetSigs[strings.ToLower(qn)] + return ps, ok +} + +// entityExtends reports whether child is entity or a specialization of it, and +// whether the chain could be read completely. +func (v *attributeScopeValidator) entityExtends(child, entity string) (yes, complete bool) { + chain, complete := scriptGeneralizationChain(v.pb.ctx, v.sc, child) + for _, e := range chain { + if strings.EqualFold(e, entity) { + return true, true + } + } + return false, complete +} + +func (v *attributeScopeValidator) checkSnippetCallParams(w *ast.WidgetV3, enclosing dataContext) { + if !strings.EqualFold(w.Type, "snippetcall") { + return + } + qn, _ := w.Properties["Snippet"].(string) + if qn == "" { + return + } + params, ok := v.snippetParams(qn) + if !ok || len(params) == 0 { + return + } + supplied := map[string]string{} + for _, p := range w.GetSnippetParams() { + supplied[strings.ToLower(strings.TrimPrefix(p.ParamName, "$"))] = p.Variable + } + for _, d := range params { + arg, given := supplied[strings.ToLower(d.name)] + if !given { + if d.primitive != "" && d.entity == "" { + v.errs = append(v.errs, fmt.Sprintf("snippet %s requires parameter $%s — add Params: (%s = $) to the SNIPPETCALL, "+ + "passing a page parameter, page variable or snippet parameter of that type", qn, d.name, d.name)) + continue + } + if enclosing.unresolved || d.entity == "" { + continue + } + supplies := false + for _, e := range enclosing.entities { + if yes, _ := v.entityExtends(e, d.entity); yes { + supplies = true + } + if yes, _ := v.entityExtends(d.entity, e); yes { + supplies = true + } + } + if !supplies { + v.errs = append(v.errs, fmt.Sprintf("snippet %s requires parameter $%s — add Params: (%s = $) to the SNIPPETCALL, "+ + "or place the call inside a data context of %s so the parameter is satisfied from it", qn, d.name, d.name, d.entity)) + } + continue + } + if d.entity == "" || isContextArgument(arg) { + continue + } + argEntity := v.paramEntity(strings.TrimPrefix(arg, "$")) + if argEntity == "" { + continue + } + yes, complete := v.entityExtends(argEntity, d.entity) + if yes || !complete { + continue + } + v.errs = append(v.errs, fmt.Sprintf("snippetcall `%s`: snippet %s's parameter $%s is a %s, but %s is a %s — the argument "+ + "must be that entity or a specialization of it; mxbuild reports CE0115 \"The arguments that are passed to snippet … "+ + "do not match the expected parameters\"", w.Name, qn, d.name, d.entity, arg, argEntity)) + } +} diff --git a/mdl/executor/validate_microflow.go b/mdl/executor/validate_microflow.go index 1fd53ad160..290960d605 100644 --- a/mdl/executor/validate_microflow.go +++ b/mdl/executor/validate_microflow.go @@ -52,6 +52,19 @@ func validateMicroflowWith(stmt *ast.CreateMicroflowStmt, voids *voidCodeActions v.params = stmt.Parameters v.excluded = stmt.Excluded v.validate(stmt.Body) + // A JavaScript action runs in the client: a microflow cannot call one. + // Measured on MxBuild 11.16.1, with and without an output variable: CE0009 + // "This action is not supported in microflows." (check-gap f83) + forEachMicroflowStatement(stmt.Body, func(s ast.MicroflowStatement) { + js, ok := s.(*ast.CallJavaScriptActionStmt) + if !ok { + return + } + v.addViolation("MDL126", linter.SeverityError, + fmt.Sprintf("call javascript action %s: a JavaScript action runs in the client and is not supported in a microflow — "+ + "mxbuild reports CE0009 \"This action is not supported in microflows.\"", js.ActionName), + "Call it from a nanoflow, or do the work in a Java action or the microflow itself.") + }) return v.violations } diff --git a/mdl/executor/validate_nonpersistent_sources.go b/mdl/executor/validate_nonpersistent_sources.go new file mode 100644 index 0000000000..5793b8fb94 --- /dev/null +++ b/mdl/executor/validate_nonpersistent_sources.go @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "strings" + + "github.com/mendixlabs/mxcli/mdl/ast" +) + +// A non-persistent entity has no table, so nothing can read it from the database +// (check-gap f91 f92 f93). Measured on MxBuild 11.16.1, one project per case: +// +// data grid / list view / gallery with `datasource: database NP` +// CE8812 "The entity 'Sp.NP' cannot be used here, because it is not persistable." +// retrieve $L from NP — plain, `first` or `where`, in a microflow or a nanoflow +// CE0056 "Entity 'Sp.NP' cannot be retrieved from the database because it is non-persistable." +// the same over a persistent entity clean +// +// Only an entity that is established to be non-persistent is judged: one the +// script declares `non-persistent`, or a stored one whose Persistable flag is +// off. An external (OData) or view entity is not judged — its data does not come +// from a table either, but a database source over it is how it is read. + +// nonPersistentEntity reports whether entityQN is established to be +// non-persistent. +func nonPersistentEntity(ctx *ExecContext, sc *scriptContext, entityQN string) bool { + if entityQN == "" || !strings.Contains(entityQN, ".") { + return false + } + if sc != nil { + if decl := sc.entityDecls[entityQN]; decl != nil { + // A specialization whose kind the statement does not state takes + // its generalization's; only a stated kind (or a root) is known. + return decl.Kind == ast.EntityNonPersistent && (decl.KindStated || decl.Generalization == nil) + } + if sc.entities[entityQN] || sc.viewEntities[entityQN] { + return false // made by a statement that is not a plain entity + } + } + if ctx == nil { + return false + } + b, ok := ctx.Backend.(entityLookupBackend) + if !ok { + return false + } + e, found := findEntityByQN(b, entityQN) + if !found || e == nil { + return false + } + if e.RemoteServiceName != "" || isViewEntity(e) { + return false + } + return !e.Persistable +} + +// checkDatabaseSourcePersistable reports a list widget whose database source is +// a non-persistent entity (CE8812). +func (v *attributeScopeValidator) checkDatabaseSourcePersistable(w *ast.WidgetV3) { + ds := w.GetDataSource() + if ds == nil || ds.Type != "database" || ds.Reference == "" { + return + } + switch strings.ToLower(w.Type) { + case "datagrid", "listview", "gallery": + default: + return + } + entity := unquoteQualifiedName(ds.Reference) + if !nonPersistentEntity(v.pb.ctx, v.sc, entity) { + return + } + v.errs = append(v.errs, fmt.Sprintf( + "%s `%s`: its database source %s is non-persistent, so it has no table to read — mxbuild reports CE8812 "+ + "\"The entity '%s' cannot be used here, because it is not persistable.\" Use a microflow or nanoflow data source "+ + "that builds the objects", w.Type, w.Name, entity, entity)) +} + +// retrieveNonPersistent reports a database retrieve of a non-persistent entity +// (CE0056). +func (r *flowMemberRefs) retrieveNonPersistent(s *ast.RetrieveStmt) string { + if s.StartVariable != "" || s.Source.Module == "" || s.Source.Name == "" { + return "" + } + entity := s.Source.String() + if !nonPersistentEntity(r.ctx, r.sc, entity) { + return "" + } + return fmt.Sprintf("retrieve $%s from %s: %s is non-persistent, so it cannot be retrieved from the database — "+ + "mxbuild reports CE0056 \"Entity '%s' cannot be retrieved from the database because it is non-persistable.\" "+ + "Keep the objects in a list variable, or reach them over an association", + s.Variable, entity, entity, entity) +} diff --git a/mdl/executor/validate_own_container_slots_2109_test.go b/mdl/executor/validate_own_container_slots_2109_test.go index aa19454569..b6b5d49b32 100644 --- a/mdl/executor/validate_own_container_slots_2109_test.go +++ b/mdl/executor/validate_own_container_slots_2109_test.go @@ -61,7 +61,7 @@ func comboBoxOptionContentPage(visible string) string { return `mdl 1; create page M.Edit ( Title: 'Edit', Layout: Atlas_Core.PopupLayout, Params: ( $Agent: M.Agent ) ) { dataview dataView2 ( DataSource: $Agent ) { - combobox comboBox3 ( Attribute: Agent_Version_InUse, DataSource: database from M.Version, optionsSourceAssociationCustomContentType: 'yes' ) { + combobox comboBox3 ( Association: Agent_Version_InUse, DataSource: database from M.Version, optionsSourceAssociationCustomContentType: 'yes' ) { optionssourceassociationcustomcontent { container container5 ( Visible: ` + visible + ` ) } diff --git a/mdl/executor/validate_program.go b/mdl/executor/validate_program.go index 8d6ad8edbc..b4ccd7e457 100644 --- a/mdl/executor/validate_program.go +++ b/mdl/executor/validate_program.go @@ -52,6 +52,13 @@ func ValidateProgram(prog *ast.Program, projectPath string) []linter.Violation { violations = append(violations, ValidateMappingAssociations(prog, project)...) // An alter that leaves a published OData attribute published as the wrong type (CE5016). violations = append(violations, ValidatePublishedAttributeTypes(prog, project)...) + // A mapping value of the wrong type (CE5015) or naming no attribute (CE1613), + // and an import from mapping fed something that is not text (CE0239). + violations = append(violations, ValidateMappingValues(prog, project)...) + violations = append(violations, ValidateImportFromMappingInputs(prog, project)...) + // A published REST service path, resource or operation the build rejects + // (CE3471, CE0357, CE0331, CE0358). + violations = append(violations, ValidatePublishedRestShape(prog)...) for _, stmt := range prog.Statements { // Check enumeration values for reserved words if enumStmt, ok := stmt.(*ast.CreateEnumerationStmt); ok { diff --git a/mdl/executor/validate_published_rest_gaps.go b/mdl/executor/validate_published_rest_gaps.go new file mode 100644 index 0000000000..f23281e662 --- /dev/null +++ b/mdl/executor/validate_published_rest_gaps.go @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "regexp" + "strings" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/linter" +) + +// Check-gap sweep 4, batch C (mdl-examples/check-gap f80 f81 f82): published +// REST services MxBuild 11.16.1 rejects. Measured there, one service per case: +// +// service path '/rest/x/v1' CE3471 "The path should not start with a /." +// service path 'rest/x/v1/' clean +// resource '/items' CE0357 "The resource name should be a well-formed uri string." +// two resources 'items' CE0331 "Duplicate resource name 'items'." +// get '' twice CE0358 "Operation has a conflicting path 'GET /items'." +// get 'x' and get 'x/' CE0358 (a trailing slash does not tell them apart) +// get '{id}' and get '{key}' CE0358 (nor does a path parameter's name) +// get 'a' and get 'A', or get '' and post '' clean (case and method do) +// get '/x' clean +// get '{id}', microflow without $id CE1613 "The selected parameter '….id' no longer exists." +// get '{Id}', microflow with $id CE0352 "The operation path contains a parameter that is not in the parameter list: 'Id'." +// get '{a}/{b}', microflow with $a only CE0352 (… 'b') +// +// The first four need nothing but the statement (MDL129); a path parameter +// needs the microflow's parameters, so it is judged in the reference pass. + +const publishedRestShapeRule = "MDL129" + +var restPathParam = regexp.MustCompile(`\{[^}]*\}`) + +// publishedRestConflictKey is the operation as MxBuild compares it: method, +// resource and path without surrounding slashes, each path parameter alike. +func publishedRestConflictKey(resource, method, path string) string { + return publishedRestOperationKey(resource, method, restPathParam.ReplaceAllString(path, "{}")) +} + +func ValidatePublishedRestShape(prog *ast.Program) []linter.Violation { + if prog == nil { + return nil + } + var out []linter.Violation + for _, stmt := range prog.Statements { + s, ok := stmt.(*ast.CreatePublishedRestServiceStmt) + if !ok { + continue + } + loc := linter.Location{Module: s.Name.Module, DocumentType: "published rest service", DocumentName: s.Name.Name} + report := func(msg, suggestion string) { + out = append(out, linter.Violation{RuleID: publishedRestShapeRule, Severity: linter.SeverityError, + Location: loc, Message: "published rest service " + s.Name.String() + ": " + msg, Suggestion: suggestion}) + } + if strings.HasPrefix(s.Path, "/") { + report(fmt.Sprintf("the path '%s' starts with a slash — mxbuild reports CE3471 \"The path should not start with a /.\"", s.Path), + "Write the path without the leading slash: '"+strings.TrimLeft(s.Path, "/")+"'.") + } + resources := map[string]bool{} + for _, r := range s.Resources { + if r == nil { + continue + } + if strings.HasPrefix(r.Name, "/") { + report(fmt.Sprintf("the resource name '%s' starts with a slash — mxbuild reports CE0357 \"The resource name should be "+ + "a well-formed uri string.\"", r.Name), "Name the resource without the slash: '"+strings.TrimLeft(r.Name, "/")+"'.") + } + if resources[r.Name] { + report(fmt.Sprintf("the resource '%s' is declared twice — mxbuild reports CE0331 \"Duplicate resource name '%s'.\"", r.Name, r.Name), + "Put the operations in one resource block.") + } + resources[r.Name] = true + ops := map[string]bool{} + for _, op := range r.Operations { + if op == nil { + continue + } + key := publishedRestConflictKey(r.Name, op.HTTPMethod, op.Path) + if ops[key] { + report(fmt.Sprintf("resource '%s' has two %s operations on the path '%s' — a trailing slash or a path parameter's "+ + "name does not tell them apart; mxbuild reports CE0358 \"Operation has a conflicting path …\"", + r.Name, strings.ToUpper(op.HTTPMethod), op.Path), + "Give each operation of a method its own path.") + } + ops[key] = true + } + } + } + return out +} + +// publishedRestPathParamErrors reports, in the reference pass, an operation +// path naming a parameter its microflow does not have (CE0352, CE1613). The +// match is case-sensitive, as exec's derivation of path parameters is. +func publishedRestPathParamErrors(ctx *ExecContext, sc *scriptContext, s *ast.CreatePublishedRestServiceStmt) []string { + var errs []string + var project map[string]*flowSignature + for _, r := range s.Resources { + if r == nil { + continue + } + for _, op := range r.Operations { + if op == nil || !strings.Contains(op.Path, "{") { + continue + } + qn := op.Microflow.String() + key := strings.ToLower(qn) + sig, ok := (*flowSignature)(nil), false + if sc != nil { + sig, ok = sc.flowParams[key] + } + if !ok && ctx != nil && ctx.Connected() { + if project == nil { + project = buildFlowSignatures(ctx) + } + sig, ok = project[key] + } + if !ok || sig == nil { + continue + } + have := map[string]bool{} + for _, p := range sig.Params { + have[p.Name] = true + } + declared := "no parameters" + if names := sig.paramNames(); len(names) > 0 { + declared = "$" + strings.Join(names, ", $") + } + for _, m := range restPathParam.FindAllString(op.Path, -1) { + name := strings.TrimSuffix(strings.TrimPrefix(m, "{"), "}") + if name == "" || have[name] { + continue + } + errs = append(errs, fmt.Sprintf("published rest service %s: %s '%s' in resource '%s' names the path parameter {%s}, "+ + "but microflow %s has no parameter $%s (it declares %s) — the name must match exactly, case included; "+ + "mxbuild reports CE0352 \"The operation path contains a parameter that is not in the parameter list\" or CE1613", + s.Name, strings.ToUpper(op.HTTPMethod), op.Path, r.Name, name, qn, name, declared)) + } + } + } + return errs +} diff --git a/mdl/executor/validate_widget_attribute_scope.go b/mdl/executor/validate_widget_attribute_scope.go index 56585e1b58..8158a029e5 100644 --- a/mdl/executor/validate_widget_attribute_scope.go +++ b/mdl/executor/validate_widget_attribute_scope.go @@ -80,6 +80,7 @@ func validatePluggableAttributeScopes(ctx *ExecContext, layout string, params [] if sc != nil { v.generalizations = sc.entityGeneralizations v.decls = sc.entityDecls + v.sc = sc v.scriptNames = scriptDeclaredNames(sc) } for _, w := range widgets { @@ -121,6 +122,9 @@ type attributeScopeValidator struct { // decls are the script's entity declarations, for the audit fields' // declared names (validate_expr_system_member.go). decls map[string]*ast.CreateEntityStmt + // sc is the whole script's context, for the questions decls alone cannot + // answer (validate_nonpersistent_sources.go). + sc *scriptContext // scriptNames are the entities and associations this script declares, // lower-cased, both qualified and short: what the stored model cannot @@ -130,6 +134,10 @@ type attributeScopeValidator struct { // members resolves the members a widget expression names, with the // microflow expression check's verdict (validate_expr_system_member.go). members *flowMemberRefs + + // snippetSigs caches snippet parameter lists, lower-cased qualified name + // -> parameters (validate_mapping_snippet_gaps.go). + snippetSigs map[string][]snippetParamDecl } // paramEntity is the entity of the document parameter `$name`, or "". @@ -157,11 +165,13 @@ func (v *attributeScopeValidator) walk(w *ast.WidgetV3, enclosing dataContext) { v.checkAssocHopStart(w, enclosing) v.checkReactUnsupported(w) v.checkExprSystemMembers(w, enclosing) + v.checkDatabaseSourcePersistable(w) // Check-gap sweep 3: a data source's return shape, a non-Boolean // condition, an action argument of the wrong type (validate_page_gaps.go). v.checkDataSourceShape(w) v.checkBooleanConditions(w, enclosing) v.checkActionArgTypes(w, enclosing, inner) + v.checkSnippetCallParams(w, enclosing) v.checkQualifiedAttributePaths(w, enclosing) if v.registry == nil { // No registry: the pluggable half cannot run, and a pluggable widget's diff --git a/mdl/executor/validate_widget_attribute_type_test.go b/mdl/executor/validate_widget_attribute_type_test.go index eba69ac0e2..8ebcf84f4b 100644 --- a/mdl/executor/validate_widget_attribute_type_test.go +++ b/mdl/executor/validate_widget_attribute_type_test.go @@ -341,7 +341,7 @@ func TestCheck_ComboBoxOnBooleanIsCE7247(t *testing.T) { func TestCheck_ComboBoxAssociationModeIsNotTypeChecked(t *testing.T) { ctx := typeCheckCtx(t, "Yes") errs := typeErrs(t, ctx, `dataview dv (datasource: $Thing) { - combobox cb1 (label: 'O', attribute: Thing_Other, datasource: database Sales.Other, CaptionAttribute: Txt) + combobox cb1 (label: 'O', Association: Thing_Other, datasource: database Sales.Other, CaptionAttribute: Txt) }`, nil) for _, e := range errs { if strings.Contains(e, "MDL-WIDGET39") { diff --git a/mdl/executor/validate_widget_required.go b/mdl/executor/validate_widget_required.go index 19987fcd72..d1699baacd 100644 --- a/mdl/executor/validate_widget_required.go +++ b/mdl/executor/validate_widget_required.go @@ -111,9 +111,32 @@ func requiredSuggestion(p mpk.PropertyDef, def *WidgetDefinition) string { } } } + // The MDL keyword that fills the property, when one does: the storage + // key is refused as MDL-WIDGET01 (ako/mxcli#2709). + if kw := mdlKeywordFor(def, p.Key); kw != "" { + return fmt.Sprintf("set `%s:`", kw) + } return fmt.Sprintf("set `%s:`", p.Key) } +// mdlKeywordFor is the MDL source keyword def maps to the property key, in +// the top-level mappings or any mode's; "" when none does. +func mdlKeywordFor(def *WidgetDefinition, key string) string { + if def == nil { + return "" + } + all := append([]PropertyMapping{}, def.PropertyMappings...) + for _, m := range def.Modes { + all = append(all, m.PropertyMappings...) + } + for _, m := range all { + if m.Source != "" && strings.EqualFold(m.PropertyKey, key) { + return m.Source + } + } + return "" +} + // requiredTopLevelProps returns the widget's required, non-system top-level // properties as its installed package declares them; nil without one. func requiredTopLevelProps(projectPath, widgetID string) []mpk.PropertyDef { diff --git a/mdl/executor/validate_widgets.go b/mdl/executor/validate_widgets.go index 6154856304..2acdd6803a 100644 --- a/mdl/executor/validate_widgets.go +++ b/mdl/executor/validate_widgets.go @@ -285,6 +285,9 @@ func validateWidgetTreeIn(widgets []*ast.WidgetV3, registry *WidgetRegistry, loc out = append(out, validatePluggableTemplateParams(w, locationPrefix)...) } out = append(out, validateWidgetVisibility(w, registry, locationPrefix)...) + // `Attribute:` naming the association the widget binds; the one + // spelling is `Association:` (MDL-WIDGET57, ako/mxcli#2709). + out = append(out, validateAttributeForAssociation(lookupWidgetDef(w, registry), w, locationPrefix)...) // A required property the package declares, left unset: CE0642 / // CE4899 at build time (MDL-WIDGET56). out = append(out, validateWidgetRequired(w, registry, locationPrefix)...) @@ -505,6 +508,63 @@ func validateComboBoxAssociation(w *ast.WidgetV3, locationPrefix string) []linte }} } +// attributeForAssociationRule refuses `Attribute:` naming the association a +// widget's mode binds (ako/mxcli#2709). +const attributeForAssociationRule = "MDL-WIDGET57" + +// attributeNamesBoundAssociation reports whether w writes the association its +// mode binds under `Attribute:`: the mode def selects for w maps a property +// from `Association:` and none from `Attribute:`, and w sets `Attribute:` but +// not `Association:`. That spelling was accepted as an alias, and the readers +// of a script disagreed on it — exec wrote the association, the +// required-property check saw it unset (MDL-WIDGET56) — so there is one +// spelling, `Association:`, and this one is refused by check and exec alike. +func attributeNamesBoundAssociation(def *WidgetDefinition, w *ast.WidgetV3) bool { + if def == nil || w == nil || w.GetStringProp("Association") != "" || w.GetAttribute() == "" { + return false + } + mode, err := (&PluggableWidgetEngine{}).selectMode(def, w) + if err != nil || mode == nil { + return false + } + takesAssociation := false + for _, mappings := range [][]PropertyMapping{def.PropertyMappings, mode.PropertyMappings} { + for _, m := range mappings { + switch m.Source { + case "Association": + takesAssociation = true + case "Attribute": + return false + } + } + } + return takesAssociation +} + +// attributeForAssociationMessage is the refusal check and exec give. +func attributeForAssociationMessage(w *ast.WidgetV3) (message, suggestion string) { + attr := w.GetAttribute() + message = fmt.Sprintf("%s `%s` binds an association, written `Attribute: %s`: an association is written `Association:`", + strings.ToLower(w.Type), w.Name, attr) + suggestion = fmt.Sprintf("Write `Association: %s` instead of `Attribute: %s`; `Attribute:` names an attribute. "+ + "describe prints `Association:` for this binding.", attr, attr) + return message, suggestion +} + +// validateAttributeForAssociation is MDL-WIDGET57 (attributeNamesBoundAssociation). +func validateAttributeForAssociation(def *WidgetDefinition, w *ast.WidgetV3, locationPrefix string) []linter.Violation { + if !attributeNamesBoundAssociation(def, w) { + return nil + } + msg, suggestion := attributeForAssociationMessage(w) + return []linter.Violation{{ + RuleID: attributeForAssociationRule, + Severity: linter.SeverityError, + Message: locationPrefix + ": " + msg, + Suggestion: suggestion, + }} +} + // comboBoxDefinition is the built-in combo box definition. Check asks its mode // selection rather than restating it, so the two cannot drift. var comboBoxDefinition = sync.OnceValue(func() *WidgetDefinition { @@ -1262,6 +1322,8 @@ var staticWidgetKnownProps = func() map[string]bool { "Password", "Validation", "ValidationMessage", // A text box's Auto focus (ako/mxcli#2519). "AutoFocus", + // An input's Aria required, a text box's autocomplete purpose (ako/mxcli#2710). + "AriaRequired", "AutocompletePurpose", // a text area's (ako/mxcli#977) "NumberOfLines", "Autocomplete", // button icon-collection reference (issue #602) diff --git a/mdl/executor/validate_workflow.go b/mdl/executor/validate_workflow.go index 748498664a..b9eac1cacf 100644 --- a/mdl/executor/validate_workflow.go +++ b/mdl/executor/validate_workflow.go @@ -237,8 +237,9 @@ func lastSegment(s string) string { // // mxbuild wants set EQUALITY, so a missing enumeration *value* is CE6686 too // (measured: Standard + ” on a two-value enum is 1 error). That half needs the -// enumeration's definition and so belongs to the reference pass, not here; this -// rule reports only what is decidable from the statement alone. +// enumeration's definition and so belongs to the reference pass +// (validate_workflow_outcomes.go); this rule reports only what is decidable from +// the statement alone. func checkWorkflowEmptyEnumOutcome(outcomes []ast.WorkflowConditionOutcomeNode, kind, label string, loc linter.Location) []linter.Violation { var enumValues []string for _, o := range outcomes { diff --git a/mdl/executor/validate_workflow_call_signature.go b/mdl/executor/validate_workflow_call_signature.go index 885d7cd708..a7735d892a 100644 --- a/mdl/executor/validate_workflow_call_signature.go +++ b/mdl/executor/validate_workflow_call_signature.go @@ -25,8 +25,8 @@ import ( // CE0078 "Condition should be of type boolean or enumeration but is of type …" // decision $WorkflowContext/B, or $WorkflowContext/Qty > 1 clean // -// A microflow returning an enumeration also needs its outcomes to match (CE6686), -// which is not judged here. Anything this checker cannot establish — a +// The outcomes must match the result as well (CE6686): see +// validate_workflow_outcomes.go. Anything this checker cannot establish — a // microflow neither the script nor the project declares, a parameter entity // whose inheritance cannot be read, an attribute of unknown type — is silence. @@ -44,7 +44,9 @@ func (c *workflowTaskSignatureChecker) checkCallMicroflowSignature(label string, } var errs []string switch sig.ReturnKind { - case ast.TypeUnknown, ast.TypeVoid, ast.TypeBoolean, ast.TypeEnumeration: + case ast.TypeVoid, ast.TypeBoolean, ast.TypeEnumeration: + errs = append(errs, c.checkWorkflowOutcomes(label, sig.ReturnKind, sig.ReturnEnum, n.Outcomes, true)...) + case ast.TypeUnknown: default: ret := sig.ReturnKind.String() if sig.Returns != "" { @@ -78,36 +80,56 @@ func (c *workflowTaskSignatureChecker) checkCallMicroflowSignature(label string, return errs } -// checkDecisionCondition reports a workflow decision whose condition is a single -// context attribute that is neither a Boolean nor an enumeration (CE0078). -func (c *workflowTaskSignatureChecker) checkDecisionCondition(label, expr, contextEntity string) string { +// checkDecision reports the decision's condition (CE0078) or, when it is a +// Boolean or enumeration attribute, its outcomes (CE6686). +func (c *workflowTaskSignatureChecker) checkDecision(label string, d *ast.WorkflowDecisionNode, contextEntity string) []string { + msg, t, ok := c.decisionConditionType(label, d.Expression, contextEntity) + if msg != "" { + return []string{msg} + } + if !ok { + return nil + } + enumQN := "" + if t.EnumRef != nil { + enumQN = t.EnumRef.String() + } + return c.checkWorkflowOutcomes(label, t.Kind, enumQN, d.Outcomes, false) +} + +// decisionConditionType is the CE0078 report for a decision's condition, or +// the type of the single context attribute it names (ok) when that is a +// Boolean or an enumeration. +func (c *workflowTaskSignatureChecker) decisionConditionType(label, expr, contextEntity string) (string, ast.DataType, bool) { if strings.TrimSpace(expr) == "" || contextEntity == "" || contextEntity == "." { - return "" + return "", ast.DataType{}, false } e, ok := visitor.ParseExpressionText(expr) if !ok { - return "" + return "", ast.DataType{}, false } p, ok := unwrapWorkflowExpr(e).(*ast.AttributePathExpr) if !ok || !strings.EqualFold(strings.TrimPrefix(p.Variable, "$"), workflowContextVar) { - return "" + return "", ast.DataType{}, false } steps := expressionPathSteps(p) if len(steps) != 1 || strings.Contains(steps[0], ".") { - return "" + return "", ast.DataType{}, false } t, ok := retrieveAttributeType(c.ctx, c.sc, contextEntity, steps[0]) if !ok { - return "" + return "", ast.DataType{}, false } switch t.Kind { - case ast.TypeUnknown, ast.TypeBoolean, ast.TypeEnumeration: - return "" + case ast.TypeUnknown: + return "", ast.DataType{}, false + case ast.TypeBoolean, ast.TypeEnumeration: + return "", t, true } return fmt.Sprintf( "%s: the condition %s is %s, not a Boolean or an enumeration — a decision branches on true/false or on an "+ "enumeration's values; the build fails CE0078 (compare it, such as `%s != empty`)", - label, strings.TrimSpace(expr), t.Kind.String(), strings.TrimSpace(expr)) + label, strings.TrimSpace(expr), t.Kind.String(), strings.TrimSpace(expr)), ast.DataType{}, false } func unwrapWorkflowExpr(e ast.Expression) ast.Expression { diff --git a/mdl/executor/validate_workflow_outcomes.go b/mdl/executor/validate_workflow_outcomes.go new file mode 100644 index 0000000000..d6f73f5cfe --- /dev/null +++ b/mdl/executor/validate_workflow_outcomes.go @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "strings" + + "github.com/mendixlabs/mxcli/mdl/ast" +) + +// The outcome half of CE6686 (check-gap sweep 4, batch C), which MDL-WF06 left +// to this reference pass because it needs the enumeration's definition. +// Measured on MxBuild 11.16.1, one workflow per case, enumeration Sp.Color +// (Red, Blue), context entity Sp.Ctx: +// +// call microflow returning Boolean true + false, or no outcomes clean +// true only, or an enum value CE6686 +// call microflow returning Color Red + Blue + '' clean +// the same plus `default` clean +// no outcomes, Red + '' (+ default), +// or true + false CE6686 +// call microflow returning nothing no outcomes clean +// true + false CE6686 +// decision on a Boolean attribute no outcomes, or true only CE6686 +// decision on a Color attribute Red + Blue + '' clean +// no outcomes, or Red + '' CE6686 +// an outcome Sp.Color.Green CE1613 "The selected enumeration value +// 'Sp.Color.Green' no longer exists." +// +// So the outcomes must be exactly the result's values: true and false, or each +// enumeration value plus the empty one. A `default` outcome is not counted. A +// call microflow returning a Boolean may also have none, a decision may not. +// A set missing only the empty value is MDL-WF06's report, not repeated here; +// a result whose type or values cannot be established is not judged. + +const ( + ce6686CallText = "The current outcomes of the call microflow activity do not match the configured microflow." + ce6686DecisionText = "The current outcomes of the decision activity do not match the configured expression." +) + +// checkWorkflowOutcomes judges one activity's outcomes against the type it +// branches on. kind is ast.TypeBoolean, ast.TypeEnumeration (with enumQN) or +// ast.TypeVoid; isCall tells a call microflow from a decision. +func (c *workflowTaskSignatureChecker) checkWorkflowOutcomes(label string, kind ast.DataTypeKind, enumQN string, + outcomes []ast.WorkflowConditionOutcomeNode, isCall bool) []string { + ceText := ce6686DecisionText + if isCall { + ceText = ce6686CallText + } + var hasTrue, hasFalse, hasEmpty bool + var enumGiven []string + counted := 0 + for _, o := range outcomes { + switch o.Value { + case "Default": + continue + case "True": + hasTrue = true + case "False": + hasFalse = true + case "": + hasEmpty = true + default: + enumGiven = append(enumGiven, o.Value) + } + counted++ + } + mismatch := func(what string) []string { + return []string{fmt.Sprintf("%s: %s — the outcomes must be exactly the result's values; the build fails CE6686 %q", + label, what, ceText)} + } + switch kind { + case ast.TypeVoid: + if !isCall || counted == 0 { + return nil + } + return mismatch("the microflow returns nothing, so the activity takes no outcomes") + case ast.TypeBoolean: + switch { + case counted == 0 && isCall: + return nil + case counted == 0: + return mismatch("a Boolean condition needs a true and a false outcome, and this decision has none") + case len(enumGiven) > 0 || hasEmpty: + return mismatch("the result is a Boolean, so its outcomes are true and false, not enumeration values") + case !hasTrue || !hasFalse: + missing := "false" + if !hasTrue { + missing = "true" + } + return mismatch("a Boolean result needs a true and a false outcome, and " + missing + " is missing") + } + return nil + case ast.TypeEnumeration: + values, ok := c.sc.enumerationValues(c.ctx, enumQN) + if !ok || len(values) == 0 { + return nil + } + if hasTrue || hasFalse { + return mismatch(fmt.Sprintf("the result is a %s, so its outcomes are that enumeration's values and '', not true and false", enumQN)) + } + var errs []string + given := map[string]bool{} + for _, v := range enumGiven { + name, ok := enumOutcomeValueName(v, enumQN) + if !ok { + continue // another rule reports an unqualified value + } + found := false + for _, ev := range values { + if ev == name { + found, given[ev] = true, true + } + } + if !found { + errs = append(errs, fmt.Sprintf("%s: the outcome '%s' is not a value of %s (%s); the build fails "+ + "CE1613 \"The selected enumeration value '%s' no longer exists.\"", + label, v, enumQN, strings.Join(values, ", "), v)) + } + } + if len(errs) > 0 { + return errs + } + var missing []string + for _, ev := range values { + if !given[ev] { + missing = append(missing, "'"+enumQN+"."+ev+"'") + } + } + switch { + case counted == 0: + return mismatch(fmt.Sprintf("the result is a %s and the activity has no outcomes; it needs one per value (%s) and one for ''", + enumQN, strings.Join(values, ", "))) + case len(missing) == 0: + return nil // at most '' is missing: MDL-WF06 + } + if !hasEmpty { + missing = append(missing, "''") + } + return mismatch(fmt.Sprintf("the result is a %s and the outcomes leave out %s", enumQN, strings.Join(missing, ", "))) + } + return nil +} + +// enumOutcomeValueName is the value name an outcome `'Module.Enum.Value'` +// names, when it names a value of enumQN; a value of another enumeration is +// returned whole, so it is reported as not belonging. false for a value that +// is not qualified. +func enumOutcomeValueName(v, enumQN string) (string, bool) { + if !strings.Contains(v, ".") { + return "", false + } + if prefix := enumQN + "."; len(v) > len(prefix) && strings.EqualFold(v[:len(prefix)], prefix) { + return v[len(prefix):], true + } + return v, true +} diff --git a/mdl/executor/validate_workflow_task_signature.go b/mdl/executor/validate_workflow_task_signature.go index 5d178164d3..3a0d4254c1 100644 --- a/mdl/executor/validate_workflow_task_signature.go +++ b/mdl/executor/validate_workflow_task_signature.go @@ -117,7 +117,7 @@ func (c *workflowTaskSignatureChecker) checkActivities(activities []ast.Workflow return } if d, ok := a.(*ast.WorkflowDecisionNode); ok { - errs = appendIfSet(errs, c.checkDecisionCondition("decision "+workflowDecisionLabel(d), d.Expression, contextEntity)) + errs = append(errs, c.checkDecision("decision "+workflowDecisionLabel(d), d, contextEntity)...) return } n, ok := a.(*ast.WorkflowUserTaskNode) diff --git a/mdl/executor/widget_engine.go b/mdl/executor/widget_engine.go index 5b213cb178..8e0437a0e1 100644 --- a/mdl/executor/widget_engine.go +++ b/mdl/executor/widget_engine.go @@ -2077,15 +2077,15 @@ func (e *PluggableWidgetEngine) resolveMapping(mapping PropertyMapping, w *ast.W } case "Association": - // Accept either the explicit `Association:` keyword or the generic - // `attribute:` keyword for the reference the widget binds (e.g. a ComboBox - // in association mode). Before this, only `attribute:` was read, so a - // natural `combobox (Association: Mod.A_B, …)` silently dropped the binding - // and failed the build with CE0642. (traceops #23) - attr := w.GetStringProp("Association") - if attr == "" { - attr = w.GetAttribute() + // The reference the widget binds is written `Association:`. The + // `Attribute:` spelling was accepted as an alias, and check, exec and + // describe disagreed on it (ako/mxcli#2709): it is refused, as check + // refuses it (MDL-WIDGET57). + if attributeNamesBoundAssociation(e.currentDef, w) { + msg, suggestion := attributeForAssociationMessage(w) + return nil, mdlerrors.NewValidation(msg + ". " + suggestion) } + attr := w.GetStringProp("Association") if name, rest, named := namedObjectBinding(attr); named { // `$Param.Assoc`: the association starts at a page or snippet // parameter (Snip_TaskDashboard_Header's referenceSelector5). diff --git a/mdl/executor/widget_engine_test.go b/mdl/executor/widget_engine_test.go index 7b3b6537cc..c42b14c214 100644 --- a/mdl/executor/widget_engine_test.go +++ b/mdl/executor/widget_engine_test.go @@ -466,7 +466,7 @@ func TestResolveMapping_Association(t *testing.T) { Source: "Association", Operation: "association", } - w := &ast.WidgetV3{Properties: map[string]any{"Attribute": "Order_Customer"}} + w := &ast.WidgetV3{Properties: map[string]any{"Association": "Order_Customer"}} ctx, err := engine.resolveMapping(mapping, w) if err != nil { diff --git a/mdl/executor/widget_native_props.go b/mdl/executor/widget_native_props.go index 934b61ec2a..49626a4ead 100644 --- a/mdl/executor/widget_native_props.go +++ b/mdl/executor/widget_native_props.go @@ -96,15 +96,15 @@ var nativeWidgetKinds = map[string]nativeWidgetKind{ "textbox": {stored: "Forms$TextBox", tail: true, visible: true, reads: withReads(inputReads, "Placeholder", "ReadOnlyStyle", "Password", "Validation", "ValidationMessage", "SubmitBehaviour", "SubmitOnInputDelay", "KeyboardType", "OnEnterKeyPress", "OnEnterKeyPressAction", - "AutoFocus")}, + "AutoFocus", "AriaRequired", "Autocomplete", "AutocompletePurpose")}, "textarea": {stored: "Forms$TextArea", tail: true, visible: true, reads: withReads(inputReads, "Placeholder", "ReadOnlyStyle", "NumberOfLines", "Autocomplete", - "SubmitBehaviour", "SubmitOnInputDelay")}, + "SubmitBehaviour", "SubmitOnInputDelay", "AriaRequired")}, "datepicker": {stored: "Forms$DatePicker", tail: true, visible: true, - reads: withReads(inputReads, "ReadOnlyStyle")}, + reads: withReads(inputReads, "ReadOnlyStyle", "AriaRequired")}, "dropdown": {stored: "Forms$DropDown", tail: true, visible: true, reads: withReads(inputReads)}, "checkbox": {stored: "Forms$CheckBox", tail: true, visible: true, reads: withReads(inputReads, "ReadOnlyStyle", "LabelPosition")}, - "radiobuttons": {stored: "Forms$RadioButtonGroup", tail: true, visible: true, reads: withReads(inputReads, "ReadOnlyStyle", "RenderHorizontal")}, + "radiobuttons": {stored: "Forms$RadioButtonGroup", tail: true, visible: true, reads: withReads(inputReads, "ReadOnlyStyle", "RenderHorizontal", "AriaRequired")}, "filemanager": {stored: "Forms$FileManager", tail: true, visible: true, reads: []string{"Label", "ShowLabel", "Type", "MaxFileSize", "AllowedExtensions", "ShowFileInBrowser"}}, diff --git a/mdl/exprcheck/adapters/check.go b/mdl/exprcheck/adapters/check.go index 928762c1c9..ffb73f676b 100644 --- a/mdl/exprcheck/adapters/check.go +++ b/mdl/exprcheck/adapters/check.go @@ -180,6 +180,11 @@ func (c *CheckAdapter) walkBodyWithScope(body []ast.MicroflowStatement, mf strin for _, a := range n.Arguments { c.checkExpr(a.Value, exprcheck.CallArgumentSlot(n.NanoflowName.String(), a.Name), mf, r) } + case *ast.CallJavaScriptActionStmt: + // Declared the same way as a Java action's (check-gap f84). + for _, a := range n.Arguments { + c.checkExpr(a.Value, exprcheck.CallArgumentSlot(n.ActionName.String(), a.Name), mf, r) + } case *ast.CallJavaActionStmt: // The executor declares a Java action's primitive parameters as a // flow's (declareJavaActionParams), so the call-argument matrix diff --git a/mdl/roundtrip/listview_database_over_association_test.go b/mdl/roundtrip/listview_database_over_association_test.go index 2e3e534bcb..3197d48a59 100644 --- a/mdl/roundtrip/listview_database_over_association_test.go +++ b/mdl/roundtrip/listview_database_over_association_test.go @@ -181,7 +181,7 @@ func TestDatabaseOverAssociationKeptUnderANamedDatasourceKey(t *testing.T) { dataview dv1 (DataSource: $Rule) { combobox cb1 ( Label: 'Business rule', - Attribute: Rules.RuleAction_BusinessRule, + Association: Rules.RuleAction_BusinessRule, optionsSourceAssociationDataSource: database from $RuleCategory/Rules.BusinessRule_RuleCategory/Rules.BusinessRule, CaptionAttribute: Name ) diff --git a/mdl/roundtrip/pluggable_replace_keeps_test.go b/mdl/roundtrip/pluggable_replace_keeps_test.go index e09c847bd6..b65d0c880b 100644 --- a/mdl/roundtrip/pluggable_replace_keeps_test.go +++ b/mdl/roundtrip/pluggable_replace_keeps_test.go @@ -28,7 +28,7 @@ alter page Rules.BusinessRule_NewEdit { replace comboBox1 with { combobox comboBox1 ( Label: 'Rule category', - Attribute: Rules.BusinessRule_RuleCategory, + Association: Rules.BusinessRule_RuleCategory, DataSource: database from Rules.RuleCategory sort by Name asc, CaptionAttribute: Name ) diff --git a/mdl/visitor/visitor_association.go b/mdl/visitor/visitor_association.go index d68c103946..97a4db1b0d 100644 --- a/mdl/visitor/visitor_association.go +++ b/mdl/visitor/visitor_association.go @@ -74,12 +74,14 @@ func (b *Builder) ExitCreateAssociationStatement(ctx *parser.CreateAssociationSt // DELETE_BEHAVIOR , the original spelling. if delBehavior := optCtx.DeleteBehavior(); delBehavior != nil { stmt.DeleteBehavior = buildDeleteBehavior(delBehavior) + stmt.DeleteBehaviorSet = true } // ON DELETE , the SQL spelling. Both set the same field — // they are two ways of naming one Mendix behaviour, not two features. if onDel := optCtx.OnDeleteClause(); onDel != nil { stmt.DeleteBehavior = buildReferentialAction(onDel.ReferentialAction()) + stmt.DeleteBehaviorSet = true if msg := onDel.ErrorMessageClause(); msg != nil { stmt.DeleteErrorMessage = buildErrorMessage(msg) } diff --git a/mdl/visitor/visitor_association_delete_stated_test.go b/mdl/visitor/visitor_association_delete_stated_test.go new file mode 100644 index 0000000000..a8fc765265 --- /dev/null +++ b/mdl/visitor/visitor_association_delete_stated_test.go @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: Apache-2.0 + +package visitor + +import ( + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" +) + +// #2713: the executor keeps the stored delete behaviour when the statement does +// not state one, so the visitor must say whether it did — DeleteKeepReferences +// is the zero value and cannot tell "unstated" from "on delete set null". +func TestCreateAssociation_DeleteBehaviourStated(t *testing.T) { + cases := []struct { + name string + src string + want bool + }{ + {"unstated", `create or modify association M.A_B from M.A to M.B;`, false}, + {"on delete", `create or modify association M.A_B from M.A to M.B on delete set null;`, true}, + {"on delete restrict + message", `create or modify association M.A_B from M.A to M.B on delete restrict error_message 'no';`, true}, + {"delete_behavior", `create or modify association M.A_B from M.A to M.B delete_behavior cascade;`, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + prog, errs := Build(tc.src) + if len(errs) > 0 { + t.Fatalf("parse: %v", errs) + } + stmt := prog.Statements[0].(*ast.CreateAssociationStmt) + if stmt.DeleteBehaviorSet != tc.want { + t.Errorf("DeleteBehaviorSet = %v, want %v", stmt.DeleteBehaviorSet, tc.want) + } + }) + } +} diff --git a/mdl/visitor/visitor_page_v3.go b/mdl/visitor/visitor_page_v3.go index 74d5340a01..d1c8e6bf51 100644 --- a/mdl/visitor/visitor_page_v3.go +++ b/mdl/visitor/visitor_page_v3.go @@ -988,6 +988,14 @@ func parseWidgetPropertyV3(ctx parser.IWidgetPropertyV3Context, widget *ast.Widg // property takes one is the widget schema's question, answered by the // checker (MDL-WIDGET42) and the builder, never by writing it empty. if expr := propCtx.Expression(); expr != nil { + // `Association: $Param.Module.Assoc` — the association a combo box + // binds, read from a page or snippet parameter: kept as the string + // the builder reads, as `Attribute:` kept it while it was the + // association's spelling (ako/mxcli#2709). + if strings.EqualFold(id.GetText(), "Association") { + widget.Properties["Association"] = genericWidgetExpression(expr).Text + return + } widget.Properties[id.GetText()] = genericWidgetExpression(expr) return } @@ -1035,6 +1043,14 @@ func parseWidgetPropertyV3(ctx parser.IWidgetPropertyV3Context, widget *ast.Widg // property takes one is the widget schema's question, answered by the // checker (MDL-WIDGET42) and the builder, never by writing it empty. if expr := propCtx.Expression(); expr != nil { + // `Association: $Param.Module.Assoc` — the association a combo box + // binds, read from a page or snippet parameter: kept as the string + // the builder reads, as `Attribute:` kept it while it was the + // association's spelling (ako/mxcli#2709). + if strings.EqualFold(kw.GetText(), "Association") { + widget.Properties["Association"] = genericWidgetExpression(expr).Text + return + } widget.Properties[kw.GetText()] = genericWidgetExpression(expr) return } diff --git a/mdl/visitor/visitor_widget_attribute_ref_test.go b/mdl/visitor/visitor_widget_attribute_ref_test.go index ccd7964a57..3fff712ca5 100644 --- a/mdl/visitor/visitor_widget_attribute_ref_test.go +++ b/mdl/visitor/visitor_widget_attribute_ref_test.go @@ -59,13 +59,13 @@ func TestWidgetAttributeThroughDataViewRefusedOnOtherWidgets(t *testing.T) { } // A widget outside every data container reads a page or snippet parameter: -// `Attribute: $Param.Attr` (a combo box's association: `$Param.Module.Assoc`) +// `Attribute: $Param.Attr` (a combo box's association: `Association: $Param.Module.Assoc`) // and `Visible: $Param.Attr in (…)` — the spellings describe prints for // Studio Pro's SourceVariable {SnippetParameter|PageParameter: Param}. func TestParameterBindingsParse(t *testing.T) { src := "create snippet M.S (Params: ($Ctx: M.A)) {\n" + " combobox c1 (Attribute: $Ctx.Status)\n" + - " combobox c2 (Attribute: $Ctx.M.A_B, DataSource: database M.B, CaptionAttribute: Name)\n" + + " combobox c2 (Association: $Ctx.M.A_B, DataSource: database M.B, CaptionAttribute: Name)\n" + " image i1 (Visible: $Ctx.Status in (Running, empty))\n" + "};" prog, errs := Build(src) @@ -76,8 +76,8 @@ func TestParameterBindingsParse(t *testing.T) { if got := ws[0].GetAttribute(); got != "$Ctx.Status" { t.Errorf("c1 Attribute = %q, want $Ctx.Status", got) } - if got := ws[1].GetAttribute(); got != "$Ctx.M.A_B" { - t.Errorf("c2 Attribute = %q, want $Ctx.M.A_B", got) + if got := ws[1].GetStringProp("Association"); got != "$Ctx.M.A_B" { + t.Errorf("c2 Association = %q, want $Ctx.M.A_B", got) } vw, ok := ws[2].Properties["VisibleWhen"].(*ast.VisibleWhenV3) if !ok || vw.Attribute != "$Ctx.Status" || len(vw.Values) != 2 { diff --git a/sdk/pages/pages_widgets_input.go b/sdk/pages/pages_widgets_input.go index ca59466f26..91ed7b1718 100644 --- a/sdk/pages/pages_widgets_input.go +++ b/sdk/pages/pages_widgets_input.go @@ -42,6 +42,33 @@ func CanonicalKeyboardType(s string) (string, bool) { return "", false } +// AutocompletePurposes are the members of a text box's "Autocomplete purpose" +// (Forms$TextBox.AutocompletePurpose, the HTML autocomplete token it renders; +// Studio Pro's default is On). Taken from the metamodel's AutocompletePurposeType. +var AutocompletePurposes = []string{"On", "Off", "FullName", "HonorificPrefix", "GivenName", + "AdditionalName", "FamilyName", "HonorificSuffix", "Nickname", "JobTitle", "Username", + "NewPassword", "CurrentPassword", "CompanyName", "StreetAddress", "StreetAddressLine1", + "StreetAddressLine2", "StreetAddressLine3", "AddressLevel4", "AddressLevel3", "AddressLevel2", + "AddressLevel1", "CountryCode", "CountryName", "PostalCode", "CreditCardFullName", + "CreditCardGivenName", "CreditCardAdditionalName", "CreditCardFamilyName", "CreditCardNumber", + "CreditCardExpiration", "CreditCardExpirationMonth", "CreditCardExpirationYear", + "CreditCardSecurityCode", "CreditCardType", "TransactionCurrency", "TransactionAmount", + "Language", "Birthday", "DayOfBirth", "MonthOfBirth", "YearOfBirth", "Sex", "Url", "Photo", + "TelephoneNumber", "TelephoneCountryCode", "TelephoneWithoutCountryCode", "TelephoneAreaCode", + "TelephoneLocal", "TelephoneLocalPrefix", "TelephoneLocalSuffix", "TelephoneExtension", + "Email", "InstantMessageProtocol"} + +// CanonicalAutocompletePurpose matches s case-insensitively against +// AutocompletePurposes and returns the member as Mendix spells it. +func CanonicalAutocompletePurpose(s string) (string, bool) { + for _, v := range AutocompletePurposes { + if strings.EqualFold(strings.TrimSpace(s), v) { + return v, true + } + } + return "", false +} + // WidgetVariable is an input widget's SourceVariable: the Forms$PageVariable // that names which object the widget's attribute is read from when that is not // simply the enclosing data context. Studio Pro stores a widget-scoped one — @@ -73,6 +100,14 @@ type TextBox struct { // AutoFocus is Forms$TextBox.AutoFocus — on native, the keyboard opens with // the page. It was hard-coded false (ako/mxcli#2519). AutoFocus bool `json:"autoFocus,omitempty"` + // AriaRequired is Studio Pro's "Aria required", on every attribute input; + // it was hard-coded false (ako/mxcli#2710). + AriaRequired bool `json:"ariaRequired,omitempty"` + // Autocomplete and AutocompletePurpose are Forms$TextBox's; nil / "" write + // Studio Pro's defaults, true and On. AutocompletePurpose is one of + // AutocompletePurposes (ako/mxcli#2710). + Autocomplete *bool `json:"autocomplete,omitempty"` + AutocompletePurpose string `json:"autocompletePurpose,omitempty"` // ReadOnlyStyle: Inherit, Control or Text, as on CheckBox. Empty writes // Studio Pro's default, Inherit (ako/mxcli#977). ReadOnlyStyle string `json:"readOnlyStyle,omitempty"` @@ -119,6 +154,7 @@ type TextArea struct { // Autocomplete is Forms$TextArea.Autocomplete; nil writes true, the // default (ako/mxcli#977). Autocomplete *bool `json:"autocomplete,omitempty"` + AriaRequired bool `json:"ariaRequired,omitempty"` // as on TextBox // ReadOnlyStyle: Inherit, Control or Text, as on CheckBox. Empty writes // Studio Pro's default, Inherit (ako/mxcli#977). ReadOnlyStyle string `json:"readOnlyStyle,omitempty"` @@ -155,6 +191,7 @@ type DatePicker struct { // defaults (Date). It replaced a DateFormat string nothing read, so every // picker was written as date-only (ako/mxcli#968). FormattingInfo *FormattingInfo `json:"formattingInfo,omitempty"` + AriaRequired bool `json:"ariaRequired,omitempty"` // as on TextBox // ReadOnlyStyle: Inherit, Control or Text, as on CheckBox. Empty writes // Studio Pro's default, Inherit (ako/mxcli#977). ReadOnlyStyle string `json:"readOnlyStyle,omitempty"` @@ -253,6 +290,7 @@ type RadioButtons struct { AttributeRefSteps []AttributeRefStep `json:"attributeRefSteps,omitempty"` // association hops when the attribute is reached over associations (AttributeRef.EntityRef) SourceVariable *WidgetVariable `json:"sourceVariable,omitempty"` // widget-scoped variable the attribute is read from (#826) RenderDirection RenderDirection `json:"renderDirection,omitempty"` + AriaRequired bool `json:"ariaRequired,omitempty"` // as on TextBox // ReadOnlyStyle: Inherit, Control or Text, as on CheckBox. Empty writes // Studio Pro's default, Inherit (ako/mxcli#977). ReadOnlyStyle string `json:"readOnlyStyle,omitempty"`