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

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 (47) hide show
  1. package/dist/Config/config.d.ts +126 -0
  2. package/dist/Config/config.d.ts.map +1 -1
  3. package/dist/Config/config.js +48 -2
  4. package/dist/Config/config.js.map +1 -1
  5. package/dist/Database/codeGenDatabaseProvider.d.ts +87 -4
  6. package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
  7. package/dist/Database/codeGenDatabaseProvider.js +133 -1
  8. package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
  9. package/dist/Database/manage-metadata.d.ts +121 -6
  10. package/dist/Database/manage-metadata.d.ts.map +1 -1
  11. package/dist/Database/manage-metadata.js +338 -58
  12. package/dist/Database/manage-metadata.js.map +1 -1
  13. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +25 -5
  14. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
  15. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +135 -26
  16. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
  17. package/dist/Database/providers/postgresql/metadataSupportObjects.js +45 -6
  18. package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
  19. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +40 -12
  20. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
  21. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +127 -53
  22. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
  23. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts +47 -0
  24. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts.map +1 -0
  25. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js +167 -0
  26. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js.map +1 -0
  27. package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts +31 -0
  28. package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts.map +1 -0
  29. package/dist/Database/providers/sqlserver/sqlServerScriptText.js +116 -0
  30. package/dist/Database/providers/sqlserver/sqlServerScriptText.js.map +1 -0
  31. package/dist/Database/sql.d.ts +13 -0
  32. package/dist/Database/sql.d.ts.map +1 -1
  33. package/dist/Database/sql.js +39 -8
  34. package/dist/Database/sql.js.map +1 -1
  35. package/dist/Database/sql_codegen.d.ts +138 -4
  36. package/dist/Database/sql_codegen.d.ts.map +1 -1
  37. package/dist/Database/sql_codegen.js +585 -44
  38. package/dist/Database/sql_codegen.js.map +1 -1
  39. package/dist/Misc/system_integrity.d.ts +48 -0
  40. package/dist/Misc/system_integrity.d.ts.map +1 -1
  41. package/dist/Misc/system_integrity.js +151 -75
  42. package/dist/Misc/system_integrity.js.map +1 -1
  43. package/dist/runCodeGen.d.ts +21 -3
  44. package/dist/runCodeGen.d.ts.map +1 -1
  45. package/dist/runCodeGen.js +114 -44
  46. package/dist/runCodeGen.js.map +1 -1
  47. package/package.json +29 -29
@@ -10,7 +10,7 @@ import { QueryParameterProcessor } from '@memberjunction/query-processor';
10
10
  // `ClassFactory.CreateInstance(CodeGenDatabaseProvider, 'sqlserver')` returns nothing
11
11
  // and the SS code path silently fails.
12
12
  import './providers/sqlserver/SQLServerCodeGenProvider.js';
13
- import { configInfo, currentWorkingDirectory, DbPlatform, GetSettingValue, MjCoreSchema, OutputDir } from '../Config/config.js';
13
+ import { configInfo, DbPlatform, GetSettingValue, MjCoreSchema, OutputDir, ResolveAdditionalSchemaInfoPath } from '../Config/config.js';
14
14
  import { CodeNameFromString, EntityFieldInfo, EntityInfo, ExternalDataSourceReadRouter, ExtractActualDefaultValue, LogError, LogStatus, Metadata, RunQuerySQLFilterManager, SeverityType } from "@memberjunction/core";
15
15
  import { MJEntityFieldSchema } from "@memberjunction/core-entities";
16
16
  import { logError, LogMessage, logStatus, LogWarning, StartSpinner, UpdateSpinner, SucceedSpinner } from "../Misc/status_logging.js";
@@ -546,10 +546,9 @@ export class ManageMetadataBase {
546
546
  * {@link invalidateSoftPKFKConfigCache} at the start of each run so a rewritten file is picked up.
547
547
  */
548
548
  static GetSoftPKFKConfig() {
549
- // Return cached config if path hasn't changed
550
- const configPath = configInfo.additionalSchemaInfo
551
- ? path.join(currentWorkingDirectory, configInfo.additionalSchemaInfo)
552
- : '';
549
+ // Return cached config if path hasn't changed. The path resolves against the mj.config
550
+ // file's directory (or the RSU env override), never the process cwd (#5858).
551
+ const configPath = ResolveAdditionalSchemaInfoPath() ?? '';
553
552
  if (this._softPKFKConfigCache !== null && this._softPKFKConfigPath === configPath) {
554
553
  return this._softPKFKConfigCache;
555
554
  }
@@ -2182,6 +2181,12 @@ export class ManageMetadataBase {
2182
2181
  // failure for this entire function
2183
2182
  }
2184
2183
  logStatus(` > Recompiled base views in ${(new Date().getTime() - start.getTime()) / 1000} seconds`);
2184
+ // Keep pre-6.1 hierarchies working: opt in the self-referencing FKs that already had a Root*
2185
+ // column before the field sync and view regeneration below drop it (#5976).
2186
+ if (!await this.seedLegacyHierarchyConfiguration(pool, excludeSchemas)) {
2187
+ logError(' Error seeding hierarchy configuration for legacy self-referencing foreign keys');
2188
+ bSuccess = false;
2189
+ }
2185
2190
  start = new Date();
2186
2191
  logStatus(' Managing entity fields...');
2187
2192
  // note that we skip Advanced Generation here because we do it again later when the manageSQLScriptsAndExecution occurs in SQLCodeGen class
@@ -2306,6 +2311,109 @@ export class ManageMetadataBase {
2306
2311
  await this.checkEntityFieldSequenceIntegrity(pool, excludeSchemas);
2307
2312
  return bSuccess;
2308
2313
  }
2314
+ /**
2315
+ * One-time upgrade step for #5976. Before 6.1, CodeGen projected a `Root<Field>` column for every
2316
+ * self-referencing foreign key; 6.1 made that opt-in through `Configuration.Hierarchy.IsHierarchy`.
2317
+ * An application schema upgraded without seeding that flag keeps its virtual `Root<Field>`
2318
+ * EntityField while the regenerated view drops the column, and every read of the entity fails.
2319
+ *
2320
+ * This sets `{"Hierarchy":{"IsHierarchy":true}}` (merged into any existing Configuration) on every
2321
+ * non-virtual, non-key self-referencing FK whose Configuration has no `Hierarchy` key, when the
2322
+ * entity still has a virtual `Root<Field>` EntityField or the database still has the field's
2323
+ * `fn<Table><Field>_GetRootID` function. Each seeded field is logged as a warning so the owner can
2324
+ * opt out deliberately. The core schema is skipped: its hierarchy fields are seeded by metadata,
2325
+ * and its baseline-shipped root functions exist for fields that were deliberately left out.
2326
+ */
2327
+ async seedLegacyHierarchyConfiguration(pool, excludeSchemas) {
2328
+ try {
2329
+ const q = (n) => this.qi(n);
2330
+ const candidateSQL = `SELECT ef.${q('ID')} AS ${q('ID')}, ef.${q('EntityID')} AS ${q('EntityID')}, ef.${q('Name')} AS ${q('Name')},
2331
+ ef.${q('Configuration')} AS ${q('Configuration')}, e.${q('Name')} AS ${q('EntityName')},
2332
+ e.${q('SchemaName')} AS ${q('SchemaName')}, e.${q('BaseTable')} AS ${q('BaseTable')}
2333
+ FROM ${this.qs(MjCoreSchema(), 'EntityField')} ef
2334
+ INNER JOIN ${this.qs(MjCoreSchema(), 'Entity')} e ON e.${q('ID')} = ef.${q('EntityID')}
2335
+ WHERE ef.${q('IsVirtual')} = ${this.boolLit(false)}
2336
+ AND ef.${q('IsPrimaryKey')} = ${this.boolLit(false)}
2337
+ AND ef.${q('RelatedEntityID')} = ef.${q('EntityID')}`;
2338
+ const coreSchema = MjCoreSchema().trim().toLowerCase();
2339
+ const candidates = (await this.runQuery(pool, candidateSQL)).recordset
2340
+ .filter(r => !this.isSchemaExcluded(r.SchemaName, excludeSchemas) && r.SchemaName?.trim().toLowerCase() !== coreSchema);
2341
+ if (candidates.length === 0) {
2342
+ return true;
2343
+ }
2344
+ const rootFieldSQL = `SELECT ${q('EntityID')}, ${q('Name')} FROM ${this.qs(MjCoreSchema(), 'EntityField')}
2345
+ WHERE ${q('IsVirtual')} = ${this.boolLit(true)} AND ${q('Name')} LIKE 'Root%'`;
2346
+ const rootFields = (await this.runQuery(pool, rootFieldSQL)).recordset;
2347
+ const functionSQL = `SELECT ROUTINE_SCHEMA AS "RoutineSchema", ROUTINE_NAME AS "RoutineName"
2348
+ FROM INFORMATION_SCHEMA.ROUTINES
2349
+ WHERE ROUTINE_TYPE = 'FUNCTION' AND LOWER(ROUTINE_NAME) LIKE '%root%id'`;
2350
+ const functions = (await this.runQuery(pool, functionSQL)).recordset;
2351
+ const seeds = this.planLegacyHierarchySeeds(candidates, rootFields, functions);
2352
+ for (const seed of seeds) {
2353
+ const guard = seed.Row.Configuration === null || seed.Row.Configuration.trim().length === 0
2354
+ ? `(${q('Configuration')} IS NULL OR ${q('Configuration')} = '')`
2355
+ : `${q('Configuration')} = '${EscapeSQLString(seed.Row.Configuration)}'`;
2356
+ const sql = `UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
2357
+ SET ${q('Configuration')} = '${EscapeSQLString(seed.Configuration)}'
2358
+ WHERE ${q('ID')} = '${seed.Row.ID}' AND ${guard}`;
2359
+ await this.logSQLAndExecute(pool, sql, `Seed Hierarchy.IsHierarchy on legacy self-referencing FK ${seed.Row.EntityName}.${seed.Row.Name}`);
2360
+ LogWarning(` Seeded Configuration.Hierarchy.IsHierarchy = true on ${seed.Row.EntityName}.${seed.Row.Name} (${seed.Reason}). ` +
2361
+ `This keeps the Root${seed.Row.Name} column it had before 6.1; set IsHierarchy to false to opt out.`);
2362
+ }
2363
+ return true;
2364
+ }
2365
+ catch (e) {
2366
+ logError(` Error seeding legacy hierarchy configuration: ${e instanceof Error ? e.message : String(e)}`);
2367
+ return false;
2368
+ }
2369
+ }
2370
+ /**
2371
+ * Pure decision step of {@link seedLegacyHierarchyConfiguration}: which candidate fields to seed,
2372
+ * why, and the Configuration JSON to write. Fields whose Configuration already has a `Hierarchy`
2373
+ * key are left alone, as are fields whose Configuration is not valid JSON (with a warning).
2374
+ */
2375
+ planLegacyHierarchySeeds(candidates, rootFields, functions) {
2376
+ // Function names compare with case and underscores removed, which matches both the
2377
+ // `fn<Table><Field>_GetRootID` form and PostgreSQL's snake_case `fn_<table>_<field>_get_root_id`.
2378
+ const squash = (v) => v.toLowerCase().replace(/_/g, '');
2379
+ const functionKeys = new Set(functions.map(f => `${String(f.RoutineSchema).trim().toLowerCase()}.${squash(String(f.RoutineName))}`));
2380
+ const rootFieldKeys = new Set(rootFields.map(f => `${NormalizeUUID(String(f.EntityID))}|${String(f.Name).toLowerCase()}`));
2381
+ const seeds = [];
2382
+ for (const row of candidates) {
2383
+ let existing = {};
2384
+ const raw = row.Configuration?.trim() ?? '';
2385
+ if (raw.length > 0) {
2386
+ let parsed;
2387
+ try {
2388
+ parsed = JSON.parse(raw);
2389
+ }
2390
+ catch {
2391
+ LogWarning(` Not seeding hierarchy on ${row.EntityName}.${row.Name}: its Configuration is not valid JSON`);
2392
+ continue;
2393
+ }
2394
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
2395
+ LogWarning(` Not seeding hierarchy on ${row.EntityName}.${row.Name}: its Configuration is not a JSON object`);
2396
+ continue;
2397
+ }
2398
+ existing = parsed;
2399
+ if ('Hierarchy' in existing) {
2400
+ continue; // an explicit setting, opt-in or opt-out, always wins
2401
+ }
2402
+ }
2403
+ const hasRootField = rootFieldKeys.has(`${NormalizeUUID(String(row.EntityID))}|root${row.Name.toLowerCase()}`);
2404
+ const functionKey = `${String(row.SchemaName).trim().toLowerCase()}.${squash(`fn${row.BaseTable}${row.Name}GetRootID`)}`;
2405
+ const hasRootFunction = functionKeys.has(functionKey);
2406
+ if (!hasRootField && !hasRootFunction) {
2407
+ continue;
2408
+ }
2409
+ seeds.push({
2410
+ Row: row,
2411
+ Reason: hasRootField ? `virtual Root${row.Name} field present` : `root ID function for ${row.Name} present`,
2412
+ Configuration: JSON.stringify({ ...existing, Hierarchy: { IsHierarchy: true } }),
2413
+ });
2414
+ }
2415
+ return seeds;
2416
+ }
2309
2417
  /** @deprecated Use {@link ManageMetadata}. */
2310
2418
  async manageMetadata(pool, currentUser) {
2311
2419
  return this.ManageMetadata(pool, currentUser);
@@ -3223,19 +3331,30 @@ export class ManageMetadataBase {
3223
3331
  * that mirror the parent entity's base table fields (excluding PKs, timestamps, and virtual fields).
3224
3332
  * Runs collision detection to prevent child table columns from shadowing parent fields.
3225
3333
  */
3226
- async manageParentEntityFields(pool) {
3334
+ async manageParentEntityFields(pool, excludeSchemas = []) {
3227
3335
  let bSuccess = true;
3228
- let anyUpdates = false;
3336
+ const updatedChildNames = [];
3337
+ // `excludeSchemas` is the compiled scope: the authored exclude list plus every schema the
3338
+ // includeSchemas allow-list left out (ApplyIncludeSchemaScope). Only children in scope are
3339
+ // synced. Without this an Open App publisher run processed every IS-A child in the database
3340
+ // and wrote INSERTs for sibling apps' children into its own migration capture (#4879).
3229
3341
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
3230
- const childEntities = md.Entities.filter(e => e.IsChildType);
3342
+ const allChildEntities = md.Entities.filter(e => e.IsChildType);
3343
+ const childEntities = allChildEntities.filter(e => !this.isSchemaExcluded(e.SchemaName, excludeSchemas));
3344
+ const outOfScope = allChildEntities.length - childEntities.length;
3231
3345
  if (childEntities.length === 0) {
3346
+ if (outOfScope > 0) {
3347
+ logStatus(` Skipping IS-A parent fields: all ${outOfScope} child entit${outOfScope === 1 ? 'y is' : 'ies are'} in excluded schemas`);
3348
+ }
3232
3349
  return { success: true, anyUpdates: false };
3233
3350
  }
3234
- logStatus(` Processing IS-A parent fields for ${childEntities.length} child entit${childEntities.length === 1 ? 'y' : 'ies'}...`);
3351
+ logStatus(` Processing IS-A parent fields for ${childEntities.length} child entit${childEntities.length === 1 ? 'y' : 'ies'}${outOfScope > 0 ? ` (${outOfScope} in excluded schemas skipped)` : ''}...`);
3235
3352
  for (const childEntity of childEntities) {
3236
3353
  try {
3237
3354
  const { success, updated } = await this.manageSingleEntityParentFields(pool, childEntity);
3238
- anyUpdates = anyUpdates || updated;
3355
+ if (updated) {
3356
+ updatedChildNames.push(childEntity.Name);
3357
+ }
3239
3358
  if (!success) {
3240
3359
  logError(` Error managing IS-A parent fields for ${childEntity.Name}`);
3241
3360
  bSuccess = false;
@@ -3246,7 +3365,27 @@ export class ManageMetadataBase {
3246
3365
  bSuccess = false;
3247
3366
  }
3248
3367
  }
3249
- return { success: bSuccess, anyUpdates };
3368
+ // A child whose virtual EntityField set changed has a different TypeScript surface (entity
3369
+ // subclass, zod schema, GraphQL types). The rows were written directly above, so nothing
3370
+ // else marks the entity — and the file emit only rebuilds schemas holding a new or modified
3371
+ // entity (fileEmit.dirtySchemaOnly). Mark it here or the run reports success and ships a
3372
+ // class that lacks the field the metadata declares, until someone runs `--skipdb` (#5961).
3373
+ if (updatedChildNames.length > 0) {
3374
+ ManageMetadataBase.AddNewEntitiesToModifiedList(updatedChildNames);
3375
+ }
3376
+ return { success: bSuccess, anyUpdates: updatedChildNames.length > 0 };
3377
+ }
3378
+ /**
3379
+ * True when `schemaName` is on the compiled exclude list. Schema names are compared
3380
+ * case-insensitively: SQL Server resolves them that way, and PostgreSQL folds unquoted
3381
+ * identifiers, so the list and the metadata can legitimately differ in case.
3382
+ */
3383
+ isSchemaExcluded(schemaName, excludeSchemas) {
3384
+ if (!schemaName || excludeSchemas.length === 0) {
3385
+ return false;
3386
+ }
3387
+ const target = schemaName.trim().toLowerCase();
3388
+ return excludeSchemas.some(s => s.trim().toLowerCase() === target);
3250
3389
  }
3251
3390
  /**
3252
3391
  * Creates/updates virtual EntityField records for a single child entity's parent fields.
@@ -3275,20 +3414,39 @@ export class ManageMetadataBase {
3275
3414
  // Identifiers are quoted via qi(): __mj.EntityField's columns are mixed-case, and an
3276
3415
  // unquoted reference folds to lower case on PostgreSQL — `column "length" does not exist`.
3277
3416
  // SQL Server's case-insensitive resolution hid this for as long as IS-A ran only there.
3278
- const existsResult = await this.runQueryWithParams(pool, `SELECT ${this.qi('ID')}, ${this.qi('IsVirtual')}, ${this.qi('Type')}, ${this.qi('Length')}, ${this.qi('Precision')}, ${this.qi('Scale')}, ${this.qi('AllowsNull')}, ${this.qi('AllowUpdateAPI')}
3417
+ const existsResult = await this.runQueryWithParams(pool, `SELECT ${this.qi('ID')}, ${this.qi('IsVirtual')}, ${this.qi('Type')}, ${this.qi('Length')}, ${this.qi('Precision')}, ${this.qi('Scale')}, ${this.qi('AllowsNull')}, ${this.qi('AllowUpdateAPI')},
3418
+ ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityFieldName')}, ${this.qi('RelatedEntityDisplayType')},
3419
+ ${this.qi('IncludeRelatedEntityNameFieldInBaseView')}, ${this.qi('AutoUpdateRelatedEntityInfo')}
3279
3420
  FROM ${this.qs(MjCoreSchema(), 'EntityField')}
3280
3421
  WHERE ${this.qi('EntityID')} = @EntityID AND ${this.qi('Name')} = @FieldName`, { 'EntityID': childEntity.ID, 'FieldName': parentField.Name });
3422
+ // The inherited column reaches the child through its view, so there is no FK constraint
3423
+ // on the child table to derive the relationship from. It is copied from the parent's
3424
+ // field instead (#4569), or the generated form renders a plain text input that writes ''
3425
+ // into a uniqueidentifier column.
3426
+ const related = this.inheritedRelatedEntityInfo(parentField);
3281
3427
  if (existsResult.recordset.length > 0) {
3282
3428
  // Field already exists — update it to ensure it's marked as a virtual IS-A field
3283
3429
  const existingRow = existsResult.recordset[0];
3430
+ // AutoUpdateRelatedEntityInfo = 0 pins a hand-set relationship; leave it alone. The
3431
+ // related-name join is forced off either way: an inherited row never gets its own
3432
+ // name-field join in the child's view.
3433
+ const syncRelated = this.isTruthyBit(existingRow.AutoUpdateRelatedEntityInfo ?? true);
3284
3434
  const needsUpdate = !existingRow.IsVirtual ||
3285
3435
  existingRow.Type?.trim().toLowerCase() !== parentField.Type.trim().toLowerCase() ||
3286
3436
  existingRow.Length !== parentField.Length ||
3287
3437
  existingRow.Precision !== parentField.Precision ||
3288
3438
  existingRow.Scale !== parentField.Scale ||
3289
3439
  existingRow.AllowsNull !== parentField.AllowsNull ||
3290
- !existingRow.AllowUpdateAPI;
3440
+ !existingRow.AllowUpdateAPI ||
3441
+ this.isTruthyBit(existingRow.IncludeRelatedEntityNameFieldInBaseView ?? false) ||
3442
+ (syncRelated && this.inheritedRelatedEntityInfoDiffers(existingRow, related));
3291
3443
  if (needsUpdate) {
3444
+ const relatedSet = syncRelated
3445
+ ? `,
3446
+ ${this.qi('RelatedEntityID')}=${related.RelatedEntityID ? `'${related.RelatedEntityID}'` : 'NULL'},
3447
+ ${this.qi('RelatedEntityFieldName')}=${this.sqlStringOrNull(related.RelatedEntityFieldName)},
3448
+ ${this.qi('RelatedEntityDisplayType')}='${EscapeSQLString(related.RelatedEntityDisplayType)}'`
3449
+ : '';
3292
3450
  const sqlUpdate = `UPDATE ${this.qs(MjCoreSchema(), 'EntityField')}
3293
3451
  SET ${this.qi('IsVirtual')}=${this.boolLit(true)},
3294
3452
  ${this.qi('Type')}='${parentField.Type}',
@@ -3296,7 +3454,8 @@ export class ManageMetadataBase {
3296
3454
  ${this.qi('Precision')}=${parentField.Precision},
3297
3455
  ${this.qi('Scale')}=${parentField.Scale},
3298
3456
  ${this.qi('AllowsNull')}=${this.boolLit(parentField.AllowsNull)},
3299
- ${this.qi('AllowUpdateAPI')}=${this.boolLit(true)}
3457
+ ${this.qi('AllowUpdateAPI')}=${this.boolLit(true)},
3458
+ ${this.qi('IncludeRelatedEntityNameFieldInBaseView')}=${this.boolLit(false)}${relatedSet}
3300
3459
  WHERE ${this.qi('ID')}='${existingRow.ID}'`;
3301
3460
  await this.logSQLAndExecute(pool, sqlUpdate, `Update IS-A parent field ${parentField.Name} on ${childEntity.Name}`);
3302
3461
  bUpdated = true;
@@ -3308,18 +3467,31 @@ export class ManageMetadataBase {
3308
3467
  // Apply-time Sequence (see applyTimeEntityFieldSequenceSQL); reordered by
3309
3468
  // updateExistingEntityFieldsFromSchema afterwards.
3310
3469
  const q = (n) => this.qi(n);
3311
- const sqlInsert = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityField')} (
3470
+ // The INSERT is captured into the run's migration SQL and replayed on other hosts, so it
3471
+ // carries the same existence guard as the schema-field inserts in createNewEntityFieldsFromSchema.
3472
+ // Unguarded, a replay on a host where the field already exists (a second app captured on the
3473
+ // same chain, or the owning app shipping the field itself) fails on
3474
+ // UQ_EntityField_EntityID_Name and stops the install (#4879).
3475
+ const conflictCheck = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntityField')} WHERE ${q('ID')} = '${newFieldID}' OR (${q('EntityID')} = '${childEntity.ID}' AND ${q('Name')} = '${parentField.Name}')`;
3476
+ const guard = this.dbProvider.wrapInsertWithConflictGuard(conflictCheck);
3477
+ const sqlInsert = `${guard.prefix}
3478
+ INSERT INTO ${this.qs(MjCoreSchema(), 'EntityField')} (
3312
3479
  ${q('ID')}, ${q('EntityID')}, ${q('Name')}, ${q('Type')}, ${q('AllowsNull')},
3313
3480
  ${q('Length')}, ${q('Precision')}, ${q('Scale')},
3314
3481
  ${q('Sequence')}, ${q('IsVirtual')}, ${q('AllowUpdateAPI')},
3315
3482
  ${q('IsPrimaryKey')}, ${q('IsUnique')},
3483
+ ${q('RelatedEntityID')}, ${q('RelatedEntityFieldName')}, ${q('RelatedEntityDisplayType')},
3484
+ ${q('IncludeRelatedEntityNameFieldInBaseView')},
3316
3485
  ${q('__mj_CreatedAt')}, ${q('__mj_UpdatedAt')})
3317
3486
  VALUES (
3318
3487
  '${newFieldID}', '${childEntity.ID}', '${parentField.Name}',
3319
3488
  '${parentField.Type}', ${this.boolLit(parentField.AllowsNull)},
3320
3489
  ${parentField.Length}, ${parentField.Precision}, ${parentField.Scale},
3321
3490
  ${this.applyTimeEntityFieldSequenceSQL(childEntity.ID)}, ${this.boolLit(true)}, ${this.boolLit(true)}, ${this.boolLit(false)}, ${this.boolLit(false)},
3322
- ${this.utcNow()}, ${this.utcNow()})`;
3491
+ ${related.RelatedEntityID ? `'${related.RelatedEntityID}'` : 'NULL'}, ${this.sqlStringOrNull(related.RelatedEntityFieldName)}, '${EscapeSQLString(related.RelatedEntityDisplayType)}',
3492
+ ${this.boolLit(false)},
3493
+ ${this.utcNow()}, ${this.utcNow()})
3494
+ ${guard.suffix}`;
3323
3495
  await this.logSQLAndExecute(pool, sqlInsert, `Create IS-A parent field ${parentField.Name} on ${childEntity.Name}`);
3324
3496
  ManageMetadataBase.registerNewField(childEntity.ID, parentField.Name);
3325
3497
  bUpdated = true;
@@ -3342,6 +3514,35 @@ export class ManageMetadataBase {
3342
3514
  }
3343
3515
  return { success: true, updated: bUpdated };
3344
3516
  }
3517
+ /**
3518
+ * The relationship an IS-A inherited field carries, copied from the parent's field (#4569).
3519
+ * RelatedEntityNameFieldMap is left NULL and IncludeRelatedEntityNameFieldInBaseView is written
3520
+ * as 0, so the child's view gains no name-field join for the inherited column.
3521
+ */
3522
+ inheritedRelatedEntityInfo(parentField) {
3523
+ return {
3524
+ RelatedEntityID: parentField.RelatedEntityID ? parentField.RelatedEntityID : null,
3525
+ RelatedEntityFieldName: parentField.RelatedEntityID && parentField.RelatedEntityFieldName ? parentField.RelatedEntityFieldName : null,
3526
+ RelatedEntityDisplayType: parentField.RelatedEntityDisplayType || 'Search',
3527
+ };
3528
+ }
3529
+ /** True when the stored row's relationship columns differ from what the parent field implies. */
3530
+ inheritedRelatedEntityInfoDiffers(existingRow, related) {
3531
+ const currentID = existingRow.RelatedEntityID ?? null;
3532
+ const idDiffers = (currentID === null) !== (related.RelatedEntityID === null) ||
3533
+ (currentID !== null && related.RelatedEntityID !== null && !UUIDsEqual(currentID, related.RelatedEntityID));
3534
+ return idDiffers ||
3535
+ (existingRow.RelatedEntityFieldName ?? null) !== related.RelatedEntityFieldName ||
3536
+ (existingRow.RelatedEntityDisplayType ?? 'Search') !== related.RelatedEntityDisplayType;
3537
+ }
3538
+ /** Reads a bit column that may come back as boolean, number or string depending on the driver. */
3539
+ isTruthyBit(value) {
3540
+ return value === true || value === 1 || value === '1' || value === 'true';
3541
+ }
3542
+ /** A SQL string literal, or NULL for a null/empty value. */
3543
+ sqlStringOrNull(value) {
3544
+ return value ? `'${EscapeSQLString(value)}'` : 'NULL';
3545
+ }
3345
3546
  /**
3346
3547
  * Checks if an existing virtual parent field record needs to be updated to match the parent field.
3347
3548
  */
@@ -3750,6 +3951,9 @@ export class ManageMetadataBase {
3750
3951
  const sql = `SELECT * FROM ${this.qs(MjCoreSchema(), 'vwEntitiesWithMissingBaseTables')}${this.dbProvider.getEntitiesWithMissingBaseTablesFilter()}`;
3751
3952
  const entitiesResult = await this.runQuery(pool, sql);
3752
3953
  const entities = entitiesResult.recordset;
3954
+ // An entity whose removal fails is recorded and the rest still run; the step then fails
3955
+ // (#3546). A half-pruned entity left behind silently drops out of every later generation.
3956
+ const failedRemovals = [];
3753
3957
  if (entities && entities.length > 0) {
3754
3958
  for (const e of entities) {
3755
3959
  // External-data-source entities have no physical MJ table by design, so they always
@@ -3763,9 +3967,8 @@ export class ManageMetadataBase {
3763
3967
  if (e.ExternalDataSourceID) {
3764
3968
  continue;
3765
3969
  }
3766
- // for the given entity, wipe out the entity metadata and its core deps.
3767
- // the below could fail if there are non-core dependencies on the entity, but that's ok, we will flag that in the console
3768
- // for the admin to handle manually
3970
+ // for the given entity, wipe out the entity metadata and its core deps. This fails when
3971
+ // a dependency the routine does not handle still references the entity.
3769
3972
  try {
3770
3973
  // discardResult: this routine only performs deletions — nothing below reads rows
3771
3974
  // from it — and on PostgreSQL it is declared RETURNS SETOF record, which cannot be
@@ -3787,13 +3990,18 @@ export class ManageMetadataBase {
3787
3990
  await this.checkDropSQLObject(pool, e.FullTextSearchFunctionGenerated, 'function', e.SchemaName, e.FullTextSearchFunction);
3788
3991
  }
3789
3992
  catch (ex) {
3790
- logError(`Error removing metadata for entity ${ex.Name}, error: ${ex}`);
3993
+ failedRemovals.push(`${e.Name} (${e.SchemaName}.${e.BaseTable})`);
3994
+ logError(`Error removing metadata for entity ${e.Name} (${e.SchemaName}.${e.BaseTable}): ${ex instanceof Error ? ex.message : String(ex)}`);
3791
3995
  }
3792
3996
  }
3793
3997
  // if we get here we now need to refresh our metadata object
3794
3998
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
3795
3999
  await md.Refresh();
3796
4000
  }
4001
+ if (failedRemovals.length > 0) {
4002
+ logError(` Could not remove metadata for ${failedRemovals.length} entit${failedRemovals.length === 1 ? 'y' : 'ies'} whose base table was dropped: ${failedRemovals.join(', ')}`);
4003
+ return false;
4004
+ }
3797
4005
  return true;
3798
4006
  }
3799
4007
  catch (e) {
@@ -3878,19 +4086,45 @@ export class ManageMetadataBase {
3878
4086
  * Manages the creation, updating and deletion of entity field records in the metadata based on the database schema.
3879
4087
  *
3880
4088
  * @param entityFilter Optional list of entity NAMES to scope the field-management work to. When provided,
3881
- * the three SP/inline-SQL passes (delete unneeded, create new from schema, update existing from schema)
3882
- * filter to those entities only. Other steps remain unscoped — they are cheap enough that scoping them
3883
- * adds complexity without measurable benefit. An empty array short-circuits the entire method as a no-op,
3884
- * which is the typical "no schema changes since last run" case in Pass 2.
4089
+ * the create-new and update-existing schema-sync passes filter to those entities only. The orphan prune
4090
+ * is never scoped (#4050): it runs first, over every entity, and any entity it removed fields from is
4091
+ * added to the filter so its Sequence is renumbered in the same run. An empty filter with nothing pruned
4092
+ * skips the rest of the method, which is the typical "no schema changes since last run" case in Pass 2.
3885
4093
  * `undefined` (default) preserves prior full-scan behavior.
3886
4094
  */
3887
4095
  async ManageEntityFields(pool, excludeSchemas, skipCreatedAtUpdatedAtDeletedAtFieldValidation, skipEntityFieldValues, currentUser, skipAdvancedGeneration, skipDeleteUnneededFields = false, entityFilter) {
3888
4096
  let bSuccess = true;
3889
4097
  const startTime = new Date();
3890
- // Fast-exit: an explicit empty filter means "no entities changed in Pass 1, so Pass 2 has nothing to do"
3891
- if (entityFilter && entityFilter.length === 0) {
4098
+ // Prune orphaned EntityField rows FIRST and UNSCOPED (#4050, #5976, #6028). The SQL pass
4099
+ // regenerates the base view of every included entity, so a view can lose columns while its
4100
+ // table is unchanged (the hierarchy opt-in gate drops Root*/Depth/Path this way). Such an
4101
+ // entity is in neither the new nor the modified list, which are built from table changes,
4102
+ // so a scoped prune — or the empty-filter exit below — never reaches it. The prune is one
4103
+ // routine call; the scan is the same one R__RefreshMetadata runs on every migrate.
4104
+ let prunedEntityNames = [];
4105
+ if (skipDeleteUnneededFields) {
4106
+ logStatus(` Skipping deletion of unneeded entity fields (deferred to post-SQL pass)`);
4107
+ }
4108
+ else {
4109
+ const pruneStart = new Date();
4110
+ const prune = await this.deleteUnneededEntityFields(pool, excludeSchemas);
4111
+ if (!prune.success) {
4112
+ logError('Error deleting unneeded entity fields');
4113
+ bSuccess = false;
4114
+ }
4115
+ prunedEntityNames = prune.prunedEntityNames;
4116
+ logStatus(` Deleted unneeded entity fields${prunedEntityNames.length > 0 ? ` from ${prunedEntityNames.length} entit${prunedEntityNames.length === 1 ? 'y' : 'ies'}` : ''} in ${(new Date().getTime() - pruneStart.getTime()) / 1000} seconds`);
4117
+ }
4118
+ // A pruned entity joins this pass's scope: spUpdateExistingEntityFieldsFromSchema renumbers
4119
+ // Sequence from the live view and only touches entities in scope. The caller snapshotted the
4120
+ // modified list before this call, so the prune's addition to that list does not reach here.
4121
+ const effectiveFilter = entityFilter
4122
+ ? [...new Set([...entityFilter, ...prunedEntityNames])]
4123
+ : undefined;
4124
+ // Fast-exit: an empty filter means "no entities changed in Pass 1 and nothing was pruned"
4125
+ if (effectiveFilter && effectiveFilter.length === 0) {
3892
4126
  logStatus(` manageEntityFields: empty entityFilter — skipping Pass 2 (no entities to process)`);
3893
- return true;
4127
+ return bSuccess;
3894
4128
  }
3895
4129
  // Resolve entity names → IDs once up front so SP wrappers can receive UUIDs directly.
3896
4130
  // If a non-empty filter resolved to zero IDs (e.g., all names were stale/invalid),
@@ -3898,11 +4132,11 @@ export class ManageMetadataBase {
3898
4132
  // unscoped full scan, which is worse than the original intent. Treating "filter
3899
4133
  // provided but nothing resolved" as a no-op is the correct behavior.
3900
4134
  let scopedEntityIDs;
3901
- if (entityFilter) {
3902
- scopedEntityIDs = this.resolveEntityNamesToIDs(entityFilter);
4135
+ if (effectiveFilter) {
4136
+ scopedEntityIDs = this.resolveEntityNamesToIDs(effectiveFilter);
3903
4137
  if (scopedEntityIDs.length === 0) {
3904
- logStatus(` manageEntityFields: entityFilter (${entityFilter.length} names) resolved to 0 IDs — skipping Pass 2`);
3905
- return true;
4138
+ logStatus(` manageEntityFields: entityFilter (${effectiveFilter.length} names) resolved to 0 IDs — skipping Pass 2`);
4139
+ return bSuccess;
3906
4140
  }
3907
4141
  }
3908
4142
  if (!skipCreatedAtUpdatedAtDeletedAtFieldValidation) {
@@ -3913,17 +4147,6 @@ export class ManageMetadataBase {
3913
4147
  }
3914
4148
  logStatus(` Ensured ${EntityInfo.CreatedAtFieldName}/${EntityInfo.UpdatedAtFieldName}/${EntityInfo.DeletedAtFieldName} fields exist in ${(new Date().getTime() - startTime.getTime()) / 1000} seconds`);
3915
4149
  }
3916
- const step1StartTime = new Date();
3917
- if (skipDeleteUnneededFields) {
3918
- logStatus(` Skipping deletion of unneeded entity fields (deferred to post-SQL pass)`);
3919
- }
3920
- else {
3921
- if (!await this.deleteUnneededEntityFields(pool, excludeSchemas, scopedEntityIDs)) {
3922
- logError('Error deleting unneeded entity fields');
3923
- bSuccess = false;
3924
- }
3925
- logStatus(` Deleted unneeded entity fields in ${(new Date().getTime() - step1StartTime.getTime()) / 1000} seconds`);
3926
- }
3927
4150
  // AN: 14-June-2025 - See note below about the new order of these steps, this must
3928
4151
  // happen before we update existing entity fields from schema.
3929
4152
  const step2StartTime = new Date();
@@ -3956,12 +4179,13 @@ export class ManageMetadataBase {
3956
4179
  const stepConfigStartTime = new Date();
3957
4180
  if (!await this.applySoftPKFKConfig(pool)) {
3958
4181
  logError('Error applying soft PK/FK configuration');
4182
+ bSuccess = false;
3959
4183
  }
3960
4184
  logStatus(` Applied soft PK/FK configuration in ${(new Date().getTime() - stepConfigStartTime.getTime()) / 1000} seconds`);
3961
4185
  // CRITICAL: Refresh metadata to pick up soft PK/FK flags
3962
4186
  // Without this, downstream SQL and TypeScript generation will fail
3963
4187
  // because entity.Fields and entity.PrimaryKeys won't reflect the updated flags
3964
- if (configInfo.additionalSchemaInfo) {
4188
+ if (ResolveAdditionalSchemaInfoPath()) {
3965
4189
  logStatus(' Refreshing metadata after applying soft PK/FK configuration...');
3966
4190
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
3967
4191
  await md.Refresh();
@@ -3970,7 +4194,7 @@ export class ManageMetadataBase {
3970
4194
  // IS-A parent field sync: create/update virtual EntityField records for parent chain fields
3971
4195
  // Must run AFTER metadata refresh so it sees current soft PK/FK flags
3972
4196
  const stepISAStartTime = new Date();
3973
- const isaResult = await this.manageParentEntityFields(pool);
4197
+ const isaResult = await this.manageParentEntityFields(pool, excludeSchemas);
3974
4198
  if (!isaResult.success) {
3975
4199
  logError('Error managing IS-A parent entity fields');
3976
4200
  bSuccess = false;
@@ -4092,21 +4316,27 @@ export class ManageMetadataBase {
4092
4316
  * {@link applyVirtualEntitySoftKeys}.
4093
4317
  */
4094
4318
  async applySoftPKFKConfig(pool) {
4095
- // Check if additionalSchemaInfo is configured in mj.config.cjs
4096
- if (!configInfo.additionalSchemaInfo) {
4319
+ // Check if additionalSchemaInfo is configured (mj.config.cjs or the RSU env override)
4320
+ const configPath = ResolveAdditionalSchemaInfoPath();
4321
+ if (!configPath) {
4097
4322
  // No additional schema info configured - this is fine, it's optional
4098
4323
  return true;
4099
4324
  }
4100
- const configPath = path.join(currentWorkingDirectory, configInfo.additionalSchemaInfo);
4325
+ // A configured file that does not exist yet is normal: RSU writes it the first time it adds
4326
+ // a table, so a fresh checkout has none. Say where CodeGen looked, so a path that resolves
4327
+ // somewhere unexpected is visible (#5858). RSU itself fails the run when CodeGen creates no
4328
+ // entity for a table it added, which is what catches a real mismatch. An unreadable file
4329
+ // (below) is still a failure.
4101
4330
  if (!fs.existsSync(configPath)) {
4102
- logStatus(` ⚠️ additionalSchemaInfo configured but file not found: ${configPath}`);
4331
+ LogWarning(` additionalSchemaInfo is configured but no file exists yet at ${configPath}; no soft keys applied`);
4103
4332
  return true;
4104
4333
  }
4105
4334
  try {
4106
- logStatus(` Found ${configInfo.additionalSchemaInfo}, applying soft PK/FK configuration...`);
4335
+ logStatus(` Found ${configPath}, applying soft PK/FK configuration...`);
4107
4336
  const config = ManageMetadataBase.getSoftPKFKConfig();
4108
4337
  if (!config) {
4109
- return true;
4338
+ logError(` additionalSchemaInfo file could not be parsed: ${configPath}`);
4339
+ return false;
4110
4340
  }
4111
4341
  // Config supports two formats:
4112
4342
  // 1. Schema-as-key (template format): { "dbo": [{ "TableName": "Orders", ... }] }
@@ -5288,6 +5518,14 @@ export class ManageMetadataBase {
5288
5518
  }
5289
5519
  return [...out];
5290
5520
  }
5521
+ /**
5522
+ * Removes EntityField rows whose column no longer exists on the entity's base view or table.
5523
+ *
5524
+ * @param entityIDs Optional scope. {@link ManageEntityFields} omits it so every entity is scanned:
5525
+ * an entity orphaned by a view-only change is never in a change list (#4050).
5526
+ * @returns `success`, plus the distinct names of the entities rows were deleted from, so the
5527
+ * caller can bring them into scope for the Sequence renumber that follows.
5528
+ */
5291
5529
  async deleteUnneededEntityFields(pool, excludeSchemas, entityIDs) {
5292
5530
  try {
5293
5531
  // One SP call regardless of scope: pass the entire entity ID list as a comma-delimited
@@ -5312,15 +5550,29 @@ export class ManageMetadataBase {
5312
5550
  const result = await this.logSQLAndExecute(pool, sSQL, label, true);
5313
5551
  // result contains the DELETED entity fields. Get a distinct list of entity names
5314
5552
  // and add them to the modified entity list if they're not already in there.
5315
- if (result && result.length > 0) {
5316
- ManageMetadataBase.addNewEntitiesToModifiedList(result.map((r) => r.Entity));
5553
+ const prunedEntityNames = this.distinctPrunedEntityNames(result);
5554
+ if (prunedEntityNames.length > 0) {
5555
+ ManageMetadataBase.addNewEntitiesToModifiedList(prunedEntityNames);
5317
5556
  }
5318
- return true;
5557
+ return { success: true, prunedEntityNames };
5319
5558
  }
5320
5559
  catch (e) {
5321
- logError(e);
5322
- return false;
5560
+ logError(`Error deleting unneeded entity fields: ${e instanceof Error ? e.message : String(e)}`);
5561
+ return { success: false, prunedEntityNames: [] };
5562
+ }
5563
+ }
5564
+ /**
5565
+ * Distinct, non-blank entity names from the rows spDeleteUnneededEntityFields returns (one row per
5566
+ * deleted field, carrying the owning entity's name in `Entity`).
5567
+ */
5568
+ distinctPrunedEntityNames(rows) {
5569
+ if (!rows || rows.length === 0) {
5570
+ return [];
5323
5571
  }
5572
+ const names = rows
5573
+ .map(r => r.Entity)
5574
+ .filter((name) => typeof name === 'string' && name.trim().length > 0);
5575
+ return [...new Set(names)];
5324
5576
  }
5325
5577
  async manageEntityFieldValuesAndValidatorFunctions(pool, excludeSchemas, currentUser, skipDBUpdate) {
5326
5578
  try {
@@ -6069,12 +6321,12 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6069
6321
  * Checks if a table has a soft primary key defined in the additionalSchemaInfo JSON file (configured in mj.config.cjs)
6070
6322
  */
6071
6323
  hasSoftPrimaryKeyInConfig(schemaName, tableName) {
6072
- if (!configInfo.additionalSchemaInfo) {
6324
+ const configPath = ResolveAdditionalSchemaInfoPath();
6325
+ if (!configPath) {
6073
6326
  return false;
6074
6327
  }
6075
- const configPath = path.join(currentWorkingDirectory, configInfo.additionalSchemaInfo);
6076
6328
  if (!fs.existsSync(configPath)) {
6077
- logStatus(` [Soft PK Check] Config file not found at: ${configPath}`);
6329
+ logError(` [Soft PK Check] additionalSchemaInfo is configured but the file was not found: ${configPath}`);
6078
6330
  return false;
6079
6331
  }
6080
6332
  try {
@@ -7662,8 +7914,36 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
7662
7914
  isFieldEligibleForNameField(field) {
7663
7915
  if (field.IsVirtual === true && !this.isInheritedISAField(field))
7664
7916
  return false;
7917
+ if (this.isForeignKeyOrPolymorphicRecordIDField(field))
7918
+ return false;
7665
7919
  return this.isNameFieldTypeSafe(field);
7666
7920
  }
7921
+ /**
7922
+ * Rejects foreign-key columns (`RelatedEntityID`) and polymorphic record-ID
7923
+ * payload columns (`EntityIDFieldName` populated, or named `*RecordID` /
7924
+ * `*RecordPrimaryKey` such as `RecordID`, `SourceRecordID`, `TargetRecordID`,
7925
+ * `LinkedRecordID`, `SurvivingRecordID`) from being selected as `IsNameField`.
7926
+ *
7927
+ * Polymorphic `RecordID` columns use `nvarchar(450)` / `nvarchar(750)` so they
7928
+ * can hold composite primary keys or non-UUID strings, which previously tricked
7929
+ * Smart Field Identification into treating them as human-readable text names
7930
+ * and displaying raw UUIDs in tab headers, breadcrumbs, and link cards.
7931
+ */
7932
+ isForeignKeyOrPolymorphicRecordIDField(field) {
7933
+ const relatedEntityId = field.RelatedEntityID;
7934
+ if (relatedEntityId && String(relatedEntityId).trim().length > 0) {
7935
+ return true;
7936
+ }
7937
+ const entityIdFieldName = field.EntityIDFieldName;
7938
+ if (entityIdFieldName && String(entityIdFieldName).trim().length > 0) {
7939
+ return true;
7940
+ }
7941
+ const name = (field.Name ?? '').trim();
7942
+ if (/^(?:[A-Z][A-Za-z0-9]*?)?Record(?:ID|PrimaryKey)$/.test(name)) {
7943
+ return true;
7944
+ }
7945
+ return false;
7946
+ }
7667
7947
  /**
7668
7948
  * The TYPE half of {@link isFieldEligibleForNameField}, with no virtuality
7669
7949
  * opinion: a primary key, a non-text type, or unbounded (MAX) text can never be