d365fo-mcp 1.19.1 → 1.21.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.
Files changed (172) hide show
  1. package/README.md +5 -3
  2. package/bridge/D365MetadataBridge/D365MetadataBridge.csproj +71 -0
  3. package/bridge/D365MetadataBridge/Models/AxDbSqlModels.cs +129 -0
  4. package/bridge/D365MetadataBridge/Models/Models.cs +7 -0
  5. package/bridge/D365MetadataBridge/Program.cs +37 -2
  6. package/bridge/D365MetadataBridge/Protocol/RequestDispatcher.cs +20 -2
  7. package/bridge/D365MetadataBridge/Services/AccessGrantText.cs +88 -0
  8. package/bridge/D365MetadataBridge/Services/AxDbSqlPolicy.cs +128 -0
  9. package/bridge/D365MetadataBridge/Services/AxDbSqlService.cs +391 -0
  10. package/bridge/D365MetadataBridge/Services/MetadataReadService.cs +2 -0
  11. package/bridge/D365MetadataBridge/Services/MetadataWriteService.cs +118 -10
  12. package/bridge/D365MetadataBridge/Services/Trace/EtlTraceReader.cs +123 -0
  13. package/bridge/D365MetadataBridge/Services/Trace/TraceAnalysisCommand.cs +114 -0
  14. package/bridge/D365MetadataBridge/Services/Trace/XppTraceAggregator.cs +613 -0
  15. package/dist/bridge/bridgeAdapter.js +14 -0
  16. package/dist/bridge/bridgeClient.d.ts +20 -0
  17. package/dist/bridge/bridgeClient.js +47 -10
  18. package/dist/bridge/bridgeReadiness.js +2 -0
  19. package/dist/bridge/bridgeTypes.d.ts +6 -0
  20. package/dist/cli/aosWebConfig.d.ts +19 -0
  21. package/dist/cli/aosWebConfig.js +46 -0
  22. package/dist/cli/bridgeSources.d.ts +13 -0
  23. package/dist/cli/bridgeSources.js +68 -0
  24. package/dist/cli/commands/config.js +14 -0
  25. package/dist/cli/commands/doctor.d.ts +30 -1
  26. package/dist/cli/commands/doctor.js +127 -6
  27. package/dist/cli/commands/instance.js +6 -3
  28. package/dist/cli/commands/setup.js +16 -6
  29. package/dist/cli/commands/update.d.ts +15 -6
  30. package/dist/cli/commands/update.js +26 -7
  31. package/dist/cli/context.d.ts +7 -6
  32. package/dist/cli/context.js +11 -7
  33. package/dist/cli/settingsPrompt.d.ts +7 -0
  34. package/dist/cli/settingsPrompt.js +26 -5
  35. package/dist/cli/sqlEnvironmentSetup.d.ts +3 -0
  36. package/dist/cli/sqlEnvironmentSetup.js +23 -0
  37. package/dist/cli/sqlSetup.d.ts +12 -0
  38. package/dist/cli/sqlSetup.js +45 -0
  39. package/dist/cli/ui.d.ts +1 -0
  40. package/dist/cli/ui.js +6 -1
  41. package/dist/config/axdbSql.d.ts +11 -0
  42. package/dist/config/axdbSql.js +22 -0
  43. package/dist/config/settings.d.ts +3 -1
  44. package/dist/config/settings.js +41 -10
  45. package/dist/config/sqlSettings.d.ts +3 -0
  46. package/dist/config/sqlSettings.js +17 -0
  47. package/dist/config/trace.d.ts +14 -0
  48. package/dist/config/trace.js +53 -0
  49. package/dist/config/traceSettings.d.ts +3 -0
  50. package/dist/config/traceSettings.js +16 -0
  51. package/dist/index.js +19 -0
  52. package/dist/metadata/modelDescriptor.d.ts +6 -15
  53. package/dist/metadata/modelDescriptor.js +6 -23
  54. package/dist/prompts/systemInstructions.js +9 -0
  55. package/dist/scripts/build-database.js +149 -13
  56. package/dist/scripts/build-fts.js +149 -13
  57. package/dist/scripts/extract-metadata.js +149 -13
  58. package/dist/server/mcpServer.js +2 -3
  59. package/dist/server/serverMode.d.ts +8 -15
  60. package/dist/server/serverMode.js +17 -6
  61. package/dist/server/toolAnnotations.js +2 -0
  62. package/dist/server/toolSchemas/axdbSql.d.ts +15 -0
  63. package/dist/server/toolSchemas/axdbSql.js +12 -0
  64. package/dist/server/toolSchemas/buildD365foProject.js +1 -1
  65. package/dist/server/toolSchemas/d365foFile.js +2 -2
  66. package/dist/server/toolSchemas/index.d.ts +13 -327
  67. package/dist/server/toolSchemas/index.js +4 -0
  68. package/dist/server/toolSchemas/labels.js +1 -1
  69. package/dist/server/toolSchemas/traceD365fo.d.ts +15 -0
  70. package/dist/server/toolSchemas/traceD365fo.js +12 -0
  71. package/dist/tools/analysis/findReferences.js +35 -8
  72. package/dist/tools/analysis/prefixDiagnostics.js +20 -9
  73. package/dist/tools/analysis/validateObjectNaming.js +5 -2
  74. package/dist/tools/d365foFile.d.ts +2 -1
  75. package/dist/tools/d365foFile.js +10 -5
  76. package/dist/tools/knowledge/xppKnowledge.js +1 -0
  77. package/dist/tools/labels.js +1 -1
  78. package/dist/tools/prepare/prepareCreate.js +12 -2
  79. package/dist/tools/readers/getWorkspaceInfo.js +40 -8
  80. package/dist/tools/readers/tableInfo.js +22 -12
  81. package/dist/tools/responseCaps.js +2 -0
  82. package/dist/tools/sdlc/aosWebConfig.js +1 -9
  83. package/dist/tools/sdlc/axdbSql/contract.d.ts +155 -0
  84. package/dist/tools/sdlc/axdbSql/contract.js +69 -0
  85. package/dist/tools/sdlc/axdbSql/output.d.ts +3 -0
  86. package/dist/tools/sdlc/axdbSql/output.js +22 -0
  87. package/dist/tools/sdlc/axdbSql.d.ts +16 -0
  88. package/dist/tools/sdlc/axdbSql.js +37 -0
  89. package/dist/tools/sdlc/buildProject.d.ts +7 -9
  90. package/dist/tools/sdlc/buildProject.js +137 -194
  91. package/dist/tools/sdlc/sysTestRunner.d.ts +2 -2
  92. package/dist/tools/sdlc/sysTestRunner.js +2 -5
  93. package/dist/tools/sdlc/trace/analysis.d.ts +34 -0
  94. package/dist/tools/sdlc/trace/analysis.js +124 -0
  95. package/dist/tools/sdlc/trace/capture.d.ts +98 -0
  96. package/dist/tools/sdlc/trace/capture.js +230 -0
  97. package/dist/tools/sdlc/trace/contract.d.ts +83 -0
  98. package/dist/tools/sdlc/trace/contract.js +78 -0
  99. package/dist/tools/sdlc/traceD365fo.d.ts +13 -0
  100. package/dist/tools/sdlc/traceD365fo.js +232 -0
  101. package/dist/tools/smart/codeGen.js +26 -14
  102. package/dist/tools/smart/generateSmartForm.js +1 -1
  103. package/dist/tools/smart/generateSmartReport.js +1 -1
  104. package/dist/tools/smart/generateSmartTable.js +21 -2
  105. package/dist/tools/specs/d365foFileOpSpecs.js +99 -26
  106. package/dist/tools/specs/labelsOpSpecs.js +2 -1
  107. package/dist/tools/toolHandler.js +7 -6
  108. package/dist/tools/write/compileLabels.d.ts +3 -3
  109. package/dist/tools/write/compileLabels.js +37 -16
  110. package/dist/tools/write/createD365File.js +122 -15
  111. package/dist/tools/write/createLabel.js +158 -15
  112. package/dist/tools/write/dataEntityOps.d.ts +39 -0
  113. package/dist/tools/write/dataEntityOps.js +108 -0
  114. package/dist/tools/write/deleteD365File.js +4 -0
  115. package/dist/tools/write/directXmlWriters.d.ts +125 -1
  116. package/dist/tools/write/directXmlWriters.js +442 -5
  117. package/dist/tools/write/modifyBackup.d.ts +64 -0
  118. package/dist/tools/write/modifyBackup.js +145 -0
  119. package/dist/tools/write/modifyD365File.d.ts +6 -26
  120. package/dist/tools/write/modifyD365File.js +127 -126
  121. package/dist/tools/write/renameLabel.js +125 -25
  122. package/dist/tools/xml/createTablePropertyHonesty.js +49 -3
  123. package/dist/tools/xml/dataEntityViewEdit.d.ts +74 -0
  124. package/dist/tools/xml/dataEntityViewEdit.js +272 -0
  125. package/dist/tools/xml/dataEntityXml.d.ts +11 -0
  126. package/dist/tools/xml/dataEntityXml.js +63 -11
  127. package/dist/tools/xml/tableFieldPropertyEdit.d.ts +45 -0
  128. package/dist/tools/xml/tableFieldPropertyEdit.js +129 -0
  129. package/dist/tools/xml/tableXml.d.ts +6 -0
  130. package/dist/tools/xml/tableXml.js +13 -0
  131. package/dist/tools/xml/xmlTemplateGenerator.js +5 -1
  132. package/dist/utils/appSettings.d.ts +20 -0
  133. package/dist/utils/appSettings.js +58 -0
  134. package/dist/utils/axTablePropertyOrder.d.ts +10 -1
  135. package/dist/utils/axTablePropertyOrder.js +28 -1
  136. package/dist/utils/callDedup.js +2 -0
  137. package/dist/utils/configManager.d.ts +46 -2
  138. package/dist/utils/configManager.js +154 -26
  139. package/dist/utils/crossModelWriteGuard.d.ts +5 -0
  140. package/dist/utils/crossModelWriteGuard.js +7 -5
  141. package/dist/utils/effectivePrefix.js +14 -8
  142. package/dist/utils/formControlPlacement.d.ts +84 -0
  143. package/dist/utils/formControlPlacement.js +308 -0
  144. package/dist/utils/formControlPropertyXml.d.ts +54 -0
  145. package/dist/utils/formControlPropertyXml.js +187 -0
  146. package/dist/utils/formExtensionControlXml.d.ts +25 -0
  147. package/dist/utils/formExtensionControlXml.js +1 -1
  148. package/dist/utils/formMetadataNamespace.d.ts +29 -0
  149. package/dist/utils/formMetadataNamespace.js +134 -0
  150. package/dist/utils/indexedXmlLookup.d.ts +13 -12
  151. package/dist/utils/indexedXmlLookup.js +147 -33
  152. package/dist/utils/loadEnv.js +9 -0
  153. package/dist/utils/metadataResolver.d.ts +5 -0
  154. package/dist/utils/metadataResolver.js +19 -8
  155. package/dist/utils/modelClassifier.d.ts +110 -4
  156. package/dist/utils/modelClassifier.js +242 -18
  157. package/dist/utils/modelPrefixInference.js +4 -1
  158. package/dist/utils/objectNaming.d.ts +17 -1
  159. package/dist/utils/objectNaming.js +38 -5
  160. package/dist/utils/objectNamingRules.d.ts +1 -0
  161. package/dist/utils/objectNamingRules.js +100 -27
  162. package/dist/utils/pathContainment.js +14 -1
  163. package/dist/utils/smartXmlBuilder.js +3 -0
  164. package/dist/utils/subscriberAccessLevel.d.ts +87 -0
  165. package/dist/utils/subscriberAccessLevel.js +251 -0
  166. package/dist/utils/symbolLookup.js +12 -1
  167. package/dist/utils/toolProgressMessage.js +9 -0
  168. package/dist/validation/formControlElementOrder.d.ts +2 -0
  169. package/dist/validation/formControlElementOrder.js +11 -2
  170. package/dist/workspace/projectFile.d.ts +12 -1
  171. package/dist/workspace/projectFile.js +22 -2
  172. package/package.json +1 -1
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  <div align="center">
4
4
 
5
- **20 AI tools that know every X++ class, table, form, and EDT in your D365FO codebase**
5
+ **22 AI tools that know every X++ class, table, form, and EDT in your D365FO codebase**
6
6
 
7
7
  [![npm](https://img.shields.io/npm/v/d365fo-mcp.svg?logo=npm&color=cb3837)](https://www.npmjs.com/package/d365fo-mcp)
8
8
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](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 20 specialized MCP tools. Every signature, every CoC wrapper, every label, every form pattern — verified against your real metadata **before** the AI writes a single line.
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
  ![Solution Architecture](docs/img/solution-architecture-diagram.svg)
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 20 tools](docs/MCP_TOOLS.md) | [Azure deployment](docs/SETUP_AZURE.md) |
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
+ }
@@ -36,6 +36,13 @@ namespace D365MetadataBridge.Models
36
36
  [JsonPropertyName("saveDataPerCompany")]
37
37
  public string? SaveDataPerCompany { get; set; }
38
38
 
39
+ /// <summary>"Read=Allow, Create=Deny" — the set permissions; null when none are.</summary>
40
+ [JsonPropertyName("subscriberAccessLevel")]
41
+ public string? SubscriberAccessLevel { get; set; }
42
+
43
+ [JsonPropertyName("allowRowVersionChangeTracking")]
44
+ public string? AllowRowVersionChangeTracking { get; set; }
45
+
39
46
  [JsonPropertyName("extends")]
40
47
  public string? Extends { get; set; }
41
48
 
@@ -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 dispatcher = new RequestDispatcher(metadataService, writeService, xrefService);
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,88 @@
1
+ using System;
2
+ using System.Collections.Generic;
3
+ using Microsoft.Dynamics.AX.Metadata.Core.MetaModel;
4
+
5
+ namespace D365MetadataBridge.Services
6
+ {
7
+ /// <summary>
8
+ /// Text form of an AccessGrant — AxTable.SubscriberAccessLevel, "Subscriber access
9
+ /// level" in Visual Studio. Six permissions, each Unset/Allow/Deny; the serializer
10
+ /// writes only the set ones, as child elements. AccessGrant is a STRUCT: change a
11
+ /// copy and assign it back, or the change is lost.
12
+ /// </summary>
13
+ internal static class AccessGrantText
14
+ {
15
+ private static readonly string[] Permissions = { "Correct", "Create", "Delete", "Invoke", "Read", "Update" };
16
+
17
+ /// <summary>"Create=Deny, Read=Allow" for the set permissions; null when none are.</summary>
18
+ public static string? Describe(AccessGrant grant)
19
+ {
20
+ var parts = new List<string>();
21
+ foreach (var name in Permissions)
22
+ {
23
+ var value = Get(grant, name);
24
+ if (value != AccessGrantPermission.Unset) parts.Add($"{name}={value}");
25
+ }
26
+ return parts.Count > 0 ? string.Join(", ", parts) : null;
27
+ }
28
+
29
+ /// <summary>
30
+ /// Parse "Read=Allow,Create=Deny", a bare list "Read,Update" (Allow), or "None".
31
+ /// Permissions not named are Unset. Throws ArgumentException on anything else.
32
+ /// </summary>
33
+ public static AccessGrant Parse(string? text)
34
+ {
35
+ var grant = new AccessGrant();
36
+ var s = (text ?? "").Trim();
37
+ if (s.Length == 0 || s.Equals("None", StringComparison.OrdinalIgnoreCase)
38
+ || s.Equals("Unset", StringComparison.OrdinalIgnoreCase))
39
+ return grant;
40
+
41
+ foreach (var raw in s.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries))
42
+ {
43
+ var pair = raw.Split(new[] { '=', ':' }, 2);
44
+ var key = pair[0].Trim();
45
+ var name = Array.Find(Permissions, p => p.Equals(key, StringComparison.OrdinalIgnoreCase))
46
+ ?? throw new ArgumentException(
47
+ $"Unknown subscriber permission '{key}'. Permissions: {string.Join(", ", Permissions)}; " +
48
+ "values: Allow, Deny, Unset. Example: \"Read=Allow,Create=Deny\", or \"None\".");
49
+ var valueText = pair.Length > 1 ? pair[1].Trim() : "Allow";
50
+ if (!Enum.TryParse<AccessGrantPermission>(valueText, true, out var value) || !Enum.IsDefined(typeof(AccessGrantPermission), value))
51
+ throw new ArgumentException(
52
+ $"Invalid value '{valueText}' for subscriber permission {name}. Values: Allow, Deny, Unset.");
53
+ grant = Set(grant, name, value);
54
+ }
55
+ return grant;
56
+ }
57
+
58
+ /// <summary>What Visual Studio sets on a new regular table: Read=Allow.</summary>
59
+ public static AccessGrant VisualStudioDefault() => Set(new AccessGrant(), "Read", AccessGrantPermission.Allow);
60
+
61
+ private static AccessGrantPermission Get(AccessGrant g, string name)
62
+ {
63
+ switch (name)
64
+ {
65
+ case "Correct": return g.Correct;
66
+ case "Create": return g.Create;
67
+ case "Delete": return g.Delete;
68
+ case "Invoke": return g.Invoke;
69
+ case "Read": return g.Read;
70
+ default: return g.Update;
71
+ }
72
+ }
73
+
74
+ private static AccessGrant Set(AccessGrant g, string name, AccessGrantPermission value)
75
+ {
76
+ switch (name)
77
+ {
78
+ case "Correct": g.Correct = value; break;
79
+ case "Create": g.Create = value; break;
80
+ case "Delete": g.Delete = value; break;
81
+ case "Invoke": g.Invoke = value; break;
82
+ case "Read": g.Read = value; break;
83
+ default: g.Update = value; break;
84
+ }
85
+ return g;
86
+ }
87
+ }
88
+ }
@@ -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
+ }