diff --git a/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-21-queue-refs-false-module-cycle.json b/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-21-queue-refs-false-module-cycle.json new file mode 100644 index 000000000..3aec98bb6 --- /dev/null +++ b/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-21-queue-refs-false-module-cycle.json @@ -0,0 +1 @@ +{"area": "cmd/mxcli", "date": "2026-11-21", "symptom": "report architecture (and the catalog's GRAPH_MODULE_CYCLES behind module_cycles()) shows a false 9-module domain cycle through the module that holds a task queue", "cause": "the `queue` ref runs from the queue to the flow it runs and was counted as module use, so the queue's module 'depended on' every flow it runs; no edge recorded the caller's use of the queue. `by_name` (a constant naming a flow) was counted the same way", "file": "`mdl/catalog/builder_references.go` (extractQueueRefs, RefKindsNotModuleUse), `mdl/catalog/builder_graph.go` (loadModuleEdges), `cmd/mxcli/projectreport/architecture.go`", "insight": "A reference kind added for reachability (so a flow is not dead) is not automatically a dependency: ask which way the use runs before a kind enters module edges. One shared list (RefKindsNotModuleUse) keeps the catalog and the report agreeing", "refs": ["ako/mxcli#2503"], "test": "TestQueueAndByNameCloseNoModuleCycle"} diff --git a/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-21-report-all-nil-context-panic.json b/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-21-report-all-nil-context-panic.json new file mode 100644 index 000000000..72038c9c5 --- /dev/null +++ b/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-21-report-all-nil-context-panic.json @@ -0,0 +1 @@ +{"area": "cmd/mxcli", "date": "2026-11-21", "symptom": "report all panics in the dependencies stage with \"cannot create context from nil parent\" (with a Marketplace token and Marketplace modules) and writes nothing, losing the reports already computed; without the panic its vulnerability check fails as \"net/http: nil Context\"", "cause": "report all and report readiness call each kind's collect with that kind's cobra command, which cobra never executed, so cmd.Context() is nil; files were only written after every kind was collected, and a panic in a collector was not recovered", "file": "`cmd/mxcli/cmd_report_all.go` (collectKind, safely, runReportAll)", "insight": "A cobra command called directly instead of through Execute has no context: give it the caller's (SetContext) at the one place that calls collectors, not in each collector. And a roll-up must treat one kind's panic like its error, and write each result as it is finished", "refs": ["ako/mxcli#2500"], "test": "TestReportAllGivesEachKindAContext"} diff --git a/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-21-verify-lint-resolved-dropped.json b/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-21-verify-lint-resolved-dropped.json new file mode 100644 index 000000000..794bc1b13 --- /dev/null +++ b/.claude/skills/fix-issue/findings/cmd-mxcli/2026-11-21-verify-lint-resolved-dropped.json @@ -0,0 +1 @@ +{"area": "cmd-mxcli", "date": "2026-11-21", "refs": ["ako/mxcli#2506"], "ce": [], "symptom": "`verify` printed lint's passthrough line `0 new, 451 already known, 1 fixed` but its lint stage summary omitted the count and `--format json` said `\"resolved\": 0`; the mxcheck stage filled the same field correctly.", "file": "cmd/mxcli/cmd_verify.go lintOutcome. Test: cmd/mxcli/cmd_verify_test.go TestLintOutcomeCarriesFixedAsResolved", "cause": "The lint stage read Unchanged and UnchangedBySeverity from lint's baseline object and never read Fixed, so Outcome.Resolved stayed zero.", "insight": "**When two stages fill one report field, compare what each stage's outcome sets, not just what the runner prints.** The correct sibling (mxcheck) was the control that showed this was an omission. The outcome construction was inline in the runner and so untestable; extracting it was what made a test possible."} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-21-published-rest-alter-add-drop-operation.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-21-published-rest-alter-add-drop-operation.json new file mode 100644 index 000000000..1e231b1e9 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-21-published-rest-alter-add-drop-operation.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-11-21", "refs": ["ako/mxcli#2449", "mendixlabs/mxcli#1903"], "ce": [], "symptom": "`alter published rest service M.BookingApi add operation delete '{id}' in resource 'bookings' …` was a parse error (mismatched input 'operation' expecting RESOURCE): there was no way to add one operation to a stored resource short of restating the whole service.", "file": "grammar MDLParser.g4 alterPublishedRestServiceAction (ADD OPERATION IN RESOURCE '…' { … } / DROP OPERATION ['path'] IN RESOURCE '…'); visitor_rest.go buildPublishedRestOperationDef (shared with the resource block); cmd_published_rest.go execAlterPublishedRestService; check in validate_published_rest_ops.go publishedRestAlterResourceProblems. Test: mdl/executor/alter_published_rest_operation_2449_test.go; mdl-examples/bug-tests/2449-published-rest-add-operation.mdl", "cause": "ALTER had only resource-level actions.", "insight": "**Reuse create's operation rule inside the alter, not a re-spelled one**: the resource block (`add operation in resource 'x' { ; }`) lets describe output be pasted into an add unchanged, and one visitor builder serves both, so they cannot drift. An operation is keyed resource+method+path exactly as the drop warning keys it."} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-21-published-rest-rewrite-drops-operations.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-21-published-rest-rewrite-drops-operations.json new file mode 100644 index 000000000..43ff6b5f7 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-21-published-rest-rewrite-drops-operations.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-11-21", "refs": ["ako/mxcli#2449", "mendixlabs/mxcli#1903"], "ce": [], "symptom": "`create or modify published rest service M.BookingApi (...) { resource 'bookings' { delete '{id}' microflow M.PRS_DeleteBooking; } }` deleted the stored GET '' and GET '{id}' and printed only `Modified published rest service`; `alter … add resource 'bookings' { … }` with the stored name passed check and exec refused it (resource 'bookings' already exists).", "file": "mdl/executor/validate_published_rest_ops.go droppedPublishedRestOperations / CheckPublishedRestOperationDrops (MDL-REST06, wired in cmd/mxcli/cmd_check.go and execCreatePublishedRestService) and publishedRestAlterResourceProblems (validate.go). Test: mdl/executor/validate_published_rest_ops_2449_test.go", "cause": "A create-or-modify replaces the service's resource list wholesale with no comparison against the stored operations; the alter's resource actions were judged only by exec.", "insight": "**Key an operation as describe prints it (resource + method + path with slashes trimmed)**: `get microflow`, `get ''` and `get '/'` are one operation, and keying on the raw path would warn on every describe -> exec round trip. The control is exactly that round trip: Unchanged, no warning."} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-21-single-external-entity-unmapped-attributes.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-21-single-external-entity-unmapped-attributes.json new file mode 100644 index 000000000..33e2795eb --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-21-single-external-entity-unmapped-attributes.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-11-21", "refs": ["ako/mxcli#2497", "ako/mxcli#2477"], "ce": ["CE6612", "CE6010", "CE6630"], "symptom": "`create external entity M.Order from consumed odata service M.Sales (EntitySet: 'Orders') (OrderId: Long, Title: String(100), Status: …)` passed check and exec; mx check 11.12.6 reported CE6010 \"Key cannot be empty\", CE6612 on every attribute and CE6630 for $top and $skip, on a contract `create external entities` builds at 0 errors.", "file": "mdl/executor/cmd_odata_single_contract.go resolveSingleExternalEntity (called from execCreateExternalEntity in cmd_odata.go); the per-entity build extracted from the bulk import as contractEntityAttributes (cmd_contract.go); deferred enumerations in cmd_contract_enums.go. Test: mdl/executor/create_external_entity_contract_2497_test.go", "cause": "The single form built attributes from the statement alone (DomainModels$StoredValue, no RemoteName/RemoteType), wrote no key, and took capabilities from the statement with false defaults; the bulk import, which reads the contract, was the only path that wrote the mapping.", "insight": "**Two statements that write one document kind must share the converter, not each have one**: extracting the bulk import's per-entity build and calling it from both made the single form correct by construction, and the describe -> exec round trip (Unchanged) is the check that the two agree. A rewrite of an imported entity had always worked because the carry restored the mapping by name — which is why this survived: only a fresh create or a newly added attribute reached the unmapped path."} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-21-splice-append-after-error-handler-rejoin.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-21-splice-append-after-error-handler-rejoin.json new file mode 100644 index 000000000..90ec8b900 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-21-splice-append-after-error-handler-rejoin.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-11-21", "refs": ["ako/mxcli#2489"], "ce": [], "symptom": "`create or modify microflow` appending `call microflow M.SUB_Startup();` before `return true;`, after `$R = call … on error without rollback begin … end error;`, spliced the call between the activity and the merge its handler rejoins (describe: `join rejoin1; end error; call …; merge rejoin1; return true;`), so the error path skipped it, and the next exec of the unchanged script was refused: the stored statement \"Join\" has no activity to address (MDL-V1-REBUILD).", "file": "mdl/executor/cmd_flow_modify.go insertAnchor. Test: mdl/executor/flow_splice_after_handler_2489_pedapp_test.go", "cause": "insertAnchor prefers InsertAfter on the stored activity before the gap. An activity whose custom handler rejoins has the rejoin merge on its normal outgoing flow, which the stored statements do not show (describe prints a merge only once a join names it), so the insert landed before the merge.", "insight": "**Print the stored statement list the planner sees, not the describe output**: describe after the splice showed a `merge`, but the list before it had none, which is why no gap-contents rule could see it. The anchor rule has to read the predecessor's shape (customErrorHandler), and the acceptance check is that the unchanged script then re-runs Unchanged."} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-21-xpath-assoc-dot-attr-missing-entity-step.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-21-xpath-assoc-dot-attr-missing-entity-step.json new file mode 100644 index 000000000..96efdcb83 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-21-xpath-assoc-dot-attr-missing-entity-step.json @@ -0,0 +1 @@ +{"area": "mdl-executor", "date": "2026-11-21", "refs": ["ako/mxcli#2491", "mendixlabs/mxcli#1916"], "ce": ["CE0161", "CE1613"], "symptom": "`grant read * on entity Repro.Car to Repro.R where [Car_Assignment.ReturnedOn = empty]` got MDL047 suggesting `[not(Car_Assignment.ReturnedOn/)]` and a reference error calling `Car_Assignment.ReturnedOn` an association that is neither attribute nor association of Repro.Car; both kept the dotted name, and an agent followed them for 40 minutes.", "file": "mdl/executor/validate_xpath_missing_step.go missingEntityStepHint (used by validate_grant_refs.go xpathProblem and validate_retrieve_members.go); MDL047's xpathAssocEmptyHit.fix in validate_microflow.go. Test: mdl/executor/validate_xpath_missing_step_2491_test.go", "cause": "The XPath walk reads `A.B` as one qualified association name. `Car_Assignment.ReturnedOn` is association Car_Assignment then attribute ReturnedOn of its far end, with the entity step missing, which only a project lookup (AssociationTarget + member resolution) can tell.", "insight": "**A diagnostic's suggested fix must be re-checked against the input that produced it**: running `check` on the suggestion would have shown it fails the same way. The project tier can name the exact path (association/entity/attribute); the project-free rule cannot tell the two readings apart, so it offers both rather than guessing one."} diff --git a/.claude/skills/fix-issue/findings/mdl-executor/2026-11-22-json-custom-name-invalid-ce9524.json b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-22-json-custom-name-invalid-ce9524.json new file mode 100644 index 000000000..cb17ae8e6 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-executor/2026-11-22-json-custom-name-invalid-ce9524.json @@ -0,0 +1 @@ +{"area": "mdl/executor", "date": "2026-11-22", "refs": ["ako/mxcli#1258"], "ce": ["CE9524"], "symptom": "A `custom name map` name (or an `item of` name) that Mendix refuses, such as '1bad', 'has space', 'Owner', 'class' or an empty string, passed `check` and `exec` and was written; `mx check` reported CE9524 \"JSON element '(Object)/name' has an invalid custom name\".", "file": "mdl/executor/validate_json_structure_names.go validCustomName and invalidCustomNameViolations (MDL-JSON03). Tests validate_json_structure_names_test.go; fixtures mdl-examples/bug-tests/json-structure-invalid-custom-name.fail.mdl and json-structure-custom-names.mdl", "cause": "The earlier CE9524 findings were about GENERATED names (`$type`, `owner`, `%3A`) and were fixed by sanitising the default name, which is why a bare structure now builds clean; an explicit custom name is written verbatim and nothing judged it.", "insight": "**Re-measure an old finding's symptom before building on it: the class had moved.** Three records said CE9524 came from member names, and a fresh matrix showed every such member now builds clean (the default is sanitised). What remained was the author's own custom name, which is written verbatim. The accepted set was measured over 90 names rather than assumed from the message text: ASCII only (Größe, naïve are refused although they are letters), a lone underscore is refused, and the reserved list is the SAME case-insensitive one the platform uses for CE7247, so types.IsPlatformReserved is reused instead of a second list; String, System, Value, Entity, Date, List and User are not reserved. Every word of PlatformReservedWords and SystemAttributeNames was rejected in the second measurement, so the shared list is safe to reuse here."} diff --git a/.claude/skills/fix-issue/findings/mdl-other/2026-11-21-lint-mpr017-mpr019-external-and-mapped-writes.json b/.claude/skills/fix-issue/findings/mdl-other/2026-11-21-lint-mpr017-mpr019-external-and-mapped-writes.json new file mode 100644 index 000000000..7b1440935 --- /dev/null +++ b/.claude/skills/fix-issue/findings/mdl-other/2026-11-21-lint-mpr017-mpr019-external-and-mapped-writes.json @@ -0,0 +1 @@ +{"area": "mdl/other", "date": "2026-11-21", "refs": ["ako/mxcli#2501", "ako/mxcli#2502"], "ce": [], "symptom": "MPR019 reported 39 index findings on a frontend app, all 39 on external entities (no table in this app, nothing to index). MPR017 reported 4 of 4 false findings on one solution: three attributes set by a database-connection query Map and one attribute of an external entity, each read as nothing assigns it. An import mapping setting a Boolean from JSON true had the same false positive, reproduced on a fresh project.", "file": "mdl/linter/rules/mpr019_unindexed_constraint.go indexableEntity; mdl/linter/rules/mpr017_fixed_guard_attribute.go guardableEntity, mappedAttributeNames, collectAttributeFacts; tests mpr017_fixed_guard_attribute_test.go, mpr019_unindexed_constraint_test.go", "cause": "Both rules reasoned from the model's local writes. MPR019's indexableEntity was just Persistable, which an external entity is. MPR017 counted only Change and Create members as writes, so an attribute assigned by an import mapping, a database query or an external service read as unassigned.", "insight": "**A rule that concludes from the ABSENCE of a write has to enumerate every writer, and the report named two of at least four.** The database query and the external entity were real; the import mapping, a far commoner writer, was not in the report and showed up only by writing the same flag through a mapping on a fresh project. The first unit test covered only the pure helper and a stub of the wiring still passed; only a test through collectAttributeFacts failed it. That test needs a file-backed catalog (an in-memory one gives each pooled connection its own empty database, #2417) and a full entity row: a missing EntityType makes Entities() fail to scan and yield nothing, so a green test over an empty fixture proves nothing. Not covered yet: export mappings and message definitions as writers, and view entities for MPR019."} diff --git a/.claude/skills/fix-issue/findings/other/2026-11-21-import-link-self-association-junction-columns.json b/.claude/skills/fix-issue/findings/other/2026-11-21-import-link-self-association-junction-columns.json new file mode 100644 index 000000000..53a6aeca2 --- /dev/null +++ b/.claude/skills/fix-issue/findings/other/2026-11-21-import-link-self-association-junction-columns.json @@ -0,0 +1 @@ +{"area": "sql", "date": "2026-11-21", "refs": ["ako/mxcli#1686"], "ce": [], "symptom": "`import from source query 'SELECT name, friend FROM later' into MyFirstModule.Person map (name as Name) link (friend to Person_Friend on Name)` through a self-Reference stored as a table failed: junction table INSERT … column \"myfirstmodule$personid\" of relation \"myfirstmodule$person_friend\" does not exist (SQLSTATE 42703).", "file": "sql/import_assoc.go JunctionColumns + LookupAssociationInfo (now reads parent_column_name); mdl/executor/cmd_import.go resolveOneLink. Test: sql/import_assoc_self_1686_test.go", "cause": "Both junction column names were derived from the entity by convention ({module}${entity}id), identical for a self-association; mendixsystem$association's parent_column_name/child_column_name were not read for table storage.", "insight": "**Measure the junction table, then read the system row rather than re-deriving it**: on 11.12.6 Person_Friend (Person to Person, table) is myfirstmodule$personid1 (parent) / personid2 (child), and mendixsystem$association records exactly that. A control run of the unfixed build on the same database is what showed the failure is real (the issue had only been read off the code). IMPORT LINK accepts Reference only, so a ReferenceSet repro stops earlier."} diff --git a/.claude/skills/mendix/json-structures-and-mappings/SKILL.md b/.claude/skills/mendix/json-structures-and-mappings/SKILL.md index 6d4b715bd..f637648b6 100644 --- a/.claude/skills/mendix/json-structures-and-mappings/SKILL.md +++ b/.claude/skills/mendix/json-structures-and-mappings/SKILL.md @@ -12,18 +12,18 @@ description: "Create and manage JSON structures, import mappings and export mapp |---|---| | 33-110 | Key Concepts | | 111-122 | Export Mappings | -| 123-187 | JSON Structures | -| 188-234 | Message Definitions | -| 235-400 | Import Mappings | -| 401-498 | Export Mappings | -| 499-516 | Starting a Mapping Below the Payload Root | -| 517-600 | Microflow Actions | -| 601-613 | Browse | -| 614-661 | Export Workflow: PE → NPE → JSON | -| 662-668 | Realistic Example: Countries REST API | -| 669-692 | Placing Documents in Folders | -| 693-708 | Documentation | -| 709-723 | Common Mistakes | +| 123-188 | JSON Structures | +| 189-235 | Message Definitions | +| 236-401 | Import Mappings | +| 402-499 | Export Mappings | +| 500-517 | Starting a Mapping Below the Payload Root | +| 518-601 | Microflow Actions | +| 602-614 | Browse | +| 615-662 | Export Workflow: PE → NPE → JSON | +| 663-669 | Realistic Example: Countries REST API | +| 670-693 | Placing Documents in Folders | +| 694-709 | Documentation | +| 710-724 | Common Mistakes | # JSON Structures, Import Mappings & Export Mappings @@ -174,6 +174,7 @@ this structure carries, and it is one of the two names a member resolves by. - A root-level array has no key: `item of 'Root' as 'Entry'`. - An entry whose key is not in the snippet is an error (`MDL-JSON01`), as is `item of` on something that is not an array (`MDL-JSON02`). +- A custom name is ASCII letters, digits and `_`, not starting with a digit, and not a reserved word in any case (`Owner`, `Type`, `Id`, `class`, ...): else `MDL-JSON03` (CE9524). ### Browse diff --git a/.claude/skills/mendix/write-lint-rules/security-and-settings.md b/.claude/skills/mendix/write-lint-rules/security-and-settings.md index f62bd3696..6f400c33a 100644 --- a/.claude/skills/mendix/write-lint-rules/security-and-settings.md +++ b/.claude/skills/mendix/write-lint-rules/security-and-settings.md @@ -39,7 +39,7 @@ MPR reader, so they need no particular catalog depth. | `target_type` | string | What it points AT, upper-case: `"ENTITY"`, `"ASSOCIATION"`, `"MICROFLOW"`, `"NANOFLOW"`, `"RULE"`, `"PAGE"`, `"SNIPPET"`, `"LAYOUT"`, `"WORKFLOW"`, `"WIDGET"`, `"JAVA_ACTION"`, `"JAVASCRIPT_ACTION"`, `"REST_OPERATION"`, `"REGULAR_EXPRESSION"`, `"ATTRIBUTE"`, `"ENUMERATION"`, `"ENUMERATION_VALUE"`, `"IMPORT_MAPPING"`, `"EXPORT_MAPPING"`, `"JSON_STRUCTURE"`, `"AGENT"`, `"AI_MODEL"`, `"KNOWLEDGE_BASE"`, `"CONSUMED_MCP_SERVICE"`, `"CONSTANT"`. `WIDGET`, `ATTRIBUTE`, `ENUMERATION`, `ENUMERATION_VALUE` and `JSON_STRUCTURE` are only ever targets; `SCHEDULED_EVENT`, `PROJECT_SETTINGS` and the service types only ever sources | | `target_id` | string | Target UUID | | `target_name` | string | `"Sales.Customer"`; three-part for an attribute or an enumeration value: `"Sales.Order.Total"`, `"Sales.OrderStatus.Open"` | -| `ref_kind` | string | How it references: `"call"`, `"create"`, `"retrieve"`, `"change"`, `"delete"`, `"commit"` (a commit action, or a create/change that commits — beside its `"create"`/`"change"` edge; a commit of a variable whose entity the flow cannot tell has no edge), `"show_page"`, `"snippet_call"` (a page, snippet or layout places a snippet), `"datasource"`, `"action"`, `"layout"`, `"parameter"` (a page, snippet or flow parameter's entity type), `"return"`, `"generalize"`, `"associate"`, `"home_page"`, `"login_page"`, `"menu_item"`, `"calculate"`, `"schedule"`, `"validate"`, `"settings"`, `"widget"`, `"sync"`, `"publish"` (a published REST operation, OData resource or action, a published MCP service's tool microflow, or a service's authentication microflow), `"event"` (an entity event or a business event handler), `"member"` (binds/reads/writes an attribute, navigates an association, or reaches the entity an association step arrives at), `"xpath"` (an XPath constraint names it, or reaches the entity through an association), `"type"` (typed as an enumeration; or an entity named as a type: an action's result variable, a list a flow creates, an entity-type argument to a Java or JavaScript action), `"value"` (an expression names an enumeration value; an ENUMERATION target when the value named does not exist), `"mapping"` (an import/export mapping maps the entity, or a message definition exposes it), `"split"` (a decision branches on an object being the entity), `"mapping_call"` (a flow applies an import or export mapping: an import/export action, or a REST or web service call's request or response mapping), `"structure"` (a mapping is built on a JSON structure), `"tool"` (an agent draws on a knowledge base or consumed MCP service; an agent's tool microflow, nanoflow or agent is a `"call"`, as is a microflow or agent document passed as a Java action parameter), `"model"` (an agent runs on an AI model), `"key"` (an AI model or knowledge base reads its key from a constant), `"endpoint"` (a consumed MCP service reads its server URL from a constant), `"by_name"` (a constant's value — default or a configuration's — is a flow's qualified name, so the flow is called by name), `"queue"` (a task queue runs the microflow or Java action a call places in it; the caller's `"call"` edge stays) — lower-case, unlike the types above. Attribute names used only through a variable in a free-text expression (`$Order/Total`) have no edge | +| `ref_kind` | string | How it references: `"call"`, `"create"`, `"retrieve"`, `"change"`, `"delete"`, `"commit"` (a commit action, or a create/change that commits — beside its `"create"`/`"change"` edge; a commit of a variable whose entity the flow cannot tell has no edge), `"show_page"`, `"snippet_call"` (a page, snippet or layout places a snippet), `"datasource"`, `"action"`, `"layout"`, `"parameter"` (a page, snippet or flow parameter's entity type), `"return"`, `"generalize"`, `"associate"`, `"home_page"`, `"login_page"`, `"menu_item"`, `"calculate"`, `"schedule"`, `"validate"`, `"settings"`, `"widget"`, `"sync"`, `"publish"` (a published REST operation, OData resource or action, a published MCP service's tool microflow, or a service's authentication microflow), `"event"` (an entity event or a business event handler), `"member"` (binds/reads/writes an attribute, navigates an association, or reaches the entity an association step arrives at), `"xpath"` (an XPath constraint names it, or reaches the entity through an association), `"type"` (typed as an enumeration; or an entity named as a type: an action's result variable, a list a flow creates, an entity-type argument to a Java or JavaScript action), `"value"` (an expression names an enumeration value; an ENUMERATION target when the value named does not exist), `"mapping"` (an import/export mapping maps the entity, or a message definition exposes it), `"split"` (a decision branches on an object being the entity), `"mapping_call"` (a flow applies an import or export mapping: an import/export action, or a REST or web service call's request or response mapping), `"structure"` (a mapping is built on a JSON structure), `"tool"` (an agent draws on a knowledge base or consumed MCP service; an agent's tool microflow, nanoflow or agent is a `"call"`, as is a microflow or agent document passed as a Java action parameter), `"model"` (an agent runs on an AI model), `"key"` (an AI model or knowledge base reads its key from a constant), `"endpoint"` (a consumed MCP service reads its server URL from a constant), `"by_name"` (a constant's value — default or a configuration's — is a flow's qualified name, so the flow is called by name), `"queue"` (a task queue runs the microflow or Java action a call places in it; the caller's `"call"` edge stays), `"enqueue"` (a microflow places a call in a task queue — the caller's use of the queue; `"queue"` and `"by_name"` are not module dependencies) — lower-case, unlike the types above. Attribute names used only through a variable in a free-text expression (`$Order/Total`) have no edge | | `module_name` | string | Source module | ### project_security diff --git a/CHANGELOG.md b/CHANGELOG.md index 0384f2c92..1ff6a2883 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] ### Fixed - +- **`check` rejects a JSON structure custom name that Mendix refuses** (ako/mxcli#1258) — a `custom name map` or `item of` name such as `1bad`, `has space`, `Größe`, `_`, an empty string, or a reserved word in any case (`Owner`, `ChangedDate`, `Type`, `Id`, `class`, `null`) passed `check` and `exec`, and the build reported CE9524 "invalid custom name". New MDL-JSON03, which needs no project. A member whose JSON key is invalid (`$type`, `research%3Aread`) still needs no custom name: its default is sanitised. Measured on MxBuild 11.16.1 over 90 names. +- **Lint MPR017 and MPR019 no longer report external entities, and MPR017 counts mappings as writes** (ako/mxcli#2501, ako/mxcli#2502) — MPR019 told the owner of a frontend app to add 39 indexes, every one on an external entity whose table lives in the publishing app. MPR017 reported "can only ever be false" for an attribute assigned by a database-connection query's `Map:`, by an import mapping, or by an external service, none of which is a Change activity. External entities are skipped by both, and an import mapping's value elements and a query's mapped columns count as unknown writes. Export mappings, message definitions and view entities are not yet covered. +- **A published REST service rewrite says which operations it removes** (ako/mxcli#2449, mendixlabs/mxcli#1903) — `create or modify published rest service` naming only a new operation deleted the stored ones, and exec said only "Modified". `check` and exec now warn with the operations removed (MDL-REST06), and `check` refuses `alter … add resource` with a stored resource's name and `drop resource` of a missing one, as exec does. +- **`import … link` works through a self-association stored as a table** (ako/mxcli#1686) — both junction columns were named after the one entity, so the insert failed (`column "myfirstmodule$personid" … does not exist`). The column names now come from `mendixsystem$association`, and without a row a self-association's two are numbered as Mendix names them (`…personid1` parent, `…personid2` child, measured on 11.12.6). +- **A statement appended after an activity with an error handler goes after the handler's rejoin** (ako/mxcli#2489) — `create or modify microflow` spliced it between the activity and the merge its handler rejoins, so the error path skipped the new statement, and the next exec of the unchanged script was refused (MDL-V1-REBUILD). It now goes after the merge, and the script re-runs unchanged. +- **`check` names the missing entity step in `[Assoc.Attr …]`** (ako/mxcli#2491, mendixlabs/mxcli#1916) — an XPath constraint that joins an association and its far end's attribute with a dot (`[Car_Assignment.ReturnedOn = empty]`) was reported as an unknown association, and MDL047 suggested a `not(…)` that kept the dotted name. With `-p`, the access-rule and retrieve checks now say the entity step is missing and give the path (`[Repro.Car_Assignment/Repro.Assignment/ReturnedOn = empty]`); without a project, MDL047's suggestion offers that reading too. + +- **A hand-written `create external entity` maps its attributes to the contract** (ako/mxcli#2497) — every attribute was stored as a local value, with no key and `$top`/`$skip` off, so mx check reported CE6612 on each attribute, CE6010 and CE6630 on a contract the bulk import builds clean. Each stated attribute is now the contract's property of that name, as the bulk import maps it. A name, type, missing key or capability that contradicts the contract is refused, and a statement with no attribute list imports them all. - **OData enum properties are imported** (ako/mxcli#2477, mendixlabs/mxcli#1913) — `create external entities` dropped a property typed as a vendor `EnumType`, and adding it back by hand was CE6612 (or CE4597 with an ordinary enumeration). It is now an enumeration attribute of an enumeration generated from the contract, as Studio Pro makes one. `create or modify enumeration` keeps such an enumeration's link to the contract, and `alter entity … add attribute` on an external entity is refused up front (CE6612). - **`describe --format elk page` keeps a data grid's slot widgets** (ako/mxcli#2465, mendixlabs/mxcli#1910) — a DataGrid2's column content, column filters, control bar and empty-state placeholder were missing from the JSON tree. Columns now carry `children` and `filter`, and the grid carries `slots` (a gallery's filters too). - **`check` refuses a data view in a layout and a misplaced sidebar toggle** (ako/mxcli#2461) — a `dataview` in a layout (CE6086), a toggling region with no `sidebartoggle` (CE0611), a toggle outside the layout's one top-level scroll container (CE0628) and a toggle on a page or snippet (CE6086) passed check and exec and failed the build. They are now MDL-LAYOUT01..04. @@ -44,6 +51,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Not the fix, recorded because it looks like one: pinning the pool to a single connection also makes the catalog one database and **deadlocks**. The readers nest — `Entities()` yields from an open cursor while the loop body calls `AttributesFor()` — so the inner read waits forever for the connection the outer cursor holds, and a lint run that took seconds hung past 600s. ### Added +- **`alter published rest service … add operation in resource '' { … }` and `drop operation [''] in resource ''`** (ako/mxcli#2449, mendixlabs/mxcli#1903) — one operation of a stored resource, written as `create` writes it, added or removed without restating the service; the resource's other operations, and everything MDL cannot spell about them, are written back as stored. An operation the resource already has, or a resource it does not have, is refused by check and exec. - **A business event message's operations are its children, and one message can both publish and subscribe** (ako/mxcli#2490) — `message X (…) { publish (Entity: M.P); subscribe (Entity: M.C, Microflow: M.H); };` writes one message with both flags and two operations; a consumed service's subscription is `consume X (Entity: …, Microflow: …);`. Declaring a message twice, once per operation (the only way before), stored two messages of one name and the deployment failed ("An item with the same key has already been added"); `check` and `exec` now refuse it. The keyword clauses `publish entity … microflow …` and `consume X entity … microflow …` still parse as deprecated aliases (MDL-DEPR075, MDL-DEPR076), and `fmt --upgrade` rewrites them. - **Lint `MPR019`: an attribute an XPath constraint filters on with no index leading with it** (ako/mxcli#2407) — every such query scans the table, and nothing else reports it: `mx check` is clean and demo data hides it. Severity `info`, because whether an index earns its place depends on table size and write rate, which the model does not know; it names a candidate rather than asserting a defect. diff --git a/cmd/mxcli/cmd_check.go b/cmd/mxcli/cmd_check.go index efc9357bc..2cd0d5c39 100644 --- a/cmd/mxcli/cmd_check.go +++ b/cmd/mxcli/cmd_check.go @@ -551,6 +551,9 @@ func runCheckFileAgainst(cmd *cobra.Command, filePath, against string) int { // write the clause (ako/mxcli#1914) — the omitted-clause warning exec // prints, said before the write. projectViolations = append(projectViolations, exec.CheckCarriedIncludedAssociations(prog)...) + // MDL-REST06: a create or modify of a stored published REST service + // that removes operations it does not list (ako/mxcli#2449). + projectViolations = append(projectViolations, exec.CheckPublishedRestOperationDrops(prog)...) projectViolations = append(projectViolations, exec.TypeCheckProgram(prog)...) flowReport := exec.CheckFlowVerdictsReport(prog) projectViolations = append(projectViolations, flowReport.Violations...) diff --git a/cmd/mxcli/cmd_report_all.go b/cmd/mxcli/cmd_report_all.go index 48aef49c6..41ef39a5d 100644 --- a/cmd/mxcli/cmd_report_all.go +++ b/cmd/mxcli/cmd_report_all.go @@ -3,6 +3,7 @@ package main import ( + "context" "fmt" "io" "os" @@ -113,7 +114,11 @@ func runReportAll(cmd *cobra.Command, projectPath, dir string, skip map[string]b fmt.Fprintf(log, "report %s ...\n", kind) p := reportPage{kind: kind} if kind == "quality" { - r, _, err := buildScoredReport(reportCmd, projectPath, io.Discard) + var r *linter.Report + err := safely(func() (err error) { + r, _, err = buildScoredReport(reportCmd, projectPath, io.Discard) + return err + }) if err != nil { p.missing, p.failed = err.Error(), true } else { @@ -136,11 +141,16 @@ func runReportAll(cmd *cobra.Command, projectPath, dir string, skip map[string]b pages = append(pages, p) continue } - env, err := rk.spec.collect(rk.cmd, projectPath) + env, err := collectKind(cmd, rk, projectPath) if err != nil { p.missing, p.failed = err.Error(), true } else { p.env = env + // Written as soon as it exists: a later kind that fails, or a run + // that is stopped, no longer takes the finished reports with it. + if err := writeFileWith(filepath.Join(dir, kind+".json"), env.WriteJSON); err != nil { + return err + } } pages = append(pages, p) } @@ -191,9 +201,6 @@ func runReportAll(cmd *cobra.Command, projectPath, dir string, skip map[string]b if err != nil { return fmt.Errorf("%s annotations: %w", p.kind, err) } - if err := writeFileWith(filepath.Join(dir, p.kind+".json"), p.env.WriteJSON); err != nil { - return err - } rk := reportKinds[p.kind] if rk.spec.renderHTML != nil { if err := writeFileWith(filepath.Join(dir, p.kind+".html"), func(w io.Writer) error { return rk.spec.renderHTML(w, p.env, ann) }); err != nil { @@ -457,3 +464,34 @@ func writeReadiness(cmd *cobra.Command, dir, project string, pages []reportPage, card.Lede, card.Stats = doc.Lede, firstStats(doc.Stats, 4) return card, nil } + +// collectKind runs one kind's collector the way `report all` and +// `report readiness` call it: with the calling command's context, which a +// kind's own command — never executed by cobra — does not have, and with a +// panic turned into that kind's error. Without the context the dependencies +// report panicked on the Marketplace ("cannot create context from nil +// parent") and its vulnerability check failed ("net/http: nil Context"); the +// panic took the whole run, and every report already computed, with it +// (ako/mxcli#2500). +func collectKind(parent *cobra.Command, rk reportKind, projectPath string) (env *projectreport.Envelope, err error) { + ctx := parent.Context() + if ctx == nil { + ctx = context.Background() + } + rk.cmd.SetContext(ctx) + err = safely(func() (err error) { + env, err = rk.spec.collect(rk.cmd, projectPath) + return err + }) + return env, err +} + +// safely runs f, turning a panic into an error that names it. +func safely(f func() error) (err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("panic: %v", r) + } + }() + return f() +} diff --git a/cmd/mxcli/cmd_report_all_robust_test.go b/cmd/mxcli/cmd_report_all_robust_test.go new file mode 100644 index 000000000..1c55b5a38 --- /dev/null +++ b/cmd/mxcli/cmd_report_all_robust_test.go @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "io" + "os" + "path/filepath" + "strings" + "testing" + + mp "github.com/mendixlabs/mxcli/internal/marketplace" + "github.com/spf13/cobra" +) + +// probeMarketplace stands in for the Marketplace: it records the context it +// was given, and panics when asked to. +type probeMarketplace struct { + gotCtx *context.Context + panics bool +} + +func (f probeMarketplace) Catalog(ctx context.Context) ([]mp.Content, error) { + *f.gotCtx = ctx + if f.panics { + panic("cannot create context from nil parent") + } + return nil, nil +} + +func (f probeMarketplace) Versions(ctx context.Context, contentID int) ([]mp.Version, error) { + return nil, nil +} + +// runAllWith runs `report all` on a copy of pedapp (it has Marketplace +// modules) for architecture and dependencies only, with the Marketplace +// replaced by fake. +func runAllWith(t *testing.T, fake probeMarketplace) (string, error) { + t.Helper() + work := t.TempDir() + if err := copyTree(filepath.Join("..", "..", "testdata", "pedapp"), filepath.Join(work, "app")); err != nil { + t.Fatal(err) + } + out := filepath.Join(work, "reports") + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatal(err) + } + old := newMarketplaceSource + newMarketplaceSource = func(cmd *cobra.Command) (marketplaceSource, error) { return fake, nil } + t.Cleanup(func() { newMarketplaceSource = old }) + skip := map[string]bool{"readiness": true} + for _, k := range reportAllKinds { + skip[k] = k != "architecture" && k != "dependencies" + } + return out, runReportAll(reportAllCmd, filepath.Join(work, "app", "PedApp.mpr"), out, skip, io.Discard) +} + +// Under `report all` a kind's command is never executed by cobra, so its +// context was nil: the dependencies report passed it to the Marketplace and +// panicked with "cannot create context from nil parent", and the +// vulnerability check failed with "net/http: nil Context" (ako/mxcli#2500). +func TestReportAllGivesEachKindAContext(t *testing.T) { + var got context.Context + if _, err := runAllWith(t, probeMarketplace{gotCtx: &got}); err != nil { + t.Fatal(err) + } + if got == nil { + t.Error("the dependencies report reached the Marketplace with a nil context") + } +} + +// A collector that panics is one failed page, not a lost run: the other +// reports and the overview are still written (ako/mxcli#2500). +func TestReportAllSurvivesAPanickingKind(t *testing.T) { + var got context.Context + out, err := runAllWith(t, probeMarketplace{gotCtx: &got, panics: true}) + if err != nil { + t.Fatal(err) + } + for _, f := range []string{"architecture.html", "architecture.json", "index.html"} { + if _, err := os.Stat(filepath.Join(out, f)); err != nil { + t.Errorf("missing %s after a kind panicked", f) + } + } + index, _ := os.ReadFile(filepath.Join(out, "index.html")) + if !strings.Contains(string(index), "panic") || !strings.Contains(string(index), "cannot create context from nil parent") { + t.Error("the overview says the dependencies report panicked, and why") + } +} diff --git a/cmd/mxcli/cmd_report_readiness.go b/cmd/mxcli/cmd_report_readiness.go index 6591bcb7b..c30004ba8 100644 --- a/cmd/mxcli/cmd_report_readiness.go +++ b/cmd/mxcli/cmd_report_readiness.go @@ -78,7 +78,7 @@ Sign off a blocking item with --annotations: readiness: with status continue } fmt.Fprintf(os.Stderr, "report %s ...\n", k) - env, err := rk.spec.collect(rk.cmd, projectPath) + env, err := collectKind(cmd, rk, projectPath) if err != nil { warnings = append(warnings, fmt.Sprintf("%s could not run: %v", k, err)) continue @@ -86,7 +86,8 @@ Sign off a blocking item with --annotations: readiness: with status envs[k] = env } fmt.Fprintln(os.Stderr, "report quality ...") - if r, _, err := buildScoredReport(reportCmd, projectPath, io.Discard); err != nil { + var r *linter.Report + if err := safely(func() (err error) { r, _, err = buildScoredReport(reportCmd, projectPath, io.Discard); return err }); err != nil { warnings = append(warnings, fmt.Sprintf("the scored report could not run: %v", err)) } else if quality, err = qualityJSON(r); err != nil { return nil, err diff --git a/cmd/mxcli/cmd_verify.go b/cmd/mxcli/cmd_verify.go index c7bf9612c..5547f6153 100644 --- a/cmd/mxcli/cmd_verify.go +++ b/cmd/mxcli/cmd_verify.go @@ -343,12 +343,22 @@ func (v *verifyRunner) lint() (verify.Outcome, error) { return verify.Outcome{Recorded: true, PreExisting: len(findings), Note: "baseline recorded at " + lintBaseline}, nil } pre, _ := parseLintBaselineSummary(string(stderr)) + return lintOutcome(findings, bl, pre, note), nil +} + +// lintOutcome is the lint stage's result from lint's report. pre is the +// pre-existing count read from lint's summary line, used when the JSON carries +// no baseline object. Fixed findings are the stage's resolved count, as the +// mx check stage reports its own (ako/mxcli#2506). +func lintOutcome(findings []verify.Finding, bl *lintBaselineJSON, pre int, note string) verify.Outcome { var preBy map[string]int + var resolved int if bl != nil { pre = bl.Unchanged preBy = bl.UnchangedBySeverity + resolved = bl.Fixed } - return verify.Outcome{New: findings, PreExisting: pre, PreExistingBy: preBy, Note: note, Incomplete: bl.incomplete()}, nil + return verify.Outcome{New: findings, PreExisting: pre, PreExistingBy: preBy, Resolved: resolved, Note: note, Incomplete: bl.incomplete()} } func (v *verifyRunner) mxcheck() (verify.Outcome, error) { diff --git a/cmd/mxcli/cmd_verify_test.go b/cmd/mxcli/cmd_verify_test.go index 5def3b5f9..93020506b 100644 --- a/cmd/mxcli/cmd_verify_test.go +++ b/cmd/mxcli/cmd_verify_test.go @@ -355,3 +355,22 @@ func TestVerifyListFindings(t *testing.T) { t.Errorf("listing = %q", got) } } + +// A lint finding the baseline held and the change removed is "fixed" in lint's +// comparison; the stage reports it as resolved, as the mx check stage does +// (ako/mxcli#2506). +func TestLintOutcomeCarriesFixedAsResolved(t *testing.T) { + _, bl, err := parseReport("lint", []byte(`{"violations": [], "baseline": {"new": 0, "unchanged": 451, "fixed": 1}}`)) + if err != nil { + t.Fatal(err) + } + out := lintOutcome(nil, bl, 0, "") + if out.Resolved != 1 || out.PreExisting != 451 { + t.Errorf("outcome = resolved %d, pre-existing %d; want 1 and 451", out.Resolved, out.PreExisting) + } + // The control: nothing fixed reports nothing resolved. + _, bl, _ = parseReport("lint", []byte(`{"violations": [], "baseline": {"new": 0, "unchanged": 451, "fixed": 0}}`)) + if out := lintOutcome(nil, bl, 0, ""); out.Resolved != 0 { + t.Errorf("resolved = %d with nothing fixed", out.Resolved) + } +} diff --git a/cmd/mxcli/projectreport/architecture.go b/cmd/mxcli/projectreport/architecture.go index 53d4c8dd8..91ec7167b 100644 --- a/cmd/mxcli/projectreport/architecture.go +++ b/cmd/mxcli/projectreport/architecture.go @@ -4,6 +4,7 @@ package projectreport import ( "fmt" + "github.com/mendixlabs/mxcli/mdl/catalog" "math" "path" "regexp" @@ -190,10 +191,17 @@ func CollectArchitecture(q Querier, opt ArchitectureOptions) (*ArchitectureData, return nil, err } refs := make([]refRow, 0, len(rs)) + notUse := setOf(catalog.RefKindsNotModuleUse) for _, r := range rs { if excl.out(r["SourceName"]) || excl.out(r["TargetName"]) { continue } + // A queue does not use the flows queued on it (the caller does, by + // `enqueue`), and a constant naming a flow is configuration + // (ako/mxcli#2503). + if notUse[r["RefKind"]] { + continue + } refs = append(refs, refRow{r["SourceName"], r["SourceType"], r["TargetName"], r["TargetType"], r["RefKind"]}) } diff --git a/cmd/mxcli/projectreport/architecture_test.go b/cmd/mxcli/projectreport/architecture_test.go index 9d5e58904..4d97403af 100644 --- a/cmd/mxcli/projectreport/architecture_test.go +++ b/cmd/mxcli/projectreport/architecture_test.go @@ -248,3 +248,46 @@ func TestArchitectureExcludeDocs(t *testing.T) { _ = RenderMarkdown(&md, doc) mustContain(t, md.String(), "2 app documents matching `Billing.ACT_*`, `Billing.Unused` are left out") } + +// A task queue runs flows of other modules, but its module does not use them: +// the caller does, through the queue. `queue` and `by_name` edges made the +// queue's module "depend" on every flow it runs, closing a false 9-module +// cycle (ako/mxcli#2503). +func TestQueueAndByNameAreNotModuleDependencies(t *testing.T) { + f := newFixture(t) + for _, m := range []string{"Rooster", "Ruilen", "Verlof", "OIDC"} { + f.module(m, "") + } + f.microflow("Ruilen.WFA_Goedkeuren", false, "") + f.microflow("Ruilen.SUB_Ruiling_Doorvoeren", false, "") + f.microflow("Verlof.SUB_Verlof_InRooster", false, "") + f.microflow("Rooster.SUB_Rooster", false, "") + // The queue lives in Rooster and runs Ruilen's and Verlof's flows. + f.ref("Rooster.TQ_RoosterMutaties", "TASK_QUEUE", "Ruilen.SUB_Ruiling_Doorvoeren", "MICROFLOW", "queue") + f.ref("Rooster.TQ_RoosterMutaties", "TASK_QUEUE", "Verlof.SUB_Verlof_InRooster", "MICROFLOW", "queue") + // Ruilen's caller places the call in Rooster's queue: Ruilen uses Rooster. + f.ref("Ruilen.WFA_Goedkeuren", "MICROFLOW", "Rooster.TQ_RoosterMutaties", "TASK_QUEUE", "enqueue") + f.call("Ruilen.WFA_Goedkeuren", "Ruilen.SUB_Ruiling_Doorvoeren") + // A constant in OIDC names a Rooster flow: configuration, not use. + f.ref("OIDC.ProvisioningMicroflow", "CONSTANT", "Rooster.SUB_Rooster", "MICROFLOW", "by_name") + + d, err := CollectArchitecture(f.cat, ArchitectureOptions{}) + if err != nil { + t.Fatal(err) + } + edges := map[string]bool{} + for _, e := range d.DomainEdges { + edges[e.From+"->"+e.To] = true + } + for _, bad := range []string{"Rooster->Ruilen", "Rooster->Verlof", "OIDC->Rooster"} { + if edges[bad] { + t.Errorf("false dependency %s (edges %v)", bad, edges) + } + } + if !edges["Ruilen->Rooster"] { + t.Errorf("the caller's use of the queue is Ruilen -> Rooster (edges %v)", edges) + } + if len(d.Cycles) != 0 { + t.Errorf("no cycle: %+v", d.Cycles) + } +} diff --git a/cmd/mxcli/syntax/features_integration.go b/cmd/mxcli/syntax/features_integration.go index 65980762a..81b8f8160 100644 --- a/cmd/mxcli/syntax/features_integration.go +++ b/cmd/mxcli/syntax/features_integration.go @@ -63,7 +63,11 @@ func init() { "CREATE EXTERNAL ENTITY Module.Name\n" + " FROM CONSUMED ODATA SERVICE Module.Client\n" + " (EntitySet: 'Name', RemoteName: 'Name')\n" + - " (Attr: Type, ...);\n\n" + + " (Attr: Type, ...);\n" + + "-- Each Attr is the contract property of that name, mapped as the bulk\n" + + "-- 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" + " [INTO Module] [ENTITIES (Name1, Name2)];\n\n" + "ALTER ENTITY Module.Name SET (AllowCreateChangeLocally: true);\n\n" + @@ -430,7 +434,7 @@ func init() { "-- Documentation: the /** ... */ doc comment above CREATE, the service's own\n" + "-- documentation (not the OpenAPI description, which MDL keeps unchanged).\n" + "-- On OR MODIFY no comment keeps the stored text, /** */ clears it.\n\n" + - "ALTER PUBLISHED REST SERVICE Module.Name SET ( Version: '2.0.0', Authentication: (session) );\nALTER PUBLISHED REST SERVICE Module.Name SET Version = '2.0.0';\nALTER PUBLISHED REST SERVICE Module.Name ADD RESOURCE 'items' { ... };\nALTER PUBLISHED REST SERVICE Module.Name DROP RESOURCE 'legacy';\nDROP PUBLISHED REST SERVICE Module.Name;", + "ALTER PUBLISHED REST SERVICE Module.Name SET ( Version: '2.0.0', Authentication: (session) );\nALTER PUBLISHED REST SERVICE Module.Name SET Version = '2.0.0';\nALTER PUBLISHED REST SERVICE Module.Name ADD RESOURCE 'items' { ... };\nALTER PUBLISHED REST SERVICE Module.Name DROP RESOURCE 'legacy';\nALTER PUBLISHED REST SERVICE Module.Name ADD OPERATION IN RESOURCE 'items' {\n delete '{id}' microflow Module.PRS_DeleteItem;\n}; -- create's operation line; the resource's other operations are kept as stored\nALTER PUBLISHED REST SERVICE Module.Name DROP OPERATION delete '{id}' IN RESOURCE 'items';\nDROP PUBLISHED REST SERVICE Module.Name;", Example: "mdl 1;\nCREATE PUBLISHED REST SERVICE Module.OrderAPI (\n Path: 'rest/orders/v1',\n Version: '1.0.0',\n ServiceName: 'Order API',\n Authentication: (basic, session)\n)\n{\n RESOURCE 'orders' {\n GET '' MICROFLOW Module.GetAllOrders;\n GET '{id}' MICROFLOW Module.GetOrderById;\n POST '' MICROFLOW Module.CreateOrder;\n DELETE '{id}' MICROFLOW Module.DeleteOrder;\n }\n};\n\nGRANT ACCESS ON PUBLISHED REST SERVICE Module.OrderAPI\n TO Module.User, Module.Admin;", SeeAlso: []string{"rest", "rest.consumed"}, }) diff --git a/docs-site/src/appendixes/error-messages.md b/docs-site/src/appendixes/error-messages.md index fed772aa8..37fb2ec7d 100644 --- a/docs-site/src/appendixes/error-messages.md +++ b/docs-site/src/appendixes/error-messages.md @@ -295,6 +295,17 @@ CE6086 ("Data views are not allowed on web layouts.") [MDL-LAYOUT01] **Solution:** Put the data view on the page, inside `placeholder Main { … }`. For a toggling sidebar, make the `scrollcontainer` the layout's one top-level widget and put the toggle in one of its regions, for example `region top { sidebartoggle tg (Caption: 'Menu') }`. A layout built on another one (`Layout:`) is checked only for data views. +### MDL-REST06: `create or modify` removes stored operations + +``` +⚠ create or modify published rest service Shop.BookingApi removes 1 stored operation(s) it does not list: +GET bookings/{id} [MDL-REST06] +``` + +**Cause:** `create or modify published rest service` describes the whole service. An operation of the stored service that the statement does not list is deleted. That is right when the script means to remove it. It is a loss when the statement was written to add one operation and lists only that. exec used to report only "Modified published rest service". + +**Solution:** List every operation the service keeps; `describe published rest service` prints them. To add or remove one operation, leave the rest of the service alone with `alter published rest service … add operation in resource '' { ; }` and `drop operation [''] in resource ''`. `check` refuses `add resource` with the name of a stored resource, and `add operation` with an operation the resource already has, as exec does. + ## mxcli Parser Errors diff --git a/docs-site/src/reference/odata/README.md b/docs-site/src/reference/odata/README.md index 33f9957e0..eb58239dc 100644 --- a/docs-site/src/reference/odata/README.md +++ b/docs-site/src/reference/odata/README.md @@ -24,9 +24,36 @@ Mendix supports consuming and publishing OData services. Consumed services (ODat | Statement | Description | |-----------|-------------| -| [CREATE EXTERNAL ENTITY](create-external-entity.md) | Import an entity from a consumed OData service | +| [CREATE EXTERNAL ENTITY](#create-external-entity) | Import one entity from a consumed OData service | | [CREATE EXTERNAL ENTITIES](#create-external-entities) | Bulk-create external entities from cached $metadata | +## CREATE EXTERNAL ENTITY + +```sql +create external entity Sales.Order from consumed odata service Sales.SalesApi + (EntitySet: 'Orders') + (OrderId: Long, Title: String(100), Status: Enumeration(Sales.OrderStatus)); +``` + +The attributes come from the service's cached `$metadata`. Each one listed is +the property of that name, mapped exactly as [CREATE EXTERNAL +ENTITIES](#create-external-entities) maps it. Its remote name and type, its +capabilities, the entity's key, `Countable`, `$top` and `$skip` all follow the +contract. So does the enumeration of an enum-typed property (see below). List +a subset to import only those properties. Leave out the list to import them +all. + +What would not build is refused, with nothing written: + +- a name that is not one of the contract's attributes (the message lists them); +- a type the service does not publish, including an ordinary enumeration for an + enum-typed property; +- a missing key attribute (`CE6010` "Key cannot be empty"); +- a `Countable`, `Creatable` or `Deletable` that differs from the entity set's + (`CE6630`). Leave them out to follow the service. + +`AllowCreateChangeLocally` is a local choice and is written as stated. + ## CREATE EXTERNAL ENTITIES Bulk-create external entities from a consumed OData service's cached `$metadata`. diff --git a/mdl-examples/bug-tests/2449-published-rest-add-operation.mdl b/mdl-examples/bug-tests/2449-published-rest-add-operation.mdl new file mode 100644 index 000000000..d9f2a82ca --- /dev/null +++ b/mdl-examples/bug-tests/2449-published-rest-add-operation.mdl @@ -0,0 +1,43 @@ +-- ako/mxcli#2449 (mendixlabs/mxcli#1903): one operation of a stored resource +-- of a published REST service, added or removed without restating the service. +-- The operation is written as create writes it; the resource's other +-- operations are written back as stored. Measured on 11.12.6: mx check 0 +-- errors, and the describe output re-executes Unchanged. +mdl 1; + +create module BugRest2449; + +create microflow BugRest2449.PRS_ListBookings () returns String as $Result +begin + return 'list'; +end; + +create microflow BugRest2449.PRS_GetBooking ($id: String) returns String as $Result +begin + return $id; +end; + +create microflow BugRest2449.PRS_DeleteBooking ($id: String) returns String as $Result +begin + return $id; +end; + +create published rest service BugRest2449.BookingApi ( + Path: 'rest/booking/v1', + Version: '1.0.0', + ServiceName: 'Booking API' +) +{ + resource 'bookings' { + get '' microflow BugRest2449.PRS_ListBookings; + get '{id}' microflow BugRest2449.PRS_GetBooking; + } +}; + +alter published rest service BugRest2449.BookingApi + add operation in resource 'bookings' { + delete '{id}' microflow BugRest2449.PRS_DeleteBooking; + }; + +alter published rest service BugRest2449.BookingApi + drop operation get '{id}' in resource 'bookings'; diff --git a/mdl-examples/bug-tests/external-entity-allow-create-change-locally.mdl b/mdl-examples/bug-tests/external-entity-allow-create-change-locally.mdl index 155f79b1e..b660af422 100644 --- a/mdl-examples/bug-tests/external-entity-allow-create-change-locally.mdl +++ b/mdl-examples/bug-tests/external-entity-allow-create-change-locally.mdl @@ -2,15 +2,16 @@ mdl 1; -- Issue #534: ALTER ENTITY SET ALLOW_CREATE_CHANGE_LOCALLY = true/false -- and CREATE EXTERNAL ENTITY with AllowCreateChangeLocally property. --- Create an external entity with the flag set at creation time. +-- Create an external entity with the flag set at creation time. The flag is a +-- local choice; Countable, Creatable and Deletable are TripPin's, which declares +-- no capability annotations (read-only), and a stated value that contradicts +-- them is refused as CE6630 (ako/mxcli#2497). create or modify external entity TripPin.People from consumed odata service TripPin.TripPinClient ( EntitySet: 'People', Countable: Yes, - Creatable: Yes, Deletable: No, - Updatable: Yes, AllowCreateChangeLocally: Yes ) ( diff --git a/mdl-examples/bug-tests/json-structure-custom-names.mdl b/mdl-examples/bug-tests/json-structure-custom-names.mdl new file mode 100644 index 000000000..1b04c4dc7 --- /dev/null +++ b/mdl-examples/bug-tests/json-structure-custom-names.mdl @@ -0,0 +1,15 @@ +mdl 1; +-- CONTROL for json-structure-invalid-custom-name.fail.mdl: custom names MxBuild 11.16.1 +-- builds clean, including words that look reserved but are not (String, System, Value, +-- Entity, Date, List, User). +create json structure MyFirstModule.JS_GoodNames + sample '{"a": "x", "b": "x", "c": "x", "d": "x", "e": "x", "f": "x", "tags": ["t"], "$type": "s", "owner": "o"}' + custom name map ( + 'a' as 'Good_Name1', + 'b' as '_x', + 'c' as 'String', + 'd' as 'System', + 'e' as 'Value', + 'f' as 'Entity', + item of 'tags' as 'Tag' + ); diff --git a/mdl-examples/bug-tests/json-structure-invalid-custom-name.fail.mdl b/mdl-examples/bug-tests/json-structure-invalid-custom-name.fail.mdl new file mode 100644 index 000000000..d139e75c6 --- /dev/null +++ b/mdl-examples/bug-tests/json-structure-invalid-custom-name.fail.mdl @@ -0,0 +1,30 @@ +mdl 1; +-- NEGATIVE TEST — `mxcli check` must REFUSE this file (MDL-JSON03), with no project. +-- +-- A CUSTOM NAME MAP name (or an `item of` name) that Mendix refuses. `check` and +-- `exec` accepted every one and wrote the structure; the build reported +-- +-- [CE9524] "JSON element '(Object)/name' has an invalid custom name '1bad'. Custom name +-- should start with a letter or underscore, followed by letters, digits or +-- underscores." +-- +-- Measured on MxBuild 11.16.1 over 90 names: the name must be ASCII letters, digits and +-- underscores, starting with a letter or underscore (a lone `_` is refused too), and must +-- not be a platform-reserved word in any case (Owner, ChangedDate, Type, Id, GUID, Object, +-- class, null, …). See json-structure-custom-names.mdl for the names that build clean. +-- A member whose JSON KEY is invalid needs no custom name: the default is sanitised. +create json structure MyFirstModule.JS_BadDigit + sample '{"name": "a"}' + custom name map ('name' as '1bad'); + +create json structure MyFirstModule.JS_BadSpace + sample '{"name": "a"}' + custom name map ('name' as 'has space'); + +create json structure MyFirstModule.JS_Reserved + sample '{"name": "a"}' + custom name map ('name' as 'Owner'); + +create json structure MyFirstModule.JS_BadItem + sample '{"tags": ["a"]}' + custom name map (item of 'tags' as 'class'); diff --git a/mdl/ast/ast_rest.go b/mdl/ast/ast_rest.go index 2bafbc3cc..e14f582fe 100644 --- a/mdl/ast/ast_rest.go +++ b/mdl/ast/ast_rest.go @@ -272,3 +272,22 @@ type PublishedRestDropResourceAction struct { } func (a *PublishedRestDropResourceAction) isPublishedRestAlterAction() {} + +// PublishedRestAddOperationsAction represents: +// ADD OPERATION IN RESOURCE 'name' { ops... } (ako/mxcli#2449). +type PublishedRestAddOperationsAction struct { + Resource string + Operations []*PublishedRestOperationDef +} + +func (a *PublishedRestAddOperationsAction) isPublishedRestAlterAction() {} + +// PublishedRestDropOperationAction represents: +// DROP OPERATION ['path'] IN RESOURCE 'name' (ako/mxcli#2449). +type PublishedRestDropOperationAction struct { + Resource string + HTTPMethod string + Path string +} + +func (a *PublishedRestDropOperationAction) isPublishedRestAlterAction() {} diff --git a/mdl/catalog/builder_byname_queue_refs_test.go b/mdl/catalog/builder_byname_queue_refs_test.go index 8f33d55f7..08f897e04 100644 --- a/mdl/catalog/builder_byname_queue_refs_test.go +++ b/mdl/catalog/builder_byname_queue_refs_test.go @@ -63,8 +63,8 @@ func TestByNameAndQueueRefs(t *testing.T) { if err := tx.Commit(); err != nil { t.Fatal(err) } - if n != 4 { - t.Errorf("emitted %d refs, want 4", n) + if n != 5 { + t.Errorf("emitted %d refs, want 5", n) } res, err := cat.Query(`SELECT SourceType, SourceName, TargetType, TargetName, RefKind, ModuleName FROM refs ORDER BY RefKind, SourceName, TargetName`) if err != nil { @@ -73,6 +73,8 @@ func TestByNameAndQueueRefs(t *testing.T) { want := [][]any{ {"CONSTANT", "OIDC.Hook", "MICROFLOW", "Loops.Configured", "by_name", "OIDC"}, {"CONSTANT", "OIDC.ProvisioningMicroflow", "MICROFLOW", "Loops.Provision", "by_name", "OIDC"}, + // the caller uses the queue (ako/mxcli#2503) + {"MICROFLOW", "Loops.Act_Enqueue", "TASK_QUEUE", "Loops.Background", "enqueue", "Loops"}, {"TASK_QUEUE", "Loops.Background", "JAVA_ACTION", "Loops.JA_Export", "queue", "Loops"}, {"TASK_QUEUE", "Loops.Background", "MICROFLOW", "Loops.Sub_Background", "queue", "Loops"}, } diff --git a/mdl/catalog/builder_graph.go b/mdl/catalog/builder_graph.go index ebe765f32..8ffa5d285 100644 --- a/mdl/catalog/builder_graph.go +++ b/mdl/catalog/builder_graph.go @@ -291,7 +291,8 @@ func (b *Builder) loadModuleEdges() ([]graph.Edge, map[string]map[string]map[str FROM refs WHERE instr(SourceName, '.') > 0 AND instr(TargetName, '.') > 0 AND substr(SourceName, 1, instr(SourceName, '.') - 1) - != substr(TargetName, 1, instr(TargetName, '.') - 1)`) + != substr(TargetName, 1, instr(TargetName, '.') - 1) + AND RefKind NOT IN (` + notModuleUseSQL() + `)`) if err != nil { return nil, nil, err } @@ -349,3 +350,12 @@ func (b *Builder) loadGraphEdges() ([]graph.Edge, error) { } return edges, rows.Err() } + +// notModuleUseSQL renders RefKindsNotModuleUse as a quoted SQL IN list. +func notModuleUseSQL() string { + quoted := make([]string, len(RefKindsNotModuleUse)) + for i, k := range RefKindsNotModuleUse { + quoted[i] = "'" + k + "'" + } + return strings.Join(quoted, ", ") +} diff --git a/mdl/catalog/builder_module_cycles_test.go b/mdl/catalog/builder_module_cycles_test.go index 66a8a1efe..25b4177f4 100644 --- a/mdl/catalog/builder_module_cycles_test.go +++ b/mdl/catalog/builder_module_cycles_test.go @@ -236,3 +236,27 @@ func TestGraphAnalysisScopeTracksGraphRefKinds(t *testing.T) { t.Errorf("kinds in graphRefKinds reported as outside the asset graph: %v", excluded) } } + +// A queue in module A running flows of B is not A using B: the caller in B +// uses A's queue (`enqueue`). Counting the `queue` edge closed a false cycle +// across every module whose flow the queue runs — 9 modules on one app — and a +// constant in A naming a flow in B is configuration, not use (ako/mxcli#2503). +func TestQueueAndByNameCloseNoModuleCycle(t *testing.T) { + cat := moduleCycleCatalog(t, []probeRef{ + {"Ruilen.WFA_Goedkeuren", "Rooster.TQ_RoosterMutaties", "enqueue"}, + {"Rooster.TQ_RoosterMutaties", "Ruilen.SUB_Ruiling_Doorvoeren", "queue"}, + {"Verlof.SUB_Plan", "OIDC.Hook", "call"}, + {"OIDC.ProvisioningMicroflow", "Verlof.SUB_Provision", "by_name"}, + }) + if got := moduleCycleRows(t, cat); len(got) != 0 { + t.Errorf("graph_module_cycles = %v, want empty: queue and by_name edges are not module use", got) + } + // Control: a real use the other way closes the cycle. + cat = moduleCycleCatalog(t, []probeRef{ + {"Ruilen.WFA_Goedkeuren", "Rooster.TQ_RoosterMutaties", "enqueue"}, + {"Rooster.SUB_Rooster", "Ruilen.SUB_Ruiling_Doorvoeren", "call"}, + }) + if got := moduleCycleRows(t, cat); len(got) != 2 { + t.Errorf("control: a call back from Rooster closes the cycle, got %v", got) + } +} diff --git a/mdl/catalog/builder_references.go b/mdl/catalog/builder_references.go index 5a86396a0..780a5fa1a 100644 --- a/mdl/catalog/builder_references.go +++ b/mdl/catalog/builder_references.go @@ -53,8 +53,16 @@ const ( RefKindEndpoint = "endpoint" // A consumed MCP service reads its server URL from a constant RefKindByName = "by_name" // A constant's value (default or a configuration's) is a flow's qualified name: the flow is called by name RefKindQueue = "queue" // A task queue runs a microflow or Java action a call places in it + RefKindEnqueue = "enqueue" // A microflow places a call in a task queue: the caller uses the queue (ako/mxcli#2503) ) +// RefKindsNotModuleUse are kinds whose edge does not mean the source's module +// uses the target's: a queue does not depend on the flows queued on it (the +// caller does, through `enqueue`), and a constant naming a flow is +// configuration. Module dependencies and module cycles leave them out; +// reachability (dead assets, callers) still counts them (ako/mxcli#2503). +var RefKindsNotModuleUse = []string{RefKindQueue, RefKindByName} + // RefKinds is every value that reaches refs.RefKind. It is the vocabulary a // consumer of the reference graph iterates when it must decide something per // kind: TestQUAL004CountsEveryRefKind drives each one at the orphan rule, so an @@ -72,6 +80,7 @@ var RefKinds = []string{ RefKindValue, RefKindMapping, RefKindSplit, RefKindSnippetCall, RefKindMappingCall, RefKindStructure, RefKindTool, RefKindModel, RefKindKey, RefKindEndpoint, RefKindByName, RefKindQueue, + RefKindEnqueue, } // Object types recorded in refs.SourceType and refs.TargetType — the catalog's @@ -1505,8 +1514,9 @@ func (b *Builder) extractByNameRefs(stmt *Stmt, projectID, snapshotID string) in } // extractQueueRefs emits one `queue` edge from a task queue to each microflow -// or Java action a call runs in it. The caller's own `call` edge is kept: the -// caller still decides THAT it runs, the queue decides WHEN. +// or Java action a call runs in it, and one `enqueue` edge from each microflow +// that places a call in a queue to that queue. The caller's own `call` edge is +// kept: the caller still decides THAT it runs, the queue decides WHEN. func (b *Builder) extractQueueRefs(stmt *Stmt, projectID, snapshotID string) int { b.disown() rows, err := b.tx.Query(`SELECT DISTINCT a.QueueRef, a.ActionRef, @@ -1528,6 +1538,28 @@ func (b *Builder) extractQueueRefs(stmt *Stmt, projectID, snapshotID string) int } rows.Close() count := 0 + // The caller's side: the microflow that places the call uses the queue. + // Without it the only edge between the two modules ran from the queue's + // module to the queued flow's, the wrong way round (ako/mxcli#2503). + callers, err := b.tx.Query(`SELECT DISTINCT MicroflowQualifiedName, ModuleName, QueueRef + FROM activities_data WHERE COALESCE(QueueRef, '') != '' AND COALESCE(MicroflowQualifiedName, '') != '' ORDER BY 1, 3`) + if err == nil { + type use struct{ caller, module, queue string } + var uses []use + for callers.Next() { + var u use + if callers.Scan(&u.caller, &u.module, &u.queue) == nil { + uses = append(uses, u) + } + } + callers.Close() + for _, u := range uses { + if _, err := stmt.Exec(RefObjectMicroflow, "", u.caller, RefObjectTaskQueue, "", u.queue, + RefKindEnqueue, u.module, projectID, snapshotID); err == nil { + count++ + } + } + } for _, e := range edges { target := RefObjectJavaAction if e.isFlow { diff --git a/mdl/catalog/tables.go b/mdl/catalog/tables.go index b44576897..a4e183c14 100644 --- a/mdl/catalog/tables.go +++ b/mdl/catalog/tables.go @@ -7,6 +7,11 @@ package catalog // // History: // +// 50 (task queue direction): refs gains `enqueue` edges, from the +// microflow that places a call in a task queue to the queue, and module +// cycles no longer count `queue` and `by_name` edges, which made a +// queue's module "depend" on every flow it runs (ako/mxcli#2503). +// Without the bump a cached catalog keeps the false module cycles. // 49 (constant base URL, published REST authentication): // consumed_rest_services gains BaseUrlConstant, the constant a REST // client reads its base URL from; BaseUrl held only a literal, so a @@ -269,7 +274,7 @@ package catalog // SnapshotSource / SourceId / SourceBranch / SourceRevision columns // from every row (issue #576). // 1 — initial flat schema with denormalized snapshot columns on every row. -const CatalogSchemaVersion = "49" +const CatalogSchemaVersion = "50" // MetaSchemaVersion is the catalog_meta key that records the schema version // the cache was built against. diff --git a/mdl/executor/alter_published_rest_operation_2449_test.go b/mdl/executor/alter_published_rest_operation_2449_test.go new file mode 100644 index 000000000..4276761b0 --- /dev/null +++ b/mdl/executor/alter_published_rest_operation_2449_test.go @@ -0,0 +1,112 @@ +// 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/mdl/visitor" + "github.com/mendixlabs/mxcli/model" +) + +// ako/mxcli#2449 part 1: an operation of a stored resource, added or dropped +// on its own. The operation is written as `create` writes it, inside +// `add operation in resource '' { … }`; the resource's other +// operations, and the service's other resources, are written back as stored. + +func alterOps2449(t *testing.T, src string) (*model.PublishedRestService, error) { + t.Helper() + mod := mkModule("M") + h := mkHierarchy(mod) + svc := bookingService2449() + svc.ID = nextID("prs") + svc.ContainerID = mod.ID + svc.Resources[0].Operations[0].Microflow = "M.PRS_ListBookings" + svc.Resources[0].Operations[1].Microflow = "M.PRS_GetBooking" + svc.Resources[0].Operations[1].Summary = "set in Studio Pro" + withContainer(h, svc.ContainerID, mod.ID) + var written *model.PublishedRestService + mb := &mock.MockBackend{ + IsConnectedFunc: func() bool { return true }, + ListModulesFunc: func() ([]*model.Module, error) { return []*model.Module{mod}, nil }, + ListPublishedRestServicesFunc: func() ([]*model.PublishedRestService, error) { + return []*model.PublishedRestService{svc}, nil + }, + UpdatePublishedRestServiceFunc: func(s *model.PublishedRestService) error { written = s; return nil }, + } + ctx, _ := newMockCtx(t, withBackend(mb), withHierarchy(h)) + prog, errs := visitor.Build(src) + if len(errs) > 0 { + t.Fatalf("parse: %v", errs) + } + stmt := prog.Statements[0].(*ast.AlterPublishedRestServiceStmt) + if err := execAlterPublishedRestService(ctx, stmt); err != nil { + return written, err + } + return written, nil +} + +func operationKeys2449(svc *model.PublishedRestService) []string { + var out []string + for _, r := range svc.Resources { + for _, op := range r.Operations { + out = append(out, publishedRestOperationKey(r.Name, op.HTTPMethod, op.Path)+" -> "+op.Microflow) + } + } + return out +} + +func TestAlterAddOperationInResource_2449(t *testing.T) { + got, err := alterOps2449(t, `alter published rest service M.BookingApi + add operation in resource 'bookings' { + delete '{id}' microflow M.PRS_DeleteBooking; + post microflow M.PRS_CreateBooking commit Yes; + };`) + if err != nil { + t.Fatal(err) + } + want := "GET bookings -> M.PRS_ListBookings, GET bookings/{id} -> M.PRS_GetBooking, " + + "DELETE bookings/{id} -> M.PRS_DeleteBooking, POST bookings -> M.PRS_CreateBooking" + if strings.Join(operationKeys2449(got), ", ") != want { + t.Errorf("operations = %v\nwant %s", operationKeys2449(got), want) + } + // What MDL cannot spell on a stored operation stays. + if got.Resources[0].Operations[1].Summary != "set in Studio Pro" { + t.Error("the stored operation lost its summary") + } +} + +func TestAlterDropOperationInResource_2449(t *testing.T) { + got, err := alterOps2449(t, `alter published rest service M.BookingApi drop operation get '{id}' in resource 'bookings';`) + if err != nil { + t.Fatal(err) + } + if strings.Join(operationKeys2449(got), ", ") != "GET bookings -> M.PRS_ListBookings" { + t.Errorf("operations = %v", operationKeys2449(got)) + } +} + +func TestAlterOperationRefusals_2449(t *testing.T) { + for src, want := range map[string]string{ + `alter published rest service M.BookingApi add operation in resource 'bookings' { get '{id}' microflow M.X; };`: "already exists", + `alter published rest service M.BookingApi add operation in resource 'rooms' { get microflow M.X; };`: "add resource 'rooms'", + `alter published rest service M.BookingApi drop operation put '{id}' in resource 'bookings';`: "not found", + } { + written, err := alterOps2449(t, src) + if err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%s\n err = %v, want one mentioning %q", src, err, want) + } + if written != nil { + t.Errorf("%s\n written despite the refusal", src) + } + // check says the same before exec. + prog, _ := visitor.Build(src) + probs := publishedRestAlterResourceProblems(bookingService2449(), prog.Statements[0].(*ast.AlterPublishedRestServiceStmt)) + if len(probs) == 0 { + t.Errorf("%s\n check found nothing", src) + } + } +} diff --git a/mdl/executor/cmd_contract.go b/mdl/executor/cmd_contract.go index 8df2876c2..20edf6b83 100644 --- a/mdl/executor/cmd_contract.go +++ b/mdl/executor/cmd_contract.go @@ -581,255 +581,10 @@ func createExternalEntities(ctx *ExecContext, s *ast.CreateExternalEntitiesStmt) continue } - // Resolve the merged property and key set by walking the BaseType chain. - mergedProps, keyProps := mergedPropertiesWithKey(et, typeByQualified) - - // Expand complex-typed properties into one attribute per leaf, the - // way Studio Pro imports them (MaxQty -> MaxQty_UoMNId, - // MaxQty_QuantityValue). Without this every such property fell - // through the `!strings.HasPrefix(p.Type, "Edm.")` drop below and - // vanished without a word, and the loss surfaced much later as - // CE1613 on a page written against the attributes Studio Pro would - // have made (mendixlabs/mxcli#1118). - flatProps, nestedComplex := doc.FlattenProperties(mergedProps) - for _, u := range nestedComplex { - dropped = append(dropped, fmt.Sprintf("%s.%s", mendixName, u)) - } - - keyPropSet := make(map[string]bool) - for _, k := range keyProps { - keyPropSet[k] = true - } - - // Build key parts from the resolved key (root entity in the chain) - var keyParts []*domainmodel.RemoteKeyPart - for _, keyName := range keyProps { - var keyProp *types.EdmProperty - for _, p := range mergedProps { - if p.Name == keyName { - keyProp = p - break - } - } - if keyProp == nil { - continue - } - keyParts = append(keyParts, &domainmodel.RemoteKeyPart{ - Name: attrNameForOData(keyName, et.Name), - RemoteName: keyName, - RemoteType: keyProp.Type, - Type: edmToDomainModelAttrType(keyProp, true), - // The key part has its own Filterable, which mxbuild compares with - // the service's — the same restrictions the attribute follows. - NotFilterable: !entitySet.AttrFilterable(keyName), - }) - } - - // Capability defaults follow Mendix's CONSERVATIVE model: an OData - // entity set with no InsertRestrictions/UpdateRestrictions annotation - // is treated as read-only (Creatable/Updatable = false). Verified - // against `mx check` on the TripPin RESTier service — its metadata has - // zero capability annotations, and Mendix reports the entities as - // Creatable=False, so the app must match or CE6630 fires. Only an - // explicit annotation flips a capability on. Non-top-level (contained/ - // derived) types default true — they are mutated via their parent's - // write flow. (The earlier permissive default regressed this; the - // service that motivated #729 was a narrower ETag/Concurrency case.) - defaultCreatable := false - if !isTopLevel { - defaultCreatable = true - } - if entitySet != nil && entitySet.Insertable != nil { - defaultCreatable = *entitySet.Insertable - } - - // Updatable does NOT follow UpdateRestrictions, and that asymmetry - // with Creatable right above it is the whole of this rule: NO - // attribute of a top-level entity is updatable, and EVERY attribute - // of a non-top-level one is, because the latter is written through - // its parent's flow. - // - // Measured on mxbuild 11.12.1 across ten contract shapes, each a - // top-level set mxbuild reads as updatable and each answering - // False — inline , typed , - // UpdateMethod=PATCH, +NonUpdatableProperties +DeleteRestrictions, - // unannotated, external , - // Core.Permissions/ReadWrite, Core.OptimisticConcurrency (ETag), - // DeepUpdateSupport/Supported=true, and NonUpdatableProperties - // naming ONLY the key. That last one is what closes it: the service - // lists `Id` as the sole non-updatable property, i.e. asserts that - // the others ARE updatable, and mxbuild still says False. Following - // the annotation is one CE6630 per attribute. - // - // It is not "the entity is read-only" — Creatable follows - // Insertable on the very same attributes. It is not the model's - // "allow creating and changing objects locally" either: setting - // AllowCreateChangeLocally=Yes left the expectation at False. An - // external object can be changed in memory and passed to an - // external action, which is what that flag governs; this one - // mirrors what the endpoint itself accepts. - // - // entitySet.Updatable and NonUpdatableProperties are therefore read - // but never consulted here. They are left in place deliberately: if - // a contract is ever found that mxbuild does treat as updatable, - // this is where the per-property list becomes load-bearing again — - // and the key would then need its own guard, since mxbuild computes - // a top-level key as non-updatable independently (one CE6630 per - // key part, measured across the same ten shapes). - defaultUpdatable := !isTopLevel - nonInsertable := make(map[string]bool) - nonUpdatable := make(map[string]bool) - // Filter/Sort restrictions name the properties the service refuses to - // filter or sort on. Marking them filterable anyway is CE6630 - // ("'latitude' is marked Filterable=False in the OData service, but - // True in the app") — one per property, on an import whose whole job - // is to match the contract. - // Both restrictions have two shapes — a per-property exclusion list and - // a whole-set boolean — so they are resolved by EdmEntitySet rather - // than read field by field here; consulting one shape and not the - // other is what produced 28 × CE6630 on a single service - // (mxcli-formula1 §48). AttrFilterable/AttrSortable are nil-safe. - if entitySet != nil { - for _, name := range entitySet.NonInsertableProperties { - nonInsertable[name] = true - } - for _, name := range entitySet.NonUpdatableProperties { - nonUpdatable[name] = true - } - } - - // Build attributes from the flattened property set - var attrs []*domainmodel.Attribute - for _, p := range flatProps { - // Drop collection-of-primitive — handled separately as primitive - // collection NPEs below. - if strings.HasPrefix(p.Type, "Collection(") { - continue - } - // An enum-typed property becomes an enumeration attribute of an - // enumeration generated from the contract's EnumType, as Studio - // Pro imports it (ako/mxcli#2477). It was dropped, and the - // attribute written back by hand was CE6612 (a stored, not a - // mapped, value) or, with a plain enumeration, CE4597. - var enumType domainmodel.AttributeType - if et := doc.FindEnumType(p.Type); et != nil && !strings.HasPrefix(p.Type, "Edm.") { - qn, why := odataEnums.ensure(ctx, module.ID, targetModule, serviceRef, p.Type, et) - if why != "" { - dropped = append(dropped, fmt.Sprintf("%s.%s (%s) — %s", mendixName, p.Path(), p.Type, why)) - continue - } - enumType = &domainmodel.EnumerationAttributeType{EnumerationRef: qn} - } - // Anything still not an Edm type after the flatten is an entity - // reference or a complex type this document does not declare. - // Neither can become an attribute — but say so: silence here is - // what made mendixlabs/mxcli#1118 cost a build to discover. - if enumType == nil && !strings.HasPrefix(p.Type, "Edm.") { - dropped = append(dropped, fmt.Sprintf("%s.%s (%s) — not a supported attribute type", mendixName, p.Path(), p.Type)) - continue - } - // Drop Edm.Duration — Mendix has no native duration type and - // Studio Pro skips these properties. - if p.Type == "Edm.Duration" { - dropped = append(dropped, fmt.Sprintf("%s.%s (Edm.Duration) — Mendix has no duration type; Studio Pro skips it too", mendixName, p.Path())) - continue - } - - // Contract-side lookups key on the property PATH, which is what - // the service names in a PropertyPath annotation and what a - // $filter would address: "MaxQty/QuantityValue", not the local - // attribute name. - remoteName := p.Path() - - isKey := keyPropSet[p.Name] - - creatable := defaultCreatable - updatable := defaultUpdatable - if nonInsertable[remoteName] || p.Computed { - creatable = false - } - if nonUpdatable[remoteName] || p.Computed || p.Immutable { - updatable = false - } - // The key of a top-level entity is non-updatable for a reason - // of its own — a key cannot be changed after the object exists, - // which is the symptom that was reported ("'DefinitionId' is - // marked Updatable=False in the OData service, but True in the - // app") — but it needs no guard here, because defaultUpdatable - // already answers false for every top-level attribute. On a - // NON-top-level entity the key goes the other way and must stay - // updatable: clearing it there is CE6630 inverted, measured on - // the live TripPin contract over Trip, PlanItem, Event, Flight, - // PublicTransportation, Employee and Manager. `UserName` is the - // two-sided control inside that one document — False on Person - // (an entity set), True on Employee and Manager (derived). - // A property reached through a complex type carries NONE of the - // four capabilities, whatever the entity set says. - // - // Creatable/Updatable follow "External entities that contain - // attributes of complex types can only be read or deleted. They - // cannot be created, updated, or used in external actions" - // (Consumed OData Service Requirements), measured on 11.12.1 - // against a contract annotated Insertable=true AND - // Updatable=true: Mendix still reports them Creatable=False / - // Updatable=False, so following the entity set is two CE6630 per - // attribute. - // - // Filterable/Sortable go the same way, but ONLY on an entity - // with no entity set. A flattened attribute is queryable exactly - // where its entity is: measured on TripPin (11.12.1), which - // carries no capability annotations at all, Mendix reports - // - // Person (entity set People) HomeAddress_Address True - // Employee (derived, no entity set) HomeAddress_Address False - // Manager (derived, no entity set) BossOffice_Address False - // Event (derived, no entity set) OccursAt_BuildingInfo False - // - // so CE6630 fires in BOTH directions and a blanket answer cannot - // be right: stamping false everywhere is "marked Filterable=True - // in the OData service, but False in the app" on People, and - // leaving the default true is the same sentence inverted on the - // other three. Manager.BossOffice is Manager's OWN property, so - // the split is the entity set, not inheritance. - // - // Ordinary attributes of a derived type stay filterable — this - // is a property of the flattening, not of derived types. - filterable := entitySet.AttrFilterable(remoteName) - sortable := entitySet.AttrSortable(remoteName) - if p.RemotePath != "" { - creatable = false - updatable = false - if !isTopLevel { - filterable = false - sortable = false - } - } - - attrName := attrNameForOData(p.Name, et.Name) - if attrName != p.Name { - // Never let a rename be discovered later, when a page written - // against the published $metadata fails with "The selected - // attribute … no longer exists" (mxcli-formula1 #28). - renamed = append(renamed, fmt.Sprintf("%s.%s: %s -> %s", mendixName, p.Name, p.Name, attrName)) - } - attrType := enumType - if attrType == nil { - attrType = edmToDomainModelAttrType(p, isKey) - } - attr := &domainmodel.Attribute{ - Name: attrName, - Type: attrType, - RemoteName: remoteName, - RemoteType: p.Type, - Filterable: filterable, - Sortable: sortable, - Creatable: creatable, - Updatable: updatable, - } - attr.ID = model.ID(types.GenerateID()) - attrs = append(attrs, attr) - } - + 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) @@ -1944,3 +1699,274 @@ func asyncTypeString(p *types.AsyncAPIProperty) string { } // --- Executor method wrappers for backward compatibility --- + +// contractEntityParts is what one contract entity type becomes: its +// attributes (each mapped to its property), its key, and the properties that +// could not be imported or had to be renamed, with the reason. +type contractEntityParts struct { + attrs []*domainmodel.Attribute + keyParts []*domainmodel.RemoteKeyPart + dropped []string + renamed []string +} + +// contractEntityAttributes builds an entity type's attributes and key from +// the contract, as Studio Pro imports them. The bulk import and the single +// `create external entity` both write what this returns, so an attribute is +// mapped the same way whichever statement wrote it (ako/mxcli#2497). +func contractEntityAttributes(ctx *ExecContext, doc *types.EdmxDocument, et *types.EdmEntityType, + typeByQualified map[string]*types.EdmEntityType, entitySet *types.EdmEntitySet, isTopLevel bool, + mendixName string, moduleID model.ID, targetModule, serviceRef string, odataEnums *odataEnumerations) contractEntityParts { + var dropped, renamed []string + + // Resolve the merged property and key set by walking the BaseType chain. + mergedProps, keyProps := mergedPropertiesWithKey(et, typeByQualified) + + // Expand complex-typed properties into one attribute per leaf, the + // way Studio Pro imports them (MaxQty -> MaxQty_UoMNId, + // MaxQty_QuantityValue). Without this every such property fell + // through the `!strings.HasPrefix(p.Type, "Edm.")` drop below and + // vanished without a word, and the loss surfaced much later as + // CE1613 on a page written against the attributes Studio Pro would + // have made (mendixlabs/mxcli#1118). + flatProps, nestedComplex := doc.FlattenProperties(mergedProps) + for _, u := range nestedComplex { + dropped = append(dropped, fmt.Sprintf("%s.%s", mendixName, u)) + } + + keyPropSet := make(map[string]bool) + for _, k := range keyProps { + keyPropSet[k] = true + } + + // Build key parts from the resolved key (root entity in the chain) + var keyParts []*domainmodel.RemoteKeyPart + for _, keyName := range keyProps { + var keyProp *types.EdmProperty + for _, p := range mergedProps { + if p.Name == keyName { + keyProp = p + break + } + } + if keyProp == nil { + continue + } + keyParts = append(keyParts, &domainmodel.RemoteKeyPart{ + Name: attrNameForOData(keyName, et.Name), + RemoteName: keyName, + RemoteType: keyProp.Type, + Type: edmToDomainModelAttrType(keyProp, true), + // The key part has its own Filterable, which mxbuild compares with + // the service's — the same restrictions the attribute follows. + NotFilterable: !entitySet.AttrFilterable(keyName), + }) + } + + // Capability defaults follow Mendix's CONSERVATIVE model: an OData + // entity set with no InsertRestrictions/UpdateRestrictions annotation + // is treated as read-only (Creatable/Updatable = false). Verified + // against `mx check` on the TripPin RESTier service — its metadata has + // zero capability annotations, and Mendix reports the entities as + // Creatable=False, so the app must match or CE6630 fires. Only an + // explicit annotation flips a capability on. Non-top-level (contained/ + // derived) types default true — they are mutated via their parent's + // write flow. (The earlier permissive default regressed this; the + // service that motivated #729 was a narrower ETag/Concurrency case.) + defaultCreatable := false + if !isTopLevel { + defaultCreatable = true + } + if entitySet != nil && entitySet.Insertable != nil { + defaultCreatable = *entitySet.Insertable + } + + // Updatable does NOT follow UpdateRestrictions, and that asymmetry + // with Creatable right above it is the whole of this rule: NO + // attribute of a top-level entity is updatable, and EVERY attribute + // of a non-top-level one is, because the latter is written through + // its parent's flow. + // + // Measured on mxbuild 11.12.1 across ten contract shapes, each a + // top-level set mxbuild reads as updatable and each answering + // False — inline , typed , + // UpdateMethod=PATCH, +NonUpdatableProperties +DeleteRestrictions, + // unannotated, external , + // Core.Permissions/ReadWrite, Core.OptimisticConcurrency (ETag), + // DeepUpdateSupport/Supported=true, and NonUpdatableProperties + // naming ONLY the key. That last one is what closes it: the service + // lists `Id` as the sole non-updatable property, i.e. asserts that + // the others ARE updatable, and mxbuild still says False. Following + // the annotation is one CE6630 per attribute. + // + // It is not "the entity is read-only" — Creatable follows + // Insertable on the very same attributes. It is not the model's + // "allow creating and changing objects locally" either: setting + // AllowCreateChangeLocally=Yes left the expectation at False. An + // external object can be changed in memory and passed to an + // external action, which is what that flag governs; this one + // mirrors what the endpoint itself accepts. + // + // entitySet.Updatable and NonUpdatableProperties are therefore read + // but never consulted here. They are left in place deliberately: if + // a contract is ever found that mxbuild does treat as updatable, + // this is where the per-property list becomes load-bearing again — + // and the key would then need its own guard, since mxbuild computes + // a top-level key as non-updatable independently (one CE6630 per + // key part, measured across the same ten shapes). + defaultUpdatable := !isTopLevel + nonInsertable := make(map[string]bool) + nonUpdatable := make(map[string]bool) + // Filter/Sort restrictions name the properties the service refuses to + // filter or sort on. Marking them filterable anyway is CE6630 + // ("'latitude' is marked Filterable=False in the OData service, but + // True in the app") — one per property, on an import whose whole job + // is to match the contract. + // Both restrictions have two shapes — a per-property exclusion list and + // a whole-set boolean — so they are resolved by EdmEntitySet rather + // than read field by field here; consulting one shape and not the + // other is what produced 28 × CE6630 on a single service + // (mxcli-formula1 §48). AttrFilterable/AttrSortable are nil-safe. + if entitySet != nil { + for _, name := range entitySet.NonInsertableProperties { + nonInsertable[name] = true + } + for _, name := range entitySet.NonUpdatableProperties { + nonUpdatable[name] = true + } + } + + // Build attributes from the flattened property set + var attrs []*domainmodel.Attribute + for _, p := range flatProps { + // Drop collection-of-primitive — handled separately as primitive + // collection NPEs below. + if strings.HasPrefix(p.Type, "Collection(") { + continue + } + // An enum-typed property becomes an enumeration attribute of an + // enumeration generated from the contract's EnumType, as Studio + // Pro imports it (ako/mxcli#2477). It was dropped, and the + // attribute written back by hand was CE6612 (a stored, not a + // mapped, value) or, with a plain enumeration, CE4597. + var enumType domainmodel.AttributeType + if et := doc.FindEnumType(p.Type); et != nil && !strings.HasPrefix(p.Type, "Edm.") { + qn, why := odataEnums.ensure(ctx, moduleID, targetModule, serviceRef, p.Type, et) + if why != "" { + dropped = append(dropped, fmt.Sprintf("%s.%s (%s) — %s", mendixName, p.Path(), p.Type, why)) + continue + } + enumType = &domainmodel.EnumerationAttributeType{EnumerationRef: qn} + } + // Anything still not an Edm type after the flatten is an entity + // reference or a complex type this document does not declare. + // Neither can become an attribute — but say so: silence here is + // what made mendixlabs/mxcli#1118 cost a build to discover. + if enumType == nil && !strings.HasPrefix(p.Type, "Edm.") { + dropped = append(dropped, fmt.Sprintf("%s.%s (%s) — not a supported attribute type", mendixName, p.Path(), p.Type)) + continue + } + // Drop Edm.Duration — Mendix has no native duration type and + // Studio Pro skips these properties. + if p.Type == "Edm.Duration" { + dropped = append(dropped, fmt.Sprintf("%s.%s (Edm.Duration) — Mendix has no duration type; Studio Pro skips it too", mendixName, p.Path())) + continue + } + + // Contract-side lookups key on the property PATH, which is what + // the service names in a PropertyPath annotation and what a + // $filter would address: "MaxQty/QuantityValue", not the local + // attribute name. + remoteName := p.Path() + + isKey := keyPropSet[p.Name] + + creatable := defaultCreatable + updatable := defaultUpdatable + if nonInsertable[remoteName] || p.Computed { + creatable = false + } + if nonUpdatable[remoteName] || p.Computed || p.Immutable { + updatable = false + } + // The key of a top-level entity is non-updatable for a reason + // of its own — a key cannot be changed after the object exists, + // which is the symptom that was reported ("'DefinitionId' is + // marked Updatable=False in the OData service, but True in the + // app") — but it needs no guard here, because defaultUpdatable + // already answers false for every top-level attribute. On a + // NON-top-level entity the key goes the other way and must stay + // updatable: clearing it there is CE6630 inverted, measured on + // the live TripPin contract over Trip, PlanItem, Event, Flight, + // PublicTransportation, Employee and Manager. `UserName` is the + // two-sided control inside that one document — False on Person + // (an entity set), True on Employee and Manager (derived). + // A property reached through a complex type carries NONE of the + // four capabilities, whatever the entity set says. + // + // Creatable/Updatable follow "External entities that contain + // attributes of complex types can only be read or deleted. They + // cannot be created, updated, or used in external actions" + // (Consumed OData Service Requirements), measured on 11.12.1 + // against a contract annotated Insertable=true AND + // Updatable=true: Mendix still reports them Creatable=False / + // Updatable=False, so following the entity set is two CE6630 per + // attribute. + // + // Filterable/Sortable go the same way, but ONLY on an entity + // with no entity set. A flattened attribute is queryable exactly + // where its entity is: measured on TripPin (11.12.1), which + // carries no capability annotations at all, Mendix reports + // + // Person (entity set People) HomeAddress_Address True + // Employee (derived, no entity set) HomeAddress_Address False + // Manager (derived, no entity set) BossOffice_Address False + // Event (derived, no entity set) OccursAt_BuildingInfo False + // + // so CE6630 fires in BOTH directions and a blanket answer cannot + // be right: stamping false everywhere is "marked Filterable=True + // in the OData service, but False in the app" on People, and + // leaving the default true is the same sentence inverted on the + // other three. Manager.BossOffice is Manager's OWN property, so + // the split is the entity set, not inheritance. + // + // Ordinary attributes of a derived type stay filterable — this + // is a property of the flattening, not of derived types. + filterable := entitySet.AttrFilterable(remoteName) + sortable := entitySet.AttrSortable(remoteName) + if p.RemotePath != "" { + creatable = false + updatable = false + if !isTopLevel { + filterable = false + sortable = false + } + } + + attrName := attrNameForOData(p.Name, et.Name) + if attrName != p.Name { + // Never let a rename be discovered later, when a page written + // against the published $metadata fails with "The selected + // attribute … no longer exists" (mxcli-formula1 #28). + renamed = append(renamed, fmt.Sprintf("%s.%s: %s -> %s", mendixName, p.Name, p.Name, attrName)) + } + attrType := enumType + if attrType == nil { + attrType = edmToDomainModelAttrType(p, isKey) + } + attr := &domainmodel.Attribute{ + Name: attrName, + Type: attrType, + RemoteName: remoteName, + RemoteType: p.Type, + Filterable: filterable, + Sortable: sortable, + Creatable: creatable, + Updatable: updatable, + } + attr.ID = model.ID(types.GenerateID()) + attrs = append(attrs, attr) + } + + return contractEntityParts{attrs: attrs, keyParts: keyParts, dropped: dropped, renamed: renamed} +} diff --git a/mdl/executor/cmd_contract_enums.go b/mdl/executor/cmd_contract_enums.go index 0faad0421..e5260ed53 100644 --- a/mdl/executor/cmd_contract_enums.go +++ b/mdl/executor/cmd_contract_enums.go @@ -28,6 +28,27 @@ import ( // to, one value per member with the member's name as name and caption. type odataEnumerations struct { byRemote map[string]string // remote type name -> enumeration qualified name + // deferred holds back creating an enumeration until createPending names + // it: the single `create external entity` resolves every property and + // keeps only the ones the statement lists (ako/mxcli#2497). + deferred bool + pending map[string]*model.Enumeration // qualified name -> not yet created +} + +// createPending creates the held-back enumeration of that qualified name, if +// there is one. +func (o *odataEnumerations) createPending(ctx *ExecContext, qn string) error { + enum := o.pending[qn] + if enum == nil { + return nil + } + delete(o.pending, qn) + if err := ctx.Backend.CreateEnumeration(enum); err != nil { + return fmt.Errorf("creating enumeration %s: %w", qn, err) + } + invalidateHierarchy(ctx) + fmt.Fprintf(ctx.Output, " Created enumeration %s from %s\n", qn, enum.RemoteName) + return nil } var enumValueName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) @@ -73,6 +94,14 @@ func (o *odataEnumerations) ensure(ctx *ExecContext, moduleID model.ID, module, RemoteName: m.Name, }) } + if o.deferred { + if o.pending == nil { + o.pending = map[string]*model.Enumeration{} + } + o.pending[qn] = enum + o.byRemote[remoteType] = qn + return qn, "" + } if err := ctx.Backend.CreateEnumeration(enum); err != nil { return "", "creating enumeration " + qn + ": " + err.Error() } diff --git a/mdl/executor/cmd_flow_modify.go b/mdl/executor/cmd_flow_modify.go index c6ddc1ce1..5072d5536 100644 --- a/mdl/executor/cmd_flow_modify.go +++ b/mdl/executor/cmd_flow_modify.go @@ -1938,7 +1938,22 @@ func withAnnotations(st ast.MicroflowStatement, edit func(*ast.ActivityAnnotatio // before the stored statement after it. gapStart is the index of the first // stored statement after the run's predecessor; next is the index of the // matched statement after the run. +// +// An activity with a custom error handler is not anchored after: its handler +// rejoins the flow at a merge on that activity's outgoing flow, which the +// stored statements do not show (describe prints the merge only once a join +// names it), so a statement spliced after it lands between the activity and +// the merge, and the error path skips it. The next exec then cannot address +// the join it made (MDL-V1-REBUILD, ako/mxcli#2489). Before the stored +// statement after the gap is after the merge, where the source puts it. func insertAnchor(loc *storedLocator, stored []ast.MicroflowStatement, gapStart, next int) (ast.AlterFlowOpKind, mfmutator.Candidate, error) { + if gapStart > 0 && next < len(stored) && customErrorHandler(stored[gapStart-1]) { + c, err := loc.locate(stored[next]) + if err != nil { + return "", mfmutator.Candidate{}, err + } + return ast.AlterFlowInsertBefore, c, nil + } if gapStart > 0 { if c, err := loc.locate(stored[gapStart-1]); err == nil { if _, ok := c.Object.(*microflows.ActionActivity); ok { diff --git a/mdl/executor/cmd_import.go b/mdl/executor/cmd_import.go index 662be4aab..a7c5747eb 100644 --- a/mdl/executor/cmd_import.go +++ b/mdl/executor/cmd_import.go @@ -258,12 +258,13 @@ func resolveOneLink( } } else { info.JunctionTable = sysInfo.TableName - // Junction column names from conventions - parentParts := strings.SplitN(entityNames[string(getParentID(foundAssoc, foundCross))], ".", 2) + // The row's junction column names, else the convention; a + // self-association's two are numbered (ako/mxcli#1686). + parentEntity := entityNames[string(getParentID(foundAssoc, foundCross))] + parentParts := strings.SplitN(parentEntity, ".", 2) childParts := strings.SplitN(childEntity, ".", 2) if len(parentParts) == 2 && len(childParts) == 2 { - info.ParentColName = sqllib.JunctionColumnFromConvention(entityNames[string(getParentID(foundAssoc, foundCross))]) - info.ChildColName = sqllib.JunctionColumnFromConvention(childEntity) + info.ParentColName, info.ChildColName = sqllib.JunctionColumns(sysInfo, parentEntity, childEntity) } } } else { @@ -272,8 +273,7 @@ func resolveOneLink( info.FKColumnName = sqllib.AssocColumnNameFromConvention(assocQualName) } else { info.JunctionTable = sqllib.JunctionTableFromConvention(assocQualName) - info.ParentColName = sqllib.JunctionColumnFromConvention(getParentEntityName(foundAssoc, foundCross, entityNames)) - info.ChildColName = sqllib.JunctionColumnFromConvention(childEntity) + info.ParentColName, info.ChildColName = sqllib.JunctionColumns(nil, getParentEntityName(foundAssoc, foundCross, entityNames), childEntity) } } diff --git a/mdl/executor/cmd_odata.go b/mdl/executor/cmd_odata.go index 0df6db163..6fccdd30e 100644 --- a/mdl/executor/cmd_odata.go +++ b/mdl/executor/cmd_odata.go @@ -914,6 +914,24 @@ func execCreateExternalEntity(ctx *ExecContext, s *ast.CreateExternalEntityStmt) if s.AllowCreateChangeLocally != nil { existingEntity.CreateChangeLocally = *s.AllowCreateChangeLocally } + // The attributes as the contract maps them, where its contract is cached: + // one the entity did not hold before was stored as a local value, CE6612 + // (ako/mxcli#2497). A rewrite without a cached contract carries the + // stored mapping by name, as before. + if len(attrs) > 0 && existingEntity.RemoteEntitySet != "" { + if _, _, cerr := parseServiceContract(ctx, s.ServiceRef); cerr == nil { + set := existingEntity.RemoteEntitySet + if s.EntitySet != nil && *s.EntitySet != "" { + set = *s.EntitySet + } + res, err := resolveSingleExternalEntity(ctx, s, module.ID, set, existingEntity) + if err != nil { + return err + } + attrs = res.attrs + existingEntity.RemoteKeyParts = res.keyParts + } + } if len(attrs) > 0 { // The rebuilt attributes keep each stored attribute's identity and // what the statement cannot spell (the OData mapping; LocalizeDate when @@ -951,21 +969,19 @@ func execCreateExternalEntity(ctx *ExecContext, s *ast.CreateExternalEntityStmt) return mdlerrors.NewValidation("EntitySet property is required when creating an external entity") } + // Everything Mendix checks against the contract comes from it: each + // attribute's mapping, the key, the capabilities (ako/mxcli#2497). + res, err := resolveSingleExternalEntity(ctx, s, module.ID, *s.EntitySet, nil) + if err != nil { + return err + } newEntity := &domainmodel.Entity{ - Name: s.Name.Name, - Documentation: s.Documentation, - Persistable: false, // External entities are not persistable - Attributes: attrs, - Source: "Rest$ODataRemoteEntitySource", - RemoteServiceName: serviceRef, - RemoteEntitySet: *s.EntitySet, - RemoteEntityName: derefString(s.RemoteName), - Countable: derefBool(s.Countable), - Creatable: derefBool(s.Creatable), - Deletable: derefBool(s.Deletable), - Updatable: derefBool(s.Updatable), - CreateChangeLocally: derefBool(s.AllowCreateChangeLocally), + Name: s.Name.Name, + Documentation: s.Documentation, } + applyExternalEntityFields(newEntity, res.et, true, serviceRef, res.entitySet, res.keyParts, res.attrs) + // A local modelling choice, which the contract does not say. + newEntity.CreateChangeLocally = derefBool(s.AllowCreateChangeLocally) newEntity.ID = model.ID(types.GenerateID()) // The next grid slot whose box clears everything already in the module. // This used to be the single-row `100 + len(dm.Entities)*150` that CREATE diff --git a/mdl/executor/cmd_odata_mock_test.go b/mdl/executor/cmd_odata_mock_test.go index a8e2647fb..b7bf5dbae 100644 --- a/mdl/executor/cmd_odata_mock_test.go +++ b/mdl/executor/cmd_odata_mock_test.go @@ -246,6 +246,8 @@ func TestCreateExternalEntity_AcceptsExistingClient(t *testing.T) { BaseElement: model.BaseElement{ID: nextID("cos")}, ContainerID: mod.ID, Name: "ProductsClient", + // The attributes come from the contract (ako/mxcli#2497). + Metadata: singleSetContract("Demo", "Product", "Products"), } withContainer(h, svc.ContainerID, mod.ID) dm := &domainmodel.DomainModel{BaseElement: model.BaseElement{ID: nextID("dm")}, ContainerID: mod.ID} @@ -289,6 +291,7 @@ func TestCreateExternalEntity_AllowCreateChangeLocally_Issue534(t *testing.T) { BaseElement: model.BaseElement{ID: nextID("cos")}, ContainerID: mod.ID, Name: "TripPinClient", + Metadata: singleSetContract("Trippin", "Person", "People"), } withContainer(h, svc.ContainerID, mod.ID) dm := &domainmodel.DomainModel{BaseElement: model.BaseElement{ID: nextID("dm")}, ContainerID: mod.ID} @@ -738,3 +741,18 @@ func TestCreateOrModifyExternalEntity_KeepsAttributeIdentityAndMapping(t *testin t.Errorf("new attribute Added = %+v", b) } } + +// singleSetContract is a $metadata with one entity type keyed on Id and the +// entity set that exposes it. +func singleSetContract(ns, typ, set string) string { + return ` + + + + + + + + +` +} diff --git a/mdl/executor/cmd_odata_single_contract.go b/mdl/executor/cmd_odata_single_contract.go new file mode 100644 index 000000000..f90e4b265 --- /dev/null +++ b/mdl/executor/cmd_odata_single_contract.go @@ -0,0 +1,199 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "sort" + "strings" + + "github.com/mendixlabs/mxcli/mdl/ast" + mdlerrors "github.com/mendixlabs/mxcli/mdl/errors" + "github.com/mendixlabs/mxcli/mdl/types" + "github.com/mendixlabs/mxcli/model" + "github.com/mendixlabs/mxcli/sdk/domainmodel" +) + +// singleEntityContract is what the contract makes of one hand-written +// `create external entity`: the entity type and set it maps, and the stated +// attributes as the contract maps them. +type singleEntityContract struct { + et *types.EdmEntityType + entitySet *types.EdmEntitySet + attrs []*domainmodel.Attribute + keyParts []*domainmodel.RemoteKeyPart +} + +// resolveSingleExternalEntity maps a hand-written external entity's attributes +// onto the service's cached contract (ako/mxcli#2497). The statement used to +// store each attribute as a local value with no key, and mx check 11.12.6 +// reported, on a contract the bulk import builds at 0 errors: +// +// CE6010 "Key cannot be empty" +// CE6612 "Attribute 'X' of external entity 'E' is not supported." — every attribute +// CE6630 "'E' is marked supports $top=True in the OData service, but False in the app." (and $skip) +// +// Each stated attribute is now the attribute the bulk import makes of the +// property of that name — mapped value, remote type, capabilities — so the +// two statements cannot disagree. What cannot build is refused, with nothing +// written: a name the contract does not have, a type it does not publish, a +// key left out, and a capability the contract contradicts. +// +// stored is the entity a rewrite replaces, nil on create. Its attributes are +// matched by their mapping as well as by name: an older import named a +// property differently (a key `_Id` where today's import says `DeviceId`), and +// describe prints the stored name. +func resolveSingleExternalEntity(ctx *ExecContext, s *ast.CreateExternalEntityStmt, moduleID model.ID, entitySetName string, stored *domainmodel.Entity) (*singleEntityContract, error) { + qn := s.Name.String() + doc, _, err := parseServiceContract(ctx, s.ServiceRef) + if err != nil { + return nil, err + } + var entitySet *types.EdmEntitySet + var setNames []string + for _, es := range doc.EntitySets { + setNames = append(setNames, es.Name) + if es.Name == entitySetName { + entitySet = es + } + } + if entitySet == nil { + return nil, mdlerrors.NewValidation(fmt.Sprintf( + "external entity %s: %s has no entity set %q; its entity sets are %s", + qn, s.ServiceRef, entitySetName, strings.Join(setNames, ", "))) + } + typeByQualified := make(map[string]*types.EdmEntityType) + for _, schema := range doc.Schemas { + for _, et := range schema.EntityTypes { + typeByQualified[schema.Namespace+"."+et.Name] = et + } + } + et := typeByQualified[entitySet.EntityType] + if et == nil { + et = doc.FindEntityType(entitySet.EntityType) + } + if et == nil { + return nil, mdlerrors.NewValidation(fmt.Sprintf( + "external entity %s: the contract does not declare %s, the type of entity set %s", qn, entitySet.EntityType, entitySetName)) + } + if s.RemoteName != nil && *s.RemoteName != "" && *s.RemoteName != et.Name && *s.RemoteName != entitySet.EntityType { + return nil, mdlerrors.NewValidation(fmt.Sprintf( + "external entity %s: RemoteName %q is not the type of entity set %s, which is %s", + qn, *s.RemoteName, entitySetName, et.Name)) + } + + enums := &odataEnumerations{byRemote: map[string]string{}, deferred: true} + parts := contractEntityAttributes(ctx, doc, et, typeByQualified, entitySet, true, + s.Name.Name, moduleID, s.Name.Module, s.ServiceRef.String(), enums) + byName := map[string]*domainmodel.Attribute{} + byRemote := map[string]*domainmodel.Attribute{} + var available []string + for _, a := range parts.attrs { + byName[a.Name] = a + byRemote[a.RemoteName] = a + available = append(available, a.Name+": "+getAttributeTypeName(a.Type)) + } + sort.Strings(available) + + var problems []string + var kept []*domainmodel.Attribute + stated := map[string]bool{} + // No attribute list: every property the contract has, as the bulk + // import makes the entity. + if len(s.Attributes) == 0 { + kept = parts.attrs + for _, a := range parts.attrs { + stated[a.RemoteName] = true + } + } + for _, a := range s.Attributes { + c := byName[a.Name] + if c == nil && stored != nil { + for _, old := range stored.Attributes { + if old != nil && old.Name == a.Name && old.RemoteName != "" && byRemote[old.RemoteName] != nil { + renamed := *byRemote[old.RemoteName] + renamed.Name = a.Name + c = &renamed + } + } + } + if c != nil { + stated[c.RemoteName] = true + } + if c == nil { + why := "is not a property of " + et.Name + for _, d := range parts.dropped { + if strings.Contains(d, "."+a.Name+" ") { + why = "cannot be imported: " + d + } + } + problems = append(problems, fmt.Sprintf("%s %s", a.Name, why)) + continue + } + declared := convertDataType(a.Type) + want := getAttributeTypeName(c.Type) + if declared == nil || declared.GetTypeName() != c.Type.GetTypeName() || + (isEnumType(declared) && getAttributeTypeName(declared) != want) { + problems = append(problems, fmt.Sprintf("%s is declared %s, but the service publishes it as %s, which is %s", + a.Name, getAttributeTypeName(declared), c.RemoteType, want)) + continue + } + kept = append(kept, c) + } + // stated is keyed on the remote property, so a key kept under another + // local name counts. + for _, k := range parts.keyParts { + if !stated[k.RemoteName] { + problems = append(problems, fmt.Sprintf("%s is the key (%s) and must be listed: an external entity without it is CE6010 \"Key cannot be empty\"", + k.Name, k.RemoteName)) + } + } + // The capabilities are the contract's; a stated one that differs is CE6630. + for _, c := range []struct { + name string + stated *bool + want bool + }{ + {"Countable", s.Countable, entitySet.Countable == nil || *entitySet.Countable}, + {"Creatable", s.Creatable, entitySet.Insertable != nil && *entitySet.Insertable}, + {"Deletable", s.Deletable, entitySet.Deletable != nil && *entitySet.Deletable}, + } { + if c.stated != nil && *c.stated != c.want { + problems = append(problems, fmt.Sprintf("%s: %v, but the service says %v for entity set %s, which mx check reports as CE6630; leave it out to follow the service", + c.name, *c.stated, c.want, entitySetName)) + } + } + if len(problems) > 0 { + return nil, mdlerrors.NewValidation(fmt.Sprintf( + "external entity %s: its attributes come from %s's contract, and this statement does not match it:\n - %s\n"+ + "Nothing was written. The contract's attributes for %s are: %s. "+ + "`create or modify external entities from %s entities (%s)` imports the entity with all of them.", + qn, s.ServiceRef, strings.Join(problems, "\n - "), et.Name, strings.Join(available, ", "), s.ServiceRef, et.Name)) + } + for _, a := range kept { + if e, ok := a.Type.(*domainmodel.EnumerationAttributeType); ok { + if err := enums.createPending(ctx, e.EnumerationRef); err != nil { + return nil, mdlerrors.NewBackend("create enumeration", err) + } + } + } + // A key part is named as the attribute it keys (EntityKeyPartName). + localName := map[string]string{} + for _, a := range kept { + localName[a.RemoteName] = a.Name + } + var keyParts []*domainmodel.RemoteKeyPart + for _, k := range parts.keyParts { + kp := *k + if n := localName[k.RemoteName]; n != "" { + kp.Name = n + } + keyParts = append(keyParts, &kp) + } + return &singleEntityContract{et: et, entitySet: entitySet, attrs: kept, keyParts: keyParts}, nil +} + +func isEnumType(t domainmodel.AttributeType) bool { + _, ok := t.(*domainmodel.EnumerationAttributeType) + return ok +} diff --git a/mdl/executor/cmd_published_rest.go b/mdl/executor/cmd_published_rest.go index 253833963..005702d6b 100644 --- a/mdl/executor/cmd_published_rest.go +++ b/mdl/executor/cmd_published_rest.go @@ -557,6 +557,12 @@ func execCreatePublishedRestService(ctx *ExecContext, s *ast.CreatePublishedRest return mdlerrors.NewAlreadyExistsMsg("published rest service", s.Name.Module+"."+s.Name.Name, fmt.Sprintf("published rest service already exists: %s.%s (use create or modify to update)", s.Name.Module, s.Name.Name)) } + // The statement is the whole service: say which stored operations it + // removes, which exec did not (MDL-REST06, ako/mxcli#2449). + if dropped := droppedPublishedRestOperations(existing, s); len(dropped) > 0 { + fmt.Fprintf(ctx.progress(), "Warning [%s]: %s. %s\n", publishedRestOperationDropRule, + publishedRestDropMessage(s.Name.String(), dropped), publishedRestDropSuggestion) + } module, err := findModule(ctx, s.Name.Module) if err != nil { @@ -925,6 +931,50 @@ func execAlterPublishedRestService(ctx *ExecContext, s *ast.AlterPublishedRestSe } svc.Resources = append(svc.Resources, resource) + case *ast.PublishedRestAddOperationsAction: + // One operation of a stored resource; the resource's other + // operations are written back as stored (ako/mxcli#2449). + res := publishedRestResourceNamed(svc, a.Resource) + if res == nil { + return mdlerrors.NewNotFoundMsg("resource", a.Resource, fmt.Sprintf( + "resource %s not found on %s.%s: `add operation in resource` adds to a stored resource; a new one is `add resource %s { … }`", + mdlQuoted(a.Resource), s.Name.Module, s.Name.Name, mdlQuoted(a.Resource))) + } + added, err := astResourceDefToModel(&ast.PublishedRestResourceDef{Name: a.Resource, Operations: a.Operations}) + if err != nil { + return err + } + for _, op := range added.Operations { + key := publishedRestOperationKey(a.Resource, op.HTTPMethod, op.Path) + for _, stored := range res.Operations { + if publishedRestOperationKey(a.Resource, stored.HTTPMethod, stored.Path) == key { + return mdlerrors.NewAlreadyExistsMsg("operation", key, fmt.Sprintf( + "operation %s already exists on %s.%s: `add operation` adds a new one; to change it, "+ + "`drop operation %s in resource %s` first and add it back", key, s.Name.Module, s.Name.Name, + publishedRestOperationSpelling(op.HTTPMethod, op.Path), mdlQuoted(a.Resource))) + } + } + res.Operations = append(res.Operations, op) + } + + case *ast.PublishedRestDropOperationAction: + res := publishedRestResourceNamed(svc, a.Resource) + if res == nil { + return mdlerrors.NewNotFoundMsg("resource", a.Resource, fmt.Sprintf("resource '%s' not found on %s.%s", a.Resource, s.Name.Module, s.Name.Name)) + } + key := publishedRestOperationKey(a.Resource, a.HTTPMethod, a.Path) + idx := -1 + for i, op := range res.Operations { + if publishedRestOperationKey(a.Resource, op.HTTPMethod, op.Path) == key { + idx = i + break + } + } + if idx == -1 { + return mdlerrors.NewNotFoundMsg("operation", key, fmt.Sprintf("operation %s not found on %s.%s", key, s.Name.Module, s.Name.Name)) + } + res.Operations = append(res.Operations[:idx], res.Operations[idx+1:]...) + case *ast.PublishedRestDropResourceAction: idx := -1 for i, existing := range svc.Resources { @@ -955,3 +1005,23 @@ func execAlterPublishedRestService(ctx *ExecContext, s *ast.AlterPublishedRestSe } // Executor wrappers for unmigrated callers. + +// publishedRestResourceNamed is the service's resource of that name, or nil. +func publishedRestResourceNamed(svc *model.PublishedRestService, name string) *model.PublishedRestResource { + for _, r := range svc.Resources { + if r.Name == name { + return r + } + } + return nil +} + +// publishedRestOperationSpelling is an operation as MDL writes it: method and, +// when there is one, the quoted path. +func publishedRestOperationSpelling(method, path string) string { + m := strings.ToLower(method) + if p := strings.Trim(path, "/"); p != "" { + return m + " " + mdlQuoted(p) + } + return m +} diff --git a/mdl/executor/create_external_entity_contract_2497_test.go b/mdl/executor/create_external_entity_contract_2497_test.go new file mode 100644 index 000000000..6567cc108 --- /dev/null +++ b/mdl/executor/create_external_entity_contract_2497_test.go @@ -0,0 +1,208 @@ +// 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/mdl/types" + "github.com/mendixlabs/mxcli/mdl/visitor" + "github.com/mendixlabs/mxcli/model" + "github.com/mendixlabs/mxcli/sdk/domainmodel" +) + +// ako/mxcli#2497: the hand-written `create external entity … (attrs)` stored +// every attribute as a DomainModels$StoredValue, no key, and TopSupported / +// SkipSupported false. mx check 11.12.6 on a contract the bulk import builds at +// 0 errors: CE6010 "Key cannot be empty", CE6612 on every attribute, and two +// CE6630 ($top, $skip). The attributes now come from the contract, as the bulk +// import makes them. +const salesContract2497 = ` + + + + + + + + + + + + + +` + +type singleImport2497 struct { + created map[string]*domainmodel.Entity + updated map[string]*domainmodel.Entity + enums []*model.Enumeration +} + +func runSingle2497(t *testing.T, src string, existing ...*domainmodel.Entity) (singleImport2497, error) { + t.Helper() + mod := mkModule("Shop") + svc := &model.ConsumedODataService{BaseElement: model.BaseElement{ID: nextID("cos")}, ContainerID: mod.ID, + Name: "Sales", MetadataUrl: "http://localhost/$metadata", ODataVersion: "4.0", Metadata: salesContract2497} + h := mkHierarchy(mod) + withContainer(h, svc.ContainerID, mod.ID) + dm := &domainmodel.DomainModel{Entities: existing} + dm.ID = nextID("dm") + r := singleImport2497{created: map[string]*domainmodel.Entity{}, updated: map[string]*domainmodel.Entity{}} + 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 + }, + GetDomainModelFunc: func(model.ID) (*domainmodel.DomainModel, error) { return dm, nil }, + ListEnumerationsFunc: func() ([]*model.Enumeration, error) { return r.enums, nil }, + CreateEnumerationFunc: func(e *model.Enumeration) error { + e.ContainerID = mod.ID + r.enums = append(r.enums, e) + return nil + }, + CreateEntityFunc: func(_ model.ID, e *domainmodel.Entity) error { r.created[e.Name] = e; return nil }, + UpdateEntityFunc: func(_ model.ID, e *domainmodel.Entity) error { r.updated[e.Name] = e; return nil }, + ProjectVersionFunc: func() *types.ProjectVersion { + return &types.ProjectVersion{MajorVersion: 11, MinorVersion: 12, ProductVersion: "11.12.6"} + }, + } + ctx, _ := newMockCtx(t, withBackend(mb), withHierarchy(h)) + prog, errs := visitor.Build(src) + if len(errs) > 0 { + t.Fatalf("parse: %v", errs) + } + return r, execCreateExternalEntity(ctx, prog.Statements[0].(*ast.CreateExternalEntityStmt)) +} + +const singleOrder2497 = `create external entity Shop.Order from consumed odata service Shop.Sales (EntitySet: 'Orders') ( + OrderId: Long, + Title: String(100), + Status: Enumeration(Shop.OrderStatus) +);` + +func TestSingleExternalEntityMapsTheContract_2497(t *testing.T) { + r, err := runSingle2497(t, singleOrder2497) + if err != nil { + t.Fatal(err) + } + e := r.created["Order"] + if e == nil { + t.Fatal("not created") + } + // CE6010: the key. + if len(e.RemoteKeyParts) != 1 || e.RemoteKeyParts[0].RemoteName != "Id" || e.RemoteKeyParts[0].Name != "OrderId" { + t.Errorf("key = %+v", e.RemoteKeyParts) + } + // CE6612: each attribute mapped to its property. + want := map[string]string{"OrderId": "Id/Edm.Int64", "Title": "Title/Edm.String", "Status": "Status/Vendor.Sales.OrderStatus"} + for _, a := range e.Attributes { + if got := a.RemoteName + "/" + a.RemoteType; got != want[a.Name] { + t.Errorf("%s mapped to %q, want %q", a.Name, got, want[a.Name]) + } + delete(want, a.Name) + } + if len(want) != 0 { + t.Errorf("attributes missing: %v", want) + } + // CE6630: the contract's capabilities. + if !e.TopSupported || !e.SkipSupported || e.RemoteEntityName != "Order" || e.Source != "Rest$ODataRemoteEntitySource" { + t.Errorf("entity = top %v skip %v remote %q source %q", e.TopSupported, e.SkipSupported, e.RemoteEntityName, e.Source) + } + // The enum attribute's enumeration is generated, as the bulk import does it. + if len(r.enums) != 1 || r.enums[0].RemoteName != "Vendor.Sales.OrderStatus" { + t.Errorf("enumerations = %+v", r.enums) + } +} + +// A subset of the properties is kept as stated; a property the statement does +// not name is not imported, and its enumeration is not generated. +func TestSingleExternalEntityKeepsTheStatedSubset_2497(t *testing.T) { + r, err := runSingle2497(t, `create external entity Shop.Order from consumed odata service Shop.Sales (EntitySet: 'Orders') ( + OrderId: Long +);`) + if err != nil { + t.Fatal(err) + } + if e := r.created["Order"]; e == nil || len(e.Attributes) != 1 || e.Attributes[0].Name != "OrderId" { + t.Fatalf("created = %+v", e) + } + if len(r.enums) != 0 { + t.Errorf("an enumeration was generated for a property not imported: %+v", r.enums) + } +} + +func TestSingleExternalEntityRefusesWhatCannotBuild_2497(t *testing.T) { + for name, c := range map[string]struct{ src, want string }{ + "not in the contract": {`create external entity Shop.Order from consumed odata service Shop.Sales (EntitySet: 'Orders') ( + OrderId: Long, Note: String(50));`, "Note"}, + "type contradicts the contract": {`create external entity Shop.Order from consumed odata service Shop.Sales (EntitySet: 'Orders') ( + OrderId: Long, Title: Integer);`, "String(100)"}, + "key left out": {`create external entity Shop.Order from consumed odata service Shop.Sales (EntitySet: 'Orders') ( + Title: String(100));`, "OrderId"}, + "capability contradicts the contract": {`create external entity Shop.Order from consumed odata service Shop.Sales (EntitySet: 'Orders', Creatable: true) ( + OrderId: Long);`, "CE6630"}, + "unknown entity set": {`create external entity Shop.Order from consumed odata service Shop.Sales (EntitySet: 'Ordrs') ( + OrderId: Long);`, "Orders"}, + "plain enumeration": {`create external entity Shop.Order from consumed odata service Shop.Sales (EntitySet: 'Orders') ( + OrderId: Long, Status: Enumeration(Shop.LocalStatus));`, "Shop.OrderStatus"}, + } { + t.Run(name, func(t *testing.T) { + r, err := runSingle2497(t, c.src) + if err == nil { + t.Fatalf("accepted; created %+v", r.created["Order"]) + } + if !strings.Contains(err.Error(), c.want) { + t.Errorf("error does not mention %q:\n%s", c.want, err) + } + if len(r.created) != 0 { + t.Error("written despite the refusal") + } + }) + } +} + +// With no attribute list the entity gets every property the contract has. +func TestSingleExternalEntityWithoutAttributesTakesTheContract_2497(t *testing.T) { + r, err := runSingle2497(t, `create external entity Shop.Order from consumed odata service Shop.Sales (EntitySet: 'Orders');`) + if err != nil { + t.Fatal(err) + } + if e := r.created["Order"]; e == nil || len(e.Attributes) != 3 || len(e.RemoteKeyParts) != 1 { + t.Fatalf("created = %+v", e) + } +} + +// A stored entity whose attribute maps a property under another local name — +// an older import named the key `_Id`, today's names it `OrderId` — is +// rewritten by its describe output: the stated name is matched by the stored +// mapping, and keeps its name (the TestApp round trip, Odata.Devices). +func TestSingleExternalEntityRewriteMatchesStoredMapping_2497(t *testing.T) { + stored := &domainmodel.Entity{ + BaseElement: model.BaseElement{ID: nextID("ent")}, Name: "Order", Source: "Rest$ODataRemoteEntitySource", + RemoteServiceName: "Shop.Sales", RemoteEntitySet: "Orders", RemoteEntityName: "Order", + Attributes: []*domainmodel.Attribute{ + {Name: "_Id", RemoteName: "Id", RemoteType: "Edm.Int64", Type: &domainmodel.LongAttributeType{}}, + {Name: "Title", RemoteName: "Title", RemoteType: "Edm.String", Type: &domainmodel.StringAttributeType{Length: 100}}, + }, + RemoteKeyParts: []*domainmodel.RemoteKeyPart{{Name: "_Id", RemoteName: "Id", RemoteType: "Edm.Int64"}}, + } + r, err := runSingle2497(t, `create or modify external entity Shop.Order from consumed odata service Shop.Sales (EntitySet: 'Orders', RemoteName: 'Order') ( + _Id: Long, + Title: String(100) +);`, stored) + if err != nil { + t.Fatal(err) + } + e := r.updated["Order"] + if e == nil || len(e.Attributes) != 2 || e.Attributes[0].Name != "_Id" || e.Attributes[0].RemoteName != "Id" { + t.Fatalf("updated = %+v", e) + } + if len(e.RemoteKeyParts) != 1 || e.RemoteKeyParts[0].Name != "_Id" { + t.Errorf("key = %+v, want the key part named as the stored attribute", e.RemoteKeyParts) + } +} diff --git a/mdl/executor/documentation_preserved_test.go b/mdl/executor/documentation_preserved_test.go index 120821e45..dd18f8529 100644 --- a/mdl/executor/documentation_preserved_test.go +++ b/mdl/executor/documentation_preserved_test.go @@ -225,7 +225,9 @@ func docPreserveCases() []docPreserveCase { { name: "external entity", storedOnly: true, - create: "create odata client MyFirstModule.DocExtOdc (\n MetadataUrl: 'http://127.0.0.1:9/nope/$metadata'\n);\n" + doc + + // The entity's attributes come from the client's cached contract + // (ako/mxcli#2497), so the client has one. + create: "create odata client MyFirstModule.DocExtOdc (\n MetadataUrl: '" + thingsContractURL() + "'\n);\n" + doc + "create external entity MyFirstModule.DocExt\nfrom odata client MyFirstModule.DocExtOdc\n(\n EntitySet: 'Things',\n Countable: Yes\n);", rewrite: "create or modify external entity MyFirstModule.DocExt\nfrom odata client MyFirstModule.DocExtOdc\n(\n EntitySet: 'Things',\n Countable: No\n);", }, @@ -427,3 +429,27 @@ func TestDocumentation_EmptyCommentClears(t *testing.T) { t.Errorf("an explicitly empty /** */ did not clear the documentation:\n%s", out) } } + +// thingsContractURL writes a $metadata with one entity set, Things, to a +// temporary file and returns its file:// URL. +func thingsContractURL() string { + dir, err := os.MkdirTemp("", "doc-ext-contract") + if err != nil { + panic(err) + } + path := filepath.Join(dir, "metadata.xml") + contract := ` + + + + + + + + +` + if err := os.WriteFile(path, []byte(contract), 0o644); err != nil { + panic(err) + } + return "file://" + path +} diff --git a/mdl/executor/flow_splice_after_handler_2489_pedapp_test.go b/mdl/executor/flow_splice_after_handler_2489_pedapp_test.go new file mode 100644 index 000000000..316e57ef3 --- /dev/null +++ b/mdl/executor/flow_splice_after_handler_2489_pedapp_test.go @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" +) + +// ako/mxcli#2489: a statement appended after an activity with a custom error +// handler (`on error without rollback begin … end error;`) was spliced onto the +// activity's normal outgoing flow — between the activity and the merge the +// handler rejoins. On the error path the flow jumped past it, and the next exec +// of the unchanged script was refused: `the stored statement "Join" has no +// activity to address … (MDL-V1-REBUILD)`. The new statement belongs after the +// merge, where the source puts it. + +const handler2489Setup = `mdl 1; +create microflow MyFirstModule.SUB_Ensure2489 () returns Boolean as $R +begin + return true; +end; +create microflow MyFirstModule.SUB_Startup2489 () +begin + log info node 'Probe' 'start'; +end;` + +const handler2489Before = `mdl 1; +create or modify microflow MyFirstModule.ASU2489 () returns Boolean as $Ok +begin + $Ready = call microflow MyFirstModule.SUB_Ensure2489() on error without rollback begin + log warning node 'Probe' 'ensure failed'; + end error; + return true; +end;` + +var handler2489After = strings.Replace(handler2489Before, " end error;\n return true;", + " end error;\n call microflow MyFirstModule.SUB_Startup2489();\n return true;", 1) + +func TestSpliceAppendsAfterTheHandlersRejoin_2489(t *testing.T) { + exec, out, _ := openPedAppCopy(t) + for _, src := range []string{handler2489Setup, handler2489Before} { + if err := agreeExec(t, exec, src); err != nil { + t.Fatalf("setup: %v\n%s", err, out.String()) + } + } + out.Reset() + if err := agreeExec(t, exec, handler2489After); err != nil { + t.Fatalf("append: %v\n%s", err, out.String()) + } + out.Reset() + if err := afRun(t, exec, "describe microflow MyFirstModule.ASU2489;"); err != nil { + t.Fatal(err) + } + desc := out.String() + call := strings.Index(desc, "call microflow MyFirstModule.SUB_Startup2489") + merge := strings.Index(desc, "merge ") + if call < 0 { + t.Fatalf("appended call missing:\n%s", desc) + } + // Either no explicit merge (the rejoin is implicit, at the call) or the + // call after it: never between the handler's join and its merge. + if merge >= 0 && call < merge { + t.Errorf("the appended call sits before the rejoin merge, so the error path skips it:\n%s", desc) + } + + // The unchanged script re-runs: nothing refused. + out.Reset() + if err := agreeExec(t, exec, handler2489After); err != nil { + t.Fatalf("re-run of the unchanged script refused: %v\n%s", err, out.String()) + } +} diff --git a/mdl/executor/validate.go b/mdl/executor/validate.go index 1e03ea462..92941c59f 100644 --- a/mdl/executor/validate.go +++ b/mdl/executor/validate.go @@ -1189,6 +1189,16 @@ func validateWithContext(ctx *ExecContext, stmt ast.Statement, sc *scriptContext case *ast.CreateMessageDefinitionStmt: return messageDefinitionMemberErrors(ctx, sc, s.Name.String(), s.Definition) case *ast.AlterPublishedRestServiceStmt: + // What exec refuses about the stored service's resources, said here + // (ako/mxcli#2449). A service the script creates is not stored yet, + // so the lookup finds nothing and there is nothing to judge. + if ctx.Connected() { + if stored, err := findPublishedRestService(ctx, s.Name.Module, s.Name.Name); err == nil && stored != nil { + if probs := publishedRestAlterResourceProblems(stored, s); len(probs) > 0 { + return mdlerrors.NewValidationf("alter published rest service %s:\n - %s", s.Name, strings.Join(probs, "\n - ")) + } + } + } for _, a := range s.Actions { if set, ok := a.(*ast.PublishedRestSetAction); ok { if err := validatePublishedRestAuthMicroflow(ctx, set.Authentication, sc); err != nil { diff --git a/mdl/executor/validate_grant_refs.go b/mdl/executor/validate_grant_refs.go index 00d6ba3b6..474c72ef2 100644 --- a/mdl/executor/validate_grant_refs.go +++ b/mdl/executor/validate_grant_refs.go @@ -636,6 +636,12 @@ func (g *grantResolver) xpathProblem(qn ast.QualifiedName, xpath string) string stored := accessRuleXPathConstraint(g.ctx, xpath, name) var bad []string for _, b := range unresolvableXPathStepsWith(g.ctx, g.xpath.model, stored, name, g.xpath.resolve) { + // `Assoc.Attr`: one name to the walk, an association and an + // attribute with the entity step missing (ako/mxcli#2491). + if hint := missingEntityStepHint(g.xpath.model, g.xpath.resolve, name, b.name); hint != "" { + return fmt.Sprintf("the access rule's constraint names %q, which is %s; as written mxbuild reports "+ + "CE1613 \"The selected … no longer exists\" at the access rule", b.name, hint) + } bad = append(bad, fmt.Sprintf("%s %q", b.kind, b.name)) } if len(bad) == 0 { diff --git a/mdl/executor/validate_json_structure_names.go b/mdl/executor/validate_json_structure_names.go index 083b58a6b..e61d54068 100644 --- a/mdl/executor/validate_json_structure_names.go +++ b/mdl/executor/validate_json_structure_names.go @@ -35,6 +35,9 @@ func ValidateJsonStructureNames(prog *ast.Program) []linter.Violation { if !ok || (len(s.CustomNameMap) == 0 && len(s.CustomItemNameMap) == 0) { continue } + // A name that is itself invalid (CE9524) is judged whether or not its key + // is found: it needs no snippet. + out = append(out, invalidCustomNameViolations(s)...) keys, arrayKeys, rootIsArray, err := types.SnippetKeys(s.JsonSnippet) if err != nil { // An unparseable snippet is a different, louder failure reported by @@ -119,3 +122,57 @@ func sortedSet(m map[string]bool) []string { sort.Strings(out) return out } + +// validCustomName reports whether Mendix accepts name as a JSON element's custom +// name. Measured on MxBuild 11.16.1 over 90 names (MDL-JSON03): an ASCII letter or +// underscore, then ASCII letters, digits or underscores, a lone underscore is +// refused, and so is every platform-reserved word in any case (Owner, ChangedDate, +// Type, Id, GUID, Object, class, null, …). `String`, `System`, `Name`, `Value`, +// `Entity`, `Date`, `List` and `User` are accepted. +func validCustomName(name string) bool { + if name == "" || name == "_" { + return false + } + for i := 0; i < len(name); i++ { + c := name[i] + letter := (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' + digit := c >= '0' && c <= '9' + if !letter && !(digit && i > 0) { + return false + } + } + return !types.IsPlatformReserved(name) +} + +// invalidCustomNameViolations reports (MDL-JSON03) each CUSTOM NAME MAP name, and +// each `item of` name, that MxBuild rejects as CE9524. The default name of a member +// whose JSON key is invalid is sanitised, so only a name the author wrote counts. +func invalidCustomNameViolations(s *ast.CreateJsonStructureStmt) []linter.Violation { + var out []linter.Violation + check := func(prefix string, m map[string]string) { + for _, k := range sortedKeysOf(m) { + name := m[k] + if validCustomName(name) { + continue + } + out = append(out, linter.Violation{ + RuleID: "MDL-JSON03", + Severity: linter.SeverityError, + Message: fmt.Sprintf("json structure %s: `%s'%s' as '%s'` is not a name Mendix accepts — "+ + "mxbuild reports CE9524 \"JSON element … has an invalid custom name '%s'\"", + s.Name.String(), prefix, k, name, name), + Location: linter.Location{ + Module: s.Name.Module, + DocumentType: "json structure", + DocumentName: s.Name.Name, + }, + Suggestion: "Start with an ASCII letter or underscore and continue with ASCII letters, digits or " + + "underscores, and avoid platform-reserved words (Owner, Type, Id, class, …). A member whose " + + "JSON key is invalid needs no custom name: its default name is sanitised.", + }) + } + } + check("", s.CustomNameMap) + check("item of ", s.CustomItemNameMap) + return out +} diff --git a/mdl/executor/validate_json_structure_names_test.go b/mdl/executor/validate_json_structure_names_test.go index 0eb0884fb..5a99997af 100644 --- a/mdl/executor/validate_json_structure_names_test.go +++ b/mdl/executor/validate_json_structure_names_test.go @@ -152,3 +152,68 @@ func TestDescribeCollectsARootArrayItemName(t *testing.T) { t.Errorf("got %v, want Root -> Entry", got) } } + +// MDL-JSON03 (CE9524). A custom name must start with an ASCII letter or an +// underscore and continue with ASCII letters, digits or underscores, and must not be +// a platform-reserved word. Measured on MxBuild 11.16.1 over 90 names; `check` and +// `exec` accepted every rejected one and the build reported +// +// [CE9524] JSON element '(Object)/name' has an invalid custom name '1bad'. +// +// Rejected: '1a', 'a b', 'a-b', 'a.b', 'a$', ”, '_' (alone), 'Größe', 'naïve', 'Ünï', +// and every word in types.PlatformReservedWords or SystemAttributeNames in any case +// (Owner, OWNER, ChangedDate, Type, Id, GUID, Object, class, Int, Null, true, …). +// Accepted: 'Good_Name1', '_x', 'x1', 'String', 'System', 'Name', 'Value', 'Entity', +// 'Date', 'List', 'User'. The same check applies to an `item of` name and to the root +// item. A member whose JSON KEY is invalid needs no entry: the default name is +// sanitised (`$type` and `research%3Aread` build clean). +func TestInvalidCustomNames(t *testing.T) { + bad := []string{"1a", "a b", "a-b", "a.b", "a$", "", "_", "Größe", "naïve", "Ünï", + "Owner", "OWNER", "owner", "ChangedDate", "createdDate", "Type", "Id", "GUID", + "CurrentUser", "Object", "class", "Class", "Int", "Null", "true", "Public", "this"} + good := []string{"Good_Name1", "_x", "x1", "X_y", "String", "System", "Name", "Value", "Entity", "Date", "List", "User"} + + for _, n := range bad { + src := `create json structure M.JSON_A + snippet '{"name": "x"}' + custom name map ('name' as '` + n + `');` + got := jsonNameViolations(t, src) + if len(got) != 1 || got[0].RuleID != "MDL-JSON03" || !strings.Contains(got[0].Message, "CE9524") { + t.Errorf("name %q: got %v, want one MDL-JSON03 naming CE9524", n, got) + } + } + for _, n := range good { + src := `create json structure M.JSON_A + snippet '{"name": "x"}' + custom name map ('name' as '` + n + `');` + if got := jsonNameViolations(t, src); len(got) != 0 { + t.Errorf("name %q builds clean, got %v", n, got) + } + } +} + +// An `item of` name, and the root item, are judged the same way. +func TestInvalidItemNames(t *testing.T) { + got := jsonNameViolations(t, `create json structure M.JSON_A + snippet '{"tags": ["a"]}' + custom name map (item of 'tags' as 'bad name');`) + if len(got) != 1 || got[0].RuleID != "MDL-JSON03" { + t.Errorf("item name: got %v, want one MDL-JSON03", got) + } + got = jsonNameViolations(t, `create json structure M.JSON_B + snippet '[{"id": 1}]' + custom name map (item of 'Root' as 'class');`) + if len(got) != 1 || got[0].RuleID != "MDL-JSON03" { + t.Errorf("root item name: got %v, want one MDL-JSON03", got) + } +} + +// The member whose JSON key is invalid needs no custom name: the generated name is +// sanitised, which is what the earlier fixes for $type, owner and %3A did. +func TestInvalidKeysWithoutACustomNameAreNotReported(t *testing.T) { + got := jsonNameViolations(t, `create json structure M.JSON_A + snippet '{"$type": "a", "owner": "b", "research%3Aread": "c"}';`) + if len(got) != 0 { + t.Fatalf("got %v, want none", got) + } +} diff --git a/mdl/executor/validate_microflow.go b/mdl/executor/validate_microflow.go index 3563b86a1..023c39adc 100644 --- a/mdl/executor/validate_microflow.go +++ b/mdl/executor/validate_microflow.go @@ -850,11 +850,25 @@ func (h xpathAssocEmptyHit) test() string { return h.Assoc + " " + h.Op + " empt // fix is the spelling Mendix XPath accepts: a path to the associated object // tests its presence, `not(…)` around it its absence. +// +// Without the project the name cannot be told apart from `Assoc.Attr`, an +// association and an attribute of its other end with the entity step +// missing; that reading is the one an agent hit (ako/mxcli#2491), and the +// absence fix kept the dotted name, so both are offered. `check -p` says +// which it is. func (h xpathAssocEmptyHit) fix() string { + var fix string if h.Op == "!=" { - return fmt.Sprintf("Test for the presence of the associated object with a path: `[%s/]`.", h.Assoc) + fix = fmt.Sprintf("Test for the presence of the associated object with a path: `[%s/]`.", h.Assoc) + } else { + fix = fmt.Sprintf("Test for the absence of the associated object with negation: `[not(%s/)]`.", h.Assoc) + } + if dot := strings.LastIndex(h.Assoc, "."); dot > 0 { + assoc, attr := h.Assoc[:dot], h.Assoc[dot+1:] + fix += fmt.Sprintf(" If `%s` is an association and `%s` an attribute of the entity it leads to, the entity step is missing: "+ + "`[.%s//%s %s empty]`.", assoc, attr, assoc, attr, h.Op) } - return fmt.Sprintf("Test for the absence of the associated object with negation: `[not(%s/)]`.", h.Assoc) + return fix } // xpathAssociationEmptyMatches returns the module-qualified associations an diff --git a/mdl/executor/validate_published_rest_ops.go b/mdl/executor/validate_published_rest_ops.go new file mode 100644 index 000000000..c08872122 --- /dev/null +++ b/mdl/executor/validate_published_rest_ops.go @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "context" + "fmt" + "strings" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/linter" + "github.com/mendixlabs/mxcli/model" +) + +// publishedRestOperationDropRule warns that `create or modify published rest +// service` removes stored operations it does not list (ako/mxcli#2449, +// mendixlabs/mxcli#1903). The statement is the whole service, so a rewrite +// that names only the operation it means to add deletes the others — and exec +// said only "Modified published rest service". A warning, as for an entity's +// unstated members (MDL107): "modify to this shape" is a legitimate use. +const publishedRestOperationDropRule = "MDL-REST06" + +// publishedRestOperationKey identifies an operation within its service: +// resource, method and path, as describe prints them. +func publishedRestOperationKey(resource, method, path string) string { + p := strings.Trim(path, "/") + return fmt.Sprintf("%s %s", strings.ToUpper(method), strings.TrimSuffix(resource+"/"+p, "/")) +} + +// droppedPublishedRestOperations lists the stored operations a create or +// modify statement does not declare, in stored order. +func droppedPublishedRestOperations(stored *model.PublishedRestService, s *ast.CreatePublishedRestServiceStmt) []string { + if stored == nil { + return nil + } + declared := map[string]bool{} + for _, r := range s.Resources { + for _, op := range r.Operations { + declared[publishedRestOperationKey(r.Name, op.HTTPMethod, op.Path)] = true + } + } + var out []string + for _, r := range stored.Resources { + for _, op := range r.Operations { + if k := publishedRestOperationKey(r.Name, op.HTTPMethod, op.Path); !declared[k] { + out = append(out, k) + } + } + } + return out +} + +func publishedRestDropMessage(qn string, dropped []string) string { + return fmt.Sprintf("create or modify published rest service %s removes %d stored operation(s) it does not list: %s", + qn, len(dropped), strings.Join(dropped, ", ")) +} + +const publishedRestDropSuggestion = "List every operation the service keeps — `describe published rest service` prints them — " + + "or change one operation and leave the rest alone: `alter published rest service … add operation in resource '' { … }` " + + "or `drop operation [''] in resource ''`." + +// CheckPublishedRestOperationDrops reports, before exec, each create or modify +// of a stored published REST service that would remove operations. +func (e *Executor) CheckPublishedRestOperationDrops(prog *ast.Program) []linter.Violation { + if e == nil { + return nil + } + ctx := e.newExecContext(context.Background()) + if prog == nil || !ctx.Connected() { + return nil + } + var out []linter.Violation + for _, stmt := range prog.Statements { + s, ok := stmt.(*ast.CreatePublishedRestServiceStmt) + if !ok || !s.CreateOrModify { + continue + } + stored, err := findPublishedRestService(ctx, s.Name.Module, s.Name.Name) + if err != nil || stored == nil { + continue + } + if dropped := droppedPublishedRestOperations(stored, s); len(dropped) > 0 { + out = append(out, linter.Violation{ + RuleID: publishedRestOperationDropRule, + Severity: linter.SeverityWarning, + Location: linter.Location{Module: s.Name.Module, DocumentType: "published rest service", DocumentName: s.Name.Name}, + Message: publishedRestDropMessage(s.Name.String(), dropped), + Suggestion: publishedRestDropSuggestion, + }) + } + } + return out +} + +// publishedRestAlterResourceProblems are the resource actions of an ALTER +// that exec refuses against the stored service: adding a resource it already +// has, or dropping one it does not. check passed both (ako/mxcli#2449). The +// actions are applied in order, as exec applies them. +func publishedRestAlterResourceProblems(stored *model.PublishedRestService, s *ast.AlterPublishedRestServiceStmt) []string { + have := map[string]bool{} + ops := map[string]bool{} + for _, r := range stored.Resources { + have[r.Name] = true + for _, op := range r.Operations { + ops[publishedRestOperationKey(r.Name, op.HTTPMethod, op.Path)] = true + } + } + var out []string + for _, a := range s.Actions { + switch act := a.(type) { + case *ast.PublishedRestAddOperationsAction: + if !have[act.Resource] { + out = append(out, fmt.Sprintf("resource %s not found on %s: `add operation in resource` adds to a stored resource; "+ + "a new one is `add resource %s { … }`", mdlQuoted(act.Resource), s.Name, mdlQuoted(act.Resource))) + continue + } + for _, op := range act.Operations { + k := publishedRestOperationKey(act.Resource, op.HTTPMethod, op.Path) + if ops[k] { + out = append(out, fmt.Sprintf("operation %s already exists on %s: `add operation` adds a new one; "+ + "to change it, `drop operation %s in resource %s` first and add it back", + k, s.Name, publishedRestOperationSpelling(op.HTTPMethod, op.Path), mdlQuoted(act.Resource))) + } + ops[k] = true + } + case *ast.PublishedRestDropOperationAction: + k := publishedRestOperationKey(act.Resource, act.HTTPMethod, act.Path) + if !ops[k] { + out = append(out, fmt.Sprintf("operation %s not found on %s", k, s.Name)) + } + delete(ops, k) + case *ast.PublishedRestAddResourceAction: + if have[act.Resource.Name] { + out = append(out, fmt.Sprintf("resource %s already exists on %s: `add resource` adds a new one; "+ + "to change it, `drop resource %s` first and add it back with every operation it keeps", + mdlQuoted(act.Resource.Name), s.Name, mdlQuoted(act.Resource.Name))) + } + have[act.Resource.Name] = true + case *ast.PublishedRestDropResourceAction: + if !have[act.Name] { + out = append(out, fmt.Sprintf("resource %s not found on %s", mdlQuoted(act.Name), s.Name)) + } + delete(have, act.Name) + } + } + return out +} diff --git a/mdl/executor/validate_published_rest_ops_2449_test.go b/mdl/executor/validate_published_rest_ops_2449_test.go new file mode 100644 index 000000000..4413c9ad9 --- /dev/null +++ b/mdl/executor/validate_published_rest_ops_2449_test.go @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/model" +) + +// ako/mxcli#2449 (mendixlabs/mxcli#1903): adding one operation to a stored +// published REST service. `add resource` with the stored name passed check and +// exec refused it; `create or modify` naming only the new operation deleted +// the others, and exec said only "Modified published rest service". + +func bookingService2449() *model.PublishedRestService { + return &model.PublishedRestService{Name: "BookingApi", Resources: []*model.PublishedRestResource{{ + Name: "bookings", + Operations: []*model.PublishedRestOperation{ + {HTTPMethod: "GET", Path: ""}, + {HTTPMethod: "GET", Path: "{id}"}, + }, + }}} +} + +func TestCreateOrModifyNamesTheOperationsItRemoves_2449(t *testing.T) { + stmt := &ast.CreatePublishedRestServiceStmt{CreateOrModify: true, Resources: []*ast.PublishedRestResourceDef{{ + Name: "bookings", Operations: []*ast.PublishedRestOperationDef{{HTTPMethod: "DELETE", Path: "{id}"}}, + }}} + got := droppedPublishedRestOperations(bookingService2449(), stmt) + if strings.Join(got, ", ") != "GET bookings, GET bookings/{id}" { + t.Errorf("dropped = %v, want both GET operations", got) + } + // Control: the stored operations listed — describe's spelling, `/` and + // `''` for the resource's own path — remove nothing. + full := &ast.CreatePublishedRestServiceStmt{CreateOrModify: true, Resources: []*ast.PublishedRestResourceDef{{ + Name: "bookings", Operations: []*ast.PublishedRestOperationDef{ + {HTTPMethod: "get", Path: "/"}, {HTTPMethod: "GET", Path: "/{id}"}, {HTTPMethod: "DELETE", Path: "{id}"}, + }, + }}} + if got := droppedPublishedRestOperations(bookingService2449(), full); len(got) != 0 { + t.Errorf("a statement listing every stored operation removes %v", got) + } +} + +func TestAlterResourceProblemsMatchExec_2449(t *testing.T) { + alter := func(actions ...ast.PublishedRestAlterAction) *ast.AlterPublishedRestServiceStmt { + return &ast.AlterPublishedRestServiceStmt{Name: ast.QualifiedName{Module: "M", Name: "BookingApi"}, Actions: actions} + } + add := func(n string) ast.PublishedRestAlterAction { + return &ast.PublishedRestAddResourceAction{Resource: &ast.PublishedRestResourceDef{Name: n}} + } + drop := func(n string) ast.PublishedRestAlterAction { return &ast.PublishedRestDropResourceAction{Name: n} } + + if p := publishedRestAlterResourceProblems(bookingService2449(), alter(add("bookings"))); len(p) != 1 || !strings.Contains(p[0], "already exists") { + t.Errorf("add of a stored resource: %v", p) + } + if p := publishedRestAlterResourceProblems(bookingService2449(), alter(drop("rooms"))); len(p) != 1 || !strings.Contains(p[0], "not found") { + t.Errorf("drop of a missing resource: %v", p) + } + // Controls: drop then add back, and a new resource, are what exec applies. + for _, a := range [][]ast.PublishedRestAlterAction{{drop("bookings"), add("bookings")}, {add("rooms")}} { + if p := publishedRestAlterResourceProblems(bookingService2449(), alter(a...)); len(p) != 0 { + t.Errorf("valid actions refused: %v", p) + } + } +} diff --git a/mdl/executor/validate_rest_mapping.go b/mdl/executor/validate_rest_mapping.go index b63f48231..60ed375b0 100644 --- a/mdl/executor/validate_rest_mapping.go +++ b/mdl/executor/validate_rest_mapping.go @@ -95,8 +95,11 @@ func ValidatePublishedRestCommit(prog *ast.Program) []linter.Violation { } case *ast.AlterPublishedRestServiceStmt: for _, a := range s.Actions { - if add, ok := a.(*ast.PublishedRestAddResourceAction); ok { + switch add := a.(type) { + case *ast.PublishedRestAddResourceAction: visit(add.Resource) + case *ast.PublishedRestAddOperationsAction: + visit(&ast.PublishedRestResourceDef{Name: add.Resource, Operations: add.Operations}) } } } diff --git a/mdl/executor/validate_retrieve_members.go b/mdl/executor/validate_retrieve_members.go index 8989e5e10..0a9d5acd1 100644 --- a/mdl/executor/validate_retrieve_members.go +++ b/mdl/executor/validate_retrieve_members.go @@ -48,7 +48,7 @@ func validateRetrieveMembers(ctx *ExecContext, retrieves []retrieveConstraintRef } errs = append(errs, fmt.Sprintf( "retrieve from %s: the constraint names %q, which is neither an attribute nor an association of it — mxbuild rejects the constraint (CE0161 \"Error(s) in XPath constraint\")%s", - r.entity, bad.name, systemMemberSpellingHint(bad.name))) + r.entity, bad.name, systemMemberSpellingHint(bad.name)+missingStepSuffix(missingEntityStepHint(m, resolve, r.entity, bad.name)))) } } return errs diff --git a/mdl/executor/validate_xpath_missing_step.go b/mdl/executor/validate_xpath_missing_step.go new file mode 100644 index 000000000..4ca1875d0 --- /dev/null +++ b/mdl/executor/validate_xpath_missing_step.go @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "fmt" + "strings" + + "github.com/mendixlabs/mxcli/mdl/xpathrefs" +) + +// missingEntityStepHint recognises `.` read as one +// qualified name — `[Car_Assignment.ReturnedOn = empty]` — where the first +// part is an association of the entity and the second an attribute of the +// entity at its other end (ako/mxcli#2491). What is missing is the entity +// step between them: `[Repro.Car_Assignment/Repro.Assignment/ReturnedOn …]`. +// The messages that called the name an unknown association, and MDL047's +// `not(…)` fix, kept the dotted name, and an agent followed them for 40 +// minutes. It returns the clause that says so, "" when the name is not that +// shape. +func missingEntityStepHint(m xpathrefs.Model, resolve func(entityQN, member string) memberResolution, entityQN, name string) string { + dot := strings.LastIndex(name, ".") + if dot <= 0 || dot == len(name)-1 { + return "" + } + assoc, attr := name[:dot], name[dot+1:] + if !strings.Contains(assoc, ".") { + mod := entityQN + if i := strings.Index(entityQN, "."); i > 0 { + mod = entityQN[:i] + } + assoc = mod + "." + assoc + } + target, ok := m.AssociationTarget(assoc, entityQN) + if !ok || target == "" || resolve(target, attr) != memberFound { + return "" + } + return fmt.Sprintf("association %s followed by attribute %s of %s, with the entity step between them missing — "+ + "a path goes association/entity/attribute: `[%s/%s/%s …]`, or with a predicate `[%s/%s[%s …]]`", + assoc, attr, target, assoc, target, attr, assoc, target, attr) +} + +// missingStepSuffix appends the clause to a message that has named the step. +func missingStepSuffix(hint string) string { + if hint == "" { + return "" + } + return ": it is " + hint +} diff --git a/mdl/executor/validate_xpath_missing_step_2491_test.go b/mdl/executor/validate_xpath_missing_step_2491_test.go new file mode 100644 index 000000000..995a5ddb6 --- /dev/null +++ b/mdl/executor/validate_xpath_missing_step_2491_test.go @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: Apache-2.0 + +package executor + +import ( + "strings" + "testing" +) + +// ako/mxcli#2491: `[Car_Assignment.ReturnedOn = empty]` on Repro.Car, where +// Car_Assignment leads to Repro.Assignment and ReturnedOn is its attribute. +// MDL047 suggested `[not(Car_Assignment.ReturnedOn/)]` +// and the reference check called the whole name an unknown association; both +// kept the dotted name, and neither said a path needs association/entity/ +// attribute. An agent followed them for about 40 minutes. + +type fakeXPathModel2491 struct{ assoc map[string]string } + +func (f fakeXPathModel2491) IsEntity(qn string) bool { + return qn == "Repro.Car" || qn == "Repro.Assignment" +} +func (f fakeXPathModel2491) AssociationTarget(qn, from string) (string, bool) { + t, ok := f.assoc[qn] + return t, ok +} + +func resolve2491(entityQN, member string) memberResolution { + if entityQN == "Repro.Assignment" && member == "ReturnedOn" { + return memberFound + } + return memberMissing +} + +func TestMissingEntityStepHint_2491(t *testing.T) { + m := fakeXPathModel2491{assoc: map[string]string{"Repro.Car_Assignment": "Repro.Assignment"}} + for _, name := range []string{"Car_Assignment.ReturnedOn", "Repro.Car_Assignment.ReturnedOn"} { + hint := missingEntityStepHint(m, resolve2491, "Repro.Car", name) + for _, want := range []string{"entity step", "[Repro.Car_Assignment/Repro.Assignment/ReturnedOn", "[Repro.Car_Assignment/Repro.Assignment[ReturnedOn"} { + if !strings.Contains(hint, want) { + t.Errorf("%s: hint %q lacks %q", name, hint, want) + } + } + } + // Controls: a real unknown association, an attribute the far end does not + // have, and a name with no dot say nothing extra. + for _, name := range []string{"Repro.NoSuchAssoc", "Car_Assignment.Missing", "ReturnedOn"} { + if hint := missingEntityStepHint(m, resolve2491, "Repro.Car", name); hint != "" { + t.Errorf("%s: unexpected hint %q", name, hint) + } + } +} + +// Without a project MDL047 cannot tell `Module.Assoc` from `Assoc.Attr`, so +// its fix names the missing-step reading as well as the absence form. +func TestMDL047FixOffersTheMissingStepReading_2491(t *testing.T) { + hits := xpathAssociationEmptyMatches("[Car_Assignment.ReturnedOn = empty]") + if len(hits) != 1 { + t.Fatalf("hits = %+v", hits) + } + fix := hits[0].fix() + if !strings.Contains(fix, "not(Car_Assignment.ReturnedOn/") || !strings.Contains(fix, ".Car_Assignment//ReturnedOn = empty") { + t.Errorf("fix = %q", fix) + } +} diff --git a/mdl/grammar/MDLParser.g4 b/mdl/grammar/MDLParser.g4 index 03d250448..098f07241 100644 --- a/mdl/grammar/MDLParser.g4 +++ b/mdl/grammar/MDLParser.g4 @@ -304,6 +304,10 @@ alterPublishedRestServiceAction | SET publishedRestAlterAssignment (COMMA publishedRestAlterAssignment)* | ADD publishedRestResource | DROP RESOURCE STRING_LITERAL + // One operation of a stored resource, written as create writes it; the + // others are written back as stored (ako/mxcli#2449). + | ADD OPERATION IN RESOURCE STRING_LITERAL LBRACE publishedRestOperation+ RBRACE + | DROP OPERATION restHttpMethod publishedRestOpPath? IN RESOURCE STRING_LITERAL ; publishedRestAlterAssignment diff --git a/mdl/linter/rules/mpr017_fixed_guard_attribute.go b/mdl/linter/rules/mpr017_fixed_guard_attribute.go index 5143056f8..6250f081a 100644 --- a/mdl/linter/rules/mpr017_fixed_guard_attribute.go +++ b/mdl/linter/rules/mpr017_fixed_guard_attribute.go @@ -55,6 +55,14 @@ import ( // - not read in any condition: then there is no guard, dead or otherwise. // (The mirror case, written but never read, is a separate verdict and is // deliberately not in this rule.) +// - assigned by a mapping or a database query: an import mapping's value +// elements and a database-connection query's `Map:` columns set the attribute +// at runtime with no Change activity, so each counts as an unknown write +// (ako/mxcli#2501). Without it a flag set from JSON `true` and tested by a +// decision was reported as "can only ever be false". +// - an attribute of an external entity: the published service supplies the +// values, so "nothing in this app assigns it" says nothing about the runtime +// value (ako/mxcli#2501). // // Writes are collected from EVERY module, including Marketplace ones, while // only the project's own attributes are reported. A Marketplace flow writing an @@ -136,7 +144,7 @@ func (r *FixedGuardAttributeRule) Check(ctx *linter.LintContext) []linter.Violat var owned []linter.Attribute for e := range ctx.Entities() { - if ctx.IsExcluded(e.ModuleName) { + if ctx.IsExcluded(e.ModuleName) || !guardableEntity(e) { continue } for a := range ctx.AttributesFor(e.QualifiedName) { @@ -171,6 +179,62 @@ func (r *FixedGuardAttributeRule) Check(ctx *linter.LintContext) []linter.Violat return violations } +// guardableEntity reports whether the rule may judge the entity's attributes. An +// external entity's values come from the published service, so "nothing in this +// app assigns it" is true of the model and says nothing about the runtime value +// (ako/mxcli#2501). +func guardableEntity(e linter.Entity) bool { return !e.IsExternal } + +// mappedAttributeNames is every attribute a mapping or a database query assigns +// at runtime without a Change activity: the value elements of import mappings and +// the columns of database-connection queries. Sorted and distinct. +func mappedAttributeNames(imports []*model.ImportMapping, conns []*model.DatabaseConnection) []string { + seen := map[string]bool{} + var walk func(es []*model.ImportMappingElement) + walk = func(es []*model.ImportMappingElement) { + for _, e := range es { + if e == nil { + continue + } + if e.Attribute != "" { + seen[e.Attribute] = true + } + walk(e.Children) + } + } + for _, m := range imports { + if m != nil { + walk(m.Elements) + } + } + for _, c := range conns { + if c == nil { + continue + } + for _, q := range c.Queries { + if q == nil { + continue + } + for _, tm := range q.TableMappings { + if tm == nil { + continue + } + for _, col := range tm.Columns { + if col != nil && col.Attribute != "" { + seen[col.Attribute] = true + } + } + } + } + } + out := make([]string, 0, len(seen)) + for a := range seen { + out = append(out, a) + } + sort.Strings(out) + return out +} + func entityName(qualified string) string { if i := strings.LastIndex(qualified, "."); i >= 0 { return qualified[i+1:] @@ -385,6 +449,38 @@ func collectAttributeFacts(ctx *linter.LintContext) (map[string]*attrFacts, stri markRead(mc.Value) }) } + // Writes the runtime makes with no Change activity: an import mapping and a + // database query assign the attributes they map (ako/mxcli#2501). They are + // unknown writes, like an expression: the value set cannot be enumerated. The + // reader reaches these through an assertion, as DomainModels does; a reader + // that cannot list them (a test double) simply has none to report. + var imports []*model.ImportMapping + var conns []*model.DatabaseConnection + if r, ok := reader.(interface { + ListImportMappings() ([]*model.ImportMapping, error) + }); ok { + if imports, err = r.ListImportMappings(); err != nil { + return nil, fmt.Sprintf("reading import mappings for assigned attributes: %v", err) + } + } + if r, ok := reader.(interface { + ListDatabaseConnections() ([]*model.DatabaseConnection, error) + }); ok { + if conns, err = r.ListDatabaseConnections(); err != nil { + return nil, fmt.Sprintf("reading database connections for assigned attributes: %v", err) + } + } + for _, qn := range mappedAttributeNames(imports, conns) { + targets := []string{} + if f := facts[qn]; f != nil { + targets = append(targets, qn) + } else { + targets = append(targets, byName[entityName(qn)]...) + } + for _, t := range targets { + get(t).unknownWrite = true + } + } return facts, "" } diff --git a/mdl/linter/rules/mpr017_fixed_guard_attribute_test.go b/mdl/linter/rules/mpr017_fixed_guard_attribute_test.go index fc9ef9b90..d5245d741 100644 --- a/mdl/linter/rules/mpr017_fixed_guard_attribute_test.go +++ b/mdl/linter/rules/mpr017_fixed_guard_attribute_test.go @@ -3,9 +3,12 @@ package rules import ( + "path/filepath" "testing" + "github.com/mendixlabs/mxcli/mdl/catalog" "github.com/mendixlabs/mxcli/mdl/linter" + "github.com/mendixlabs/mxcli/model" ) func attr(entity, name, dataType, def string) linter.Attribute { @@ -230,3 +233,123 @@ func TestFixedGuardAttributeRule_RequiresFullCatalog(t *testing.T) { t.Errorf("RequiredCatalogMode([rule]) = %v, want CatalogFull", got) } } + +// ako/mxcli#2501: four findings, all false, by two mechanisms plus one the +// report did not list. In each the attribute really is assigned, but not by a +// Change activity, so the rule read "nothing assigns it". +// +// - an external entity's attributes come from the published service; +// - a database-connection query's `Map:` assigns the attributes it maps; +// - an import mapping assigns the attributes it maps (reproduced on a project: +// a Boolean set from JSON `true` and tested by a decision was reported as +// "can only ever be false"). +func TestMappedAttributeNames_ImportMappingsAndDatabaseQueries(t *testing.T) { + imports := []*model.ImportMapping{{ + Name: "IMM", + Elements: []*model.ImportMappingElement{{ + Kind: "Object", Entity: "Shop.Standing", + Children: []*model.ImportMappingElement{ + {Kind: "Value", Attribute: "Shop.Standing.Won"}, + {Kind: "Object", Entity: "Shop.Line", Children: []*model.ImportMappingElement{ + {Kind: "Value", Attribute: "Shop.Line.Accepted"}, + }}, + {Kind: "Value"}, // an element that maps no attribute + }, + }}, + }} + conns := []*model.DatabaseConnection{{ + Name: "Db", + Queries: []*model.DatabaseQuery{{ + Name: "Q", + TableMappings: []*model.DatabaseTableMapping{{ + Entity: "Shop.Result", + Columns: []*model.DatabaseColumnMapping{ + {Attribute: "Shop.Result.Accepted"}, + {Attribute: ""}, + }, + }}, + }}, + }} + got := mappedAttributeNames(imports, conns) + want := []string{"Shop.Line.Accepted", "Shop.Result.Accepted", "Shop.Standing.Won"} + if len(got) != len(want) { + t.Fatalf("got %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("got %v, want %v", got, want) + } + } + if got := mappedAttributeNames(nil, nil); len(got) != 0 { + t.Errorf("nothing mapped: want none, got %v", got) + } +} + +// An external entity is not judged: nothing in the consuming app assigns its +// attributes by construction, so "nothing ever assigns it" says nothing about the +// runtime value. A local entity is still judged (the control). +func TestFixedGuardEntity_ExternalEntitiesAreNotJudged(t *testing.T) { + if guardableEntity(linter.Entity{QualifiedName: "F1Admin.Narrative", IsExternal: true}) { + t.Error("an external entity must not be judged") + } + if !guardableEntity(linter.Entity{QualifiedName: "Shop.Settings"}) { + t.Error("a local entity must still be judged") + } +} + +// mappedWritesReader is a reader that also lists import mappings and database +// connections, the way the production backend does (reached by assertion). +type mappedWritesReader struct { + rawUnitReader + imports []*model.ImportMapping + conns []*model.DatabaseConnection +} + +func (r mappedWritesReader) ListImportMappings() ([]*model.ImportMapping, error) { + return r.imports, nil +} +func (r mappedWritesReader) ListDatabaseConnections() ([]*model.DatabaseConnection, error) { + return r.conns, nil +} + +// Through the real entry point: a mapped attribute is an unknown write, so +// fixedGuards then leaves it alone. The unmapped one (the control) stays reportable. +func TestCollectAttributeFacts_MappedAttributesAreWrites(t *testing.T) { + // A file-backed catalog: an in-memory one gives each pooled connection its own + // empty database (ako/mxcli#2417). + cat, err := catalog.NewFromFile(filepath.Join(t.TempDir(), "cat.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = cat.Close() }) + for _, q := range []string{ + `INSERT INTO modules_data (Id, Name, ProjectId, SnapshotId) VALUES ('m1', 'Shop', 'default', 's1')`, + `INSERT INTO entities_data (Id, Name, QualifiedName, ModuleName, Folder, EntityType, Description, Generalization, AttributeCount, AccessRuleCount, ValidationRuleCount, HasEventHandlers, IsExternal, ProjectId, SnapshotId) VALUES ('e1', 'Standing', 'Shop.Standing', 'Shop', '', 'PERSISTENT', '', '', 3, 0, 0, 0, 0, 'default', 's1')`, + `INSERT INTO attributes_data (Id, Name, EntityId, EntityQualifiedName, ModuleName, DataType, Length, IsUnique, IsRequired, DefaultValue, IsCalculated, Description, ProjectId, SnapshotId) VALUES + ('a1', 'Won', 'e1', 'Shop.Standing', 'Shop', 'Boolean', 0, 0, 0, 'false', 0, '', 'default', 's1'), + ('a2', 'Accepted', 'e1', 'Shop.Standing', 'Shop', 'Boolean', 0, 0, 0, 'false', 0, '', 'default', 's1'), + ('a3', 'Local', 'e1', 'Shop.Standing', 'Shop', 'Boolean', 0, 0, 0, 'false', 0, '', 'default', 's1')`, + } { + if _, err := cat.CatalogDB().Exec(q); err != nil { + t.Fatalf("seed: %v", err) + } + } + r := mappedWritesReader{ + imports: []*model.ImportMapping{{Elements: []*model.ImportMappingElement{{Kind: "Object", Entity: "Shop.Standing", + Children: []*model.ImportMappingElement{{Kind: "Value", Attribute: "Shop.Standing.Won"}}}}}}, + conns: []*model.DatabaseConnection{{Queries: []*model.DatabaseQuery{{TableMappings: []*model.DatabaseTableMapping{{ + Columns: []*model.DatabaseColumnMapping{{Attribute: "Shop.Standing.Accepted"}}}}}}}}, + } + facts, why := collectAttributeFacts(linter.NewLintContext(cat, r)) + if why != "" { + t.Fatalf("collect failed: %s", why) + } + for _, qn := range []string{"Shop.Standing.Won", "Shop.Standing.Accepted"} { + if f := facts[qn]; f == nil || !f.unknownWrite { + t.Errorf("%s is assigned by a mapping, so it must count as an unknown write: %+v", qn, f) + } + } + if f := facts["Shop.Standing.Local"]; f == nil || f.unknownWrite { + t.Errorf("control: Shop.Standing.Local is mapped by nothing and must not be marked written: %+v", f) + } +} diff --git a/mdl/linter/rules/mpr019_unindexed_constraint.go b/mdl/linter/rules/mpr019_unindexed_constraint.go index 21b13e83f..2018adf20 100644 --- a/mdl/linter/rules/mpr019_unindexed_constraint.go +++ b/mdl/linter/rules/mpr019_unindexed_constraint.go @@ -207,10 +207,17 @@ func indexableEntityIndex(ctx *linter.LintContext) map[string]*indexableEntityIn } // indexableEntity reports whether an entity has a table to index at all. +// +// An external entity is stored persistable but its table lives in the app that +// publishes it, so there is no index here to add (ako/mxcli#2502: all 39 findings +// on a frontend app were external entities). func indexableEntity(e *domainmodel.Entity) bool { - return e != nil && e.Persistable && e.Name != "" + return e != nil && e.Persistable && e.Name != "" && e.Source != externalEntitySource } +// externalEntitySource is the stored Source of an external (OData remote) entity. +const externalEntitySource = "Rest$ODataRemoteEntitySource" + // attributeRefIndex returns an entity's attributes by UUID and by lower-cased // name, the two keys an attribute reference can arrive as. func attributeRefIndex(e *domainmodel.Entity) (byID map[model.ID]string, names map[string]bool) { diff --git a/mdl/linter/rules/mpr019_unindexed_constraint_test.go b/mdl/linter/rules/mpr019_unindexed_constraint_test.go index 19c0ae4d9..185102d61 100644 --- a/mdl/linter/rules/mpr019_unindexed_constraint_test.go +++ b/mdl/linter/rules/mpr019_unindexed_constraint_test.go @@ -212,3 +212,19 @@ func TestResolveAttributeRef_AcceptsUUIDAndQualifiedName(t *testing.T) { t.Errorf("empty ref = %q, want empty", got) } } + +// ako/mxcli#2502: MPR019 reported 39 findings on a frontend app, all 39 on an +// external entity. An external entity is stored persistable, but its table lives +// in the publishing app, so there is no index here to add. A local persistable +// entity is still indexable (the control). +func TestIndexableEntity_ExternalEntityHasNoTableHere(t *testing.T) { + e := idxEntity("Calendar", []string{"month"}) + e.Persistable = true + if !indexableEntity(e) { + t.Fatal("control: a local persistable entity is indexable") + } + e.Source = "Rest$ODataRemoteEntitySource" + if indexableEntity(e) { + t.Error("an external entity has no table in this app, so it is not indexable") + } +} diff --git a/mdl/visitor/visitor_rest.go b/mdl/visitor/visitor_rest.go index bde927f38..ebf9241a0 100644 --- a/mdl/visitor/visitor_rest.go +++ b/mdl/visitor/visitor_rest.go @@ -535,56 +535,61 @@ func buildPublishedRestResourceDef(rc *parser.PublishedRestResourceContext) *ast } for _, opCtx := range rc.AllPublishedRestOperation() { - oc := opCtx.(*parser.PublishedRestOperationContext) - opDef := &ast.PublishedRestOperationDef{} + resDef.Operations = append(resDef.Operations, buildPublishedRestOperationDef(opCtx.(*parser.PublishedRestOperationContext))) + } - // HTTP method - if mCtx := oc.RestHttpMethod(); mCtx != nil { - opDef.HTTPMethod = strings.ToUpper(mCtx.GetText()) - } + return resDef +} - // Operation path — strip leading/trailing slashes (CE6550/CE6551) - if pCtx := oc.PublishedRestOpPath(); pCtx != nil { - pc := pCtx.(*parser.PublishedRestOpPathContext) - if pc.STRING_LITERAL() != nil { - opDef.Path = strings.Trim(unquoteStringLit(pc.STRING_LITERAL()), "/") - } - } +// buildPublishedRestOperationDef converts one operation line, shared by a +// resource block and ALTER … ADD OPERATION (ako/mxcli#2449). +func buildPublishedRestOperationDef(oc *parser.PublishedRestOperationContext) *ast.PublishedRestOperationDef { + opDef := &ast.PublishedRestOperationDef{} - // Microflow reference - allQN := oc.AllQualifiedName() - if len(allQN) >= 1 { - opDef.Microflow = buildQualifiedName(allQN[0]) - } + // HTTP method + if mCtx := oc.RestHttpMethod(); mCtx != nil { + opDef.HTTPMethod = strings.ToUpper(mCtx.GetText()) + } - if oc.DEPRECATED() != nil { - opDef.Deprecated = true + // Operation path — strip leading/trailing slashes (CE6550/CE6551) + if pCtx := oc.PublishedRestOpPath(); pCtx != nil { + pc := pCtx.(*parser.PublishedRestOpPathContext) + if pc.STRING_LITERAL() != nil { + opDef.Path = strings.Trim(unquoteStringLit(pc.STRING_LITERAL()), "/") } + } + + // Microflow reference + allQN := oc.AllQualifiedName() + if len(allQN) >= 1 { + opDef.Microflow = buildQualifiedName(allQN[0]) + } - // Import/Export mapping (qualifiedName after IMPORT/EXPORT MAPPING) - if oc.IMPORT() != nil && len(allQN) >= 2 { - opDef.ImportMapping = buildQualifiedName(allQN[1]).String() + if oc.DEPRECATED() != nil { + opDef.Deprecated = true + } + + // Import/Export mapping (qualifiedName after IMPORT/EXPORT MAPPING) + if oc.IMPORT() != nil && len(allQN) >= 2 { + opDef.ImportMapping = buildQualifiedName(allQN[1]).String() + } + if oc.EXPORT() != nil { + idx := 1 + if oc.IMPORT() != nil { + idx = 2 } - if oc.EXPORT() != nil { - idx := 1 - if oc.IMPORT() != nil { - idx = 2 - } - if len(allQN) > idx { - opDef.ExportMapping = buildQualifiedName(allQN[idx]).String() - } + if len(allQN) > idx { + opDef.ExportMapping = buildQualifiedName(allQN[idx]).String() } + } - if oc.COMMIT() != nil { - if idCtx := oc.IdentifierOrKeyword(); idCtx != nil { - opDef.Commit = identifierOrKeywordText(idCtx.(*parser.IdentifierOrKeywordContext)) - } + if oc.COMMIT() != nil { + if idCtx := oc.IdentifierOrKeyword(); idCtx != nil { + opDef.Commit = identifierOrKeywordText(idCtx.(*parser.IdentifierOrKeywordContext)) } - - resDef.Operations = append(resDef.Operations, opDef) } - return resDef + return opDef } // exitAlterRestClientStatement handles ALTER CONSUMED REST SERVICE @@ -694,6 +699,31 @@ func (b *Builder) exitAlterPublishedRestServiceStatement(ctx *parser.AlterStatem continue } + // ADD OPERATION IN RESOURCE 'name' { ... } (ako/mxcli#2449) + if ac.ADD() != nil && ac.OPERATION() != nil { + act := &ast.PublishedRestAddOperationsAction{Resource: unquoteStringLit(ac.STRING_LITERAL())} + for _, opCtx := range ac.AllPublishedRestOperation() { + act.Operations = append(act.Operations, buildPublishedRestOperationDef(opCtx.(*parser.PublishedRestOperationContext))) + } + stmt.Actions = append(stmt.Actions, act) + continue + } + + // DROP OPERATION ['path'] IN RESOURCE 'name' + if ac.DROP() != nil && ac.OPERATION() != nil { + act := &ast.PublishedRestDropOperationAction{Resource: unquoteStringLit(ac.STRING_LITERAL())} + if m := ac.RestHttpMethod(); m != nil { + act.HTTPMethod = strings.ToUpper(m.GetText()) + } + if pCtx := ac.PublishedRestOpPath(); pCtx != nil { + if pc := pCtx.(*parser.PublishedRestOpPathContext); pc.STRING_LITERAL() != nil { + act.Path = strings.Trim(unquoteStringLit(pc.STRING_LITERAL()), "/") + } + } + stmt.Actions = append(stmt.Actions, act) + continue + } + // ADD RESOURCE 'name' { ... } if ac.ADD() != nil { if rc := ac.PublishedRestResource(); rc != nil { diff --git a/sql/import_assoc.go b/sql/import_assoc.go index 212e9318d..b04267c47 100644 --- a/sql/import_assoc.go +++ b/sql/import_assoc.go @@ -71,7 +71,10 @@ type AssocSystemInfo struct { AssociationName string TableName string ChildColumnName string - StorageFormat string // decoded: StorageFormatColumn or StorageFormatTable + // ParentColumnName is the junction table's column for the parent (FROM) + // entity; for column storage Mendix writes `id` here (ako/mxcli#1686). + ParentColumnName string + StorageFormat string // decoded: StorageFormatColumn or StorageFormatTable } // decodeStorageFormat normalises a mendixsystem$association.storage_format @@ -130,15 +133,15 @@ func decodeStorageFormatText(s string) (string, error) { // cannot be decoded. func LookupAssociationInfo(ctx context.Context, conn *Connection, assocName string) (*AssocSystemInfo, error) { query := ` - SELECT association_name, table_name, child_column_name, storage_format + SELECT association_name, table_name, parent_column_name, child_column_name, storage_format FROM mendixsystem$association WHERE association_name = $1` var info AssocSystemInfo - var childCol sql.NullString + var parentCol, childCol sql.NullString var rawFormat any err := conn.DB.QueryRowContext(ctx, query, assocName).Scan( - &info.AssociationName, &info.TableName, &childCol, &rawFormat) + &info.AssociationName, &info.TableName, &parentCol, &childCol, &rawFormat) if err != nil { if err == sql.ErrNoRows { return nil, nil // not found — caller will fall back to conventions @@ -152,6 +155,7 @@ func LookupAssociationInfo(ctx context.Context, conn *Connection, assocName stri } info.StorageFormat = format info.ChildColumnName = childCol.String + info.ParentColumnName = parentCol.String return &info, nil } @@ -203,6 +207,25 @@ func JunctionTableFromConvention(assocQualifiedName string) string { // JunctionColumnFromConvention derives a junction table column name. // Convention: {module}${entity_name_lower}id +// JunctionColumns names a junction table's parent and child columns: the +// ones mendixsystem$association records when it has the row, else the naming +// convention. A self-association's two ends are one entity, so the convention +// numbers them — measured on Mendix 11.12.6, Person_Friend from Person to +// Person is stored as myfirstmodule$personid1 (parent) and +// myfirstmodule$personid2 (child). Naming both after the entity put one +// column in the insert twice (ako/mxcli#1686). +func JunctionColumns(sys *AssocSystemInfo, parentEntity, childEntity string) (parent, child string) { + if sys != nil && sys.StorageFormat == StorageFormatTable && sys.ParentColumnName != "" && sys.ChildColumnName != "" { + return sys.ParentColumnName, sys.ChildColumnName + } + parent = JunctionColumnFromConvention(parentEntity) + child = JunctionColumnFromConvention(childEntity) + if strings.EqualFold(parentEntity, childEntity) { + return parent + "1", child + "2" + } + return parent, child +} + func JunctionColumnFromConvention(entityQualifiedName string) string { parts := strings.SplitN(entityQualifiedName, ".", 2) if len(parts) != 2 { diff --git a/sql/import_assoc_self_1686_test.go b/sql/import_assoc_self_1686_test.go new file mode 100644 index 000000000..cd535326a --- /dev/null +++ b/sql/import_assoc_self_1686_test.go @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 + +package sql + +import ( + "context" + "testing" +) + +// ako/mxcli#1686: IMPORT … LINK through a table-stored self-association named +// both junction columns after the one entity (`myfirstmodule$personid`), so +// the insert named one column twice. Measured on Mendix 11.12.6 against +// PostgreSQL, `MyFirstModule.Person_Friend` from Person to Person, storage +// table: +// +// mendixsystem$association: table_name myfirstmodule$person_friend, +// parent_column_name myfirstmodule$personid1, +// child_column_name myfirstmodule$personid2 +// information_schema: the same two columns. +// +// The row's names are used; the convention, used only when there is no row, +// numbers the two the same way. + +func TestJunctionColumnsFromTheSystemRow_1686(t *testing.T) { + conn := openSQLite(t, "self1686", + `CREATE TABLE mendixsystem$association (id TEXT, association_name TEXT, table_name TEXT, + parent_column_name TEXT, child_column_name TEXT, storage_format)`, + `INSERT INTO mendixsystem$association VALUES ('a', 'MyFirstModule.Person_Friend', 'myfirstmodule$person_friend', + 'myfirstmodule$personid1', 'myfirstmodule$personid2', 2)`, + ) + sys, err := LookupAssociationInfo(context.Background(), conn, "MyFirstModule.Person_Friend") + if err != nil || sys == nil { + t.Fatalf("lookup: %v %v", sys, err) + } + p, c := JunctionColumns(sys, "MyFirstModule.Person", "MyFirstModule.Person") + if p != "myfirstmodule$personid1" || c != "myfirstmodule$personid2" { + t.Errorf("columns = %q, %q; want the row's personid1, personid2", p, c) + } +} + +func TestJunctionColumnsByConvention_1686(t *testing.T) { + // No row (the app has not run since the association was made). + p, c := JunctionColumns(nil, "MyFirstModule.Person", "MyFirstModule.Person") + if p != "myfirstmodule$personid1" || c != "myfirstmodule$personid2" || p == c { + t.Errorf("self-association = %q, %q; want personid1, personid2", p, c) + } + // Control: two entities keep their unnumbered names. + p, c = JunctionColumns(nil, "MyFirstModule.EmployeeTbl", "MyFirstModule.Department") + if p != "myfirstmodule$employeetblid" || c != "myfirstmodule$departmentid" { + t.Errorf("two entities = %q, %q", p, c) + } +}