@memberjunction/codegen-lib 6.2.0-edge.0 → 6.2.0-edge.2

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 (222) hide show
  1. package/README.md +25 -23
  2. package/dist/Angular/angular-codegen.d.ts +6 -0
  3. package/dist/Angular/angular-codegen.d.ts.map +1 -1
  4. package/dist/Angular/angular-codegen.js +26 -14
  5. package/dist/Angular/angular-codegen.js.map +1 -1
  6. package/dist/Config/config.d.ts +45 -2
  7. package/dist/Config/config.d.ts.map +1 -1
  8. package/dist/Config/config.js +116 -39
  9. package/dist/Config/config.js.map +1 -1
  10. package/dist/Config/db-connection.d.ts +4 -0
  11. package/dist/Config/db-connection.d.ts.map +1 -1
  12. package/dist/Config/db-connection.js +11 -3
  13. package/dist/Config/db-connection.js.map +1 -1
  14. package/dist/Config/pg-connection.d.ts +2 -0
  15. package/dist/Config/pg-connection.d.ts.map +1 -1
  16. package/dist/Config/pg-connection.js +5 -1
  17. package/dist/Config/pg-connection.js.map +1 -1
  18. package/dist/Config/schema-output.d.ts +8 -0
  19. package/dist/Config/schema-output.d.ts.map +1 -1
  20. package/dist/Config/schema-output.js +19 -7
  21. package/dist/Config/schema-output.js.map +1 -1
  22. package/dist/Database/__tests__/exclude-schema-permissions.test.js +3 -3
  23. package/dist/Database/codeGenDatabaseProvider.d.ts +16 -1
  24. package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
  25. package/dist/Database/codeGenDatabaseProvider.js +37 -9
  26. package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
  27. package/dist/Database/dbSchema.d.ts +4 -0
  28. package/dist/Database/dbSchema.d.ts.map +1 -1
  29. package/dist/Database/dbSchema.js +17 -9
  30. package/dist/Database/dbSchema.js.map +1 -1
  31. package/dist/Database/entity-field-change-tracking.d.ts +4 -0
  32. package/dist/Database/entity-field-change-tracking.d.ts.map +1 -1
  33. package/dist/Database/entity-field-change-tracking.js +12 -4
  34. package/dist/Database/entity-field-change-tracking.js.map +1 -1
  35. package/dist/Database/exclude-tables.d.ts +2 -0
  36. package/dist/Database/exclude-tables.d.ts.map +1 -1
  37. package/dist/Database/exclude-tables.js +5 -1
  38. package/dist/Database/exclude-tables.js.map +1 -1
  39. package/dist/Database/field-metadata-lock.d.ts +8 -6
  40. package/dist/Database/field-metadata-lock.d.ts.map +1 -1
  41. package/dist/Database/field-metadata-lock.js +29 -25
  42. package/dist/Database/field-metadata-lock.js.map +1 -1
  43. package/dist/Database/heal-schema-params.d.ts +14 -2
  44. package/dist/Database/heal-schema-params.d.ts.map +1 -1
  45. package/dist/Database/heal-schema-params.js +21 -5
  46. package/dist/Database/heal-schema-params.js.map +1 -1
  47. package/dist/Database/manage-metadata.d.ts +203 -8
  48. package/dist/Database/manage-metadata.d.ts.map +1 -1
  49. package/dist/Database/manage-metadata.js +830 -490
  50. package/dist/Database/manage-metadata.js.map +1 -1
  51. package/dist/Database/materializationAnalysis.d.ts +61 -2
  52. package/dist/Database/materializationAnalysis.d.ts.map +1 -1
  53. package/dist/Database/materializationAnalysis.js +43 -23
  54. package/dist/Database/materializationAnalysis.js.map +1 -1
  55. package/dist/Database/materializationBroadRender.d.ts +5 -3
  56. package/dist/Database/materializationBroadRender.d.ts.map +1 -1
  57. package/dist/Database/materializationBroadRender.js +17 -13
  58. package/dist/Database/materializationBroadRender.js.map +1 -1
  59. package/dist/Database/materializationDrift.d.ts +2 -0
  60. package/dist/Database/materializationDrift.d.ts.map +1 -1
  61. package/dist/Database/materializationDrift.js +5 -1
  62. package/dist/Database/materializationDrift.js.map +1 -1
  63. package/dist/Database/materializationParamClassifier.d.ts +17 -2
  64. package/dist/Database/materializationParamClassifier.d.ts.map +1 -1
  65. package/dist/Database/materializationParamClassifier.js +22 -10
  66. package/dist/Database/materializationParamClassifier.js.map +1 -1
  67. package/dist/Database/materializationParamVerifier.d.ts +2 -0
  68. package/dist/Database/materializationParamVerifier.d.ts.map +1 -1
  69. package/dist/Database/materializationParamVerifier.js +18 -14
  70. package/dist/Database/materializationParamVerifier.js.map +1 -1
  71. package/dist/Database/materializationSqlAst.d.ts +19 -1
  72. package/dist/Database/materializationSqlAst.d.ts.map +1 -1
  73. package/dist/Database/materializationSqlAst.js +53 -17
  74. package/dist/Database/materializationSqlAst.js.map +1 -1
  75. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
  76. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +92 -69
  77. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
  78. package/dist/Database/providers/postgresql/__tests__/LayeredBaseViewPermissions.test.d.ts +2 -0
  79. package/dist/Database/providers/postgresql/__tests__/LayeredBaseViewPermissions.test.d.ts.map +1 -0
  80. package/dist/Database/providers/postgresql/__tests__/LayeredBaseViewPermissions.test.js +72 -0
  81. package/dist/Database/providers/postgresql/__tests__/LayeredBaseViewPermissions.test.js.map +1 -0
  82. package/dist/Database/providers/postgresql/__tests__/ViewRegenDependents.test.d.ts +2 -0
  83. package/dist/Database/providers/postgresql/__tests__/ViewRegenDependents.test.d.ts.map +1 -0
  84. package/dist/Database/providers/postgresql/__tests__/ViewRegenDependents.test.js +53 -0
  85. package/dist/Database/providers/postgresql/__tests__/ViewRegenDependents.test.js.map +1 -0
  86. package/dist/Database/providers/postgresql/metadataSupportObjects.d.ts +2 -0
  87. package/dist/Database/providers/postgresql/metadataSupportObjects.d.ts.map +1 -1
  88. package/dist/Database/providers/postgresql/metadataSupportObjects.js +5 -1
  89. package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
  90. package/dist/Database/providers/postgresql/viewDependencyCapture.d.ts +10 -0
  91. package/dist/Database/providers/postgresql/viewDependencyCapture.d.ts.map +1 -1
  92. package/dist/Database/providers/postgresql/viewDependencyCapture.js +25 -5
  93. package/dist/Database/providers/postgresql/viewDependencyCapture.js.map +1 -1
  94. package/dist/Database/providers/postgresql/viewFallback.d.ts +11 -7
  95. package/dist/Database/providers/postgresql/viewFallback.d.ts.map +1 -1
  96. package/dist/Database/providers/postgresql/viewFallback.js +18 -12
  97. package/dist/Database/providers/postgresql/viewFallback.js.map +1 -1
  98. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +13 -13
  99. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
  100. package/dist/Database/reconcileFieldLevelSecurity.d.ts +2 -0
  101. package/dist/Database/reconcileFieldLevelSecurity.d.ts.map +1 -1
  102. package/dist/Database/reconcileFieldLevelSecurity.js +5 -1
  103. package/dist/Database/reconcileFieldLevelSecurity.js.map +1 -1
  104. package/dist/Database/reorder-columns.d.ts +2 -0
  105. package/dist/Database/reorder-columns.d.ts.map +1 -1
  106. package/dist/Database/reorder-columns.js +5 -1
  107. package/dist/Database/reorder-columns.js.map +1 -1
  108. package/dist/Database/schema-filters.d.ts +6 -0
  109. package/dist/Database/schema-filters.d.ts.map +1 -1
  110. package/dist/Database/schema-filters.js +17 -5
  111. package/dist/Database/schema-filters.js.map +1 -1
  112. package/dist/Database/schema-scope.d.ts +4 -0
  113. package/dist/Database/schema-scope.d.ts.map +1 -1
  114. package/dist/Database/schema-scope.js +13 -5
  115. package/dist/Database/schema-scope.js.map +1 -1
  116. package/dist/Database/search-guardrails.d.ts +42 -0
  117. package/dist/Database/search-guardrails.d.ts.map +1 -1
  118. package/dist/Database/search-guardrails.js +57 -17
  119. package/dist/Database/search-guardrails.js.map +1 -1
  120. package/dist/Database/sql.d.ts +20 -0
  121. package/dist/Database/sql.d.ts.map +1 -1
  122. package/dist/Database/sql.js +85 -32
  123. package/dist/Database/sql.js.map +1 -1
  124. package/dist/Database/sql_codegen.d.ts +92 -0
  125. package/dist/Database/sql_codegen.d.ts.map +1 -1
  126. package/dist/Database/sql_codegen.js +202 -114
  127. package/dist/Database/sql_codegen.js.map +1 -1
  128. package/dist/EntityNameScanner/EntityNameScanner.d.ts +16 -0
  129. package/dist/EntityNameScanner/EntityNameScanner.d.ts.map +1 -1
  130. package/dist/EntityNameScanner/EntityNameScanner.js +47 -15
  131. package/dist/EntityNameScanner/EntityNameScanner.js.map +1 -1
  132. package/dist/EntityNameScanner/HtmlEntityNameScanner.d.ts +6 -0
  133. package/dist/EntityNameScanner/HtmlEntityNameScanner.d.ts.map +1 -1
  134. package/dist/EntityNameScanner/HtmlEntityNameScanner.js +19 -7
  135. package/dist/EntityNameScanner/HtmlEntityNameScanner.js.map +1 -1
  136. package/dist/EntityNameScanner/MetadataNameScanner.d.ts +6 -0
  137. package/dist/EntityNameScanner/MetadataNameScanner.d.ts.map +1 -1
  138. package/dist/EntityNameScanner/MetadataNameScanner.js +19 -7
  139. package/dist/EntityNameScanner/MetadataNameScanner.js.map +1 -1
  140. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts +6 -0
  141. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts.map +1 -1
  142. package/dist/Manifest/GenerateClassRegistrationsManifest.js +16 -4
  143. package/dist/Manifest/GenerateClassRegistrationsManifest.js.map +1 -1
  144. package/dist/Misc/action_subclasses_codegen.d.ts +4 -0
  145. package/dist/Misc/action_subclasses_codegen.d.ts.map +1 -1
  146. package/dist/Misc/action_subclasses_codegen.js +11 -3
  147. package/dist/Misc/action_subclasses_codegen.js.map +1 -1
  148. package/dist/Misc/advanced_generation.d.ts +48 -2
  149. package/dist/Misc/advanced_generation.d.ts.map +1 -1
  150. package/dist/Misc/advanced_generation.js +53 -15
  151. package/dist/Misc/advanced_generation.js.map +1 -1
  152. package/dist/Misc/codegen-reporter.d.ts +53 -0
  153. package/dist/Misc/codegen-reporter.d.ts.map +1 -1
  154. package/dist/Misc/codegen-reporter.js +106 -22
  155. package/dist/Misc/codegen-reporter.js.map +1 -1
  156. package/dist/Misc/createNewUser.d.ts +6 -0
  157. package/dist/Misc/createNewUser.d.ts.map +1 -1
  158. package/dist/Misc/createNewUser.js +5 -1
  159. package/dist/Misc/createNewUser.js.map +1 -1
  160. package/dist/Misc/entity_subclasses_codegen.d.ts +8 -0
  161. package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
  162. package/dist/Misc/entity_subclasses_codegen.js +52 -36
  163. package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
  164. package/dist/Misc/externalTypeMapping.d.ts +2 -0
  165. package/dist/Misc/externalTypeMapping.d.ts.map +1 -1
  166. package/dist/Misc/externalTypeMapping.js +5 -1
  167. package/dist/Misc/externalTypeMapping.js.map +1 -1
  168. package/dist/Misc/file-write.d.ts +2 -0
  169. package/dist/Misc/file-write.d.ts.map +1 -1
  170. package/dist/Misc/file-write.js +5 -1
  171. package/dist/Misc/file-write.js.map +1 -1
  172. package/dist/Misc/graphql_server_codegen.d.ts +10 -0
  173. package/dist/Misc/graphql_server_codegen.d.ts.map +1 -1
  174. package/dist/Misc/graphql_server_codegen.js +46 -26
  175. package/dist/Misc/graphql_server_codegen.js.map +1 -1
  176. package/dist/Misc/remote_operations_codegen.d.ts +12 -0
  177. package/dist/Misc/remote_operations_codegen.d.ts.map +1 -1
  178. package/dist/Misc/remote_operations_codegen.js +21 -5
  179. package/dist/Misc/remote_operations_codegen.js.map +1 -1
  180. package/dist/Misc/runCommand.d.ts +6 -0
  181. package/dist/Misc/runCommand.d.ts.map +1 -1
  182. package/dist/Misc/runCommand.js +16 -4
  183. package/dist/Misc/runCommand.js.map +1 -1
  184. package/dist/Misc/schema-emit.d.ts +28 -0
  185. package/dist/Misc/schema-emit.d.ts.map +1 -1
  186. package/dist/Misc/schema-emit.js +75 -23
  187. package/dist/Misc/schema-emit.js.map +1 -1
  188. package/dist/Misc/sql_logging.d.ts +31 -9
  189. package/dist/Misc/sql_logging.d.ts.map +1 -1
  190. package/dist/Misc/sql_logging.js +95 -51
  191. package/dist/Misc/sql_logging.js.map +1 -1
  192. package/dist/Misc/sql_text.d.ts +4 -0
  193. package/dist/Misc/sql_text.d.ts.map +1 -1
  194. package/dist/Misc/sql_text.js +10 -2
  195. package/dist/Misc/sql_text.js.map +1 -1
  196. package/dist/Misc/status_logging.d.ts +36 -0
  197. package/dist/Misc/status_logging.d.ts.map +1 -1
  198. package/dist/Misc/status_logging.js +95 -23
  199. package/dist/Misc/status_logging.js.map +1 -1
  200. package/dist/Misc/system_integrity.js +4 -4
  201. package/dist/Misc/system_integrity.js.map +1 -1
  202. package/dist/Misc/temp_batch_file.d.ts +12 -0
  203. package/dist/Misc/temp_batch_file.d.ts.map +1 -1
  204. package/dist/Misc/temp_batch_file.js +35 -11
  205. package/dist/Misc/temp_batch_file.js.map +1 -1
  206. package/dist/Misc/util.d.ts +33 -0
  207. package/dist/Misc/util.d.ts.map +1 -1
  208. package/dist/Misc/util.js +53 -13
  209. package/dist/Misc/util.js.map +1 -1
  210. package/dist/index.d.ts +1 -1
  211. package/dist/index.d.ts.map +1 -1
  212. package/dist/index.js +1 -1
  213. package/dist/index.js.map +1 -1
  214. package/dist/plugins/index.d.ts +11 -1
  215. package/dist/plugins/index.d.ts.map +1 -1
  216. package/dist/plugins/index.js +9 -1
  217. package/dist/plugins/index.js.map +1 -1
  218. package/dist/runCodeGen.d.ts +6 -0
  219. package/dist/runCodeGen.d.ts.map +1 -1
  220. package/dist/runCodeGen.js +150 -138
  221. package/dist/runCodeGen.js.map +1 -1
  222. package/package.json +29 -29
@@ -1,54 +1,54 @@
1
1
  import { SQLServerDialect, PostgreSQLDialect } from '@memberjunction/sql-dialect';
2
2
  import { CodeGenDatabaseProvider } from './codeGenDatabaseProvider.js';
3
- import { analyzeQueryForMaterialization, detectAggregationKeyColumns, detectAdditiveMeasures, MATERIALIZATION_SURROGATE_COLUMN } from './materializationAnalysis.js';
4
- import { evaluateMaterializationDrift } from './materializationDrift.js';
5
- import { classifyQueryParameters, buildHeldValues } from './materializationParamClassifier.js';
6
- import { buildBroadRowFilterSQL } from './materializationBroadRender.js';
3
+ import { AnalyzeQueryForMaterialization, DetectAggregationKeyColumns, DetectAdditiveMeasures, MATERIALIZATION_SURROGATE_COLUMN } from './materializationAnalysis.js';
4
+ import { EvaluateMaterializationDrift } from './materializationDrift.js';
5
+ import { ClassifyQueryParameters, BuildHeldValues } from './materializationParamClassifier.js';
6
+ import { BuildBroadRowFilterSQL } from './materializationBroadRender.js';
7
7
  import { QueryParameterProcessor } from '@memberjunction/query-processor';
8
8
  // Side-effect import — registers `SQLServerCodeGenProvider` with `MJGlobal.ClassFactory`
9
9
  // under the `'sqlserver'` key via its `@RegisterClass` decorator. Without this import,
10
10
  // `ClassFactory.CreateInstance(CodeGenDatabaseProvider, 'sqlserver')` returns nothing
11
11
  // and the SS code path silently fails.
12
12
  import './providers/sqlserver/SQLServerCodeGenProvider.js';
13
- import { configInfo, currentWorkingDirectory, dbPlatform, getSettingValue, mj_core_schema, outputDir } from '../Config/config.js';
13
+ import { configInfo, currentWorkingDirectory, DbPlatform, GetSettingValue, MjCoreSchema, OutputDir } from '../Config/config.js';
14
14
  import { CodeNameFromString, EntityFieldInfo, EntityInfo, ExternalDataSourceReadRouter, ExtractActualDefaultValue, LogError, LogStatus, Metadata, RunQuerySQLFilterManager, SeverityType } from "@memberjunction/core";
15
15
  import { MJEntityFieldSchema } from "@memberjunction/core-entities";
16
- import { logError, logMessage, logStatus, startSpinner, updateSpinner, succeedSpinner } from "../Misc/status_logging.js";
16
+ import { logError, LogMessage, logStatus, StartSpinner, UpdateSpinner, SucceedSpinner } from "../Misc/status_logging.js";
17
17
  import { SQLUtilityBase } from "./sql.js";
18
- import { applyIncludeSchemaScope } from "./schema-scope.js";
19
- import { buildHealSchemaRoutineParams, getAuthoredExcludeSchemas, snapshotAuthoredExcludeSchemas } from "./heal-schema-params.js";
20
- import { AdvancedGeneration, isPlausibleEntityName } from "../Misc/advanced_generation.js";
18
+ import { ApplyIncludeSchemaScope } from "./schema-scope.js";
19
+ import { BuildHealSchemaRoutineParams, GetAuthoredExcludeSchemas, SnapshotAuthoredExcludeSchemas } from "./heal-schema-params.js";
20
+ import { AdvancedGeneration, IsPlausibleEntityName } from "../Misc/advanced_generation.js";
21
21
  import { CodeGenReporter } from "../Misc/codegen-reporter.js";
22
- import { applySearchableFieldsCap, defaultPredicateFor, entityLevelEnableBlockedReason, isNarrativeFieldName, MAX_SEARCHABLE_FIELDS_PER_ENTITY, NAME_LIKE_FIELD_NAMES, normalizePredicate, normalizeSmartFieldResultShape, } from "./search-guardrails.js";
23
- import { mapExternalNativeTypeToMJ } from "../Misc/externalTypeMapping.js";
22
+ import { ApplySearchableFieldsCap, DefaultPredicateFor, EntityLevelEnableBlockedReason, IsNarrativeFieldName, MAX_SEARCHABLE_FIELDS_PER_ENTITY, NAME_LIKE_FIELD_NAMES, NormalizePredicate, NormalizeSmartFieldResultShape, } from "./search-guardrails.js";
23
+ import { MapExternalNativeTypeToMJ } from "../Misc/externalTypeMapping.js";
24
24
  import { SQLParser } from "@memberjunction/sql-parser";
25
- import { createDisplayName, generatePluralName, MJGlobal, ResolveSingleEntityResourceTarget, stripTrailingChars, UUIDsEqual } from "@memberjunction/global";
25
+ import { createDisplayName, EscapeSQLString, generatePluralName, MJGlobal, ResolveSingleEntityResourceTarget, stripTrailingChars, UUIDsEqual } from "@memberjunction/global";
26
26
  import { v4 as uuidv4, v5 as uuidv5 } from 'uuid';
27
27
  import * as fs from 'fs';
28
28
  import path from 'path';
29
- import { canonicalJSONStringify, deepEqualJSON } from "../Misc/util.js";
30
- import { trimTrailingStatementTerminators } from "../Misc/sql_text.js";
29
+ import { CanonicalJSONStringify, DeepEqualJSON } from "../Misc/util.js";
30
+ import { TrimTrailingStatementTerminators } from "../Misc/sql_text.js";
31
31
  import { SQLLogging } from "../Misc/sql_logging.js";
32
- import { computeFieldMetadataUpdate } from "./field-metadata-lock.js";
32
+ import { ComputeFieldMetadataUpdate } from "./field-metadata-lock.js";
33
33
  import { TRACKED_FIELD_COLUMNS, DISPLAYNAME_REOPEN_REASONS, TYPE_REOPEN_REASONS, diffEntityFieldSnapshots, } from './entity-field-change-tracking.js';
34
- export { TRACKED_FIELD_COLUMNS, DISPLAYNAME_REOPEN_REASONS, TYPE_REOPEN_REASONS, diffEntityFieldSnapshots, } from './entity-field-change-tracking.js';
34
+ export { TRACKED_FIELD_COLUMNS, DISPLAYNAME_REOPEN_REASONS, TYPE_REOPEN_REASONS, DiffEntityFieldSnapshots, diffEntityFieldSnapshots, } from './entity-field-change-tracking.js';
35
35
  export class ValidatorResult {
36
36
  constructor() {
37
- this.entityName = "";
38
- this.sourceCheckConstraint = "";
39
- this.functionText = "";
40
- this.functionName = "";
41
- this.functionDescription = "";
37
+ this.entityName = ""; // case-violation-ok-legacy-back-compat: object literals are assigned to this class, so an accessor stub changes what they must supply
38
+ this.sourceCheckConstraint = ""; // case-violation-ok-legacy-back-compat: object literals are assigned to this class, so an accessor stub changes what they must supply
39
+ this.functionText = ""; // case-violation-ok-legacy-back-compat: object literals are assigned to this class, so an accessor stub changes what they must supply
40
+ this.functionName = ""; // case-violation-ok-legacy-back-compat: object literals are assigned to this class, so an accessor stub changes what they must supply
41
+ this.functionDescription = ""; // case-violation-ok-legacy-back-compat: object literals are assigned to this class, so an accessor stub changes what they must supply
42
42
  /**
43
43
  * The ID value in the Generated Codes entity that was created for this validator.
44
44
  */
45
- this.generatedCodeId = "";
45
+ this.generatedCodeId = ""; // case-violation-ok-legacy-back-compat: object literals are assigned to this class, so an accessor stub changes what they must supply
46
46
  /**
47
47
  * The ID for the AI Model that was used to generate the code
48
48
  */
49
- this.aiModelID = "";
50
- this.wasGenerated = true;
51
- this.success = false;
49
+ this.aiModelID = ""; // case-violation-ok-legacy-back-compat: object literals are assigned to this class, so an accessor stub changes what they must supply
50
+ this.wasGenerated = true; // case-violation-ok-legacy-back-compat: object literals are assigned to this class, so an accessor stub changes what they must supply
51
+ this.success = false; // case-violation-ok-legacy-back-compat: object literals are assigned to this class, so an accessor stub changes what they must supply
52
52
  }
53
53
  }
54
54
  export class ManageMetadataBase {
@@ -98,7 +98,7 @@ export class ManageMetadataBase {
98
98
  */
99
99
  get dbProvider() {
100
100
  if (!this._dbProvider) {
101
- const platform = dbPlatform();
101
+ const platform = DbPlatform();
102
102
  const provider = MJGlobal.Instance.ClassFactory.CreateInstance(CodeGenDatabaseProvider, platform);
103
103
  // CreateInstance returns the abstract base class on a missed key (it
104
104
  // doesn't throw), so disambiguate by constructor identity: anything
@@ -191,7 +191,7 @@ export class ManageMetadataBase {
191
191
  */
192
192
  applyTimeEntityFieldSequenceSQL(entityID) {
193
193
  // COALESCE is valid on both platforms and is the form the docs and the gate describe.
194
- return `(SELECT COALESCE(MAX(${this.qi('Sequence')}), 0) + 1 FROM ${this.qs(mj_core_schema(), 'EntityField')} WHERE ${this.qi('EntityID')} = '${entityID}')`;
194
+ return `(SELECT COALESCE(MAX(${this.qi('Sequence')}), 0) + 1 FROM ${this.qs(MjCoreSchema(), 'EntityField')} WHERE ${this.qi('EntityID')} = '${entityID}')`;
195
195
  }
196
196
  /**
197
197
  * Wraps a SELECT query with a row limit.
@@ -213,7 +213,7 @@ export class ManageMetadataBase {
213
213
  * (avoids hardcoding runtime UUIDs that may differ on a fresh database).
214
214
  */
215
215
  entityIdSubquery(tableName, schemaName) {
216
- const schema = mj_core_schema();
216
+ const schema = MjCoreSchema();
217
217
  return `(${this.selectTop(1, 'ID', `FROM ${this.qs(schema, 'vwEntities')} WHERE BaseTable = '${tableName}' AND SchemaName = '${schemaName}'`)})`;
218
218
  }
219
219
  /**
@@ -263,22 +263,38 @@ export class ManageMetadataBase {
263
263
  /**
264
264
  * Globally scoped list of entities that have been created during the metadata management process.
265
265
  */
266
- static get newEntityList() {
266
+ static get NewEntityList() {
267
267
  return this._newEntityList;
268
268
  }
269
- static set newEntityList(value) {
269
+ static set NewEntityList(value) {
270
270
  this._newEntityList = value;
271
271
  }
272
+ /** @deprecated Use {@link NewEntityList}. */
273
+ static get newEntityList() {
274
+ return this.NewEntityList;
275
+ }
276
+ /** @deprecated Use {@link NewEntityList}. */
277
+ static set newEntityList(value) {
278
+ this.NewEntityList = value;
279
+ }
272
280
  static { this._modifiedEntityList = []; }
273
281
  /**
274
282
  * Globally scoped list of entities that have been modified during the metadata management process.
275
283
  */
276
- static get modifiedEntityList() {
284
+ static get ModifiedEntityList() {
277
285
  return this._modifiedEntityList;
278
286
  }
279
- static set modifiedEntityList(value) {
287
+ static set ModifiedEntityList(value) {
280
288
  this._modifiedEntityList = value;
281
289
  }
290
+ /** @deprecated Use {@link ModifiedEntityList}. */
291
+ static get modifiedEntityList() {
292
+ return this.ModifiedEntityList;
293
+ }
294
+ /** @deprecated Use {@link ModifiedEntityList}. */
295
+ static set modifiedEntityList(value) {
296
+ this.ModifiedEntityList = value;
297
+ }
282
298
  static { this._newFieldSet = new Set(); }
283
299
  static { this._changedFields = new Map(); }
284
300
  static { this._changedFieldReport = []; }
@@ -290,13 +306,17 @@ export class ManageMetadataBase {
290
306
  }
291
307
  return `${eid}:${fld}`;
292
308
  }
293
- static registerNewField(entityID, name) {
309
+ static RegisterNewField(entityID, name) {
294
310
  const key = this.fieldKey(entityID, name);
295
311
  if (key) {
296
312
  this._newFieldSet.add(key);
297
313
  }
298
314
  }
299
- static registerFieldChange(entityID, name, reasons) {
315
+ /** @deprecated Use {@link RegisterNewField}. */
316
+ static registerNewField(entityID, name) {
317
+ return this.RegisterNewField(entityID, name);
318
+ }
319
+ static RegisterFieldChange(entityID, name, reasons) {
300
320
  const key = this.fieldKey(entityID, name);
301
321
  if (key) {
302
322
  let set = this._changedFields.get(key);
@@ -309,17 +329,29 @@ export class ManageMetadataBase {
309
329
  }
310
330
  }
311
331
  }
312
- static isFieldNew(entityID, name) {
332
+ /** @deprecated Use {@link RegisterFieldChange}. */
333
+ static registerFieldChange(entityID, name, reasons) {
334
+ return this.RegisterFieldChange(entityID, name, reasons);
335
+ }
336
+ static IsFieldNew(entityID, name) {
313
337
  const key = this.fieldKey(entityID, name);
314
338
  return key ? this._newFieldSet.has(key) : false;
315
339
  }
316
- static fieldChangeReasons(entityID, name) {
340
+ /** @deprecated Use {@link IsFieldNew}. */
341
+ static isFieldNew(entityID, name) {
342
+ return this.IsFieldNew(entityID, name);
343
+ }
344
+ static FieldChangeReasons(entityID, name) {
317
345
  const key = this.fieldKey(entityID, name);
318
346
  const set = key ? this._changedFields.get(key) : undefined;
319
347
  return set ?? new Set();
320
348
  }
321
- static isDisplayNameReopened(entityID, name) {
322
- const reasons = this.fieldChangeReasons(entityID, name);
349
+ /** @deprecated Use {@link FieldChangeReasons}. */
350
+ static fieldChangeReasons(entityID, name) {
351
+ return this.FieldChangeReasons(entityID, name);
352
+ }
353
+ static IsDisplayNameReopened(entityID, name) {
354
+ const reasons = this.FieldChangeReasons(entityID, name);
323
355
  for (const r of reasons) {
324
356
  if (DISPLAYNAME_REOPEN_REASONS.has(r)) {
325
357
  return true;
@@ -327,8 +359,12 @@ export class ManageMetadataBase {
327
359
  }
328
360
  return false;
329
361
  }
330
- static isTypeReopened(entityID, name) {
331
- const reasons = this.fieldChangeReasons(entityID, name);
362
+ /** @deprecated Use {@link IsDisplayNameReopened}. */
363
+ static isDisplayNameReopened(entityID, name) {
364
+ return this.IsDisplayNameReopened(entityID, name);
365
+ }
366
+ static IsTypeReopened(entityID, name) {
367
+ const reasons = this.FieldChangeReasons(entityID, name);
332
368
  for (const r of reasons) {
333
369
  if (TYPE_REOPEN_REASONS.has(r)) {
334
370
  return true;
@@ -336,20 +372,40 @@ export class ManageMetadataBase {
336
372
  }
337
373
  return false;
338
374
  }
339
- static get newFieldCount() {
375
+ /** @deprecated Use {@link IsTypeReopened}. */
376
+ static isTypeReopened(entityID, name) {
377
+ return this.IsTypeReopened(entityID, name);
378
+ }
379
+ static get NewFieldCount() {
340
380
  return this._newFieldSet.size;
341
381
  }
342
- static get changedFieldCount() {
382
+ /** @deprecated Use {@link NewFieldCount}. */
383
+ static get newFieldCount() {
384
+ return this.NewFieldCount;
385
+ }
386
+ static get ChangedFieldCount() {
343
387
  return this._changedFields.size;
344
388
  }
345
- static get changedFieldReport() {
389
+ /** @deprecated Use {@link ChangedFieldCount}. */
390
+ static get changedFieldCount() {
391
+ return this.ChangedFieldCount;
392
+ }
393
+ static get ChangedFieldReport() {
346
394
  return this._changedFieldReport;
347
395
  }
348
- static clearFieldTracking() {
396
+ /** @deprecated Use {@link ChangedFieldReport}. */
397
+ static get changedFieldReport() {
398
+ return this.ChangedFieldReport;
399
+ }
400
+ static ClearFieldTracking() {
349
401
  this._newFieldSet.clear();
350
402
  this._changedFields.clear();
351
403
  this._changedFieldReport = [];
352
404
  }
405
+ /** @deprecated Use {@link ClearFieldTracking}. */
406
+ static clearFieldTracking() {
407
+ return this.ClearFieldTracking();
408
+ }
353
409
  /**
354
410
  * Takes a snapshot of EntityField rows from vwEntityFields for diffing.
355
411
  * Only queries columns in TRACKED_FIELD_COLUMNS (Sequence is excluded).
@@ -361,7 +417,7 @@ export class ManageMetadataBase {
361
417
  : '';
362
418
  const cols = TRACKED_FIELD_COLUMNS.map(c => this.qi(c)).join(', ');
363
419
  const sSQL = `SELECT ${this.qi('ID')}, ${this.qi('EntityID')}, ${this.qi('Entity')} AS ${this.qi('EntityName')}, ${this.qi('Name')}, ${cols}
364
- FROM ${this.qs(mj_core_schema(), 'vwEntityFields')}
420
+ FROM ${this.qs(MjCoreSchema(), 'vwEntityFields')}
365
421
  ${filter}`;
366
422
  const result = await this.runQuery(pool, sSQL);
367
423
  const map = new Map();
@@ -391,9 +447,13 @@ export class ManageMetadataBase {
391
447
  * the dead class keeps a live `@RegisterClass` registration on disk. The old monolith could
392
448
  * not drift this way: it was rewritten in full every run.
393
449
  */
394
- static get deletedEntitySchemaList() {
450
+ static get DeletedEntitySchemaList() {
395
451
  return this._deletedEntitySchemaList;
396
452
  }
453
+ /** @deprecated Use {@link DeletedEntitySchemaList}. */
454
+ static get deletedEntitySchemaList() {
455
+ return this.DeletedEntitySchemaList;
456
+ }
397
457
  static { this._entitiesRequiringViewRegen = []; }
398
458
  /**
399
459
  * Entities that had late-phase changes requiring their base views to be
@@ -412,9 +472,13 @@ export class ManageMetadataBase {
412
472
  /**
413
473
  * Globally scoped list of validators that have been generated during the metadata management process.
414
474
  */
415
- static get generatedValidators() {
475
+ static get GeneratedValidators() {
416
476
  return this._generatedValidators;
417
477
  }
478
+ /** @deprecated Use {@link GeneratedValidators}. */
479
+ static get generatedValidators() {
480
+ return this.GeneratedValidators;
481
+ }
418
482
  static { this._softPKFKConfigCache = null; }
419
483
  static { this._softPKFKConfigPath = ''; }
420
484
  /**
@@ -429,16 +493,20 @@ export class ManageMetadataBase {
429
493
  * Deterministic + event-driven (no mtime/TOCTOU race). The CLI `Run()` path does not call this, so its
430
494
  * load-once-per-process behavior is unchanged.
431
495
  */
432
- static invalidateSoftPKFKConfigCache() {
496
+ static InvalidateSoftPKFKConfigCache() {
433
497
  ManageMetadataBase._softPKFKConfigCache = null;
434
498
  ManageMetadataBase._softPKFKConfigPath = '';
435
499
  }
500
+ /** @deprecated Use {@link InvalidateSoftPKFKConfigCache}. */
501
+ static invalidateSoftPKFKConfigCache() {
502
+ return this.InvalidateSoftPKFKConfigCache();
503
+ }
436
504
  /**
437
505
  * Loads and caches the soft PK/FK configuration from the additionalSchemaInfo file.
438
506
  * Cached per process to avoid repeated I/O within a CodeGen run; the in-process (RSU) path calls
439
507
  * {@link invalidateSoftPKFKConfigCache} at the start of each run so a rewritten file is picked up.
440
508
  */
441
- static getSoftPKFKConfig() {
509
+ static GetSoftPKFKConfig() {
442
510
  // Return cached config if path hasn't changed
443
511
  const configPath = configInfo.additionalSchemaInfo
444
512
  ? path.join(currentWorkingDirectory, configInfo.additionalSchemaInfo)
@@ -464,6 +532,10 @@ export class ManageMetadataBase {
464
532
  return null;
465
533
  }
466
534
  }
535
+ /** @deprecated Use {@link GetSoftPKFKConfig}. */
536
+ static getSoftPKFKConfig() {
537
+ return this.GetSoftPKFKConfig();
538
+ }
467
539
  /**
468
540
  * Extracts a flat array of table configs from the config file, handling both formats:
469
541
  * 1. Schema-as-key (template format): { "dbo": [{ "TableName": "Orders", ... }] }
@@ -524,6 +596,28 @@ export class ManageMetadataBase {
524
596
  ForeignKeys: Array.isArray(ve.ForeignKeys) ? ve.ForeignKeys : undefined,
525
597
  }));
526
598
  }
599
+ /**
600
+ * Schema a VirtualEntities entry resolves to when it names none. Same default as table entries.
601
+ */
602
+ resolveVirtualEntitySchema(ve) {
603
+ const schema = ve.SchemaName?.trim();
604
+ return schema && schema.length > 0 ? schema : 'dbo';
605
+ }
606
+ /**
607
+ * VirtualEntities entries that declare keys, in the table-entry shape the soft key writer consumes.
608
+ * A virtual entity stores its view name in BaseTable, so the existing SchemaName + BaseTable lookup applies.
609
+ */
610
+ virtualEntityConfigsAsTableConfigs(config) {
611
+ return this.extractVirtualEntitiesFromConfig(config)
612
+ .filter(ve => (ve.PrimaryKey?.length ?? 0) > 0 || (ve.ForeignKeys?.length ?? 0) > 0)
613
+ .map(ve => ({
614
+ SchemaName: this.resolveVirtualEntitySchema(ve),
615
+ TableName: ve.ViewName,
616
+ Description: ve.Description,
617
+ PrimaryKey: (ve.PrimaryKey ?? []).map(fieldName => ({ FieldName: fieldName })),
618
+ ForeignKeys: ve.ForeignKeys ?? [],
619
+ }));
620
+ }
527
621
  /**
528
622
  * Extracts the MaterializedBaseViews array from the additionalSchemaInfo config file.
529
623
  * Each entry declares a 1:1 base-view materialization of an existing entity (plan §4.1).
@@ -673,7 +767,7 @@ export class ManageMetadataBase {
673
767
  const allOrganicKeys = this.extractOrganicKeysFromConfig(config);
674
768
  if (allOrganicKeys.length === 0)
675
769
  return { success: true, createdCount: 0, updatedCount: 0, failedCount: 0 };
676
- const schema = mj_core_schema();
770
+ const schema = MjCoreSchema();
677
771
  let createdCount = 0;
678
772
  let updatedCount = 0;
679
773
  let failedCount = 0;
@@ -709,7 +803,7 @@ export class ManageMetadataBase {
709
803
  // well as last — and the metadata DML logged just before it (entity-config UPDATEs, the
710
804
  // previous key's INSERTs) has no trailing GO. requiresOwnBatch puts the provider's
711
805
  // separator on both sides in the migration file ('' on PostgreSQL: nothing is added).
712
- await this.LogSQLAndExecute(pool, viewSQL, `Create transitive bridge view ${viewFullName} for organic key "${okConfig.Name}" on ${ownerEntityName}`, false, true, this.dbProvider.BatchSeparator, true);
806
+ await this.logSQLAndExecute(pool, viewSQL, `Create transitive bridge view ${viewFullName} for organic key "${okConfig.Name}" on ${ownerEntityName}`, false, true, this.dbProvider.BatchSeparator, true);
713
807
  // Auto-populate TransitiveObject from the view definition
714
808
  re.TransitiveObject = viewFullName;
715
809
  }
@@ -729,7 +823,7 @@ export class ManageMetadataBase {
729
823
  Sequence = ${okConfig.Sequence ?? 0},
730
824
  Status = 'Active'
731
825
  WHERE ID = '${organicKeyId}'`;
732
- await this.LogSQLAndExecute(pool, updateSQL, `Update organic key "${okConfig.Name}" on ${ownerEntityName}`);
826
+ await this.logSQLAndExecute(pool, updateSQL, `Update organic key "${okConfig.Name}" on ${ownerEntityName}`);
733
827
  updatedCount++;
734
828
  logStatus(` > Organic key: Updated "${okConfig.Name}" on ${ownerEntityName}`);
735
829
  }
@@ -739,7 +833,7 @@ export class ManageMetadataBase {
739
833
  const insertSQL = `INSERT INTO ${this.qs(schema, 'EntityOrganicKey')}
740
834
  (EntityID, Name, ${okConfig.Description ? 'Description, ' : ''}MatchFieldNames, NormalizationStrategy, ${okConfig.CustomNormalizationExpression ? 'CustomNormalizationExpression, ' : ''}Sequence, Status)
741
835
  VALUES (${ownerSubquery}, '${okConfig.Name}', ${okConfig.Description ? `'${okConfig.Description.replace(/'/g, "''")}', ` : ''}'${matchFieldNames}', '${okConfig.NormalizationStrategy || 'LowerCaseTrim'}', ${okConfig.CustomNormalizationExpression ? `'${okConfig.CustomNormalizationExpression.replace(/'/g, "''")}', ` : ''}${okConfig.Sequence ?? 0}, 'Active')`;
742
- await this.LogSQLAndExecute(pool, insertSQL, `Insert organic key "${okConfig.Name}" on ${ownerEntityName}`);
836
+ await this.logSQLAndExecute(pool, insertSQL, `Insert organic key "${okConfig.Name}" on ${ownerEntityName}`);
743
837
  createdCount++;
744
838
  logStatus(` > Organic key: Created "${okConfig.Name}" on ${ownerEntityName}`);
745
839
  // Fetch the new ID
@@ -769,7 +863,7 @@ export class ManageMetadataBase {
769
863
  DisplayLocation = '${reConfig.DisplayLocation || 'After Field Tabs'}',
770
864
  Sequence = ${reConfig.Sequence ?? 0}
771
865
  WHERE ID = '${relId}'`;
772
- await this.LogSQLAndExecute(pool, updateRelSQL, `Update organic key related entity: "${okConfig.Name}" → ${relEntityName}`);
866
+ await this.logSQLAndExecute(pool, updateRelSQL, `Update organic key related entity: "${okConfig.Name}" → ${relEntityName}`);
773
867
  }
774
868
  else {
775
869
  // Use subqueries for FK references so the logged SQL is portable across databases
@@ -789,7 +883,7 @@ export class ManageMetadataBase {
789
883
  ${reConfig.DisplayName ? `'${reConfig.DisplayName.replace(/'/g, "''")}'` : 'NULL'},
790
884
  '${reConfig.DisplayLocation || 'After Field Tabs'}',
791
885
  ${reConfig.Sequence ?? 0})`;
792
- await this.LogSQLAndExecute(pool, insertRelSQL, `Insert organic key related entity: "${okConfig.Name}" → ${relEntityName}`);
886
+ await this.logSQLAndExecute(pool, insertRelSQL, `Insert organic key related entity: "${okConfig.Name}" → ${relEntityName}`);
793
887
  }
794
888
  logStatus(` > Organic key "${okConfig.Name}": ${existingRel.recordset.length > 0 ? 'updated' : 'created'} → ${relEntityName} (${isDirect ? 'direct' : 'transitive'})`);
795
889
  }
@@ -812,7 +906,7 @@ export class ManageMetadataBase {
812
906
  */
813
907
  async findOrganicKeyEntity(pool, schemaName, tableName) {
814
908
  const result = await this.runQueryWithParams(pool, `
815
- ${this.selectTop(1, 'ID, Name', `FROM ${this.qs(mj_core_schema(), 'vwEntities')}
909
+ ${this.selectTop(1, 'ID, Name', `FROM ${this.qs(MjCoreSchema(), 'vwEntities')}
816
910
  WHERE (BaseTable = @TableName AND SchemaName = @SchemaName)
817
911
  OR Name = @TableName`, 'CASE WHEN BaseTable = @TableName AND SchemaName = @SchemaName THEN 0 ELSE 1 END')}
818
912
  `, { 'TableName': tableName, 'SchemaName': schemaName });
@@ -881,7 +975,7 @@ export class ManageMetadataBase {
881
975
  if (relationships.length === 0)
882
976
  return { success: true, updatedCount: 0 };
883
977
  let updatedCount = 0;
884
- const schema = mj_core_schema();
978
+ const schema = MjCoreSchema();
885
979
  for (const rel of relationships) {
886
980
  try {
887
981
  // Look up the parent entity — try by Name first, then by BaseTable within the given schema
@@ -925,7 +1019,7 @@ export class ManageMetadataBase {
925
1019
  SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()},
926
1020
  ${this.qi('ParentID')} = '${parentId}'
927
1021
  WHERE ${this.qi('ID')} = '${childId}'`;
928
- await this.LogSQLAndExecute(pool, updateSQL, `Set IS-A ParentID for "${childName}" → "${parentName}"`);
1022
+ await this.logSQLAndExecute(pool, updateSQL, `Set IS-A ParentID for "${childName}" → "${parentName}"`);
929
1023
  if (existingParentId) {
930
1024
  logStatus(` > IS-A: Updated "${childName}" ParentID from previous value to "${parentName}"`);
931
1025
  }
@@ -973,7 +1067,7 @@ export class ManageMetadataBase {
973
1067
  * so a broken declaration fails before it produces generated code.
974
1068
  */
975
1069
  async validateISARelationships(pool) {
976
- const schema = mj_core_schema();
1070
+ const schema = MjCoreSchema();
977
1071
  let errorCount = 0;
978
1072
  try {
979
1073
  const results = await this.runQuery(pool, this.buildISAValidationSQL(schema));
@@ -1064,7 +1158,7 @@ export class ManageMetadataBase {
1064
1158
  if (entityConfigs.length === 0)
1065
1159
  return { success: true, updatedCount: 0 };
1066
1160
  let updatedCount = 0;
1067
- const schema = mj_core_schema();
1161
+ const schema = MjCoreSchema();
1068
1162
  const reservedKeys = new Set(['BaseTable', 'SchemaName']);
1069
1163
  for (const ec of entityConfigs) {
1070
1164
  try {
@@ -1129,7 +1223,7 @@ export class ManageMetadataBase {
1129
1223
  const updateSQL = `UPDATE ${this.qs(schema, 'Entity')}
1130
1224
  SET ${setClauses.join(', ')}
1131
1225
  WHERE ${this.qi('ID')} = '${entityId}'`;
1132
- await this.LogSQLAndExecute(pool, updateSQL, `Update attributes on "${entityName}" from additionalSchemaInfo`);
1226
+ await this.logSQLAndExecute(pool, updateSQL, `Update attributes on "${entityName}" from additionalSchemaInfo`);
1133
1227
  const attrSummary = differingAttrs.map(a => a.summary).join(', ');
1134
1228
  logStatus(` > Entities config: Set ${attrSummary} on "${entityName}"`);
1135
1229
  updatedCount++;
@@ -1142,58 +1236,87 @@ export class ManageMetadataBase {
1142
1236
  return { success: true, updatedCount };
1143
1237
  }
1144
1238
  /**
1145
- * Processes virtual entity configurations from the additionalSchemaInfo config.
1146
- * For each configured virtual entity, checks if it already exists and creates
1147
- * it if not. Uses the spCreateVirtualEntity stored procedure.
1148
- * Must run BEFORE manageVirtualEntities() so newly created entities get field-synced.
1239
+ * Creates the virtual entities declared in additionalSchemaInfo that do not exist yet.
1240
+ * Creation is two logged statements (Entity row with a CodeGen-generated ID, then the first key
1241
+ * column) so the CodeGen_Run capture replays on any database. Each new entity joins its schema's
1242
+ * application, gets the default permissions, and is registered in NewEntityList so pass 2 and
1243
+ * file generation include it in this same run. Must run BEFORE manageVirtualEntities().
1244
+ * An entry whose EntityName is already in use is skipped before anything is written to the capture.
1149
1245
  */
1150
- async processVirtualEntityConfig(pool, currentUser) {
1151
- const config = ManageMetadataBase.getSoftPKFKConfig();
1246
+ async processVirtualEntityConfig(pool, currentUser, md) {
1247
+ const config = ManageMetadataBase.GetSoftPKFKConfig();
1152
1248
  if (!config)
1153
- return { success: true, createdCount: 0 };
1249
+ return { success: true, createdCount: 0, createdEntityNames: [] };
1154
1250
  const virtualEntities = this.extractVirtualEntitiesFromConfig(config);
1155
1251
  if (virtualEntities.length === 0)
1156
- return { success: true, createdCount: 0 };
1157
- let createdCount = 0;
1158
- const schema = mj_core_schema();
1252
+ return { success: true, createdCount: 0, createdEntityNames: [] };
1253
+ const createdEntityNames = [];
1254
+ const existingEntityNames = md.Entities.map(e => e.Name);
1255
+ const schema = MjCoreSchema();
1159
1256
  for (const ve of virtualEntities) {
1160
- const viewSchema = ve.SchemaName || schema;
1257
+ const viewSchema = this.resolveVirtualEntitySchema(ve);
1161
1258
  const viewName = ve.ViewName;
1162
- const entityName = ve.EntityName || this.deriveEntityNameFromView(viewName);
1163
- const pkField = ve.PrimaryKey?.[0] || 'ID';
1259
+ const configuredName = ve.EntityName || this.deriveEntityNameFromView(viewName);
1164
1260
  // Check if entity already exists for this view
1165
1261
  const existsResult = await this.runQueryWithParams(pool, `SELECT ID FROM ${this.qs(schema, 'vwEntities')} WHERE BaseView = @ViewName AND SchemaName = @SchemaName`, { 'ViewName': viewName, 'SchemaName': viewSchema });
1166
1262
  if (existsResult.recordset.length > 0) {
1167
- logStatus(` > Virtual entity "${entityName}" already exists for view [${viewSchema}].[${viewName}], skipping creation`);
1263
+ logStatus(` > Virtual entity "${configuredName}" already exists for view [${viewSchema}].[${viewName}], skipping creation`);
1168
1264
  continue;
1169
1265
  }
1170
1266
  // Verify the view actually exists in the database
1171
1267
  const viewExistsResult = await this.runQueryWithParams(pool, this.dbProvider.getViewExistsSQL(), { 'ViewName': viewName, 'SchemaName': viewSchema });
1172
1268
  if (viewExistsResult.recordset.length === 0) {
1173
- logError(` > View [${viewSchema}].[${viewName}] does not exist — skipping virtual entity creation for "${entityName}"`);
1269
+ logError(` > View [${viewSchema}].[${viewName}] does not exist — skipping virtual entity creation for "${configuredName}"`);
1174
1270
  continue;
1175
1271
  }
1176
- // Create the virtual entity via the stored procedure
1177
- try {
1178
- const createResult = await pool.executeStoredProcedure(`${this.qs(schema, 'spCreateVirtualEntity')}`, { 'Name': entityName, 'BaseView': viewName, 'SchemaName': viewSchema, 'PrimaryKeyFieldName': pkField, 'Description': ve.Description || null });
1179
- const newEntityId = createResult.recordset?.[0]?.['']
1180
- || createResult.recordset?.[0]?.ID
1181
- || createResult.recordset?.[0]?.Column0;
1182
- logStatus(` > Created virtual entity "${entityName}" (ID: ${newEntityId}) for view [${viewSchema}].[${viewName}]`);
1183
- createdCount++;
1184
- // Add virtual entity to the application for its schema and set default permissions
1185
- // (same logic as table-backed entities)
1186
- if (newEntityId) {
1187
- await this.addEntityToApplicationForSchema(pool, newEntityId, entityName, viewSchema, currentUser);
1188
- await this.addDefaultPermissionsForEntity(pool, newEntityId, entityName);
1189
- }
1272
+ const entityName = this.resolveVirtualEntityName(ve, viewSchema, existingEntityNames);
1273
+ if (!entityName) {
1274
+ logError(` > Entity name "${configuredName}" is already in use — skipping virtual entity creation for view [${viewSchema}].[${viewName}]. Set a different EntityName.`);
1275
+ continue;
1190
1276
  }
1191
- catch (err) {
1192
- const errMessage = err instanceof Error ? err.message : String(err);
1193
- logError(` > Failed to create virtual entity "${entityName}": ${errMessage}`);
1277
+ if (entityName !== configuredName) {
1278
+ logStatus(` > Entity name "${configuredName}" is already in use; using "${entityName}" for view [${viewSchema}].[${viewName}]`);
1279
+ }
1280
+ if (await this.createVirtualEntityFromConfig(pool, ve, entityName, viewSchema, currentUser)) {
1281
+ createdEntityNames.push(entityName);
1194
1282
  }
1195
1283
  }
1196
- return { success: true, createdCount };
1284
+ return { success: true, createdCount: createdEntityNames.length, createdEntityNames };
1285
+ }
1286
+ /**
1287
+ * Name for a new config-declared virtual entity, or null when its EntityName is already in use.
1288
+ * A name derived from the view gets the same collision suffix as a table-backed entity. Names are
1289
+ * compared without case, as UQ_Entity_Name does, and include the names created earlier in this run.
1290
+ */
1291
+ resolveVirtualEntityName(ve, viewSchema, existingEntityNames) {
1292
+ if (ve.EntityName) {
1293
+ return this.ResolveUniqueEntityName(ve.EntityName, viewSchema, existingEntityNames).suffix === '' ? ve.EntityName : null;
1294
+ }
1295
+ return this.ResolveUniqueEntityName(this.deriveEntityNameFromView(ve.ViewName), viewSchema, existingEntityNames).name;
1296
+ }
1297
+ /**
1298
+ * Writes the logged Entity INSERT and key seed for one config-declared virtual entity, registers it
1299
+ * in NewEntityList, adds it to its schema's application and grants the default permissions.
1300
+ * @returns true when the entity rows were written, even if the application or permission step failed
1301
+ */
1302
+ async createVirtualEntityFromConfig(pool, ve, entityName, viewSchema, currentUser) {
1303
+ const pkFields = ve.PrimaryKey && ve.PrimaryKey.length > 0 ? ve.PrimaryKey : ['ID'];
1304
+ let created = false;
1305
+ try {
1306
+ const newEntityId = this.createNewUUID();
1307
+ await this.logSQLAndExecute(pool, this.buildVirtualEntityInsertSQL(newEntityId, entityName, viewSchema, ve.ViewName, ve.Description ?? null), `SQL generated to create new virtual entity ${entityName}`);
1308
+ await this.logSQLAndExecute(pool, this.buildVirtualEntityPlaceholderPKSQL(this.createNewUUID(), newEntityId, pkFields[0], pkFields.length === 1), `SQL generated to seed primary key field ${pkFields[0]} for virtual entity ${entityName}`);
1309
+ logStatus(` > Created virtual entity "${entityName}" (ID: ${newEntityId}) for view [${viewSchema}].[${ve.ViewName}]`);
1310
+ ManageMetadataBase.NewEntityList.push(entityName);
1311
+ created = true;
1312
+ await this.addEntityToApplicationForSchema(pool, newEntityId, entityName, viewSchema, currentUser);
1313
+ await this.addDefaultPermissionsForEntity(pool, newEntityId, entityName);
1314
+ }
1315
+ catch (err) {
1316
+ const errMessage = err instanceof Error ? err.message : String(err);
1317
+ logError(` > Failed to create virtual entity "${entityName}": ${errMessage}`);
1318
+ }
1319
+ return created;
1197
1320
  }
1198
1321
  /**
1199
1322
  * Processes base-view materialization declarations from additionalSchemaInfo (plan §4.1).
@@ -1231,7 +1354,7 @@ export class ManageMetadataBase {
1231
1354
  // Refresh so entity.Fields reflect this run's field sync before we snapshot the shape.
1232
1355
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
1233
1356
  await md.Refresh();
1234
- const coreSchema = mj_core_schema();
1357
+ const coreSchema = MjCoreSchema();
1235
1358
  const esc = (s) => s.replace(/'/g, "''");
1236
1359
  const lit = (s) => (s ? `'${esc(s)}'` : 'NULL');
1237
1360
  let processedCount = 0;
@@ -1294,8 +1417,8 @@ export class ManageMetadataBase {
1294
1417
  // includeBatchSeparator: each is a single GO-free batch (executed via ds.query), but the
1295
1418
  // migration file needs a GO between statements for Flyway/sqlcmd. Pass the provider's
1296
1419
  // separator, not the 'GO' default: on PostgreSQL it is '' and a literal GO breaks replay.
1297
- await this.LogSQLAndExecute(pool, tableSQL, `Create materialized table for base-view materialization of entity ${entity.Name}`, false, true, this.dbProvider.BatchSeparator);
1298
- await this.LogSQLAndExecute(pool, viewSQL, `Create wrapper view for base-view materialization of entity ${entity.Name}`, false, true, this.dbProvider.BatchSeparator);
1420
+ await this.logSQLAndExecute(pool, tableSQL, `Create materialized table for base-view materialization of entity ${entity.Name}`, false, true, this.dbProvider.BatchSeparator);
1421
+ await this.logSQLAndExecute(pool, viewSQL, `Create wrapper view for base-view materialization of entity ${entity.Name}`, false, true, this.dbProvider.BatchSeparator);
1299
1422
  // 4) Upsert the MJ: Materialized Results row, keyed on (SourceType, SourceEntityID).
1300
1423
  const existing = await this.runQueryWithParams(pool, `SELECT ID FROM ${this.qs(coreSchema, 'MaterializedResult')} WHERE SourceType = @SourceType AND SourceEntityID = @EntityID`, { SourceType: 'EntityBaseView', EntityID: entity.ID });
1301
1424
  if (existing.recordset.length > 0) {
@@ -1303,7 +1426,7 @@ export class ManageMetadataBase {
1303
1426
  SET SchemaName='${esc(matSchema)}', TableName='${esc(tableName)}', ViewName='${esc(viewName)}',
1304
1427
  RefreshSchedule=${lit(decl.RefreshSchedule)}, IntendedWorkload=${lit(decl.IntendedWorkload)}
1305
1428
  WHERE ID='${existing.recordset[0].ID}'`;
1306
- await this.LogSQLAndExecute(pool, sqlUpd, `Update MJ: Materialized Results for base-view materialization of ${entity.Name}`);
1429
+ await this.logSQLAndExecute(pool, sqlUpd, `Update MJ: Materialized Results for base-view materialization of ${entity.Name}`);
1307
1430
  }
1308
1431
  else {
1309
1432
  const newId = this.createNewUUID();
@@ -1315,7 +1438,7 @@ export class ManageMetadataBase {
1315
1438
  VALUES ( '${newId}', 'EntityBaseView', '${entity.ID}', '${esc(matSchema)}', '${esc(tableName)}', '${esc(viewName)}',
1316
1439
  'None', 'FullRebuild', ${lit(decl.RefreshSchedule)}, 'Building', ${lit(decl.IntendedWorkload)},
1317
1440
  ${this.utcNow()}, ${this.utcNow()} )`;
1318
- await this.LogSQLAndExecute(pool, sqlIns, `Insert MJ: Materialized Results for base-view materialization of ${entity.Name}`);
1441
+ await this.logSQLAndExecute(pool, sqlIns, `Insert MJ: Materialized Results for base-view materialization of ${entity.Name}`);
1319
1442
  }
1320
1443
  processedCount++;
1321
1444
  logStatus(` > Base-view materialization ready for entity "${entity.Name}" → [${matSchema}].[${viewName}]`);
@@ -1329,7 +1452,7 @@ export class ManageMetadataBase {
1329
1452
  * fields, or a precise refusal (per-parameter reasons) so non-qualifying queries are skipped loudly.
1330
1453
  */
1331
1454
  async classifyParameterizedQueryForMaterialization(pool, queryId, queryName, outputColumns, currentUser) {
1332
- const coreSchema = mj_core_schema();
1455
+ const coreSchema = MjCoreSchema();
1333
1456
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
1334
1457
  // Load the query template + parameter definitions (typed entities for the renderer).
1335
1458
  const qRes = await this.runQueryWithParams(pool, `SELECT SQL, UsesTemplate FROM ${this.qs(coreSchema, 'Query')} WHERE ID = @QID`, { QID: queryId });
@@ -1361,31 +1484,31 @@ export class ManageMetadataBase {
1361
1484
  // Phase 2 is shipped: enable Bucket-1 row-filter broad materialization. The provider now auto-injects
1362
1485
  // the read-time predicate from the persisted ReadFilterSpec (bound params), so a RowFilterBroad
1363
1486
  // materialization is safe to mint. `allowRowFilterBroad` remains the build-level kill switch.
1364
- const classification = classifyQueryParameters({ queryName, params: paramDefs, outputColumns, dialect, render, allowRowFilterBroad: true });
1365
- if (!classification.qualification.qualifies) {
1366
- const detail = classification.perParam.map((pp) => `${pp.name}: ${pp.verdict.reason}`).join('; ');
1367
- return { qualifies: false, reason: `${classification.qualification.reason ?? 'parameters not materializable'}${detail ? ` — [${detail}]` : ''}` };
1487
+ const classification = ClassifyQueryParameters({ queryName, params: paramDefs, outputColumns, dialect, render, allowRowFilterBroad: true });
1488
+ if (!classification.Qualification.qualifies) {
1489
+ const detail = classification.PerParam.map((pp) => `${pp.name}: ${pp.verdict.reason}`).join('; ');
1490
+ return { qualifies: false, reason: `${classification.Qualification.reason ?? 'parameters not materializable'}${detail ? ` — [${detail}]` : ''}` };
1368
1491
  }
1369
- if (classification.qualification.paramMode !== 'RowFilterBroad') {
1370
- return { qualifies: false, reason: `parameterization mode '${classification.qualification.paramMode}' is not supported for materialization in v1 (only RowFilterBroad)` };
1492
+ if (classification.Qualification.paramMode !== 'RowFilterBroad') {
1493
+ return { qualifies: false, reason: `parameterization mode '${classification.Qualification.paramMode}' is not supported for materialization in v1 (only RowFilterBroad)` };
1371
1494
  }
1372
1495
  // Build the broad source SQL: render a concrete instance (held values) then strip the row-filter predicates.
1373
1496
  let renderedHeld;
1374
1497
  try {
1375
- renderedHeld = render(buildHeldValues(paramDefs));
1498
+ renderedHeld = render(BuildHeldValues(paramDefs));
1376
1499
  }
1377
1500
  catch (e) {
1378
1501
  return { qualifies: false, reason: `could not render the query to build broad SQL: ${e instanceof Error ? e.message : String(e)}` };
1379
1502
  }
1380
- const expectedRemovals = classification.qualification.rowFilterColumns.length;
1381
- const broad = buildBroadRowFilterSQL(renderedHeld, classification.qualification.rowFilterColumns, dialect, expectedRemovals);
1382
- if (broad.removedCount === 0) {
1383
- return { qualifies: false, reason: `expected to strip row-filter predicate(s) on [${classification.qualification.rowFilterColumns.join(', ')}] but none were removed from the rendered SQL — refusing to avoid a wrongly-filtered materialization` };
1503
+ const expectedRemovals = classification.Qualification.rowFilterColumns.length;
1504
+ const broad = BuildBroadRowFilterSQL(renderedHeld, classification.Qualification.rowFilterColumns, dialect, expectedRemovals);
1505
+ if (broad.RemovedCount === 0) {
1506
+ return { qualifies: false, reason: `expected to strip row-filter predicate(s) on [${classification.Qualification.rowFilterColumns.join(', ')}] but none were removed from the rendered SQL — refusing to avoid a wrongly-filtered materialization` };
1384
1507
  }
1385
- if (broad.ambiguous) {
1386
- return { qualifies: false, reason: `expected to strip exactly ${expectedRemovals} row-filter parameter predicate(s) on [${classification.qualification.rowFilterColumns.join(', ')}] but matched ${broad.removedCount} — the parameter predicate(s) cannot be cleanly isolated from other static or same-named predicates on those columns, so a broad materialization would include or exclude rows the live query never would. Refusing (query stays live-only).` };
1508
+ if (broad.Ambiguous) {
1509
+ return { qualifies: false, reason: `expected to strip exactly ${expectedRemovals} row-filter parameter predicate(s) on [${classification.Qualification.rowFilterColumns.join(', ')}] but matched ${broad.RemovedCount} — the parameter predicate(s) cannot be cleanly isolated from other static or same-named predicates on those columns, so a broad materialization would include or exclude rows the live query never would. Refusing (query stays live-only).` };
1387
1510
  }
1388
- return { qualifies: true, rowFilterColumns: classification.qualification.rowFilterColumns, broadSQL: broad.sql, readFilterSpec: classification.qualification.readFilterSpec };
1511
+ return { qualifies: true, rowFilterColumns: classification.Qualification.rowFilterColumns, broadSQL: broad.Sql, readFilterSpec: classification.Qualification.readFilterSpec };
1389
1512
  }
1390
1513
  /**
1391
1514
  * Processes query materialization (CodeGen materialization phase, sub-step C — plan §4.2).
@@ -1404,7 +1527,7 @@ export class ManageMetadataBase {
1404
1527
  * Parameterized queries are skipped with a log (deferred to Phase 2).
1405
1528
  */
1406
1529
  async processQueryMaterializations(pool, currentUser) {
1407
- const coreSchema = mj_core_schema();
1530
+ const coreSchema = MjCoreSchema();
1408
1531
  // Gate the whole method on the IsMaterialized column existing — the flagged-query SELECT below filters on it,
1409
1532
  // and it (like the MaterializedResult table) is added by the materialization Foundation migration. On a DB
1410
1533
  // where that migration hasn't run yet the SELECT would throw and abort the entire codegen pass; with no such
@@ -1468,7 +1591,7 @@ export class ManageMetadataBase {
1468
1591
  // Detected BEFORE the shape analysis so the surrogate column can be typed for the keyed case.
1469
1592
  const detectSQL = paramMode === 'RowFilterBroad' ? (broadSQL ?? '') : querySQL;
1470
1593
  const matDialect = this.dbProvider.PlatformKey === 'postgresql' ? new PostgreSQLDialect() : new SQLServerDialect();
1471
- const detectedKeyColumns = detectSQL ? detectAggregationKeyColumns({ sql: detectSQL, dialect: matDialect, fields }) : null;
1594
+ const detectedKeyColumns = detectSQL ? DetectAggregationKeyColumns({ sql: detectSQL, dialect: matDialect, fields }) : null;
1472
1595
  // An EXTERNAL query refreshes via rebuildFromExternalQuery, which fetches all rows through the EDS
1473
1596
  // driver and writes a SYNTHETIC row-index surrogate — it cannot compute the per-group combined-key
1474
1597
  // hash and ignores KeyColumns entirely. So minting a keyed (hash-surrogate) entity for an external
@@ -1494,7 +1617,7 @@ export class ManageMetadataBase {
1494
1617
  // The materialized table's column shape is the query's output columns — independent of
1495
1618
  // parameterization (a row-filter query is materialized broad over the same columns). Pass
1496
1619
  // isParameterized:false so the analyzer yields the shape; the param gate above already ran.
1497
- const analysis = analyzeQueryForMaterialization({ queryName, isParameterized: false, fields, surrogateSQLType });
1620
+ const analysis = AnalyzeQueryForMaterialization({ queryName, isParameterized: false, fields, surrogateSQLType });
1498
1621
  if (!analysis.qualifies) {
1499
1622
  logStatus(` > Skipping materialization of query "${queryName}": ${analysis.reason}`);
1500
1623
  continue;
@@ -1512,7 +1635,7 @@ export class ManageMetadataBase {
1512
1635
  const isKeyedSingleSource = isKeyed && !!detectSQL && SQLParser.ExtractTableRefs(detectSQL, matDialect).length === 1;
1513
1636
  const refreshStrategy = !isKeyedSingleSource
1514
1637
  ? 'FullRebuild'
1515
- : detectAdditiveMeasures(detectSQL)
1638
+ : DetectAdditiveMeasures(detectSQL)
1516
1639
  ? 'Incremental'
1517
1640
  : 'DirtyGroupRecompute';
1518
1641
  // RLS downgrade gate (§6.2, ships day one) — a materialized query entity does NOT inherit its
@@ -1551,10 +1674,10 @@ export class ManageMetadataBase {
1551
1674
  logError(` > REFUSING to materialize query "${queryName}": its derived table [${coreSchema}].[${tableName}] (from CodeName "${codeName}") is already owned by a different materialization (SourceType=${foreignOwner.SourceType}, QueryID=${foreignOwner.QueryID ?? 'n/a'}). Two sources whose names normalize to the same CodeName would clobber each other's snapshot — rename one so their CodeNames differ. Skipping.`);
1552
1675
  continue;
1553
1676
  }
1554
- const tableSQL = this.dbProvider.generateMaterializedTableSQL(coreSchema, tableName, analysis.columns);
1677
+ const tableSQL = this.dbProvider.generateMaterializedTableSQL(coreSchema, tableName, analysis.Columns);
1555
1678
  const viewSQL = this.dbProvider.generateMaterializedWrapperViewSQL(coreSchema, viewName, tableName);
1556
- await this.LogSQLAndExecute(pool, tableSQL, `Create materialized table for query "${queryName}"`, false, true, this.dbProvider.BatchSeparator);
1557
- await this.LogSQLAndExecute(pool, viewSQL, `Create wrapper view for query "${queryName}"`, false, true, this.dbProvider.BatchSeparator);
1679
+ await this.logSQLAndExecute(pool, tableSQL, `Create materialized table for query "${queryName}"`, false, true, this.dbProvider.BatchSeparator);
1680
+ await this.logSQLAndExecute(pool, viewSQL, `Create wrapper view for query "${queryName}"`, false, true, this.dbProvider.BatchSeparator);
1558
1681
  // 3) Mint the read-only Virtual Entity over the wrapper view (idempotent by view).
1559
1682
  const existingVE = await this.runQueryWithParams(pool, `SELECT ID FROM ${this.qs(coreSchema, 'vwEntities')} WHERE BaseView = @V AND SchemaName = @S`, { V: viewName, S: coreSchema });
1560
1683
  let generatedEntityId = existingVE.recordset[0]?.ID;
@@ -1564,7 +1687,7 @@ export class ManageMetadataBase {
1564
1687
  Name: queryName,
1565
1688
  BaseView: viewName,
1566
1689
  SchemaName: coreSchema,
1567
- PrimaryKeyFieldName: analysis.surrogateColumnName,
1690
+ PrimaryKeyFieldName: analysis.SurrogateColumnName,
1568
1691
  Description: `Materialized result of query "${queryName}".`,
1569
1692
  });
1570
1693
  generatedEntityId = createRes.recordset?.[0]?.[''] || createRes.recordset?.[0]?.ID || createRes.recordset?.[0]?.Column0;
@@ -1603,7 +1726,7 @@ export class ManageMetadataBase {
1603
1726
  SET GeneratedEntityID=${idLit(generatedEntityId)}, SchemaName='${esc(coreSchema)}', TableName='${esc(tableName)}', ViewName='${esc(viewName)}',
1604
1727
  ${this.qi('ParamMode')}='${paramMode}', ${this.qi('RowFilterColumns')}=${rowFilterColumnsLit}, ${this.qi('BroadSQL')}=${broadSQLLit}, ${this.qi('ReadFilterSpec')}=${readFilterSpecLit}, ${this.qi('KeyColumns')}=${keyColumnsLit}, ${this.qi('RefreshStrategy')}='${refreshStrategy}'
1605
1728
  WHERE ID='${matResultId}'`;
1606
- await this.LogSQLAndExecute(pool, sqlUpd, `Update MJ: Materialized Results for query "${queryName}"`);
1729
+ await this.logSQLAndExecute(pool, sqlUpd, `Update MJ: Materialized Results for query "${queryName}"`);
1607
1730
  }
1608
1731
  else {
1609
1732
  matResultId = this.createNewUUID();
@@ -1613,13 +1736,13 @@ export class ManageMetadataBase {
1613
1736
  ${c('ParamMode')}, ${c('RowFilterColumns')}, ${c('BroadSQL')}, ${c('ReadFilterSpec')}, ${c('KeyColumns')}, ${c('RefreshStrategy')}, ${c('Status')}, ${c('__mj_CreatedAt')}, ${c('__mj_UpdatedAt')} )
1614
1737
  VALUES ( '${matResultId}', 'Query', ${idLit(generatedEntityId)}, '${esc(coreSchema)}', '${esc(tableName)}', '${esc(viewName)}',
1615
1738
  '${paramMode}', ${rowFilterColumnsLit}, ${broadSQLLit}, ${readFilterSpecLit}, ${keyColumnsLit}, '${refreshStrategy}', 'Building', ${this.utcNow()}, ${this.utcNow()} )`;
1616
- await this.LogSQLAndExecute(pool, sqlIns, `Insert MJ: Materialized Results for query "${queryName}"`);
1739
+ await this.logSQLAndExecute(pool, sqlIns, `Insert MJ: Materialized Results for query "${queryName}"`);
1617
1740
  // Link the new materialization to its source Query via the join table.
1618
1741
  const joinId = this.createNewUUID();
1619
1742
  const sqlJoinIns = `INSERT INTO ${this.qs(coreSchema, 'MaterializedResultQuery')} (
1620
1743
  ${c('ID')}, ${c('MaterializedResultID')}, ${c('QueryID')}, ${c('__mj_CreatedAt')}, ${c('__mj_UpdatedAt')} )
1621
1744
  VALUES ( '${joinId}', '${matResultId}', '${queryId}', ${this.utcNow()}, ${this.utcNow()} )`;
1622
- await this.LogSQLAndExecute(pool, sqlJoinIns, `Link MJ: Materialized Results to Query "${queryName}" via join row`);
1745
+ await this.logSQLAndExecute(pool, sqlJoinIns, `Link MJ: Materialized Results to Query "${queryName}" via join row`);
1623
1746
  }
1624
1747
  processedCount++;
1625
1748
  }
@@ -1636,7 +1759,7 @@ export class ManageMetadataBase {
1636
1759
  * auto-rebuilds. Already-held (`DriftHold`) and `Disabled` rows are skipped.
1637
1760
  */
1638
1761
  async detectMaterializationDrift(pool) {
1639
- const coreSchema = mj_core_schema();
1762
+ const coreSchema = MjCoreSchema();
1640
1763
  // Gate on MaterializedResult existing — the SELECT below reads it. Absent (materialization migration not yet
1641
1764
  // applied on this DB) ⇒ no materializations exist to check for drift; skip cleanly rather than throwing and
1642
1765
  // aborting the codegen pass.
@@ -1741,14 +1864,14 @@ export class ManageMetadataBase {
1741
1864
  // would only stop FUTURE refreshes while leaving the already-populated rows queryable via raw SQL
1742
1865
  // over the wrapper view. Emptying (not dropping) removes the leaked data without breaking any object
1743
1866
  // dependency; the wrapper view remains but returns nothing. Then DriftHold so refresh never refills it.
1744
- await this.LogSQLAndExecute(pool, `DELETE FROM ${this.qs(r.SchemaName, r.TableName)}`, `Empty external RLS base-view mirror "${r.TableName}" (leak guard — mirror exposed RLS-refused rows)`);
1745
- await this.LogSQLAndExecute(pool, `UPDATE ${this.qs(coreSchema, 'MaterializedResult')} SET ${this.qi('Status')}='DriftHold' WHERE ID='${r.ID}'`, `Flag external RLS base-view materialization "${r.TableName}" as DriftHold (leak guard)`);
1867
+ await this.logSQLAndExecute(pool, `DELETE FROM ${this.qs(r.SchemaName, r.TableName)}`, `Empty external RLS base-view mirror "${r.TableName}" (leak guard — mirror exposed RLS-refused rows)`);
1868
+ await this.logSQLAndExecute(pool, `UPDATE ${this.qs(coreSchema, 'MaterializedResult')} SET ${this.qi('Status')}='DriftHold' WHERE ID='${r.ID}'`, `Flag external RLS base-view materialization "${r.TableName}" as DriftHold (leak guard)`);
1746
1869
  logError(` > RLS LEAK GUARD: base-view materialization "${r.TableName}" mirrors an EXTERNAL row-restricted entity ("${bvEntity.Name}" — role RLS and/or an API-key row filter) → mirror EMPTIED + DriftHold (refresh stopped). It exposed rows the live path refuses under RLS.`);
1747
1870
  return true;
1748
1871
  }
1749
1872
  }
1750
1873
  const facts = await this.gatherDriftFacts(pool, md, r, coreSchema);
1751
- const verdict = evaluateMaterializationDrift(facts);
1874
+ const verdict = EvaluateMaterializationDrift(facts);
1752
1875
  if (verdict.drift) {
1753
1876
  // Fail-closed on ANY hold of a QUERY materialization: once held, the row drops out of
1754
1877
  // detectMaterializationDrift's `Status NOT IN ('DriftHold', ...)` scan, so the C1 RLS re-check and the
@@ -1760,7 +1883,7 @@ export class ManageMetadataBase {
1760
1883
  if (r.SourceType === 'Query' && r.GeneratedEntityID) {
1761
1884
  await this.revokeMaterializedEntityReadAccess(pool, r.GeneratedEntityID, r.TableName, `drift hold — ${verdict.reason ?? 'shape/provenance drift'}`);
1762
1885
  }
1763
- await this.LogSQLAndExecute(pool, `UPDATE ${this.qs(coreSchema, 'MaterializedResult')} SET ${this.qi('Status')}='DriftHold' WHERE ID='${r.ID}'`, `Flag materialization "${r.TableName}" as DriftHold`);
1886
+ await this.logSQLAndExecute(pool, `UPDATE ${this.qs(coreSchema, 'MaterializedResult')} SET ${this.qi('Status')}='DriftHold' WHERE ID='${r.ID}'`, `Flag materialization "${r.TableName}" as DriftHold`);
1764
1887
  logStatus(` > DRIFT: materialization "${r.TableName}" → DriftHold — ${verdict.reason}`);
1765
1888
  return true;
1766
1889
  }
@@ -1794,7 +1917,7 @@ export class ManageMetadataBase {
1794
1917
  if (r.GeneratedEntityID) {
1795
1918
  await this.revokeMaterializedEntityReadAccess(pool, r.GeneratedEntityID, r.TableName, reason);
1796
1919
  }
1797
- await this.LogSQLAndExecute(pool, `UPDATE ${this.qs(coreSchema, 'MaterializedResult')} SET ${this.qi('Status')}='DriftHold' WHERE ID='${r.ID}'`, `Flag materialization "${r.TableName}" as DriftHold (${label.toLowerCase()})`);
1920
+ await this.logSQLAndExecute(pool, `UPDATE ${this.qs(coreSchema, 'MaterializedResult')} SET ${this.qi('Status')}='DriftHold' WHERE ID='${r.ID}'`, `Flag materialization "${r.TableName}" as DriftHold (${label.toLowerCase()})`);
1798
1921
  logError(` > ${label}: materialization "${r.TableName}" → read access revoked + DriftHold — ${reason}`);
1799
1922
  }
1800
1923
  /** Gathers the drift-relevant existence facts for one materialization against current metadata. */
@@ -1905,7 +2028,7 @@ export class ManageMetadataBase {
1905
2028
  * @param pool - the ConnectionPool object to use for querying and updating the database
1906
2029
  * @returns
1907
2030
  */
1908
- async manageMetadata(pool, currentUser) {
2031
+ async ManageMetadata(pool, currentUser) {
1909
2032
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
1910
2033
  // Auto-exclude platform-specific system schemas.
1911
2034
  // We mutate configInfo.excludeSchemas directly so that all downstream code
@@ -1926,7 +2049,7 @@ export class ManageMetadataBase {
1926
2049
  // machinery — when the provider supplies DDL (PostgreSQL), we install it
1927
2050
  // idempotently here rather than depending on migrations to have shipped
1928
2051
  // it. Nothing below can work without them, so a failure here is fatal.
1929
- const supportObjectsSQL = this.dbProvider.getMetadataSupportObjectsSQL(mj_core_schema());
2052
+ const supportObjectsSQL = this.dbProvider.getMetadataSupportObjectsSQL(MjCoreSchema());
1930
2053
  if (supportObjectsSQL) {
1931
2054
  try {
1932
2055
  await pool.query(supportObjectsSQL);
@@ -1940,7 +2063,7 @@ export class ManageMetadataBase {
1940
2063
  // Authored exclude list (sys, staging, …) must be captured BEFORE includeSchemas is
1941
2064
  // compiled into excludeSchemas. Heal EXEC statements use that original list plus
1942
2065
  // @IncludedSchemaNames — never the sibling snapshot of this machine's database.
1943
- snapshotAuthoredExcludeSchemas(configInfo.excludeSchemas);
2066
+ SnapshotAuthoredExcludeSchemas(configInfo.excludeSchemas);
1944
2067
  // Resolve the opt-in `includeSchemas` positive scope into excludeSchemas, BEFORE the exclude
1945
2068
  // snapshot below and before createNewEntities() runs. The universe is queried from the DATABASE
1946
2069
  // rather than taken from loaded metadata on purpose: createNewEntities() discovers tables with no
@@ -1950,12 +2073,12 @@ export class ManageMetadataBase {
1950
2073
  // every run after, orphaning its entity records). No-op when includeSchemas is unset.
1951
2074
  if (configInfo.includeSchemas && configInfo.includeSchemas.length > 0) {
1952
2075
  try {
1953
- const schemaSQL = `SELECT DISTINCT ${this.qi('SchemaName')} FROM ${this.qs(mj_core_schema(), 'vwSQLTablesAndEntities')}`;
2076
+ const schemaSQL = `SELECT DISTINCT ${this.qi('SchemaName')} FROM ${this.qs(MjCoreSchema(), 'vwSQLTablesAndEntities')}`;
1954
2077
  const schemaResult = await this.runQuery(pool, schemaSQL);
1955
2078
  const allSchemas = (schemaResult.recordset ?? [])
1956
2079
  .map((r) => r.SchemaName)
1957
2080
  .filter((s) => !!s);
1958
- const newlyExcluded = applyIncludeSchemaScope(allSchemas, configInfo);
2081
+ const newlyExcluded = ApplyIncludeSchemaScope(allSchemas, configInfo);
1959
2082
  logStatus(` Applied includeSchemas scope [${configInfo.includeSchemas.join(', ')}] — excluded ${newlyExcluded.length} other schema(s) present in the database`);
1960
2083
  }
1961
2084
  catch (e) {
@@ -2005,12 +2128,12 @@ export class ManageMetadataBase {
2005
2128
  start = new Date();
2006
2129
  logStatus(' Recompiling base views...');
2007
2130
  const sqlUtility = MJGlobal.Instance.ClassFactory.CreateInstance(SQLUtilityBase);
2008
- const adminSchema = getSettingValue('mj_core_schema', '__mj');
2009
- const schemasToExclude = getSettingValue('recompile_mj_views', true)
2131
+ const adminSchema = GetSettingValue('mj_core_schema', '__mj');
2132
+ const schemasToExclude = GetSettingValue('recompile_mj_views', true)
2010
2133
  ? excludeSchemas.filter((s) => s !== adminSchema)
2011
2134
  : excludeSchemas;
2012
2135
  if (!await sqlUtility.recompileAllBaseViews(pool, schemasToExclude, true, ManageMetadataBase._newEntityList /*exclude the newly created entities from the above step the first time we run as those views don't exist yet*/)) {
2013
- logMessage(' Warning: Non-Fatal error recompiling base views', SeverityType.Warning, false);
2136
+ LogMessage(' Warning: Non-Fatal error recompiling base views', SeverityType.Warning, false);
2014
2137
  // many times the former versions of base views will NOT succesfully recompile, so don't consider that scenario to be a
2015
2138
  // failure for this entire function
2016
2139
  }
@@ -2021,7 +2144,7 @@ export class ManageMetadataBase {
2021
2144
  // Also skip deleting unneeded fields on this first pass — base views haven't been regenerated yet,
2022
2145
  // so virtual fields (which come from view JOINs) would be incorrectly identified as orphaned and deleted.
2023
2146
  // Deletion runs on the second pass (in sql_codegen.ts) after views are current.
2024
- if (!await this.manageEntityFields(pool, excludeSchemas, false, false, currentUser, true, true)) {
2147
+ if (!await this.ManageEntityFields(pool, excludeSchemas, false, false, currentUser, true, true)) {
2025
2148
  logError(' Error managing entity fields');
2026
2149
  bSuccess = false;
2027
2150
  }
@@ -2038,7 +2161,7 @@ export class ManageMetadataBase {
2038
2161
  }
2039
2162
  // Config-driven virtual entity creation — run BEFORE manageVirtualEntities
2040
2163
  // so newly created entities get their fields synced in the next step
2041
- const vecResult = await this.processVirtualEntityConfig(pool, currentUser);
2164
+ const vecResult = await this.processVirtualEntityConfig(pool, currentUser, md);
2042
2165
  if (vecResult.createdCount > 0) {
2043
2166
  logStatus(` > Created ${vecResult.createdCount} virtual entit${vecResult.createdCount === 1 ? 'y' : 'ies'} from config`);
2044
2167
  // Refresh metadata so manageVirtualEntities can find the newly-created entities
@@ -2058,6 +2181,11 @@ export class ManageMetadataBase {
2058
2181
  logError(' Error managing virtual entities');
2059
2182
  bSuccess = false;
2060
2183
  }
2184
+ // VirtualEntities keys apply after the view-column sync, so a new entity or a new view column
2185
+ // gets its configured key in this run — the same second pass external entities get below.
2186
+ if (!await this.applyConfiguredVirtualEntityKeys(pool, excludeSchemas, md)) {
2187
+ bSuccess = false;
2188
+ }
2061
2189
  // External-data-source entities: introspect the REMOTE schema and sync their EntityField rows
2062
2190
  // (the remote analogue of reading the local view's columns for a virtual entity).
2063
2191
  const eeResult = await this.manageExternalEntities(pool, currentUser);
@@ -2134,6 +2262,10 @@ export class ManageMetadataBase {
2134
2262
  await this.checkEntityFieldSequenceIntegrity(pool, excludeSchemas);
2135
2263
  return bSuccess;
2136
2264
  }
2265
+ /** @deprecated Use {@link ManageMetadata}. */
2266
+ async manageMetadata(pool, currentUser) {
2267
+ return this.ManageMetadata(pool, currentUser);
2268
+ }
2137
2269
  /**
2138
2270
  * INTEGRITY CHECK — in a well-formed entity every base (non-virtual) field sequences BEFORE the
2139
2271
  * virtual/related fields, so the EntityField order matches the base view's `SELECT [base].*, <joins>`
@@ -2147,10 +2279,10 @@ export class ManageMetadataBase {
2147
2279
  async checkEntityFieldSequenceIntegrity(pool, excludeSchemas) {
2148
2280
  try {
2149
2281
  const excl = excludeSchemas.length > 0
2150
- ? `WHERE ${this.qi('EntityID')} NOT IN (SELECT ${this.qi('ID')} FROM ${this.qs(mj_core_schema(), 'Entity')} WHERE ${this.qi('SchemaName')} IN (${excludeSchemas.map(s => `'${s}'`).join(',')}))`
2282
+ ? `WHERE ${this.qi('EntityID')} NOT IN (SELECT ${this.qi('ID')} FROM ${this.qs(MjCoreSchema(), 'Entity')} WHERE ${this.qi('SchemaName')} IN (${excludeSchemas.map(s => `'${s}'`).join(',')}))`
2151
2283
  : '';
2152
2284
  const sSQL = `SELECT ${this.qi('EntityID')}, ${this.qi('Entity')}, ${this.qi('Name')}, ${this.qi('Sequence')}, ${this.qi('IsVirtual')}
2153
- FROM ${this.qs(mj_core_schema(), 'vwEntityFields')}
2285
+ FROM ${this.qs(MjCoreSchema(), 'vwEntityFields')}
2154
2286
  ${excl}
2155
2287
  ORDER BY ${this.qi('EntityID')}, ${this.qi('Sequence')}, ${this.qi('Name')}`;
2156
2288
  const result = await this.runQuery(pool, sSQL);
@@ -2202,7 +2334,7 @@ export class ManageMetadataBase {
2202
2334
  // virtual entities are records defined in the entity metadata and do NOT define a distinct base table
2203
2335
  // but they do specify a base view. We DO NOT generate a base view for a virtual entity, we simply use it to figure
2204
2336
  // out the fields that should be in the entity definition and add/update/delete the entity definition to match what's in the view when this runs
2205
- const sql = `SELECT * FROM ${this.qs(mj_core_schema(), 'vwEntities')} WHERE VirtualEntity = ${this.boolLit(true)}`;
2337
+ const sql = `SELECT * FROM ${this.qs(MjCoreSchema(), 'vwEntities')} WHERE VirtualEntity = ${this.boolLit(true)}`;
2206
2338
  const virtualEntitiesResult = await this.runQuery(pool, sql);
2207
2339
  const virtualEntities = virtualEntitiesResult.recordset;
2208
2340
  let anyUpdates = false;
@@ -2262,7 +2394,7 @@ export class ManageMetadataBase {
2262
2394
  async materializedResultTableExists(pool) {
2263
2395
  if (this._materializedResultTableExists === null) {
2264
2396
  const sql = `SELECT COUNT(*) AS TblExists FROM INFORMATION_SCHEMA.TABLES ` +
2265
- `WHERE TABLE_SCHEMA = '${mj_core_schema()}' AND TABLE_NAME = 'MaterializedResult'`;
2397
+ `WHERE TABLE_SCHEMA = '${MjCoreSchema()}' AND TABLE_NAME = 'MaterializedResult'`;
2266
2398
  const result = await this.runQuery(pool, sql);
2267
2399
  const row = (result.recordset?.[0] ?? {});
2268
2400
  const cnt = row.TblExists ?? row.tblexists ?? 0;
@@ -2280,7 +2412,7 @@ export class ManageMetadataBase {
2280
2412
  if (!(await this.entityHasExternalDataSourceColumn(pool))) {
2281
2413
  return { success: true, anyUpdates: false, relationshipsUpdated: false };
2282
2414
  }
2283
- const sql = `SELECT * FROM ${this.qs(mj_core_schema(), 'vwEntities')} WHERE ExternalDataSourceID IS NOT NULL`;
2415
+ const sql = `SELECT * FROM ${this.qs(MjCoreSchema(), 'vwEntities')} WHERE ExternalDataSourceID IS NOT NULL`;
2284
2416
  const result = await this.runQuery(pool, sql);
2285
2417
  const externalEntities = result.recordset;
2286
2418
  if (!externalEntities || externalEntities.length === 0) {
@@ -2397,16 +2529,16 @@ export class ManageMetadataBase {
2397
2529
  }
2398
2530
  // Map each introspected column into the veField shape that manageSingleVirtualEntityField consumes.
2399
2531
  const eeFields = obj.Columns.map(c => {
2400
- const t = mapExternalNativeTypeToMJ(c.NativeType);
2532
+ const t = MapExternalNativeTypeToMJ(c.NativeType);
2401
2533
  return { FieldName: c.Name, Type: t.Type, Length: t.Length, Precision: t.Precision, Scale: t.Scale, AllowsNull: c.Nullable, IsPrimaryKey: c.IsPrimaryKey };
2402
2534
  });
2403
2535
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
2404
2536
  const entity = md.EntityByName(externalEntity.Name);
2405
2537
  if (entity) {
2406
2538
  // remove EntityFields no longer present in the remote object
2407
- const sqlRemove = this.buildExternalFieldRemoveSQL(mj_core_schema(), entity.Fields, eeFields.map(ef => ef.FieldName));
2539
+ const sqlRemove = this.buildExternalFieldRemoveSQL(MjCoreSchema(), entity.Fields, eeFields.map(ef => ef.FieldName));
2408
2540
  if (sqlRemove) {
2409
- await this.LogSQLAndExecute(pool, sqlRemove, `SQL text to remove fields from external entity ${externalEntity.Name}`);
2541
+ await this.logSQLAndExecute(pool, sqlRemove, `SQL text to remove fields from external entity ${externalEntity.Name}`);
2410
2542
  bUpdated = true;
2411
2543
  }
2412
2544
  // create/update each remote column. Use the real PK info from introspection; fall back
@@ -2437,8 +2569,8 @@ export class ManageMetadataBase {
2437
2569
  }
2438
2570
  }
2439
2571
  if (bUpdated) {
2440
- const sqlUpdate = `UPDATE ${this.qs(mj_core_schema(), 'Entity')} SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()} WHERE ID='${externalEntity.ID}'`;
2441
- await this.LogSQLAndExecute(pool, sqlUpdate, `SQL text to update external entity updated date for ${externalEntity.Name}`);
2572
+ const sqlUpdate = `UPDATE ${this.qs(MjCoreSchema(), 'Entity')} SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()} WHERE ID='${externalEntity.ID}'`;
2573
+ await this.logSQLAndExecute(pool, sqlUpdate, `SQL text to update external entity updated date for ${externalEntity.Name}`);
2442
2574
  }
2443
2575
  return { success: bSuccess, updatedEntity: bUpdated, relationshipsUpdated: bRelationshipsUpdated };
2444
2576
  }
@@ -2495,7 +2627,7 @@ export class ManageMetadataBase {
2495
2627
  if (alreadySet) {
2496
2628
  continue;
2497
2629
  }
2498
- sqlStatements.push(`UPDATE ${this.qs(mj_core_schema(), 'EntityField')}
2630
+ sqlStatements.push(`UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
2499
2631
  SET RelatedEntityID='${relatedEntity.ID}',
2500
2632
  RelatedEntityFieldName='${refColumn.replace(/'/g, "''")}',
2501
2633
  IsSoftForeignKey=1
@@ -2505,7 +2637,7 @@ export class ManageMetadataBase {
2505
2637
  if (sqlStatements.length === 0) {
2506
2638
  return false;
2507
2639
  }
2508
- await this.LogSQLBatchAndExecute(pool, sqlStatements, `Set external foreign keys for ${externalEntity.Name}`);
2640
+ await this.logSQLBatchAndExecute(pool, sqlStatements, `Set external foreign keys for ${externalEntity.Name}`);
2509
2641
  return true;
2510
2642
  }
2511
2643
  async manageSingleVirtualEntity(pool, virtualEntity) {
@@ -2524,19 +2656,22 @@ export class ManageMetadataBase {
2524
2656
  const entity = md.EntityByName(virtualEntity.Name);
2525
2657
  if (entity) {
2526
2658
  const removeList = [];
2527
- const fieldsToRemove = entity.Fields.filter(f => !veFields.find((vf) => vf.FieldName === f.Name));
2659
+ // Same case-insensitive match as manageSingleVirtualEntityField, which keeps the row and fixes its casing
2660
+ const fieldsToRemove = entity.Fields.filter(f => !veFields.find((vf) => vf.FieldName.trim().toLowerCase() === f.Name.trim().toLowerCase()));
2528
2661
  for (const f of fieldsToRemove) {
2529
2662
  removeList.push(f.ID);
2530
2663
  }
2531
2664
  if (removeList.length > 0) {
2532
- const sqlRemove = `DELETE FROM ${this.qs(mj_core_schema(), 'EntityField')} WHERE ID IN (${removeList.map(removeId => `'${removeId}'`).join(',')})`;
2665
+ const sqlRemove = `DELETE FROM ${this.qs(MjCoreSchema(), 'EntityField')} WHERE ID IN (${removeList.map(removeId => `'${removeId}'`).join(',')})`;
2533
2666
  // this removes the fields that shouldn't be there anymore
2534
- await this.LogSQLAndExecute(pool, sqlRemove, `SQL text to remove fields from entity ${virtualEntity.Name}`);
2667
+ await this.logSQLAndExecute(pool, sqlRemove, `SQL text to remove fields from entity ${virtualEntity.Name}`);
2535
2668
  bUpdated = true;
2536
2669
  }
2537
- // check to see if any of the fields in the virtual entity have Pkey attribute set. If not, we will default to the first field
2538
- // as pkey and user can change this.
2539
- const hasPkey = entity.Fields.find(f => f.IsPrimaryKey) !== undefined;
2670
+ // A key must survive the removal above; otherwise the first view column becomes the key.
2671
+ const hasPkey = this.virtualEntityHasPrimaryKey(entity.Fields, new Set(removeList));
2672
+ if (!hasPkey) {
2673
+ logStatus(` ⚠️ Virtual entity ${virtualEntity.Name} has no primary key; using first view column ${veFields[0].FieldName}. Set PrimaryKey in additionalSchemaInfo to choose the key.`);
2674
+ }
2540
2675
  // now create/update the fields that are in the view
2541
2676
  for (let i = 0; i < veFields.length; i++) {
2542
2677
  const vef = veFields[i];
@@ -2551,8 +2686,8 @@ export class ManageMetadataBase {
2551
2686
  }
2552
2687
  if (bUpdated) {
2553
2688
  // finally make sure we update the UpdatedAt field for the entity if we made changes to its fields
2554
- const sqlUpdate = `UPDATE ${this.qs(mj_core_schema(), 'Entity')} SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()} WHERE ID='${virtualEntity.ID}'`;
2555
- await this.LogSQLAndExecute(pool, sqlUpdate, `SQL text to update virtual entity updated date for ${virtualEntity.Name}`);
2689
+ const sqlUpdate = `UPDATE ${this.qs(MjCoreSchema(), 'Entity')} SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()} WHERE ID='${virtualEntity.ID}'`;
2690
+ await this.logSQLAndExecute(pool, sqlUpdate, `SQL text to update virtual entity updated date for ${virtualEntity.Name}`);
2556
2691
  }
2557
2692
  return { success: bSuccess, updatedEntity: bUpdated };
2558
2693
  }
@@ -2569,6 +2704,13 @@ export class ManageMetadataBase {
2569
2704
  resolvePrimaryKeyFlags(makePrimaryKey, singleColumnPrimaryKey) {
2570
2705
  return { wantPrimaryKey: makePrimaryKey, wantUnique: makePrimaryKey && singleColumnPrimaryKey };
2571
2706
  }
2707
+ /**
2708
+ * True when a key field survives the removal of view columns that no longer exist.
2709
+ * The cached field list still holds rows the sync just deleted, so they must be excluded.
2710
+ */
2711
+ virtualEntityHasPrimaryKey(fields, removedFieldIDs) {
2712
+ return fields.some(f => f.IsPrimaryKey && !removedFieldIDs.has(f.ID));
2713
+ }
2572
2714
  /**
2573
2715
  * Whether a field's PK/Unique flags need to change. In RECONCILE mode (external entities, whose
2574
2716
  * introspected PK set is authoritative across ALL fields) we sync in BOTH directions — setting the
@@ -2611,7 +2753,9 @@ export class ManageMetadataBase {
2611
2753
  // bootstrap, not authoritative) we only SET on acquisition and never clear, to avoid wiping a
2612
2754
  // legitimately-configured PK — and we avoid re-UPDATING an unchanged row every run.
2613
2755
  const pkFlagsChanged = this.primaryKeyFlagsChanged({ isPrimaryKey: field.IsPrimaryKey, isUnique: field.IsUnique }, { wantPrimaryKey, wantUnique }, makePrimaryKey, reconcilePrimaryKey);
2614
- if (pkFlagsChanged ||
2756
+ // The match above ignores case; the stored name takes the view column's exact casing.
2757
+ const nameChanged = field.Name !== veField.FieldName;
2758
+ if (pkFlagsChanged || nameChanged ||
2615
2759
  field.Type.trim().toLowerCase() !== veField.Type.trim().toLowerCase() ||
2616
2760
  field.Length !== veField.Length ||
2617
2761
  field.AllowsNull !== veField.AllowsNull ||
@@ -2620,8 +2764,9 @@ export class ManageMetadataBase {
2620
2764
  field.Sequence !== fieldSequence) {
2621
2765
  // the field needs to be updated, so update it
2622
2766
  const sqlUpdate = `UPDATE
2623
- ${this.qs(mj_core_schema(), 'EntityField')}
2767
+ ${this.qs(MjCoreSchema(), 'EntityField')}
2624
2768
  SET
2769
+ ${nameChanged ? `Name='${EscapeSQLString(veField.FieldName)}',` : ''}
2625
2770
  Sequence=${fieldSequence},
2626
2771
  Type='${veField.Type}',
2627
2772
  AllowsNull=${this.boolLit(veField.AllowsNull)},
@@ -2631,7 +2776,7 @@ export class ManageMetadataBase {
2631
2776
  Scale=${veField.Scale}
2632
2777
  WHERE
2633
2778
  ID = '${field.ID}'`; // don't need to update the __mj_UpdatedAt field here, that happens automatically via the trigger
2634
- await this.LogSQLAndExecute(pool, sqlUpdate, `SQL text to update virtual entity field ${veField.FieldName} for entity ${virtualEntity.Name}`);
2779
+ await this.logSQLAndExecute(pool, sqlUpdate, `SQL text to update virtual entity field ${veField.FieldName} for entity ${virtualEntity.Name}`);
2635
2780
  didUpdate = true;
2636
2781
  }
2637
2782
  }
@@ -2641,7 +2786,7 @@ export class ManageMetadataBase {
2641
2786
  // Apply-time Sequence: see applyTimeEntityFieldSequenceSQL. A literal here would be
2642
2787
  // replayed verbatim from the CodeGen capture and collide on a fresh install.
2643
2788
  const q = (n) => this.qi(n);
2644
- const sqlAdd = `INSERT INTO ${this.qs(mj_core_schema(), 'EntityField')} (
2789
+ const sqlAdd = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityField')} (
2645
2790
  ${q('ID')}, ${q('EntityID')}, ${q('Name')}, ${q('Type')}, ${q('AllowsNull')},
2646
2791
  ${q('Length')}, ${q('Precision')}, ${q('Scale')},
2647
2792
  ${q('Sequence')}, ${q('IsPrimaryKey')}, ${q('IsUnique')},
@@ -2651,7 +2796,7 @@ export class ManageMetadataBase {
2651
2796
  ${this.applyTimeEntityFieldSequenceSQL(entity.ID)}, ${this.boolLit(wantPrimaryKey)}, ${this.boolLit(wantUnique)},
2652
2797
  ${this.utcNow()}, ${this.utcNow()}
2653
2798
  )`;
2654
- await this.LogSQLAndExecute(pool, sqlAdd, `SQL text to add virtual entity field ${veField.FieldName} for entity ${virtualEntity.Name}`);
2799
+ await this.logSQLAndExecute(pool, sqlAdd, `SQL text to add virtual entity field ${veField.FieldName} for entity ${virtualEntity.Name}`);
2655
2800
  ManageMetadataBase.registerNewField(entity.ID, veField.FieldName);
2656
2801
  didUpdate = true;
2657
2802
  }
@@ -2747,7 +2892,7 @@ export class ManageMetadataBase {
2747
2892
  return { decorated: false, skipped: false };
2748
2893
  }
2749
2894
  // Apply results to EntityField records
2750
- const schema = mj_core_schema();
2895
+ const schema = MjCoreSchema();
2751
2896
  let anyUpdated = false;
2752
2897
  // Apply primary keys
2753
2898
  anyUpdated = await this.applyLLMPrimaryKeys(pool, entity, result.primaryKeys, schema) || anyUpdated;
@@ -2759,7 +2904,7 @@ export class ManageMetadataBase {
2759
2904
  anyUpdated = await this.applyVEFieldCategories(pool, entity, result) || anyUpdated;
2760
2905
  if (anyUpdated) {
2761
2906
  const sqlUpdate = `UPDATE ${this.qs(schema, 'Entity')} SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()} WHERE ID='${entity.ID}'`;
2762
- await this.LogSQLAndExecute(pool, sqlUpdate, `Update entity timestamp for ${entity.Name} after LLM decoration`);
2907
+ await this.logSQLAndExecute(pool, sqlUpdate, `Update entity timestamp for ${entity.Name} after LLM decoration`);
2763
2908
  }
2764
2909
  return { decorated: anyUpdated, skipped: false };
2765
2910
  }
@@ -2813,7 +2958,7 @@ export class ManageMetadataBase {
2813
2958
  return false;
2814
2959
  }
2815
2960
  // Load VE EntityField rows from DB (we need the ID and auto-update flags)
2816
- const schema = mj_core_schema();
2961
+ const schema = MjCoreSchema();
2817
2962
  const fieldsSQL = `
2818
2963
  SELECT ID, Name, Category, AutoUpdateCategory, AutoUpdateDisplayName, AutoUpdateExtendedType, GeneratedFormSection, DisplayName, ExtendedType, CodeType, ValueListType
2819
2964
  FROM ${this.qs(schema, 'EntityField')}
@@ -2877,7 +3022,7 @@ export class ManageMetadataBase {
2877
3022
  WHERE EntityID='${entity.ID}' AND Name='${pk}'`);
2878
3023
  logStatus(` ✓ Set PK for ${entity.Name}.${pk} (LLM-identified)`);
2879
3024
  }
2880
- await this.LogSQLBatchAndExecute(pool, sqlStatements, `Set LLM-identified PKs for ${entity.Name}: ${validPKs.join(', ')}`);
3025
+ await this.logSQLBatchAndExecute(pool, sqlStatements, `Set LLM-identified PKs for ${entity.Name}: ${validPKs.join(', ')}`);
2881
3026
  return true;
2882
3027
  }
2883
3028
  /**
@@ -2922,7 +3067,7 @@ export class ManageMetadataBase {
2922
3067
  if (sqlStatements.length === 0) {
2923
3068
  return false;
2924
3069
  }
2925
- await this.LogSQLBatchAndExecute(pool, sqlStatements, `Set LLM-identified FKs for ${entity.Name}`);
3070
+ await this.logSQLBatchAndExecute(pool, sqlStatements, `Set LLM-identified FKs for ${entity.Name}`);
2926
3071
  return true;
2927
3072
  }
2928
3073
  /**
@@ -2962,7 +3107,7 @@ export class ManageMetadataBase {
2962
3107
  if (sqlStatements.length === 0) {
2963
3108
  return false;
2964
3109
  }
2965
- await this.LogSQLBatchAndExecute(pool, sqlStatements, `Set LLM-generated descriptions for ${entity.Name} (${sqlStatements.length} fields)`);
3110
+ await this.logSQLBatchAndExecute(pool, sqlStatements, `Set LLM-generated descriptions for ${entity.Name} (${sqlStatements.length} fields)`);
2966
3111
  return true;
2967
3112
  }
2968
3113
  /**
@@ -3087,7 +3232,7 @@ export class ManageMetadataBase {
3087
3232
  // unquoted reference folds to lower case on PostgreSQL — `column "length" does not exist`.
3088
3233
  // SQL Server's case-insensitive resolution hid this for as long as IS-A ran only there.
3089
3234
  const existsResult = await this.runQueryWithParams(pool, `SELECT ${this.qi('ID')}, ${this.qi('IsVirtual')}, ${this.qi('Type')}, ${this.qi('Length')}, ${this.qi('Precision')}, ${this.qi('Scale')}, ${this.qi('AllowsNull')}, ${this.qi('AllowUpdateAPI')}
3090
- FROM ${this.qs(mj_core_schema(), 'EntityField')}
3235
+ FROM ${this.qs(MjCoreSchema(), 'EntityField')}
3091
3236
  WHERE ${this.qi('EntityID')} = @EntityID AND ${this.qi('Name')} = @FieldName`, { 'EntityID': childEntity.ID, 'FieldName': parentField.Name });
3092
3237
  if (existsResult.recordset.length > 0) {
3093
3238
  // Field already exists — update it to ensure it's marked as a virtual IS-A field
@@ -3100,7 +3245,7 @@ export class ManageMetadataBase {
3100
3245
  existingRow.AllowsNull !== parentField.AllowsNull ||
3101
3246
  !existingRow.AllowUpdateAPI;
3102
3247
  if (needsUpdate) {
3103
- const sqlUpdate = `UPDATE ${this.qs(mj_core_schema(), 'EntityField')}
3248
+ const sqlUpdate = `UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
3104
3249
  SET ${this.qi('IsVirtual')}=${this.boolLit(true)},
3105
3250
  ${this.qi('Type')}='${parentField.Type}',
3106
3251
  ${this.qi('Length')}=${parentField.Length},
@@ -3109,7 +3254,7 @@ export class ManageMetadataBase {
3109
3254
  ${this.qi('AllowsNull')}=${this.boolLit(parentField.AllowsNull)},
3110
3255
  ${this.qi('AllowUpdateAPI')}=${this.boolLit(true)}
3111
3256
  WHERE ${this.qi('ID')}='${existingRow.ID}'`;
3112
- await this.LogSQLAndExecute(pool, sqlUpdate, `Update IS-A parent field ${parentField.Name} on ${childEntity.Name}`);
3257
+ await this.logSQLAndExecute(pool, sqlUpdate, `Update IS-A parent field ${parentField.Name} on ${childEntity.Name}`);
3113
3258
  bUpdated = true;
3114
3259
  }
3115
3260
  }
@@ -3119,7 +3264,7 @@ export class ManageMetadataBase {
3119
3264
  // Apply-time Sequence (see applyTimeEntityFieldSequenceSQL); reordered by
3120
3265
  // updateExistingEntityFieldsFromSchema afterwards.
3121
3266
  const q = (n) => this.qi(n);
3122
- const sqlInsert = `INSERT INTO ${this.qs(mj_core_schema(), 'EntityField')} (
3267
+ const sqlInsert = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityField')} (
3123
3268
  ${q('ID')}, ${q('EntityID')}, ${q('Name')}, ${q('Type')}, ${q('AllowsNull')},
3124
3269
  ${q('Length')}, ${q('Precision')}, ${q('Scale')},
3125
3270
  ${q('Sequence')}, ${q('IsVirtual')}, ${q('AllowUpdateAPI')},
@@ -3131,7 +3276,7 @@ export class ManageMetadataBase {
3131
3276
  ${parentField.Length}, ${parentField.Precision}, ${parentField.Scale},
3132
3277
  ${this.applyTimeEntityFieldSequenceSQL(childEntity.ID)}, ${this.boolLit(true)}, ${this.boolLit(true)}, ${this.boolLit(false)}, ${this.boolLit(false)},
3133
3278
  ${this.utcNow()}, ${this.utcNow()})`;
3134
- await this.LogSQLAndExecute(pool, sqlInsert, `Create IS-A parent field ${parentField.Name} on ${childEntity.Name}`);
3279
+ await this.logSQLAndExecute(pool, sqlInsert, `Create IS-A parent field ${parentField.Name} on ${childEntity.Name}`);
3135
3280
  ManageMetadataBase.registerNewField(childEntity.ID, parentField.Name);
3136
3281
  bUpdated = true;
3137
3282
  }
@@ -3143,13 +3288,13 @@ export class ManageMetadataBase {
3143
3288
  !f.IsPrimaryKey && !f.Name.startsWith('__mj_') &&
3144
3289
  !currentParentFieldNames.has(f.Name.toLowerCase()));
3145
3290
  for (const staleField of staleFields) {
3146
- const sqlDelete = `DELETE FROM ${this.qs(mj_core_schema(), 'EntityField')} WHERE ID='${staleField.ID}'`;
3147
- await this.LogSQLAndExecute(pool, sqlDelete, `Remove stale IS-A parent field ${staleField.Name} from ${childEntity.Name}`);
3291
+ const sqlDelete = `DELETE FROM ${this.qs(MjCoreSchema(), 'EntityField')} WHERE ID='${staleField.ID}'`;
3292
+ await this.logSQLAndExecute(pool, sqlDelete, `Remove stale IS-A parent field ${staleField.Name} from ${childEntity.Name}`);
3148
3293
  bUpdated = true;
3149
3294
  }
3150
3295
  if (bUpdated) {
3151
- const sqlUpdate = `UPDATE ${this.qs(mj_core_schema(), 'Entity')} SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()} WHERE ID='${childEntity.ID}'`;
3152
- await this.LogSQLAndExecute(pool, sqlUpdate, `Update entity timestamp for ${childEntity.Name} after IS-A field sync`);
3296
+ const sqlUpdate = `UPDATE ${this.qs(MjCoreSchema(), 'Entity')} SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()} WHERE ID='${childEntity.ID}'`;
3297
+ await this.logSQLAndExecute(pool, sqlUpdate, `Update entity timestamp for ${childEntity.Name} after IS-A field sync`);
3153
3298
  }
3154
3299
  return { success: true, updated: bUpdated };
3155
3300
  }
@@ -3200,16 +3345,16 @@ export class ManageMetadataBase {
3200
3345
  try {
3201
3346
  // STEP 1 - search for all foreign keys in the vwEntityFields view, we use the RelatedEntityID field to determine our FKs
3202
3347
  const sSQL = `SELECT *
3203
- FROM ${this.qs(mj_core_schema(), 'vwEntityFields')}
3348
+ FROM ${this.qs(MjCoreSchema(), 'vwEntityFields')}
3204
3349
  WHERE
3205
3350
  RelatedEntityID IS NOT NULL AND
3206
3351
  IsVirtual = ${this.boolLit(false)} AND
3207
- EntityID NOT IN (SELECT ID FROM ${this.qs(mj_core_schema(), 'Entity')} WHERE SchemaName IN (${excludeSchemas.map(s => `'${s}'`).join(',')}))
3352
+ EntityID NOT IN (SELECT ID FROM ${this.qs(MjCoreSchema(), 'Entity')} WHERE SchemaName IN (${excludeSchemas.map(s => `'${s}'`).join(',')}))
3208
3353
  ORDER BY RelatedEntityID, EntityID, Sequence, ID`;
3209
3354
  const entityFieldsResult = await this.runQuery(pool, sSQL);
3210
3355
  const entityFields = entityFieldsResult.recordset;
3211
3356
  // Get the relationship counts for each entity
3212
- const sSQLRelationshipCount = `SELECT ${this.qi('EntityID')}, COUNT(*) AS ${this.qi('Count')} FROM ${this.qs(mj_core_schema(), 'EntityRelationship')} GROUP BY ${this.qi('EntityID')}`;
3357
+ const sSQLRelationshipCount = `SELECT ${this.qi('EntityID')}, COUNT(*) AS ${this.qi('Count')} FROM ${this.qs(MjCoreSchema(), 'EntityRelationship')} GROUP BY ${this.qi('EntityID')}`;
3213
3358
  const relationshipCountsResult = await this.runQuery(pool, sSQLRelationshipCount);
3214
3359
  const relationshipCounts = relationshipCountsResult.recordset;
3215
3360
  const relationshipCountMap = new Map();
@@ -3218,7 +3363,7 @@ export class ManageMetadataBase {
3218
3363
  relationshipCountMap.set(rc.EntityID, Number(rc.Count));
3219
3364
  }
3220
3365
  // get all relationships in one query for performance improvement
3221
- const sSQLRelationship = `SELECT * FROM ${this.qs(mj_core_schema(), 'EntityRelationship')}`;
3366
+ const sSQLRelationship = `SELECT * FROM ${this.qs(MjCoreSchema(), 'EntityRelationship')}`;
3222
3367
  const allRelationshipsResult = await this.runQuery(pool, sSQLRelationship);
3223
3368
  const allRelationships = allRelationshipsResult.recordset;
3224
3369
  // Group FK fields by entity pair (ParentEntityID -> ChildEntityID) so we can
@@ -3244,12 +3389,12 @@ export class ManageMetadataBase {
3244
3389
  }
3245
3390
  batchCount++;
3246
3391
  if (batchCount % batchItems === 0 && batchSQL.length > 0) {
3247
- await this.LogSQLAndExecute(pool, batchSQL);
3392
+ await this.logSQLAndExecute(pool, batchSQL);
3248
3393
  batchSQL = '';
3249
3394
  }
3250
3395
  }
3251
3396
  if (batchSQL.length > 0) {
3252
- await this.LogSQLAndExecute(pool, batchSQL);
3397
+ await this.logSQLAndExecute(pool, batchSQL);
3253
3398
  }
3254
3399
  // NOTE: Stale relationship cleanup is intentionally NOT done here because this
3255
3400
  // method runs BEFORE deleteUnneededEntityFields(). Stale EntityField records
@@ -3290,8 +3435,8 @@ export class ManageMetadataBase {
3290
3435
  const relCount = relationshipCountMap.get(parentEntityID) || 0;
3291
3436
  const sequence = relCount + 1;
3292
3437
  const newEntityRelationshipUUID = this.createNewUUID();
3293
- const checkQuery = `SELECT 1 FROM ${this.qs(mj_core_schema(), 'EntityRelationship')} WHERE ${this.qi('ID')} = '${newEntityRelationshipUUID}'`;
3294
- const insertSQL = `INSERT INTO ${this.qs(mj_core_schema(), 'EntityRelationship')} (${this.qi('ID')}, ${this.qi('EntityID')}, ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityJoinField')}, ${this.qi('Type')}, ${this.qi('BundleInAPI')}, ${this.qi('DisplayInForm')}, ${this.qi('Sequence')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')})
3438
+ const checkQuery = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntityRelationship')} WHERE ${this.qi('ID')} = '${newEntityRelationshipUUID}'`;
3439
+ const insertSQL = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityRelationship')} (${this.qi('ID')}, ${this.qi('EntityID')}, ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityJoinField')}, ${this.qi('Type')}, ${this.qi('BundleInAPI')}, ${this.qi('DisplayInForm')}, ${this.qi('Sequence')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')})
3295
3440
  VALUES ('${newEntityRelationshipUUID}', '${f.RelatedEntityID}', '${f.EntityID}', '${f.Name}', 'One To Many', ${this.boolLit(true)}, ${this.boolLit(true)}, ${sequence}, ${this.utcNow()}, ${this.utcNow()})`;
3296
3441
  relationshipCountMap.set(parentEntityID, sequence);
3297
3442
  return `
@@ -3353,7 +3498,7 @@ export class ManageMetadataBase {
3353
3498
  logStatus(` > Updating EntityRelationship join field: ${oldJoinField} -> ${newJoinField} (ID: ${r.ID})`);
3354
3499
  sql += `
3355
3500
  /* Update EntityRelationship join field from '${oldJoinField}' to '${newJoinField}' */
3356
- UPDATE ${this.qs(mj_core_schema(), 'EntityRelationship')}
3501
+ UPDATE ${this.qs(MjCoreSchema(), 'EntityRelationship')}
3357
3502
  SET ${this.qi('RelatedEntityJoinField')} = '${newJoinField}',
3358
3503
  ${this.qi('__mj_UpdatedAt')} = ${this.utcNow()}
3359
3504
  WHERE ${this.qi('ID')} = '${r.ID}';
@@ -3375,18 +3520,18 @@ export class ManageMetadataBase {
3375
3520
  * @param pool - database connection
3376
3521
  * @param excludeSchemas - schemas to exclude from FK field lookup
3377
3522
  */
3378
- async cleanupStaleEntityRelationships(pool, excludeSchemas) {
3523
+ async CleanupStaleEntityRelationships(pool, excludeSchemas) {
3379
3524
  try {
3380
3525
  const sSQL = `SELECT *
3381
- FROM ${this.qs(mj_core_schema(), 'vwEntityFields')}
3526
+ FROM ${this.qs(MjCoreSchema(), 'vwEntityFields')}
3382
3527
  WHERE
3383
3528
  RelatedEntityID IS NOT NULL AND
3384
3529
  IsVirtual = ${this.boolLit(false)} AND
3385
- EntityID NOT IN (SELECT ID FROM ${this.qs(mj_core_schema(), 'Entity')} WHERE SchemaName IN (${excludeSchemas.map(s => `'${s}'`).join(',')}))
3530
+ EntityID NOT IN (SELECT ID FROM ${this.qs(MjCoreSchema(), 'Entity')} WHERE SchemaName IN (${excludeSchemas.map(s => `'${s}'`).join(',')}))
3386
3531
  ORDER BY RelatedEntityID, EntityID, Sequence, ID`;
3387
3532
  const entityFieldsResult = await this.runQuery(pool, sSQL);
3388
3533
  const entityFields = entityFieldsResult.recordset;
3389
- const sSQLRelationship = `SELECT * FROM ${this.qs(mj_core_schema(), 'EntityRelationship')}`;
3534
+ const sSQLRelationship = `SELECT * FROM ${this.qs(MjCoreSchema(), 'EntityRelationship')}`;
3390
3535
  const allRelationshipsResult = await this.runQuery(pool, sSQLRelationship);
3391
3536
  const allRelationships = allRelationshipsResult.recordset;
3392
3537
  await this.removeStaleOneToManyRelationships(pool, allRelationships, entityFields);
@@ -3397,6 +3542,10 @@ export class ManageMetadataBase {
3397
3542
  return false;
3398
3543
  }
3399
3544
  }
3545
+ /** @deprecated Use {@link CleanupStaleEntityRelationships}. */
3546
+ async cleanupStaleEntityRelationships(pool, excludeSchemas) {
3547
+ return this.CleanupStaleEntityRelationships(pool, excludeSchemas);
3548
+ }
3400
3549
  /**
3401
3550
  * Removes stale One-To-Many EntityRelationship records whose RelatedEntityJoinField no longer
3402
3551
  * corresponds to a valid FK field in the database. Only removes relationships where
@@ -3419,10 +3568,10 @@ export class ManageMetadataBase {
3419
3568
  logStatus(` > Removing stale EntityRelationship: ${r.Entity} -> ${r.RelatedEntity} via '${r.RelatedEntityJoinField}' (ID: ${r.ID})`);
3420
3569
  deleteSQL += `
3421
3570
  /* Remove stale EntityRelationship: ${r.Entity} -> ${r.RelatedEntity} (FK field '${r.RelatedEntityJoinField}' no longer exists) */
3422
- DELETE FROM ${this.qs(mj_core_schema(), 'EntityRelationship')} WHERE ${this.qi('ID')} = '${r.ID}';
3571
+ DELETE FROM ${this.qs(MjCoreSchema(), 'EntityRelationship')} WHERE ${this.qi('ID')} = '${r.ID}';
3423
3572
  `;
3424
3573
  }
3425
- await this.LogSQLAndExecute(pool, deleteSQL, 'Remove stale One-To-Many EntityRelationships');
3574
+ await this.logSQLAndExecute(pool, deleteSQL, 'Remove stale One-To-Many EntityRelationships');
3426
3575
  }
3427
3576
  }
3428
3577
  /**
@@ -3433,7 +3582,7 @@ export class ManageMetadataBase {
3433
3582
  */
3434
3583
  async checkAndRemoveMetadataForDeletedTables(pool, excludeSchemas) {
3435
3584
  try {
3436
- const sql = `SELECT * FROM ${this.qs(mj_core_schema(), 'vwEntitiesWithMissingBaseTables')}${this.dbProvider.getEntitiesWithMissingBaseTablesFilter()}`;
3585
+ const sql = `SELECT * FROM ${this.qs(MjCoreSchema(), 'vwEntitiesWithMissingBaseTables')}${this.dbProvider.getEntitiesWithMissingBaseTablesFilter()}`;
3437
3586
  const entitiesResult = await this.runQuery(pool, sql);
3438
3587
  const entities = entitiesResult.recordset;
3439
3588
  if (entities && entities.length > 0) {
@@ -3456,8 +3605,8 @@ export class ManageMetadataBase {
3456
3605
  // discardResult: this routine only performs deletions — nothing below reads rows
3457
3606
  // from it — and on PostgreSQL it is declared RETURNS SETOF record, which cannot be
3458
3607
  // invoked through the default `SELECT * FROM` form at all.
3459
- const sqlDelete = this.dbProvider.callRoutineSQL(mj_core_schema(), 'spDeleteEntityWithCoreDependencies', [`'${e.ID}'`], ['EntityID'], true);
3460
- await this.LogSQLAndExecute(pool, sqlDelete, `SQL text to remove entity ${e.Name}`);
3608
+ const sqlDelete = this.dbProvider.callRoutineSQL(MjCoreSchema(), 'spDeleteEntityWithCoreDependencies', [`'${e.ID}'`], ['EntityID'], true);
3609
+ await this.logSQLAndExecute(pool, sqlDelete, `SQL text to remove entity ${e.Name}`);
3461
3610
  logStatus(` > Removed metadata for table ${e.SchemaName}.${e.BaseTable}`);
3462
3611
  // Recorded only after the delete succeeds, so a failed removal (logged below for
3463
3612
  // an admin to handle) does not mark a schema dirty for an entity still present.
@@ -3494,9 +3643,9 @@ export class ManageMetadataBase {
3494
3643
  // Object type codes: P = Stored Procedure, V = View, FN = Scalar Function, IF/TF = Table-Valued Function
3495
3644
  const upperType = type.toUpperCase();
3496
3645
  const sqlDelete = this.dbProvider.dropObjectSQL(upperType, schemaName, name);
3497
- await this.LogSQLAndExecute(pool, sqlDelete, `SQL text to remove ${type} ${schemaName}.${name}`);
3646
+ await this.logSQLAndExecute(pool, sqlDelete, `SQL text to remove ${type} ${schemaName}.${name}`);
3498
3647
  // next up, we need to clean up the cache of saved DB objects that may exist for this entity in the appropriate sub-directory.
3499
- const sqlOutputDir = outputDir('SQL', true);
3648
+ const sqlOutputDir = OutputDir('SQL', true);
3500
3649
  if (sqlOutputDir) {
3501
3650
  // now do the same thing for the /schema directory within the provided directory
3502
3651
  const fType = type === 'procedure' ? 'sp' : type === 'view' ? 'view' : 'full_text_search_function';
@@ -3570,7 +3719,7 @@ export class ManageMetadataBase {
3570
3719
  * which is the typical "no schema changes since last run" case in Pass 2.
3571
3720
  * `undefined` (default) preserves prior full-scan behavior.
3572
3721
  */
3573
- async manageEntityFields(pool, excludeSchemas, skipCreatedAtUpdatedAtDeletedAtFieldValidation, skipEntityFieldValues, currentUser, skipAdvancedGeneration, skipDeleteUnneededFields = false, entityFilter) {
3722
+ async ManageEntityFields(pool, excludeSchemas, skipCreatedAtUpdatedAtDeletedAtFieldValidation, skipEntityFieldValues, currentUser, skipAdvancedGeneration, skipDeleteUnneededFields = false, entityFilter) {
3574
3723
  let bSuccess = true;
3575
3724
  const startTime = new Date();
3576
3725
  // Fast-exit: an explicit empty filter means "no entities changed in Pass 1, so Pass 2 has nothing to do"
@@ -3623,9 +3772,9 @@ export class ManageMetadataBase {
3623
3772
  // Fix: derive virtual field AllowsNull from the FK column that drives the JOIN.
3624
3773
  // The virtual field name = FK field name minus trailing "ID" (e.g. ClassID → Class).
3625
3774
  if (this.dbProvider.NeedsVirtualFieldNullabilityFix) {
3626
- const fixSQL = this.dbProvider.getFixVirtualFieldNullabilitySQL(mj_core_schema());
3775
+ const fixSQL = this.dbProvider.getFixVirtualFieldNullabilitySQL(MjCoreSchema());
3627
3776
  if (fixSQL) {
3628
- await this.LogSQLAndExecute(pool, fixSQL, 'SQL to fix virtual field nullability');
3777
+ await this.logSQLAndExecute(pool, fixSQL, 'SQL to fix virtual field nullability');
3629
3778
  }
3630
3779
  }
3631
3780
  // AN: 14-June-2025 - we are now running this AFTER we create new entity fields from schema
@@ -3694,13 +3843,13 @@ export class ManageMetadataBase {
3694
3843
  // Advanced Generation - Smart field identification and form layout
3695
3844
  if (!skipAdvancedGeneration) {
3696
3845
  const step7StartTime = new Date();
3697
- startSpinner('Applying AI-powered advanced generation (smart fields, form layout)...');
3846
+ StartSpinner('Applying AI-powered advanced generation (smart fields, form layout)...');
3698
3847
  if (!await this.applyAdvancedGeneration(pool, excludeSchemas, currentUser)) {
3699
3848
  logError('Error applying advanced generation features');
3700
3849
  // Don't fail the entire process - advanced generation is optional
3701
3850
  }
3702
3851
  const step7Elapsed = ((new Date().getTime() - step7StartTime.getTime()) / 1000).toFixed(1);
3703
- succeedSpinner(`Advanced generation completed (${step7Elapsed}s)`);
3852
+ SucceedSpinner(`Advanced generation completed (${step7Elapsed}s)`);
3704
3853
  }
3705
3854
  // Deterministic search-flag hygiene. Deliberately OUTSIDE the `skipAdvancedGeneration`
3706
3855
  // guard above: advanced generation is off by default, and an entity created under that
@@ -3721,6 +3870,10 @@ export class ManageMetadataBase {
3721
3870
  logStatus(` Total time to manage entity fields: ${(new Date().getTime() - startTime.getTime()) / 1000} seconds`);
3722
3871
  return bSuccess;
3723
3872
  }
3873
+ /** @deprecated Use {@link ManageEntityFields}. */
3874
+ async manageEntityFields(pool, excludeSchemas, skipCreatedAtUpdatedAtDeletedAtFieldValidation, skipEntityFieldValues, currentUser, skipAdvancedGeneration, skipDeleteUnneededFields = false, entityFilter) {
3875
+ return this.ManageEntityFields(pool, excludeSchemas, skipCreatedAtUpdatedAtDeletedAtFieldValidation, skipEntityFieldValues, currentUser, skipAdvancedGeneration, skipDeleteUnneededFields, entityFilter);
3876
+ }
3724
3877
  /**
3725
3878
  * This method ensures that the __mj_DeletedAt field exists in each entity that has DeleteType=Soft. If the field does not exist, it is created.
3726
3879
  */
@@ -3729,7 +3882,7 @@ export class ManageMetadataBase {
3729
3882
  const sqlEntities = `SELECT
3730
3883
  *
3731
3884
  FROM
3732
- ${this.qs(mj_core_schema(), 'vwEntities')}
3885
+ ${this.qs(MjCoreSchema(), 'vwEntities')}
3733
3886
  WHERE
3734
3887
  VirtualEntity=${this.boolLit(false)} AND
3735
3888
  DeleteType='Soft' AND
@@ -3770,6 +3923,8 @@ export class ManageMetadataBase {
3770
3923
  * For soft PKs: Sets BOTH IsPrimaryKey=1 AND IsSoftPrimaryKey=1 (IsPrimaryKey is source of truth, IsSoftPrimaryKey protects from schema sync).
3771
3924
  * For soft FKs: Sets RelatedEntityID/RelatedEntityFieldName + IsSoftForeignKey=1 (RelatedEntityID is source of truth, IsSoftForeignKey protects from schema sync).
3772
3925
  * All UPDATE statements are logged to migration files via LogSQLAndExecute() for CI/CD traceability.
3926
+ * Covers table entries only. VirtualEntities entries are applied after the view-column sync by
3927
+ * {@link applyVirtualEntitySoftKeys}.
3773
3928
  */
3774
3929
  async applySoftPKFKConfig(pool) {
3775
3930
  // Check if additionalSchemaInfo is configured in mj.config.cjs
@@ -3788,100 +3943,11 @@ export class ManageMetadataBase {
3788
3943
  if (!config) {
3789
3944
  return true;
3790
3945
  }
3791
- let totalPKs = 0;
3792
- let totalFKs = 0;
3793
- const schema = mj_core_schema();
3794
3946
  // Config supports two formats:
3795
3947
  // 1. Schema-as-key (template format): { "dbo": [{ "TableName": "Orders", ... }] }
3796
3948
  // 2. Flat tables array (legacy format): { "tables": [{ "SchemaName": "dbo", "TableName": "Orders", ... }] }
3797
3949
  // Both use PascalCase property names.
3798
- const tables = this.extractTablesFromConfig(config);
3799
- for (const table of tables) {
3800
- const tableSchema = table.SchemaName;
3801
- const tableName = table.TableName;
3802
- // Look up entity ID (SELECT query - no need to log to migration file)
3803
- const entityLookupSQL = `SELECT ID FROM ${this.qs(schema, 'Entity')} WHERE SchemaName = '${tableSchema}' AND BaseTable = '${tableName}'`;
3804
- const entityResult = await this.runQuery(pool, entityLookupSQL);
3805
- if (entityResult.recordset.length === 0) {
3806
- logStatus(` ⚠️ Entity not found for ${tableSchema}.${tableName} - skipping`);
3807
- continue;
3808
- }
3809
- const entityId = entityResult.recordset[0].ID;
3810
- // Process primary keys - set BOTH IsPrimaryKey = 1 AND IsSoftPrimaryKey = 1
3811
- // IsPrimaryKey is the source of truth, IsSoftPrimaryKey protects it from schema sync
3812
- const primaryKeys = table.PrimaryKey || [];
3813
- if (primaryKeys.length > 0) {
3814
- for (const pk of primaryKeys) {
3815
- const checkSQL = `SELECT ${this.qi('IsPrimaryKey')}, ${this.qi('IsSoftPrimaryKey')}
3816
- FROM ${this.qs(schema, 'EntityField')}
3817
- WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${pk.FieldName}'`;
3818
- const checkRes = await this.runQuery(pool, checkSQL);
3819
- if (checkRes.recordset.length > 0) {
3820
- const row = checkRes.recordset[0];
3821
- const isPk = row.IsPrimaryKey === true || row.IsPrimaryKey === 1 || row.IsPrimaryKey === '1';
3822
- const isSoftPk = row.IsSoftPrimaryKey === true || row.IsSoftPrimaryKey === 1 || row.IsSoftPrimaryKey === '1';
3823
- if (isPk && isSoftPk) {
3824
- continue; // Already correctly set, skip write
3825
- }
3826
- }
3827
- const sSQL = `UPDATE ${this.qs(schema, 'EntityField')}
3828
- SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()},
3829
- ${this.qi('IsPrimaryKey')} = ${this.boolLit(true)},
3830
- ${this.qi('IsSoftPrimaryKey')} = ${this.boolLit(true)}
3831
- WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${pk.FieldName}'`;
3832
- const result = await this.LogSQLAndExecute(pool, sSQL, `Set soft PK for ${tableSchema}.${tableName}.${pk.FieldName}`);
3833
- if (result !== null) {
3834
- logStatus(` ✓ Set IsPrimaryKey=1, IsSoftPrimaryKey=1 for ${tableName}.${pk.FieldName}`);
3835
- totalPKs++;
3836
- }
3837
- }
3838
- }
3839
- // Process foreign keys - set RelatedEntityID, RelatedEntityFieldName, and IsSoftForeignKey = 1
3840
- const foreignKeys = table.ForeignKeys || [];
3841
- if (foreignKeys.length > 0) {
3842
- for (const fk of foreignKeys) {
3843
- const fkSchema = fk.SchemaName || tableSchema;
3844
- // Look up related entity ID (SELECT query - no need to log to migration file)
3845
- const relatedLookupSQL = `SELECT ID FROM ${this.qs(schema, 'Entity')} WHERE SchemaName = '${fkSchema}' AND BaseTable = '${fk.RelatedTable}'`;
3846
- const relatedEntityResult = await this.runQuery(pool, relatedLookupSQL);
3847
- if (relatedEntityResult.recordset.length === 0) {
3848
- logStatus(` ⚠️ Related entity not found for ${fkSchema}.${fk.RelatedTable} - skipping FK ${fk.FieldName}`);
3849
- continue;
3850
- }
3851
- const relatedEntityId = relatedEntityResult.recordset[0].ID;
3852
- const checkSQL = `SELECT ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityFieldName')}, ${this.qi('IsSoftForeignKey')}, ${this.qi('AutoUpdateRelatedEntityInfo')}
3853
- FROM ${this.qs(schema, 'EntityField')}
3854
- WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fk.FieldName}'`;
3855
- const checkRes = await this.runQuery(pool, checkSQL);
3856
- if (checkRes.recordset.length > 0) {
3857
- const row = checkRes.recordset[0];
3858
- const curRelId = String(row.RelatedEntityID ?? '').trim().toLowerCase();
3859
- const curRelField = String(row.RelatedEntityFieldName ?? '').trim().toLowerCase();
3860
- const curSoftFk = row.IsSoftForeignKey === true || row.IsSoftForeignKey === 1 || row.IsSoftForeignKey === '1';
3861
- const curAutoUpdate = row.AutoUpdateRelatedEntityInfo === true || row.AutoUpdateRelatedEntityInfo === 1 || row.AutoUpdateRelatedEntityInfo === '1';
3862
- if (curRelId === String(relatedEntityId).trim().toLowerCase() &&
3863
- curRelField === String(fk.RelatedField).trim().toLowerCase() &&
3864
- curSoftFk &&
3865
- !curAutoUpdate) {
3866
- continue; // Already correctly set, skip write
3867
- }
3868
- }
3869
- const sSQL = `UPDATE ${this.qs(schema, 'EntityField')}
3870
- SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()},
3871
- ${this.qi('RelatedEntityID')} = '${relatedEntityId}',
3872
- ${this.qi('RelatedEntityFieldName')} = '${fk.RelatedField}',
3873
- ${this.qi('IsSoftForeignKey')} = ${this.boolLit(true)},
3874
- ${this.qi('AutoUpdateRelatedEntityInfo')} = ${this.boolLit(false)}
3875
- WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fk.FieldName}'`;
3876
- const result = await this.LogSQLAndExecute(pool, sSQL, `Set soft FK for ${tableSchema}.${tableName}.${fk.FieldName} → ${fk.RelatedTable}.${fk.RelatedField}`);
3877
- if (result !== null) {
3878
- logStatus(` ✓ Set soft FK for ${tableName}.${fk.FieldName} → ${fk.RelatedTable}.${fk.RelatedField}`);
3879
- totalFKs++;
3880
- }
3881
- }
3882
- }
3883
- }
3884
- logStatus(` Applied ${totalPKs} soft PK(s) and ${totalFKs} soft FK(s) from configuration`);
3950
+ await this.applySoftKeysToTables(pool, this.extractTablesFromConfig(config), false);
3885
3951
  return true;
3886
3952
  }
3887
3953
  catch (e) {
@@ -3889,6 +3955,166 @@ export class ManageMetadataBase {
3889
3955
  return false;
3890
3956
  }
3891
3957
  }
3958
+ /**
3959
+ * Applies the PrimaryKey and ForeignKeys of VirtualEntities entries. Runs after the view-column
3960
+ * sync, so it sees the fields of entities and view columns created in the same run. On a
3961
+ * composite key it also clears IsUnique, which spCreateVirtualEntity set on the first column.
3962
+ * @returns success, and the number of UPDATEs written
3963
+ */
3964
+ async applyVirtualEntitySoftKeys(pool) {
3965
+ const config = ManageMetadataBase.GetSoftPKFKConfig();
3966
+ const entries = config ? this.virtualEntityConfigsAsTableConfigs(config) : [];
3967
+ if (entries.length === 0) {
3968
+ return { success: true, writeCount: 0 };
3969
+ }
3970
+ try {
3971
+ logStatus(` Applying configured keys for ${entries.length} virtual entit${entries.length === 1 ? 'y' : 'ies'}...`);
3972
+ return { success: true, writeCount: await this.applySoftKeysToTables(pool, entries, true) };
3973
+ }
3974
+ catch (e) {
3975
+ logError(`Error applying VirtualEntities soft PK/FK configuration: ${e}`);
3976
+ return { success: false, writeCount: 0 };
3977
+ }
3978
+ }
3979
+ /**
3980
+ * Applies the VirtualEntities keys, then refreshes metadata and rebuilds relationships when a key
3981
+ * changed. Runs on every CodeGen run, right after the view-column sync.
3982
+ */
3983
+ async applyConfiguredVirtualEntityKeys(pool, excludeSchemas, md) {
3984
+ const { success, writeCount } = await this.applyVirtualEntitySoftKeys(pool);
3985
+ if (!success) {
3986
+ logError(' Error applying soft PK/FK configuration for virtual entities');
3987
+ return false;
3988
+ }
3989
+ if (writeCount === 0) {
3990
+ return true;
3991
+ }
3992
+ await md.Refresh();
3993
+ logStatus(' Managing virtual-entity relationships...');
3994
+ if (!await this.manageEntityRelationships(pool, excludeSchemas, md)) {
3995
+ logError(' Error managing virtual-entity relationships');
3996
+ return false;
3997
+ }
3998
+ return true;
3999
+ }
4000
+ /**
4001
+ * Writes the soft keys of each config entry, compare-first: a column that is already set, or that
4002
+ * does not exist, gets no UPDATE.
4003
+ * @param clearUniqueOnCompositeKey clear IsUnique on the columns of a multi-column key. Only for
4004
+ * virtual entities: no schema sync maintains their IsUnique.
4005
+ * @returns the number of UPDATEs written
4006
+ */
4007
+ async applySoftKeysToTables(pool, tables, clearUniqueOnCompositeKey) {
4008
+ let totalPKs = 0;
4009
+ let totalFKs = 0;
4010
+ for (const table of tables) {
4011
+ // Look up entity ID (SELECT query - no need to log to migration file)
4012
+ const entityLookupSQL = `SELECT ID FROM ${this.qs(MjCoreSchema(), 'Entity')} WHERE SchemaName = '${EscapeSQLString(table.SchemaName)}' AND BaseTable = '${EscapeSQLString(table.TableName)}'`;
4013
+ const entityResult = await this.runQuery(pool, entityLookupSQL);
4014
+ if (entityResult.recordset.length === 0) {
4015
+ logStatus(` ⚠️ Entity not found for ${table.SchemaName}.${table.TableName} - skipping`);
4016
+ continue;
4017
+ }
4018
+ const entityId = entityResult.recordset[0].ID;
4019
+ const primaryKeys = table.PrimaryKey || [];
4020
+ totalPKs += await this.applySoftPrimaryKeys(pool, table, entityId, clearUniqueOnCompositeKey && primaryKeys.length > 1);
4021
+ totalFKs += await this.applySoftForeignKeys(pool, table, entityId);
4022
+ }
4023
+ logStatus(` Applied ${totalPKs} soft PK(s) and ${totalFKs} soft FK(s) from configuration`);
4024
+ return totalPKs + totalFKs;
4025
+ }
4026
+ /**
4027
+ * Sets IsPrimaryKey = 1 AND IsSoftPrimaryKey = 1 on each configured key column.
4028
+ * IsPrimaryKey is the source of truth, IsSoftPrimaryKey protects it from schema sync.
4029
+ * @returns the number of UPDATEs written
4030
+ */
4031
+ async applySoftPrimaryKeys(pool, table, entityId, clearUnique) {
4032
+ const schema = MjCoreSchema();
4033
+ let written = 0;
4034
+ for (const pk of table.PrimaryKey || []) {
4035
+ const fieldName = EscapeSQLString(pk.FieldName);
4036
+ const checkSQL = `SELECT ${this.qi('IsPrimaryKey')}, ${this.qi('IsSoftPrimaryKey')}, ${this.qi('IsUnique')}
4037
+ FROM ${this.qs(schema, 'EntityField')}
4038
+ WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
4039
+ const checkRes = await this.runQuery(pool, checkSQL);
4040
+ if (checkRes.recordset.length === 0) {
4041
+ logStatus(` ⚠️ Field ${table.TableName}.${pk.FieldName} not found - skipping soft PK`);
4042
+ continue;
4043
+ }
4044
+ const row = checkRes.recordset[0];
4045
+ if (this.isFlagSet(row.IsPrimaryKey) && this.isFlagSet(row.IsSoftPrimaryKey) && !(clearUnique && this.isFlagSet(row.IsUnique))) {
4046
+ continue; // Already correctly set, skip write
4047
+ }
4048
+ const clearUniqueSQL = clearUnique ? `,
4049
+ ${this.qi('IsUnique')} = ${this.boolLit(false)}` : '';
4050
+ const sSQL = `UPDATE ${this.qs(schema, 'EntityField')}
4051
+ SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()},
4052
+ ${this.qi('IsPrimaryKey')} = ${this.boolLit(true)},
4053
+ ${this.qi('IsSoftPrimaryKey')} = ${this.boolLit(true)}${clearUniqueSQL}
4054
+ WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
4055
+ const result = await this.logSQLAndExecute(pool, sSQL, `Set soft PK for ${table.SchemaName}.${table.TableName}.${pk.FieldName}`);
4056
+ if (result !== null) {
4057
+ logStatus(` ✓ Set IsPrimaryKey=1, IsSoftPrimaryKey=1 for ${table.TableName}.${pk.FieldName}`);
4058
+ written++;
4059
+ }
4060
+ }
4061
+ return written;
4062
+ }
4063
+ /**
4064
+ * Sets RelatedEntityID, RelatedEntityFieldName and IsSoftForeignKey = 1 on each configured foreign
4065
+ * key column. RelatedEntityID is the source of truth, IsSoftForeignKey protects it from schema sync.
4066
+ * @returns the number of UPDATEs written
4067
+ */
4068
+ async applySoftForeignKeys(pool, table, entityId) {
4069
+ const schema = MjCoreSchema();
4070
+ let written = 0;
4071
+ for (const fk of table.ForeignKeys || []) {
4072
+ const fkSchema = fk.SchemaName || table.SchemaName;
4073
+ // Look up related entity ID (SELECT query - no need to log to migration file)
4074
+ const relatedLookupSQL = `SELECT ID FROM ${this.qs(schema, 'Entity')} WHERE SchemaName = '${EscapeSQLString(fkSchema)}' AND BaseTable = '${EscapeSQLString(fk.RelatedTable)}'`;
4075
+ const relatedEntityResult = await this.runQuery(pool, relatedLookupSQL);
4076
+ if (relatedEntityResult.recordset.length === 0) {
4077
+ logStatus(` ⚠️ Related entity not found for ${fkSchema}.${fk.RelatedTable} - skipping FK ${fk.FieldName}`);
4078
+ continue;
4079
+ }
4080
+ const relatedEntityId = relatedEntityResult.recordset[0].ID;
4081
+ const fieldName = EscapeSQLString(fk.FieldName);
4082
+ const checkSQL = `SELECT ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityFieldName')}, ${this.qi('IsSoftForeignKey')}, ${this.qi('AutoUpdateRelatedEntityInfo')}
4083
+ FROM ${this.qs(schema, 'EntityField')}
4084
+ WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
4085
+ const checkRes = await this.runQuery(pool, checkSQL);
4086
+ if (checkRes.recordset.length === 0) {
4087
+ logStatus(` ⚠️ Field ${table.TableName}.${fk.FieldName} not found - skipping soft FK`);
4088
+ continue;
4089
+ }
4090
+ const row = checkRes.recordset[0];
4091
+ const curRelId = String(row.RelatedEntityID ?? '').trim().toLowerCase();
4092
+ const curRelField = String(row.RelatedEntityFieldName ?? '').trim().toLowerCase();
4093
+ if (curRelId === String(relatedEntityId).trim().toLowerCase() &&
4094
+ curRelField === String(fk.RelatedField).trim().toLowerCase() &&
4095
+ this.isFlagSet(row.IsSoftForeignKey) &&
4096
+ !this.isFlagSet(row.AutoUpdateRelatedEntityInfo)) {
4097
+ continue; // Already correctly set, skip write
4098
+ }
4099
+ const sSQL = `UPDATE ${this.qs(schema, 'EntityField')}
4100
+ SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()},
4101
+ ${this.qi('RelatedEntityID')} = '${relatedEntityId}',
4102
+ ${this.qi('RelatedEntityFieldName')} = '${EscapeSQLString(fk.RelatedField)}',
4103
+ ${this.qi('IsSoftForeignKey')} = ${this.boolLit(true)},
4104
+ ${this.qi('AutoUpdateRelatedEntityInfo')} = ${this.boolLit(false)}
4105
+ WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
4106
+ const result = await this.logSQLAndExecute(pool, sSQL, `Set soft FK for ${table.SchemaName}.${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${fk.RelatedField}`);
4107
+ if (result !== null) {
4108
+ logStatus(` ✓ Set soft FK for ${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${fk.RelatedField}`);
4109
+ written++;
4110
+ }
4111
+ }
4112
+ return written;
4113
+ }
4114
+ /** True for a bit column value as the SQL Server and PostgreSQL drivers return it. */
4115
+ isFlagSet(value) {
4116
+ return value === true || value === 1 || value === '1';
4117
+ }
3892
4118
  /**
3893
4119
  * Applies soft value-list configuration from Fields[] entries in additionalSchemaInfo.json.
3894
4120
  * Runs AFTER manageEntityFieldValuesAndValidatorFunctions() so CHECK-constraint-derived
@@ -3904,7 +4130,7 @@ export class ManageMetadataBase {
3904
4130
  return true;
3905
4131
  try {
3906
4132
  // Load all existing EntityFieldValue rows for dedup checking
3907
- const efvSQL = `SELECT * FROM ${this.qs(mj_core_schema(), 'EntityFieldValue')} ORDER BY EntityFieldID, Sequence, Value, ID`;
4133
+ const efvSQL = `SELECT * FROM ${this.qs(MjCoreSchema(), 'EntityFieldValue')} ORDER BY EntityFieldID, Sequence, Value, ID`;
3908
4134
  const allEFVResult = await this.runQuery(pool, efvSQL);
3909
4135
  const allEntityFieldValues = allEFVResult.recordset;
3910
4136
  let totalApplied = 0;
@@ -3930,7 +4156,7 @@ export class ManageMetadataBase {
3930
4156
  * EntityFieldValue rows already exist (from CHECK constraints) and skips if so.
3931
4157
  */
3932
4158
  async applyValueListsForTable(pool, schemaName, tableName, fields, allEntityFieldValues) {
3933
- const schema = mj_core_schema();
4159
+ const schema = MjCoreSchema();
3934
4160
  let applied = 0;
3935
4161
  let skipped = 0;
3936
4162
  // Look up entity ID
@@ -3976,7 +4202,7 @@ export class ManageMetadataBase {
3976
4202
  const newType = fieldCfg.ValueListType;
3977
4203
  if (currentValueListType !== newType.toLowerCase()) {
3978
4204
  const updateSQL = `UPDATE ${this.qs(schema, 'EntityField')} SET ValueListType='${newType}' WHERE ID='${entityFieldID}'`;
3979
- await this.LogSQLAndExecute(pool, updateSQL, `Set soft ValueListType='${newType}' for ${schemaName}.${tableName}.${fieldCfg.FieldName}`);
4205
+ await this.logSQLAndExecute(pool, updateSQL, `Set soft ValueListType='${newType}' for ${schemaName}.${tableName}.${fieldCfg.FieldName}`);
3980
4206
  }
3981
4207
  logStatus(` ✓ Applied soft value-list for ${tableName}.${fieldCfg.FieldName} (${sortedValues.length} values, type=${newType})`);
3982
4208
  return 'applied';
@@ -3998,7 +4224,7 @@ export class ManageMetadataBase {
3998
4224
  const sqlEntities = `SELECT
3999
4225
  *
4000
4226
  FROM
4001
- ${this.qs(mj_core_schema(), 'vwEntities')}
4227
+ ${this.qs(MjCoreSchema(), 'vwEntities')}
4002
4228
  WHERE
4003
4229
  VirtualEntity = ${this.boolLit(false)} AND
4004
4230
  ${externalEntityClause}
@@ -4062,7 +4288,7 @@ export class ManageMetadataBase {
4062
4288
  // and the subsequent UPDATE referencing that column run in separate batches.
4063
4289
  // SQL Server compiles an entire batch before executing, so without the separator
4064
4290
  // the UPDATE fails with "Invalid column name" since the column doesn't exist yet at compile time.
4065
- await this.LogSQLAndExecute(pool, stmt, `SQL text to add special date field ${fieldName} to entity ${entity.SchemaName}.${entity.BaseTable}`, false, true, this.dbProvider.BatchSeparator);
4291
+ await this.logSQLAndExecute(pool, stmt, `SQL text to add special date field ${fieldName} to entity ${entity.SchemaName}.${entity.BaseTable}`, false, true, this.dbProvider.BatchSeparator);
4066
4292
  }
4067
4293
  }
4068
4294
  else {
@@ -4075,7 +4301,7 @@ export class ManageMetadataBase {
4075
4301
  // modifying the column, and finally adding the default constraint back in.
4076
4302
  await this.dropExistingDefaultConstraint(pool, entity, fieldName);
4077
4303
  const sql = this.dbProvider.alterColumnTypeAndNullabilitySQL(entity.SchemaName, entity.BaseTable, fieldName, this.timestampType, allowNull);
4078
- await this.LogSQLAndExecute(pool, sql, `SQL text to update special date field ${fieldName} in entity ${entity.SchemaName}.${entity.BaseTable}`);
4304
+ await this.logSQLAndExecute(pool, sql, `SQL text to update special date field ${fieldName} in entity ${entity.SchemaName}.${entity.BaseTable}`);
4079
4305
  if (!allowNull)
4080
4306
  await this.createDefaultConstraintForSpecialDateField(pool, entity, fieldName);
4081
4307
  }
@@ -4105,7 +4331,7 @@ export class ManageMetadataBase {
4105
4331
  async createDefaultConstraintForSpecialDateField(pool, entity, fieldName) {
4106
4332
  try {
4107
4333
  const sqlAddDefaultConstraint = this.dbProvider.addDefaultConstraintSQL(entity.SchemaName, entity.BaseTable, fieldName, this.utcNow());
4108
- await this.LogSQLAndExecute(pool, sqlAddDefaultConstraint, `SQL text to add default constraint for special date field ${fieldName} in entity ${entity.SchemaName}.${entity.BaseTable}`);
4334
+ await this.logSQLAndExecute(pool, sqlAddDefaultConstraint, `SQL text to add default constraint for special date field ${fieldName} in entity ${entity.SchemaName}.${entity.BaseTable}`);
4109
4335
  }
4110
4336
  catch (e) {
4111
4337
  logError(e);
@@ -4132,7 +4358,7 @@ export class ManageMetadataBase {
4132
4358
  try {
4133
4359
  const sqlDropDefaultConstraint = this.dbProvider.dropDefaultConstraintSQL(entity.SchemaName, entity.BaseTable, fieldName);
4134
4360
  // DECLARE-bearing block: close its batch in the replayable log (see SQLLogging.appendToSQLLogFile).
4135
- await this.LogSQLAndExecute(pool, sqlDropDefaultConstraint, `SQL text to drop default existing default constraints in entity ${entity.SchemaName}.${entity.BaseTable}`, false, true, this.dbProvider.BatchSeparator);
4361
+ await this.logSQLAndExecute(pool, sqlDropDefaultConstraint, `SQL text to drop default existing default constraints in entity ${entity.SchemaName}.${entity.BaseTable}`, false, true, this.dbProvider.BatchSeparator);
4136
4362
  }
4137
4363
  catch (e) {
4138
4364
  logError(e);
@@ -4157,15 +4383,15 @@ export class ManageMetadataBase {
4157
4383
  // "Unclosed quotation mark" (SQL Server) at the very end of an otherwise-complete
4158
4384
  // pass. '' doubling is correct on both supported dialects.
4159
4385
  const esc = (s) => s.replace(/'/g, "''");
4160
- const dataResult = await this.runQuery(pool, `SELECT * FROM ${this.qs(mj_core_schema(), 'vwEntities')} WHERE Name = '${esc(e)}'`);
4386
+ const dataResult = await this.runQuery(pool, `SELECT * FROM ${this.qs(MjCoreSchema(), 'vwEntities')} WHERE Name = '${esc(e)}'`);
4161
4387
  const data = dataResult.recordset;
4162
- const fieldsResult = await this.runQuery(pool, `SELECT * FROM ${this.qs(mj_core_schema(), 'vwEntityFields')} WHERE EntityID='${data[0].ID}'`);
4388
+ const fieldsResult = await this.runQuery(pool, `SELECT * FROM ${this.qs(MjCoreSchema(), 'vwEntityFields')} WHERE EntityID='${data[0].ID}'`);
4163
4389
  const fields = fieldsResult.recordset;
4164
4390
  // Use new API to generate entity description
4165
4391
  const result = await ag.generateEntityDescription(e, data[0].BaseTable, fields.map((f) => ({ Name: f.Name, Type: f.Type, IsNullable: f.AllowsNull, Description: f.Description })), currentUser);
4166
4392
  if (result?.entityDescription && result.entityDescription.length > 0) {
4167
- const sSQL = `UPDATE ${this.qs(mj_core_schema(), 'Entity')} SET ${this.qi('Description')} = '${esc(result.entityDescription)}', ${this.qi('AutoUpdateDescription')} = ${this.boolLit(false)} WHERE ${this.qi('Name')} = '${esc(e)}'`;
4168
- await this.LogSQLAndExecute(pool, sSQL, `SQL text to update entity description for entity ${e}`);
4393
+ const sSQL = `UPDATE ${this.qs(MjCoreSchema(), 'Entity')} SET ${this.qi('Description')} = '${esc(result.entityDescription)}', ${this.qi('AutoUpdateDescription')} = ${this.boolLit(false)} WHERE ${this.qi('Name')} = '${esc(e)}'`;
4394
+ await this.logSQLAndExecute(pool, sSQL, `SQL text to update entity description for entity ${e}`);
4169
4395
  }
4170
4396
  else {
4171
4397
  console.warn(' >>> Advanced Generation Error: LLM returned invalid result, skipping entity description for entity ' + e);
@@ -4186,9 +4412,9 @@ export class ManageMetadataBase {
4186
4412
  const sql = `SELECT
4187
4413
  ef.ID, ef.Name
4188
4414
  FROM
4189
- ${this.qs(mj_core_schema(), 'vwEntityFields')} ef
4415
+ ${this.qs(MjCoreSchema(), 'vwEntityFields')} ef
4190
4416
  INNER JOIN
4191
- ${this.qs(mj_core_schema(), 'vwEntities')} e
4417
+ ${this.qs(MjCoreSchema(), 'vwEntities')} e
4192
4418
  ON
4193
4419
  ef.EntityID = e.ID
4194
4420
  WHERE
@@ -4203,8 +4429,8 @@ export class ManageMetadataBase {
4203
4429
  const namingOptions = configInfo.entityNaming?.normalizeFieldNames !== false ? this.getEntityNamingOptions() : undefined;
4204
4430
  const sDisplayName = stripTrailingChars(createDisplayName(field.Name, namingOptions), 'ID', true).trim();
4205
4431
  if (sDisplayName.length > 0 && sDisplayName.toLowerCase().trim() !== field.Name.toLowerCase().trim()) {
4206
- const sSQL = `UPDATE ${this.qs(mj_core_schema(), 'EntityField')} SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()}, DisplayName = '${sDisplayName}' WHERE ID = '${field.ID}'`;
4207
- await this.LogSQLAndExecute(pool, sSQL, `SQL text to update display name for field ${field.Name}`);
4432
+ const sSQL = `UPDATE ${this.qs(MjCoreSchema(), 'EntityField')} SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()}, DisplayName = '${sDisplayName}' WHERE ID = '${field.ID}'`;
4433
+ await this.logSQLAndExecute(pool, sSQL, `SQL text to update display name for field ${field.Name}`);
4208
4434
  }
4209
4435
  }
4210
4436
  return true;
@@ -4224,12 +4450,12 @@ export class ManageMetadataBase {
4224
4450
  */
4225
4451
  async setDefaultColumnWidthWhereNeeded(pool, excludeSchemas) {
4226
4452
  try {
4227
- const heal = buildHealSchemaRoutineParams({
4228
- authoredExclude: getAuthoredExcludeSchemas(excludeSchemas),
4453
+ const heal = BuildHealSchemaRoutineParams({
4454
+ authoredExclude: GetAuthoredExcludeSchemas(excludeSchemas),
4229
4455
  includeSchemas: configInfo.includeSchemas,
4230
4456
  });
4231
- const sSQL = this.dbProvider.callRoutineSQL(mj_core_schema(), 'spSetDefaultColumnWidthWhereNeeded', heal.values, heal.names);
4232
- await this.LogSQLAndExecute(pool, sSQL, `SQL text to set default column width where needed`, true);
4457
+ const sSQL = this.dbProvider.callRoutineSQL(MjCoreSchema(), 'spSetDefaultColumnWidthWhereNeeded', heal.Values, heal.Names);
4458
+ await this.logSQLAndExecute(pool, sSQL, `SQL text to set default column width where needed`, true);
4233
4459
  return true;
4234
4460
  }
4235
4461
  catch (e) {
@@ -4249,7 +4475,7 @@ export class ManageMetadataBase {
4249
4475
  * @returns {string} - The SQL statement to retrieve pending entity fields.
4250
4476
  */
4251
4477
  getPendingEntityFieldsSELECTSQL(entityIDs, excludeSchemas) {
4252
- const schema = mj_core_schema();
4478
+ const schema = MjCoreSchema();
4253
4479
  return this.dbProvider.getPendingEntityFieldsSQL(schema, entityIDs, excludeSchemas);
4254
4480
  }
4255
4481
  /**
@@ -4292,7 +4518,7 @@ export class ManageMetadataBase {
4292
4518
  const quotedDefaultValue = (parsedDefaultValue == null || parsedDefaultValue.trim().length === 0)
4293
4519
  ? 'NULL'
4294
4520
  : (parsedDefaultValue.trim().toLowerCase() === 'null' ? 'NULL' : `'${escapedParsedDefault}'`);
4295
- const conflictCheck = `SELECT 1 FROM ${this.qs(mj_core_schema(), 'EntityField')} WHERE ID = '${newEntityFieldUUID}' OR (EntityID = '${n.EntityID}' AND Name = '${n.FieldName}')`;
4521
+ const conflictCheck = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntityField')} WHERE ID = '${newEntityFieldUUID}' OR (EntityID = '${n.EntityID}' AND Name = '${n.FieldName}')`;
4296
4522
  const guard = this.dbProvider.wrapInsertWithConflictGuard(conflictCheck);
4297
4523
  // Sequence is an apply-time expression, never a literal: see applyTimeEntityFieldSequenceSQL.
4298
4524
  // `n.Sequence` (MAX+100000+ordinal from the pending SELECT) is only that query's ORDER BY key
@@ -4300,7 +4526,7 @@ export class ManageMetadataBase {
4300
4526
  const sequenceExpr = this.applyTimeEntityFieldSequenceSQL(n.EntityID);
4301
4527
  return `
4302
4528
  ${guard.prefix}
4303
- INSERT INTO ${this.qs(mj_core_schema(), 'EntityField')}
4529
+ INSERT INTO ${this.qs(MjCoreSchema(), 'EntityField')}
4304
4530
  (
4305
4531
  ${this.qi('ID')},
4306
4532
  ${this.qi('EntityID')},
@@ -4415,7 +4641,7 @@ export class ManageMetadataBase {
4415
4641
  for (let i = 0; i < inserts.length; i += CHUNK_SIZE) {
4416
4642
  const chunk = inserts.slice(i, i + CHUNK_SIZE);
4417
4643
  try {
4418
- await this.LogSQLBatchAndExecute(pool, chunk, `SQL text to insert ${chunk.length} new entity field(s)`);
4644
+ await this.logSQLBatchAndExecute(pool, chunk, `SQL text to insert ${chunk.length} new entity field(s)`);
4419
4645
  // an error blows up the transaction (all-or-nothing), which is what we want
4420
4646
  }
4421
4647
  catch (e) {
@@ -4449,10 +4675,10 @@ export class ManageMetadataBase {
4449
4675
  * @param relatedEntityNameFieldMap
4450
4676
  * @returns
4451
4677
  */
4452
- async updateEntityFieldRelatedEntityNameFieldMap(pool, entityFieldID, relatedEntityNameFieldMap) {
4678
+ async UpdateEntityFieldRelatedEntityNameFieldMap(pool, entityFieldID, relatedEntityNameFieldMap) {
4453
4679
  try {
4454
- const sSQL = this.dbProvider.callRoutineSQL(mj_core_schema(), 'spUpdateEntityFieldRelatedEntityNameFieldMap', [`'${entityFieldID}'`, `'${relatedEntityNameFieldMap}'`], ['EntityFieldID', 'RelatedEntityNameFieldMap']);
4455
- await this.LogSQLAndExecute(pool, sSQL, `SQL text to update entity field related entity name field map for entity field ID ${entityFieldID}`);
4680
+ const sSQL = this.dbProvider.callRoutineSQL(MjCoreSchema(), 'spUpdateEntityFieldRelatedEntityNameFieldMap', [`'${entityFieldID}'`, `'${relatedEntityNameFieldMap}'`], ['EntityFieldID', 'RelatedEntityNameFieldMap']);
4681
+ await this.logSQLAndExecute(pool, sSQL, `SQL text to update entity field related entity name field map for entity field ID ${entityFieldID}`);
4456
4682
  return true;
4457
4683
  }
4458
4684
  catch (e) {
@@ -4460,14 +4686,18 @@ export class ManageMetadataBase {
4460
4686
  return false;
4461
4687
  }
4462
4688
  }
4689
+ /** @deprecated Use {@link UpdateEntityFieldRelatedEntityNameFieldMap}. */
4690
+ async updateEntityFieldRelatedEntityNameFieldMap(pool, entityFieldID, relatedEntityNameFieldMap) {
4691
+ return this.UpdateEntityFieldRelatedEntityNameFieldMap(pool, entityFieldID, relatedEntityNameFieldMap);
4692
+ }
4463
4693
  async updateExistingEntitiesFromSchema(pool, excludeSchemas) {
4464
4694
  try {
4465
- const heal = buildHealSchemaRoutineParams({
4466
- authoredExclude: getAuthoredExcludeSchemas(excludeSchemas),
4695
+ const heal = BuildHealSchemaRoutineParams({
4696
+ authoredExclude: GetAuthoredExcludeSchemas(excludeSchemas),
4467
4697
  includeSchemas: configInfo.includeSchemas,
4468
4698
  });
4469
- const sSQL = this.dbProvider.callRoutineSQL(mj_core_schema(), 'spUpdateExistingEntitiesFromSchema', heal.values, heal.names);
4470
- const result = await this.LogSQLAndExecute(pool, sSQL, `SQL text to update existing entities from schema`, true);
4699
+ const sSQL = this.dbProvider.callRoutineSQL(MjCoreSchema(), 'spUpdateExistingEntitiesFromSchema', heal.Values, heal.Names);
4700
+ const result = await this.logSQLAndExecute(pool, sSQL, `SQL text to update existing entities from schema`, true);
4471
4701
  // result contains the updated entities, and there is a property of each row called Name which has the entity name that was modified
4472
4702
  // add these to the modified entity list if they're not already in there
4473
4703
  if (result && result.length > 0) {
@@ -4483,30 +4713,34 @@ export class ManageMetadataBase {
4483
4713
  /**
4484
4714
  * Adds a list of entity names to the modified entity list if they're not already in there
4485
4715
  */
4486
- static addNewEntitiesToModifiedList(entityNames) {
4716
+ static AddNewEntitiesToModifiedList(entityNames) {
4487
4717
  const distinctEntityNames = [...new Set(entityNames)];
4488
4718
  const newlyModifiedEntityNames = distinctEntityNames.filter((e) => !ManageMetadataBase._modifiedEntityList.includes(e));
4489
4719
  // now make sure that each of these entity names is in the modified entity list
4490
4720
  ManageMetadataBase._modifiedEntityList = ManageMetadataBase._modifiedEntityList.concat(newlyModifiedEntityNames);
4491
4721
  }
4722
+ /** @deprecated Use {@link AddNewEntitiesToModifiedList}. */
4723
+ static addNewEntitiesToModifiedList(entityNames) {
4724
+ return this.AddNewEntitiesToModifiedList(entityNames);
4725
+ }
4492
4726
  async updateExistingEntityFieldsFromSchema(pool, excludeSchemas, entityIDs) {
4493
4727
  try {
4494
4728
  // One SP call regardless of scope: pass the entire entity ID list as a comma-delimited
4495
4729
  // string (mirrors the @ExcludedSchemaNames pattern). The SP fans the list out into
4496
4730
  // a table variable via STRING_SPLIT and joins once. This avoids both per-entity
4497
4731
  // round-trips (slow) and parallel calls (page-level lock contention on EntityField).
4498
- const heal = buildHealSchemaRoutineParams({
4499
- authoredExclude: getAuthoredExcludeSchemas(excludeSchemas),
4732
+ const heal = BuildHealSchemaRoutineParams({
4733
+ authoredExclude: GetAuthoredExcludeSchemas(excludeSchemas),
4500
4734
  includeSchemas: configInfo.includeSchemas,
4501
4735
  entityIDs,
4502
4736
  });
4503
- const sSQL = this.dbProvider.callRoutineSQL(mj_core_schema(), 'spUpdateExistingEntityFieldsFromSchema', heal.values, heal.names);
4737
+ const sSQL = this.dbProvider.callRoutineSQL(MjCoreSchema(), 'spUpdateExistingEntityFieldsFromSchema', heal.Values, heal.Names);
4504
4738
  const isScoped = entityIDs !== undefined && entityIDs.length > 0;
4505
4739
  const label = isScoped
4506
4740
  ? `SQL text to update existing entity fields from schema (${entityIDs.length} scoped entities)`
4507
4741
  : `SQL text to update existing entity fields from schema`;
4508
4742
  const before = await this.snapshotEntityFields(pool, entityIDs);
4509
- await this.LogSQLAndExecute(pool, sSQL, label, true);
4743
+ await this.logSQLAndExecute(pool, sSQL, label, true);
4510
4744
  const after = await this.snapshotEntityFields(pool, entityIDs);
4511
4745
  const changes = diffEntityFieldSnapshots(before, after, (e, n) => ManageMetadataBase.isFieldNew(e, n));
4512
4746
  if (changes.length > 0) {
@@ -4537,12 +4771,12 @@ export class ManageMetadataBase {
4537
4771
  */
4538
4772
  async updateSchemaInfoFromDatabase(pool, excludeSchemas) {
4539
4773
  try {
4540
- const heal = buildHealSchemaRoutineParams({
4541
- authoredExclude: getAuthoredExcludeSchemas(excludeSchemas),
4774
+ const heal = BuildHealSchemaRoutineParams({
4775
+ authoredExclude: GetAuthoredExcludeSchemas(excludeSchemas),
4542
4776
  includeSchemas: configInfo.includeSchemas,
4543
4777
  });
4544
- const sSQL = this.dbProvider.callRoutineSQL(mj_core_schema(), 'spUpdateSchemaInfoFromDatabase', heal.values, heal.names);
4545
- const result = await this.LogSQLAndExecute(pool, sSQL, `SQL text to sync schema info from database schemas`, true);
4778
+ const sSQL = this.dbProvider.callRoutineSQL(MjCoreSchema(), 'spUpdateSchemaInfoFromDatabase', heal.Values, heal.Names);
4779
+ const result = await this.logSQLAndExecute(pool, sSQL, `SQL text to sync schema info from database schemas`, true);
4546
4780
  if (result && result.length > 0) {
4547
4781
  logStatus(` > Updated/created ${result.length} SchemaInfo records`);
4548
4782
  this.cacheSchemaInfoRecords(result);
@@ -4572,7 +4806,7 @@ export class ManageMetadataBase {
4572
4806
  */
4573
4807
  async loadSchemaInfoRecords(pool) {
4574
4808
  try {
4575
- const sSQL = `SELECT * FROM ${this.qs(mj_core_schema(), 'SchemaInfo')}`;
4809
+ const sSQL = `SELECT * FROM ${this.qs(MjCoreSchema(), 'SchemaInfo')}`;
4576
4810
  const result = await this.runQuery(pool, sSQL);
4577
4811
  if (result?.recordset?.length > 0) {
4578
4812
  this.cacheSchemaInfoRecords(result.recordset);
@@ -4638,17 +4872,17 @@ export class ManageMetadataBase {
4638
4872
  // string (mirrors the @ExcludedSchemaNames pattern). The SP fans the list out into
4639
4873
  // a table variable via STRING_SPLIT and filters once. Avoids both per-entity
4640
4874
  // round-trips and parallel calls (page-level lock contention on EntityField).
4641
- const heal = buildHealSchemaRoutineParams({
4642
- authoredExclude: getAuthoredExcludeSchemas(excludeSchemas),
4875
+ const heal = BuildHealSchemaRoutineParams({
4876
+ authoredExclude: GetAuthoredExcludeSchemas(excludeSchemas),
4643
4877
  includeSchemas: configInfo.includeSchemas,
4644
4878
  entityIDs,
4645
4879
  });
4646
- const sSQL = this.dbProvider.callRoutineSQL(mj_core_schema(), 'spDeleteUnneededEntityFields', heal.values, heal.names);
4880
+ const sSQL = this.dbProvider.callRoutineSQL(MjCoreSchema(), 'spDeleteUnneededEntityFields', heal.Values, heal.Names);
4647
4881
  const isScoped = entityIDs !== undefined && entityIDs.length > 0;
4648
4882
  const label = isScoped
4649
4883
  ? `SQL text to delete unneeded entity fields (${entityIDs.length} scoped entities)`
4650
4884
  : `SQL text to delete unneeded entity fields`;
4651
- const result = await this.LogSQLAndExecute(pool, sSQL, label, true);
4885
+ const result = await this.logSQLAndExecute(pool, sSQL, label, true);
4652
4886
  // result contains the DELETED entity fields. Get a distinct list of entity names
4653
4887
  // and add them to the modified entity list if they're not already in there.
4654
4888
  if (result && result.length > 0) {
@@ -4668,13 +4902,13 @@ export class ManageMetadataBase {
4668
4902
  // for the field and sync that up with the EntityFieldValue table. If it is not a simple series of OR statements, we will not be able to parse it and we'll
4669
4903
  // just ignore it.
4670
4904
  const filter = this.dbProvider.getCheckConstraintsSchemaFilter(excludeSchemas);
4671
- const sSQL = `SELECT * FROM ${this.qs(mj_core_schema(), 'vwEntityFieldsWithCheckConstraints')}${filter}`;
4905
+ const sSQL = `SELECT * FROM ${this.qs(MjCoreSchema(), 'vwEntityFieldsWithCheckConstraints')}${filter}`;
4672
4906
  const resultResult = await this.runQuery(pool, sSQL);
4673
4907
  const result = resultResult.recordset;
4674
- const efvSQL = `SELECT * FROM ${this.qs(mj_core_schema(), 'EntityFieldValue')} ORDER BY EntityFieldID, Sequence, Value, ID`;
4908
+ const efvSQL = `SELECT * FROM ${this.qs(MjCoreSchema(), 'EntityFieldValue')} ORDER BY EntityFieldID, Sequence, Value, ID`;
4675
4909
  const allEntityFieldValuesResult = await this.runQuery(pool, efvSQL);
4676
4910
  const allEntityFieldValues = allEntityFieldValuesResult.recordset;
4677
- const efSQL = `SELECT * FROM ${this.qs(mj_core_schema(), 'vwEntityFields')} ORDER BY EntityID, Sequence, Name, ID`;
4911
+ const efSQL = `SELECT * FROM ${this.qs(MjCoreSchema(), 'vwEntityFields')} ORDER BY EntityID, Sequence, Name, ID`;
4678
4912
  const allEntityFieldsResult = await this.runQuery(pool, efSQL);
4679
4913
  const allEntityFields = allEntityFieldsResult.recordset;
4680
4914
  const generationPromises = [];
@@ -4692,25 +4926,30 @@ export class ManageMetadataBase {
4692
4926
  for (const r of columnLevelResults) {
4693
4927
  // now, for each of the constraints we get back here, loop through and evaluate if they're simple and if they're simple, parse and sync with entity field values for that field
4694
4928
  if (r.ConstraintDefinition && r.ConstraintDefinition.length > 0) {
4695
- const parsedValues = this.parseCheckConstraintValues(r.ConstraintDefinition, r.ColumnName, r.EntityName);
4929
+ // parse first, then decide whether THIS field should carry the list (bit, PK singleton guards).
4930
+ // UUIDsEqual, not ===: PG returns lowercase UUIDs and SQL Server uppercase, and a missed
4931
+ // lookup here fails OPEN (the exclusions stop applying), so a case mismatch would be silent.
4932
+ const field = allEntityFields.find((f) => UUIDsEqual(f.ID, r.EntityFieldID));
4933
+ const parsedValues = ManageMetadataBase.valueListForField(field, this.parseCheckConstraintValues(r.ConstraintDefinition, r.ColumnName, r.EntityName));
4696
4934
  if (parsedValues) {
4697
4935
  if (!skipDBUpdate) {
4698
4936
  // we only do this part if we are not skiping the database update as this code will sync values from the CHECK
4699
4937
  // with the EntityFieldValues in the database.
4700
- // Sort values alphabetically to ensure consistent sequences across all databases
4701
- // This guarantees the same value always gets the same sequence number regardless of
4702
- // how SQL Server returns CHECK constraint values (which can vary)
4703
- parsedValues.sort();
4938
+ // Sort the values to ensure consistent sequences across all databases. This guarantees the
4939
+ // same value always gets the same sequence number regardless of how SQL Server returns
4940
+ // CHECK constraint values (which can vary). An all-numeric list sorts numerically so the
4941
+ // dropdown reads 1, 2, 10 rather than the lexical 1, 10, 2 — still fully deterministic.
4942
+ ManageMetadataBase.sortCheckConstraintValues(parsedValues);
4704
4943
  // we have parsed values from the check constraint, so sync them with the entity field values
4705
4944
  await this.syncEntityFieldValues(pool, r.EntityFieldID, parsedValues, allEntityFieldValues);
4706
4945
  // finally, make sure the ValueListType column within the EntityField table is set to "List" because for check constraints we only allow the values specified in the list.
4707
4946
  // check to see if the ValueListType is already set to "List", if not, update it
4708
- const sSQLCheck = `SELECT ValueListType FROM ${this.qs(mj_core_schema(), 'EntityField')} WHERE ID='${r.EntityFieldID}'`;
4947
+ const sSQLCheck = `SELECT ValueListType FROM ${this.qs(MjCoreSchema(), 'EntityField')} WHERE ID='${r.EntityFieldID}'`;
4709
4948
  const checkResultResult = await this.runQuery(pool, sSQLCheck);
4710
4949
  const checkResult = checkResultResult.recordset;
4711
4950
  if (checkResult && checkResult.length > 0 && checkResult[0].ValueListType.trim().toLowerCase() !== 'list') {
4712
- const sSQL = `UPDATE ${this.qs(mj_core_schema(), 'EntityField')} SET ValueListType='List' WHERE ID='${r.EntityFieldID}'`;
4713
- await this.LogSQLAndExecute(pool, sSQL, `SQL text to update ValueListType for entity field ID ${r.EntityFieldID}`);
4951
+ const sSQL = `UPDATE ${this.qs(MjCoreSchema(), 'EntityField')} SET ValueListType='List' WHERE ID='${r.EntityFieldID}'`;
4952
+ await this.logSQLAndExecute(pool, sSQL, `SQL text to update ValueListType for entity field ID ${r.EntityFieldID}`);
4714
4953
  }
4715
4954
  }
4716
4955
  else {
@@ -4752,7 +4991,7 @@ export class ManageMetadataBase {
4752
4991
  * @param pool
4753
4992
  * @param currentUser
4754
4993
  */
4755
- async loadGeneratedCode(pool, currentUser) {
4994
+ async LoadGeneratedCode(pool, currentUser) {
4756
4995
  try {
4757
4996
  // right now we're just doing validator functions which are handled here
4758
4997
  return await this.manageEntityFieldValuesAndValidatorFunctions(pool, [], currentUser, true);
@@ -4762,6 +5001,10 @@ export class ManageMetadataBase {
4762
5001
  return false;
4763
5002
  }
4764
5003
  }
5004
+ /** @deprecated Use {@link LoadGeneratedCode}. */
5005
+ async loadGeneratedCode(pool, currentUser) {
5006
+ return this.LoadGeneratedCode(pool, currentUser);
5007
+ }
4765
5008
  async runValidationGeneration(r, allEntityFields, generateNewCode, currentUser) {
4766
5009
  const generatedFunction = await this.generateValidatorFunctionFromCheckConstraint(r, allEntityFields, currentUser, generateNewCode);
4767
5010
  if (generatedFunction?.success) {
@@ -4842,8 +5085,8 @@ export class ManageMetadataBase {
4842
5085
  for (const ev of existingValues) {
4843
5086
  if (!possibleValues.find(v => v === ev.Value)) {
4844
5087
  // delete the value from the database
4845
- const sSQLDelete = `DELETE FROM ${this.qs(mj_core_schema(), 'EntityFieldValue')} WHERE ID='${ev.ID}'`;
4846
- await this.LogSQLAndExecute(ds, sSQLDelete, `SQL text to delete entity field value ID ${ev.ID}`);
5088
+ const sSQLDelete = `DELETE FROM ${this.qs(MjCoreSchema(), 'EntityFieldValue')} WHERE ID='${ev.ID}'`;
5089
+ await this.logSQLAndExecute(ds, sSQLDelete, `SQL text to delete entity field value ID ${ev.ID}`);
4847
5090
  numRemoved++;
4848
5091
  }
4849
5092
  }
@@ -4854,11 +5097,11 @@ export class ManageMetadataBase {
4854
5097
  // Generate a UUID for this new EntityFieldValue record
4855
5098
  const newId = uuidv4();
4856
5099
  // add the value to the database with explicit ID
4857
- const sSQLInsert = `INSERT INTO ${this.qs(mj_core_schema(), 'EntityFieldValue')}
5100
+ const sSQLInsert = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityFieldValue')}
4858
5101
  (${this.qi('ID')}, ${this.qi('EntityFieldID')}, ${this.qi('Sequence')}, ${this.qi('Value')}, ${this.qi('Code')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')})
4859
5102
  VALUES
4860
5103
  ('${newId}', '${entityFieldID}', ${1 + possibleValues.indexOf(v)}, '${v}', '${v}', ${this.utcNow()}, ${this.utcNow()})`;
4861
- await this.LogSQLAndExecute(ds, sSQLInsert, `SQL text to insert entity field value with ID ${newId}`);
5104
+ await this.logSQLAndExecute(ds, sSQLInsert, `SQL text to insert entity field value with ID ${newId}`);
4862
5105
  numAdded++;
4863
5106
  }
4864
5107
  }
@@ -4870,8 +5113,8 @@ export class ManageMetadataBase {
4870
5113
  // DB returns a string for Sequence instead of a number.
4871
5114
  if (ev && ev.Sequence != 1 + possibleValues.indexOf(v)) {
4872
5115
  // update the sequence to match the order in the possible values list, if it doesn't already match
4873
- const sSQLUpdate = `UPDATE ${this.qs(mj_core_schema(), 'EntityFieldValue')} SET Sequence=${1 + possibleValues.indexOf(v)} WHERE ID='${ev.ID}'`;
4874
- await this.LogSQLAndExecute(ds, sSQLUpdate, `SQL text to update entity field value sequence`);
5116
+ const sSQLUpdate = `UPDATE ${this.qs(MjCoreSchema(), 'EntityFieldValue')} SET Sequence=${1 + possibleValues.indexOf(v)} WHERE ID='${ev.ID}'`;
5117
+ await this.logSQLAndExecute(ds, sSQLUpdate, `SQL text to update entity field value sequence`);
4875
5118
  numUpdated++;
4876
5119
  }
4877
5120
  }
@@ -4888,10 +5131,24 @@ export class ManageMetadataBase {
4888
5131
  return false;
4889
5132
  }
4890
5133
  }
5134
+ /**
5135
+ * Parses a column-level CHECK constraint into the list of values it permits, or returns null when the
5136
+ * constraint is not a simple value list (a range, a `LEN()` predicate, a mixed condition, and so on).
5137
+ *
5138
+ * Both of the ways `IN (...)` is rendered by SQL Server are handled. String, date and GUID literals come
5139
+ * back quoted — `([Status]='Active' OR [Status]='Inactive')` — but numeric and `bit` literals come back
5140
+ * **unquoted and parenthesized**: `([Level]=(3) OR [Level]=(2) OR [Level]=(1))`. Matching only the quoted
5141
+ * form left a numeric IN-list with no value list at all, and so no dropdown in Explorer either (#3978).
5142
+ * PostgreSQL's `= ANY (ARRAY[...])` rendering is handled separately, by parsePgArrayConstraint.
5143
+ *
5144
+ * A single-value list is captured too: `CHECK (Status='Active')` — which is also how SQL Server renders
5145
+ * `IN ('Active')` — permits exactly one value, which is a one-item list.
5146
+ *
5147
+ * This is a parser, not a policy: it reports what the constraint permits. WHICH fields get a value list
5148
+ * out of that is decided after the fact, by valueListForField.
5149
+ */
4891
5150
  parseCheckConstraintValues(constraintDefinition, fieldName, entityName) {
4892
- // This regex checks for the overall structure including field name and 'OR' sequences
4893
- // SQL Server uses [FieldName]='Value' quoting, PostgreSQL uses "FieldName" or unquoted FieldName
4894
- // We handle both: [FieldName], "FieldName", or bare FieldName
5151
+ // Normalize N'literal' to 'literal' so one pattern handles both.
4895
5152
  // Note: Assuming fieldName does not contain regex special characters; otherwise, it needs to be escaped as well.
4896
5153
  const processedConstraint = constraintDefinition.replace(/(^|[=(\s])N'([^']*)'/g, "$1'$2'");
4897
5154
  // PostgreSQL ANY (ARRAY[...]) pattern:
@@ -4904,46 +5161,92 @@ export class ManageMetadataBase {
4904
5161
  // Build a regex fragment that matches the field name in any quoting style:
4905
5162
  // [FieldName] (SQL Server) or "FieldName" (PostgreSQL) or bare FieldName
4906
5163
  const quotedField = `(?:\\[${fieldName}\\]|"${fieldName}"|${fieldName})`;
4907
- // Check for nested pattern: (Field IS NULL OR (Field='Value1' OR ...))
4908
- const nestedNullRegex = new RegExp(`^\\(${quotedField} IS NULL OR \\(${quotedField}='[^']+'(?: OR ${quotedField}='[^']+?')+\\)\\)$`);
4909
- if (nestedNullRegex.test(processedConstraint)) {
4910
- // Extract values from nested pattern - same extraction logic works
4911
- const valueRegex = new RegExp(`${quotedField}='([^']+)\'`, 'g');
4912
- let match;
4913
- const possibleValues = [];
4914
- while ((match = valueRegex.exec(processedConstraint)) !== null) {
4915
- if (match.index === valueRegex.lastIndex) {
4916
- valueRegex.lastIndex++;
4917
- }
4918
- if (match[1]) {
4919
- possibleValues.push(match[1]);
4920
- }
5164
+ // One literal, either quoting style. The unquoted numeric forms are the ones sys.check_constraints
5165
+ // actually stores: (3) (-1) (1.00) (2.5) (1.0000000000000000e+030) and (12345678901234567890.) —
5166
+ // an integral literal with a trailing point once the precision is large enough.
5167
+ const literal = `(?:'[^']+'|${ManageMetadataBase.NUMERIC_CHECK_LITERAL})`;
5168
+ const assignment = `${quotedField}=${literal}`;
5169
+ // Nested pattern: (Field IS NULL OR (Field=<literal> OR ...)) — how `X IS NULL OR X IN (...)` renders
5170
+ const nestedNullRegex = new RegExp(`^\\(${quotedField} IS NULL OR \\(${assignment}(?: OR ${assignment})*\\)\\)$`);
5171
+ // Standard pattern, with an optional trailing IS NULL: (Field=<literal> OR ... [OR Field IS NULL])
5172
+ const structureRegex = new RegExp(`^\\(${assignment}(?: OR ${assignment})*(?: OR ${quotedField} IS NULL)?\\)$`);
5173
+ if (!nestedNullRegex.test(processedConstraint) && !structureRegex.test(processedConstraint)) {
5174
+ return null;
5175
+ }
5176
+ // Extract the values: group 1 is a quoted literal, group 2 an unquoted numeric one.
5177
+ const valueRegex = new RegExp(`${quotedField}=(?:'([^']+)'|(${ManageMetadataBase.NUMERIC_CHECK_LITERAL}))`, 'g');
5178
+ const possibleValues = [];
5179
+ let match;
5180
+ while ((match = valueRegex.exec(processedConstraint)) !== null) {
5181
+ // This is necessary to avoid infinite loops with zero-width matches
5182
+ if (match.index === valueRegex.lastIndex) {
5183
+ valueRegex.lastIndex++;
5184
+ }
5185
+ const value = match[1] ?? (match[2] ? ManageMetadataBase.normalizeNumericCheckLiteral(match[2]) : undefined);
5186
+ if (value && value.length > 0) {
5187
+ possibleValues.push(value);
4921
5188
  }
4922
- return possibleValues.length > 0 ? possibleValues : null;
4923
5189
  }
4924
- // Check for standard pattern with optional trailing IS NULL
4925
- const structureRegex = new RegExp(`^\\(${quotedField}='[^']+'(?: OR ${quotedField}='[^']+?')+(?: OR ${quotedField} IS NULL)?\\)$`);
4926
- if (!structureRegex.test(processedConstraint)) {
5190
+ // An empty result is not a value list — returning [] here would set ValueListType='List' on a field
5191
+ // with no EntityFieldValue rows behind it.
5192
+ return possibleValues.length > 0 ? possibleValues : null;
5193
+ }
5194
+ /**
5195
+ * The value list to actually store for a field, or null when a parsed list should NOT become
5196
+ * EntityFieldValue rows (and so should not become a dropdown in Explorer either).
5197
+ *
5198
+ * Runs AFTER parsing rather than gating it, so each exclusion is no broader than its own reason and
5199
+ * neither one can drop a list that was captured before #3978:
5200
+ *
5201
+ * - `bit`: `IN (0,1)` is vacuous — bit already permits exactly 0 and 1 — and `= 1` is a validator,
5202
+ * not a two-item dropdown over what renders as a checkbox. Every bit list is rendered unquoted, so
5203
+ * none of them was reachable before this change and nothing regresses.
5204
+ * - a PRIMARY KEY carrying a SINGLE value: `CHECK (ID=1)` is the single-row-table guard MJ's own
5205
+ * sequence tables use — a structural invariant, not a set of values a user picks from. A
5206
+ * MULTI-value list on a primary key is left alone: `CHECK (Code IN ('US','CA'))` on a natural-key
5207
+ * PK is a real domain list, it was captured before this change, and CodeGen also runs over customer
5208
+ * schemas where natural-key primary keys are ordinary.
5209
+ *
5210
+ * A field whose metadata row was not found keeps whatever parsed, which is the pre-#3978 behaviour.
5211
+ */
5212
+ static valueListForField(field, parsedValues) {
5213
+ if (!parsedValues || !field) {
5214
+ return parsedValues;
5215
+ }
5216
+ if (field.Type?.trim().toLowerCase() === 'bit') {
4927
5217
  return null;
4928
5218
  }
4929
- else {
4930
- // Regular expression to match the values within the single quotes specifically for the field
4931
- const valueRegex = new RegExp(`${quotedField}='([^']+)\'`, 'g');
4932
- let match;
4933
- const possibleValues = [];
4934
- // Use regex to find matches and extract the values
4935
- while ((match = valueRegex.exec(processedConstraint)) !== null) {
4936
- // This is necessary to avoid infinite loops with zero-width matches
4937
- if (match.index === valueRegex.lastIndex) {
4938
- valueRegex.lastIndex++;
4939
- }
4940
- // The first captured group contains the value
4941
- if (match[1]) {
4942
- possibleValues.push(match[1]);
4943
- }
4944
- }
4945
- return possibleValues;
5219
+ if (field.IsPrimaryKey && parsedValues.length === 1) {
5220
+ return null;
4946
5221
  }
5222
+ return parsedValues;
5223
+ }
5224
+ /**
5225
+ * Sorts a parsed value list in place, so the sequence a value gets is stable across databases and runs.
5226
+ * An all-numeric list is compared as numbers (1, 2, 10); anything else keeps the default lexical order.
5227
+ *
5228
+ * Keyed off the VALUES, not the column type — so a string column whose list happens to be all-numeric
5229
+ * (`CHECK (Code IN ('1','2','10'))` on nvarchar) would re-sequence too. Measured over every column CHECK
5230
+ * constraint in a live 6.x database (MJ core + BizApps accounting/orders): of the 431 lists the previous
5231
+ * parser already captured, ZERO re-sequence under this comparison. If one ever turns up and the churn is
5232
+ * unwanted, gate `allNumeric` on the field being numeric as well.
5233
+ */
5234
+ static sortCheckConstraintValues(values) {
5235
+ const allNumeric = values.length > 0 && values.every(v => /^-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?$/.test(v));
5236
+ return allNumeric ? values.sort((a, b) => Number(a) - Number(b)) : values.sort();
5237
+ }
5238
+ /**
5239
+ * A numeric literal as SQL Server renders it inside a CHECK constraint: parenthesized, unquoted, and
5240
+ * possibly signed, fractional or exponential — `(3)`, `(-1)`, `(1.00)`, `(2.5)`, `(1.0e+030)`.
5241
+ */
5242
+ static { this.NUMERIC_CHECK_LITERAL = `\\(-?\\d+(?:\\.\\d*)?(?:[eE][+-]?\\d+)?\\)`; }
5243
+ /**
5244
+ * Turns a matched numeric literal into the value to store: strips the wrapping parentheses, and the
5245
+ * trailing point SQL Server adds to a large integral literal (`(12345678901234567890.)`).
5246
+ */
5247
+ static normalizeNumericCheckLiteral(literal) {
5248
+ const inner = literal.slice(1, -1);
5249
+ return inner.endsWith('.') ? inner.slice(0, -1) : inner;
4947
5250
  }
4948
5251
  /**
4949
5252
  * Parses PostgreSQL ANY (ARRAY[...]) CHECK constraint syntax.
@@ -5006,7 +5309,7 @@ export class ManageMetadataBase {
5006
5309
  // it — user-visible AND editable, letting someone mutate the snapshot the refresher overwrites. The
5007
5310
  // wrapper view is already excluded (it carries the minted entity, so EntityID IS NOT NULL). The outer
5008
5311
  // view is aliased `t` so the correlated MaterializedResult subquery can't resolve columns ambiguously.
5009
- const coreSchema = mj_core_schema();
5312
+ const coreSchema = MjCoreSchema();
5010
5313
  // Gate the MaterializedResult reference on the table actually existing. Referencing it unconditionally
5011
5314
  // would throw — breaking new-entity creation for EVERY entity — on any DB where MaterializedResult
5012
5315
  // isn't present yet (e.g. the PostgreSQL parallel world's object-availability lag). If it's absent we
@@ -5150,7 +5453,7 @@ export class ManageMetadataBase {
5150
5453
  const result = await ag.generateEntityName(newEntity.TableName, currentUser);
5151
5454
  // Checked here as well as inside generateEntityName: a subclass or a stub can return anything, and
5152
5455
  // a non-name that reaches the INSERT fails it (see createNewEntity's catch for why that used to be silent).
5153
- if (result && isPlausibleEntityName(result.entityName)) {
5456
+ if (result && IsPlausibleEntityName(result.entityName)) {
5154
5457
  return this.markupEntityName(newEntity.SchemaName, result.entityName);
5155
5458
  }
5156
5459
  else {
@@ -5215,7 +5518,7 @@ export class ManageMetadataBase {
5215
5518
  return configInfo.newEntityDefaults?.NameRulesBySchema?.find(r => {
5216
5519
  let schemaNameToUse = r.SchemaName;
5217
5520
  if (schemaNameToUse?.trim().toLowerCase() === '${mj_core_schema}') {
5218
- schemaNameToUse = mj_core_schema();
5521
+ schemaNameToUse = MjCoreSchema();
5219
5522
  }
5220
5523
  return schemaNameToUse.trim().toLowerCase() === schemaName.trim().toLowerCase();
5221
5524
  });
@@ -5265,7 +5568,7 @@ export class ManageMetadataBase {
5265
5568
  // process a single new entity
5266
5569
  let newEntityName = await this.createNewEntityName(newEntity, currentUser);
5267
5570
  const newEntityDisplayName = this.createNewEntityDisplayName(newEntity, newEntityName);
5268
- const { name: uniqueName, suffix: uniqueSuffix } = this.resolveUniqueEntityName(newEntityName, newEntity.SchemaName, md.Entities.map(e => e.Name));
5571
+ const { name: uniqueName, suffix: uniqueSuffix } = this.ResolveUniqueEntityName(newEntityName, newEntity.SchemaName, md.Entities.map(e => e.Name));
5269
5572
  if (uniqueName !== newEntityName) {
5270
5573
  LogError(` >>>> WARNING: Entity name already exists, so using ${uniqueName} instead. If you did not intend for this, please rename the ${newEntity.SchemaName}.${newEntity.TableName} table in the database.`);
5271
5574
  }
@@ -5274,7 +5577,7 @@ export class ManageMetadataBase {
5274
5577
  const isNewSchema = await this.isSchemaNew(pool, newEntity.SchemaName);
5275
5578
  const newEntityID = this.createNewUUID();
5276
5579
  const sSQLInsert = this.createNewEntityInsertSQL(newEntityID, newEntityName, newEntity, suffix, newEntityDisplayName);
5277
- await this.LogSQLAndExecute(pool, sSQLInsert, `SQL generated to create new entity ${newEntityName}`);
5580
+ await this.logSQLAndExecute(pool, sSQLInsert, `SQL generated to create new entity ${newEntityName}`);
5278
5581
  // if we get here we created a new entity safely, otherwise we get exception
5279
5582
  // add it to the new entity list
5280
5583
  ManageMetadataBase.newEntityList.push(newEntityName);
@@ -5307,10 +5610,10 @@ export class ManageMetadataBase {
5307
5610
  if (configInfo.newEntityDefaults.AddToApplicationWithSchemaName) {
5308
5611
  // only do this if the configuration setting is set to add new entities to applications for schema names
5309
5612
  for (const appUUID of apps) {
5310
- const sSQLInsertApplicationEntity = `INSERT INTO ${this.qs(mj_core_schema(), 'ApplicationEntity')}
5613
+ const sSQLInsertApplicationEntity = `INSERT INTO ${this.qs(MjCoreSchema(), 'ApplicationEntity')}
5311
5614
  (${this.qi('ApplicationID')}, ${this.qi('EntityID')}, ${this.qi('Sequence')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')}) VALUES
5312
- ('${appUUID}', '${newEntityID}', (SELECT COALESCE(MAX(${this.qi('Sequence')}),0)+1 FROM ${this.qs(mj_core_schema(), 'ApplicationEntity')} WHERE ${this.qi('ApplicationID')} = '${appUUID}'), ${this.utcNow()}, ${this.utcNow()})`;
5313
- await this.LogSQLAndExecute(pool, sSQLInsertApplicationEntity, `SQL generated to add new entity ${newEntityName} to application ID: '${appUUID}'`);
5615
+ ('${appUUID}', '${newEntityID}', (SELECT COALESCE(MAX(${this.qi('Sequence')}),0)+1 FROM ${this.qs(MjCoreSchema(), 'ApplicationEntity')} WHERE ${this.qi('ApplicationID')} = '${appUUID}'), ${this.utcNow()}, ${this.utcNow()})`;
5616
+ await this.logSQLAndExecute(pool, sSQLInsertApplicationEntity, `SQL generated to add new entity ${newEntityName} to application ID: '${appUUID}'`);
5314
5617
  }
5315
5618
  }
5316
5619
  else {
@@ -5329,7 +5632,7 @@ export class ManageMetadataBase {
5329
5632
  const RoleID = md.Roles.find(r => r.Name.trim().toLowerCase() === p.RoleName.trim().toLowerCase())?.ID;
5330
5633
  if (RoleID) {
5331
5634
  const sSQLInsertPermission = this.buildEntityPermissionInsertSQL(newEntityID, RoleID, p.CanRead, p.CanCreate, p.CanUpdate, p.CanDelete);
5332
- await this.LogSQLAndExecute(pool, sSQLInsertPermission, `SQL generated to add new permission for entity ${newEntityName} for role ${p.RoleName}`);
5635
+ await this.logSQLAndExecute(pool, sSQLInsertPermission, `SQL generated to add new permission for entity ${newEntityName} for role ${p.RoleName}`);
5333
5636
  }
5334
5637
  else
5335
5638
  LogError(` >>>> ERROR: Unable to find Role ID for role ${p.RoleName} to add permissions for new entity ${newEntityName}`);
@@ -5363,7 +5666,7 @@ export class ManageMetadataBase {
5363
5666
  async isSchemaNew(pool, schemaName) {
5364
5667
  // check to see if there are any entities in the db with this schema name
5365
5668
  // Quote the alias so PostgreSQL preserves PascalCase (unquoted aliases are lowercased in PG)
5366
- const sSQL = `SELECT COUNT(*) AS ${this.qi('Count')} FROM ${this.qs(mj_core_schema(), 'Entity')} WHERE ${this.qi('SchemaName')} = '${schemaName}'`;
5669
+ const sSQL = `SELECT COUNT(*) AS ${this.qi('Count')} FROM ${this.qs(MjCoreSchema(), 'Entity')} WHERE ${this.qi('SchemaName')} = '${schemaName}'`;
5367
5670
  const resultResult = await this.runQuery(pool, sSQL);
5368
5671
  const result = resultResult.recordset;
5369
5672
  // Use Number() because PG returns COUNT(*) as bigint, which the pg driver delivers as a string
@@ -5395,7 +5698,7 @@ export class ManageMetadataBase {
5395
5698
  // Guard the INSERT with an existence check so the emitted (and re-runnable) migration SQL is
5396
5699
  // idempotent. drop-schema clears an app's ApplicationEntity/EntityPermission/Entity rows but NOT
5397
5700
  // its Application row, so replaying this block would otherwise collide on the Application PK.
5398
- const appCheckQuery = `SELECT 1 FROM ${this.qs(mj_core_schema(), 'Application')} WHERE ${this.qi('ID')} = '${appID}'`;
5701
+ const appCheckQuery = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'Application')} WHERE ${this.qi('ID')} = '${appID}'`;
5399
5702
  // Schema-named bucket apps are plumbing (entity links, role grants, SchemaAutoAddNewEntities),
5400
5703
  // not products — hide them from new users. Application.DefaultForNewUser defaults to 1 in the
5401
5704
  // DB, so omitting the column here is what put raw '__mj_*'-named apps in every new user's
@@ -5404,10 +5707,10 @@ export class ManageMetadataBase {
5404
5707
  // statement in PG's `DO $$ ... $$` block, and the identifier auto-quoter skips dollar-quoted
5405
5708
  // blocks wholesale (they can legally contain arbitrary text), so nothing downstream will quote
5406
5709
  // these for us. Bare `ID` reaches PG folded to `id` and the INSERT fails on every run.
5407
- const appInsert = `INSERT INTO ${this.qs(mj_core_schema(), 'Application')} (${this.qi('ID')}, ${this.qi('Name')}, ${this.qi('Description')}, ${this.qi('SchemaAutoAddNewEntities')}, ${this.qi('Path')}, ${this.qi('AutoUpdatePath')}, ${this.qi('DefaultForNewUser')})
5710
+ const appInsert = `INSERT INTO ${this.qs(MjCoreSchema(), 'Application')} (${this.qi('ID')}, ${this.qi('Name')}, ${this.qi('Description')}, ${this.qi('SchemaAutoAddNewEntities')}, ${this.qi('Path')}, ${this.qi('AutoUpdatePath')}, ${this.qi('DefaultForNewUser')})
5408
5711
  VALUES ('${appID}', '${appName}', 'Generated for schema', '${schemaName}', '${path}', ${this.dialect.BooleanLiteral(true)}, ${this.dialect.BooleanLiteral(false)})`;
5409
5712
  const sSQL = this.conditionalInsert(appCheckQuery, appInsert);
5410
- await this.LogSQLAndExecute(pool, sSQL, `SQL generated to create new application ${appName}`);
5713
+ await this.logSQLAndExecute(pool, sSQL, `SQL generated to create new application ${appName}`);
5411
5714
  LogStatus(`Created new application ${appName} with Path: ${path}`);
5412
5715
  // Auto-assign default roles to the new application
5413
5716
  await this.addDefaultRolesForApplication(pool, appID, appName);
@@ -5435,12 +5738,12 @@ export class ManageMetadataBase {
5435
5738
  // This covers BOTH re-running the block after drop-schema (which leaves ApplicationRole rows
5436
5739
  // intact) AND the collision with the Integration role that manageMetadata recreates
5437
5740
  // out-of-band — either path would otherwise violate UQ_ApplicationRole_App_Role.
5438
- const roleCheckQuery = `SELECT 1 FROM ${this.qs(mj_core_schema(), 'ApplicationRole')} WHERE ${this.qi('ApplicationID')} = '${appId}' AND ${this.qi('RoleID')} = '${role.ID}'`;
5439
- const roleInsert = `INSERT INTO ${this.qs(mj_core_schema(), 'ApplicationRole')}
5741
+ const roleCheckQuery = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'ApplicationRole')} WHERE ${this.qi('ApplicationID')} = '${appId}' AND ${this.qi('RoleID')} = '${role.ID}'`;
5742
+ const roleInsert = `INSERT INTO ${this.qs(MjCoreSchema(), 'ApplicationRole')}
5440
5743
  (${this.qi('ApplicationID')}, ${this.qi('RoleID')}, ${this.qi('CanAccess')}, ${this.qi('CanAdmin')}) VALUES
5441
5744
  ('${appId}', '${role.ID}', ${this.boolLit(roleDef.CanAccess)}, ${this.boolLit(roleDef.CanAdmin)})`;
5442
5745
  const sSQLInsert = this.conditionalInsert(roleCheckQuery, roleInsert);
5443
- await this.LogSQLAndExecute(pool, sSQLInsert, `Adding role ${roleDef.RoleName} to application ${appName}`);
5746
+ await this.logSQLAndExecute(pool, sSQLInsert, `Adding role ${roleDef.RoleName} to application ${appName}`);
5444
5747
  }
5445
5748
  else {
5446
5749
  LogError(`Unable to find Role '${roleDef.RoleName}' for application ${appName}`);
@@ -5448,14 +5751,14 @@ export class ManageMetadataBase {
5448
5751
  }
5449
5752
  }
5450
5753
  async applicationExists(pool, applicationName) {
5451
- const sSQL = `SELECT ID FROM ${this.qs(mj_core_schema(), 'Application')} WHERE Name = '${applicationName}'`;
5754
+ const sSQL = `SELECT ID FROM ${this.qs(MjCoreSchema(), 'Application')} WHERE Name = '${applicationName}'`;
5452
5755
  const resultResult = await this.runQuery(pool, sSQL);
5453
5756
  const result = resultResult.recordset;
5454
5757
  return result && result.length > 0 ? result[0].ID.length > 0 : false;
5455
5758
  }
5456
5759
  async getApplicationIDForSchema(pool, schemaName) {
5457
5760
  // get all the apps each time from DB as we might be adding, don't use Metadata here for that reason
5458
- const sSQL = `SELECT ID, Name, SchemaAutoAddNewEntities FROM ${this.qs(mj_core_schema(), 'vwApplications')}`;
5761
+ const sSQL = `SELECT ID, Name, SchemaAutoAddNewEntities FROM ${this.qs(MjCoreSchema(), 'vwApplications')}`;
5459
5762
  const resultResult = await this.runQuery(pool, sSQL);
5460
5763
  const result = resultResult.recordset;
5461
5764
  if (!result || result.length === 0) {
@@ -5497,10 +5800,10 @@ export class ManageMetadataBase {
5497
5800
  if (apps && apps.length > 0) {
5498
5801
  if (configInfo.newEntityDefaults.AddToApplicationWithSchemaName) {
5499
5802
  for (const appUUID of apps) {
5500
- const sSQLInsert = `INSERT INTO ${this.qs(mj_core_schema(), 'ApplicationEntity')}
5803
+ const sSQLInsert = `INSERT INTO ${this.qs(MjCoreSchema(), 'ApplicationEntity')}
5501
5804
  (${this.qi('ApplicationID')}, ${this.qi('EntityID')}, ${this.qi('Sequence')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')}) VALUES
5502
- ('${appUUID}', '${entityId}', (SELECT COALESCE(MAX(${this.qi('Sequence')}),0)+1 FROM ${this.qs(mj_core_schema(), 'ApplicationEntity')} WHERE ${this.qi('ApplicationID')} = '${appUUID}'), ${this.utcNow()}, ${this.utcNow()})`;
5503
- await this.LogSQLAndExecute(pool, sSQLInsert, `SQL generated to add entity ${entityName} to application ID: '${appUUID}'`);
5805
+ ('${appUUID}', '${entityId}', (SELECT COALESCE(MAX(${this.qi('Sequence')}),0)+1 FROM ${this.qs(MjCoreSchema(), 'ApplicationEntity')} WHERE ${this.qi('ApplicationID')} = '${appUUID}'), ${this.utcNow()}, ${this.utcNow()})`;
5806
+ await this.logSQLAndExecute(pool, sSQLInsert, `SQL generated to add entity ${entityName} to application ID: '${appUUID}'`);
5504
5807
  }
5505
5808
  }
5506
5809
  }
@@ -5526,7 +5829,7 @@ export class ManageMetadataBase {
5526
5829
  * valid on both SQL Server and PostgreSQL, so no provider branch is needed.
5527
5830
  */
5528
5831
  buildEntityPermissionInsertSQL(entityId, roleId, canRead, canCreate, canUpdate, canDelete) {
5529
- const table = this.qs(mj_core_schema(), 'EntityPermission');
5832
+ const table = this.qs(MjCoreSchema(), 'EntityPermission');
5530
5833
  const entityLit = this.uuidLit(entityId);
5531
5834
  const roleLit = this.uuidLit(roleId);
5532
5835
  return `INSERT INTO ${table}
@@ -5551,7 +5854,7 @@ export class ManageMetadataBase {
5551
5854
  const RoleID = md.Roles.find(r => r.Name.trim().toLowerCase() === p.RoleName.trim().toLowerCase())?.ID;
5552
5855
  if (RoleID) {
5553
5856
  const sSQLInsert = this.buildEntityPermissionInsertSQL(entityId, RoleID, p.CanRead, p.CanCreate, p.CanUpdate, p.CanDelete);
5554
- await this.LogSQLAndExecute(pool, sSQLInsert, `SQL generated to add permission for entity ${entityName} for role ${p.RoleName}`);
5857
+ await this.logSQLAndExecute(pool, sSQLInsert, `SQL generated to add permission for entity ${entityName} for role ${p.RoleName}`);
5555
5858
  }
5556
5859
  else {
5557
5860
  LogError(` >>>> ERROR: Unable to find Role ID for role ${p.RoleName} to add permissions for entity ${entityName}`);
@@ -5713,7 +6016,7 @@ export class ManageMetadataBase {
5713
6016
  continue;
5714
6017
  }
5715
6018
  const sSQLInsert = this.buildEntityPermissionInsertSQL(entityId, roleId, true, false, false, false);
5716
- await this.LogSQLAndExecute(pool, sSQLInsert, `SQL generated to add read permission for materialized entity ${entityName} for role ${p.RoleName}`);
6019
+ await this.logSQLAndExecute(pool, sSQLInsert, `SQL generated to add read permission for materialized entity ${entityName} for role ${p.RoleName}`);
5717
6020
  }
5718
6021
  }
5719
6022
  /**
@@ -5723,8 +6026,8 @@ export class ManageMetadataBase {
5723
6026
  * human authors protection. Non-destructive (rows are kept, just flipped) so the grant can be restored.
5724
6027
  */
5725
6028
  async revokeMaterializedEntityReadAccess(pool, entityId, entityLabel, reason) {
5726
- const sql = `UPDATE ${this.qs(mj_core_schema(), 'EntityPermission')} SET ${this.qi('CanRead')}=${this.boolLit(false)} WHERE ${this.qi('EntityID')}='${entityId}' AND ${this.qi('CanRead')}=${this.boolLit(true)}`;
5727
- await this.LogSQLAndExecute(pool, sql, `Revoke read access on materialized entity "${entityLabel}" (${reason})`);
6029
+ const sql = `UPDATE ${this.qs(MjCoreSchema(), 'EntityPermission')} SET ${this.qi('CanRead')}=${this.boolLit(false)} WHERE ${this.qi('EntityID')}='${entityId}' AND ${this.qi('CanRead')}=${this.boolLit(true)}`;
6030
+ await this.logSQLAndExecute(pool, sql, `Revoke read access on materialized entity "${entityLabel}" (${reason})`);
5728
6031
  }
5729
6032
  /**
5730
6033
  * ROLE-RLS LAYER ONLY — true if any of the entity's role permissions carries a non-empty `ReadRLSFilterID`.
@@ -5795,7 +6098,7 @@ export class ManageMetadataBase {
5795
6098
  for (const table of ['APIKeyScope', 'APIApplicationScope']) {
5796
6099
  if (!(await this.columnExistsInCoreSchema(pool, table, 'RowFilterID')))
5797
6100
  continue;
5798
- const res = await this.runQuery(pool, `SELECT DISTINCT ${this.qi('ResourcePattern')} AS ResourcePattern FROM ${this.qs(mj_core_schema(), table)} WHERE ${this.qi('RowFilterID')} IS NOT NULL`);
6101
+ const res = await this.runQuery(pool, `SELECT DISTINCT ${this.qi('ResourcePattern')} AS ResourcePattern FROM ${this.qs(MjCoreSchema(), table)} WHERE ${this.qi('RowFilterID')} IS NOT NULL`);
5799
6102
  for (const row of res.recordset ?? []) {
5800
6103
  const r = row;
5801
6104
  const pattern = (r.ResourcePattern ?? r.resourcepattern) ?? '';
@@ -5828,7 +6131,7 @@ export class ManageMetadataBase {
5828
6131
  if (cached !== undefined)
5829
6132
  return cached;
5830
6133
  const sql = `SELECT COUNT(*) AS ColExists FROM INFORMATION_SCHEMA.COLUMNS ` +
5831
- `WHERE TABLE_SCHEMA = '${mj_core_schema()}' AND TABLE_NAME = '${table}' AND COLUMN_NAME = '${column}'`;
6134
+ `WHERE TABLE_SCHEMA = '${MjCoreSchema()}' AND TABLE_NAME = '${table}' AND COLUMN_NAME = '${column}'`;
5832
6135
  const result = await this.runQuery(pool, sql);
5833
6136
  const row = (result.recordset?.[0] ?? {});
5834
6137
  const cnt = row.ColExists ?? row.colexists ?? 0;
@@ -5848,14 +6151,14 @@ export class ManageMetadataBase {
5848
6151
  if (sourceEntities.length === 0)
5849
6152
  return 0; // no sources to intersect against — the RLS/empty gate handles this
5850
6153
  const roleCanReadAllSources = (roleId) => sourceEntities.every((e) => e.Permissions.some((p) => UUIDsEqual(p.RoleID, roleId) && p.CanRead));
5851
- const grants = await this.runQuery(pool, `SELECT ${this.qi('RoleID')} FROM ${this.qs(mj_core_schema(), 'EntityPermission')} WHERE ${this.qi('EntityID')}='${entityId}' AND ${this.qi('CanRead')}=${this.boolLit(true)}`);
6154
+ const grants = await this.runQuery(pool, `SELECT ${this.qi('RoleID')} FROM ${this.qs(MjCoreSchema(), 'EntityPermission')} WHERE ${this.qi('EntityID')}='${entityId}' AND ${this.qi('CanRead')}=${this.boolLit(true)}`);
5852
6155
  let revoked = 0;
5853
6156
  for (const g of grants.recordset) {
5854
6157
  const roleId = g.RoleID;
5855
6158
  if (!roleId)
5856
6159
  continue;
5857
6160
  if (!roleCanReadAllSources(roleId)) {
5858
- await this.LogSQLAndExecute(pool, `UPDATE ${this.qs(mj_core_schema(), 'EntityPermission')} SET ${this.qi('CanRead')}=${this.boolLit(false)} WHERE ${this.qi('EntityID')}='${entityId}' AND ${this.qi('RoleID')}='${roleId}' AND ${this.qi('CanRead')}=${this.boolLit(true)}`, `Narrow read grant on materialized entity "${entityLabel}": role ${roleId} can no longer read every source (C2 intersection re-narrowed)`);
6161
+ await this.logSQLAndExecute(pool, `UPDATE ${this.qs(MjCoreSchema(), 'EntityPermission')} SET ${this.qi('CanRead')}=${this.boolLit(false)} WHERE ${this.qi('EntityID')}='${entityId}' AND ${this.qi('RoleID')}='${roleId}' AND ${this.qi('CanRead')}=${this.boolLit(true)}`, `Narrow read grant on materialized entity "${entityLabel}": role ${roleId} can no longer read every source (C2 intersection re-narrowed)`);
5859
6162
  revoked++;
5860
6163
  }
5861
6164
  }
@@ -5885,7 +6188,7 @@ export class ManageMetadataBase {
5885
6188
  * earlier in this run (which are not in metadata yet)
5886
6189
  * @returns the free name and the suffix used to reach it ('' when the name was already free)
5887
6190
  */
5888
- resolveUniqueEntityName(desiredName, schemaName, takenNames) {
6191
+ ResolveUniqueEntityName(desiredName, schemaName, takenNames) {
5889
6192
  const taken = new Set([...takenNames, ...ManageMetadataBase.newEntityList].map(n => n.toLowerCase()));
5890
6193
  const isTaken = (candidate) => taken.has(candidate.toLowerCase());
5891
6194
  if (!isTaken(desiredName)) {
@@ -5904,13 +6207,50 @@ export class ManageMetadataBase {
5904
6207
  }
5905
6208
  return { name, suffix };
5906
6209
  }
6210
+ /** @deprecated Use {@link ResolveUniqueEntityName}. */
6211
+ resolveUniqueEntityName(desiredName, schemaName, takenNames) {
6212
+ return this.ResolveUniqueEntityName(desiredName, schemaName, takenNames);
6213
+ }
6214
+ /**
6215
+ * INSERT for a config-declared virtual entity's Entity row. Logged rather than a stored-procedure
6216
+ * call so the CodeGen_Run capture replays it with the same ID on every database, exactly like
6217
+ * table-backed entities. Column set and flags match spCreateVirtualEntity, plus Description.
6218
+ */
6219
+ buildVirtualEntityInsertSQL(entityId, entityName, viewSchema, viewName, description) {
6220
+ const q = (name) => this.qi(name);
6221
+ const lit = (value) => `'${EscapeSQLString(value)}'`;
6222
+ return `INSERT INTO ${this.qs(MjCoreSchema(), 'Entity')} (
6223
+ ${q('ID')}, ${q('Name')}, ${q('Description')}, ${q('BaseTable')}, ${q('BaseView')}, ${q('SchemaName')},
6224
+ ${q('VirtualEntity')}, ${q('IncludeInAPI')}, ${q('AllowCreateAPI')}, ${q('AllowUpdateAPI')}, ${q('AllowDeleteAPI')},
6225
+ ${q('AllowRecordMerge')}, ${q('TrackRecordChanges')}, ${q('__mj_CreatedAt')}, ${q('__mj_UpdatedAt')}
6226
+ ) VALUES (
6227
+ ${this.uuidLit(entityId)}, ${lit(entityName)}, ${description ? lit(description) : 'NULL'}, ${lit(viewName)}, ${lit(viewName)}, ${lit(viewSchema)},
6228
+ ${this.boolLit(true)}, ${this.boolLit(true)}, ${this.boolLit(false)}, ${this.boolLit(false)}, ${this.boolLit(false)},
6229
+ ${this.boolLit(false)}, ${this.boolLit(false)}, ${this.utcNow()}, ${this.utcNow()}
6230
+ )`;
6231
+ }
6232
+ /**
6233
+ * Seeds the first configured key column before the view-column sync runs, so the sync sees a key
6234
+ * and does not promote the first view column. Type is a placeholder the sync replaces.
6235
+ */
6236
+ buildVirtualEntityPlaceholderPKSQL(fieldId, entityId, pkFieldName, singleColumnPrimaryKey) {
6237
+ const q = (name) => this.qi(name);
6238
+ const { wantPrimaryKey, wantUnique } = this.resolvePrimaryKeyFlags(true, singleColumnPrimaryKey);
6239
+ return `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityField')} (
6240
+ ${q('ID')}, ${q('EntityID')}, ${q('Sequence')}, ${q('Name')}, ${q('IsPrimaryKey')}, ${q('IsUnique')}, ${q('Type')},
6241
+ ${q('__mj_CreatedAt')}, ${q('__mj_UpdatedAt')}
6242
+ ) VALUES (
6243
+ ${this.uuidLit(fieldId)}, ${this.uuidLit(entityId)}, ${this.applyTimeEntityFieldSequenceSQL(entityId)}, '${EscapeSQLString(pkFieldName)}',
6244
+ ${this.boolLit(wantPrimaryKey)}, ${this.boolLit(wantUnique)}, 'int', ${this.utcNow()}, ${this.utcNow()}
6245
+ )`;
6246
+ }
5907
6247
  createNewEntityInsertSQL(newEntityUUID, newEntityName, newEntity, newEntitySuffix, newEntityDisplayName) {
5908
6248
  const newEntityDefaults = configInfo.newEntityDefaults;
5909
6249
  const newEntityDescriptionEscaped = newEntity.EntityDescription ? `'${newEntity.EntityDescription.replace(/'/g, "''")}'` : null;
5910
6250
  const allowCaching = this.resolveAllowCachingForSchema(newEntity.SchemaName);
5911
6251
  const q = (name) => this.qi(name);
5912
6252
  const sSQLInsert = `
5913
- INSERT INTO ${this.qs(mj_core_schema(), 'Entity')} (
6253
+ INSERT INTO ${this.qs(MjCoreSchema(), 'Entity')} (
5914
6254
  ${q('ID')},
5915
6255
  ${q('Name')},
5916
6256
  ${q('DisplayName')},
@@ -5971,7 +6311,7 @@ export class ManageMetadataBase {
5971
6311
  const match = overrides.find(entry => {
5972
6312
  let candidate = entry.SchemaName;
5973
6313
  if (candidate?.trim().toLowerCase() === '${mj_core_schema}') {
5974
- candidate = mj_core_schema();
6314
+ candidate = MjCoreSchema();
5975
6315
  }
5976
6316
  return candidate.trim().toLowerCase() === schemaName.trim().toLowerCase();
5977
6317
  });
@@ -6032,7 +6372,7 @@ export class ManageMetadataBase {
6032
6372
  e.FullTextSearchEnabled,
6033
6373
  e.AutoUpdateFullTextSearch
6034
6374
  FROM
6035
- ${this.qs(mj_core_schema(), 'vwEntities')} e
6375
+ ${this.qs(MjCoreSchema(), 'vwEntities')} e
6036
6376
  WHERE
6037
6377
  ${whereClause}
6038
6378
  ORDER BY
@@ -6081,7 +6421,7 @@ export class ManageMetadataBase {
6081
6421
  ef.AutoUpdateFullTextSearch,
6082
6422
  ef.${this.qi('Length')} as MaxLength
6083
6423
  FROM
6084
- ${this.qs(mj_core_schema(), 'vwEntityFields')} ef
6424
+ ${this.qs(MjCoreSchema(), 'vwEntityFields')} ef
6085
6425
  WHERE
6086
6426
  ef.EntityID IN (${entityIds})
6087
6427
  ORDER BY
@@ -6099,7 +6439,7 @@ export class ManageMetadataBase {
6099
6439
  es.Name,
6100
6440
  es.Value
6101
6441
  FROM
6102
- ${this.qs(mj_core_schema(), 'EntitySetting')} es
6442
+ ${this.qs(MjCoreSchema(), 'EntitySetting')} es
6103
6443
  WHERE
6104
6444
  es.EntityID IN (${entityIds})
6105
6445
  AND es.Name = 'FieldCategoryInfo'
@@ -6174,13 +6514,13 @@ export class ManageMetadataBase {
6174
6514
  }
6175
6515
  }
6176
6516
  const pct = Math.round((processedCount / total) * 100);
6177
- updateSpinner(`Advanced generation: ${processedCount}/${total} entities (${pct}%)${errorCount > 0 ? ` — ${errorCount} error(s)` : ''}`);
6517
+ UpdateSpinner(`Advanced generation: ${processedCount}/${total} entities (${pct}%)${errorCount > 0 ? ` — ${errorCount} error(s)` : ''}`);
6178
6518
  // Credential circuit tripped (e.g. keyless / mis-credentialed env) — stop issuing further
6179
6519
  // AI calls; the remaining entities would only produce doomed round-trips. One clear message
6180
6520
  // was already logged when the circuit opened.
6181
6521
  if (ag.AICircuitOpen) {
6182
6522
  const skipped = total - processedCount;
6183
- updateSpinner(`Advanced generation: AI credential circuit open — skipping remaining ${skipped} entit${skipped === 1 ? 'y' : 'ies'} (check AI credentials).`);
6523
+ UpdateSpinner(`Advanced generation: AI credential circuit open — skipping remaining ${skipped} entit${skipped === 1 ? 'y' : 'ies'} (check AI credentials).`);
6184
6524
  break;
6185
6525
  }
6186
6526
  }
@@ -6351,7 +6691,7 @@ export class ManageMetadataBase {
6351
6691
  // Execute all updates in one batch
6352
6692
  if (sqlStatements.length > 0) {
6353
6693
  try {
6354
- await this.LogSQLBatchAndExecute(pool, sqlStatements, `Set field properties for entity`, false);
6694
+ await this.logSQLBatchAndExecute(pool, sqlStatements, `Set field properties for entity`, false);
6355
6695
  }
6356
6696
  catch (ex) {
6357
6697
  logError('Error executing combined smart field SQL: ', ex);
@@ -6379,7 +6719,7 @@ export class ManageMetadataBase {
6379
6719
  const proposedSearchableCount = (result.searchableFields ?? []).length;
6380
6720
  const proposedAllowUserSearch = result.allowUserSearch === true;
6381
6721
  // 1. Shape cleanup (defensive — identifyFields() also runs this).
6382
- const cleaned = normalizeSmartFieldResultShape(result);
6722
+ const cleaned = NormalizeSmartFieldResultShape(result);
6383
6723
  result.searchableFields = cleaned.searchableFields ?? [];
6384
6724
  result.searchPredicates = cleaned.searchPredicates ?? [];
6385
6725
  result.allowUserSearch = cleaned.allowUserSearch;
@@ -6400,14 +6740,14 @@ export class ManageMetadataBase {
6400
6740
  droppedIneligibleCount += 1;
6401
6741
  continue;
6402
6742
  }
6403
- if (isNarrativeFieldName(name) && !ftxEnabled) {
6743
+ if (IsNarrativeFieldName(name) && !ftxEnabled) {
6404
6744
  droppedNarrativeCount += 1;
6405
6745
  continue;
6406
6746
  }
6407
6747
  eligible.push(name);
6408
6748
  }
6409
6749
  // 3. Per-entity cap.
6410
- const { accepted, dropped: droppedByCap } = applySearchableFieldsCap(eligible);
6750
+ const { accepted, dropped: droppedByCap } = ApplySearchableFieldsCap(eligible);
6411
6751
  result.searchableFields = accepted;
6412
6752
  // 4. Predicate normalization. Build a fresh searchPredicates list keyed
6413
6753
  // on the accepted fields. The LLM's proposed predicates are the input
@@ -6422,7 +6762,7 @@ export class ManageMetadataBase {
6422
6762
  const normalizedPredicates = [];
6423
6763
  let predicatesRewrittenCount = 0;
6424
6764
  for (const fieldName of accepted) {
6425
- const { predicate, rewritten } = normalizePredicate({
6765
+ const { predicate, rewritten } = NormalizePredicate({
6426
6766
  fieldName,
6427
6767
  proposed: proposedByName.get(fieldName),
6428
6768
  isInFullTextSearchFields: ftsFieldSet.has(fieldName),
@@ -6497,7 +6837,7 @@ export class ManageMetadataBase {
6497
6837
  // Set the winner when it isn't flagged yet (and auto-update is allowed).
6498
6838
  if (winner && winner.AutoUpdateIsNameField && winner.ID && !winner.IsNameField) {
6499
6839
  sqlStatements.push(`
6500
- UPDATE ${this.qs(mj_core_schema(), 'EntityField')}
6840
+ UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
6501
6841
  SET IsNameField = ${this.boolLit(true)}
6502
6842
  WHERE ID = '${winner.ID}'
6503
6843
  AND AutoUpdateIsNameField = ${this.boolLit(true)}
@@ -6509,7 +6849,7 @@ export class ManageMetadataBase {
6509
6849
  continue;
6510
6850
  }
6511
6851
  sqlStatements.push(`
6512
- UPDATE ${this.qs(mj_core_schema(), 'EntityField')}
6852
+ UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
6513
6853
  SET IsNameField = ${this.boolLit(false)}
6514
6854
  WHERE ID = '${f.ID}'
6515
6855
  AND AutoUpdateIsNameField = ${this.boolLit(true)}
@@ -6658,7 +6998,7 @@ export class ManageMetadataBase {
6658
6998
  for (const field of defaultInViewFields) {
6659
6999
  if (!field.DefaultInView) {
6660
7000
  sqlStatements.push(`
6661
- UPDATE ${this.qs(mj_core_schema(), 'EntityField')}
7001
+ UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
6662
7002
  SET DefaultInView = ${this.boolLit(true)}
6663
7003
  WHERE ID = '${field.ID}'
6664
7004
  AND AutoUpdateDefaultInView = ${this.boolLit(true)}
@@ -6696,7 +7036,7 @@ export class ManageMetadataBase {
6696
7036
  }
6697
7037
  if (!field.IncludeInUserSearchAPI) {
6698
7038
  sqlStatements.push(`
6699
- UPDATE ${this.qs(mj_core_schema(), 'EntityField')}
7039
+ UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
6700
7040
  SET IncludeInUserSearchAPI = ${this.boolLit(true)}
6701
7041
  WHERE ID = '${field.ID}'
6702
7042
  AND AutoUpdateIncludeInUserSearchAPI = ${this.boolLit(true)}
@@ -6751,7 +7091,7 @@ export class ManageMetadataBase {
6751
7091
  * which is T-SQL-only. The subquery form is ANSI and runs unchanged on both platforms.
6752
7092
  */
6753
7093
  buildSearchFlagHygieneSQL(excludeSchemas) {
6754
- const coreSchema = mj_core_schema();
7094
+ const coreSchema = MjCoreSchema();
6755
7095
  const entity = this.qs(coreSchema, 'Entity');
6756
7096
  const entityField = this.qs(coreSchema, 'EntityField');
6757
7097
  const yes = this.boolLit(true);
@@ -6764,7 +7104,7 @@ export class ManageMetadataBase {
6764
7104
  // to 'Contains' in the database, which is `LIKE '%term%'` — the unindexable scan the
6765
7105
  // guardrails exist to prevent. Seeding the flag without the predicate would have made every
6766
7106
  // seeded entity a full scan on every keystroke.
6767
- const seedPredicate = defaultPredicateFor(NAME_LIKE_FIELD_NAMES[0]);
7107
+ const seedPredicate = DefaultPredicateFor(NAME_LIKE_FIELD_NAMES[0]);
6768
7108
  // The entity-shape guardrails the LLM path applies (`entityLevelEnableBlockedReason`).
6769
7109
  // A log / audit / run-history table grows without bound and a detail / line-item child is
6770
7110
  // reached through its parent; neither is a global-search target, whichever columns it has.
@@ -6917,7 +7257,7 @@ export class ManageMetadataBase {
6917
7257
  const seedCount = await this.searchFlagHygieneCandidateCount(pool, seedProbeSQL);
6918
7258
  if (seedCount > 0) {
6919
7259
  logStatus(` Search-flag hygiene: seeding ${seedCount} name field(s)`);
6920
- await this.LogSQLBatchAndExecute(pool, [seedSQL], 'Deterministic search-flag hygiene — seed name fields', false);
7260
+ await this.logSQLBatchAndExecute(pool, [seedSQL], 'Deterministic search-flag hygiene — seed name fields', false);
6921
7261
  }
6922
7262
  // Probed AFTER the seed has run, not alongside it. Seeding changes which entities still
6923
7263
  // have nothing searchable, so a clear probe taken before it would count entities the seed
@@ -6930,7 +7270,7 @@ export class ManageMetadataBase {
6930
7270
  const shown = clearNames.slice(0, 25).join(', ');
6931
7271
  const more = clearNames.length > 25 ? `, ... and ${clearNames.length - 25} more` : '';
6932
7272
  logStatus(` Search-flag hygiene: turning AllowUserSearchAPI OFF on ${clearNames.length} entity(ies): ${shown}${more}`);
6933
- await this.LogSQLBatchAndExecute(pool, [clearSQL], 'Deterministic search-flag hygiene — clear AllowUserSearchAPI', false);
7273
+ await this.logSQLBatchAndExecute(pool, [clearSQL], 'Deterministic search-flag hygiene — clear AllowUserSearchAPI', false);
6934
7274
  }
6935
7275
  return true;
6936
7276
  }
@@ -7018,7 +7358,7 @@ export class ManageMetadataBase {
7018
7358
  // Only update if the current value differs from the recommended predicate
7019
7359
  if (field.UserSearchPredicateAPI !== sp.predicate) {
7020
7360
  sqlStatements.push(`
7021
- UPDATE ${this.qs(mj_core_schema(), 'EntityField')}
7361
+ UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
7022
7362
  SET UserSearchPredicateAPI = '${sp.predicate}'
7023
7363
  WHERE ID = '${field.ID}'
7024
7364
  AND AutoUpdateUserSearchPredicate = ${this.boolLit(true)}
@@ -7049,7 +7389,7 @@ export class ManageMetadataBase {
7049
7389
  // the field-level guardrails, and refuses log/audit and detail/line-
7050
7390
  // item-shaped entities. Anything blocked here gets a one-line note in
7051
7391
  // the CodeGen run report so the team can audit proposals.
7052
- const blocked = entityLevelEnableBlockedReason({
7392
+ const blocked = EntityLevelEnableBlockedReason({
7053
7393
  entityName: entity.Name,
7054
7394
  confidence: result.confidence,
7055
7395
  acceptedSearchableFieldsCount: (result.searchableFields ?? []).length,
@@ -7065,7 +7405,7 @@ export class ManageMetadataBase {
7065
7405
  }
7066
7406
  if (newValue !== currentValue) {
7067
7407
  sqlStatements.push(`
7068
- UPDATE ${this.qs(mj_core_schema(), 'Entity')}
7408
+ UPDATE ${this.qs(MjCoreSchema(), 'Entity')}
7069
7409
  SET AllowUserSearchAPI = ${this.boolLit(newValue)}
7070
7410
  WHERE ID = '${entity.ID}'
7071
7411
  AND AutoUpdateAllowUserSearchAPI = ${this.boolLit(true)}
@@ -7108,7 +7448,7 @@ export class ManageMetadataBase {
7108
7448
  const currentValue = !!entity.FullTextSearchEnabled;
7109
7449
  if (newValue !== currentValue) {
7110
7450
  sqlStatements.push(`
7111
- UPDATE ${this.qs(mj_core_schema(), 'Entity')}
7451
+ UPDATE ${this.qs(MjCoreSchema(), 'Entity')}
7112
7452
  SET FullTextSearchEnabled = ${this.boolLit(newValue)}
7113
7453
  WHERE ID = '${entity.ID}'
7114
7454
  AND AutoUpdateFullTextSearch = ${this.boolLit(true)}
@@ -7130,7 +7470,7 @@ export class ManageMetadataBase {
7130
7470
  }
7131
7471
  if (!field.FullTextSearchEnabled) {
7132
7472
  sqlStatements.push(`
7133
- UPDATE ${this.qs(mj_core_schema(), 'EntityField')}
7473
+ UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
7134
7474
  SET FullTextSearchEnabled = ${this.boolLit(true)}
7135
7475
  WHERE ID = '${field.ID}'
7136
7476
  AND AutoUpdateFullTextSearch = ${this.boolLit(true)}
@@ -7175,7 +7515,7 @@ export class ManageMetadataBase {
7175
7515
  * Respects the AutoUpdateSupportsGeoCoding flag — if 0, the value is locked.
7176
7516
  */
7177
7517
  async detectAndSetGeoCodingSupport(pool, entity) {
7178
- const schema = mj_core_schema();
7518
+ const schema = MjCoreSchema();
7179
7519
  // Check if the entity's AutoUpdateSupportsGeoCoding flag allows us to modify it
7180
7520
  const autoUpdateResult = await pool.query(`
7181
7521
  SELECT ${this.qi('AutoUpdateSupportsGeoCoding')}, ${this.qi('SupportsGeoCoding')}
@@ -7198,7 +7538,7 @@ export class ManageMetadataBase {
7198
7538
  const shouldSupportGeo = existingGeoCount > 0;
7199
7539
  const currentValue = row.SupportsGeoCoding ? true : false;
7200
7540
  if (shouldSupportGeo !== currentValue) {
7201
- await this.LogSQLAndExecute(pool, `
7541
+ await this.logSQLAndExecute(pool, `
7202
7542
  UPDATE ${this.qs(schema, 'Entity')}
7203
7543
  SET ${this.qi('SupportsGeoCoding')} = ${this.boolLit(shouldSupportGeo)}
7204
7544
  WHERE ${this.qi('ID')} = '${entity.ID}' AND ${this.qi('AutoUpdateSupportsGeoCoding')} = ${this.boolLit(true)}
@@ -7272,14 +7612,14 @@ export class ManageMetadataBase {
7272
7612
  continue;
7273
7613
  }
7274
7614
  const lockCtx = {
7275
- isNewEntity: ctx.isNewEntity,
7276
- isNewField: ManageMetadataBase.isFieldNew(entity.ID, field.Name),
7277
- descriptionReopened: ManageMetadataBase.isDisplayNameReopened(entity.ID, field.Name),
7278
- typeReopened: ManageMetadataBase.isTypeReopened(entity.ID, field.Name),
7279
- existingCategories,
7615
+ IsNewEntity: ctx.isNewEntity,
7616
+ IsNewField: ManageMetadataBase.isFieldNew(entity.ID, field.Name),
7617
+ DescriptionReopened: ManageMetadataBase.isDisplayNameReopened(entity.ID, field.Name),
7618
+ TypeReopened: ManageMetadataBase.isTypeReopened(entity.ID, field.Name),
7619
+ ExistingCategories: existingCategories,
7280
7620
  };
7281
- const update = computeFieldMetadataUpdate(field, fieldCategory, lockCtx, this.validateExtendedType.bind(this), (val, fn) => this.sanitizeCodeType(val, fn ?? field.Name, entity.Name));
7282
- for (const skip of update.skipped) {
7621
+ const update = ComputeFieldMetadataUpdate(field, fieldCategory, lockCtx, this.validateExtendedType.bind(this), (val, fn) => this.sanitizeCodeType(val, fn ?? field.Name, entity.Name));
7622
+ for (const skip of update.Skipped) {
7283
7623
  if (skip.reason === 'locked') {
7284
7624
  reporter.counter('ai.fieldsLocked');
7285
7625
  }
@@ -7306,7 +7646,7 @@ export class ManageMetadataBase {
7306
7646
  setClauses.push(`CodeType = ${codeVal}`);
7307
7647
  }
7308
7648
  if (setClauses.length > 0) {
7309
- sqlStatements.push(`\n-- UPDATE Entity Field Category Info ${entity.Name}.${field.Name} \nUPDATE ${this.qs(mj_core_schema(), 'EntityField')}
7649
+ sqlStatements.push(`\n-- UPDATE Entity Field Category Info ${entity.Name}.${field.Name} \nUPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
7310
7650
  SET
7311
7651
  ${setClauses.join(',\n ')}
7312
7652
  WHERE
@@ -7315,7 +7655,7 @@ WHERE
7315
7655
  }
7316
7656
  if (sqlStatements.length > 0) {
7317
7657
  try {
7318
- await this.LogSQLBatchAndExecute(pool, sqlStatements, `Set categories for ${sqlStatements.length} fields`, false);
7658
+ await this.logSQLBatchAndExecute(pool, sqlStatements, `Set categories for ${sqlStatements.length} fields`, false);
7319
7659
  }
7320
7660
  catch (ex) {
7321
7661
  logError('Error Applying Field Categories', ex);
@@ -7328,19 +7668,19 @@ WHERE
7328
7668
  async applyEntityIcon(pool, entityId, entityIcon, entityName) {
7329
7669
  if (!entityIcon || entityIcon.trim().length === 0)
7330
7670
  return;
7331
- const checkSQL = `SELECT Icon FROM ${this.qs(mj_core_schema(), 'Entity')} WHERE ID = '${entityId}'`;
7671
+ const checkSQL = `SELECT Icon FROM ${this.qs(MjCoreSchema(), 'Entity')} WHERE ID = '${entityId}'`;
7332
7672
  const entityCheck = await this.runQuery(pool, checkSQL);
7333
7673
  if (entityCheck.recordset.length > 0) {
7334
7674
  const currentIcon = entityCheck.recordset[0].Icon;
7335
7675
  if (!currentIcon || currentIcon.trim().length === 0) {
7336
7676
  const escapedIcon = entityIcon.replace(/'/g, "''");
7337
7677
  const updateSQL = `
7338
- UPDATE ${this.qs(mj_core_schema(), 'Entity')}
7678
+ UPDATE ${this.qs(MjCoreSchema(), 'Entity')}
7339
7679
  SET ${this.qi('Icon')} = '${escapedIcon}', ${this.qi(EntityInfo.UpdatedAtFieldName)} = ${this.utcNow()}
7340
7680
  WHERE ${this.qi('ID')} = '${entityId}'
7341
7681
  `;
7342
7682
  try {
7343
- await this.LogSQLAndExecute(pool, updateSQL, `Set entity icon to ${entityIcon}`, false);
7683
+ await this.logSQLAndExecute(pool, updateSQL, `Set entity icon to ${entityIcon}`, false);
7344
7684
  logStatus(` Set entity icon: ${entityIcon}`);
7345
7685
  }
7346
7686
  catch (ex) {
@@ -7355,26 +7695,26 @@ WHERE
7355
7695
  async applyCategoryInfoSettings(pool, entityId, categoryInfo, _entityName) {
7356
7696
  if (!categoryInfo || Object.keys(categoryInfo).length === 0)
7357
7697
  return;
7358
- const canonicalInfo = canonicalJSONStringify(categoryInfo, 2);
7698
+ const canonicalInfo = CanonicalJSONStringify(categoryInfo, 2);
7359
7699
  const infoJSON = canonicalInfo.replace(/'/g, "''");
7360
7700
  const ENTITY_SETTING_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
7361
7701
  // Upsert FieldCategoryInfo (new format)
7362
- const checkNewSQL = `SELECT ${this.qi('ID')}, ${this.qi('Value')} FROM ${this.qs(mj_core_schema(), 'EntitySetting')} WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryInfo'`;
7702
+ const checkNewSQL = `SELECT ${this.qi('ID')}, ${this.qi('Value')} FROM ${this.qs(MjCoreSchema(), 'EntitySetting')} WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryInfo'`;
7363
7703
  const existingNew = await this.runQuery(pool, checkNewSQL);
7364
7704
  if (existingNew.recordset.length > 0) {
7365
7705
  let isMatch = false;
7366
7706
  try {
7367
7707
  const rawVal = existingNew.recordset[0].Value;
7368
7708
  const parsed = typeof rawVal === 'string' ? JSON.parse(rawVal) : rawVal;
7369
- isMatch = deepEqualJSON(parsed, categoryInfo);
7709
+ isMatch = DeepEqualJSON(parsed, categoryInfo);
7370
7710
  }
7371
7711
  catch {
7372
7712
  isMatch = false;
7373
7713
  }
7374
7714
  if (!isMatch) {
7375
7715
  try {
7376
- await this.LogSQLAndExecute(pool, `
7377
- UPDATE ${this.qs(mj_core_schema(), 'EntitySetting')}
7716
+ await this.logSQLAndExecute(pool, `
7717
+ UPDATE ${this.qs(MjCoreSchema(), 'EntitySetting')}
7378
7718
  SET ${this.qi('Value')} = '${infoJSON}', ${this.qi(EntityInfo.UpdatedAtFieldName)} = ${this.utcNow()}
7379
7719
  WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryInfo'
7380
7720
  `, `Update FieldCategoryInfo setting for entity`, false);
@@ -7387,11 +7727,11 @@ WHERE
7387
7727
  else {
7388
7728
  const newId = uuidv5(`${entityId}|FieldCategoryInfo`, ENTITY_SETTING_NAMESPACE);
7389
7729
  try {
7390
- const checkQuery = `SELECT 1 FROM ${this.qs(mj_core_schema(), 'EntitySetting')} WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryInfo'`;
7391
- const insertSQL = `INSERT INTO ${this.qs(mj_core_schema(), 'EntitySetting')} (${this.qi('ID')}, ${this.qi('EntityID')}, ${this.qi('Name')}, ${this.qi('Value')}, ${this.qi(EntityInfo.CreatedAtFieldName)}, ${this.qi(EntityInfo.UpdatedAtFieldName)})
7730
+ const checkQuery = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntitySetting')} WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryInfo'`;
7731
+ const insertSQL = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntitySetting')} (${this.qi('ID')}, ${this.qi('EntityID')}, ${this.qi('Name')}, ${this.qi('Value')}, ${this.qi(EntityInfo.CreatedAtFieldName)}, ${this.qi(EntityInfo.UpdatedAtFieldName)})
7392
7732
  VALUES ('${newId}', '${entityId}', 'FieldCategoryInfo', '${infoJSON}', ${this.utcNow()}, ${this.utcNow()})`;
7393
7733
  const sSQL = this.conditionalInsert(checkQuery, insertSQL);
7394
- await this.LogSQLAndExecute(pool, sSQL, `Insert FieldCategoryInfo setting for entity`, false);
7734
+ await this.logSQLAndExecute(pool, sSQL, `Insert FieldCategoryInfo setting for entity`, false);
7395
7735
  }
7396
7736
  catch (ex) {
7397
7737
  logError('Error Applying Category Info Settings: Part 2', ex);
@@ -7404,24 +7744,24 @@ WHERE
7404
7744
  iconsOnly[category] = info.icon;
7405
7745
  }
7406
7746
  }
7407
- const canonicalIcons = canonicalJSONStringify(iconsOnly, 2);
7747
+ const canonicalIcons = CanonicalJSONStringify(iconsOnly, 2);
7408
7748
  const iconsJSON = canonicalIcons.replace(/'/g, "''");
7409
- const checkLegacySQL = `SELECT ${this.qi('ID')}, ${this.qi('Value')} FROM ${this.qs(mj_core_schema(), 'EntitySetting')} WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryIcons'`;
7749
+ const checkLegacySQL = `SELECT ${this.qi('ID')}, ${this.qi('Value')} FROM ${this.qs(MjCoreSchema(), 'EntitySetting')} WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryIcons'`;
7410
7750
  const existingLegacy = await this.runQuery(pool, checkLegacySQL);
7411
7751
  if (existingLegacy.recordset.length > 0) {
7412
7752
  let isMatch = false;
7413
7753
  try {
7414
7754
  const rawVal = existingLegacy.recordset[0].Value;
7415
7755
  const parsed = typeof rawVal === 'string' ? JSON.parse(rawVal) : rawVal;
7416
- isMatch = deepEqualJSON(parsed, iconsOnly);
7756
+ isMatch = DeepEqualJSON(parsed, iconsOnly);
7417
7757
  }
7418
7758
  catch {
7419
7759
  isMatch = false;
7420
7760
  }
7421
7761
  if (!isMatch) {
7422
7762
  try {
7423
- await this.LogSQLAndExecute(pool, `
7424
- UPDATE ${this.qs(mj_core_schema(), 'EntitySetting')}
7763
+ await this.logSQLAndExecute(pool, `
7764
+ UPDATE ${this.qs(MjCoreSchema(), 'EntitySetting')}
7425
7765
  SET ${this.qi('Value')} = '${iconsJSON}', ${this.qi(EntityInfo.UpdatedAtFieldName)} = ${this.utcNow()}
7426
7766
  WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryIcons'
7427
7767
  `, `Update FieldCategoryIcons setting (legacy)`, false);
@@ -7434,11 +7774,11 @@ WHERE
7434
7774
  else {
7435
7775
  const newId = uuidv5(`${entityId}|FieldCategoryIcons`, ENTITY_SETTING_NAMESPACE);
7436
7776
  try {
7437
- const checkQuery = `SELECT 1 FROM ${this.qs(mj_core_schema(), 'EntitySetting')} WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryIcons'`;
7438
- const insertSQL = `INSERT INTO ${this.qs(mj_core_schema(), 'EntitySetting')} (${this.qi('ID')}, ${this.qi('EntityID')}, ${this.qi('Name')}, ${this.qi('Value')}, ${this.qi(EntityInfo.CreatedAtFieldName)}, ${this.qi(EntityInfo.UpdatedAtFieldName)})
7777
+ const checkQuery = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntitySetting')} WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryIcons'`;
7778
+ const insertSQL = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntitySetting')} (${this.qi('ID')}, ${this.qi('EntityID')}, ${this.qi('Name')}, ${this.qi('Value')}, ${this.qi(EntityInfo.CreatedAtFieldName)}, ${this.qi(EntityInfo.UpdatedAtFieldName)})
7439
7779
  VALUES ('${newId}', '${entityId}', 'FieldCategoryIcons', '${iconsJSON}', ${this.utcNow()}, ${this.utcNow()})`;
7440
7780
  const sSQL = this.conditionalInsert(checkQuery, insertSQL);
7441
- await this.LogSQLAndExecute(pool, sSQL, `Insert FieldCategoryIcons setting (legacy)`, false);
7781
+ await this.logSQLAndExecute(pool, sSQL, `Insert FieldCategoryIcons setting (legacy)`, false);
7442
7782
  }
7443
7783
  catch (ex) {
7444
7784
  logError('Error Applying Category Info Settings: Part 4', ex);
@@ -7451,12 +7791,12 @@ WHERE
7451
7791
  */
7452
7792
  async applyEntityImportance(pool, entityId, importance, entityName) {
7453
7793
  const updateSQL = `
7454
- UPDATE ${this.qs(mj_core_schema(), 'ApplicationEntity')}
7794
+ UPDATE ${this.qs(MjCoreSchema(), 'ApplicationEntity')}
7455
7795
  SET ${this.qi('DefaultForNewUser')} = ${this.boolLit(importance.defaultForNewUser)}, ${this.qi(EntityInfo.UpdatedAtFieldName)} = ${this.utcNow()}
7456
7796
  WHERE ${this.qi('EntityID')} = '${entityId}'
7457
7797
  `;
7458
7798
  try {
7459
- await this.LogSQLAndExecute(pool, updateSQL, `Set DefaultForNewUser=${importance.defaultForNewUser} for NEW entity (category: ${importance.entityCategory}, confidence: ${importance.confidence})`, false);
7799
+ await this.logSQLAndExecute(pool, updateSQL, `Set DefaultForNewUser=${importance.defaultForNewUser} for NEW entity (category: ${importance.entityCategory}, confidence: ${importance.confidence})`, false);
7460
7800
  logStatus(` Entity importance (NEW Entity): ${importance.entityCategory} (defaultForNewUser: ${importance.defaultForNewUser}, confidence: ${importance.confidence})`);
7461
7801
  logStatus(` Reasoning: ${importance.reasoning}`);
7462
7802
  }
@@ -7474,7 +7814,7 @@ WHERE
7474
7814
  * @param isRecurringScript - if set to true tells the logger that the provided SQL represents a recurring script meaning it is something that is executed, generally, for all CodeGen runs. In these cases, the Config settings can result in omitting these recurring scripts from being logged because the configuration environment may have those recurring scripts already set to run after all run-specific migrations get run.
7475
7815
  * @returns - The result of the query execution.
7476
7816
  */
7477
- async LogSQLAndExecute(pool, query, description, isRecurringScript = false, includeBatchSeparator = false, batchSeparator = 'GO', requiresOwnBatch = false) {
7817
+ async logSQLAndExecute(pool, query, description, isRecurringScript = false, includeBatchSeparator = false, batchSeparator = 'GO', requiresOwnBatch = false) {
7478
7818
  return await SQLLogging.LogSQLAndExecute(pool, this.qsql(query), description, isRecurringScript, includeBatchSeparator, batchSeparator, requiresOwnBatch);
7479
7819
  }
7480
7820
  /**
@@ -7493,17 +7833,17 @@ WHERE
7493
7833
  * Empty / whitespace-only statements are filtered out. Returns
7494
7834
  * `undefined` (no execution) when nothing remains.
7495
7835
  */
7496
- async LogSQLBatchAndExecute(pool, statements, description, isRecurringScript = false, includeBatchSeparator = false, batchSeparator = 'GO') {
7836
+ async logSQLBatchAndExecute(pool, statements, description, isRecurringScript = false, includeBatchSeparator = false, batchSeparator = 'GO') {
7497
7837
  const terminated = [];
7498
7838
  for (const s of statements) {
7499
- const trimmed = trimTrailingStatementTerminators(s ?? '');
7839
+ const trimmed = TrimTrailingStatementTerminators(s ?? '');
7500
7840
  if (trimmed.length === 0)
7501
7841
  continue;
7502
7842
  terminated.push(`${trimmed};`);
7503
7843
  }
7504
7844
  if (terminated.length === 0)
7505
7845
  return undefined;
7506
- return await this.LogSQLAndExecute(pool, terminated.join('\n'), description, isRecurringScript, includeBatchSeparator, batchSeparator);
7846
+ return await this.logSQLAndExecute(pool, terminated.join('\n'), description, isRecurringScript, includeBatchSeparator, batchSeparator);
7507
7847
  }
7508
7848
  }
7509
7849
  //# sourceMappingURL=manage-metadata.js.map