@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
@@ -6,7 +6,7 @@ import './providers/sqlserver/SQLServerCodeGenProvider.js';
6
6
  import { EntityFieldExtendedType, EntityFieldInfo, EntityInfo, type EntityConfigurableAtCreationAttribute, ExternalDataSourceReadRouter, ExternalSchemaObject, FieldCategoryInfo, Metadata, UserInfo } from "@memberjunction/core";
7
7
  import { SQLUtilityBase } from "./sql.js";
8
8
  import { JSONCheckTranslator, JSONFieldRow, JSONValidatorResult } from "./json-check-validators.js";
9
- import { AdvancedGeneration, SmartFieldIdentificationResult, FormLayoutResult, VirtualEntityDecorationResult } from "../Misc/advanced_generation.js";
9
+ import { AdvancedGeneration, EntityDisplayNameResult, SmartFieldIdentificationResult, FormLayoutResult, VirtualEntityDecorationResult } from "../Misc/advanced_generation.js";
10
10
  import { FieldChangeReason, EntityFieldSnapshotRow } from './entity-field-change-tracking.js';
11
11
  export { TRACKED_FIELD_COLUMNS, FieldChangeReason, DISPLAYNAME_REOPEN_REASONS, TYPE_REOPEN_REASONS, EntityFieldSnapshotRow, EntityFieldChange, DiffEntityFieldSnapshots, diffEntityFieldSnapshots, } from './entity-field-change-tracking.js';
12
12
  export declare class ValidatorResult {
@@ -27,6 +27,65 @@ export declare class ValidatorResult {
27
27
  wasGenerated: boolean;
28
28
  success: boolean;
29
29
  }
30
+ /**
31
+ * The columns of an IS-A inherited EntityField row that the parent-field sync reads back.
32
+ * Bit columns arrive as boolean, number or string depending on the driver.
33
+ */
34
+ type IsAInheritedFieldRow = {
35
+ ID: string;
36
+ IsVirtual: boolean | number;
37
+ Type: string | null;
38
+ Length: number;
39
+ Precision: number;
40
+ Scale: number;
41
+ AllowsNull: boolean;
42
+ AllowUpdateAPI: boolean | number;
43
+ RelatedEntityID: string | null;
44
+ RelatedEntityFieldName: string | null;
45
+ RelatedEntityDisplayType: string | null;
46
+ IncludeRelatedEntityNameFieldInBaseView: boolean | number | string | null;
47
+ AutoUpdateRelatedEntityInfo: boolean | number | string | null;
48
+ };
49
+ /** A self-referencing FK field considered by the legacy hierarchy seed (#5976). */
50
+ type LegacyHierarchyCandidateRow = {
51
+ ID: string;
52
+ EntityID: string;
53
+ Name: string;
54
+ Configuration: string | null;
55
+ EntityName: string;
56
+ SchemaName: string;
57
+ BaseTable: string;
58
+ };
59
+ /** A field the legacy hierarchy seed will update, with the Configuration JSON to write. */
60
+ type LegacyHierarchySeed = {
61
+ Row: LegacyHierarchyCandidateRow;
62
+ Reason: string;
63
+ Configuration: string;
64
+ };
65
+ /** The relationship columns an IS-A inherited field copies from its parent field (#4569). */
66
+ /** An EntityRelationship row as the stale-relationship check reads it (`SELECT *` from the table). */
67
+ export type StaleRelationshipCandidate = {
68
+ ID: string;
69
+ EntityID: string;
70
+ RelatedEntityID: string;
71
+ RelatedEntityJoinField: string | null;
72
+ EntityKeyField?: string | null;
73
+ Type: string | null;
74
+ AutoUpdateFromSchema: boolean | number | string | null;
75
+ Entity?: string | null;
76
+ RelatedEntity?: string | null;
77
+ };
78
+ /** The EntityField columns the stale-relationship check reads. */
79
+ export type StaleRelationshipField = {
80
+ EntityID: string;
81
+ Name: string;
82
+ RelatedEntityID: string | null;
83
+ };
84
+ type InheritedRelatedEntityInfo = {
85
+ RelatedEntityID: string | null;
86
+ RelatedEntityFieldName: string | null;
87
+ RelatedEntityDisplayType: string;
88
+ };
30
89
  /**
31
90
  * Configuration for a soft primary key field in the additionalSchemaInfo config file.
32
91
  * Uses PascalCase property names to match MemberJunction naming conventions.
@@ -396,6 +455,25 @@ export declare class ManageMetadataBase {
396
455
  private static _changedFieldReport;
397
456
  private static fieldKey;
398
457
  static RegisterNewField(entityID: string, name: string): void;
458
+ private static _fieldShapeChangedEntityIDs;
459
+ private static _fieldShapeChangedEntityNames;
460
+ /**
461
+ * Records that an entity's columns changed shape during this run: a field was added or
462
+ * dropped, or its type, length, precision, scale or nullability changed. The saved queries
463
+ * that read such an entity are re-bound after the run's field sync. Give the entity by ID or
464
+ * by name.
465
+ */
466
+ static RegisterFieldShapeChange(entity: {
467
+ EntityID?: string | null;
468
+ EntityName?: string | null;
469
+ }): void;
470
+ /** The entities whose fields changed shape during this run, by ID (lower-cased) and by name. */
471
+ static get FieldShapeChangedEntities(): {
472
+ IDs: readonly string[];
473
+ Names: readonly string[];
474
+ };
475
+ /** Forgets the entities {@link RegisterFieldShapeChange} recorded. */
476
+ static ClearFieldShapeChanges(): void;
399
477
  /** @deprecated Use {@link RegisterNewField}. */
400
478
  static registerNewField(entityID: string, name: string): void;
401
479
  static RegisterFieldChange(entityID: string, name: string, reasons: Iterable<FieldChangeReason>): void;
@@ -814,6 +892,38 @@ export declare class ManageMetadataBase {
814
892
  * @returns
815
893
  */
816
894
  ManageMetadata(pool: CodeGenConnection, currentUser: UserInfo): Promise<boolean>;
895
+ /**
896
+ * Resolves the opt-in `includeSchemas` scope into `configInfo.excludeSchemas` (#3384).
897
+ * @returns true when every entry matched a database schema (or none are set), false when an entry
898
+ * matched none (the scope is still applied), null when the scope could not be resolved.
899
+ */
900
+ ResolveIncludeSchemaScope(pool: CodeGenConnection): Promise<boolean | null>;
901
+ /**
902
+ * One-time upgrade step for #5976. Before 6.1, CodeGen projected a `Root<Field>` column for every
903
+ * self-referencing foreign key; 6.1 made that opt-in through `Configuration.Hierarchy.IsHierarchy`.
904
+ * An application schema upgraded without seeding that flag keeps its virtual `Root<Field>`
905
+ * EntityField while the regenerated view drops the column, and every read of the entity fails.
906
+ *
907
+ * This sets `{"Hierarchy":{"IsHierarchy":true}}` (merged into any existing Configuration) on every
908
+ * non-virtual, non-key self-referencing FK whose Configuration has no `Hierarchy` key, when the
909
+ * entity still has a virtual `Root<Field>` EntityField or the database still has the field's
910
+ * `fn<Table><Field>_GetRootID` function. Each seeded field is logged as a warning so the owner can
911
+ * opt out deliberately. The core schema is skipped: its hierarchy fields are seeded by metadata,
912
+ * and its baseline-shipped root functions exist for fields that were deliberately left out.
913
+ */
914
+ protected seedLegacyHierarchyConfiguration(pool: CodeGenConnection, excludeSchemas: string[]): Promise<boolean>;
915
+ /**
916
+ * Pure decision step of {@link seedLegacyHierarchyConfiguration}: which candidate fields to seed,
917
+ * why, and the Configuration JSON to write. Fields whose Configuration already has a `Hierarchy`
918
+ * key are left alone, as are fields whose Configuration is not valid JSON (with a warning).
919
+ */
920
+ protected planLegacyHierarchySeeds(candidates: LegacyHierarchyCandidateRow[], rootFields: ReadonlyArray<{
921
+ EntityID: string;
922
+ Name: string;
923
+ }>, functions: ReadonlyArray<{
924
+ RoutineSchema: string;
925
+ RoutineName: string;
926
+ }>): LegacyHierarchySeed[];
817
927
  /** @deprecated Use {@link ManageMetadata}. */
818
928
  manageMetadata(pool: CodeGenConnection, currentUser: UserInfo): Promise<boolean>;
819
929
  /**
@@ -1008,6 +1118,14 @@ export declare class ManageMetadataBase {
1008
1118
  * All SQL updates are batched into a single execution for performance.
1009
1119
  */
1010
1120
  protected applyLLMForeignKeys(pool: CodeGenConnection, entity: EntityInfo, foreignKeys: VirtualEntityDecorationResult['foreignKeys'], schema: string): Promise<boolean>;
1121
+ /**
1122
+ * True when an LLM-identified foreign key may be written to the field: the field has no
1123
+ * relationship yet and its relationship is not pinned (AutoUpdateRelatedEntityInfo = 0).
1124
+ */
1125
+ static LLMForeignKeyMayApply(field: {
1126
+ RelatedEntityID?: string | null;
1127
+ AutoUpdateRelatedEntityInfo?: boolean | number | string | null;
1128
+ }): boolean;
1011
1129
  /**
1012
1130
  * Applies LLM-generated field descriptions to entity fields that lack descriptions.
1013
1131
  * All SQL updates are batched into a single execution for performance.
@@ -1029,10 +1147,16 @@ export declare class ManageMetadataBase {
1029
1147
  * that mirror the parent entity's base table fields (excluding PKs, timestamps, and virtual fields).
1030
1148
  * Runs collision detection to prevent child table columns from shadowing parent fields.
1031
1149
  */
1032
- protected manageParentEntityFields(pool: CodeGenConnection): Promise<{
1150
+ protected manageParentEntityFields(pool: CodeGenConnection, excludeSchemas?: string[]): Promise<{
1033
1151
  success: boolean;
1034
1152
  anyUpdates: boolean;
1035
1153
  }>;
1154
+ /**
1155
+ * True when `schemaName` is on the compiled exclude list. Schema names are compared
1156
+ * case-insensitively: SQL Server resolves them that way, and PostgreSQL folds unquoted
1157
+ * identifiers, so the list and the metadata can legitimately differ in case.
1158
+ */
1159
+ protected isSchemaExcluded(schemaName: string | null | undefined, excludeSchemas: readonly string[]): boolean;
1036
1160
  /**
1037
1161
  * Creates/updates virtual EntityField records for a single child entity's parent fields.
1038
1162
  * Detects field name collisions between child's own base table columns and parent fields.
@@ -1041,6 +1165,18 @@ export declare class ManageMetadataBase {
1041
1165
  success: boolean;
1042
1166
  updated: boolean;
1043
1167
  }>;
1168
+ /**
1169
+ * The relationship an IS-A inherited field carries, copied from the parent's field (#4569).
1170
+ * RelatedEntityNameFieldMap is left NULL and IncludeRelatedEntityNameFieldInBaseView is written
1171
+ * as 0, so the child's view gains no name-field join for the inherited column.
1172
+ */
1173
+ protected inheritedRelatedEntityInfo(parentField: EntityFieldInfo): InheritedRelatedEntityInfo;
1174
+ /** True when the stored row's relationship columns differ from what the parent field implies. */
1175
+ protected inheritedRelatedEntityInfoDiffers(existingRow: IsAInheritedFieldRow, related: InheritedRelatedEntityInfo): boolean;
1176
+ /** Reads a bit column that may come back as boolean, number or string depending on the driver. */
1177
+ protected isTruthyBit(value: boolean | number | string): boolean;
1178
+ /** A SQL string literal, or NULL for a null/empty value. */
1179
+ protected sqlStringOrNull(value: string | null | undefined): string;
1044
1180
  /**
1045
1181
  * Checks if an existing virtual parent field record needs to be updated to match the parent field.
1046
1182
  */
@@ -1065,6 +1201,11 @@ export declare class ManageMetadataBase {
1065
1201
  * Builds SQL to INSERT a new EntityRelationship record for a discovered FK field.
1066
1202
  */
1067
1203
  protected buildInsertRelationshipSQL(f: Record<string, unknown>, md: Metadata, relationshipCountMap: Map<number, number>): string;
1204
+ /**
1205
+ * The existence check for a new One To Many EntityRelationship: true when the row id is taken OR
1206
+ * a relationship with the same natural key (parent entity, child entity, join field) exists.
1207
+ */
1208
+ protected relationshipInsertGuardSQL(newID: string, parentEntityID: string, childEntityID: string, joinField: string): string;
1068
1209
  /**
1069
1210
  * Resolves the `EntityRelationship.EntityKeyField` value for a discovered FK field, or `null`
1070
1211
  * when the relationship joins the parent's primary key and the column therefore must stay NULL.
@@ -1124,27 +1265,60 @@ export declare class ManageMetadataBase {
1124
1265
  */
1125
1266
  protected buildEntityPairRelationshipSQL(relationships: Record<string, unknown>[], fkFields: Record<string, unknown>[], md: Metadata, relationshipCountMap: Map<number, number>): string;
1126
1267
  /**
1127
- * Public entry point for cleaning up stale EntityRelationship records. This must be called
1128
- * AFTER deleteUnneededEntityFields() has run, so that stale EntityField records (for dropped
1129
- * columns) are removed before we check which relationships are still valid.
1130
- * Called from sql_codegen.ts after the second manageEntityFields() pass.
1268
+ * Finds, and unless `DryRun` is set removes, One To Many EntityRelationship rows whose join field
1269
+ * no longer backs them (#2071). Must run AFTER the entity-field prune, so the fields of dropped
1270
+ * columns are already gone. The run calls it after STEP 3's field sync; it deletes only when the
1271
+ * `cleanupStaleRelationships` config option is set.
1272
+ *
1273
+ * A row is stale only when every one of these holds:
1274
+ * - `Type` is One To Many and `AutoUpdateFromSchema` is set. Rows pinned with `AutoUpdateFromSchema = 0`
1275
+ * are never touched; a row made in Explorer defaults to 1, so it is a candidate unless unticked;
1276
+ * - `EntityKeyField` is empty. A row joining on a non-PK parent column can carry a child join field
1277
+ * whose FK points at a third entity, so the FK target says nothing about whether it is stale;
1278
+ * - `RelatedEntityJoinField` is not empty. An empty one names no column, so nothing can be checked;
1279
+ * - BOTH its parent and child entities are in scope. Out of scope means untouched, not deleted
1280
+ * (#3384): an app run must not delete relationships of core or sibling-app entities;
1281
+ * - the child's join field is gone (dropped or renamed column), or it now points at a different
1282
+ * parent entity. A join field that still exists with no relationship at all is kept: that is how
1283
+ * a hand-made relationship over a non-FK column looks, and it cannot be told apart from a
1284
+ * dropped FK.
1285
+ * Soft FKs (`IsSoftForeignKey`, from additionalSchemaInfo or the LLM) carry RelatedEntityID like a
1286
+ * real FK, so the rows built from them are valid. IDs compare via NormalizeUUID, and names are
1287
+ * trimmed (nchar padding) and compared case-insensitively, so every mismatch errs towards keeping.
1131
1288
  * @param pool - database connection
1132
- * @param excludeSchemas - schemas to exclude from FK field lookup
1133
- */
1134
- CleanupStaleEntityRelationships(pool: CodeGenConnection, excludeSchemas: string[]): Promise<boolean>;
1289
+ * @param excludeSchemas - the compiled exclude list (authored excludes plus includeSchemas scope)
1290
+ * @param options.DryRun - report what would be removed without removing it (default true)
1291
+ * @returns false on error. {@link StaleRelationshipsRemoved} holds how many rows the call deleted.
1292
+ */
1293
+ CleanupStaleEntityRelationships(pool: CodeGenConnection, excludeSchemas: string[], options?: {
1294
+ DryRun?: boolean;
1295
+ }): Promise<boolean>;
1296
+ private _staleRelationshipsRemoved;
1297
+ /** Rows the last {@link CleanupStaleEntityRelationships} call deleted (always 0 on a dry run). */
1298
+ get StaleRelationshipsRemoved(): number;
1135
1299
  /** @deprecated Use {@link CleanupStaleEntityRelationships}. */
1136
- cleanupStaleEntityRelationships(pool: CodeGenConnection, excludeSchemas: string[]): Promise<boolean>;
1300
+ cleanupStaleEntityRelationships(pool: CodeGenConnection, excludeSchemas: string[], options?: {
1301
+ DryRun?: boolean;
1302
+ }): Promise<boolean>;
1303
+ /**
1304
+ * The pure half of {@link CleanupStaleEntityRelationships}: picks the stale One To Many rows.
1305
+ * @param relationships - every EntityRelationship row
1306
+ * @param fields - EntityField rows (EntityID, Name, RelatedEntityID) of at least the in-scope entities
1307
+ * @param inScopeEntityIDs - normalized IDs (NormalizeUUID) of the entities this run owns
1308
+ */
1309
+ static FindStaleOneToManyRelationships(relationships: StaleRelationshipCandidate[], fields: StaleRelationshipField[], inScopeEntityIDs: ReadonlySet<string>): StaleRelationshipCandidate[];
1137
1310
  /**
1138
- * Removes stale One-To-Many EntityRelationship records whose RelatedEntityJoinField no longer
1139
- * corresponds to a valid FK field in the database. Only removes relationships where
1140
- * AutoUpdateFromSchema = true and Type = 'One To Many'.
1311
+ * Logs each stale relationship and, unless `dryRun`, deletes it. Each DELETE is keyed on the row
1312
+ * id, so a captured script replayed on a host with different ids deletes nothing there.
1141
1313
  */
1142
- protected removeStaleOneToManyRelationships(pool: CodeGenConnection, allRelationships: Record<string, unknown>[], entityFields: Record<string, unknown>[]): Promise<void>;
1314
+ protected removeStaleOneToManyRelationships(pool: CodeGenConnection, staleRelationships: StaleRelationshipCandidate[], dryRun: boolean): Promise<number>;
1143
1315
  /**
1144
1316
  * 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
1145
1317
  * should be removed. This method is called as part of the manageMetadata method and is not intended to be called directly.
1146
1318
  * @param ds
1147
- * @param excludeSchemas
1319
+ * @param excludeSchemas - deliberately NOT read (#3384). Removal is driven by the physical table
1320
+ * being gone, never by scope: an out-of-scope entity is untouched, not deleted, so filtering
1321
+ * on this list would turn "this schema is out of scope" into "delete its metadata".
1148
1322
  */
1149
1323
  protected checkAndRemoveMetadataForDeletedTables(pool: CodeGenConnection, excludeSchemas: string[]): Promise<boolean>;
1150
1324
  protected checkDropSQLObject(pool: CodeGenConnection, proceed: boolean, type: 'procedure' | 'view' | 'function', schemaName: string, name: string): Promise<void>;
@@ -1179,10 +1353,10 @@ export declare class ManageMetadataBase {
1179
1353
  * Manages the creation, updating and deletion of entity field records in the metadata based on the database schema.
1180
1354
  *
1181
1355
  * @param entityFilter Optional list of entity NAMES to scope the field-management work to. When provided,
1182
- * the three SP/inline-SQL passes (delete unneeded, create new from schema, update existing from schema)
1183
- * filter to those entities only. Other steps remain unscoped — they are cheap enough that scoping them
1184
- * adds complexity without measurable benefit. An empty array short-circuits the entire method as a no-op,
1185
- * which is the typical "no schema changes since last run" case in Pass 2.
1356
+ * the create-new and update-existing schema-sync passes filter to those entities only. The orphan prune
1357
+ * is never scoped (#4050): it runs first, over every entity, and any entity it removed fields from is
1358
+ * added to the filter so its Sequence is renumbered in the same run. An empty filter with nothing pruned
1359
+ * skips the rest of the method, which is the typical "no schema changes since last run" case in Pass 2.
1186
1360
  * `undefined` (default) preserves prior full-scan behavior.
1187
1361
  */
1188
1362
  ManageEntityFields(pool: CodeGenConnection, excludeSchemas: string[], skipCreatedAtUpdatedAtDeletedAtFieldValidation: boolean, skipEntityFieldValues: boolean, currentUser: UserInfo, skipAdvancedGeneration: boolean, skipDeleteUnneededFields?: boolean, entityFilter?: string[]): Promise<boolean>;
@@ -1261,6 +1435,25 @@ export declare class ManageMetadataBase {
1261
1435
  * @returns the number of UPDATEs written
1262
1436
  */
1263
1437
  protected applySoftPrimaryKeys(pool: CodeGenConnection, table: SoftPKFKTableConfig, entityId: string, clearUnique: boolean): Promise<number>;
1438
+ /**
1439
+ * Clears the soft primary key from columns the table's entry no longer lists (#2568). Without it a
1440
+ * wrong soft PK (say a composite key that should have been one column) stays on the entity after
1441
+ * the file is corrected, and only hand-written SQL could remove it.
1442
+ *
1443
+ * Only rows CodeGen marked (`IsSoftPrimaryKey = 1`) are touched, and only for a table whose entry
1444
+ * still declares a PrimaryKey that resolved to at least one column: the entity always keeps a key.
1445
+ * An entry with no PrimaryKey, or a table missing from the file, is left alone, so a truncated or
1446
+ * partial file cannot strip keys. Clearing IsSoftPrimaryKey hands IsPrimaryKey back to schema sync,
1447
+ * which re-derives it from the table on the next field sync.
1448
+ * @returns the number of UPDATEs written
1449
+ */
1450
+ protected retractUndeclaredSoftPrimaryKeys(pool: CodeGenConnection, table: SoftPKFKTableConfig, entityId: string): Promise<number>;
1451
+ /**
1452
+ * The soft-PK columns to clear: those marked soft PK that the entry does not declare. Returns none
1453
+ * when no declared column is currently a soft PK, so a key is never removed without its
1454
+ * replacement in place. Names compare case-insensitively, which errs towards keeping.
1455
+ */
1456
+ static SoftPrimaryKeysToRetract(declaredFieldNames: string[], softPrimaryKeyFieldNames: string[]): string[];
1264
1457
  /**
1265
1458
  * Sets RelatedEntityID, RelatedEntityFieldName and IsSoftForeignKey = 1 on each configured foreign
1266
1459
  * key column. RelatedEntityID is the source of truth, IsSoftForeignKey protects it from schema sync.
@@ -1287,6 +1480,16 @@ export declare class ManageMetadataBase {
1287
1480
  * Applies value-list config for a single field. Returns 'applied' or 'skipped'.
1288
1481
  */
1289
1482
  private applyValueListForField;
1483
+ /**
1484
+ * Warns about every in-scope field whose ValueListType is 'List' but which has no EntityFieldValue
1485
+ * rows (#3986). That combination permits no value at all, so it is always broken metadata; the
1486
+ * runtime permits everything for such a field and logs an error, which is late and easy to miss.
1487
+ *
1488
+ * A warning, not a correction: setting ValueListType to 'None' would discard the intent that the
1489
+ * field is constrained. Never fails the run; a failed query is logged and ignored.
1490
+ * @returns the fields found, as `Entity.Field`
1491
+ */
1492
+ protected warnOnEmptyValueLists(pool: CodeGenConnection, excludeSchemas: string[]): Promise<string[]>;
1290
1493
  /**
1291
1494
  * 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.
1292
1495
  * 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
@@ -1489,7 +1692,25 @@ export declare class ManageMetadataBase {
1489
1692
  protected resolveBaseViewExclusionSupport(pool: CodeGenConnection): Promise<void>;
1490
1693
  /** The configured base-view exclusions, as bare field names for the prune's protected list. */
1491
1694
  protected configuredProtectedFieldNames(): string[];
1492
- protected deleteUnneededEntityFields(pool: CodeGenConnection, excludeSchemas: string[], entityIDs?: string[]): Promise<boolean>;
1695
+ /**
1696
+ * Removes EntityField rows whose column no longer exists on the entity's base view or table.
1697
+ *
1698
+ * @param entityIDs Optional scope. {@link ManageEntityFields} omits it so every entity is scanned:
1699
+ * an entity orphaned by a view-only change is never in a change list (#4050).
1700
+ * @returns `success`, plus the distinct names of the entities rows were deleted from, so the
1701
+ * caller can bring them into scope for the Sequence renumber that follows.
1702
+ */
1703
+ protected deleteUnneededEntityFields(pool: CodeGenConnection, excludeSchemas: string[], entityIDs?: string[]): Promise<{
1704
+ success: boolean;
1705
+ prunedEntityNames: string[];
1706
+ }>;
1707
+ /**
1708
+ * Distinct, non-blank entity names from the rows spDeleteUnneededEntityFields returns (one row per
1709
+ * deleted field, carrying the owning entity's name in `Entity`).
1710
+ */
1711
+ protected distinctPrunedEntityNames(rows: ReadonlyArray<{
1712
+ Entity?: unknown;
1713
+ }> | null | undefined): string[];
1493
1714
  protected manageEntityFieldValuesAndValidatorFunctions(pool: CodeGenConnection, excludeSchemas: string[], currentUser: UserInfo, skipDBUpdate: boolean): Promise<boolean>;
1494
1715
  /**
1495
1716
  * Loads (always) and generates (only when `generateNewCode` and the `ParseCheckConstraints`
@@ -1522,6 +1743,14 @@ export declare class ManageMetadataBase {
1522
1743
  * @returns a data structure with the function text, function name, function description, and a success flag
1523
1744
  */
1524
1745
  protected generateValidatorFunctionFromCheckConstraint(data: any, allEntityFields: any[], currentUser: UserInfo, generateNewCode: boolean): Promise<ValidatorResult>;
1746
+ /** Width of `EntityFieldValue.Code` (nvarchar(50)); `Value` is nvarchar(255). */
1747
+ static readonly EntityFieldValueCodeMaxLength = 50;
1748
+ /**
1749
+ * The Code written for a value-list entry: the value itself when it fits the Code column, else
1750
+ * NULL, which the column documents as "same as Value". Truncating instead could make two codes
1751
+ * collide.
1752
+ */
1753
+ static EntityFieldValueCode(value: string): string | null;
1525
1754
  protected syncEntityFieldValues(ds: CodeGenConnection, entityFieldID: number, possibleValues: string[], allEntityFieldValues: any): Promise<boolean>;
1526
1755
  /**
1527
1756
  * Parses a column-level CHECK constraint into the list of values it permits, or returns null when the
@@ -1701,7 +1930,6 @@ export declare class ManageMetadataBase {
1701
1930
  private logSchemaNameRuleConflict;
1702
1931
  protected createNewUUID(): string;
1703
1932
  protected createNewEntity(pool: CodeGenConnection, newEntity: any, md: Metadata, currentUser: UserInfo): Promise<void>;
1704
- protected isSchemaNew(pool: CodeGenConnection, schemaName: string): Promise<boolean>;
1705
1933
  /**
1706
1934
  * Creates a new application using direct SQL INSERT to ensure it's captured in SQL logging.
1707
1935
  * The Path field is auto-generated from Name using the same slug logic as MJApplicationEntityServer.
@@ -1723,10 +1951,20 @@ export declare class ManageMetadataBase {
1723
1951
  protected getApplicationIDForSchema(pool: CodeGenConnection, schemaName: string): Promise<string[] | null>;
1724
1952
  /**
1725
1953
  * Adds a newly created entity to the application(s) that match its schema name.
1726
- * If no application exists for the schema and config allows it, creates one.
1727
- * Shared by both table-backed entity creation and virtual entity creation.
1954
+ * If no application exists for the schema and config allows it, creates one. The lookup and
1955
+ * create run on every call, so a create that failed for an earlier entity is retried (#4034).
1956
+ * When the application is created after other entities of the schema already exist, those that
1957
+ * are in no application are linked to it as well.
1958
+ * Shared by table-backed, virtual and materialized-query entity creation.
1728
1959
  */
1729
1960
  protected addEntityToApplicationForSchema(pool: CodeGenConnection, entityId: string, entityName: string, schemaName: string, currentUser: UserInfo): Promise<void>;
1961
+ /**
1962
+ * Links every entity of `schemaName` that is in no application to `appID`, numbering them after
1963
+ * the application's current last Sequence in entity-name order. Called when a schema's
1964
+ * application is created after some of its entities, e.g. after an earlier create failed or
1965
+ * while CreateNewApplicationWithSchemaName was off. Emits nothing when there is nothing to link.
1966
+ */
1967
+ protected linkUnassignedSchemaEntitiesToApplication(pool: CodeGenConnection, appID: string, schemaName: string): Promise<void>;
1730
1968
  /**
1731
1969
  * INSERT for one `EntityPermission` row, skipped when a row already exists for that
1732
1970
  * (EntityID, RoleID, Type).
@@ -1773,12 +2011,16 @@ export declare class ManageMetadataBase {
1773
2011
  /** Maps a physical (schema, table/view) reference to the MJ entities backed by it — by BaseView or BaseTable,
1774
2012
  * case/whitespace-insensitive. Returns ALL candidates so the P1 guard can fail closed on an AMBIGUOUS ref.
1775
2013
  * Resolution: an explicit, non-default schema yields only that schema's exact matches; an empty schema OR the
1776
- * parser-default `'dbo'` — which {@link SQLParser.ExtractTableRefs} assigns to every UNQUALIFIED ref, while MJ
2014
+ * parser-default schema (`'dbo'`, or `'public'` on PostgreSQL) — which {@link SQLParser.ExtractTableRefs} assigns to every UNQUALIFIED ref, while MJ
1777
2015
  * core/app entities live in `__mj`/app schemas (never `dbo`) — is treated as unqualified and yields every
1778
2016
  * schema-agnostic name match. That way an unqualified reference to a `__mj`/app-schema entity is still caught,
1779
2017
  * and a same-base-name collision across schemas surfaces every candidate rather than just the first (so the
1780
2018
  * guard refuses if any of them is under-linked). Used by the P1 under-linking guard. */
1781
2019
  protected findEntitiesByBaseObject(md: Metadata, schema: string | undefined, table: string): EntityInfo[];
2020
+ /** Whether a parsed table ref's schema (lower case) can stand for an unqualified name: empty, `dbo`, or the
2021
+ * platform's default schema (`public` on PostgreSQL), which {@link SQLParser.ExtractTableRefs} fills in for
2022
+ * every unqualified ref. Reading such a ref as unqualified widens the candidate set, the fail-closed direction. */
2023
+ protected isUnqualifiedRefSchema(schema: string): boolean;
1782
2024
  /**
1783
2025
  * Grants read permissions to a newly-minted materialized QUERY entity scoped to the INTERSECTION of source
1784
2026
  * read access (C2). A precomputed snapshot has no per-row scoping, so a role may read it only if it can read
@@ -1967,6 +2209,76 @@ export declare class ManageMetadataBase {
1967
2209
  * @param currentUser User context
1968
2210
  */
1969
2211
  protected processEntityAdvancedGeneration(pool: CodeGenConnection, entity: EntityInfo, fieldsByEntity: Map<string, any[]>, ag: AdvancedGeneration, currentUser: UserInfo): Promise<void>;
2212
+ /**
2213
+ * Decides whether an entity should be sent to the LLM for a display-name pass.
2214
+ *
2215
+ * Three independent gates, cheapest first:
2216
+ *
2217
+ * 1. `Entity.AutoUpdateDisplayName` — an administrator has locked this name.
2218
+ * 2. The feature flag itself (checked inside `GenerateEntityDisplayName` too,
2219
+ * but checked here so the opacity assessment is skipped when it is off).
2220
+ * 3. Opacity — whether the deterministic `createDisplayName()` conversion
2221
+ * already produces something readable. This is a COST filter and can be
2222
+ * turned off with the `alwaysGenerate` option; correctness does not depend
2223
+ * on it, only the token bill.
2224
+ */
2225
+ protected needsEntityDisplayNameGeneration(ag: AdvancedGeneration, entityRecord: Record<string, unknown>): boolean;
2226
+ /**
2227
+ * Writes an LLM-proposed entity display name.
2228
+ *
2229
+ * Refuses to write in three cases, each of which would otherwise make the
2230
+ * feature actively harmful rather than merely unhelpful:
2231
+ *
2232
+ * - **Not high or medium confidence.** A confidently wrong display name is worse
2233
+ * than an ugly accurate one, since nothing downstream flags it as a guess. An
2234
+ * allowlist, not a `'low'` check: a missing, null or oddly-cased confidence is
2235
+ * a model that did not answer the question, and it is treated the same way.
2236
+ * - **No change.** Skipped so the run does not report work it did not do.
2237
+ * - **Empty or over-long.** `Entity.DisplayName` is nvarchar(255); a model
2238
+ * that returns prose instead of a name is discarded rather than truncated.
2239
+ *
2240
+ * The schema prefix a name rule puts on `Entity.Name` (`CRM: ACCT_STAT_CD`) is
2241
+ * stripped from the proposal first: `DisplayName` drops it by convention (see
2242
+ * {@link createNewEntityDisplayName}), and a model that keeps it would otherwise
2243
+ * leave this one entity prefixed while its siblings are not.
2244
+ *
2245
+ * The UPDATE goes through the SQL capture like every other metadata write here,
2246
+ * so it reaches the CodeGen_Run_*.sql file that becomes the migration. A bare
2247
+ * `runQuery` would land it in this machine's database and nowhere else.
2248
+ */
2249
+ protected applyEntityDisplayName(pool: CodeGenConnection, entityRecord: Record<string, unknown>, result: EntityDisplayNameResult): Promise<void>;
2250
+ /**
2251
+ * Removes the prefix and suffix the entity's schema name rule adds to `Entity.Name` from a
2252
+ * proposed display name. `DisplayName` never carries them (`createNewEntityDisplayName` strips
2253
+ * them the same way), so a proposal that kept the prefix — `CRM: Account Status Codes`, or
2254
+ * `CRM:Account Status Codes` with the separator space dropped — becomes `Account Status Codes`.
2255
+ * Either affix strips only at a word boundary: under `Sales: `, `Salesforce Contacts` is a real
2256
+ * name that happens to start with the prefix's letters, and stays whole.
2257
+ * Without a rule, or when stripping would leave nothing, the proposal is returned as given.
2258
+ */
2259
+ protected stripEntityNameAffixes(proposed: string, schemaName: string): string;
2260
+ /**
2261
+ * True when two adjacent characters do not both belong to one word, so an affix may end (or
2262
+ * begin) between them. An empty side is a boundary: the affix met the end of the name.
2263
+ */
2264
+ private static isWordBoundary;
2265
+ /**
2266
+ * Decides whether the form-layout (category) pass runs for an entity. It needs work to do (blank
2267
+ * categories with AutoUpdateCategory=1, or reopened fields) AND a reason to look: a change event
2268
+ * (new entity, new fields, reopened description or type), or an explicit backfill request.
2269
+ *
2270
+ * The change-event gate keeps a field the LLM keeps omitting from re-triggering the pass on every
2271
+ * run. It also meant a field left blank by an earlier run (advanced generation off, or omitted by
2272
+ * the LLM) was never categorized by any later run (#4831). `forceRegeneration.enabled`, which
2273
+ * `mj codegen --force-advanced-gen` sets, is that explicit request: it backfills blank categories
2274
+ * without making the automatic path loop.
2275
+ */
2276
+ static NeedsFormLayoutGeneration(state: {
2277
+ HasChangeEvent: boolean;
2278
+ HasReopenedFields: boolean;
2279
+ HasBlankCategories: boolean;
2280
+ BackfillRequested: boolean;
2281
+ }): boolean;
1970
2282
  /**
1971
2283
  * Builds IS-A parent chain context for an entity, computing which parent each
1972
2284
  * inherited field originates from. Used to provide the LLM with inheritance
@@ -2114,6 +2426,18 @@ export declare class ManageMetadataBase {
2114
2426
  * (MJ issue #3551).
2115
2427
  */
2116
2428
  protected isFieldEligibleForNameField(field: Record<string, unknown>): boolean;
2429
+ /**
2430
+ * Rejects foreign-key columns (`RelatedEntityID`) and polymorphic record-ID
2431
+ * payload columns (`EntityIDFieldName` populated, or named `*RecordID` /
2432
+ * `*RecordPrimaryKey` such as `RecordID`, `SourceRecordID`, `TargetRecordID`,
2433
+ * `LinkedRecordID`, `SurvivingRecordID`) from being selected as `IsNameField`.
2434
+ *
2435
+ * Polymorphic `RecordID` columns use `nvarchar(450)` / `nvarchar(750)` so they
2436
+ * can hold composite primary keys or non-UUID strings, which previously tricked
2437
+ * Smart Field Identification into treating them as human-readable text names
2438
+ * and displaying raw UUIDs in tab headers, breadcrumbs, and link cards.
2439
+ */
2440
+ protected isForeignKeyOrPolymorphicRecordIDField(field: Record<string, unknown>): boolean;
2117
2441
  /**
2118
2442
  * The TYPE half of {@link isFieldEligibleForNameField}, with no virtuality
2119
2443
  * opinion: a primary key, a non-text type, or unbounded (MAX) text can never be
@@ -2141,6 +2465,15 @@ export declare class ManageMetadataBase {
2141
2465
  * name-field guardrail needs.
2142
2466
  */
2143
2467
  protected isInheritedISAField(field: Record<string, unknown>): boolean;
2468
+ /**
2469
+ * Lower-cased names of the computed columns (`IsVirtual = 1 AND IsComputed = 1`, not a PK, not
2470
+ * an `__mj_` column) on every entity in the IS-A parent chain of `entityID`. Empty for an entity
2471
+ * with no parent, or when metadata is unavailable. Memoized per entity: the smart-field pass asks
2472
+ * once per field. The memo resets when the loaded entity list changes (a metadata refresh).
2473
+ */
2474
+ protected inheritedComputedFieldNames(entityID: string): Set<string>;
2475
+ private _inheritedComputedSource;
2476
+ private readonly _inheritedComputedNames;
2144
2477
  /**
2145
2478
  * Generate SQL UPDATEs for DefaultInView on the identified default view fields
2146
2479
  */
@@ -2397,8 +2730,30 @@ export declare class ManageMetadataBase {
2397
2730
  protected applyEntityIcon(pool: CodeGenConnection, entityId: string, entityIcon: string, entityName?: string): Promise<void>;
2398
2731
  /**
2399
2732
  * Upserts FieldCategoryInfo (new format) and FieldCategoryIcons (legacy format) in EntitySetting.
2733
+ *
2734
+ * The incoming map is MERGED into what is stored, never written over it (#5369). For an existing
2735
+ * entity the LLM describes only the categories of the fields it was shown (the new ones), so a
2736
+ * replace dropped every other category's icon and description, and with them the IS-A
2737
+ * `inheritedFromEntity*` markers the generated form reads. See {@link MergeFieldCategoryInfo}.
2400
2738
  */
2401
2739
  protected applyCategoryInfoSettings(pool: CodeGenConnection, entityId: string, categoryInfo: Record<string, FieldCategoryInfo>, _entityName?: string): Promise<void>;
2740
+ /**
2741
+ * Merges an incoming FieldCategoryInfo map into the stored one (#5369):
2742
+ * - a category only the stored map has is kept as it is;
2743
+ * - a category only the incoming map has is added;
2744
+ * - a category both have keeps its stored properties and takes each property the incoming entry
2745
+ * sets. So an LLM entry that redescribes an inherited category (icon and description only)
2746
+ * does not drop its `inheritedFromEntityID` / `inheritedFromEntityName`.
2747
+ * Neither input is modified.
2748
+ */
2749
+ static MergeFieldCategoryInfo(stored: Record<string, FieldCategoryInfo>, incoming: Record<string, FieldCategoryInfo>): Record<string, FieldCategoryInfo>;
2750
+ /** A copy of `info` without the keys whose value is undefined, so a spread does not erase them. */
2751
+ private static withoutUndefined;
2752
+ /**
2753
+ * Parses an EntitySetting value holding a JSON object. Returns null for anything that is not a
2754
+ * JSON object (unparseable text, an array, a scalar), so the caller treats it as unreadable.
2755
+ */
2756
+ static ParseStoredSettingObject<T extends object>(rawValue: unknown): T | null;
2402
2757
  /**
2403
2758
  * Applies entity importance analysis to MJApplicationEntity records.
2404
2759
  * Only called for NEW entities to set DefaultForNewUser.