d365fo-mcp 1.20.0 → 1.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/copilot-instructions.md +2 -2
- package/README.md +5 -3
- package/bridge/D365MetadataBridge/D365MetadataBridge.csproj +71 -0
- package/bridge/D365MetadataBridge/Models/AxDbSqlModels.cs +129 -0
- package/bridge/D365MetadataBridge/Program.cs +37 -2
- package/bridge/D365MetadataBridge/Protocol/RequestDispatcher.cs +20 -2
- package/bridge/D365MetadataBridge/Services/AxDbSqlPolicy.cs +128 -0
- package/bridge/D365MetadataBridge/Services/AxDbSqlService.cs +391 -0
- package/bridge/D365MetadataBridge/Services/MetadataWriteService.cs +226 -10
- package/bridge/D365MetadataBridge/Services/Trace/EtlTraceReader.cs +123 -0
- package/bridge/D365MetadataBridge/Services/Trace/TraceAnalysisCommand.cs +114 -0
- package/bridge/D365MetadataBridge/Services/Trace/XppTraceAggregator.cs +613 -0
- package/dist/bridge/bridgeAdapter.d.ts +3 -0
- package/dist/bridge/bridgeAdapter.js +33 -4
- package/dist/bridge/bridgeClient.d.ts +20 -0
- package/dist/bridge/bridgeClient.js +47 -10
- package/dist/bridge/bridgeFailure.d.ts +23 -0
- package/dist/bridge/bridgeFailure.js +28 -0
- package/dist/bridge/bridgeReadiness.d.ts +10 -0
- package/dist/bridge/bridgeReadiness.js +15 -0
- package/dist/bridge/bridgeTypes.d.ts +2 -0
- package/dist/bridge/index.d.ts +1 -1
- package/dist/bridge/index.js +1 -1
- package/dist/cli/aosWebConfig.d.ts +19 -0
- package/dist/cli/aosWebConfig.js +46 -0
- package/dist/cli/bridgeSources.d.ts +13 -0
- package/dist/cli/bridgeSources.js +68 -0
- package/dist/cli/commands/config.js +14 -0
- package/dist/cli/commands/doctor.d.ts +30 -1
- package/dist/cli/commands/doctor.js +139 -7
- package/dist/cli/commands/instance.js +6 -3
- package/dist/cli/commands/setup.js +16 -6
- package/dist/cli/commands/update.d.ts +15 -6
- package/dist/cli/commands/update.js +26 -7
- package/dist/cli/context.d.ts +7 -6
- package/dist/cli/context.js +11 -7
- package/dist/cli/settingsPrompt.d.ts +7 -0
- package/dist/cli/settingsPrompt.js +26 -5
- package/dist/cli/sqlEnvironmentSetup.d.ts +3 -0
- package/dist/cli/sqlEnvironmentSetup.js +23 -0
- package/dist/cli/sqlSetup.d.ts +12 -0
- package/dist/cli/sqlSetup.js +45 -0
- package/dist/cli/ui.d.ts +1 -0
- package/dist/cli/ui.js +6 -1
- package/dist/config/axdbSql.d.ts +11 -0
- package/dist/config/axdbSql.js +22 -0
- package/dist/config/settings.d.ts +3 -1
- package/dist/config/settings.js +43 -9
- package/dist/config/sqlSettings.d.ts +3 -0
- package/dist/config/sqlSettings.js +17 -0
- package/dist/config/trace.d.ts +14 -0
- package/dist/config/trace.js +53 -0
- package/dist/config/traceSettings.d.ts +3 -0
- package/dist/config/traceSettings.js +16 -0
- package/dist/config/xrefSetup.d.ts +14 -0
- package/dist/config/xrefSetup.js +22 -0
- package/dist/index.js +20 -1
- package/dist/knowledge/kernelEdts.d.ts +54 -0
- package/dist/knowledge/kernelEdts.js +158 -0
- package/dist/metadata/modelDescriptor.d.ts +6 -15
- package/dist/metadata/modelDescriptor.js +6 -23
- package/dist/metadata/symbolIndex.d.ts +35 -2
- package/dist/metadata/symbolIndex.js +226 -63
- package/dist/metadata/types.d.ts +5 -0
- package/dist/metadata/xmlParser.d.ts +16 -2
- package/dist/metadata/xmlParser.js +41 -5
- package/dist/prompts/systemInstructions.js +13 -1
- package/dist/scripts/build-database.js +349 -83
- package/dist/scripts/build-fts.js +349 -83
- package/dist/scripts/extract-metadata.js +191 -18
- package/dist/scripts/startupIndexWorker.js +202 -72
- package/dist/server/mcpServer.js +2 -3
- package/dist/server/serverMode.d.ts +8 -15
- package/dist/server/serverMode.js +17 -6
- package/dist/server/toolAnnotations.js +2 -0
- package/dist/server/toolSchemas/axdbSql.d.ts +15 -0
- package/dist/server/toolSchemas/axdbSql.js +12 -0
- package/dist/server/toolSchemas/buildD365foProject.js +1 -1
- package/dist/server/toolSchemas/d365foFile.js +2 -2
- package/dist/server/toolSchemas/index.d.ts +13 -327
- package/dist/server/toolSchemas/index.js +4 -0
- package/dist/server/toolSchemas/labels.js +1 -1
- package/dist/server/toolSchemas/runSystestClass.js +1 -1
- package/dist/server/toolSchemas/search.js +1 -1
- package/dist/server/toolSchemas/traceD365fo.d.ts +15 -0
- package/dist/server/toolSchemas/traceD365fo.js +12 -0
- package/dist/tools/analysis/findReferences.js +126 -15
- package/dist/tools/analysis/prefixDiagnostics.js +25 -9
- package/dist/tools/analysis/search.js +1 -1
- package/dist/tools/analysis/validateCode.js +4 -3
- package/dist/tools/analysis/validateObjectNaming.js +11 -4
- package/dist/tools/analysis/validateXpp.d.ts +1 -0
- package/dist/tools/analysis/validateXpp.js +191 -15
- package/dist/tools/d365foFile.d.ts +2 -1
- package/dist/tools/d365foFile.js +72 -13
- package/dist/tools/knowledge/methodSignature.js +1 -1
- package/dist/tools/knowledge/xppKnowledge.js +4 -3
- package/dist/tools/labels.js +1 -1
- package/dist/tools/prepare/prepareCreate.js +18 -5
- package/dist/tools/readers/edtInfo.js +7 -0
- package/dist/tools/readers/formInfo.js +16 -1
- package/dist/tools/readers/getMethodSource.js +19 -2
- package/dist/tools/readers/getObjectInfo.js +1 -1
- package/dist/tools/readers/getWorkspaceInfo.js +48 -8
- package/dist/tools/readers/mapInfo.d.ts +4 -2
- package/dist/tools/readers/mapInfo.js +81 -2
- package/dist/tools/readers/objectXml.js +24 -1
- package/dist/tools/responseCaps.js +11 -0
- package/dist/tools/sdlc/axdbSql/contract.d.ts +155 -0
- package/dist/tools/sdlc/axdbSql/contract.js +69 -0
- package/dist/tools/sdlc/axdbSql/output.d.ts +3 -0
- package/dist/tools/sdlc/axdbSql/output.js +22 -0
- package/dist/tools/sdlc/axdbSql.d.ts +16 -0
- package/dist/tools/sdlc/axdbSql.js +37 -0
- package/dist/tools/sdlc/buildProject.d.ts +22 -9
- package/dist/tools/sdlc/buildProject.js +340 -197
- package/dist/tools/sdlc/compilerMetadataPrune.d.ts +16 -0
- package/dist/tools/sdlc/compilerMetadataPrune.js +44 -1
- package/dist/tools/sdlc/odataActionGuard.d.ts +66 -0
- package/dist/tools/sdlc/odataActionGuard.js +226 -0
- package/dist/tools/sdlc/runBpCheck.js +14 -8
- package/dist/tools/sdlc/sysTestRunner.d.ts +19 -1
- package/dist/tools/sdlc/sysTestRunner.js +153 -35
- package/dist/tools/sdlc/trace/analysis.d.ts +34 -0
- package/dist/tools/sdlc/trace/analysis.js +124 -0
- package/dist/tools/sdlc/trace/capture.d.ts +98 -0
- package/dist/tools/sdlc/trace/capture.js +230 -0
- package/dist/tools/sdlc/trace/contract.d.ts +83 -0
- package/dist/tools/sdlc/trace/contract.js +78 -0
- package/dist/tools/sdlc/traceD365fo.d.ts +13 -0
- package/dist/tools/sdlc/traceD365fo.js +232 -0
- package/dist/tools/sdlc/undoLastModification.js +26 -2
- package/dist/tools/sdlc/updateSymbolIndex.js +10 -6
- package/dist/tools/smart/codeGen.js +31 -13
- package/dist/tools/smart/generateSmartForm.js +10 -1
- package/dist/tools/smart/generateSmartReport.js +10 -1
- package/dist/tools/smart/generateSmartTable.js +26 -4
- package/dist/tools/specs/d365foFileOpSpecs.js +34 -18
- package/dist/tools/specs/labelsOpSpecs.js +2 -1
- package/dist/tools/specs/opSpecs.d.ts +13 -0
- package/dist/tools/specs/opSpecs.js +17 -1
- package/dist/tools/toolHandler.js +13 -12
- package/dist/tools/write/compileLabels.d.ts +4 -2
- package/dist/tools/write/compileLabels.js +33 -9
- package/dist/tools/write/createD365File.js +79 -17
- package/dist/tools/write/createLabel.js +158 -15
- package/dist/tools/write/deleteD365File.js +10 -0
- package/dist/tools/write/directXmlWriters.d.ts +152 -2
- package/dist/tools/write/directXmlWriters.js +502 -16
- package/dist/tools/write/edtBaseTypeFromExtends.d.ts +31 -0
- package/dist/tools/write/edtBaseTypeFromExtends.js +65 -0
- package/dist/tools/write/enumValueNames.d.ts +44 -0
- package/dist/tools/write/enumValueNames.js +130 -0
- package/dist/tools/write/inlineXppValidation.d.ts +7 -1
- package/dist/tools/write/inlineXppValidation.js +21 -4
- package/dist/tools/write/methodXmlFallback.d.ts +23 -0
- package/dist/tools/write/methodXmlFallback.js +36 -0
- package/dist/tools/write/modifyBackup.d.ts +64 -0
- package/dist/tools/write/modifyBackup.js +145 -0
- package/dist/tools/write/modifyD365File.d.ts +16 -27
- package/dist/tools/write/modifyD365File.js +172 -141
- package/dist/tools/write/resolveReferences.d.ts +2 -1
- package/dist/tools/write/resolveReferences.js +39 -1
- package/dist/tools/xml/generateD365Xml.js +6 -2
- package/dist/tools/xml/xmlTemplateGenerator.d.ts +13 -0
- package/dist/tools/xml/xmlTemplateGenerator.js +46 -5
- package/dist/utils/axEnumProperties.d.ts +18 -0
- package/dist/utils/axEnumProperties.js +26 -0
- package/dist/utils/callDedup.js +2 -0
- package/dist/utils/configManager.d.ts +46 -2
- package/dist/utils/configManager.js +154 -26
- package/dist/utils/crossModelWriteGuard.js +7 -2
- package/dist/utils/effectivePrefix.js +16 -8
- package/dist/utils/eolUtils.d.ts +13 -0
- package/dist/utils/eolUtils.js +26 -0
- package/dist/utils/formControlPlacement.d.ts +84 -0
- package/dist/utils/formControlPlacement.js +308 -0
- package/dist/utils/formControlPropertyXml.d.ts +54 -0
- package/dist/utils/formControlPropertyXml.js +187 -0
- package/dist/utils/formExtensionControlXml.d.ts +25 -0
- package/dist/utils/formExtensionControlXml.js +1 -1
- package/dist/utils/formMetadataNamespace.d.ts +29 -0
- package/dist/utils/formMetadataNamespace.js +134 -0
- package/dist/utils/indexedXmlLookup.d.ts +28 -1
- package/dist/utils/indexedXmlLookup.js +45 -4
- package/dist/utils/loadEnv.js +9 -0
- package/dist/utils/methodSourceSpans.d.ts +32 -0
- package/dist/utils/methodSourceSpans.js +100 -0
- package/dist/utils/modelClassifier.d.ts +51 -0
- package/dist/utils/modelClassifier.js +113 -2
- package/dist/utils/modelPrefixInference.js +4 -1
- package/dist/utils/objectFileLookup.js +1 -0
- package/dist/utils/objectNaming.d.ts +25 -0
- package/dist/utils/objectNaming.js +69 -2
- package/dist/utils/objectNamingRules.js +59 -17
- package/dist/utils/pathContainment.js +14 -1
- package/dist/utils/toolProgressMessage.js +9 -0
- package/dist/validation/formControlElementOrder.d.ts +2 -0
- package/dist/validation/formControlElementOrder.js +11 -2
- package/dist/workspace/projectFile.d.ts +35 -4
- package/dist/workspace/projectFile.js +89 -38
- package/dist/workspace/projectMembership.js +2 -1
- package/package.json +1 -1
|
@@ -22,7 +22,7 @@ Call `get_workspace_info()` before doing anything with D365FO objects.
|
|
|
22
22
|
|
|
23
23
|
## Terminal Prohibition
|
|
24
24
|
|
|
25
|
-
PowerShell / any terminal command **WILL HANG** in VS 2022 / VS 2026 MCP integration. Never use `run_in_terminal` or generate scripts as a fallback when an MCP tool fails — STOP and report the error verbatim.
|
|
25
|
+
PowerShell / any terminal command **WILL HANG** in VS 2022 / VS 2026 MCP integration. Never use `run_command_in_terminal` / `run_in_terminal` (or any other terminal tool) or generate scripts as a fallback when an MCP tool fails — STOP and report the error verbatim.
|
|
26
26
|
|
|
27
27
|
## Core Tool Mapping
|
|
28
28
|
|
|
@@ -32,7 +32,7 @@ PowerShell / any terminal command **WILL HANG** in VS 2022 / VS 2026 MCP integra
|
|
|
32
32
|
| Plan a new object before creating it | `prepare(mode="create", goal, objectName, objectType)` — returns collision check, naming, EDT/label hints + `groundingToken` |
|
|
33
33
|
| Create a D365FO object | `d365fo_file(action="create")` (never `create_file`) |
|
|
34
34
|
| Edit an existing object | `d365fo_file(action="modify")` (applies immediately — confirm in chat first) |
|
|
35
|
-
| Revert the last write | `d365fo_file(action="undo", filePath)` — git-tracked → checkout HEAD (discards ALL uncommitted changes to that file); untracked → deleted |
|
|
35
|
+
| Revert the last write | `d365fo_file(action="undo", filePath)` — git-tracked → checkout HEAD (discards ALL uncommitted changes to that file); untracked → deleted only if created this session |
|
|
36
36
|
| Search objects | `search` — multiple via `search(queries[])`, custom-only via `search(scope="extensions")` |
|
|
37
37
|
| Read any object's metadata | `get_object_info(objectType, name, options?)` — objectType ∈ class/table/form/query/view/enum/edt/report/data-entity/menu-item/service/map/config-key/security-policy/macro. 2+ known names: `get_object_info(objects=[{objectType,objectName},…])` — ONE call, never a loop |
|
|
38
38
|
| Method signature for CoC | `get_object_info(objectType="class", name, options={method, include:"signature"})` (already returned by `prepare(mode="change")`) |
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
<div align="center">
|
|
4
4
|
|
|
5
|
-
**
|
|
5
|
+
**22 AI tools that know every X++ class, table, form, and EDT in your D365FO codebase**
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/d365fo-mcp)
|
|
8
8
|
[](https://opensource.org/licenses/MIT)
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
|
|
30
30
|
AI assistants excel at C#, Python, and JavaScript. X++ is different: your D365FO codebase is private, deeply customized, and invisible to every model — so AI confidently generates code that doesn't compile.
|
|
31
31
|
|
|
32
|
-
This server pre-indexes your entire D365FO installation (580 000+ symbols across standard, ISV, and custom models) and exposes it as
|
|
32
|
+
This server pre-indexes your entire D365FO installation (580 000+ symbols across standard, ISV, and custom models) and exposes it as 22 specialized MCP tools (`axdb_sql` and `trace_d365fo` only once configured). Every signature, every CoC wrapper, every label, every form pattern — verified against your real metadata **before** the AI writes a single line.
|
|
33
33
|
|
|
34
34
|

|
|
35
35
|
|
|
@@ -53,6 +53,8 @@ This server pre-indexes your entire D365FO installation (580 000+ symbols across
|
|
|
53
53
|
| 🧩 **Form pattern engine** | Complete catalog of Microsoft form patterns and sub-patterns: recommends the right pattern, clones reference forms with datasource re-binding, **deterministically expands** patterns that have no reference form, **auto-repairs** a form's missing required controls, validates structure and blocks invalid writes |
|
|
54
54
|
| ✍️ **Safe metadata writes** | C# bridge uses Microsoft's own `IMetadataProvider` wherever it can express the object; the few types and ops it cannot go through structured XML writers with ambiguity guards — never blind string replacement. Automatic `.rnrproj` registration, one-call undo |
|
|
55
55
|
| 🏗️ **SDLC integration** | MSBuild compilation with structured diagnostics, DB sync, xppbp best practices, SysTestRunner — all from chat. Optional `restartAos: true` refreshes the matching local IIS/IIS Express runtime after a successful build and requested sync. [Runtime restart](docs/AOS_RUNTIME_RESTART.md) |
|
|
56
|
+
| 🗄️ **Optional AxDB SQL** | Off by default and not even published until configured: `axdb_sql` runs read-only, parameterized queries against AxDB on the development VM, so the agent can check what the code actually persisted. Windows authentication; one SELECT checked on the parsed T-SQL tree, inside a transaction that is always rolled back; no result cache. [Setup](docs/AXDB_SQL.md) |
|
|
57
|
+
| ⏱️ **Optional performance trace** | Off by default and not published until enabled: `trace_d365fo` captures the AOS's ETW events (X++ method enter/exit, SQL latency) on the development VM while the agent — or you — reproduce a slow scenario, and analyses the capture: where the time goes per method, which statements run thousands of times from one caller. No timer code added to the application; parameter values never returned. [Setup and accuracy](docs/TRACE.md) |
|
|
56
58
|
| 📐 **X++ knowledge base** | Queryable rules: select grammar, CoC authoring, financial dimensions, the posting engine (`LedgerVoucher`), number sequences, `SysExtension`, Electronic Reporting, AX2012→D365FO migration — prevents deprecated APIs |
|
|
57
59
|
|
|
58
60
|
### Pattern-grounded form development
|
|
@@ -115,7 +117,7 @@ Deployment guide: [docs/SETUP_AZURE.md](docs/SETUP_AZURE.md) — includes CI/CD
|
|
|
115
117
|
|
|
116
118
|
| Getting started | Reference | Operations |
|
|
117
119
|
|-----------------|-----------|------------|
|
|
118
|
-
| [Quick Start](docs/QUICK_START.md) — connect or install | [All
|
|
120
|
+
| [Quick Start](docs/QUICK_START.md) — connect or install | [All 22 tools](docs/MCP_TOOLS.md) | [Azure deployment](docs/SETUP_AZURE.md) |
|
|
119
121
|
| [Setup scenarios A–F](docs/SETUP.md) | [`.mcp.json` reference](docs/MCP_CONFIG.md) | [DevOps pipelines](docs/SETUP_AZURE.md#azure-devops-pipelines) |
|
|
120
122
|
| [Claude Code setup](docs/SETUP.md#claude-code-cli) | [Configuration](docs/CONFIGURATION.md) | [Testing](docs/TESTING.md) |
|
|
121
123
|
| [Usage examples](docs/USAGE_EXAMPLES.md) — real tool chains | [Architecture](docs/ARCHITECTURE.md) | [Custom / ISV models](docs/CUSTOM_EXTENSIONS.md) |
|
|
@@ -71,6 +71,7 @@
|
|
|
71
71
|
<!-- NuGet packages -->
|
|
72
72
|
<ItemGroup>
|
|
73
73
|
<PackageReference Include="System.Text.Json" Version="8.0.5" />
|
|
74
|
+
<PackageReference Include="Microsoft.SqlServer.TransactSql.ScriptDom" Version="161.8901.0" />
|
|
74
75
|
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies.net48" Version="1.0.3">
|
|
75
76
|
<PrivateAssets>all</PrivateAssets>
|
|
76
77
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
|
|
@@ -143,4 +144,74 @@
|
|
|
143
144
|
</Task>
|
|
144
145
|
</UsingTask>
|
|
145
146
|
|
|
147
|
+
<!--
|
|
148
|
+
Record WHICH sources this binary was compiled from, next to the binary (#1115).
|
|
149
|
+
|
|
150
|
+
An update can move the bridge sources and leave the built exe in place: `npm
|
|
151
|
+
install -g` replaces the package but not the build in the data directory,
|
|
152
|
+
and `git pull` never touches bin/Release. The server then runs new
|
|
153
|
+
TypeScript against an old bridge, and nothing says so. `update` and `doctor`
|
|
154
|
+
compare this stamp with the sources on disk (src/cli/bridgeSources.ts).
|
|
155
|
+
|
|
156
|
+
Written by the build itself, so every way of building leaves one: setup,
|
|
157
|
+
update, `npm run bridge:build` or a hand-run `dotnet build`, with or without
|
|
158
|
+
`-o`. The hash is the one scripts/bridgeAttest.mjs computes (same files,
|
|
159
|
+
same order, CRLF normalised). It runs only after a successful build: a
|
|
160
|
+
failed build keeps the previous binary and so, correctly, its stamp.
|
|
161
|
+
-->
|
|
162
|
+
<Target Name="WriteBridgeSourceStamp" AfterTargets="Build">
|
|
163
|
+
<WriteBridgeSourceStamp ProjectDir="$(MSBuildProjectDirectory)"
|
|
164
|
+
RepoRoot="$([System.IO.Path]::GetFullPath('$(MSBuildProjectDirectory)\..\..'))"
|
|
165
|
+
OutputFile="$(OutDir)D365MetadataBridge.sources.json" />
|
|
166
|
+
<ItemGroup>
|
|
167
|
+
<FileWrites Include="$(OutDir)D365MetadataBridge.sources.json" />
|
|
168
|
+
</ItemGroup>
|
|
169
|
+
</Target>
|
|
170
|
+
|
|
171
|
+
<UsingTask TaskName="WriteBridgeSourceStamp" TaskFactory="RoslynCodeTaskFactory"
|
|
172
|
+
AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
|
|
173
|
+
<ParameterGroup>
|
|
174
|
+
<ProjectDir ParameterType="System.String" Required="true" />
|
|
175
|
+
<RepoRoot ParameterType="System.String" Required="true" />
|
|
176
|
+
<OutputFile ParameterType="System.String" Required="true" />
|
|
177
|
+
</ParameterGroup>
|
|
178
|
+
<Task>
|
|
179
|
+
<Code Type="Fragment" Language="cs">
|
|
180
|
+
<![CDATA[
|
|
181
|
+
var files = new System.Collections.Generic.List<string>();
|
|
182
|
+
var pending = new System.Collections.Generic.Stack<string>();
|
|
183
|
+
pending.Push(System.IO.Path.GetFullPath(ProjectDir).TrimEnd('\\', '/'));
|
|
184
|
+
while (pending.Count > 0)
|
|
185
|
+
{
|
|
186
|
+
var dir = pending.Pop();
|
|
187
|
+
foreach (var sub in System.IO.Directory.GetDirectories(dir))
|
|
188
|
+
{
|
|
189
|
+
var name = System.IO.Path.GetFileName(sub);
|
|
190
|
+
if (name != "obj" && name != "bin") pending.Push(sub);
|
|
191
|
+
}
|
|
192
|
+
foreach (var file in System.IO.Directory.GetFiles(dir))
|
|
193
|
+
if (file.EndsWith(".cs", System.StringComparison.Ordinal) || file.EndsWith(".csproj", System.StringComparison.Ordinal)) files.Add(file);
|
|
194
|
+
}
|
|
195
|
+
files.Sort(System.StringComparer.Ordinal);
|
|
196
|
+
var root = System.IO.Path.GetFullPath(RepoRoot).TrimEnd('\\', '/');
|
|
197
|
+
var manifest = new System.Text.StringBuilder();
|
|
198
|
+
using (var sha = System.Security.Cryptography.SHA256.Create())
|
|
199
|
+
{
|
|
200
|
+
foreach (var file in files)
|
|
201
|
+
{
|
|
202
|
+
var rel = file.Substring(root.Length).TrimStart('\\', '/').Replace('\\', '/');
|
|
203
|
+
var content = new System.Text.UTF8Encoding(false).GetString(System.IO.File.ReadAllBytes(file)).Replace("\r\n", "\n");
|
|
204
|
+
var fileHash = System.BitConverter.ToString(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(content))).Replace("-", "").ToLowerInvariant();
|
|
205
|
+
manifest.Append(rel).Append(':').Append(fileHash).Append('\n');
|
|
206
|
+
}
|
|
207
|
+
var hash = System.BitConverter.ToString(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(manifest.ToString()))).Replace("-", "").ToLowerInvariant();
|
|
208
|
+
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(OutputFile)));
|
|
209
|
+
System.IO.File.WriteAllText(OutputFile,
|
|
210
|
+
"{\n \"sourceHash\": \"" + hash + "\",\n \"sourceFileCount\": " + files.Count + ",\n \"builtAt\": \"" + System.DateTime.UtcNow.ToString("o") + "\"\n}\n");
|
|
211
|
+
}
|
|
212
|
+
]]>
|
|
213
|
+
</Code>
|
|
214
|
+
</Task>
|
|
215
|
+
</UsingTask>
|
|
216
|
+
|
|
146
217
|
</Project>
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
using System;
|
|
2
|
+
using System.Collections.Generic;
|
|
3
|
+
using System.Data;
|
|
4
|
+
using System.Data.SqlClient;
|
|
5
|
+
using System.Data.SqlTypes;
|
|
6
|
+
using System.Globalization;
|
|
7
|
+
using System.Text.Json;
|
|
8
|
+
|
|
9
|
+
namespace D365MetadataBridge.Models
|
|
10
|
+
{
|
|
11
|
+
public sealed class AxDbSqlOptions
|
|
12
|
+
{
|
|
13
|
+
public string Server { get; set; } = "";
|
|
14
|
+
public string Database { get; set; } = "AxDB";
|
|
15
|
+
public bool TrustCertificate { get; set; }
|
|
16
|
+
public int TimeoutSeconds { get; set; } = 30;
|
|
17
|
+
public int MaxRows { get; set; } = 100;
|
|
18
|
+
public bool Enabled => !string.IsNullOrWhiteSpace(Server);
|
|
19
|
+
|
|
20
|
+
public string ConnectionString()
|
|
21
|
+
{
|
|
22
|
+
if (!Enabled) throw new ArgumentException("AxDB SQL server is not configured.");
|
|
23
|
+
if (string.IsNullOrWhiteSpace(Database) || TimeoutSeconds < 1 || TimeoutSeconds > 30 || MaxRows < 1 || MaxRows > 1000)
|
|
24
|
+
throw new ArgumentException("Invalid AxDB SQL configuration: database required, timeout 1..30, max rows 1..1000.");
|
|
25
|
+
return new SqlConnectionStringBuilder
|
|
26
|
+
{
|
|
27
|
+
DataSource = Server, InitialCatalog = Database, IntegratedSecurity = true,
|
|
28
|
+
Encrypt = true, TrustServerCertificate = TrustCertificate, ConnectTimeout = TimeoutSeconds,
|
|
29
|
+
ApplicationName = "D365MetadataBridge AxDB debug", Pooling = false, ConnectRetryCount = 0
|
|
30
|
+
}.ConnectionString;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
public sealed class AxDbSqlRequest
|
|
35
|
+
{
|
|
36
|
+
public string Sql { get; set; } = "";
|
|
37
|
+
public List<AxDbSqlParameter>? Parameters { get; set; }
|
|
38
|
+
public int? MaxRows { get; set; }
|
|
39
|
+
public string Table { get; set; } = "";
|
|
40
|
+
public string Schema { get; set; } = "dbo";
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
public sealed class AxDbSqlParameter
|
|
44
|
+
{
|
|
45
|
+
public string Name { get; set; } = "";
|
|
46
|
+
public string Type { get; set; } = "";
|
|
47
|
+
public JsonElement Value { get; set; }
|
|
48
|
+
public int? Size { get; set; }
|
|
49
|
+
public byte? Precision { get; set; }
|
|
50
|
+
public byte? Scale { get; set; }
|
|
51
|
+
|
|
52
|
+
public SqlParameter ToSqlParameter()
|
|
53
|
+
{
|
|
54
|
+
if (Name.Length < 1 || Name.Length > 128 || !(AsciiLetter(Name[0]) || Name[0] == '_'))
|
|
55
|
+
throw new ArgumentException("Parameter name must start with a letter or underscore, without @.");
|
|
56
|
+
for (var i = 1; i < Name.Length; i++)
|
|
57
|
+
if (!(AsciiLetter(Name[i]) || (Name[i] >= '0' && Name[i] <= '9') || Name[i] == '_')) throw new ArgumentException("Invalid SQL parameter name.");
|
|
58
|
+
if (Value.ValueKind == JsonValueKind.Undefined) throw new ArgumentException("Parameter value is required (use null for SQL NULL).");
|
|
59
|
+
var isNull = Value.ValueKind == JsonValueKind.Null;
|
|
60
|
+
var parameter = new SqlParameter { ParameterName = "@" + Name };
|
|
61
|
+
object value = DBNull.Value;
|
|
62
|
+
switch (Type.ToLowerInvariant())
|
|
63
|
+
{
|
|
64
|
+
case "bit":
|
|
65
|
+
parameter.SqlDbType = SqlDbType.Bit;
|
|
66
|
+
if (!isNull) value = Value.GetBoolean();
|
|
67
|
+
break;
|
|
68
|
+
case "int":
|
|
69
|
+
parameter.SqlDbType = SqlDbType.Int;
|
|
70
|
+
if (!isNull) value = Value.GetInt32();
|
|
71
|
+
break;
|
|
72
|
+
case "bigint":
|
|
73
|
+
parameter.SqlDbType = SqlDbType.BigInt;
|
|
74
|
+
if (!isNull) value = long.Parse(RequireString(), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture);
|
|
75
|
+
break;
|
|
76
|
+
case "decimal":
|
|
77
|
+
parameter.SqlDbType = SqlDbType.Decimal;
|
|
78
|
+
if (!Precision.HasValue || !Scale.HasValue || Precision < 1 || Precision > 38 || Scale > Precision)
|
|
79
|
+
throw new ArgumentException("decimal requires precision 1..38 and scale 0..precision.");
|
|
80
|
+
parameter.Precision = Precision.Value;
|
|
81
|
+
parameter.Scale = Scale.Value;
|
|
82
|
+
if (!isNull)
|
|
83
|
+
{
|
|
84
|
+
var parsed = SqlDecimal.Parse(RequireString());
|
|
85
|
+
var adjusted = SqlDecimal.ConvertToPrecScale(parsed, Precision.Value, Scale.Value);
|
|
86
|
+
if (SqlDecimal.NotEquals(parsed, adjusted).Value) throw new ArgumentException("Decimal parameter would be rounded.");
|
|
87
|
+
value = adjusted;
|
|
88
|
+
}
|
|
89
|
+
break;
|
|
90
|
+
case "nvarchar":
|
|
91
|
+
parameter.SqlDbType = SqlDbType.NVarChar;
|
|
92
|
+
if (!Size.HasValue || (Size != -1 && (Size < 1 || Size > 4000)))
|
|
93
|
+
throw new ArgumentException("nvarchar requires size 1..4000 or -1 (max).");
|
|
94
|
+
parameter.Size = Size.Value;
|
|
95
|
+
if (!isNull)
|
|
96
|
+
{
|
|
97
|
+
var text = RequireString();
|
|
98
|
+
if (text.Length > 65536 || (Size != -1 && text.Length > Size)) throw new ArgumentException("nvarchar value exceeds its declared size or 65536 characters.");
|
|
99
|
+
value = text;
|
|
100
|
+
}
|
|
101
|
+
break;
|
|
102
|
+
case "uniqueidentifier":
|
|
103
|
+
parameter.SqlDbType = SqlDbType.UniqueIdentifier;
|
|
104
|
+
if (!isNull) value = Guid.ParseExact(RequireString(), "D");
|
|
105
|
+
break;
|
|
106
|
+
case "date":
|
|
107
|
+
parameter.SqlDbType = SqlDbType.Date;
|
|
108
|
+
if (!isNull) value = DateTime.ParseExact(RequireString(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
|
|
109
|
+
break;
|
|
110
|
+
case "datetime2":
|
|
111
|
+
parameter.SqlDbType = SqlDbType.DateTime2;
|
|
112
|
+
parameter.Scale = 7;
|
|
113
|
+
if (!isNull) value = DateTime.ParseExact(RequireString(), new[] { "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.FFFFFFF" }, CultureInfo.InvariantCulture, DateTimeStyles.None);
|
|
114
|
+
break;
|
|
115
|
+
default: throw new ArgumentException("Unsupported parameter type: " + Type + ".");
|
|
116
|
+
}
|
|
117
|
+
parameter.Value = value;
|
|
118
|
+
return parameter;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
private string RequireString()
|
|
122
|
+
{
|
|
123
|
+
if (Value.ValueKind != JsonValueKind.String) throw new ArgumentException(Type + " parameters must use JSON strings.");
|
|
124
|
+
return Value.GetString()!;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
private static bool AsciiLetter(char value) => value >= 'A' && value <= 'Z' || value >= 'a' && value <= 'z';
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -37,11 +37,17 @@ namespace D365MetadataBridge
|
|
|
37
37
|
private static string? _binPath = null; // Explicit bin path (UDE: microsoftPackagesPath/bin)
|
|
38
38
|
private static string _xrefServer = "localhost";
|
|
39
39
|
private static string _xrefDatabase = string.Empty;
|
|
40
|
+
private static readonly Models.AxDbSqlOptions AxDbOptions = new Models.AxDbSqlOptions();
|
|
40
41
|
private static string? _logFile = null;
|
|
41
42
|
private static readonly TextWriter Log = Console.Error;
|
|
42
43
|
|
|
43
44
|
static async Task<int> Main(string[] args)
|
|
44
45
|
{
|
|
46
|
+
// A separate one-shot mode: analyse an ETW capture and exit. It runs in its own process
|
|
47
|
+
// (started by the MCP server), so a multi-minute analysis never holds the bridge.
|
|
48
|
+
if (args.Length > 0 && args[0] == "--analyze-trace")
|
|
49
|
+
return Services.Trace.TraceAnalysisCommand.Run(args);
|
|
50
|
+
|
|
45
51
|
// Parse command-line arguments — NO D365FO type references allowed here!
|
|
46
52
|
for (int i = 0; i < args.Length; i++)
|
|
47
53
|
{
|
|
@@ -65,6 +71,25 @@ namespace D365MetadataBridge
|
|
|
65
71
|
case "--log-file" when i + 1 < args.Length:
|
|
66
72
|
_logFile = args[++i];
|
|
67
73
|
break;
|
|
74
|
+
case "--axdb-server" when i + 1 < args.Length:
|
|
75
|
+
AxDbOptions.Server = args[++i];
|
|
76
|
+
break;
|
|
77
|
+
case "--axdb-database" when i + 1 < args.Length:
|
|
78
|
+
AxDbOptions.Database = args[++i];
|
|
79
|
+
break;
|
|
80
|
+
case "--axdb-trust-certificate":
|
|
81
|
+
AxDbOptions.TrustCertificate = true;
|
|
82
|
+
break;
|
|
83
|
+
case "--axdb-timeout" when i + 1 < args.Length:
|
|
84
|
+
if (!int.TryParse(args[++i], out var timeout) || timeout < 1 || timeout > 30)
|
|
85
|
+
{ Log.WriteLine("[FATAL] --axdb-timeout must be 1..30 seconds."); return 1; }
|
|
86
|
+
AxDbOptions.TimeoutSeconds = timeout;
|
|
87
|
+
break;
|
|
88
|
+
case "--axdb-max-rows" when i + 1 < args.Length:
|
|
89
|
+
if (!int.TryParse(args[++i], out var maxRows) || maxRows < 1 || maxRows > 1000)
|
|
90
|
+
{ Log.WriteLine("[FATAL] --axdb-max-rows must be 1..1000."); return 1; }
|
|
91
|
+
AxDbOptions.MaxRows = maxRows;
|
|
92
|
+
break;
|
|
68
93
|
case "--help":
|
|
69
94
|
PrintUsage();
|
|
70
95
|
return 0;
|
|
@@ -147,7 +172,8 @@ namespace D365MetadataBridge
|
|
|
147
172
|
}
|
|
148
173
|
|
|
149
174
|
// Create request dispatcher
|
|
150
|
-
var
|
|
175
|
+
var axdbService = new Services.AxDbSqlService(AxDbOptions);
|
|
176
|
+
var dispatcher = new RequestDispatcher(metadataService, writeService, xrefService, axdbService);
|
|
151
177
|
|
|
152
178
|
// Send ready signal
|
|
153
179
|
var readyResponse = new BridgeResponse
|
|
@@ -160,7 +186,8 @@ namespace D365MetadataBridge
|
|
|
160
186
|
packagesPath = _packagesPath,
|
|
161
187
|
referencePackagesPath = _referencePackagesPath,
|
|
162
188
|
metadataAvailable = metadataService != null,
|
|
163
|
-
xrefAvailable = xrefService != null
|
|
189
|
+
xrefAvailable = xrefService != null,
|
|
190
|
+
axdbSqlAvailable = axdbService.Enabled
|
|
164
191
|
})
|
|
165
192
|
};
|
|
166
193
|
await WriteResponse(readyResponse);
|
|
@@ -522,6 +549,9 @@ D365 Metadata Bridge — stdin/stdout JSON protocol for D365FO metadata access
|
|
|
522
549
|
|
|
523
550
|
Usage:
|
|
524
551
|
D365MetadataBridge.exe [options]
|
|
552
|
+
D365MetadataBridge.exe --analyze-trace <file.etl> --out <result.json> [--focus A;B] [--pid N]
|
|
553
|
+
[--scope thread|subtree] [--top N] [--repeat N] [--progress <file>]
|
|
554
|
+
One-shot: analyse an ETW capture (X++ and SQL time) and exit.
|
|
525
555
|
|
|
526
556
|
Options:
|
|
527
557
|
--packages-path <path> Path to primary PackagesLocalDirectory (required; the server detects it per machine)
|
|
@@ -532,6 +562,11 @@ Options:
|
|
|
532
562
|
--xref-server <server> SQL Server for cross-reference DB (default: localhost)
|
|
533
563
|
--xref-database <db> Cross-reference database name, e.g. DYNAMICSXREFDB
|
|
534
564
|
(no default: without it cross-references are off)
|
|
565
|
+
--axdb-server <server> Enable separate, lazy, read-only AxDB SQL debug access (Windows integrated authentication)
|
|
566
|
+
--axdb-database <db> SQL debug database (default: AxDB)
|
|
567
|
+
--axdb-trust-certificate Trust the SQL certificate (encryption remains enabled)
|
|
568
|
+
--axdb-timeout <seconds> Per-command timeout, 1..30 (default: 30)
|
|
569
|
+
--axdb-max-rows <rows> Default SQL query row cap, 1..1000 (default: 100)
|
|
535
570
|
--log-file <path> Write all diagnostic logs to this file (append mode)
|
|
536
571
|
--help Show this help
|
|
537
572
|
|
|
@@ -15,12 +15,14 @@ namespace D365MetadataBridge.Protocol
|
|
|
15
15
|
private readonly MetadataReadService? _metadataService;
|
|
16
16
|
private readonly MetadataWriteService? _writeService;
|
|
17
17
|
private readonly CrossReferenceService? _xrefService;
|
|
18
|
+
private readonly AxDbSqlService _axdbService;
|
|
18
19
|
|
|
19
|
-
public RequestDispatcher(MetadataReadService? metadataService, MetadataWriteService? writeService, CrossReferenceService? xrefService)
|
|
20
|
+
public RequestDispatcher(MetadataReadService? metadataService, MetadataWriteService? writeService, CrossReferenceService? xrefService, AxDbSqlService? axdbService = null)
|
|
20
21
|
{
|
|
21
22
|
_metadataService = metadataService;
|
|
22
23
|
_writeService = writeService;
|
|
23
24
|
_xrefService = xrefService;
|
|
25
|
+
_axdbService = axdbService ?? new AxDbSqlService(new AxDbSqlOptions());
|
|
24
26
|
}
|
|
25
27
|
|
|
26
28
|
public Task<BridgeResponse> Dispatch(BridgeRequest request)
|
|
@@ -33,6 +35,12 @@ namespace D365MetadataBridge.Protocol
|
|
|
33
35
|
case "ping":
|
|
34
36
|
return Task.FromResult(BridgeResponse.CreateSuccess(request.Id, "pong"));
|
|
35
37
|
|
|
38
|
+
// Standalone, read-only AxDB SQL debug operations; they never touch the metadata provider.
|
|
39
|
+
case "axdbstatus":
|
|
40
|
+
case "axdbschema":
|
|
41
|
+
case "axdbquery":
|
|
42
|
+
return HandleAxDb(request);
|
|
43
|
+
|
|
36
44
|
// === Metadata Read ===
|
|
37
45
|
case "readtable":
|
|
38
46
|
return HandleMetadata(request, () =>
|
|
@@ -266,6 +274,7 @@ namespace D365MetadataBridge.Protocol
|
|
|
266
274
|
metadataAvailable = _metadataService != null,
|
|
267
275
|
xrefAvailable = _xrefService != null,
|
|
268
276
|
writeAvailable = _writeService != null,
|
|
277
|
+
axdbSqlAvailable = _axdbService.Enabled,
|
|
269
278
|
capabilities = new[]
|
|
270
279
|
{
|
|
271
280
|
"ping", "readTable", "readClass", "readEnum", "readEdt",
|
|
@@ -282,7 +291,7 @@ namespace D365MetadataBridge.Protocol
|
|
|
282
291
|
"setProperty", "replaceCode",
|
|
283
292
|
"getCapabilities", "discoverFormPatterns",
|
|
284
293
|
"findExtensionClasses", "findEventSubscribers", "findApiUsageCallers"
|
|
285
|
-
}
|
|
294
|
+
}.Concat(_axdbService.Enabled ? new[] { "axdbSql", "axdbStatus", "axdbSchema", "axdbQuery" } : Array.Empty<string>()).ToArray()
|
|
286
295
|
}));
|
|
287
296
|
|
|
288
297
|
// === Write-support (validate / resolve / refresh) ===
|
|
@@ -813,6 +822,12 @@ namespace D365MetadataBridge.Protocol
|
|
|
813
822
|
}
|
|
814
823
|
}
|
|
815
824
|
|
|
825
|
+
private async Task<BridgeResponse> HandleAxDb(BridgeRequest request)
|
|
826
|
+
{
|
|
827
|
+
var result = await _axdbService.Handle(request.Method, request.Params).ConfigureAwait(false);
|
|
828
|
+
return BridgeResponse.CreateSuccess(request.Id, result);
|
|
829
|
+
}
|
|
830
|
+
|
|
816
831
|
/// <summary>
|
|
817
832
|
/// Methods that only READ metadata, and may therefore run concurrently with
|
|
818
833
|
/// each other.
|
|
@@ -845,6 +860,9 @@ namespace D365MetadataBridge.Protocol
|
|
|
845
860
|
// Cross-reference queries
|
|
846
861
|
"findreferences", "findeventsubscribers", "findextensionclasses",
|
|
847
862
|
"findapiusagecallers", "samplexrefrows",
|
|
863
|
+
// AxDB SQL: its own connection per call, no metadata provider, read-only. A query may
|
|
864
|
+
// run up to its 45 s budget; exclusive, it would hold every metadata call behind it.
|
|
865
|
+
"axdbstatus", "axdbschema", "axdbquery",
|
|
848
866
|
};
|
|
849
867
|
|
|
850
868
|
/// <summary>True when <paramref name="method"/> may run alongside other reads.</summary>
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
using System;
|
|
2
|
+
using System.Collections;
|
|
3
|
+
using System.Collections.Generic;
|
|
4
|
+
using System.IO;
|
|
5
|
+
using System.Linq;
|
|
6
|
+
using Microsoft.SqlServer.TransactSql.ScriptDom;
|
|
7
|
+
|
|
8
|
+
namespace D365MetadataBridge.Services
|
|
9
|
+
{
|
|
10
|
+
public sealed class AxDbTableReference
|
|
11
|
+
{
|
|
12
|
+
public string Schema { get; set; } = "dbo";
|
|
13
|
+
public string Table { get; set; } = "";
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/// <summary>
|
|
17
|
+
/// Conservative AST validation: exactly one SELECT. This is the FIRST guard, not the only one —
|
|
18
|
+
/// on a dev VM the MCP account is normally sysadmin, so SQL permissions restrict nothing, and
|
|
19
|
+
/// AxDbSqlService runs every statement in a transaction it always rolls back (the second guard).
|
|
20
|
+
/// </summary>
|
|
21
|
+
public static class AxDbSqlPolicy
|
|
22
|
+
{
|
|
23
|
+
private static readonly HashSet<string> Functions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
|
24
|
+
{
|
|
25
|
+
"COUNT", "COUNT_BIG", "SUM", "AVG", "MIN", "MAX", "ABS", "ROUND", "CEILING", "FLOOR",
|
|
26
|
+
"LEN", "DATALENGTH", "LOWER", "UPPER", "LTRIM", "RTRIM", "TRIM", "LEFT", "RIGHT", "SUBSTRING",
|
|
27
|
+
"REPLACE", "CONCAT", "CONCAT_WS", "CHARINDEX", "PATINDEX", "ISNULL", "NULLIF", "COALESCE",
|
|
28
|
+
"GETDATE", "GETUTCDATE", "SYSDATETIME", "SYSUTCDATETIME", "DATEADD", "DATEDIFF", "DATEDIFF_BIG",
|
|
29
|
+
"DATEPART", "DATENAME", "YEAR", "MONTH", "DAY", "EOMONTH", "ROW_NUMBER", "RANK", "DENSE_RANK",
|
|
30
|
+
"LAG", "LEAD", "FIRST_VALUE", "LAST_VALUE", "STRING_AGG", "STDEV", "STDEVP", "VAR", "VARP",
|
|
31
|
+
"COLLATIONPROPERTY", "DATABASEPROPERTYEX", "DB_NAME"
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
public static IReadOnlyList<AxDbTableReference> Validate(string sql)
|
|
35
|
+
{
|
|
36
|
+
if (string.IsNullOrWhiteSpace(sql) || sql.Length > 65536)
|
|
37
|
+
throw new ArgumentException("SQL must contain 1..65536 characters.");
|
|
38
|
+
var parser = new TSql160Parser(true);
|
|
39
|
+
var script = (TSqlScript)parser.Parse(new StringReader(sql), out var errors);
|
|
40
|
+
if (errors.Count != 0) throw new ArgumentException("Invalid SQL: " + errors[0].Message);
|
|
41
|
+
if (script.Batches.Count != 1 || script.Batches[0].Statements.Count != 1)
|
|
42
|
+
throw new ArgumentException("Exactly one SQL statement is required per item; batches are not allowed.");
|
|
43
|
+
var statement = script.Batches[0].Statements[0];
|
|
44
|
+
if (!(statement is SelectStatement))
|
|
45
|
+
throw new ArgumentException("Only SELECT is allowed.");
|
|
46
|
+
|
|
47
|
+
var nodes = Walk(statement).ToList();
|
|
48
|
+
// Exact spelling is conservative across both case-sensitive and case-insensitive database collations.
|
|
49
|
+
// A case-folded match could hide a distinct physical table on a case-sensitive database.
|
|
50
|
+
var cteList = ((SelectStatement)statement).WithCtesAndXmlNamespaces?.CommonTableExpressions?.ToList()
|
|
51
|
+
?? new List<CommonTableExpression>();
|
|
52
|
+
var ctes = new HashSet<string>(cteList.Select(c => c.ExpressionName.Value), StringComparer.Ordinal);
|
|
53
|
+
// A CTE name is in scope only for the CTEs AFTER it (and its own body, for
|
|
54
|
+
// recursion) and for the main query. Inside an earlier CTE body the same name
|
|
55
|
+
// resolves to the real object: `WITH a AS (SELECT * FROM syslogins),
|
|
56
|
+
// syslogins AS (SELECT 1 x) SELECT * FROM a` reads the server's logins. So a
|
|
57
|
+
// reference inside CTE i sees only CTEs 0..i; anything else goes to the
|
|
58
|
+
// catalog check like any other table.
|
|
59
|
+
var cteScope = new Dictionary<NamedTableReference, HashSet<string>>(ReferenceComparer.Instance);
|
|
60
|
+
for (var i = 0; i < cteList.Count; i++)
|
|
61
|
+
{
|
|
62
|
+
var visible = new HashSet<string>(cteList.Take(i + 1).Select(c => c.ExpressionName.Value), StringComparer.Ordinal);
|
|
63
|
+
foreach (var reference in Walk(cteList[i].QueryExpression).OfType<NamedTableReference>())
|
|
64
|
+
if (!cteScope.ContainsKey(reference)) cteScope[reference] = visible;
|
|
65
|
+
}
|
|
66
|
+
var tables = new List<AxDbTableReference>();
|
|
67
|
+
foreach (var node in nodes)
|
|
68
|
+
{
|
|
69
|
+
var kind = node.GetType().Name;
|
|
70
|
+
if (node is TSqlStatement nested && nested != statement)
|
|
71
|
+
throw new ArgumentException("Nested SQL statements are not supported.");
|
|
72
|
+
if (node is SelectStatement select && select.Into != null)
|
|
73
|
+
throw new ArgumentException("SELECT INTO is not allowed.");
|
|
74
|
+
if (kind == "OutputClause" || kind == "OutputIntoClause" || kind == "ExecuteInsertSource" ||
|
|
75
|
+
kind == "NextValueForExpression" || kind == "SelectSetVariable" || kind.EndsWith("ForClause", StringComparison.Ordinal) ||
|
|
76
|
+
node is TableHint || node is OptimizerHint || node is UserDataTypeReference)
|
|
77
|
+
throw new ArgumentException("Unsupported SQL construct: " + kind + ".");
|
|
78
|
+
if (node is FunctionCall function && (function.CallTarget != null || !Functions.Contains(function.FunctionName.Value)))
|
|
79
|
+
throw new ArgumentException("Only supported built-in SQL functions are allowed.");
|
|
80
|
+
if (kind == "UserDefinedTypeCallTarget" || kind == "MultiPartIdentifierCallTarget")
|
|
81
|
+
throw new ArgumentException("User-defined methods are not allowed.");
|
|
82
|
+
if (node is TableReference && !(node is NamedTableReference || node is QueryDerivedTable ||
|
|
83
|
+
node is QualifiedJoin || node is UnqualifiedJoin || node is JoinParenthesisTableReference || node is InlineDerivedTable))
|
|
84
|
+
throw new ArgumentException("Unsupported table source: " + kind + ".");
|
|
85
|
+
if (node is NamedTableReference table)
|
|
86
|
+
{
|
|
87
|
+
var name = table.SchemaObject;
|
|
88
|
+
if (name.Identifiers.Count > 2 || name.Identifiers.Count == 0 || name.BaseIdentifier.Value.StartsWith("#", StringComparison.Ordinal))
|
|
89
|
+
throw new ArgumentException("Only local database tables and CTEs are allowed.");
|
|
90
|
+
var inScope = cteScope.TryGetValue(table, out var visibleCtes) ? visibleCtes : ctes;
|
|
91
|
+
if (name.Identifiers.Count == 1 && inScope.Contains(name.BaseIdentifier.Value)) continue;
|
|
92
|
+
// Empty schema means SQL's normal default-schema resolution, not an assumed dbo object.
|
|
93
|
+
tables.Add(new AxDbTableReference { Schema = name.SchemaIdentifier?.Value ?? "", Table = name.BaseIdentifier.Value });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return tables;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private sealed class ReferenceComparer : IEqualityComparer<NamedTableReference>
|
|
100
|
+
{
|
|
101
|
+
public static readonly ReferenceComparer Instance = new ReferenceComparer();
|
|
102
|
+
public bool Equals(NamedTableReference x, NamedTableReference y) => ReferenceEquals(x, y);
|
|
103
|
+
public int GetHashCode(NamedTableReference obj) => System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Reflection walks only AST children, not tokens/parents. This also sees constructs nested in expressions/CTEs.
|
|
107
|
+
private static IEnumerable<TSqlFragment> Walk(TSqlFragment root)
|
|
108
|
+
{
|
|
109
|
+
yield return root;
|
|
110
|
+
foreach (var property in root.GetType().GetProperties())
|
|
111
|
+
{
|
|
112
|
+
if (property.GetIndexParameters().Length != 0 || property.Name == "ScriptTokenStream") continue;
|
|
113
|
+
if (typeof(TSqlFragment).IsAssignableFrom(property.PropertyType))
|
|
114
|
+
{
|
|
115
|
+
if (property.GetValue(root) is TSqlFragment child)
|
|
116
|
+
foreach (var node in Walk(child)) yield return node;
|
|
117
|
+
}
|
|
118
|
+
else if (property.PropertyType.IsGenericType && typeof(IEnumerable).IsAssignableFrom(property.PropertyType) &&
|
|
119
|
+
typeof(TSqlFragment).IsAssignableFrom(property.PropertyType.GetGenericArguments()[0]))
|
|
120
|
+
{
|
|
121
|
+
if (property.GetValue(root) is IEnumerable children)
|
|
122
|
+
foreach (TSqlFragment child in children)
|
|
123
|
+
foreach (var node in Walk(child)) yield return node;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|