@memberjunction/codegen-lib 6.2.0-edge.6 → 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 (85) 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 +175 -0
  7. package/dist/Config/config.d.ts.map +1 -1
  8. package/dist/Config/config.js +142 -84
  9. package/dist/Config/config.js.map +1 -1
  10. package/dist/Database/codeGenDatabaseProvider.d.ts +14 -0
  11. package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
  12. package/dist/Database/codeGenDatabaseProvider.js +37 -3
  13. package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
  14. package/dist/Database/manage-metadata.d.ts +258 -18
  15. package/dist/Database/manage-metadata.d.ts.map +1 -1
  16. package/dist/Database/manage-metadata.js +683 -179
  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/__tests__/MetadataSupportObjectsDDL.test.js +9 -5
  37. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js.map +1 -1
  38. package/dist/Database/providers/postgresql/metadataSupportObjects.js +244 -84
  39. package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
  40. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +8 -0
  41. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
  42. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +19 -1
  43. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
  44. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js +66 -0
  45. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js.map +1 -1
  46. package/dist/Database/queryRebindPass.d.ts +37 -0
  47. package/dist/Database/queryRebindPass.d.ts.map +1 -0
  48. package/dist/Database/queryRebindPass.js +110 -0
  49. package/dist/Database/queryRebindPass.js.map +1 -0
  50. package/dist/Database/schema-scope.d.ts +12 -0
  51. package/dist/Database/schema-scope.d.ts.map +1 -1
  52. package/dist/Database/schema-scope.js +15 -0
  53. package/dist/Database/schema-scope.js.map +1 -1
  54. package/dist/Database/sql_codegen.d.ts +74 -2
  55. package/dist/Database/sql_codegen.d.ts.map +1 -1
  56. package/dist/Database/sql_codegen.js +181 -20
  57. package/dist/Database/sql_codegen.js.map +1 -1
  58. package/dist/Misc/advanced_generation.d.ts +129 -5
  59. package/dist/Misc/advanced_generation.d.ts.map +1 -1
  60. package/dist/Misc/advanced_generation.js +212 -8
  61. package/dist/Misc/advanced_generation.js.map +1 -1
  62. package/dist/Misc/display-name-heuristics.d.ts +57 -0
  63. package/dist/Misc/display-name-heuristics.d.ts.map +1 -0
  64. package/dist/Misc/display-name-heuristics.js +97 -0
  65. package/dist/Misc/display-name-heuristics.js.map +1 -0
  66. package/dist/Misc/entity_subclasses_codegen.d.ts +31 -3
  67. package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
  68. package/dist/Misc/entity_subclasses_codegen.js +79 -17
  69. package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
  70. package/dist/Misc/remote_operations_codegen.d.ts.map +1 -1
  71. package/dist/Misc/remote_operations_codegen.js +21 -4
  72. package/dist/Misc/remote_operations_codegen.js.map +1 -1
  73. package/dist/Misc/sql_logging.d.ts +12 -0
  74. package/dist/Misc/sql_logging.d.ts.map +1 -1
  75. package/dist/Misc/sql_logging.js +21 -8
  76. package/dist/Misc/sql_logging.js.map +1 -1
  77. package/dist/Misc/validator-text.d.ts +17 -0
  78. package/dist/Misc/validator-text.d.ts.map +1 -1
  79. package/dist/Misc/validator-text.js +59 -0
  80. package/dist/Misc/validator-text.js.map +1 -1
  81. package/dist/runCodeGen.d.ts +16 -0
  82. package/dist/runCodeGen.d.ts.map +1 -1
  83. package/dist/runCodeGen.js +47 -7
  84. package/dist/runCodeGen.js.map +1 -1
  85. 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';
@@ -15,15 +15,16 @@ import { CodeNameFromString, EntityFieldInfo, EntityInfo, ExternalDataSourceRead
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);
@@ -1671,12 +1700,7 @@ export class ManageMetadataBase {
1671
1700
  // Joins/multi-table sources can't be localized by one watermark → keep FullRebuild (§10 bias).
1672
1701
  // Among eligible ones, a PURELY ADDITIVE aggregation (only SUM/COUNT) uses the MERGE-upsert
1673
1702
  // 'Incremental' path (in-place, no row churn); non-additive uses 'DirtyGroupRecompute' (delete+insert).
1674
- const isKeyedSingleSource = isKeyed && !!detectSQL && SQLParser.ExtractTableRefs(detectSQL, matDialect).length === 1;
1675
- const refreshStrategy = !isKeyedSingleSource
1676
- ? 'FullRebuild'
1677
- : DetectAdditiveMeasures(detectSQL)
1678
- ? 'Incremental'
1679
- : 'DirtyGroupRecompute';
1703
+ const refreshStrategy = ChooseMaterializationRefreshStrategy({ sql: detectSQL, dialect: matDialect, isKeyed });
1680
1704
  // RLS downgrade gate (§6.2, ships day one) — a materialized query entity does NOT inherit its
1681
1705
  // source entities' row-level security. Refuse to materialize when RLS-safety cannot be proven, to
1682
1706
  // prevent a silent privilege escalation. Asymmetric risk (§10): over-restriction is harmless; the
@@ -2107,32 +2131,15 @@ export class ManageMetadataBase {
2107
2131
  // compiled into excludeSchemas. Heal EXEC statements use that original list plus
2108
2132
  // @IncludedSchemaNames — never the sibling snapshot of this machine's database.
2109
2133
  SnapshotAuthoredExcludeSchemas(configInfo.excludeSchemas);
2110
- // Resolve the opt-in `includeSchemas` positive scope into excludeSchemas, BEFORE the exclude
2111
- // snapshot below and before createNewEntities() runs. The universe is queried from the DATABASE
2112
- // rather than taken from loaded metadata on purpose: createNewEntities() discovers tables with no
2113
- // EntityID straight from the database, so a schema MJ has never seen — the exact case an include
2114
- // list exists to protect against, e.g. a client's own schemas in a deployed instance — is absent
2115
- // from Metadata.Entities and would otherwise be adopted on the first run (and then excluded on
2116
- // every run after, orphaning its entity records). No-op when includeSchemas is unset.
2117
- if (configInfo.includeSchemas && configInfo.includeSchemas.length > 0) {
2118
- try {
2119
- const schemaSQL = `SELECT DISTINCT ${this.qi('SchemaName')} FROM ${this.qs(MjCoreSchema(), 'vwSQLTablesAndEntities')}`;
2120
- const schemaResult = await this.runQuery(pool, schemaSQL);
2121
- const allSchemas = (schemaResult.recordset ?? [])
2122
- .map((r) => r.SchemaName)
2123
- .filter((s) => !!s);
2124
- const newlyExcluded = ApplyIncludeSchemaScope(allSchemas, configInfo);
2125
- logStatus(` Applied includeSchemas scope [${configInfo.includeSchemas.join(', ')}] — excluded ${newlyExcluded.length} other schema(s) present in the database`);
2126
- }
2127
- catch (e) {
2128
- // Proceeding would let CodeGen traverse schemas the include list was meant to keep it off,
2129
- // which can create entity metadata for another app's (or a client's) tables. Fail instead.
2130
- logError(` Error resolving includeSchemas scope: ${e instanceof Error ? e.message : e}`);
2131
- return false;
2132
- }
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;
2133
2140
  }
2134
2141
  const excludeSchemas = configInfo.excludeSchemas ? [...configInfo.excludeSchemas] : [];
2135
- let bSuccess = true;
2142
+ let bSuccess = includeScope;
2136
2143
  let start = new Date();
2137
2144
  // Very early FK check - before any operations
2138
2145
  // Load SchemaInfo records early so that EntityNamePrefix/Suffix rules from the
@@ -2311,6 +2318,45 @@ export class ManageMetadataBase {
2311
2318
  await this.checkEntityFieldSequenceIntegrity(pool, excludeSchemas);
2312
2319
  return bSuccess;
2313
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
+ }
2314
2360
  /**
2315
2361
  * One-time upgrade step for #5976. Before 6.1, CodeGen projected a `Root<Field>` column for every
2316
2362
  * self-referencing foreign key; 6.1 made that opt-in through `Configuration.Hierarchy.IsHierarchy`.
@@ -3199,8 +3245,10 @@ export class ManageMetadataBase {
3199
3245
  if (!field) {
3200
3246
  continue;
3201
3247
  }
3202
- // Skip if field already has a FK set (config-defined takes precedence)
3203
- 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)) {
3204
3252
  continue;
3205
3253
  }
3206
3254
  // Look up the related entity by name
@@ -3209,11 +3257,14 @@ export class ManageMetadataBase {
3209
3257
  logStatus(` ⚠️ LLM FK: related entity '${fk.relatedEntityName}' not found for ${entity.Name}.${fk.fieldName}`);
3210
3258
  continue;
3211
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.
3212
3262
  sqlStatements.push(`UPDATE ${this.qs(schema, 'EntityField')}
3213
3263
  SET RelatedEntityID='${relatedEntity.ID}',
3214
- RelatedEntityFieldName='${fk.relatedFieldName}',
3215
- IsSoftForeignKey=1
3216
- 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)}`);
3217
3268
  logStatus(` ✓ Set FK for ${entity.Name}.${field.Name} → ${fk.relatedEntityName}.${fk.relatedFieldName} (${fk.confidence}, LLM)`);
3218
3269
  }
3219
3270
  if (sqlStatements.length === 0) {
@@ -3222,6 +3273,18 @@ export class ManageMetadataBase {
3222
3273
  await this.logSQLBatchAndExecute(pool, sqlStatements, `Set LLM-identified FKs for ${entity.Name}`);
3223
3274
  return true;
3224
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
+ }
3225
3288
  /**
3226
3289
  * Applies LLM-generated field descriptions to entity fields that lack descriptions.
3227
3290
  * All SQL updates are batched into a single execution for performance.
@@ -3644,8 +3707,8 @@ export class ManageMetadataBase {
3644
3707
  // NOTE: Stale relationship cleanup is intentionally NOT done here because this
3645
3708
  // method runs BEFORE deleteUnneededEntityFields(). Stale EntityField records
3646
3709
  // (for dropped columns) still exist at this point and would prevent detection
3647
- // of stale relationships. The cleanup is handled by cleanupStaleEntityRelationships()
3648
- // 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).
3649
3712
  return true;
3650
3713
  }
3651
3714
  catch (e) {
@@ -3687,7 +3750,14 @@ export class ManageMetadataBase {
3687
3750
  const entityKeyField = this.resolveRelationshipEntityKeyField(f, parentEntity);
3688
3751
  const keyFieldColumn = entityKeyField ? `, ${this.qi('EntityKeyField')}` : '';
3689
3752
  const keyFieldValue = entityKeyField ? `, '${entityKeyField.replace(/'/g, "''")}'` : '';
3690
- 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);
3691
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')})
3692
3762
  VALUES ('${newEntityRelationshipUUID}', '${f.RelatedEntityID}', '${f.EntityID}', '${f.Name}'${keyFieldValue}, 'One To Many', ${this.boolLit(true)}, ${this.boolLit(true)}, ${sequence}, ${this.utcNow()}, ${this.utcNow()})`;
3693
3763
  relationshipCountMap.set(parentEntityID, sequence);
@@ -3696,6 +3766,16 @@ export class ManageMetadataBase {
3696
3766
  ${this.dbProvider.conditionalInsertSQL(checkQuery, insertSQL)};
3697
3767
  `;
3698
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
+ }
3699
3779
  /**
3700
3780
  * Resolves the `EntityRelationship.EntityKeyField` value for a discovered FK field, or `null`
3701
3781
  * when the relationship joins the parent's primary key and the column therefore must stay NULL.
@@ -3879,28 +3959,43 @@ export class ManageMetadataBase {
3879
3959
  return sql;
3880
3960
  }
3881
3961
  /**
3882
- * Public entry point for cleaning up stale EntityRelationship records. This must be called
3883
- * AFTER deleteUnneededEntityFields() has run, so that stale EntityField records (for dropped
3884
- * columns) are removed before we check which relationships are still valid.
3885
- * 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.
3886
3982
  * @param pool - database connection
3887
- * @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.
3888
3986
  */
3889
- async CleanupStaleEntityRelationships(pool, excludeSchemas) {
3987
+ async CleanupStaleEntityRelationships(pool, excludeSchemas, options = {}) {
3988
+ const dryRun = options.DryRun !== false;
3989
+ this._staleRelationshipsRemoved = 0;
3890
3990
  try {
3891
- const sSQL = `SELECT *
3892
- FROM ${this.qs(MjCoreSchema(), 'vwEntityFields')}
3893
- WHERE
3894
- RelatedEntityID IS NOT NULL AND
3895
- IsVirtual = ${this.boolLit(false)} AND
3896
- EntityID NOT IN (SELECT ID FROM ${this.qs(MjCoreSchema(), 'Entity')} WHERE SchemaName IN (${excludeSchemas.map(s => `'${s}'`).join(',')}))
3897
- ORDER BY RelatedEntityID, EntityID, Sequence, ID`;
3898
- const entityFieldsResult = await this.runQuery(pool, sSQL);
3899
- const entityFields = entityFieldsResult.recordset;
3900
- const sSQLRelationship = `SELECT * FROM ${this.qs(MjCoreSchema(), 'EntityRelationship')}`;
3901
- const allRelationshipsResult = await this.runQuery(pool, sSQLRelationship);
3902
- const allRelationships = allRelationshipsResult.recordset;
3903
- 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);
3904
3999
  return true;
3905
4000
  }
3906
4001
  catch (e) {
@@ -3908,43 +4003,94 @@ export class ManageMetadataBase {
3908
4003
  return false;
3909
4004
  }
3910
4005
  }
4006
+ /** Rows the last {@link CleanupStaleEntityRelationships} call deleted (always 0 on a dry run). */
4007
+ get StaleRelationshipsRemoved() {
4008
+ return this._staleRelationshipsRemoved;
4009
+ }
3911
4010
  /** @deprecated Use {@link CleanupStaleEntityRelationships}. */
3912
- async cleanupStaleEntityRelationships(pool, excludeSchemas) {
3913
- return this.CleanupStaleEntityRelationships(pool, excludeSchemas);
4011
+ async cleanupStaleEntityRelationships(pool, excludeSchemas, options = {}) {
4012
+ return this.CleanupStaleEntityRelationships(pool, excludeSchemas, options);
3914
4013
  }
3915
4014
  /**
3916
- * Removes stale One-To-Many EntityRelationship records whose RelatedEntityJoinField no longer
3917
- * corresponds to a valid FK field in the database. Only removes relationships where
3918
- * 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
3919
4019
  */
3920
- async removeStaleOneToManyRelationships(pool, allRelationships, entityFields) {
3921
- // Build a set of valid (ParentEntityID, ChildEntityID, JoinFieldName) tuples from current FK fields.
3922
- // In EntityRelationship terms: EntityID = ParentEntityID (the "one" side), RelatedEntityID = ChildEntityID (the "many" side)
3923
- // In entityFields: f.RelatedEntityID = ParentEntityID, f.EntityID = ChildEntityID, f.Name = FK field name
3924
- const validRelationshipKeys = new Set();
3925
- for (const f of entityFields) {
3926
- 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;
3927
4068
  }
3928
- const staleRelationships = allRelationships.filter(r => String(r.Type).trim() === 'One To Many' &&
3929
- r.AutoUpdateFromSchema === true &&
3930
- !validRelationshipKeys.has(`${r.EntityID}|${r.RelatedEntityID}|${r.RelatedEntityJoinField}`));
3931
- if (staleRelationships.length > 0) {
3932
- let deleteSQL = '';
4069
+ if (dryRun) {
3933
4070
  for (const r of staleRelationships) {
3934
- logStatus(` > Removing stale EntityRelationship: ${r.Entity} -> ${r.RelatedEntity} via '${r.RelatedEntityJoinField}' (ID: ${r.ID})`);
3935
- deleteSQL += `
3936
- /* 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) */
3937
4081
  DELETE FROM ${this.qs(MjCoreSchema(), 'EntityRelationship')} WHERE ${this.qi('ID')} = '${r.ID}';
3938
4082
  `;
3939
- }
3940
- await this.logSQLAndExecute(pool, deleteSQL, 'Remove stale One-To-Many EntityRelationships');
3941
4083
  }
4084
+ await this.logSQLAndExecute(pool, deleteSQL, 'Remove stale One-To-Many EntityRelationships');
4085
+ return staleRelationships.length;
3942
4086
  }
3943
4087
  /**
3944
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
3945
4089
  * should be removed. This method is called as part of the manageMetadata method and is not intended to be called directly.
3946
4090
  * @param ds
3947
- * @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".
3948
4094
  */
3949
4095
  async checkAndRemoveMetadataForDeletedTables(pool, excludeSchemas) {
3950
4096
  try {
@@ -4228,6 +4374,8 @@ export class ManageMetadataBase {
4228
4374
  // Non-fatal: soft value-lists are supplementary
4229
4375
  }
4230
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);
4231
4379
  }
4232
4380
  // Advanced Generation - Smart field identification and form layout
4233
4381
  if (!skipAdvancedGeneration) {
@@ -4422,6 +4570,7 @@ export class ManageMetadataBase {
4422
4570
  const entityId = entityResult.recordset[0].ID;
4423
4571
  const primaryKeys = table.PrimaryKey || [];
4424
4572
  totalPKs += await this.applySoftPrimaryKeys(pool, table, entityId, clearUniqueOnCompositeKey && primaryKeys.length > 1);
4573
+ totalPKs += await this.retractUndeclaredSoftPrimaryKeys(pool, table, entityId);
4425
4574
  resolved.push({ table, entityId });
4426
4575
  }
4427
4576
  for (const { table, entityId } of resolved) {
@@ -4561,6 +4710,58 @@ export class ManageMetadataBase {
4561
4710
  }
4562
4711
  return written;
4563
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
+ }
4564
4765
  /**
4565
4766
  * Sets RelatedEntityID, RelatedEntityFieldName and IsSoftForeignKey = 1 on each configured foreign
4566
4767
  * key column. RelatedEntityID is the source of truth, IsSoftForeignKey protects it from schema sync.
@@ -4729,6 +4930,40 @@ export class ManageMetadataBase {
4729
4930
  logStatus(` ✓ Applied soft value-list for ${tableName}.${fieldCfg.FieldName} (${sortedValues.length} values, type=${newType})`);
4730
4931
  return 'applied';
4731
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
+ }
4732
4967
  /**
4733
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.
4734
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
@@ -5269,6 +5504,9 @@ export class ManageMetadataBase {
5269
5504
  ManageMetadataBase.addNewEntitiesToModifiedList(changes.map(c => c.entityName));
5270
5505
  for (const c of changes) {
5271
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
+ }
5272
5510
  ManageMetadataBase._changedFieldReport.push({
5273
5511
  entityName: c.entityName,
5274
5512
  fieldName: c.fieldName,
@@ -5553,6 +5791,9 @@ export class ManageMetadataBase {
5553
5791
  const prunedEntityNames = this.distinctPrunedEntityNames(result);
5554
5792
  if (prunedEntityNames.length > 0) {
5555
5793
  ManageMetadataBase.addNewEntitiesToModifiedList(prunedEntityNames);
5794
+ for (const entityName of prunedEntityNames) {
5795
+ ManageMetadataBase.RegisterFieldShapeChange({ EntityName: entityName });
5796
+ }
5556
5797
  }
5557
5798
  return { success: true, prunedEntityNames };
5558
5799
  }
@@ -5822,6 +6063,16 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
5822
6063
  return returnResult;
5823
6064
  }
5824
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
+ }
5825
6076
  async syncEntityFieldValues(ds, entityFieldID, possibleValues, allEntityFieldValues) {
5826
6077
  try {
5827
6078
  // first, get a list of all of the existing entity field values for the field already in the database
@@ -5845,11 +6096,13 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
5845
6096
  if (!existingValues.find((ev) => ev.Value === v)) {
5846
6097
  // Generate a UUID for this new EntityFieldValue record
5847
6098
  const newId = uuidv4();
5848
- // 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);
5849
6102
  const sSQLInsert = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityFieldValue')}
5850
6103
  (${this.qi('ID')}, ${this.qi('EntityFieldID')}, ${this.qi('Sequence')}, ${this.qi('Value')}, ${this.qi('Code')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')})
5851
6104
  VALUES
5852
- ('${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()})`;
5853
6106
  await this.logSQLAndExecute(ds, sSQLInsert, `SQL text to insert entity field value with ID ${newId}`);
5854
6107
  numAdded++;
5855
6108
  }
@@ -6508,56 +6761,16 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6508
6761
  }
6509
6762
  newEntityName = uniqueName;
6510
6763
  const suffix = uniqueSuffix;
6511
- const isNewSchema = await this.isSchemaNew(pool, newEntity.SchemaName);
6512
6764
  const newEntityID = this.createNewUUID();
6513
6765
  const sSQLInsert = this.createNewEntityInsertSQL(newEntityID, newEntityName, newEntity, suffix, newEntityDisplayName);
6514
6766
  await this.logSQLAndExecute(pool, sSQLInsert, `SQL generated to create new entity ${newEntityName}`);
6515
6767
  // if we get here we created a new entity safely, otherwise we get exception
6516
6768
  // add it to the new entity list
6517
6769
  ManageMetadataBase.newEntityList.push(newEntityName);
6518
- // 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
6519
- // our config option is set to create new applications from new schemas, then create a new application for this schema
6520
- let apps;
6521
- if (isNewSchema && configInfo.newSchemaDefaults.CreateNewApplicationWithSchemaName) {
6522
- // new schema and config option is to create a new application from the schema name so do that
6523
- // check to see if the app already exists
6524
- apps = await this.getApplicationIDForSchema(pool, newEntity.SchemaName);
6525
- if (!apps || apps.length === 0) {
6526
- // doesn't already exist, so create it
6527
- const appUUID = this.createNewUUID();
6528
- const newAppID = await this.createNewApplication(pool, appUUID, newEntity.SchemaName, newEntity.SchemaName, currentUser);
6529
- if (newAppID) {
6530
- apps = [newAppID];
6531
- }
6532
- else {
6533
- LogError(` >>>> ERROR: Unable to create new application for schema ${newEntity.SchemaName}`);
6534
- }
6535
- 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
6536
- // 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
6537
- }
6538
- }
6539
- else {
6540
- // not a new schema, attempt to look up the application for this schema
6541
- apps = await this.getApplicationIDForSchema(pool, newEntity.SchemaName);
6542
- }
6543
- if (apps && apps.length > 0) {
6544
- if (configInfo.newEntityDefaults.AddToApplicationWithSchemaName) {
6545
- // only do this if the configuration setting is set to add new entities to applications for schema names
6546
- for (const appUUID of apps) {
6547
- const sSQLInsertApplicationEntity = `INSERT INTO ${this.qs(MjCoreSchema(), 'ApplicationEntity')}
6548
- (${this.qi('ApplicationID')}, ${this.qi('EntityID')}, ${this.qi('Sequence')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')}) VALUES
6549
- ('${appUUID}', '${newEntityID}', (SELECT COALESCE(MAX(${this.qi('Sequence')}),0)+1 FROM ${this.qs(MjCoreSchema(), 'ApplicationEntity')} WHERE ${this.qi('ApplicationID')} = '${appUUID}'), ${this.utcNow()}, ${this.utcNow()})`;
6550
- await this.logSQLAndExecute(pool, sSQLInsertApplicationEntity, `SQL generated to add new entity ${newEntityName} to application ID: '${appUUID}'`);
6551
- }
6552
- }
6553
- else {
6554
- // 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
6555
- }
6556
- }
6557
- else {
6558
- // 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
6559
- 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}'.`);
6560
- }
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);
6561
6774
  // next up, we need to check if we're configured to add permissions for new entities, and if so, add them
6562
6775
  // A per-table `Entities` entry can opt a table out of the default grants (AutoAddPermissions: false),
6563
6776
  // e.g. a table only server code may touch. Applied here because grants made now would otherwise
@@ -6601,15 +6814,6 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6601
6814
  throw e instanceof Error ? e : new Error(errMsg);
6602
6815
  }
6603
6816
  }
6604
- async isSchemaNew(pool, schemaName) {
6605
- // check to see if there are any entities in the db with this schema name
6606
- // Quote the alias so PostgreSQL preserves PascalCase (unquoted aliases are lowercased in PG)
6607
- const sSQL = `SELECT COUNT(*) AS ${this.qi('Count')} FROM ${this.qs(MjCoreSchema(), 'Entity')} WHERE ${this.qi('SchemaName')} = '${schemaName}'`;
6608
- const resultResult = await this.runQuery(pool, sSQL);
6609
- const result = resultResult.recordset;
6610
- // Use Number() because PG returns COUNT(*) as bigint, which the pg driver delivers as a string
6611
- return result && result.length > 0 ? Number(result[0].Count) === 0 : true;
6612
- }
6613
6817
  /**
6614
6818
  * Creates a new application using direct SQL INSERT to ensure it's captured in SQL logging.
6615
6819
  * The Path field is auto-generated from Name using the same slug logic as MJApplicationEntityServer.
@@ -6717,17 +6921,21 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6717
6921
  }
6718
6922
  /**
6719
6923
  * Adds a newly created entity to the application(s) that match its schema name.
6720
- * If no application exists for the schema and config allows it, creates one.
6721
- * 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.
6722
6929
  */
6723
6930
  async addEntityToApplicationForSchema(pool, entityId, entityName, schemaName, currentUser) {
6724
6931
  let apps = await this.getApplicationIDForSchema(pool, schemaName);
6932
+ let createdAppID = null;
6725
6933
  // If no app exists and config says to create one for new schemas, create it
6726
6934
  if ((!apps || apps.length === 0) && configInfo.newSchemaDefaults.CreateNewApplicationWithSchemaName) {
6727
6935
  const appUUID = this.createNewUUID();
6728
- const newAppID = await this.createNewApplication(pool, appUUID, schemaName, schemaName, currentUser);
6729
- if (newAppID) {
6730
- apps = [newAppID];
6936
+ createdAppID = await this.createNewApplication(pool, appUUID, schemaName, schemaName, currentUser);
6937
+ if (createdAppID) {
6938
+ apps = [createdAppID];
6731
6939
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
6732
6940
  await md.Refresh();
6733
6941
  }
@@ -6743,12 +6951,42 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6743
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()})`;
6744
6952
  await this.logSQLAndExecute(pool, sSQLInsert, `SQL generated to add entity ${entityName} to application ID: '${appUUID}'`);
6745
6953
  }
6954
+ if (createdAppID) {
6955
+ await this.linkUnassignedSchemaEntitiesToApplication(pool, createdAppID, schemaName);
6956
+ }
6746
6957
  }
6747
6958
  }
6748
6959
  else {
6749
- 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}'.`);
6750
6961
  }
6751
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;
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`);
6989
+ }
6752
6990
  /**
6753
6991
  * INSERT for one `EntityPermission` row, skipped when a row already exists for that
6754
6992
  * (EntityID, RoleID, Type).
@@ -6872,7 +7110,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6872
7110
  continue;
6873
7111
  const refSchema = (ref.SchemaName ?? '').trim().toLowerCase();
6874
7112
  // Skip CTE self-references (only unqualified / dbo-defaulted refs can be a CTE name).
6875
- if ((refSchema === '' || refSchema === 'dbo') && cteNames.has(ref.TableName.trim().toLowerCase()))
7113
+ if (this.isUnqualifiedRefSchema(refSchema) && cteNames.has(ref.TableName.trim().toLowerCase()))
6876
7114
  continue;
6877
7115
  // Refuse ANY under-linked entity source, not only RLS-protected ones. Both the RLS-safety check above
6878
7116
  // AND the read-grant role intersection (addMaterializedQueryEntityPermissions) are computed over the
@@ -6899,7 +7137,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6899
7137
  /** Maps a physical (schema, table/view) reference to the MJ entities backed by it — by BaseView or BaseTable,
6900
7138
  * case/whitespace-insensitive. Returns ALL candidates so the P1 guard can fail closed on an AMBIGUOUS ref.
6901
7139
  * Resolution: an explicit, non-default schema yields only that schema's exact matches; an empty schema OR the
6902
- * 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
6903
7141
  * core/app entities live in `__mj`/app schemas (never `dbo`) — is treated as unqualified and yields every
6904
7142
  * schema-agnostic name match. That way an unqualified reference to a `__mj`/app-schema entity is still caught,
6905
7143
  * and a same-base-name collision across schemas surfaces every candidate rather than just the first (so the
@@ -6912,13 +7150,20 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6912
7150
  const bt = (e.BaseTable ?? '').trim().toLowerCase();
6913
7151
  return bv === t || bt === t;
6914
7152
  };
6915
- if (s && s !== 'dbo') {
7153
+ if (!this.isUnqualifiedRefSchema(s)) {
6916
7154
  // Explicit, non-default schema → only that schema's entity qualifies (no cross-schema ambiguity).
6917
7155
  return md.Entities.filter((e) => (e.SchemaName ?? '').trim().toLowerCase() === s && nameMatch(e));
6918
7156
  }
6919
- // 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.
6920
7158
  return md.Entities.filter(nameMatch);
6921
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
+ }
6922
7167
  /**
6923
7168
  * Grants read permissions to a newly-minted materialized QUERY entity scoped to the INTERSECTION of source
6924
7169
  * read access (C2). A precomputed snapshot has no per-row scoping, so a role may read it only if it can read
@@ -7356,7 +7601,9 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7356
7601
  e.AllowUserSearchAPI,
7357
7602
  e.AutoUpdateAllowUserSearchAPI,
7358
7603
  e.FullTextSearchEnabled,
7359
- e.AutoUpdateFullTextSearch
7604
+ e.AutoUpdateFullTextSearch,
7605
+ e.DisplayName,
7606
+ e.AutoUpdateDisplayName
7360
7607
  FROM
7361
7608
  ${this.qs(MjCoreSchema(), 'vwEntities')} e
7362
7609
  WHERE
@@ -7463,6 +7710,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7463
7710
  const batchSize = configInfo.advancedGeneration?.batchSize ?? 5;
7464
7711
  let processedCount = 0;
7465
7712
  let errorCount = 0;
7713
+ let circuitSkippedCount = 0;
7466
7714
  const total = entities.length;
7467
7715
  // Pre-group fields by EntityID once — O(total fields) — instead of a per-entity linear scan
7468
7716
  // of the full pooled array inside processEntityAdvancedGeneration (which was O(entities × fields),
@@ -7482,6 +7730,10 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7482
7730
  // Process in batches
7483
7731
  for (let i = 0; i < total; i += batchSize) {
7484
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
+ }
7485
7737
  // Process batch in parallel. entityPhase() sets the reporter's "current entity"
7486
7738
  // so any LLM calls issued by processEntityAdvancedGeneration get attributed
7487
7739
  // to the right entity. Also marks the entity as modified in the report flags.
@@ -7507,9 +7759,15 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7507
7759
  if (ag.AICircuitOpen) {
7508
7760
  const skipped = total - processedCount;
7509
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);
7510
7763
  break;
7511
7764
  }
7512
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
+ }
7513
7771
  return errorCount === 0;
7514
7772
  }
7515
7773
  /**
@@ -7570,8 +7828,12 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7570
7828
  // Fires only on change events (new entity, new fields, reopened description/type) AND when there is work to do
7571
7829
  // (blank categories with AutoUpdateCategory=1, or reopened fields to review). Gated on events so omitted blank fields don't loop (§3.4).
7572
7830
  const hasCategoryNeeded = fields.some((f) => Boolean(f.AutoUpdateCategory) && (!f.Category || String(f.Category).trim() === ''));
7573
- const needsCategoryGeneration = (isNewEntity || hasNewFields || hasDescriptionReopened || hasTypeReopened)
7574
- && (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
+ });
7575
7837
  if (needsCategoryGeneration) {
7576
7838
  CodeGenReporter.Instance.counter('ai.formLayoutCalls');
7577
7839
  // Build IS-A parent chain context if this entity has a parent
@@ -7589,11 +7851,163 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7589
7851
  logStatus(` Applied form layout for ${entity.Name}`);
7590
7852
  }
7591
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
+ }
7592
7871
  }
7593
7872
  catch (ex) {
7594
7873
  logError('Error Processing Entity Advanced Generation', ex);
7595
7874
  }
7596
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
+ }
7597
8011
  /**
7598
8012
  * Builds IS-A parent chain context for an entity, computing which parent each
7599
8013
  * inherited field originates from. Used to provide the LLM with inheritance
@@ -7820,8 +8234,14 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7820
8234
  }
7821
8235
  }
7822
8236
  const winner = this.selectNameFieldWinner(fields, nameFieldNames);
7823
- // 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).
7824
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)`);
7825
8245
  sqlStatements.push(`
7826
8246
  UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
7827
8247
  SET IsNameField = ${this.boolLit(true)}
@@ -7989,10 +8409,53 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7989
8409
  */
7990
8410
  isInheritedISAField(field) {
7991
8411
  const name = field.Name ?? '';
7992
- return field.IsVirtual === true
7993
- && field.AllowUpdateAPI === true
7994
- && field.IsPrimaryKey !== true
7995
- && !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;
7996
8459
  }
7997
8460
  /**
7998
8461
  * Generate SQL UPDATEs for DefaultInView on the identified default view fields
@@ -8705,27 +9168,30 @@ WHERE
8705
9168
  }
8706
9169
  /**
8707
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}.
8708
9176
  */
8709
9177
  async applyCategoryInfoSettings(pool, entityId, categoryInfo, _entityName) {
8710
9178
  if (!categoryInfo || Object.keys(categoryInfo).length === 0)
8711
9179
  return;
8712
- const canonicalInfo = CanonicalJSONStringify(categoryInfo, 2);
8713
- const infoJSON = canonicalInfo.replace(/'/g, "''");
8714
9180
  const ENTITY_SETTING_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
8715
9181
  // Upsert FieldCategoryInfo (new format)
8716
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'`;
8717
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;
8718
9187
  if (existingNew.recordset.length > 0) {
8719
- let isMatch = false;
8720
- try {
8721
- const rawVal = existingNew.recordset[0].Value;
8722
- const parsed = typeof rawVal === 'string' ? JSON.parse(rawVal) : rawVal;
8723
- isMatch = DeepEqualJSON(parsed, categoryInfo);
8724
- }
8725
- catch {
8726
- isMatch = false;
8727
- }
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);
8728
9193
  if (!isMatch) {
9194
+ const infoJSON = CanonicalJSONStringify(infoToStore, 2).replace(/'/g, "''");
8729
9195
  try {
8730
9196
  await this.logSQLAndExecute(pool, `
8731
9197
  UPDATE ${this.qs(MjCoreSchema(), 'EntitySetting')}
@@ -8739,6 +9205,7 @@ WHERE
8739
9205
  }
8740
9206
  }
8741
9207
  else {
9208
+ const infoJSON = CanonicalJSONStringify(categoryInfo, 2).replace(/'/g, "''");
8742
9209
  const newId = uuidv5(`${entityId}|FieldCategoryInfo`, ENTITY_SETTING_NAMESPACE);
8743
9210
  try {
8744
9211
  const checkQuery = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntitySetting')} WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryInfo'`;
@@ -8753,26 +9220,20 @@ WHERE
8753
9220
  }
8754
9221
  // Also upsert legacy FieldCategoryIcons for backwards compatibility
8755
9222
  const iconsOnly = {};
8756
- for (const [category, info] of Object.entries(categoryInfo)) {
9223
+ for (const [category, info] of Object.entries(infoToStore)) {
8757
9224
  if (info && typeof info === 'object' && 'icon' in info) {
8758
9225
  iconsOnly[category] = info.icon;
8759
9226
  }
8760
9227
  }
8761
- const canonicalIcons = CanonicalJSONStringify(iconsOnly, 2);
8762
- const iconsJSON = canonicalIcons.replace(/'/g, "''");
8763
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'`;
8764
9229
  const existingLegacy = await this.runQuery(pool, checkLegacySQL);
8765
9230
  if (existingLegacy.recordset.length > 0) {
8766
- let isMatch = false;
8767
- try {
8768
- const rawVal = existingLegacy.recordset[0].Value;
8769
- const parsed = typeof rawVal === 'string' ? JSON.parse(rawVal) : rawVal;
8770
- isMatch = DeepEqualJSON(parsed, iconsOnly);
8771
- }
8772
- catch {
8773
- isMatch = false;
8774
- }
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);
8775
9235
  if (!isMatch) {
9236
+ const iconsJSON = CanonicalJSONStringify(iconsToStore, 2).replace(/'/g, "''");
8776
9237
  try {
8777
9238
  await this.logSQLAndExecute(pool, `
8778
9239
  UPDATE ${this.qs(MjCoreSchema(), 'EntitySetting')}
@@ -8786,6 +9247,7 @@ WHERE
8786
9247
  }
8787
9248
  }
8788
9249
  else {
9250
+ const iconsJSON = CanonicalJSONStringify(iconsOnly, 2).replace(/'/g, "''");
8789
9251
  const newId = uuidv5(`${entityId}|FieldCategoryIcons`, ENTITY_SETTING_NAMESPACE);
8790
9252
  try {
8791
9253
  const checkQuery = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntitySetting')} WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = 'FieldCategoryIcons'`;
@@ -8799,6 +9261,48 @@ WHERE
8799
9261
  }
8800
9262
  }
8801
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
+ }
8802
9306
  /**
8803
9307
  * Applies entity importance analysis to MJApplicationEntity records.
8804
9308
  * Only called for NEW entities to set DefaultForNewUser.