@memberjunction/codegen-lib 6.2.0-edge.5 → 6.2.0-edge.7

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 (105) hide show
  1. package/README.md +1 -0
  2. package/dist/Angular/angular-codegen.d.ts +12 -1
  3. package/dist/Angular/angular-codegen.d.ts.map +1 -1
  4. package/dist/Angular/angular-codegen.js +36 -1
  5. package/dist/Angular/angular-codegen.js.map +1 -1
  6. package/dist/Config/config.d.ts +301 -0
  7. package/dist/Config/config.d.ts.map +1 -1
  8. package/dist/Config/config.js +188 -84
  9. package/dist/Config/config.js.map +1 -1
  10. package/dist/Database/codeGenDatabaseProvider.d.ts +101 -4
  11. package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
  12. package/dist/Database/codeGenDatabaseProvider.js +170 -4
  13. package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
  14. package/dist/Database/manage-metadata.d.ts +379 -24
  15. package/dist/Database/manage-metadata.d.ts.map +1 -1
  16. package/dist/Database/manage-metadata.js +1021 -237
  17. package/dist/Database/manage-metadata.js.map +1 -1
  18. package/dist/Database/materializationAnalysis.d.ts +18 -4
  19. package/dist/Database/materializationAnalysis.d.ts.map +1 -1
  20. package/dist/Database/materializationAnalysis.js +113 -99
  21. package/dist/Database/materializationAnalysis.js.map +1 -1
  22. package/dist/Database/materializationBroadRender.d.ts +7 -3
  23. package/dist/Database/materializationBroadRender.d.ts.map +1 -1
  24. package/dist/Database/materializationBroadRender.js +89 -56
  25. package/dist/Database/materializationBroadRender.js.map +1 -1
  26. package/dist/Database/materializationParamClassifier.d.ts +1 -1
  27. package/dist/Database/materializationParamClassifier.js +2 -2
  28. package/dist/Database/materializationParamVerifier.d.ts +1 -1
  29. package/dist/Database/materializationParamVerifier.d.ts.map +1 -1
  30. package/dist/Database/materializationParamVerifier.js +127 -221
  31. package/dist/Database/materializationParamVerifier.js.map +1 -1
  32. package/dist/Database/materializationSqlAst.d.ts +107 -79
  33. package/dist/Database/materializationSqlAst.d.ts.map +1 -1
  34. package/dist/Database/materializationSqlAst.js +307 -134
  35. package/dist/Database/materializationSqlAst.js.map +1 -1
  36. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +25 -5
  37. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
  38. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +135 -26
  39. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
  40. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js +9 -5
  41. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js.map +1 -1
  42. package/dist/Database/providers/postgresql/metadataSupportObjects.js +289 -90
  43. package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
  44. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +48 -12
  45. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
  46. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +146 -54
  47. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
  48. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js +66 -0
  49. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js.map +1 -1
  50. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts +47 -0
  51. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts.map +1 -0
  52. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js +167 -0
  53. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js.map +1 -0
  54. package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts +31 -0
  55. package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts.map +1 -0
  56. package/dist/Database/providers/sqlserver/sqlServerScriptText.js +116 -0
  57. package/dist/Database/providers/sqlserver/sqlServerScriptText.js.map +1 -0
  58. package/dist/Database/queryRebindPass.d.ts +37 -0
  59. package/dist/Database/queryRebindPass.d.ts.map +1 -0
  60. package/dist/Database/queryRebindPass.js +110 -0
  61. package/dist/Database/queryRebindPass.js.map +1 -0
  62. package/dist/Database/schema-scope.d.ts +12 -0
  63. package/dist/Database/schema-scope.d.ts.map +1 -1
  64. package/dist/Database/schema-scope.js +15 -0
  65. package/dist/Database/schema-scope.js.map +1 -1
  66. package/dist/Database/sql.d.ts +13 -0
  67. package/dist/Database/sql.d.ts.map +1 -1
  68. package/dist/Database/sql.js +39 -8
  69. package/dist/Database/sql.js.map +1 -1
  70. package/dist/Database/sql_codegen.d.ts +212 -6
  71. package/dist/Database/sql_codegen.d.ts.map +1 -1
  72. package/dist/Database/sql_codegen.js +765 -63
  73. package/dist/Database/sql_codegen.js.map +1 -1
  74. package/dist/Misc/advanced_generation.d.ts +129 -5
  75. package/dist/Misc/advanced_generation.d.ts.map +1 -1
  76. package/dist/Misc/advanced_generation.js +212 -8
  77. package/dist/Misc/advanced_generation.js.map +1 -1
  78. package/dist/Misc/display-name-heuristics.d.ts +57 -0
  79. package/dist/Misc/display-name-heuristics.d.ts.map +1 -0
  80. package/dist/Misc/display-name-heuristics.js +97 -0
  81. package/dist/Misc/display-name-heuristics.js.map +1 -0
  82. package/dist/Misc/entity_subclasses_codegen.d.ts +31 -3
  83. package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
  84. package/dist/Misc/entity_subclasses_codegen.js +79 -17
  85. package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
  86. package/dist/Misc/remote_operations_codegen.d.ts.map +1 -1
  87. package/dist/Misc/remote_operations_codegen.js +21 -4
  88. package/dist/Misc/remote_operations_codegen.js.map +1 -1
  89. package/dist/Misc/sql_logging.d.ts +12 -0
  90. package/dist/Misc/sql_logging.d.ts.map +1 -1
  91. package/dist/Misc/sql_logging.js +21 -8
  92. package/dist/Misc/sql_logging.js.map +1 -1
  93. package/dist/Misc/system_integrity.d.ts +48 -0
  94. package/dist/Misc/system_integrity.d.ts.map +1 -1
  95. package/dist/Misc/system_integrity.js +151 -75
  96. package/dist/Misc/system_integrity.js.map +1 -1
  97. package/dist/Misc/validator-text.d.ts +17 -0
  98. package/dist/Misc/validator-text.d.ts.map +1 -1
  99. package/dist/Misc/validator-text.js +59 -0
  100. package/dist/Misc/validator-text.js.map +1 -1
  101. package/dist/runCodeGen.d.ts +37 -3
  102. package/dist/runCodeGen.d.ts.map +1 -1
  103. package/dist/runCodeGen.js +161 -51
  104. package/dist/runCodeGen.js.map +1 -1
  105. package/package.json +29 -29
@@ -1,6 +1,6 @@
1
1
  import { SQLServerDialect, PostgreSQLDialect } from '@memberjunction/sql-dialect';
2
2
  import { CodeGenDatabaseProvider, SetBaseViewExclusionsPermitted, BaseViewExclusionsPermitted } from './codeGenDatabaseProvider.js';
3
- import { AnalyzeQueryForMaterialization, DetectAggregationKeyColumns, DetectAdditiveMeasures, MATERIALIZATION_SURROGATE_COLUMN } from './materializationAnalysis.js';
3
+ import { AnalyzeQueryForMaterialization, ChooseMaterializationRefreshStrategy, DetectAggregationKeyColumns, MATERIALIZATION_SURROGATE_COLUMN } from './materializationAnalysis.js';
4
4
  import { EvaluateMaterializationDrift } from './materializationDrift.js';
5
5
  import { ClassifyQueryParameters, BuildHeldValues } from './materializationParamClassifier.js';
6
6
  import { BuildBroadRowFilterSQL } from './materializationBroadRender.js';
@@ -10,20 +10,21 @@ import { QueryParameterProcessor } from '@memberjunction/query-processor';
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, MjCoreSchema, OutputDir } from '../Config/config.js';
13
+ import { configInfo, DbPlatform, GetSettingValue, MjCoreSchema, OutputDir, ResolveAdditionalSchemaInfoPath } 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
16
  import { logError, LogMessage, logStatus, LogWarning, StartSpinner, UpdateSpinner, SucceedSpinner } from "../Misc/status_logging.js";
17
17
  import { SQLUtilityBase } from "./sql.js";
18
- import { ApplyIncludeSchemaScope } from "./schema-scope.js";
18
+ import { ApplyIncludeSchemaScope, FindUnmatchedIncludeSchemas } from "./schema-scope.js";
19
19
  import { BuildHealSchemaRoutineParams, GetAuthoredExcludeSchemas, SnapshotAuthoredExcludeSchemas } from "./heal-schema-params.js";
20
20
  import { JSON_VALIDATOR_CATEGORY_NAME, ResolveJSONCheckValidators } from "./json-check-validators.js";
21
21
  import { AdvancedGeneration, IsPlausibleEntityName } from "../Misc/advanced_generation.js";
22
+ import { AssessDisplayNameOpacity } from "../Misc/display-name-heuristics.js";
22
23
  import { CodeGenReporter } from "../Misc/codegen-reporter.js";
23
24
  import { ApplySearchableFieldsCap, DefaultPredicateFor, EntityLevelEnableBlockedReason, IsNarrativeFieldName, MAX_SEARCHABLE_FIELDS_PER_ENTITY, NAME_LIKE_FIELD_NAMES, NormalizePredicate, NormalizeSmartFieldResultShape, } from "./search-guardrails.js";
24
25
  import { MapExternalNativeTypeToMJ } from "../Misc/externalTypeMapping.js";
25
26
  import { SQLParser } from "@memberjunction/sql-parser";
26
- import { createDisplayName, EscapeSQLString, generatePluralName, IndexByUUID, MJGlobal, NormalizeUUID, ResolveSingleEntityResourceTarget, stripTrailingChars, UUIDsEqual } from "@memberjunction/global";
27
+ import { createDisplayName, EscapeSQLString, generatePluralName, IndexByUUID, MJGlobal, NormalizeUUID, ResolveSingleEntityResourceTarget, stripTrailingChars, UUIDMap, UUIDsEqual } from "@memberjunction/global";
27
28
  import { v4 as uuidv4, v5 as uuidv5 } from 'uuid';
28
29
  import * as fs from 'fs';
29
30
  import path from 'path';
@@ -65,6 +66,7 @@ export class ManageMetadataBase {
65
66
  * references to it on this so codegen doesn't throw on a DB lacking the materialization schema. Cached per run.
66
67
  */
67
68
  this._materializedResultTableExists = null;
69
+ this._staleRelationshipsRemoved = 0;
68
70
  /**
69
71
  * Whether this database's `spDeleteUnneededEntityFields` accepts a `ProtectedFieldNames`
70
72
  * parameter. Cached for the run (a routine signature cannot change mid-run).
@@ -106,6 +108,7 @@ export class ManageMetadataBase {
106
108
  * so a new gate has no reason to hand-roll a fourth copy of the same query and its own cache field.
107
109
  */
108
110
  this._coreSchemaColumnExists = new Map();
111
+ this._inheritedComputedNames = new UUIDMap();
109
112
  }
110
113
  /**
111
114
  * Returns the CodeGenDatabaseProvider for the current database platform.
@@ -332,8 +335,34 @@ export class ManageMetadataBase {
332
335
  const key = this.fieldKey(entityID, name);
333
336
  if (key) {
334
337
  this._newFieldSet.add(key);
338
+ this.RegisterFieldShapeChange({ EntityID: entityID });
335
339
  }
336
340
  }
341
+ static { this._fieldShapeChangedEntityIDs = new Set(); }
342
+ static { this._fieldShapeChangedEntityNames = new Set(); }
343
+ /**
344
+ * Records that an entity's columns changed shape during this run: a field was added or
345
+ * dropped, or its type, length, precision, scale or nullability changed. The saved queries
346
+ * that read such an entity are re-bound after the run's field sync. Give the entity by ID or
347
+ * by name.
348
+ */
349
+ static RegisterFieldShapeChange(entity) {
350
+ const id = (entity.EntityID ?? '').trim().toLowerCase();
351
+ const name = (entity.EntityName ?? '').trim();
352
+ if (id)
353
+ this._fieldShapeChangedEntityIDs.add(id);
354
+ if (name)
355
+ this._fieldShapeChangedEntityNames.add(name);
356
+ }
357
+ /** The entities whose fields changed shape during this run, by ID (lower-cased) and by name. */
358
+ static get FieldShapeChangedEntities() {
359
+ return { IDs: [...this._fieldShapeChangedEntityIDs], Names: [...this._fieldShapeChangedEntityNames] };
360
+ }
361
+ /** Forgets the entities {@link RegisterFieldShapeChange} recorded. */
362
+ static ClearFieldShapeChanges() {
363
+ this._fieldShapeChangedEntityIDs.clear();
364
+ this._fieldShapeChangedEntityNames.clear();
365
+ }
337
366
  /** @deprecated Use {@link RegisterNewField}. */
338
367
  static registerNewField(entityID, name) {
339
368
  return this.RegisterNewField(entityID, name);
@@ -546,10 +575,9 @@ export class ManageMetadataBase {
546
575
  * {@link invalidateSoftPKFKConfigCache} at the start of each run so a rewritten file is picked up.
547
576
  */
548
577
  static GetSoftPKFKConfig() {
549
- // Return cached config if path hasn't changed
550
- const configPath = configInfo.additionalSchemaInfo
551
- ? path.join(currentWorkingDirectory, configInfo.additionalSchemaInfo)
552
- : '';
578
+ // Return cached config if path hasn't changed. The path resolves against the mj.config
579
+ // file's directory (or the RSU env override), never the process cwd (#5858).
580
+ const configPath = ResolveAdditionalSchemaInfoPath() ?? '';
553
581
  if (this._softPKFKConfigCache !== null && this._softPKFKConfigPath === configPath) {
554
582
  return this._softPKFKConfigCache;
555
583
  }
@@ -1672,12 +1700,7 @@ export class ManageMetadataBase {
1672
1700
  // Joins/multi-table sources can't be localized by one watermark → keep FullRebuild (§10 bias).
1673
1701
  // Among eligible ones, a PURELY ADDITIVE aggregation (only SUM/COUNT) uses the MERGE-upsert
1674
1702
  // 'Incremental' path (in-place, no row churn); non-additive uses 'DirtyGroupRecompute' (delete+insert).
1675
- const isKeyedSingleSource = isKeyed && !!detectSQL && SQLParser.ExtractTableRefs(detectSQL, matDialect).length === 1;
1676
- const refreshStrategy = !isKeyedSingleSource
1677
- ? 'FullRebuild'
1678
- : DetectAdditiveMeasures(detectSQL)
1679
- ? 'Incremental'
1680
- : 'DirtyGroupRecompute';
1703
+ const refreshStrategy = ChooseMaterializationRefreshStrategy({ sql: detectSQL, dialect: matDialect, isKeyed });
1681
1704
  // RLS downgrade gate (§6.2, ships day one) — a materialized query entity does NOT inherit its
1682
1705
  // source entities' row-level security. Refuse to materialize when RLS-safety cannot be proven, to
1683
1706
  // prevent a silent privilege escalation. Asymmetric risk (§10): over-restriction is harmless; the
@@ -2108,32 +2131,15 @@ export class ManageMetadataBase {
2108
2131
  // compiled into excludeSchemas. Heal EXEC statements use that original list plus
2109
2132
  // @IncludedSchemaNames — never the sibling snapshot of this machine's database.
2110
2133
  SnapshotAuthoredExcludeSchemas(configInfo.excludeSchemas);
2111
- // Resolve the opt-in `includeSchemas` positive scope into excludeSchemas, BEFORE the exclude
2112
- // snapshot below and before createNewEntities() runs. The universe is queried from the DATABASE
2113
- // rather than taken from loaded metadata on purpose: createNewEntities() discovers tables with no
2114
- // EntityID straight from the database, so a schema MJ has never seen — the exact case an include
2115
- // list exists to protect against, e.g. a client's own schemas in a deployed instance — is absent
2116
- // from Metadata.Entities and would otherwise be adopted on the first run (and then excluded on
2117
- // every run after, orphaning its entity records). No-op when includeSchemas is unset.
2118
- if (configInfo.includeSchemas && configInfo.includeSchemas.length > 0) {
2119
- try {
2120
- const schemaSQL = `SELECT DISTINCT ${this.qi('SchemaName')} FROM ${this.qs(MjCoreSchema(), 'vwSQLTablesAndEntities')}`;
2121
- const schemaResult = await this.runQuery(pool, schemaSQL);
2122
- const allSchemas = (schemaResult.recordset ?? [])
2123
- .map((r) => r.SchemaName)
2124
- .filter((s) => !!s);
2125
- const newlyExcluded = ApplyIncludeSchemaScope(allSchemas, configInfo);
2126
- logStatus(` Applied includeSchemas scope [${configInfo.includeSchemas.join(', ')}] — excluded ${newlyExcluded.length} other schema(s) present in the database`);
2127
- }
2128
- catch (e) {
2129
- // Proceeding would let CodeGen traverse schemas the include list was meant to keep it off,
2130
- // which can create entity metadata for another app's (or a client's) tables. Fail instead.
2131
- logError(` Error resolving includeSchemas scope: ${e instanceof Error ? e.message : e}`);
2132
- return false;
2133
- }
2134
+ // Resolve the opt-in `includeSchemas` scope BEFORE the exclude snapshot below and before
2135
+ // createNewEntities() runs. An entry that matches no schema fails the step (#3384), after the
2136
+ // scope is applied, so the rest of the run still uses the entries that do match.
2137
+ const includeScope = await this.ResolveIncludeSchemaScope(pool);
2138
+ if (includeScope === null) {
2139
+ return false;
2134
2140
  }
2135
2141
  const excludeSchemas = configInfo.excludeSchemas ? [...configInfo.excludeSchemas] : [];
2136
- let bSuccess = true;
2142
+ let bSuccess = includeScope;
2137
2143
  let start = new Date();
2138
2144
  // Very early FK check - before any operations
2139
2145
  // Load SchemaInfo records early so that EntityNamePrefix/Suffix rules from the
@@ -2182,6 +2188,12 @@ export class ManageMetadataBase {
2182
2188
  // failure for this entire function
2183
2189
  }
2184
2190
  logStatus(` > Recompiled base views in ${(new Date().getTime() - start.getTime()) / 1000} seconds`);
2191
+ // Keep pre-6.1 hierarchies working: opt in the self-referencing FKs that already had a Root*
2192
+ // column before the field sync and view regeneration below drop it (#5976).
2193
+ if (!await this.seedLegacyHierarchyConfiguration(pool, excludeSchemas)) {
2194
+ logError(' Error seeding hierarchy configuration for legacy self-referencing foreign keys');
2195
+ bSuccess = false;
2196
+ }
2185
2197
  start = new Date();
2186
2198
  logStatus(' Managing entity fields...');
2187
2199
  // note that we skip Advanced Generation here because we do it again later when the manageSQLScriptsAndExecution occurs in SQLCodeGen class
@@ -2306,6 +2318,148 @@ export class ManageMetadataBase {
2306
2318
  await this.checkEntityFieldSequenceIntegrity(pool, excludeSchemas);
2307
2319
  return bSuccess;
2308
2320
  }
2321
+ /**
2322
+ * Resolves the opt-in `includeSchemas` scope into `configInfo.excludeSchemas` (#3384).
2323
+ * @returns true when every entry matched a database schema (or none are set), false when an entry
2324
+ * matched none (the scope is still applied), null when the scope could not be resolved.
2325
+ */
2326
+ async ResolveIncludeSchemaScope(pool) {
2327
+ // ManageMetadata calls this before its exclude snapshot and before createNewEntities() runs.
2328
+ // The universe is queried from the DATABASE
2329
+ // rather than taken from loaded metadata on purpose: createNewEntities() discovers tables with no
2330
+ // EntityID straight from the database, so a schema MJ has never seen — the exact case an include
2331
+ // list exists to protect against, e.g. a client's own schemas in a deployed instance — is absent
2332
+ // from Metadata.Entities and would otherwise be adopted on the first run (and then excluded on
2333
+ // every run after, orphaning its entity records). No-op when includeSchemas is unset.
2334
+ if (!configInfo.includeSchemas || configInfo.includeSchemas.length === 0) {
2335
+ return true;
2336
+ }
2337
+ let allMatched = true;
2338
+ try {
2339
+ const schemaSQL = `SELECT DISTINCT ${this.qi('SchemaName')} FROM ${this.qs(MjCoreSchema(), 'vwSQLTablesAndEntities')}`;
2340
+ const schemaResult = await this.runQuery(pool, schemaSQL);
2341
+ const allSchemas = (schemaResult.recordset ?? [])
2342
+ .map((r) => r.SchemaName)
2343
+ .filter((s) => !!s);
2344
+ const unmatched = FindUnmatchedIncludeSchemas(allSchemas, configInfo.includeSchemas);
2345
+ if (unmatched.length > 0) {
2346
+ allMatched = false;
2347
+ logError(` includeSchemas entr${unmatched.length === 1 ? 'y' : 'ies'} [${unmatched.join(', ')}] match no schema in the database; check for a typo or a dropped schema`);
2348
+ }
2349
+ const newlyExcluded = ApplyIncludeSchemaScope(allSchemas, configInfo);
2350
+ logStatus(` Applied includeSchemas scope [${configInfo.includeSchemas.join(', ')}] — excluded ${newlyExcluded.length} other schema(s) present in the database`);
2351
+ }
2352
+ catch (e) {
2353
+ // Proceeding would let CodeGen traverse schemas the include list was meant to keep it off,
2354
+ // which can create entity metadata for another app's (or a client's) tables. Fail instead.
2355
+ logError(` Error resolving includeSchemas scope: ${e instanceof Error ? e.message : e}`);
2356
+ return null;
2357
+ }
2358
+ return allMatched;
2359
+ }
2360
+ /**
2361
+ * One-time upgrade step for #5976. Before 6.1, CodeGen projected a `Root<Field>` column for every
2362
+ * self-referencing foreign key; 6.1 made that opt-in through `Configuration.Hierarchy.IsHierarchy`.
2363
+ * An application schema upgraded without seeding that flag keeps its virtual `Root<Field>`
2364
+ * EntityField while the regenerated view drops the column, and every read of the entity fails.
2365
+ *
2366
+ * This sets `{"Hierarchy":{"IsHierarchy":true}}` (merged into any existing Configuration) on every
2367
+ * non-virtual, non-key self-referencing FK whose Configuration has no `Hierarchy` key, when the
2368
+ * entity still has a virtual `Root<Field>` EntityField or the database still has the field's
2369
+ * `fn<Table><Field>_GetRootID` function. Each seeded field is logged as a warning so the owner can
2370
+ * opt out deliberately. The core schema is skipped: its hierarchy fields are seeded by metadata,
2371
+ * and its baseline-shipped root functions exist for fields that were deliberately left out.
2372
+ */
2373
+ async seedLegacyHierarchyConfiguration(pool, excludeSchemas) {
2374
+ try {
2375
+ const q = (n) => this.qi(n);
2376
+ const candidateSQL = `SELECT ef.${q('ID')} AS ${q('ID')}, ef.${q('EntityID')} AS ${q('EntityID')}, ef.${q('Name')} AS ${q('Name')},
2377
+ ef.${q('Configuration')} AS ${q('Configuration')}, e.${q('Name')} AS ${q('EntityName')},
2378
+ e.${q('SchemaName')} AS ${q('SchemaName')}, e.${q('BaseTable')} AS ${q('BaseTable')}
2379
+ FROM ${this.qs(MjCoreSchema(), 'EntityField')} ef
2380
+ INNER JOIN ${this.qs(MjCoreSchema(), 'Entity')} e ON e.${q('ID')} = ef.${q('EntityID')}
2381
+ WHERE ef.${q('IsVirtual')} = ${this.boolLit(false)}
2382
+ AND ef.${q('IsPrimaryKey')} = ${this.boolLit(false)}
2383
+ AND ef.${q('RelatedEntityID')} = ef.${q('EntityID')}`;
2384
+ const coreSchema = MjCoreSchema().trim().toLowerCase();
2385
+ const candidates = (await this.runQuery(pool, candidateSQL)).recordset
2386
+ .filter(r => !this.isSchemaExcluded(r.SchemaName, excludeSchemas) && r.SchemaName?.trim().toLowerCase() !== coreSchema);
2387
+ if (candidates.length === 0) {
2388
+ return true;
2389
+ }
2390
+ const rootFieldSQL = `SELECT ${q('EntityID')}, ${q('Name')} FROM ${this.qs(MjCoreSchema(), 'EntityField')}
2391
+ WHERE ${q('IsVirtual')} = ${this.boolLit(true)} AND ${q('Name')} LIKE 'Root%'`;
2392
+ const rootFields = (await this.runQuery(pool, rootFieldSQL)).recordset;
2393
+ const functionSQL = `SELECT ROUTINE_SCHEMA AS "RoutineSchema", ROUTINE_NAME AS "RoutineName"
2394
+ FROM INFORMATION_SCHEMA.ROUTINES
2395
+ WHERE ROUTINE_TYPE = 'FUNCTION' AND LOWER(ROUTINE_NAME) LIKE '%root%id'`;
2396
+ const functions = (await this.runQuery(pool, functionSQL)).recordset;
2397
+ const seeds = this.planLegacyHierarchySeeds(candidates, rootFields, functions);
2398
+ for (const seed of seeds) {
2399
+ const guard = seed.Row.Configuration === null || seed.Row.Configuration.trim().length === 0
2400
+ ? `(${q('Configuration')} IS NULL OR ${q('Configuration')} = '')`
2401
+ : `${q('Configuration')} = '${EscapeSQLString(seed.Row.Configuration)}'`;
2402
+ const sql = `UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
2403
+ SET ${q('Configuration')} = '${EscapeSQLString(seed.Configuration)}'
2404
+ WHERE ${q('ID')} = '${seed.Row.ID}' AND ${guard}`;
2405
+ await this.logSQLAndExecute(pool, sql, `Seed Hierarchy.IsHierarchy on legacy self-referencing FK ${seed.Row.EntityName}.${seed.Row.Name}`);
2406
+ LogWarning(` Seeded Configuration.Hierarchy.IsHierarchy = true on ${seed.Row.EntityName}.${seed.Row.Name} (${seed.Reason}). ` +
2407
+ `This keeps the Root${seed.Row.Name} column it had before 6.1; set IsHierarchy to false to opt out.`);
2408
+ }
2409
+ return true;
2410
+ }
2411
+ catch (e) {
2412
+ logError(` Error seeding legacy hierarchy configuration: ${e instanceof Error ? e.message : String(e)}`);
2413
+ return false;
2414
+ }
2415
+ }
2416
+ /**
2417
+ * Pure decision step of {@link seedLegacyHierarchyConfiguration}: which candidate fields to seed,
2418
+ * why, and the Configuration JSON to write. Fields whose Configuration already has a `Hierarchy`
2419
+ * key are left alone, as are fields whose Configuration is not valid JSON (with a warning).
2420
+ */
2421
+ planLegacyHierarchySeeds(candidates, rootFields, functions) {
2422
+ // Function names compare with case and underscores removed, which matches both the
2423
+ // `fn<Table><Field>_GetRootID` form and PostgreSQL's snake_case `fn_<table>_<field>_get_root_id`.
2424
+ const squash = (v) => v.toLowerCase().replace(/_/g, '');
2425
+ const functionKeys = new Set(functions.map(f => `${String(f.RoutineSchema).trim().toLowerCase()}.${squash(String(f.RoutineName))}`));
2426
+ const rootFieldKeys = new Set(rootFields.map(f => `${NormalizeUUID(String(f.EntityID))}|${String(f.Name).toLowerCase()}`));
2427
+ const seeds = [];
2428
+ for (const row of candidates) {
2429
+ let existing = {};
2430
+ const raw = row.Configuration?.trim() ?? '';
2431
+ if (raw.length > 0) {
2432
+ let parsed;
2433
+ try {
2434
+ parsed = JSON.parse(raw);
2435
+ }
2436
+ catch {
2437
+ LogWarning(` Not seeding hierarchy on ${row.EntityName}.${row.Name}: its Configuration is not valid JSON`);
2438
+ continue;
2439
+ }
2440
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
2441
+ LogWarning(` Not seeding hierarchy on ${row.EntityName}.${row.Name}: its Configuration is not a JSON object`);
2442
+ continue;
2443
+ }
2444
+ existing = parsed;
2445
+ if ('Hierarchy' in existing) {
2446
+ continue; // an explicit setting, opt-in or opt-out, always wins
2447
+ }
2448
+ }
2449
+ const hasRootField = rootFieldKeys.has(`${NormalizeUUID(String(row.EntityID))}|root${row.Name.toLowerCase()}`);
2450
+ const functionKey = `${String(row.SchemaName).trim().toLowerCase()}.${squash(`fn${row.BaseTable}${row.Name}GetRootID`)}`;
2451
+ const hasRootFunction = functionKeys.has(functionKey);
2452
+ if (!hasRootField && !hasRootFunction) {
2453
+ continue;
2454
+ }
2455
+ seeds.push({
2456
+ Row: row,
2457
+ Reason: hasRootField ? `virtual Root${row.Name} field present` : `root ID function for ${row.Name} present`,
2458
+ Configuration: JSON.stringify({ ...existing, Hierarchy: { IsHierarchy: true } }),
2459
+ });
2460
+ }
2461
+ return seeds;
2462
+ }
2309
2463
  /** @deprecated Use {@link ManageMetadata}. */
2310
2464
  async manageMetadata(pool, currentUser) {
2311
2465
  return this.ManageMetadata(pool, currentUser);
@@ -3091,8 +3245,10 @@ export class ManageMetadataBase {
3091
3245
  if (!field) {
3092
3246
  continue;
3093
3247
  }
3094
- // Skip if field already has a FK set (config-defined takes precedence)
3095
- if (field.RelatedEntityID) {
3248
+ // Skip if field already has a FK set (config-defined takes precedence), or if its
3249
+ // relationship is pinned: AutoUpdateRelatedEntityInfo = 0 means someone set or cleared it by
3250
+ // hand, and the LLM must not write it back on the next run (#3160).
3251
+ if (!ManageMetadataBase.LLMForeignKeyMayApply(field)) {
3096
3252
  continue;
3097
3253
  }
3098
3254
  // Look up the related entity by name
@@ -3101,11 +3257,14 @@ export class ManageMetadataBase {
3101
3257
  logStatus(` ⚠️ LLM FK: related entity '${fk.relatedEntityName}' not found for ${entity.Name}.${fk.fieldName}`);
3102
3258
  continue;
3103
3259
  }
3260
+ // The AutoUpdateRelatedEntityInfo predicate repeats the check above in the statement itself,
3261
+ // so the captured SQL cannot overwrite a pin set on another host before it is replayed there.
3104
3262
  sqlStatements.push(`UPDATE ${this.qs(schema, 'EntityField')}
3105
3263
  SET RelatedEntityID='${relatedEntity.ID}',
3106
- RelatedEntityFieldName='${fk.relatedFieldName}',
3107
- IsSoftForeignKey=1
3108
- WHERE EntityID='${entity.ID}' AND Name='${field.Name}'`);
3264
+ RelatedEntityFieldName='${EscapeSQLString(fk.relatedFieldName)}',
3265
+ IsSoftForeignKey=${this.boolLit(true)}
3266
+ WHERE EntityID='${entity.ID}' AND Name='${EscapeSQLString(field.Name)}'
3267
+ AND ${this.qi('AutoUpdateRelatedEntityInfo')} = ${this.boolLit(true)}`);
3109
3268
  logStatus(` ✓ Set FK for ${entity.Name}.${field.Name} → ${fk.relatedEntityName}.${fk.relatedFieldName} (${fk.confidence}, LLM)`);
3110
3269
  }
3111
3270
  if (sqlStatements.length === 0) {
@@ -3114,6 +3273,18 @@ export class ManageMetadataBase {
3114
3273
  await this.logSQLBatchAndExecute(pool, sqlStatements, `Set LLM-identified FKs for ${entity.Name}`);
3115
3274
  return true;
3116
3275
  }
3276
+ /**
3277
+ * True when an LLM-identified foreign key may be written to the field: the field has no
3278
+ * relationship yet and its relationship is not pinned (AutoUpdateRelatedEntityInfo = 0).
3279
+ */
3280
+ static LLMForeignKeyMayApply(field) {
3281
+ if (field.RelatedEntityID) {
3282
+ return false;
3283
+ }
3284
+ // A raw driver row can carry the bit as a number or string rather than a boolean.
3285
+ const pinned = field.AutoUpdateRelatedEntityInfo;
3286
+ return !(pinned === false || pinned === 0 || pinned === '0' || pinned === 'false');
3287
+ }
3117
3288
  /**
3118
3289
  * Applies LLM-generated field descriptions to entity fields that lack descriptions.
3119
3290
  * All SQL updates are batched into a single execution for performance.
@@ -3223,19 +3394,30 @@ export class ManageMetadataBase {
3223
3394
  * that mirror the parent entity's base table fields (excluding PKs, timestamps, and virtual fields).
3224
3395
  * Runs collision detection to prevent child table columns from shadowing parent fields.
3225
3396
  */
3226
- async manageParentEntityFields(pool) {
3397
+ async manageParentEntityFields(pool, excludeSchemas = []) {
3227
3398
  let bSuccess = true;
3228
- let anyUpdates = false;
3399
+ const updatedChildNames = [];
3400
+ // `excludeSchemas` is the compiled scope: the authored exclude list plus every schema the
3401
+ // includeSchemas allow-list left out (ApplyIncludeSchemaScope). Only children in scope are
3402
+ // synced. Without this an Open App publisher run processed every IS-A child in the database
3403
+ // and wrote INSERTs for sibling apps' children into its own migration capture (#4879).
3229
3404
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
3230
- const childEntities = md.Entities.filter(e => e.IsChildType);
3405
+ const allChildEntities = md.Entities.filter(e => e.IsChildType);
3406
+ const childEntities = allChildEntities.filter(e => !this.isSchemaExcluded(e.SchemaName, excludeSchemas));
3407
+ const outOfScope = allChildEntities.length - childEntities.length;
3231
3408
  if (childEntities.length === 0) {
3409
+ if (outOfScope > 0) {
3410
+ logStatus(` Skipping IS-A parent fields: all ${outOfScope} child entit${outOfScope === 1 ? 'y is' : 'ies are'} in excluded schemas`);
3411
+ }
3232
3412
  return { success: true, anyUpdates: false };
3233
3413
  }
3234
- logStatus(` Processing IS-A parent fields for ${childEntities.length} child entit${childEntities.length === 1 ? 'y' : 'ies'}...`);
3414
+ logStatus(` Processing IS-A parent fields for ${childEntities.length} child entit${childEntities.length === 1 ? 'y' : 'ies'}${outOfScope > 0 ? ` (${outOfScope} in excluded schemas skipped)` : ''}...`);
3235
3415
  for (const childEntity of childEntities) {
3236
3416
  try {
3237
3417
  const { success, updated } = await this.manageSingleEntityParentFields(pool, childEntity);
3238
- anyUpdates = anyUpdates || updated;
3418
+ if (updated) {
3419
+ updatedChildNames.push(childEntity.Name);
3420
+ }
3239
3421
  if (!success) {
3240
3422
  logError(` Error managing IS-A parent fields for ${childEntity.Name}`);
3241
3423
  bSuccess = false;
@@ -3246,7 +3428,27 @@ export class ManageMetadataBase {
3246
3428
  bSuccess = false;
3247
3429
  }
3248
3430
  }
3249
- return { success: bSuccess, anyUpdates };
3431
+ // A child whose virtual EntityField set changed has a different TypeScript surface (entity
3432
+ // subclass, zod schema, GraphQL types). The rows were written directly above, so nothing
3433
+ // else marks the entity — and the file emit only rebuilds schemas holding a new or modified
3434
+ // entity (fileEmit.dirtySchemaOnly). Mark it here or the run reports success and ships a
3435
+ // class that lacks the field the metadata declares, until someone runs `--skipdb` (#5961).
3436
+ if (updatedChildNames.length > 0) {
3437
+ ManageMetadataBase.AddNewEntitiesToModifiedList(updatedChildNames);
3438
+ }
3439
+ return { success: bSuccess, anyUpdates: updatedChildNames.length > 0 };
3440
+ }
3441
+ /**
3442
+ * True when `schemaName` is on the compiled exclude list. Schema names are compared
3443
+ * case-insensitively: SQL Server resolves them that way, and PostgreSQL folds unquoted
3444
+ * identifiers, so the list and the metadata can legitimately differ in case.
3445
+ */
3446
+ isSchemaExcluded(schemaName, excludeSchemas) {
3447
+ if (!schemaName || excludeSchemas.length === 0) {
3448
+ return false;
3449
+ }
3450
+ const target = schemaName.trim().toLowerCase();
3451
+ return excludeSchemas.some(s => s.trim().toLowerCase() === target);
3250
3452
  }
3251
3453
  /**
3252
3454
  * Creates/updates virtual EntityField records for a single child entity's parent fields.
@@ -3275,20 +3477,39 @@ export class ManageMetadataBase {
3275
3477
  // Identifiers are quoted via qi(): __mj.EntityField's columns are mixed-case, and an
3276
3478
  // unquoted reference folds to lower case on PostgreSQL — `column "length" does not exist`.
3277
3479
  // SQL Server's case-insensitive resolution hid this for as long as IS-A ran only there.
3278
- 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')}
3480
+ 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')},
3481
+ ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityFieldName')}, ${this.qi('RelatedEntityDisplayType')},
3482
+ ${this.qi('IncludeRelatedEntityNameFieldInBaseView')}, ${this.qi('AutoUpdateRelatedEntityInfo')}
3279
3483
  FROM ${this.qs(MjCoreSchema(), 'EntityField')}
3280
3484
  WHERE ${this.qi('EntityID')} = @EntityID AND ${this.qi('Name')} = @FieldName`, { 'EntityID': childEntity.ID, 'FieldName': parentField.Name });
3485
+ // The inherited column reaches the child through its view, so there is no FK constraint
3486
+ // on the child table to derive the relationship from. It is copied from the parent's
3487
+ // field instead (#4569), or the generated form renders a plain text input that writes ''
3488
+ // into a uniqueidentifier column.
3489
+ const related = this.inheritedRelatedEntityInfo(parentField);
3281
3490
  if (existsResult.recordset.length > 0) {
3282
3491
  // Field already exists — update it to ensure it's marked as a virtual IS-A field
3283
3492
  const existingRow = existsResult.recordset[0];
3493
+ // AutoUpdateRelatedEntityInfo = 0 pins a hand-set relationship; leave it alone. The
3494
+ // related-name join is forced off either way: an inherited row never gets its own
3495
+ // name-field join in the child's view.
3496
+ const syncRelated = this.isTruthyBit(existingRow.AutoUpdateRelatedEntityInfo ?? true);
3284
3497
  const needsUpdate = !existingRow.IsVirtual ||
3285
3498
  existingRow.Type?.trim().toLowerCase() !== parentField.Type.trim().toLowerCase() ||
3286
3499
  existingRow.Length !== parentField.Length ||
3287
3500
  existingRow.Precision !== parentField.Precision ||
3288
3501
  existingRow.Scale !== parentField.Scale ||
3289
3502
  existingRow.AllowsNull !== parentField.AllowsNull ||
3290
- !existingRow.AllowUpdateAPI;
3503
+ !existingRow.AllowUpdateAPI ||
3504
+ this.isTruthyBit(existingRow.IncludeRelatedEntityNameFieldInBaseView ?? false) ||
3505
+ (syncRelated && this.inheritedRelatedEntityInfoDiffers(existingRow, related));
3291
3506
  if (needsUpdate) {
3507
+ const relatedSet = syncRelated
3508
+ ? `,
3509
+ ${this.qi('RelatedEntityID')}=${related.RelatedEntityID ? `'${related.RelatedEntityID}'` : 'NULL'},
3510
+ ${this.qi('RelatedEntityFieldName')}=${this.sqlStringOrNull(related.RelatedEntityFieldName)},
3511
+ ${this.qi('RelatedEntityDisplayType')}='${EscapeSQLString(related.RelatedEntityDisplayType)}'`
3512
+ : '';
3292
3513
  const sqlUpdate = `UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
3293
3514
  SET ${this.qi('IsVirtual')}=${this.boolLit(true)},
3294
3515
  ${this.qi('Type')}='${parentField.Type}',
@@ -3296,7 +3517,8 @@ export class ManageMetadataBase {
3296
3517
  ${this.qi('Precision')}=${parentField.Precision},
3297
3518
  ${this.qi('Scale')}=${parentField.Scale},
3298
3519
  ${this.qi('AllowsNull')}=${this.boolLit(parentField.AllowsNull)},
3299
- ${this.qi('AllowUpdateAPI')}=${this.boolLit(true)}
3520
+ ${this.qi('AllowUpdateAPI')}=${this.boolLit(true)},
3521
+ ${this.qi('IncludeRelatedEntityNameFieldInBaseView')}=${this.boolLit(false)}${relatedSet}
3300
3522
  WHERE ${this.qi('ID')}='${existingRow.ID}'`;
3301
3523
  await this.logSQLAndExecute(pool, sqlUpdate, `Update IS-A parent field ${parentField.Name} on ${childEntity.Name}`);
3302
3524
  bUpdated = true;
@@ -3308,18 +3530,31 @@ export class ManageMetadataBase {
3308
3530
  // Apply-time Sequence (see applyTimeEntityFieldSequenceSQL); reordered by
3309
3531
  // updateExistingEntityFieldsFromSchema afterwards.
3310
3532
  const q = (n) => this.qi(n);
3311
- const sqlInsert = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityField')} (
3533
+ // The INSERT is captured into the run's migration SQL and replayed on other hosts, so it
3534
+ // carries the same existence guard as the schema-field inserts in createNewEntityFieldsFromSchema.
3535
+ // Unguarded, a replay on a host where the field already exists (a second app captured on the
3536
+ // same chain, or the owning app shipping the field itself) fails on
3537
+ // UQ_EntityField_EntityID_Name and stops the install (#4879).
3538
+ const conflictCheck = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntityField')} WHERE ${q('ID')} = '${newFieldID}' OR (${q('EntityID')} = '${childEntity.ID}' AND ${q('Name')} = '${parentField.Name}')`;
3539
+ const guard = this.dbProvider.wrapInsertWithConflictGuard(conflictCheck);
3540
+ const sqlInsert = `${guard.prefix}
3541
+ INSERT INTO ${this.qs(MjCoreSchema(), 'EntityField')} (
3312
3542
  ${q('ID')}, ${q('EntityID')}, ${q('Name')}, ${q('Type')}, ${q('AllowsNull')},
3313
3543
  ${q('Length')}, ${q('Precision')}, ${q('Scale')},
3314
3544
  ${q('Sequence')}, ${q('IsVirtual')}, ${q('AllowUpdateAPI')},
3315
3545
  ${q('IsPrimaryKey')}, ${q('IsUnique')},
3546
+ ${q('RelatedEntityID')}, ${q('RelatedEntityFieldName')}, ${q('RelatedEntityDisplayType')},
3547
+ ${q('IncludeRelatedEntityNameFieldInBaseView')},
3316
3548
  ${q('__mj_CreatedAt')}, ${q('__mj_UpdatedAt')})
3317
3549
  VALUES (
3318
3550
  '${newFieldID}', '${childEntity.ID}', '${parentField.Name}',
3319
3551
  '${parentField.Type}', ${this.boolLit(parentField.AllowsNull)},
3320
3552
  ${parentField.Length}, ${parentField.Precision}, ${parentField.Scale},
3321
3553
  ${this.applyTimeEntityFieldSequenceSQL(childEntity.ID)}, ${this.boolLit(true)}, ${this.boolLit(true)}, ${this.boolLit(false)}, ${this.boolLit(false)},
3322
- ${this.utcNow()}, ${this.utcNow()})`;
3554
+ ${related.RelatedEntityID ? `'${related.RelatedEntityID}'` : 'NULL'}, ${this.sqlStringOrNull(related.RelatedEntityFieldName)}, '${EscapeSQLString(related.RelatedEntityDisplayType)}',
3555
+ ${this.boolLit(false)},
3556
+ ${this.utcNow()}, ${this.utcNow()})
3557
+ ${guard.suffix}`;
3323
3558
  await this.logSQLAndExecute(pool, sqlInsert, `Create IS-A parent field ${parentField.Name} on ${childEntity.Name}`);
3324
3559
  ManageMetadataBase.registerNewField(childEntity.ID, parentField.Name);
3325
3560
  bUpdated = true;
@@ -3342,6 +3577,35 @@ export class ManageMetadataBase {
3342
3577
  }
3343
3578
  return { success: true, updated: bUpdated };
3344
3579
  }
3580
+ /**
3581
+ * The relationship an IS-A inherited field carries, copied from the parent's field (#4569).
3582
+ * RelatedEntityNameFieldMap is left NULL and IncludeRelatedEntityNameFieldInBaseView is written
3583
+ * as 0, so the child's view gains no name-field join for the inherited column.
3584
+ */
3585
+ inheritedRelatedEntityInfo(parentField) {
3586
+ return {
3587
+ RelatedEntityID: parentField.RelatedEntityID ? parentField.RelatedEntityID : null,
3588
+ RelatedEntityFieldName: parentField.RelatedEntityID && parentField.RelatedEntityFieldName ? parentField.RelatedEntityFieldName : null,
3589
+ RelatedEntityDisplayType: parentField.RelatedEntityDisplayType || 'Search',
3590
+ };
3591
+ }
3592
+ /** True when the stored row's relationship columns differ from what the parent field implies. */
3593
+ inheritedRelatedEntityInfoDiffers(existingRow, related) {
3594
+ const currentID = existingRow.RelatedEntityID ?? null;
3595
+ const idDiffers = (currentID === null) !== (related.RelatedEntityID === null) ||
3596
+ (currentID !== null && related.RelatedEntityID !== null && !UUIDsEqual(currentID, related.RelatedEntityID));
3597
+ return idDiffers ||
3598
+ (existingRow.RelatedEntityFieldName ?? null) !== related.RelatedEntityFieldName ||
3599
+ (existingRow.RelatedEntityDisplayType ?? 'Search') !== related.RelatedEntityDisplayType;
3600
+ }
3601
+ /** Reads a bit column that may come back as boolean, number or string depending on the driver. */
3602
+ isTruthyBit(value) {
3603
+ return value === true || value === 1 || value === '1' || value === 'true';
3604
+ }
3605
+ /** A SQL string literal, or NULL for a null/empty value. */
3606
+ sqlStringOrNull(value) {
3607
+ return value ? `'${EscapeSQLString(value)}'` : 'NULL';
3608
+ }
3345
3609
  /**
3346
3610
  * Checks if an existing virtual parent field record needs to be updated to match the parent field.
3347
3611
  */
@@ -3443,8 +3707,8 @@ export class ManageMetadataBase {
3443
3707
  // NOTE: Stale relationship cleanup is intentionally NOT done here because this
3444
3708
  // method runs BEFORE deleteUnneededEntityFields(). Stale EntityField records
3445
3709
  // (for dropped columns) still exist at this point and would prevent detection
3446
- // of stale relationships. The cleanup is handled by cleanupStaleEntityRelationships()
3447
- // which is called from sql_codegen.ts AFTER entity fields are fully synced.
3710
+ // of stale relationships. CleanupStaleEntityRelationships() does it; SQLCodeGenBase.manageSQLScriptsAndExecution
3711
+ // calls it after the post-regeneration field sync (report-only unless cleanupStaleRelationships is set, #2071).
3448
3712
  return true;
3449
3713
  }
3450
3714
  catch (e) {
@@ -3486,7 +3750,14 @@ export class ManageMetadataBase {
3486
3750
  const entityKeyField = this.resolveRelationshipEntityKeyField(f, parentEntity);
3487
3751
  const keyFieldColumn = entityKeyField ? `, ${this.qi('EntityKeyField')}` : '';
3488
3752
  const keyFieldValue = entityKeyField ? `, '${entityKeyField.replace(/'/g, "''")}'` : '';
3489
- const checkQuery = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntityRelationship')} WHERE ${this.qi('ID')} = '${newEntityRelationshipUUID}'`;
3753
+ // The guard is keyed on the relationship's natural key, not only on the id minted above (#4053).
3754
+ // This SQL is captured into migrations and replayed on databases that already hold the same
3755
+ // relationship under an id of their own; an id-only guard can never match there, and
3756
+ // EntityRelationship has no unique constraint to stop the duplicate. Mirrors the EntityField
3757
+ // guard in getPendingEntityFieldINSERTSQL. The columns are the FK field's, inverted: the row's
3758
+ // EntityID is the field's RelatedEntityID (the parent) and its RelatedEntityID is the field's
3759
+ // EntityID (the child).
3760
+ const checkQuery = this.relationshipInsertGuardSQL(newEntityRelationshipUUID, f.RelatedEntityID, f.EntityID, f.Name);
3490
3761
  const insertSQL = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityRelationship')} (${this.qi('ID')}, ${this.qi('EntityID')}, ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityJoinField')}${keyFieldColumn}, ${this.qi('Type')}, ${this.qi('BundleInAPI')}, ${this.qi('DisplayInForm')}, ${this.qi('Sequence')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')})
3491
3762
  VALUES ('${newEntityRelationshipUUID}', '${f.RelatedEntityID}', '${f.EntityID}', '${f.Name}'${keyFieldValue}, 'One To Many', ${this.boolLit(true)}, ${this.boolLit(true)}, ${sequence}, ${this.utcNow()}, ${this.utcNow()})`;
3492
3763
  relationshipCountMap.set(parentEntityID, sequence);
@@ -3495,6 +3766,16 @@ export class ManageMetadataBase {
3495
3766
  ${this.dbProvider.conditionalInsertSQL(checkQuery, insertSQL)};
3496
3767
  `;
3497
3768
  }
3769
+ /**
3770
+ * The existence check for a new One To Many EntityRelationship: true when the row id is taken OR
3771
+ * a relationship with the same natural key (parent entity, child entity, join field) exists.
3772
+ */
3773
+ relationshipInsertGuardSQL(newID, parentEntityID, childEntityID, joinField) {
3774
+ return `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntityRelationship')} WHERE ${this.qi('ID')} = '${newID}'`
3775
+ + ` OR (${this.qi('EntityID')} = '${parentEntityID}'`
3776
+ + ` AND ${this.qi('RelatedEntityID')} = '${childEntityID}'`
3777
+ + ` AND ${this.qi('RelatedEntityJoinField')} = '${EscapeSQLString(joinField)}')`;
3778
+ }
3498
3779
  /**
3499
3780
  * Resolves the `EntityRelationship.EntityKeyField` value for a discovered FK field, or `null`
3500
3781
  * when the relationship joins the parent's primary key and the column therefore must stay NULL.
@@ -3678,28 +3959,43 @@ export class ManageMetadataBase {
3678
3959
  return sql;
3679
3960
  }
3680
3961
  /**
3681
- * Public entry point for cleaning up stale EntityRelationship records. This must be called
3682
- * AFTER deleteUnneededEntityFields() has run, so that stale EntityField records (for dropped
3683
- * columns) are removed before we check which relationships are still valid.
3684
- * Called from sql_codegen.ts after the second manageEntityFields() pass.
3962
+ * Finds, and unless `DryRun` is set removes, One To Many EntityRelationship rows whose join field
3963
+ * no longer backs them (#2071). Must run AFTER the entity-field prune, so the fields of dropped
3964
+ * columns are already gone. The run calls it after STEP 3's field sync; it deletes only when the
3965
+ * `cleanupStaleRelationships` config option is set.
3966
+ *
3967
+ * A row is stale only when every one of these holds:
3968
+ * - `Type` is One To Many and `AutoUpdateFromSchema` is set. Rows pinned with `AutoUpdateFromSchema = 0`
3969
+ * are never touched; a row made in Explorer defaults to 1, so it is a candidate unless unticked;
3970
+ * - `EntityKeyField` is empty. A row joining on a non-PK parent column can carry a child join field
3971
+ * whose FK points at a third entity, so the FK target says nothing about whether it is stale;
3972
+ * - `RelatedEntityJoinField` is not empty. An empty one names no column, so nothing can be checked;
3973
+ * - BOTH its parent and child entities are in scope. Out of scope means untouched, not deleted
3974
+ * (#3384): an app run must not delete relationships of core or sibling-app entities;
3975
+ * - the child's join field is gone (dropped or renamed column), or it now points at a different
3976
+ * parent entity. A join field that still exists with no relationship at all is kept: that is how
3977
+ * a hand-made relationship over a non-FK column looks, and it cannot be told apart from a
3978
+ * dropped FK.
3979
+ * Soft FKs (`IsSoftForeignKey`, from additionalSchemaInfo or the LLM) carry RelatedEntityID like a
3980
+ * real FK, so the rows built from them are valid. IDs compare via NormalizeUUID, and names are
3981
+ * trimmed (nchar padding) and compared case-insensitively, so every mismatch errs towards keeping.
3685
3982
  * @param pool - database connection
3686
- * @param excludeSchemas - schemas to exclude from FK field lookup
3983
+ * @param excludeSchemas - the compiled exclude list (authored excludes plus includeSchemas scope)
3984
+ * @param options.DryRun - report what would be removed without removing it (default true)
3985
+ * @returns false on error. {@link StaleRelationshipsRemoved} holds how many rows the call deleted.
3687
3986
  */
3688
- async CleanupStaleEntityRelationships(pool, excludeSchemas) {
3987
+ async CleanupStaleEntityRelationships(pool, excludeSchemas, options = {}) {
3988
+ const dryRun = options.DryRun !== false;
3989
+ this._staleRelationshipsRemoved = 0;
3689
3990
  try {
3690
- const sSQL = `SELECT *
3691
- FROM ${this.qs(MjCoreSchema(), 'vwEntityFields')}
3692
- WHERE
3693
- RelatedEntityID IS NOT NULL AND
3694
- IsVirtual = ${this.boolLit(false)} AND
3695
- EntityID NOT IN (SELECT ID FROM ${this.qs(MjCoreSchema(), 'Entity')} WHERE SchemaName IN (${excludeSchemas.map(s => `'${s}'`).join(',')}))
3696
- ORDER BY RelatedEntityID, EntityID, Sequence, ID`;
3697
- const entityFieldsResult = await this.runQuery(pool, sSQL);
3698
- const entityFields = entityFieldsResult.recordset;
3699
- const sSQLRelationship = `SELECT * FROM ${this.qs(MjCoreSchema(), 'EntityRelationship')}`;
3700
- const allRelationshipsResult = await this.runQuery(pool, sSQLRelationship);
3701
- const allRelationships = allRelationshipsResult.recordset;
3702
- await this.removeStaleOneToManyRelationships(pool, allRelationships, entityFields);
3991
+ const entitiesResult = await this.runQuery(pool, `SELECT ${this.qi('ID')}, ${this.qi('SchemaName')} FROM ${this.qs(MjCoreSchema(), 'Entity')}`);
3992
+ const inScopeEntityIDs = new Set(entitiesResult.recordset
3993
+ .filter(e => !this.isSchemaExcluded(e.SchemaName, excludeSchemas))
3994
+ .map(e => NormalizeUUID(String(e.ID))));
3995
+ const fieldsResult = await this.runQuery(pool, `SELECT ${this.qi('EntityID')}, ${this.qi('Name')}, ${this.qi('RelatedEntityID')} FROM ${this.qs(MjCoreSchema(), 'EntityField')}`);
3996
+ const relationshipsResult = await this.runQuery(pool, `SELECT * FROM ${this.qs(MjCoreSchema(), 'EntityRelationship')}`);
3997
+ const stale = ManageMetadataBase.FindStaleOneToManyRelationships(relationshipsResult.recordset, fieldsResult.recordset, inScopeEntityIDs);
3998
+ this._staleRelationshipsRemoved = await this.removeStaleOneToManyRelationships(pool, stale, dryRun);
3703
3999
  return true;
3704
4000
  }
3705
4001
  catch (e) {
@@ -3707,49 +4003,103 @@ export class ManageMetadataBase {
3707
4003
  return false;
3708
4004
  }
3709
4005
  }
4006
+ /** Rows the last {@link CleanupStaleEntityRelationships} call deleted (always 0 on a dry run). */
4007
+ get StaleRelationshipsRemoved() {
4008
+ return this._staleRelationshipsRemoved;
4009
+ }
3710
4010
  /** @deprecated Use {@link CleanupStaleEntityRelationships}. */
3711
- async cleanupStaleEntityRelationships(pool, excludeSchemas) {
3712
- return this.CleanupStaleEntityRelationships(pool, excludeSchemas);
4011
+ async cleanupStaleEntityRelationships(pool, excludeSchemas, options = {}) {
4012
+ return this.CleanupStaleEntityRelationships(pool, excludeSchemas, options);
3713
4013
  }
3714
4014
  /**
3715
- * Removes stale One-To-Many EntityRelationship records whose RelatedEntityJoinField no longer
3716
- * corresponds to a valid FK field in the database. Only removes relationships where
3717
- * AutoUpdateFromSchema = true and Type = 'One To Many'.
4015
+ * The pure half of {@link CleanupStaleEntityRelationships}: picks the stale One To Many rows.
4016
+ * @param relationships - every EntityRelationship row
4017
+ * @param fields - EntityField rows (EntityID, Name, RelatedEntityID) of at least the in-scope entities
4018
+ * @param inScopeEntityIDs - normalized IDs (NormalizeUUID) of the entities this run owns
3718
4019
  */
3719
- async removeStaleOneToManyRelationships(pool, allRelationships, entityFields) {
3720
- // Build a set of valid (ParentEntityID, ChildEntityID, JoinFieldName) tuples from current FK fields.
3721
- // In EntityRelationship terms: EntityID = ParentEntityID (the "one" side), RelatedEntityID = ChildEntityID (the "many" side)
3722
- // In entityFields: f.RelatedEntityID = ParentEntityID, f.EntityID = ChildEntityID, f.Name = FK field name
3723
- const validRelationshipKeys = new Set();
3724
- for (const f of entityFields) {
3725
- validRelationshipKeys.add(`${f.RelatedEntityID}|${f.EntityID}|${f.Name}`);
4020
+ static FindStaleOneToManyRelationships(relationships, fields, inScopeEntityIDs) {
4021
+ // child entity ID → (lower-cased trimmed field name → normalized RelatedEntityID or '')
4022
+ const fieldsByEntity = new Map();
4023
+ for (const f of fields) {
4024
+ const entityKey = NormalizeUUID(String(f.EntityID));
4025
+ let byName = fieldsByEntity.get(entityKey);
4026
+ if (!byName) {
4027
+ byName = new Map();
4028
+ fieldsByEntity.set(entityKey, byName);
4029
+ }
4030
+ byName.set(String(f.Name ?? '').trim().toLowerCase(), f.RelatedEntityID ? NormalizeUUID(String(f.RelatedEntityID)) : '');
4031
+ }
4032
+ const isSet = (v) => v === true || v === 1 || v === '1' || v === 'true';
4033
+ return relationships.filter(r => {
4034
+ if (String(r.Type ?? '').trim() !== 'One To Many' || !isSet(r.AutoUpdateFromSchema)) {
4035
+ return false;
4036
+ }
4037
+ const parentID = NormalizeUUID(String(r.EntityID));
4038
+ const childID = NormalizeUUID(String(r.RelatedEntityID));
4039
+ if (!inScopeEntityIDs.has(parentID) || !inScopeEntityIDs.has(childID)) {
4040
+ return false;
4041
+ }
4042
+ const childFields = fieldsByEntity.get(childID);
4043
+ if (!childFields) {
4044
+ // No field rows for the child at all: the field list is not trustworthy for it, so keep.
4045
+ return false;
4046
+ }
4047
+ if (String(r.EntityKeyField ?? '').trim() !== '') {
4048
+ return false; // joins on a non-PK parent column: the FK target cannot judge it
4049
+ }
4050
+ const joinField = String(r.RelatedEntityJoinField ?? '').trim().toLowerCase();
4051
+ if (joinField === '') {
4052
+ return false; // names no column, so there is nothing to check
4053
+ }
4054
+ if (!childFields.has(joinField)) {
4055
+ return true; // join column dropped or renamed
4056
+ }
4057
+ const target = childFields.get(joinField) ?? '';
4058
+ return target !== '' && target !== parentID; // FK now points at another entity
4059
+ });
4060
+ }
4061
+ /**
4062
+ * Logs each stale relationship and, unless `dryRun`, deletes it. Each DELETE is keyed on the row
4063
+ * id, so a captured script replayed on a host with different ids deletes nothing there.
4064
+ */
4065
+ async removeStaleOneToManyRelationships(pool, staleRelationships, dryRun) {
4066
+ if (staleRelationships.length === 0) {
4067
+ return 0;
3726
4068
  }
3727
- const staleRelationships = allRelationships.filter(r => String(r.Type).trim() === 'One To Many' &&
3728
- r.AutoUpdateFromSchema === true &&
3729
- !validRelationshipKeys.has(`${r.EntityID}|${r.RelatedEntityID}|${r.RelatedEntityJoinField}`));
3730
- if (staleRelationships.length > 0) {
3731
- let deleteSQL = '';
4069
+ if (dryRun) {
3732
4070
  for (const r of staleRelationships) {
3733
- logStatus(` > Removing stale EntityRelationship: ${r.Entity} -> ${r.RelatedEntity} via '${r.RelatedEntityJoinField}' (ID: ${r.ID})`);
3734
- deleteSQL += `
3735
- /* Remove stale EntityRelationship: ${r.Entity} -> ${r.RelatedEntity} (FK field '${r.RelatedEntityJoinField}' no longer exists) */
4071
+ LogWarning(` > Stale EntityRelationship (not removed, dry run): ${r.Entity ?? r.EntityID} -> ${r.RelatedEntity ?? r.RelatedEntityID} via '${String(r.RelatedEntityJoinField ?? '').trim()}' (ID: ${r.ID})`);
4072
+ }
4073
+ return 0;
4074
+ }
4075
+ let deleteSQL = '';
4076
+ for (const r of staleRelationships) {
4077
+ const joinField = String(r.RelatedEntityJoinField ?? '').trim();
4078
+ logStatus(` > Removing stale EntityRelationship: ${r.Entity ?? r.EntityID} -> ${r.RelatedEntity ?? r.RelatedEntityID} via '${joinField}' (ID: ${r.ID})`);
4079
+ deleteSQL += `
4080
+ /* Remove stale EntityRelationship: ${r.Entity ?? r.EntityID} -> ${r.RelatedEntity ?? r.RelatedEntityID} (join field '${joinField}' no longer backs it) */
3736
4081
  DELETE FROM ${this.qs(MjCoreSchema(), 'EntityRelationship')} WHERE ${this.qi('ID')} = '${r.ID}';
3737
4082
  `;
3738
- }
3739
- await this.logSQLAndExecute(pool, deleteSQL, 'Remove stale One-To-Many EntityRelationships');
3740
4083
  }
4084
+ await this.logSQLAndExecute(pool, deleteSQL, 'Remove stale One-To-Many EntityRelationships');
4085
+ return staleRelationships.length;
3741
4086
  }
3742
4087
  /**
3743
4088
  * This method will look for situations where entity metadata exist in the entities metadata table but the underlying table has been deleted. In this case, the metadata for the entity
3744
4089
  * should be removed. This method is called as part of the manageMetadata method and is not intended to be called directly.
3745
4090
  * @param ds
3746
- * @param excludeSchemas
4091
+ * @param excludeSchemas - deliberately NOT read (#3384). Removal is driven by the physical table
4092
+ * being gone, never by scope: an out-of-scope entity is untouched, not deleted, so filtering
4093
+ * on this list would turn "this schema is out of scope" into "delete its metadata".
3747
4094
  */
3748
4095
  async checkAndRemoveMetadataForDeletedTables(pool, excludeSchemas) {
3749
4096
  try {
3750
4097
  const sql = `SELECT * FROM ${this.qs(MjCoreSchema(), 'vwEntitiesWithMissingBaseTables')}${this.dbProvider.getEntitiesWithMissingBaseTablesFilter()}`;
3751
4098
  const entitiesResult = await this.runQuery(pool, sql);
3752
4099
  const entities = entitiesResult.recordset;
4100
+ // An entity whose removal fails is recorded and the rest still run; the step then fails
4101
+ // (#3546). A half-pruned entity left behind silently drops out of every later generation.
4102
+ const failedRemovals = [];
3753
4103
  if (entities && entities.length > 0) {
3754
4104
  for (const e of entities) {
3755
4105
  // External-data-source entities have no physical MJ table by design, so they always
@@ -3763,9 +4113,8 @@ export class ManageMetadataBase {
3763
4113
  if (e.ExternalDataSourceID) {
3764
4114
  continue;
3765
4115
  }
3766
- // for the given entity, wipe out the entity metadata and its core deps.
3767
- // the below could fail if there are non-core dependencies on the entity, but that's ok, we will flag that in the console
3768
- // for the admin to handle manually
4116
+ // for the given entity, wipe out the entity metadata and its core deps. This fails when
4117
+ // a dependency the routine does not handle still references the entity.
3769
4118
  try {
3770
4119
  // discardResult: this routine only performs deletions — nothing below reads rows
3771
4120
  // from it — and on PostgreSQL it is declared RETURNS SETOF record, which cannot be
@@ -3787,13 +4136,18 @@ export class ManageMetadataBase {
3787
4136
  await this.checkDropSQLObject(pool, e.FullTextSearchFunctionGenerated, 'function', e.SchemaName, e.FullTextSearchFunction);
3788
4137
  }
3789
4138
  catch (ex) {
3790
- logError(`Error removing metadata for entity ${ex.Name}, error: ${ex}`);
4139
+ failedRemovals.push(`${e.Name} (${e.SchemaName}.${e.BaseTable})`);
4140
+ logError(`Error removing metadata for entity ${e.Name} (${e.SchemaName}.${e.BaseTable}): ${ex instanceof Error ? ex.message : String(ex)}`);
3791
4141
  }
3792
4142
  }
3793
4143
  // if we get here we now need to refresh our metadata object
3794
4144
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
3795
4145
  await md.Refresh();
3796
4146
  }
4147
+ if (failedRemovals.length > 0) {
4148
+ logError(` Could not remove metadata for ${failedRemovals.length} entit${failedRemovals.length === 1 ? 'y' : 'ies'} whose base table was dropped: ${failedRemovals.join(', ')}`);
4149
+ return false;
4150
+ }
3797
4151
  return true;
3798
4152
  }
3799
4153
  catch (e) {
@@ -3878,19 +4232,45 @@ export class ManageMetadataBase {
3878
4232
  * Manages the creation, updating and deletion of entity field records in the metadata based on the database schema.
3879
4233
  *
3880
4234
  * @param entityFilter Optional list of entity NAMES to scope the field-management work to. When provided,
3881
- * the three SP/inline-SQL passes (delete unneeded, create new from schema, update existing from schema)
3882
- * filter to those entities only. Other steps remain unscoped — they are cheap enough that scoping them
3883
- * adds complexity without measurable benefit. An empty array short-circuits the entire method as a no-op,
3884
- * which is the typical "no schema changes since last run" case in Pass 2.
4235
+ * the create-new and update-existing schema-sync passes filter to those entities only. The orphan prune
4236
+ * is never scoped (#4050): it runs first, over every entity, and any entity it removed fields from is
4237
+ * added to the filter so its Sequence is renumbered in the same run. An empty filter with nothing pruned
4238
+ * skips the rest of the method, which is the typical "no schema changes since last run" case in Pass 2.
3885
4239
  * `undefined` (default) preserves prior full-scan behavior.
3886
4240
  */
3887
4241
  async ManageEntityFields(pool, excludeSchemas, skipCreatedAtUpdatedAtDeletedAtFieldValidation, skipEntityFieldValues, currentUser, skipAdvancedGeneration, skipDeleteUnneededFields = false, entityFilter) {
3888
4242
  let bSuccess = true;
3889
4243
  const startTime = new Date();
3890
- // Fast-exit: an explicit empty filter means "no entities changed in Pass 1, so Pass 2 has nothing to do"
3891
- if (entityFilter && entityFilter.length === 0) {
4244
+ // Prune orphaned EntityField rows FIRST and UNSCOPED (#4050, #5976, #6028). The SQL pass
4245
+ // regenerates the base view of every included entity, so a view can lose columns while its
4246
+ // table is unchanged (the hierarchy opt-in gate drops Root*/Depth/Path this way). Such an
4247
+ // entity is in neither the new nor the modified list, which are built from table changes,
4248
+ // so a scoped prune — or the empty-filter exit below — never reaches it. The prune is one
4249
+ // routine call; the scan is the same one R__RefreshMetadata runs on every migrate.
4250
+ let prunedEntityNames = [];
4251
+ if (skipDeleteUnneededFields) {
4252
+ logStatus(` Skipping deletion of unneeded entity fields (deferred to post-SQL pass)`);
4253
+ }
4254
+ else {
4255
+ const pruneStart = new Date();
4256
+ const prune = await this.deleteUnneededEntityFields(pool, excludeSchemas);
4257
+ if (!prune.success) {
4258
+ logError('Error deleting unneeded entity fields');
4259
+ bSuccess = false;
4260
+ }
4261
+ prunedEntityNames = prune.prunedEntityNames;
4262
+ logStatus(` Deleted unneeded entity fields${prunedEntityNames.length > 0 ? ` from ${prunedEntityNames.length} entit${prunedEntityNames.length === 1 ? 'y' : 'ies'}` : ''} in ${(new Date().getTime() - pruneStart.getTime()) / 1000} seconds`);
4263
+ }
4264
+ // A pruned entity joins this pass's scope: spUpdateExistingEntityFieldsFromSchema renumbers
4265
+ // Sequence from the live view and only touches entities in scope. The caller snapshotted the
4266
+ // modified list before this call, so the prune's addition to that list does not reach here.
4267
+ const effectiveFilter = entityFilter
4268
+ ? [...new Set([...entityFilter, ...prunedEntityNames])]
4269
+ : undefined;
4270
+ // Fast-exit: an empty filter means "no entities changed in Pass 1 and nothing was pruned"
4271
+ if (effectiveFilter && effectiveFilter.length === 0) {
3892
4272
  logStatus(` manageEntityFields: empty entityFilter — skipping Pass 2 (no entities to process)`);
3893
- return true;
4273
+ return bSuccess;
3894
4274
  }
3895
4275
  // Resolve entity names → IDs once up front so SP wrappers can receive UUIDs directly.
3896
4276
  // If a non-empty filter resolved to zero IDs (e.g., all names were stale/invalid),
@@ -3898,11 +4278,11 @@ export class ManageMetadataBase {
3898
4278
  // unscoped full scan, which is worse than the original intent. Treating "filter
3899
4279
  // provided but nothing resolved" as a no-op is the correct behavior.
3900
4280
  let scopedEntityIDs;
3901
- if (entityFilter) {
3902
- scopedEntityIDs = this.resolveEntityNamesToIDs(entityFilter);
4281
+ if (effectiveFilter) {
4282
+ scopedEntityIDs = this.resolveEntityNamesToIDs(effectiveFilter);
3903
4283
  if (scopedEntityIDs.length === 0) {
3904
- logStatus(` manageEntityFields: entityFilter (${entityFilter.length} names) resolved to 0 IDs — skipping Pass 2`);
3905
- return true;
4284
+ logStatus(` manageEntityFields: entityFilter (${effectiveFilter.length} names) resolved to 0 IDs — skipping Pass 2`);
4285
+ return bSuccess;
3906
4286
  }
3907
4287
  }
3908
4288
  if (!skipCreatedAtUpdatedAtDeletedAtFieldValidation) {
@@ -3913,17 +4293,6 @@ export class ManageMetadataBase {
3913
4293
  }
3914
4294
  logStatus(` Ensured ${EntityInfo.CreatedAtFieldName}/${EntityInfo.UpdatedAtFieldName}/${EntityInfo.DeletedAtFieldName} fields exist in ${(new Date().getTime() - startTime.getTime()) / 1000} seconds`);
3915
4295
  }
3916
- const step1StartTime = new Date();
3917
- if (skipDeleteUnneededFields) {
3918
- logStatus(` Skipping deletion of unneeded entity fields (deferred to post-SQL pass)`);
3919
- }
3920
- else {
3921
- if (!await this.deleteUnneededEntityFields(pool, excludeSchemas, scopedEntityIDs)) {
3922
- logError('Error deleting unneeded entity fields');
3923
- bSuccess = false;
3924
- }
3925
- logStatus(` Deleted unneeded entity fields in ${(new Date().getTime() - step1StartTime.getTime()) / 1000} seconds`);
3926
- }
3927
4296
  // AN: 14-June-2025 - See note below about the new order of these steps, this must
3928
4297
  // happen before we update existing entity fields from schema.
3929
4298
  const step2StartTime = new Date();
@@ -3956,12 +4325,13 @@ export class ManageMetadataBase {
3956
4325
  const stepConfigStartTime = new Date();
3957
4326
  if (!await this.applySoftPKFKConfig(pool)) {
3958
4327
  logError('Error applying soft PK/FK configuration');
4328
+ bSuccess = false;
3959
4329
  }
3960
4330
  logStatus(` Applied soft PK/FK configuration in ${(new Date().getTime() - stepConfigStartTime.getTime()) / 1000} seconds`);
3961
4331
  // CRITICAL: Refresh metadata to pick up soft PK/FK flags
3962
4332
  // Without this, downstream SQL and TypeScript generation will fail
3963
4333
  // because entity.Fields and entity.PrimaryKeys won't reflect the updated flags
3964
- if (configInfo.additionalSchemaInfo) {
4334
+ if (ResolveAdditionalSchemaInfoPath()) {
3965
4335
  logStatus(' Refreshing metadata after applying soft PK/FK configuration...');
3966
4336
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
3967
4337
  await md.Refresh();
@@ -3970,7 +4340,7 @@ export class ManageMetadataBase {
3970
4340
  // IS-A parent field sync: create/update virtual EntityField records for parent chain fields
3971
4341
  // Must run AFTER metadata refresh so it sees current soft PK/FK flags
3972
4342
  const stepISAStartTime = new Date();
3973
- const isaResult = await this.manageParentEntityFields(pool);
4343
+ const isaResult = await this.manageParentEntityFields(pool, excludeSchemas);
3974
4344
  if (!isaResult.success) {
3975
4345
  logError('Error managing IS-A parent entity fields');
3976
4346
  bSuccess = false;
@@ -4004,6 +4374,8 @@ export class ManageMetadataBase {
4004
4374
  // Non-fatal: soft value-lists are supplementary
4005
4375
  }
4006
4376
  logStatus(` Applied soft value-list configuration in ${(new Date().getTime() - stepValueListStartTime.getTime()) / 1000} seconds`);
4377
+ // Report fields left as ValueListType='List' with no values (#3986). Warn only.
4378
+ await this.warnOnEmptyValueLists(pool, excludeSchemas);
4007
4379
  }
4008
4380
  // Advanced Generation - Smart field identification and form layout
4009
4381
  if (!skipAdvancedGeneration) {
@@ -4092,21 +4464,27 @@ export class ManageMetadataBase {
4092
4464
  * {@link applyVirtualEntitySoftKeys}.
4093
4465
  */
4094
4466
  async applySoftPKFKConfig(pool) {
4095
- // Check if additionalSchemaInfo is configured in mj.config.cjs
4096
- if (!configInfo.additionalSchemaInfo) {
4467
+ // Check if additionalSchemaInfo is configured (mj.config.cjs or the RSU env override)
4468
+ const configPath = ResolveAdditionalSchemaInfoPath();
4469
+ if (!configPath) {
4097
4470
  // No additional schema info configured - this is fine, it's optional
4098
4471
  return true;
4099
4472
  }
4100
- const configPath = path.join(currentWorkingDirectory, configInfo.additionalSchemaInfo);
4473
+ // A configured file that does not exist yet is normal: RSU writes it the first time it adds
4474
+ // a table, so a fresh checkout has none. Say where CodeGen looked, so a path that resolves
4475
+ // somewhere unexpected is visible (#5858). RSU itself fails the run when CodeGen creates no
4476
+ // entity for a table it added, which is what catches a real mismatch. An unreadable file
4477
+ // (below) is still a failure.
4101
4478
  if (!fs.existsSync(configPath)) {
4102
- logStatus(` ⚠️ additionalSchemaInfo configured but file not found: ${configPath}`);
4479
+ LogWarning(` additionalSchemaInfo is configured but no file exists yet at ${configPath}; no soft keys applied`);
4103
4480
  return true;
4104
4481
  }
4105
4482
  try {
4106
- logStatus(` Found ${configInfo.additionalSchemaInfo}, applying soft PK/FK configuration...`);
4483
+ logStatus(` Found ${configPath}, applying soft PK/FK configuration...`);
4107
4484
  const config = ManageMetadataBase.getSoftPKFKConfig();
4108
4485
  if (!config) {
4109
- return true;
4486
+ logError(` additionalSchemaInfo file could not be parsed: ${configPath}`);
4487
+ return false;
4110
4488
  }
4111
4489
  // Config supports two formats:
4112
4490
  // 1. Schema-as-key (template format): { "dbo": [{ "TableName": "Orders", ... }] }
@@ -4192,6 +4570,7 @@ export class ManageMetadataBase {
4192
4570
  const entityId = entityResult.recordset[0].ID;
4193
4571
  const primaryKeys = table.PrimaryKey || [];
4194
4572
  totalPKs += await this.applySoftPrimaryKeys(pool, table, entityId, clearUniqueOnCompositeKey && primaryKeys.length > 1);
4573
+ totalPKs += await this.retractUndeclaredSoftPrimaryKeys(pool, table, entityId);
4195
4574
  resolved.push({ table, entityId });
4196
4575
  }
4197
4576
  for (const { table, entityId } of resolved) {
@@ -4331,6 +4710,58 @@ export class ManageMetadataBase {
4331
4710
  }
4332
4711
  return written;
4333
4712
  }
4713
+ /**
4714
+ * Clears the soft primary key from columns the table's entry no longer lists (#2568). Without it a
4715
+ * wrong soft PK (say a composite key that should have been one column) stays on the entity after
4716
+ * the file is corrected, and only hand-written SQL could remove it.
4717
+ *
4718
+ * Only rows CodeGen marked (`IsSoftPrimaryKey = 1`) are touched, and only for a table whose entry
4719
+ * still declares a PrimaryKey that resolved to at least one column: the entity always keeps a key.
4720
+ * An entry with no PrimaryKey, or a table missing from the file, is left alone, so a truncated or
4721
+ * partial file cannot strip keys. Clearing IsSoftPrimaryKey hands IsPrimaryKey back to schema sync,
4722
+ * which re-derives it from the table on the next field sync.
4723
+ * @returns the number of UPDATEs written
4724
+ */
4725
+ async retractUndeclaredSoftPrimaryKeys(pool, table, entityId) {
4726
+ const declared = (table.PrimaryKey || []).map(pk => pk.FieldName);
4727
+ if (declared.length === 0) {
4728
+ return 0;
4729
+ }
4730
+ const schema = MjCoreSchema();
4731
+ const fieldsSQL = `SELECT ${this.qi('Name')}, ${this.qi('IsSoftPrimaryKey')} FROM ${this.qs(schema, 'EntityField')}
4732
+ WHERE ${this.qi('EntityID')} = '${entityId}'`;
4733
+ const fieldsRes = await this.runQuery(pool, fieldsSQL);
4734
+ const softNames = fieldsRes.recordset.filter(r => this.isFlagSet(r.IsSoftPrimaryKey)).map(r => String(r.Name));
4735
+ const toRetract = ManageMetadataBase.SoftPrimaryKeysToRetract(declared, softNames);
4736
+ let written = 0;
4737
+ for (const name of toRetract) {
4738
+ const fieldName = EscapeSQLString(name);
4739
+ const sSQL = `UPDATE ${this.qs(schema, 'EntityField')}
4740
+ SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()},
4741
+ ${this.qi('IsPrimaryKey')} = ${this.boolLit(false)},
4742
+ ${this.qi('IsSoftPrimaryKey')} = ${this.boolLit(false)}
4743
+ WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}' AND ${this.qi('IsSoftPrimaryKey')} = ${this.boolLit(true)}`;
4744
+ const result = await this.logSQLAndExecute(pool, sSQL, `Clear soft PK no longer declared for ${table.SchemaName}.${table.TableName}.${name}`);
4745
+ if (result !== null) {
4746
+ LogWarning(` Cleared soft primary key on ${table.SchemaName}.${table.TableName}.${name}: additionalSchemaInfo no longer lists it`);
4747
+ written++;
4748
+ }
4749
+ }
4750
+ return written;
4751
+ }
4752
+ /**
4753
+ * The soft-PK columns to clear: those marked soft PK that the entry does not declare. Returns none
4754
+ * when no declared column is currently a soft PK, so a key is never removed without its
4755
+ * replacement in place. Names compare case-insensitively, which errs towards keeping.
4756
+ */
4757
+ static SoftPrimaryKeysToRetract(declaredFieldNames, softPrimaryKeyFieldNames) {
4758
+ const declared = new Set(declaredFieldNames.map(n => n.trim().toLowerCase()));
4759
+ const isDeclared = (n) => declared.has(n.trim().toLowerCase());
4760
+ if (!softPrimaryKeyFieldNames.some(isDeclared)) {
4761
+ return [];
4762
+ }
4763
+ return softPrimaryKeyFieldNames.filter(n => !isDeclared(n));
4764
+ }
4334
4765
  /**
4335
4766
  * Sets RelatedEntityID, RelatedEntityFieldName and IsSoftForeignKey = 1 on each configured foreign
4336
4767
  * key column. RelatedEntityID is the source of truth, IsSoftForeignKey protects it from schema sync.
@@ -4499,6 +4930,40 @@ export class ManageMetadataBase {
4499
4930
  logStatus(` ✓ Applied soft value-list for ${tableName}.${fieldCfg.FieldName} (${sortedValues.length} values, type=${newType})`);
4500
4931
  return 'applied';
4501
4932
  }
4933
+ /**
4934
+ * Warns about every in-scope field whose ValueListType is 'List' but which has no EntityFieldValue
4935
+ * rows (#3986). That combination permits no value at all, so it is always broken metadata; the
4936
+ * runtime permits everything for such a field and logs an error, which is late and easy to miss.
4937
+ *
4938
+ * A warning, not a correction: setting ValueListType to 'None' would discard the intent that the
4939
+ * field is constrained. Never fails the run; a failed query is logged and ignored.
4940
+ * @returns the fields found, as `Entity.Field`
4941
+ */
4942
+ async warnOnEmptyValueLists(pool, excludeSchemas) {
4943
+ const schema = MjCoreSchema();
4944
+ const scopeClause = excludeSchemas.length > 0
4945
+ ? ` AND e.${this.qi('SchemaName')} NOT IN (${excludeSchemas.map(s => `'${EscapeSQLString(s)}'`).join(',')})`
4946
+ : '';
4947
+ const sql = `SELECT e.${this.qi('Name')} AS ${this.qi('EntityName')}, ef.${this.qi('Name')} AS ${this.qi('FieldName')}
4948
+ FROM ${this.qs(schema, 'EntityField')} ef
4949
+ INNER JOIN ${this.qs(schema, 'Entity')} e ON e.${this.qi('ID')} = ef.${this.qi('EntityID')}
4950
+ WHERE ef.${this.qi('ValueListType')} = 'List'${scopeClause}
4951
+ AND NOT EXISTS (SELECT 1 FROM ${this.qs(schema, 'EntityFieldValue')} v WHERE v.${this.qi('EntityFieldID')} = ef.${this.qi('ID')})
4952
+ ORDER BY e.${this.qi('Name')}, ef.${this.qi('Name')}`;
4953
+ try {
4954
+ const result = await this.runQuery(pool, sql);
4955
+ const found = result.recordset.map(r => `${r.EntityName}.${r.FieldName}`);
4956
+ for (const name of found) {
4957
+ LogWarning(` ${name} has ValueListType='List' but no values, so no value is permitted. ` +
4958
+ `Re-derive the list (CHECK constraint or additionalSchemaInfo Fields[]), or set ValueListType='None' if the field is not meant to be constrained.`);
4959
+ }
4960
+ return found;
4961
+ }
4962
+ catch (e) {
4963
+ logError(`Error checking for empty value lists: ${e}`);
4964
+ return [];
4965
+ }
4966
+ }
4502
4967
  /**
4503
4968
  * This method ensures that the __mj_CreatedAt and __mj_UpdatedAt fields exist in each entity that has TrackRecordChanges set to true. If the fields do not exist, they are created.
4504
4969
  * If the fields exist but have incorrect default values, the default values are updated. The default value that is to be used for these special fields is GETUTCDATE() which is the
@@ -5039,6 +5504,9 @@ export class ManageMetadataBase {
5039
5504
  ManageMetadataBase.addNewEntitiesToModifiedList(changes.map(c => c.entityName));
5040
5505
  for (const c of changes) {
5041
5506
  ManageMetadataBase.registerFieldChange(c.entityID, c.fieldName, c.reasons);
5507
+ if (c.reasons.some(r => TYPE_REOPEN_REASONS.has(r))) {
5508
+ ManageMetadataBase.RegisterFieldShapeChange({ EntityID: c.entityID });
5509
+ }
5042
5510
  ManageMetadataBase._changedFieldReport.push({
5043
5511
  entityName: c.entityName,
5044
5512
  fieldName: c.fieldName,
@@ -5288,6 +5756,14 @@ export class ManageMetadataBase {
5288
5756
  }
5289
5757
  return [...out];
5290
5758
  }
5759
+ /**
5760
+ * Removes EntityField rows whose column no longer exists on the entity's base view or table.
5761
+ *
5762
+ * @param entityIDs Optional scope. {@link ManageEntityFields} omits it so every entity is scanned:
5763
+ * an entity orphaned by a view-only change is never in a change list (#4050).
5764
+ * @returns `success`, plus the distinct names of the entities rows were deleted from, so the
5765
+ * caller can bring them into scope for the Sequence renumber that follows.
5766
+ */
5291
5767
  async deleteUnneededEntityFields(pool, excludeSchemas, entityIDs) {
5292
5768
  try {
5293
5769
  // One SP call regardless of scope: pass the entire entity ID list as a comma-delimited
@@ -5312,16 +5788,33 @@ export class ManageMetadataBase {
5312
5788
  const result = await this.logSQLAndExecute(pool, sSQL, label, true);
5313
5789
  // result contains the DELETED entity fields. Get a distinct list of entity names
5314
5790
  // and add them to the modified entity list if they're not already in there.
5315
- if (result && result.length > 0) {
5316
- ManageMetadataBase.addNewEntitiesToModifiedList(result.map((r) => r.Entity));
5791
+ const prunedEntityNames = this.distinctPrunedEntityNames(result);
5792
+ if (prunedEntityNames.length > 0) {
5793
+ ManageMetadataBase.addNewEntitiesToModifiedList(prunedEntityNames);
5794
+ for (const entityName of prunedEntityNames) {
5795
+ ManageMetadataBase.RegisterFieldShapeChange({ EntityName: entityName });
5796
+ }
5317
5797
  }
5318
- return true;
5798
+ return { success: true, prunedEntityNames };
5319
5799
  }
5320
5800
  catch (e) {
5321
- logError(e);
5322
- return false;
5801
+ logError(`Error deleting unneeded entity fields: ${e instanceof Error ? e.message : String(e)}`);
5802
+ return { success: false, prunedEntityNames: [] };
5323
5803
  }
5324
5804
  }
5805
+ /**
5806
+ * Distinct, non-blank entity names from the rows spDeleteUnneededEntityFields returns (one row per
5807
+ * deleted field, carrying the owning entity's name in `Entity`).
5808
+ */
5809
+ distinctPrunedEntityNames(rows) {
5810
+ if (!rows || rows.length === 0) {
5811
+ return [];
5812
+ }
5813
+ const names = rows
5814
+ .map(r => r.Entity)
5815
+ .filter((name) => typeof name === 'string' && name.trim().length > 0);
5816
+ return [...new Set(names)];
5817
+ }
5325
5818
  async manageEntityFieldValuesAndValidatorFunctions(pool, excludeSchemas, currentUser, skipDBUpdate) {
5326
5819
  try {
5327
5820
  // here we want to get all of the entity fields that have check constraints attached to them. For each field that has a check constraint, we want to
@@ -5570,6 +6063,16 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
5570
6063
  return returnResult;
5571
6064
  }
5572
6065
  }
6066
+ /** Width of `EntityFieldValue.Code` (nvarchar(50)); `Value` is nvarchar(255). */
6067
+ static { this.EntityFieldValueCodeMaxLength = 50; }
6068
+ /**
6069
+ * The Code written for a value-list entry: the value itself when it fits the Code column, else
6070
+ * NULL, which the column documents as "same as Value". Truncating instead could make two codes
6071
+ * collide.
6072
+ */
6073
+ static EntityFieldValueCode(value) {
6074
+ return value.length <= ManageMetadataBase.EntityFieldValueCodeMaxLength ? value : null;
6075
+ }
5573
6076
  async syncEntityFieldValues(ds, entityFieldID, possibleValues, allEntityFieldValues) {
5574
6077
  try {
5575
6078
  // first, get a list of all of the existing entity field values for the field already in the database
@@ -5593,11 +6096,13 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
5593
6096
  if (!existingValues.find((ev) => ev.Value === v)) {
5594
6097
  // Generate a UUID for this new EntityFieldValue record
5595
6098
  const newId = uuidv4();
5596
- // add the value to the database with explicit ID
6099
+ // add the value to the database with explicit ID. Code is NULL ("same as Value") when
6100
+ // the value is longer than the Code column; copying it overflowed that column (#2577).
6101
+ const code = ManageMetadataBase.EntityFieldValueCode(v);
5597
6102
  const sSQLInsert = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityFieldValue')}
5598
6103
  (${this.qi('ID')}, ${this.qi('EntityFieldID')}, ${this.qi('Sequence')}, ${this.qi('Value')}, ${this.qi('Code')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')})
5599
6104
  VALUES
5600
- ('${newId}', '${entityFieldID}', ${1 + possibleValues.indexOf(v)}, '${v}', '${v}', ${this.utcNow()}, ${this.utcNow()})`;
6105
+ ('${newId}', '${entityFieldID}', ${1 + possibleValues.indexOf(v)}, '${EscapeSQLString(v)}', ${code === null ? 'NULL' : `'${EscapeSQLString(code)}'`}, ${this.utcNow()}, ${this.utcNow()})`;
5601
6106
  await this.logSQLAndExecute(ds, sSQLInsert, `SQL text to insert entity field value with ID ${newId}`);
5602
6107
  numAdded++;
5603
6108
  }
@@ -6069,12 +6574,12 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6069
6574
  * Checks if a table has a soft primary key defined in the additionalSchemaInfo JSON file (configured in mj.config.cjs)
6070
6575
  */
6071
6576
  hasSoftPrimaryKeyInConfig(schemaName, tableName) {
6072
- if (!configInfo.additionalSchemaInfo) {
6577
+ const configPath = ResolveAdditionalSchemaInfoPath();
6578
+ if (!configPath) {
6073
6579
  return false;
6074
6580
  }
6075
- const configPath = path.join(currentWorkingDirectory, configInfo.additionalSchemaInfo);
6076
6581
  if (!fs.existsSync(configPath)) {
6077
- logStatus(` [Soft PK Check] Config file not found at: ${configPath}`);
6582
+ logError(` [Soft PK Check] additionalSchemaInfo is configured but the file was not found: ${configPath}`);
6078
6583
  return false;
6079
6584
  }
6080
6585
  try {
@@ -6256,56 +6761,16 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6256
6761
  }
6257
6762
  newEntityName = uniqueName;
6258
6763
  const suffix = uniqueSuffix;
6259
- const isNewSchema = await this.isSchemaNew(pool, newEntity.SchemaName);
6260
6764
  const newEntityID = this.createNewUUID();
6261
6765
  const sSQLInsert = this.createNewEntityInsertSQL(newEntityID, newEntityName, newEntity, suffix, newEntityDisplayName);
6262
6766
  await this.logSQLAndExecute(pool, sSQLInsert, `SQL generated to create new entity ${newEntityName}`);
6263
6767
  // if we get here we created a new entity safely, otherwise we get exception
6264
6768
  // add it to the new entity list
6265
6769
  ManageMetadataBase.newEntityList.push(newEntityName);
6266
- // next, check if this entity is in a schema that is new (e.g. no other entities have been added to this schema yet), if so and if
6267
- // our config option is set to create new applications from new schemas, then create a new application for this schema
6268
- let apps;
6269
- if (isNewSchema && configInfo.newSchemaDefaults.CreateNewApplicationWithSchemaName) {
6270
- // new schema and config option is to create a new application from the schema name so do that
6271
- // check to see if the app already exists
6272
- apps = await this.getApplicationIDForSchema(pool, newEntity.SchemaName);
6273
- if (!apps || apps.length === 0) {
6274
- // doesn't already exist, so create it
6275
- const appUUID = this.createNewUUID();
6276
- const newAppID = await this.createNewApplication(pool, appUUID, newEntity.SchemaName, newEntity.SchemaName, currentUser);
6277
- if (newAppID) {
6278
- apps = [newAppID];
6279
- }
6280
- else {
6281
- LogError(` >>>> ERROR: Unable to create new application for schema ${newEntity.SchemaName}`);
6282
- }
6283
- await md.Refresh(); // refresh now since we've added a new application, not super efficient to do this for each new application but that won't happen super
6284
- // often so not a huge deal, would be more efficient do this in batch after all new apps are created but that would be an over optimization IMO
6285
- }
6286
- }
6287
- else {
6288
- // not a new schema, attempt to look up the application for this schema
6289
- apps = await this.getApplicationIDForSchema(pool, newEntity.SchemaName);
6290
- }
6291
- if (apps && apps.length > 0) {
6292
- if (configInfo.newEntityDefaults.AddToApplicationWithSchemaName) {
6293
- // only do this if the configuration setting is set to add new entities to applications for schema names
6294
- for (const appUUID of apps) {
6295
- const sSQLInsertApplicationEntity = `INSERT INTO ${this.qs(MjCoreSchema(), 'ApplicationEntity')}
6296
- (${this.qi('ApplicationID')}, ${this.qi('EntityID')}, ${this.qi('Sequence')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')}) VALUES
6297
- ('${appUUID}', '${newEntityID}', (SELECT COALESCE(MAX(${this.qi('Sequence')}),0)+1 FROM ${this.qs(MjCoreSchema(), 'ApplicationEntity')} WHERE ${this.qi('ApplicationID')} = '${appUUID}'), ${this.utcNow()}, ${this.utcNow()})`;
6298
- await this.logSQLAndExecute(pool, sSQLInsertApplicationEntity, `SQL generated to add new entity ${newEntityName} to application ID: '${appUUID}'`);
6299
- }
6300
- }
6301
- else {
6302
- // this is NOT an error condition, we do have an application UUID, but the configuration setting is to NOT add new entities to applications for schema names
6303
- }
6304
- }
6305
- else {
6306
- // this is an error condition, we should have an application for this schema, if we don't, log an error, non fatal, but should be logged
6307
- LogError(` >>>> ERROR: Unable to add new entity ${newEntityName} to an application because no Application has SchemaAutoAddNewEntities='${newEntity.SchemaName}'. To fix this, update an existing Application record or create a new one with SchemaAutoAddNewEntities='${newEntity.SchemaName}'.`);
6308
- }
6770
+ // link it to its schema's application, creating the application when none claims the schema. This runs
6771
+ // the lookup-and-create on every new entity (#4034): gating the create on "first entity in the schema"
6772
+ // meant one failed create left the schema without an application for good.
6773
+ await this.addEntityToApplicationForSchema(pool, newEntityID, newEntityName, newEntity.SchemaName, currentUser);
6309
6774
  // next up, we need to check if we're configured to add permissions for new entities, and if so, add them
6310
6775
  // A per-table `Entities` entry can opt a table out of the default grants (AutoAddPermissions: false),
6311
6776
  // e.g. a table only server code may touch. Applied here because grants made now would otherwise
@@ -6349,15 +6814,6 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6349
6814
  throw e instanceof Error ? e : new Error(errMsg);
6350
6815
  }
6351
6816
  }
6352
- async isSchemaNew(pool, schemaName) {
6353
- // check to see if there are any entities in the db with this schema name
6354
- // Quote the alias so PostgreSQL preserves PascalCase (unquoted aliases are lowercased in PG)
6355
- const sSQL = `SELECT COUNT(*) AS ${this.qi('Count')} FROM ${this.qs(MjCoreSchema(), 'Entity')} WHERE ${this.qi('SchemaName')} = '${schemaName}'`;
6356
- const resultResult = await this.runQuery(pool, sSQL);
6357
- const result = resultResult.recordset;
6358
- // Use Number() because PG returns COUNT(*) as bigint, which the pg driver delivers as a string
6359
- return result && result.length > 0 ? Number(result[0].Count) === 0 : true;
6360
- }
6361
6817
  /**
6362
6818
  * Creates a new application using direct SQL INSERT to ensure it's captured in SQL logging.
6363
6819
  * The Path field is auto-generated from Name using the same slug logic as MJApplicationEntityServer.
@@ -6465,17 +6921,21 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6465
6921
  }
6466
6922
  /**
6467
6923
  * Adds a newly created entity to the application(s) that match its schema name.
6468
- * If no application exists for the schema and config allows it, creates one.
6469
- * Shared by both table-backed entity creation and virtual entity creation.
6924
+ * If no application exists for the schema and config allows it, creates one. The lookup and
6925
+ * create run on every call, so a create that failed for an earlier entity is retried (#4034).
6926
+ * When the application is created after other entities of the schema already exist, those that
6927
+ * are in no application are linked to it as well.
6928
+ * Shared by table-backed, virtual and materialized-query entity creation.
6470
6929
  */
6471
6930
  async addEntityToApplicationForSchema(pool, entityId, entityName, schemaName, currentUser) {
6472
6931
  let apps = await this.getApplicationIDForSchema(pool, schemaName);
6932
+ let createdAppID = null;
6473
6933
  // If no app exists and config says to create one for new schemas, create it
6474
6934
  if ((!apps || apps.length === 0) && configInfo.newSchemaDefaults.CreateNewApplicationWithSchemaName) {
6475
6935
  const appUUID = this.createNewUUID();
6476
- const newAppID = await this.createNewApplication(pool, appUUID, schemaName, schemaName, currentUser);
6477
- if (newAppID) {
6478
- apps = [newAppID];
6936
+ createdAppID = await this.createNewApplication(pool, appUUID, schemaName, schemaName, currentUser);
6937
+ if (createdAppID) {
6938
+ apps = [createdAppID];
6479
6939
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
6480
6940
  await md.Refresh();
6481
6941
  }
@@ -6491,11 +6951,41 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6491
6951
  ('${appUUID}', '${entityId}', (SELECT COALESCE(MAX(${this.qi('Sequence')}),0)+1 FROM ${this.qs(MjCoreSchema(), 'ApplicationEntity')} WHERE ${this.qi('ApplicationID')} = '${appUUID}'), ${this.utcNow()}, ${this.utcNow()})`;
6492
6952
  await this.logSQLAndExecute(pool, sSQLInsert, `SQL generated to add entity ${entityName} to application ID: '${appUUID}'`);
6493
6953
  }
6954
+ if (createdAppID) {
6955
+ await this.linkUnassignedSchemaEntitiesToApplication(pool, createdAppID, schemaName);
6956
+ }
6494
6957
  }
6495
6958
  }
6496
6959
  else {
6497
- LogError(` >>>> WARNING: No application found for schema ${schemaName} to add entity ${entityName}`);
6960
+ LogWarning(` >>>> WARNING: Unable to add new entity ${entityName} to an application because no Application has SchemaAutoAddNewEntities='${schemaName}'. To fix this, update an existing Application record or create a new one with SchemaAutoAddNewEntities='${schemaName}'.`);
6961
+ }
6962
+ }
6963
+ /**
6964
+ * Links every entity of `schemaName` that is in no application to `appID`, numbering them after
6965
+ * the application's current last Sequence in entity-name order. Called when a schema's
6966
+ * application is created after some of its entities, e.g. after an earlier create failed or
6967
+ * while CreateNewApplicationWithSchemaName was off. Emits nothing when there is nothing to link.
6968
+ */
6969
+ async linkUnassignedSchemaEntitiesToApplication(pool, appID, schemaName) {
6970
+ const entityTable = this.qs(MjCoreSchema(), 'Entity');
6971
+ const appEntityTable = this.qs(MjCoreSchema(), 'ApplicationEntity');
6972
+ const unassigned = `FROM ${entityTable} e
6973
+ WHERE e.${this.qi('SchemaName')} = '${schemaName}'
6974
+ AND NOT EXISTS (SELECT 1 FROM ${appEntityTable} ae WHERE ae.${this.qi('EntityID')} = e.${this.qi('ID')})`;
6975
+ const countResult = await this.runQuery(pool, `SELECT COUNT(*) AS ${this.qi('Count')} ${unassigned}`);
6976
+ // PG returns COUNT(*) as bigint, which the pg driver delivers as a string
6977
+ const count = Number(countResult.recordset?.[0]?.Count ?? 0);
6978
+ if (count === 0) {
6979
+ return;
6498
6980
  }
6981
+ const sSQL = `INSERT INTO ${appEntityTable}
6982
+ (${this.qi('ApplicationID')}, ${this.qi('EntityID')}, ${this.qi('Sequence')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')})
6983
+ SELECT ${this.uuidLit(appID)}, e.${this.qi('ID')},
6984
+ (SELECT COALESCE(MAX(${this.qi('Sequence')}),0) FROM ${appEntityTable} WHERE ${this.qi('ApplicationID')} = ${this.uuidLit(appID)}) + ROW_NUMBER() OVER (ORDER BY e.${this.qi('Name')}),
6985
+ ${this.utcNow()}, ${this.utcNow()}
6986
+ ${unassigned}`;
6987
+ await this.logSQLAndExecute(pool, sSQL, `SQL generated to add the ${count} existing entities of schema ${schemaName} that are in no application to application ID: '${appID}'`);
6988
+ logStatus(` Linked ${count} existing ${schemaName} entities to the schema's new application`);
6499
6989
  }
6500
6990
  /**
6501
6991
  * INSERT for one `EntityPermission` row, skipped when a row already exists for that
@@ -6620,7 +7110,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6620
7110
  continue;
6621
7111
  const refSchema = (ref.SchemaName ?? '').trim().toLowerCase();
6622
7112
  // Skip CTE self-references (only unqualified / dbo-defaulted refs can be a CTE name).
6623
- if ((refSchema === '' || refSchema === 'dbo') && cteNames.has(ref.TableName.trim().toLowerCase()))
7113
+ if (this.isUnqualifiedRefSchema(refSchema) && cteNames.has(ref.TableName.trim().toLowerCase()))
6624
7114
  continue;
6625
7115
  // Refuse ANY under-linked entity source, not only RLS-protected ones. Both the RLS-safety check above
6626
7116
  // AND the read-grant role intersection (addMaterializedQueryEntityPermissions) are computed over the
@@ -6647,7 +7137,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6647
7137
  /** Maps a physical (schema, table/view) reference to the MJ entities backed by it — by BaseView or BaseTable,
6648
7138
  * case/whitespace-insensitive. Returns ALL candidates so the P1 guard can fail closed on an AMBIGUOUS ref.
6649
7139
  * Resolution: an explicit, non-default schema yields only that schema's exact matches; an empty schema OR the
6650
- * parser-default `'dbo'` — which {@link SQLParser.ExtractTableRefs} assigns to every UNQUALIFIED ref, while MJ
7140
+ * parser-default schema (`'dbo'`, or `'public'` on PostgreSQL) — which {@link SQLParser.ExtractTableRefs} assigns to every UNQUALIFIED ref, while MJ
6651
7141
  * core/app entities live in `__mj`/app schemas (never `dbo`) — is treated as unqualified and yields every
6652
7142
  * schema-agnostic name match. That way an unqualified reference to a `__mj`/app-schema entity is still caught,
6653
7143
  * and a same-base-name collision across schemas surfaces every candidate rather than just the first (so the
@@ -6660,13 +7150,20 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6660
7150
  const bt = (e.BaseTable ?? '').trim().toLowerCase();
6661
7151
  return bv === t || bt === t;
6662
7152
  };
6663
- if (s && s !== 'dbo') {
7153
+ if (!this.isUnqualifiedRefSchema(s)) {
6664
7154
  // Explicit, non-default schema → only that schema's entity qualifies (no cross-schema ambiguity).
6665
7155
  return md.Entities.filter((e) => (e.SchemaName ?? '').trim().toLowerCase() === s && nameMatch(e));
6666
7156
  }
6667
- // Empty schema / parser-default 'dbo' (i.e. UNQUALIFIED) → every name match across schemas is a candidate.
7157
+ // Empty schema / parser-default schema (i.e. UNQUALIFIED) → every name match across schemas is a candidate.
6668
7158
  return md.Entities.filter(nameMatch);
6669
7159
  }
7160
+ /** Whether a parsed table ref's schema (lower case) can stand for an unqualified name: empty, `dbo`, or the
7161
+ * platform's default schema (`public` on PostgreSQL), which {@link SQLParser.ExtractTableRefs} fills in for
7162
+ * every unqualified ref. Reading such a ref as unqualified widens the candidate set, the fail-closed direction. */
7163
+ isUnqualifiedRefSchema(schema) {
7164
+ const platformDefault = (this.dialect.Grammar.DefaultSchema ?? '').toLowerCase();
7165
+ return schema === '' || schema === 'dbo' || (platformDefault !== '' && schema === platformDefault);
7166
+ }
6670
7167
  /**
6671
7168
  * Grants read permissions to a newly-minted materialized QUERY entity scoped to the INTERSECTION of source
6672
7169
  * read access (C2). A precomputed snapshot has no per-row scoping, so a role may read it only if it can read
@@ -7104,7 +7601,9 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7104
7601
  e.AllowUserSearchAPI,
7105
7602
  e.AutoUpdateAllowUserSearchAPI,
7106
7603
  e.FullTextSearchEnabled,
7107
- e.AutoUpdateFullTextSearch
7604
+ e.AutoUpdateFullTextSearch,
7605
+ e.DisplayName,
7606
+ e.AutoUpdateDisplayName
7108
7607
  FROM
7109
7608
  ${this.qs(MjCoreSchema(), 'vwEntities')} e
7110
7609
  WHERE
@@ -7211,6 +7710,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7211
7710
  const batchSize = configInfo.advancedGeneration?.batchSize ?? 5;
7212
7711
  let processedCount = 0;
7213
7712
  let errorCount = 0;
7713
+ let circuitSkippedCount = 0;
7214
7714
  const total = entities.length;
7215
7715
  // Pre-group fields by EntityID once — O(total fields) — instead of a per-entity linear scan
7216
7716
  // of the full pooled array inside processEntityAdvancedGeneration (which was O(entities × fields),
@@ -7230,6 +7730,10 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7230
7730
  // Process in batches
7231
7731
  for (let i = 0; i < total; i += batchSize) {
7232
7732
  const batch = entities.slice(i, i + batchSize);
7733
+ // processEntityAdvancedGeneration returns at once while the circuit is open; count those entities.
7734
+ if (ag.AICircuitOpen) {
7735
+ circuitSkippedCount += batch.length;
7736
+ }
7233
7737
  // Process batch in parallel. entityPhase() sets the reporter's "current entity"
7234
7738
  // so any LLM calls issued by processEntityAdvancedGeneration get attributed
7235
7739
  // to the right entity. Also marks the entity as modified in the report flags.
@@ -7255,9 +7759,15 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7255
7759
  if (ag.AICircuitOpen) {
7256
7760
  const skipped = total - processedCount;
7257
7761
  UpdateSpinner(`Advanced generation: AI credential circuit open — skipping remaining ${skipped} entit${skipped === 1 ? 'y' : 'ies'} (check AI credentials).`);
7762
+ circuitSkippedCount += total - (i + batch.length);
7258
7763
  break;
7259
7764
  }
7260
7765
  }
7766
+ // The circuit skips entities without an error, so say so once: an entity left without a name
7767
+ // field may not have been analyzed at all this run (MJ issue #3608).
7768
+ if (ag.AICircuitOpen) {
7769
+ LogWarning(`Advanced generation: the AI credential circuit was open, so smart-field identification (name field, default-in-view, searchable fields) and form layout did not run for ${circuitSkippedCount} of ${total} entit${total === 1 ? 'y' : 'ies'}. Fix the AI credentials and run CodeGen again.`);
7770
+ }
7261
7771
  return errorCount === 0;
7262
7772
  }
7263
7773
  /**
@@ -7318,8 +7828,12 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7318
7828
  // Fires only on change events (new entity, new fields, reopened description/type) AND when there is work to do
7319
7829
  // (blank categories with AutoUpdateCategory=1, or reopened fields to review). Gated on events so omitted blank fields don't loop (§3.4).
7320
7830
  const hasCategoryNeeded = fields.some((f) => Boolean(f.AutoUpdateCategory) && (!f.Category || String(f.Category).trim() === ''));
7321
- const needsCategoryGeneration = (isNewEntity || hasNewFields || hasDescriptionReopened || hasTypeReopened)
7322
- && (hasCategoryNeeded || hasDescriptionReopened || hasTypeReopened);
7831
+ const needsCategoryGeneration = ManageMetadataBase.NeedsFormLayoutGeneration({
7832
+ HasChangeEvent: isNewEntity || hasNewFields || hasDescriptionReopened || hasTypeReopened,
7833
+ HasReopenedFields: hasDescriptionReopened || hasTypeReopened,
7834
+ HasBlankCategories: hasCategoryNeeded,
7835
+ BackfillRequested: configInfo.forceRegeneration?.enabled === true,
7836
+ });
7323
7837
  if (needsCategoryGeneration) {
7324
7838
  CodeGenReporter.Instance.counter('ai.formLayoutCalls');
7325
7839
  // Build IS-A parent chain context if this entity has a parent
@@ -7337,11 +7851,163 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7337
7851
  logStatus(` Applied form layout for ${entity.Name}`);
7338
7852
  }
7339
7853
  }
7854
+ // Entity Display Name Generation
7855
+ // Gated three ways: the entity must permit auto-update, the feature must
7856
+ // be on, and (unless alwaysGenerate is set) the name must still look
7857
+ // opaque after the deterministic conversion — so clean names never
7858
+ // reach the model.
7859
+ if (this.needsEntityDisplayNameGeneration(ag, entityRecord)) {
7860
+ const displayNameResult = await ag.GenerateEntityDisplayName({
7861
+ Name: entity.Name,
7862
+ SchemaName: entityRecord.SchemaName,
7863
+ BaseTable: entityRecord.BaseTable,
7864
+ Description: entity.Description,
7865
+ Fields: fields
7866
+ }, currentUser);
7867
+ if (displayNameResult) {
7868
+ await this.applyEntityDisplayName(pool, entityRecord, displayNameResult);
7869
+ }
7870
+ }
7340
7871
  }
7341
7872
  catch (ex) {
7342
7873
  logError('Error Processing Entity Advanced Generation', ex);
7343
7874
  }
7344
7875
  }
7876
+ /**
7877
+ * Decides whether an entity should be sent to the LLM for a display-name pass.
7878
+ *
7879
+ * Three independent gates, cheapest first:
7880
+ *
7881
+ * 1. `Entity.AutoUpdateDisplayName` — an administrator has locked this name.
7882
+ * 2. The feature flag itself (checked inside `GenerateEntityDisplayName` too,
7883
+ * but checked here so the opacity assessment is skipped when it is off).
7884
+ * 3. Opacity — whether the deterministic `createDisplayName()` conversion
7885
+ * already produces something readable. This is a COST filter and can be
7886
+ * turned off with the `alwaysGenerate` option; correctness does not depend
7887
+ * on it, only the token bill.
7888
+ */
7889
+ needsEntityDisplayNameGeneration(ag, entityRecord) {
7890
+ // The column is BIT/BOOLEAN over two drivers; compare loosely rather than
7891
+ // assuming `true` vs `1`.
7892
+ const autoUpdate = entityRecord.AutoUpdateDisplayName;
7893
+ const allowsAutoUpdate = autoUpdate === true || autoUpdate === 1 || autoUpdate === '1';
7894
+ if (!allowsAutoUpdate) {
7895
+ return false;
7896
+ }
7897
+ if (!ag.featureEnabled('EntityDisplayNames')) {
7898
+ return false;
7899
+ }
7900
+ if (ag.FeatureOptionBool('EntityDisplayNames', 'alwaysGenerate', false)) {
7901
+ return true;
7902
+ }
7903
+ const entityName = String(entityRecord.Name ?? '');
7904
+ const opacity = AssessDisplayNameOpacity(entityName);
7905
+ if (!opacity.IsOpaque) {
7906
+ return false;
7907
+ }
7908
+ logStatus(` Display name for ${entityName} looks opaque (${opacity.Reason}${opacity.OffendingToken ? `: "${opacity.OffendingToken}"` : ''}), requesting LLM rewrite`);
7909
+ return true;
7910
+ }
7911
+ /**
7912
+ * Writes an LLM-proposed entity display name.
7913
+ *
7914
+ * Refuses to write in three cases, each of which would otherwise make the
7915
+ * feature actively harmful rather than merely unhelpful:
7916
+ *
7917
+ * - **Not high or medium confidence.** A confidently wrong display name is worse
7918
+ * than an ugly accurate one, since nothing downstream flags it as a guess. An
7919
+ * allowlist, not a `'low'` check: a missing, null or oddly-cased confidence is
7920
+ * a model that did not answer the question, and it is treated the same way.
7921
+ * - **No change.** Skipped so the run does not report work it did not do.
7922
+ * - **Empty or over-long.** `Entity.DisplayName` is nvarchar(255); a model
7923
+ * that returns prose instead of a name is discarded rather than truncated.
7924
+ *
7925
+ * The schema prefix a name rule puts on `Entity.Name` (`CRM: ACCT_STAT_CD`) is
7926
+ * stripped from the proposal first: `DisplayName` drops it by convention (see
7927
+ * {@link createNewEntityDisplayName}), and a model that keeps it would otherwise
7928
+ * leave this one entity prefixed while its siblings are not.
7929
+ *
7930
+ * The UPDATE goes through the SQL capture like every other metadata write here,
7931
+ * so it reaches the CodeGen_Run_*.sql file that becomes the migration. A bare
7932
+ * `runQuery` would land it in this machine's database and nowhere else.
7933
+ */
7934
+ async applyEntityDisplayName(pool, entityRecord, result) {
7935
+ const entityName = String(entityRecord.Name ?? '');
7936
+ const proposed = this.stripEntityNameAffixes((result.DisplayName ?? '').trim(), String(entityRecord.SchemaName ?? ''));
7937
+ if (result.Confidence !== 'high' && result.Confidence !== 'medium') {
7938
+ logStatus(` Skipped display name for ${entityName}: confidence is ${JSON.stringify(result.Confidence ?? null)}, not high or medium ("${proposed}")`);
7939
+ return;
7940
+ }
7941
+ if (proposed.length === 0 || proposed.length > 255) {
7942
+ logStatus(` Skipped display name for ${entityName}: proposed value is empty or exceeds 255 characters`);
7943
+ return;
7944
+ }
7945
+ const current = entityRecord.DisplayName == null ? '' : String(entityRecord.DisplayName).trim();
7946
+ if (current === proposed) {
7947
+ return;
7948
+ }
7949
+ const sql = `UPDATE ${this.qs(MjCoreSchema(), 'Entity')} SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()}, ${this.qi('DisplayName')} = '${EscapeSQLString(proposed)}' WHERE ID = '${String(entityRecord.ID)}' AND ${this.qi('AutoUpdateDisplayName')} = ${this.boolLit(true)}`;
7950
+ await this.logSQLAndExecute(pool, sql, `Update display name for ${entityName}`);
7951
+ // The model's list of what it expanded is for the log only; a malformed one must not turn a
7952
+ // write that already happened into "Error Processing Entity Advanced Generation".
7953
+ const expansionList = Array.isArray(result.Expansions)
7954
+ ? result.Expansions.filter((e) => !!e && typeof e === 'object')
7955
+ : [];
7956
+ const expansions = expansionList.length ? ` [${expansionList.map(e => `${e.From}->${e.To}`).join(', ')}]` : '';
7957
+ logStatus(` Display name for ${entityName}: "${current || '(none)'}" -> "${proposed}"${expansions}`);
7958
+ }
7959
+ /**
7960
+ * Removes the prefix and suffix the entity's schema name rule adds to `Entity.Name` from a
7961
+ * proposed display name. `DisplayName` never carries them (`createNewEntityDisplayName` strips
7962
+ * them the same way), so a proposal that kept the prefix — `CRM: Account Status Codes`, or
7963
+ * `CRM:Account Status Codes` with the separator space dropped — becomes `Account Status Codes`.
7964
+ * Either affix strips only at a word boundary: under `Sales: `, `Salesforce Contacts` is a real
7965
+ * name that happens to start with the prefix's letters, and stays whole.
7966
+ * Without a rule, or when stripping would leave nothing, the proposal is returned as given.
7967
+ */
7968
+ stripEntityNameAffixes(proposed, schemaName) {
7969
+ const rule = schemaName ? this.getNewEntityNameRule(schemaName) : undefined;
7970
+ if (!rule) {
7971
+ return proposed;
7972
+ }
7973
+ let name = proposed.trim();
7974
+ // The rule's prefix is typically "CRM: "; match its core ("CRM") followed by any separator the
7975
+ // model kept or dropped, so both spellings above strip.
7976
+ const prefixCore = (rule.EntityNamePrefix ?? '').trim().replace(/[\s:]+$/, '');
7977
+ if (prefixCore.length > 0 && name.startsWith(prefixCore)
7978
+ && ManageMetadataBase.isWordBoundary(prefixCore.charAt(prefixCore.length - 1), name.charAt(prefixCore.length))) {
7979
+ name = name.substring(prefixCore.length).replace(/^[\s:]+/, '').trim();
7980
+ }
7981
+ const suffix = (rule.EntityNameSuffix ?? '').trim();
7982
+ if (suffix.length > 0 && name.endsWith(suffix)
7983
+ && ManageMetadataBase.isWordBoundary(name.charAt(name.length - suffix.length - 1), suffix.charAt(0))) {
7984
+ name = name.substring(0, name.length - suffix.length).trim();
7985
+ }
7986
+ return name.length > 0 ? name : proposed.trim();
7987
+ }
7988
+ /**
7989
+ * True when two adjacent characters do not both belong to one word, so an affix may end (or
7990
+ * begin) between them. An empty side is a boundary: the affix met the end of the name.
7991
+ */
7992
+ static isWordBoundary(left, right) {
7993
+ const wordChar = /[\p{L}\p{N}_]/u;
7994
+ return !(left.length > 0 && right.length > 0 && wordChar.test(left) && wordChar.test(right));
7995
+ }
7996
+ /**
7997
+ * Decides whether the form-layout (category) pass runs for an entity. It needs work to do (blank
7998
+ * categories with AutoUpdateCategory=1, or reopened fields) AND a reason to look: a change event
7999
+ * (new entity, new fields, reopened description or type), or an explicit backfill request.
8000
+ *
8001
+ * The change-event gate keeps a field the LLM keeps omitting from re-triggering the pass on every
8002
+ * run. It also meant a field left blank by an earlier run (advanced generation off, or omitted by
8003
+ * the LLM) was never categorized by any later run (#4831). `forceRegeneration.enabled`, which
8004
+ * `mj codegen --force-advanced-gen` sets, is that explicit request: it backfills blank categories
8005
+ * without making the automatic path loop.
8006
+ */
8007
+ static NeedsFormLayoutGeneration(state) {
8008
+ const hasWork = state.HasBlankCategories || state.HasReopenedFields;
8009
+ return hasWork && (state.HasChangeEvent || (state.BackfillRequested && state.HasBlankCategories));
8010
+ }
7345
8011
  /**
7346
8012
  * Builds IS-A parent chain context for an entity, computing which parent each
7347
8013
  * inherited field originates from. Used to provide the LLM with inheritance
@@ -7568,8 +8234,14 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7568
8234
  }
7569
8235
  }
7570
8236
  const winner = this.selectNameFieldWinner(fields, nameFieldNames);
7571
- // Set the winner when it isn't flagged yet (and auto-update is allowed).
8237
+ const entityName = entity?.Name ?? '(unknown entity)';
8238
+ if (!winner) {
8239
+ logStatus(` Name field: no eligible name field for ${entityName}; it has no name field after this run`);
8240
+ }
8241
+ // Set the winner when it isn't flagged yet (and auto-update is allowed). An unflagged winner
8242
+ // can only come from step 3, the AI's ranked candidates, so the pick is logged (MJ issue #3608).
7572
8243
  if (winner && winner.AutoUpdateIsNameField && winner.ID && !winner.IsNameField) {
8244
+ logStatus(` Name field: set ${entityName}.${String(winner.Name)} as the name field (AI pick; no eligible field was flagged)`);
7573
8245
  sqlStatements.push(`
7574
8246
  UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
7575
8247
  SET IsNameField = ${this.boolLit(true)}
@@ -7662,8 +8334,36 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7662
8334
  isFieldEligibleForNameField(field) {
7663
8335
  if (field.IsVirtual === true && !this.isInheritedISAField(field))
7664
8336
  return false;
8337
+ if (this.isForeignKeyOrPolymorphicRecordIDField(field))
8338
+ return false;
7665
8339
  return this.isNameFieldTypeSafe(field);
7666
8340
  }
8341
+ /**
8342
+ * Rejects foreign-key columns (`RelatedEntityID`) and polymorphic record-ID
8343
+ * payload columns (`EntityIDFieldName` populated, or named `*RecordID` /
8344
+ * `*RecordPrimaryKey` such as `RecordID`, `SourceRecordID`, `TargetRecordID`,
8345
+ * `LinkedRecordID`, `SurvivingRecordID`) from being selected as `IsNameField`.
8346
+ *
8347
+ * Polymorphic `RecordID` columns use `nvarchar(450)` / `nvarchar(750)` so they
8348
+ * can hold composite primary keys or non-UUID strings, which previously tricked
8349
+ * Smart Field Identification into treating them as human-readable text names
8350
+ * and displaying raw UUIDs in tab headers, breadcrumbs, and link cards.
8351
+ */
8352
+ isForeignKeyOrPolymorphicRecordIDField(field) {
8353
+ const relatedEntityId = field.RelatedEntityID;
8354
+ if (relatedEntityId && String(relatedEntityId).trim().length > 0) {
8355
+ return true;
8356
+ }
8357
+ const entityIdFieldName = field.EntityIDFieldName;
8358
+ if (entityIdFieldName && String(entityIdFieldName).trim().length > 0) {
8359
+ return true;
8360
+ }
8361
+ const name = (field.Name ?? '').trim();
8362
+ if (/^(?:[A-Z][A-Za-z0-9]*?)?Record(?:ID|PrimaryKey)$/.test(name)) {
8363
+ return true;
8364
+ }
8365
+ return false;
8366
+ }
7667
8367
  /**
7668
8368
  * The TYPE half of {@link isFieldEligibleForNameField}, with no virtuality
7669
8369
  * opinion: a primary key, a non-text type, or unbounded (MAX) text can never be
@@ -7709,10 +8409,53 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7709
8409
  */
7710
8410
  isInheritedISAField(field) {
7711
8411
  const name = field.Name ?? '';
7712
- return field.IsVirtual === true
7713
- && field.AllowUpdateAPI === true
7714
- && field.IsPrimaryKey !== true
7715
- && !name.startsWith('__mj_');
8412
+ if (field.IsVirtual !== true || field.IsPrimaryKey === true || name.startsWith('__mj_')) {
8413
+ return false;
8414
+ }
8415
+ if (field.AllowUpdateAPI === true) {
8416
+ return true;
8417
+ }
8418
+ // Second arm (#5899): the child's mirror of a parent's COMPUTED column (`IsVirtual = 1,
8419
+ // IsComputed = 1` on the parent, e.g. a persisted `DisplayName`). It is read-only everywhere,
8420
+ // so it arrives through the child's view as an ordinary view column with AllowUpdateAPI = 0,
8421
+ // but it is a real column on the parent's table and as good a display value as any inherited
8422
+ // plain column.
8423
+ const entityID = field.EntityID;
8424
+ return !!entityID && this.inheritedComputedFieldNames(entityID).has(name.trim().toLowerCase());
8425
+ }
8426
+ /**
8427
+ * Lower-cased names of the computed columns (`IsVirtual = 1 AND IsComputed = 1`, not a PK, not
8428
+ * an `__mj_` column) on every entity in the IS-A parent chain of `entityID`. Empty for an entity
8429
+ * with no parent, or when metadata is unavailable. Memoized per entity: the smart-field pass asks
8430
+ * once per field. The memo resets when the loaded entity list changes (a metadata refresh).
8431
+ */
8432
+ inheritedComputedFieldNames(entityID) {
8433
+ let entities;
8434
+ try {
8435
+ entities = new Metadata().Entities; // global-provider-ok: codegen runs offline against a single provider
8436
+ }
8437
+ catch {
8438
+ return new Set(); // No metadata provider: nothing is known to be inherited.
8439
+ }
8440
+ if (this._inheritedComputedSource !== entities) {
8441
+ this._inheritedComputedSource = entities;
8442
+ this._inheritedComputedNames.Clear();
8443
+ }
8444
+ const cached = this._inheritedComputedNames.Get(entityID);
8445
+ if (cached) {
8446
+ return cached;
8447
+ }
8448
+ const names = new Set();
8449
+ const entity = (entities ?? []).find(e => UUIDsEqual(e.ID, entityID));
8450
+ for (const parent of entity?.ParentChain ?? []) {
8451
+ for (const f of parent.Fields) {
8452
+ if (f.IsVirtual && f.IsComputed && !f.IsPrimaryKey && !f.Name.startsWith('__mj_')) {
8453
+ names.add(f.Name.trim().toLowerCase());
8454
+ }
8455
+ }
8456
+ }
8457
+ this._inheritedComputedNames.Set(entityID, names);
8458
+ return names;
7716
8459
  }
7717
8460
  /**
7718
8461
  * Generate SQL UPDATEs for DefaultInView on the identified default view fields
@@ -8425,27 +9168,30 @@ WHERE
8425
9168
  }
8426
9169
  /**
8427
9170
  * Upserts FieldCategoryInfo (new format) and FieldCategoryIcons (legacy format) in EntitySetting.
9171
+ *
9172
+ * The incoming map is MERGED into what is stored, never written over it (#5369). For an existing
9173
+ * entity the LLM describes only the categories of the fields it was shown (the new ones), so a
9174
+ * replace dropped every other category's icon and description, and with them the IS-A
9175
+ * `inheritedFromEntity*` markers the generated form reads. See {@link MergeFieldCategoryInfo}.
8428
9176
  */
8429
9177
  async applyCategoryInfoSettings(pool, entityId, categoryInfo, _entityName) {
8430
9178
  if (!categoryInfo || Object.keys(categoryInfo).length === 0)
8431
9179
  return;
8432
- const canonicalInfo = CanonicalJSONStringify(categoryInfo, 2);
8433
- const infoJSON = canonicalInfo.replace(/'/g, "''");
8434
9180
  const ENTITY_SETTING_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
8435
9181
  // Upsert FieldCategoryInfo (new format)
8436
9182
  const checkNewSQL = `SELECT ${this.qi('ID')}, ${this.qi('Value')} FROM ${this.qs(MjCoreSchema(), 'EntitySetting')} WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryInfo'`;
8437
9183
  const existingNew = await this.runQuery(pool, checkNewSQL);
9184
+ // What the LEGACY setting gets written from: the merged map when the stored value could be read,
9185
+ // otherwise the incoming map (the same thing it was written from before merging existed).
9186
+ let infoToStore = categoryInfo;
8438
9187
  if (existingNew.recordset.length > 0) {
8439
- let isMatch = false;
8440
- try {
8441
- const rawVal = existingNew.recordset[0].Value;
8442
- const parsed = typeof rawVal === 'string' ? JSON.parse(rawVal) : rawVal;
8443
- isMatch = DeepEqualJSON(parsed, categoryInfo);
8444
- }
8445
- catch {
8446
- isMatch = false;
8447
- }
9188
+ const stored = ManageMetadataBase.ParseStoredSettingObject(existingNew.recordset[0].Value);
9189
+ // An unreadable stored value is overwritten with the incoming map, as it was before merging:
9190
+ // there is nothing in it to keep.
9191
+ infoToStore = stored ? ManageMetadataBase.MergeFieldCategoryInfo(stored, categoryInfo) : categoryInfo;
9192
+ const isMatch = stored !== null && DeepEqualJSON(stored, infoToStore);
8448
9193
  if (!isMatch) {
9194
+ const infoJSON = CanonicalJSONStringify(infoToStore, 2).replace(/'/g, "''");
8449
9195
  try {
8450
9196
  await this.logSQLAndExecute(pool, `
8451
9197
  UPDATE ${this.qs(MjCoreSchema(), 'EntitySetting')}
@@ -8459,6 +9205,7 @@ WHERE
8459
9205
  }
8460
9206
  }
8461
9207
  else {
9208
+ const infoJSON = CanonicalJSONStringify(categoryInfo, 2).replace(/'/g, "''");
8462
9209
  const newId = uuidv5(`${entityId}|FieldCategoryInfo`, ENTITY_SETTING_NAMESPACE);
8463
9210
  try {
8464
9211
  const checkQuery = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntitySetting')} WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryInfo'`;
@@ -8473,26 +9220,20 @@ WHERE
8473
9220
  }
8474
9221
  // Also upsert legacy FieldCategoryIcons for backwards compatibility
8475
9222
  const iconsOnly = {};
8476
- for (const [category, info] of Object.entries(categoryInfo)) {
9223
+ for (const [category, info] of Object.entries(infoToStore)) {
8477
9224
  if (info && typeof info === 'object' && 'icon' in info) {
8478
9225
  iconsOnly[category] = info.icon;
8479
9226
  }
8480
9227
  }
8481
- const canonicalIcons = CanonicalJSONStringify(iconsOnly, 2);
8482
- const iconsJSON = canonicalIcons.replace(/'/g, "''");
8483
9228
  const checkLegacySQL = `SELECT ${this.qi('ID')}, ${this.qi('Value')} FROM ${this.qs(MjCoreSchema(), 'EntitySetting')} WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryIcons'`;
8484
9229
  const existingLegacy = await this.runQuery(pool, checkLegacySQL);
8485
9230
  if (existingLegacy.recordset.length > 0) {
8486
- let isMatch = false;
8487
- try {
8488
- const rawVal = existingLegacy.recordset[0].Value;
8489
- const parsed = typeof rawVal === 'string' ? JSON.parse(rawVal) : rawVal;
8490
- isMatch = DeepEqualJSON(parsed, iconsOnly);
8491
- }
8492
- catch {
8493
- isMatch = false;
8494
- }
9231
+ const storedIcons = ManageMetadataBase.ParseStoredSettingObject(existingLegacy.recordset[0].Value);
9232
+ // Same merge rule: a category only the legacy setting knows keeps its icon.
9233
+ const iconsToStore = storedIcons ? { ...storedIcons, ...iconsOnly } : iconsOnly;
9234
+ const isMatch = storedIcons !== null && DeepEqualJSON(storedIcons, iconsToStore);
8495
9235
  if (!isMatch) {
9236
+ const iconsJSON = CanonicalJSONStringify(iconsToStore, 2).replace(/'/g, "''");
8496
9237
  try {
8497
9238
  await this.logSQLAndExecute(pool, `
8498
9239
  UPDATE ${this.qs(MjCoreSchema(), 'EntitySetting')}
@@ -8506,6 +9247,7 @@ WHERE
8506
9247
  }
8507
9248
  }
8508
9249
  else {
9250
+ const iconsJSON = CanonicalJSONStringify(iconsOnly, 2).replace(/'/g, "''");
8509
9251
  const newId = uuidv5(`${entityId}|FieldCategoryIcons`, ENTITY_SETTING_NAMESPACE);
8510
9252
  try {
8511
9253
  const checkQuery = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntitySetting')} WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryIcons'`;
@@ -8519,6 +9261,48 @@ WHERE
8519
9261
  }
8520
9262
  }
8521
9263
  }
9264
+ /**
9265
+ * Merges an incoming FieldCategoryInfo map into the stored one (#5369):
9266
+ * - a category only the stored map has is kept as it is;
9267
+ * - a category only the incoming map has is added;
9268
+ * - a category both have keeps its stored properties and takes each property the incoming entry
9269
+ * sets. So an LLM entry that redescribes an inherited category (icon and description only)
9270
+ * does not drop its `inheritedFromEntityID` / `inheritedFromEntityName`.
9271
+ * Neither input is modified.
9272
+ */
9273
+ static MergeFieldCategoryInfo(stored, incoming) {
9274
+ const merged = { ...stored };
9275
+ for (const [category, info] of Object.entries(incoming)) {
9276
+ const existing = merged[category];
9277
+ merged[category] = existing && typeof existing === 'object' && info && typeof info === 'object'
9278
+ ? { ...existing, ...ManageMetadataBase.withoutUndefined(info) }
9279
+ : info;
9280
+ }
9281
+ return merged;
9282
+ }
9283
+ /** A copy of `info` without the keys whose value is undefined, so a spread does not erase them. */
9284
+ static withoutUndefined(info) {
9285
+ const out = {};
9286
+ for (const [key, value] of Object.entries(info)) {
9287
+ if (value !== undefined) {
9288
+ out[key] = value;
9289
+ }
9290
+ }
9291
+ return out;
9292
+ }
9293
+ /**
9294
+ * Parses an EntitySetting value holding a JSON object. Returns null for anything that is not a
9295
+ * JSON object (unparseable text, an array, a scalar), so the caller treats it as unreadable.
9296
+ */
9297
+ static ParseStoredSettingObject(rawValue) {
9298
+ try {
9299
+ const parsed = typeof rawValue === 'string' ? JSON.parse(rawValue) : rawValue;
9300
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
9301
+ }
9302
+ catch {
9303
+ return null;
9304
+ }
9305
+ }
8522
9306
  /**
8523
9307
  * Applies entity importance analysis to MJApplicationEntity records.
8524
9308
  * Only called for NEW entities to set DefaultForNewUser.