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

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 (54) hide show
  1. package/README.md +7 -0
  2. package/dist/Angular/angular-codegen.d.ts.map +1 -1
  3. package/dist/Angular/angular-codegen.js +2 -0
  4. package/dist/Angular/angular-codegen.js.map +1 -1
  5. package/dist/Config/config.d.ts +36 -0
  6. package/dist/Config/config.d.ts.map +1 -1
  7. package/dist/Config/config.js +33 -0
  8. package/dist/Config/config.js.map +1 -1
  9. package/dist/Database/codeGenDatabaseProvider.d.ts +118 -2
  10. package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
  11. package/dist/Database/codeGenDatabaseProvider.js +234 -4
  12. package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
  13. package/dist/Database/heal-schema-params.d.ts +7 -0
  14. package/dist/Database/heal-schema-params.d.ts.map +1 -1
  15. package/dist/Database/heal-schema-params.js +5 -0
  16. package/dist/Database/heal-schema-params.js.map +1 -1
  17. package/dist/Database/manage-metadata.d.ts +169 -1
  18. package/dist/Database/manage-metadata.d.ts.map +1 -1
  19. package/dist/Database/manage-metadata.js +399 -9
  20. package/dist/Database/manage-metadata.js.map +1 -1
  21. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +36 -3
  22. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
  23. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +104 -23
  24. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
  25. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.d.ts +2 -0
  26. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.d.ts.map +1 -0
  27. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js +127 -0
  28. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js.map +1 -0
  29. package/dist/Database/providers/postgresql/metadataSupportObjects.js +155 -2
  30. package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
  31. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +23 -1
  32. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
  33. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +77 -19
  34. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
  35. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.d.ts +2 -0
  36. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.d.ts.map +1 -0
  37. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js +141 -0
  38. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js.map +1 -0
  39. package/dist/Database/sql_codegen.d.ts +39 -1
  40. package/dist/Database/sql_codegen.d.ts.map +1 -1
  41. package/dist/Database/sql_codegen.js +100 -2
  42. package/dist/Database/sql_codegen.js.map +1 -1
  43. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts +9 -0
  44. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts.map +1 -1
  45. package/dist/Manifest/GenerateClassRegistrationsManifest.js +28 -7
  46. package/dist/Manifest/GenerateClassRegistrationsManifest.js.map +1 -1
  47. package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
  48. package/dist/Misc/entity_subclasses_codegen.js +18 -2
  49. package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
  50. package/dist/runCodeGen.d.ts +14 -0
  51. package/dist/runCodeGen.d.ts.map +1 -1
  52. package/dist/runCodeGen.js +21 -1
  53. package/dist/runCodeGen.js.map +1 -1
  54. package/package.json +29 -29
@@ -1,5 +1,5 @@
1
1
  import { SQLServerDialect, PostgreSQLDialect } from '@memberjunction/sql-dialect';
2
- import { CodeGenDatabaseProvider } from './codeGenDatabaseProvider.js';
2
+ import { CodeGenDatabaseProvider, SetBaseViewExclusionsPermitted, BaseViewExclusionsPermitted } from './codeGenDatabaseProvider.js';
3
3
  import { AnalyzeQueryForMaterialization, DetectAggregationKeyColumns, DetectAdditiveMeasures, MATERIALIZATION_SURROGATE_COLUMN } from './materializationAnalysis.js';
4
4
  import { EvaluateMaterializationDrift } from './materializationDrift.js';
5
5
  import { ClassifyQueryParameters, BuildHeldValues } from './materializationParamClassifier.js';
@@ -65,6 +65,27 @@ export class ManageMetadataBase {
65
65
  * references to it on this so codegen doesn't throw on a DB lacking the materialization schema. Cached per run.
66
66
  */
67
67
  this._materializedResultTableExists = null;
68
+ /**
69
+ * Whether this database's `spDeleteUnneededEntityFields` accepts a `ProtectedFieldNames`
70
+ * parameter. Cached for the run (a routine signature cannot change mid-run).
71
+ *
72
+ * This is the interlock for base-view column exclusions. The prune's orphan test is "does this
73
+ * EntityField have a column in `vwSQLColumnsAndEntityFields`?", and that view resolves columns
74
+ * VIEW-FIRST (`COALESCE(view_object_id, object_id)`) on both dialects. So excluding a physical
75
+ * column from a base view makes its `EntityField` row look orphaned, and the next CodeGen run
76
+ * DELETES it — silently taking out every metadata-mediated read and write of that column.
77
+ *
78
+ * CodeGen therefore refuses to apply an exclusion it cannot protect. The PostgreSQL routine ships
79
+ * with CodeGen (`metadataSupportObjects.ts`) so it always has the parameter; SQL Server's ships in
80
+ * migrations, so on a database whose migration set predates the parameter the answer is false and
81
+ * the exclusion is declined with a message naming the prerequisite. Probing rather than
82
+ * dialect-branching means the SQL Server half activates the moment the migration lands, with no
83
+ * further code change.
84
+ *
85
+ * INFORMATION_SCHEMA.PARAMETERS exists on both platforms. PostgreSQL reports the declared name
86
+ * with its `p_` prefix; SQL Server reports it with a leading `@`; so the comparison strips both.
87
+ */
88
+ this._pruneSupportsProtectedFieldNames = null;
68
89
  /**
69
90
  * Per-run cache of the entity NAMES (trimmed + lowercased) that an API-KEY row filter
70
91
  * (`APIKeyScope.RowFilterID`) or an API-APPLICATION row ceiling (`APIApplicationScope.RowFilterID`) binds to.
@@ -2079,6 +2100,10 @@ export class ManageMetadataBase {
2079
2100
  return false;
2080
2101
  }
2081
2102
  }
2103
+ // Settle base-view column exclusions BEFORE anything generates a view. The decision depends on
2104
+ // whether this database's field prune can be told to leave the excluded columns' metadata
2105
+ // alone, which is a database fact and therefore only knowable here.
2106
+ await this.resolveBaseViewExclusionSupport(pool);
2082
2107
  // Authored exclude list (sys, staging, …) must be captured BEFORE includeSchemas is
2083
2108
  // compiled into excludeSchemas. Heal EXEC statements use that original list plus
2084
2109
  // @IncludedSchemaNames — never the sibling snapshot of this machine's database.
@@ -3454,15 +3479,100 @@ export class ManageMetadataBase {
3454
3479
  const relCount = relationshipCountMap.get(parentEntityID) || 0;
3455
3480
  const sequence = relCount + 1;
3456
3481
  const newEntityRelationshipUUID = this.createNewUUID();
3482
+ // EntityKeyField names the column on the PARENT (the EntityID side) that carries the join
3483
+ // value. It is NULL for an ordinary FK-to-primary-key relationship, where every consumer
3484
+ // correctly falls back to the parent's PK. It is load-bearing whenever the FK points at a
3485
+ // NON-PK column: see resolveRelationshipEntityKeyField.
3486
+ const entityKeyField = this.resolveRelationshipEntityKeyField(f, parentEntity);
3487
+ const keyFieldColumn = entityKeyField ? `, ${this.qi('EntityKeyField')}` : '';
3488
+ const keyFieldValue = entityKeyField ? `, '${entityKeyField.replace(/'/g, "''")}'` : '';
3457
3489
  const checkQuery = `SELECT 1 FROM ${this.qs(MjCoreSchema(), 'EntityRelationship')} WHERE ${this.qi('ID')} = '${newEntityRelationshipUUID}'`;
3458
- const insertSQL = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityRelationship')} (${this.qi('ID')}, ${this.qi('EntityID')}, ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityJoinField')}, ${this.qi('Type')}, ${this.qi('BundleInAPI')}, ${this.qi('DisplayInForm')}, ${this.qi('Sequence')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')})
3459
- VALUES ('${newEntityRelationshipUUID}', '${f.RelatedEntityID}', '${f.EntityID}', '${f.Name}', 'One To Many', ${this.boolLit(true)}, ${this.boolLit(true)}, ${sequence}, ${this.utcNow()}, ${this.utcNow()})`;
3490
+ const insertSQL = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityRelationship')} (${this.qi('ID')}, ${this.qi('EntityID')}, ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityJoinField')}${keyFieldColumn}, ${this.qi('Type')}, ${this.qi('BundleInAPI')}, ${this.qi('DisplayInForm')}, ${this.qi('Sequence')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')})
3491
+ VALUES ('${newEntityRelationshipUUID}', '${f.RelatedEntityID}', '${f.EntityID}', '${f.Name}'${keyFieldValue}, 'One To Many', ${this.boolLit(true)}, ${this.boolLit(true)}, ${sequence}, ${this.utcNow()}, ${this.utcNow()})`;
3460
3492
  relationshipCountMap.set(parentEntityID, sequence);
3461
3493
  return `
3462
3494
  /* Create Entity Relationship: ${parentEntity.Name} -> ${e.Name} (One To Many via ${f.Name}) */
3463
3495
  ${this.dbProvider.conditionalInsertSQL(checkQuery, insertSQL)};
3464
3496
  `;
3465
3497
  }
3498
+ /**
3499
+ * Resolves the `EntityRelationship.EntityKeyField` value for a discovered FK field, or `null`
3500
+ * when the relationship joins the parent's primary key and the column therefore must stay NULL.
3501
+ *
3502
+ * WHY THIS EXISTS. A foreign key does not have to point at a primary key. `EntityField` records
3503
+ * the referenced column in `RelatedEntityFieldName` — populated for declared FKs by the provider
3504
+ * introspection query and for soft FKs by `applySoftPKFKConfig` — but nothing carried it across
3505
+ * into the relationship row. `EntityRelationshipInfo.EntityKeyField` is the only place a consumer
3506
+ * can learn it, and all three consumers fall back to the parent's first primary key when it is
3507
+ * blank (`entityInfo.ts` BuildRelationshipViewParams, `entity-helpers.ts`,
3508
+ * `DependencyGraphWalker.ts`). So a relationship over a non-PK join column silently queried the
3509
+ * wrong column and returned zero rows for every parent record — measured on an imported schema
3510
+ * whose real keys are external ids: 60 relationships, 0 rows each.
3511
+ *
3512
+ * NULL IS THE CORRECT VALUE FOR AN ORDINARY FK, not merely an acceptable one. The PK fallback is
3513
+ * the documented contract, a stored 'ID' would duplicate it, and emitting the column only when it
3514
+ * differs keeps the generated SQL byte-identical for every FK-to-PK relationship — which is all
3515
+ * of them in core MJ.
3516
+ *
3517
+ * Returns null when: no referenced column was recorded; the referenced column IS the parent's
3518
+ * primary key; or the parent has a composite key (a single-column join cannot address it, and
3519
+ * guessing which component to use would be worse than the existing fallback).
3520
+ */
3521
+ resolveRelationshipEntityKeyField(f, parentEntity) {
3522
+ const referenced = String(f.RelatedEntityFieldName ?? '').trim();
3523
+ if (referenced.length === 0) {
3524
+ return null;
3525
+ }
3526
+ const pkFields = parentEntity.PrimaryKeys ?? [];
3527
+ if (pkFields.length !== 1) {
3528
+ return null;
3529
+ }
3530
+ if (pkFields[0].Name.trim().toLowerCase() === referenced.toLowerCase()) {
3531
+ return null;
3532
+ }
3533
+ // The column must exist on the parent, or the consumer's `record.Get(EntityKeyField)` would
3534
+ // read undefined and build `WHERE col = undefined`. A referenced column MJ has no field for
3535
+ // is a metadata gap to report, not one to encode into a relationship row.
3536
+ const match = parentEntity.Fields.find(pf => pf.Name.trim().toLowerCase() === referenced.toLowerCase());
3537
+ if (!match) {
3538
+ logError(` > resolveRelationshipEntityKeyField: ${parentEntity.Name} has no field named '${referenced}' (referenced by FK ${f.Name}); leaving EntityKeyField NULL so the primary-key fallback applies.`);
3539
+ return null;
3540
+ }
3541
+ return match.Name.trim();
3542
+ }
3543
+ /**
3544
+ * Emits the UPDATE that brings an existing relationship row's `EntityKeyField` into line with the
3545
+ * schema, or `''` when it already agrees.
3546
+ *
3547
+ * This is the half that actually repairs a live database. A relationship whose
3548
+ * `RelatedEntityJoinField` is already correct takes the "exact match" path and is skipped, so
3549
+ * rows created before `EntityKeyField` was written stay blank forever and keep returning zero
3550
+ * rows. Honours `AutoUpdateFromSchema` exactly as the join-field reassignment below does: a row
3551
+ * an operator has taken ownership of is never touched.
3552
+ */
3553
+ buildRelationshipEntityKeyFieldHealSQL(r, f, md) {
3554
+ if (!r.AutoUpdateFromSchema) {
3555
+ return '';
3556
+ }
3557
+ const parentEntity = md.Entities.find(e => UUIDsEqual(e.ID, f.RelatedEntityID));
3558
+ if (!parentEntity) {
3559
+ return '';
3560
+ }
3561
+ const desired = this.resolveRelationshipEntityKeyField(f, parentEntity);
3562
+ const current = String(r.EntityKeyField ?? '').trim();
3563
+ if ((desired ?? '') === current) {
3564
+ return '';
3565
+ }
3566
+ const literal = desired === null ? 'NULL' : `'${desired.replace(/'/g, "''")}'`;
3567
+ logStatus(` > Healing EntityRelationship key field: '${current}' -> ${desired ?? 'NULL'} (ID: ${r.ID})`);
3568
+ return `
3569
+ /* Heal EntityRelationship EntityKeyField from '${current}' to ${desired ?? 'NULL'} (non-PK join column) */
3570
+ UPDATE ${this.qs(MjCoreSchema(), 'EntityRelationship')}
3571
+ SET ${this.qi('EntityKeyField')} = ${literal},
3572
+ ${this.qi('__mj_UpdatedAt')} = ${this.utcNow()}
3573
+ WHERE ${this.qi('ID')} = '${r.ID}';
3574
+ `;
3575
+ }
3466
3576
  /**
3467
3577
  * Groups FK fields by their entity pair key (ParentEntityID|ChildEntityID).
3468
3578
  * This ensures all FK fields for the same entity pair are processed together,
@@ -3513,6 +3623,13 @@ export class ManageMetadataBase {
3513
3623
  let sql = '';
3514
3624
  // Build sets for matching
3515
3625
  const fkFieldNames = new Set(fkFields.map(f => String(f.Name).trim()));
3626
+ const fkFieldsByName = new Map();
3627
+ for (const f of fkFields) {
3628
+ const key = String(f.Name).trim();
3629
+ if (!fkFieldsByName.has(key)) {
3630
+ fkFieldsByName.set(key, f);
3631
+ }
3632
+ }
3516
3633
  const matchedRelationshipIDs = new Set();
3517
3634
  const matchedFieldNames = new Set();
3518
3635
  // Pass 1: exact matches — relationship already has the correct JoinField
@@ -3521,6 +3638,13 @@ export class ManageMetadataBase {
3521
3638
  if (fkFieldNames.has(joinField) && !matchedFieldNames.has(joinField)) {
3522
3639
  matchedRelationshipIDs.add(String(r.ID));
3523
3640
  matchedFieldNames.add(joinField);
3641
+ // The join field agrees, so nothing below will look at this row again — but
3642
+ // EntityKeyField may still be stale or (for every row written before it was emitted)
3643
+ // blank. That is the state that returns zero rows on a non-PK join, so heal it here.
3644
+ const matchedField = fkFieldsByName.get(joinField);
3645
+ if (matchedField) {
3646
+ sql += this.buildRelationshipEntityKeyFieldHealSQL(r, matchedField, md);
3647
+ }
3524
3648
  }
3525
3649
  }
3526
3650
  // Pass 2: assign unmatched FK fields to unmatched auto-update relationships
@@ -3541,6 +3665,10 @@ export class ManageMetadataBase {
3541
3665
  WHERE ${this.qi('ID')} = '${r.ID}';
3542
3666
  `;
3543
3667
  }
3668
+ // Reassigning the join field can also change which parent column the join addresses, so
3669
+ // the key field has to move with it — including back to NULL when the new FK targets the
3670
+ // parent's primary key.
3671
+ sql += this.buildRelationshipEntityKeyFieldHealSQL(r, f, md);
3544
3672
  }
3545
3673
  // Pass 3: create new relationships for any remaining unmatched FK fields
3546
3674
  const remainingFields = unmatchedFields.slice(unmatchedRelationships.length);
@@ -4044,6 +4172,15 @@ export class ManageMetadataBase {
4044
4172
  async applySoftKeysToTables(pool, tables, clearUniqueOnCompositeKey) {
4045
4173
  let totalPKs = 0;
4046
4174
  let totalFKs = 0;
4175
+ const conflicts = this.findConflictingSoftForeignKeys(tables);
4176
+ for (const c of conflicts) {
4177
+ logError(` Soft FK ${c.SchemaName}.${c.TableName}.${c.FieldName} is declared with ${c.Targets.length} different targets (${c.Targets.join(', ')}). ` +
4178
+ `None of them is applied and the field is left as it is; keep one declaration in additionalSchemaInfo.`);
4179
+ }
4180
+ const skipFields = new Set(conflicts.map(c => this.softFKFieldKey(c.SchemaName, c.TableName, c.FieldName)));
4181
+ // Primary keys first, for every table, so the FK pass sees each target's soft PK whatever the
4182
+ // order of the tables in the file.
4183
+ const resolved = [];
4047
4184
  for (const table of tables) {
4048
4185
  // Look up entity ID (SELECT query - no need to log to migration file)
4049
4186
  const entityLookupSQL = `SELECT ID FROM ${this.qs(MjCoreSchema(), 'Entity')} WHERE SchemaName = '${EscapeSQLString(table.SchemaName)}' AND BaseTable = '${EscapeSQLString(table.TableName)}'`;
@@ -4055,11 +4192,108 @@ export class ManageMetadataBase {
4055
4192
  const entityId = entityResult.recordset[0].ID;
4056
4193
  const primaryKeys = table.PrimaryKey || [];
4057
4194
  totalPKs += await this.applySoftPrimaryKeys(pool, table, entityId, clearUniqueOnCompositeKey && primaryKeys.length > 1);
4058
- totalFKs += await this.applySoftForeignKeys(pool, table, entityId);
4195
+ resolved.push({ table, entityId });
4196
+ }
4197
+ for (const { table, entityId } of resolved) {
4198
+ totalFKs += await this.applySoftForeignKeys(pool, table, entityId, skipFields);
4059
4199
  }
4060
4200
  logStatus(` Applied ${totalPKs} soft PK(s) and ${totalFKs} soft FK(s) from configuration`);
4061
4201
  return totalPKs + totalFKs;
4062
4202
  }
4203
+ /**
4204
+ * Finds fields declared as a soft FK to more than one target. Each declaration is applied as its
4205
+ * own UPDATE, so without this check the last one in the file would win silently.
4206
+ * Names compare case-insensitively: on SQL Server `ID` and `id` are the same column; on
4207
+ * PostgreSQL one of the two does not exist, which the target check reports.
4208
+ */
4209
+ findConflictingSoftForeignKeys(tables) {
4210
+ const byField = new Map();
4211
+ for (const table of tables) {
4212
+ for (const fk of table.ForeignKeys || []) {
4213
+ const fieldKey = this.softFKFieldKey(table.SchemaName, table.TableName, fk.FieldName);
4214
+ const target = `${fk.SchemaName || table.SchemaName}.${fk.RelatedTable}.${fk.RelatedField}`;
4215
+ let entry = byField.get(fieldKey);
4216
+ if (!entry) {
4217
+ entry = { SchemaName: table.SchemaName, TableName: table.TableName, FieldName: fk.FieldName, Targets: [] };
4218
+ byField.set(fieldKey, entry);
4219
+ }
4220
+ if (!entry.Targets.some(t => t.toLowerCase() === target.toLowerCase())) {
4221
+ entry.Targets.push(target);
4222
+ }
4223
+ }
4224
+ }
4225
+ return [...byField.values()].filter(e => e.Targets.length > 1);
4226
+ }
4227
+ softFKFieldKey(schemaName, tableName, fieldName) {
4228
+ return `${schemaName}.${tableName}.${fieldName}`.toLowerCase();
4229
+ }
4230
+ /**
4231
+ * Checks a soft FK's target column against the related entity's fields. The name matches
4232
+ * case-sensitively on PostgreSQL, where `ID` and `id` are different identifiers, and
4233
+ * case-insensitively on SQL Server. A column of a multi-column primary key is not unique on its
4234
+ * own, so a join on it alone can return several rows. That is decided before `IsUnique` is read:
4235
+ * on a live SQL Server run, both columns of a two-column primary key carried `IsUnique = 1`.
4236
+ */
4237
+ checkSoftFKTarget(relatedFields, relatedField, caseSensitive) {
4238
+ const target = relatedFields.find(f => caseSensitive ? f.Name === relatedField : f.Name.toLowerCase() === relatedField.toLowerCase());
4239
+ if (!target) {
4240
+ return { ResolvedName: null, IsUnique: false };
4241
+ }
4242
+ const pkCount = relatedFields.filter(f => f.IsPrimaryKey).length;
4243
+ if (target.IsPrimaryKey && pkCount > 1) {
4244
+ return { ResolvedName: target.Name, IsUnique: false, NotUniqueReason: `it is one column of a ${pkCount}-column primary key` };
4245
+ }
4246
+ if (target.IsPrimaryKey) {
4247
+ return { ResolvedName: target.Name, IsUnique: true };
4248
+ }
4249
+ if (target.IsUnique) {
4250
+ return { ResolvedName: target.Name, IsUnique: true, UniqueByFlagOnly: true };
4251
+ }
4252
+ return { ResolvedName: target.Name, IsUnique: false, NotUniqueReason: 'it is neither a primary key nor unique' };
4253
+ }
4254
+ /**
4255
+ * Confirms a target that only `IsUnique` vouches for against the database's unique indexes.
4256
+ * Schema sync sets `IsUnique` on every column of a composite unique constraint, so the flag
4257
+ * alone cannot say whether a join on the column returns one row. A failed or unsupported
4258
+ * lookup keeps the flag's answer.
4259
+ */
4260
+ async confirmSoftFKTargetUnique(pool, schemaName, tableName, target) {
4261
+ if (!target.UniqueByFlagOnly || target.ResolvedName === null) {
4262
+ return target;
4263
+ }
4264
+ const sql = this.uniqueIndexMembershipSQL(schemaName, tableName, target.ResolvedName);
4265
+ if (!sql) {
4266
+ return target;
4267
+ }
4268
+ try {
4269
+ const res = await this.runQuery(pool, sql);
4270
+ const rows = res.recordset.map(r => ({ KeyColumnCount: Number(r.KeyColumnCount), IsIncludedColumn: this.isFlagSet(r.IsIncludedColumn) }));
4271
+ return this.uniquenessFromIndexes(target, rows);
4272
+ }
4273
+ catch (e) {
4274
+ LogWarning(` ⚠️ Could not read the unique indexes of ${schemaName}.${tableName}.${target.ResolvedName}; trusting IsUnique: ${e}`);
4275
+ return target;
4276
+ }
4277
+ }
4278
+ /** The platform's unique-index lookup for a column, or null when it has none. */
4279
+ uniqueIndexMembershipSQL(schemaName, tableName, columnName) {
4280
+ return this.dbProvider.GetUniqueIndexMembershipSQL(schemaName, tableName, columnName);
4281
+ }
4282
+ /**
4283
+ * Decides uniqueness from the unique indexes a column belongs to. A single-key-column index makes
4284
+ * it unique. Otherwise a composite unique index, or being only an INCLUDE column, means it is not.
4285
+ * No rows (a view, or IsUnique set by configuration) keeps the target as it is.
4286
+ */
4287
+ uniquenessFromIndexes(target, indexes) {
4288
+ const keyIndexes = indexes.filter(ix => !ix.IsIncludedColumn);
4289
+ if (indexes.length === 0 || keyIndexes.some(ix => ix.KeyColumnCount === 1)) {
4290
+ return target;
4291
+ }
4292
+ const reason = keyIndexes.length > 0
4293
+ ? `it is one column of a ${Math.min(...keyIndexes.map(ix => ix.KeyColumnCount))}-column unique constraint`
4294
+ : 'it is only an INCLUDE column of a unique index';
4295
+ return { ResolvedName: target.ResolvedName, IsUnique: false, NotUniqueReason: reason };
4296
+ }
4063
4297
  /**
4064
4298
  * Sets IsPrimaryKey = 1 AND IsSoftPrimaryKey = 1 on each configured key column.
4065
4299
  * IsPrimaryKey is the source of truth, IsSoftPrimaryKey protects it from schema sync.
@@ -4100,12 +4334,17 @@ export class ManageMetadataBase {
4100
4334
  /**
4101
4335
  * Sets RelatedEntityID, RelatedEntityFieldName and IsSoftForeignKey = 1 on each configured foreign
4102
4336
  * key column. RelatedEntityID is the source of truth, IsSoftForeignKey protects it from schema sync.
4337
+ * A field in `skipFields` (declared with conflicting targets) and a target column the related
4338
+ * entity does not have are skipped; a target that is not unique on its own is applied with a warning.
4103
4339
  * @returns the number of UPDATEs written
4104
4340
  */
4105
- async applySoftForeignKeys(pool, table, entityId) {
4341
+ async applySoftForeignKeys(pool, table, entityId, skipFields = new Set()) {
4106
4342
  const schema = MjCoreSchema();
4107
4343
  let written = 0;
4108
4344
  for (const fk of table.ForeignKeys || []) {
4345
+ if (skipFields.has(this.softFKFieldKey(table.SchemaName, table.TableName, fk.FieldName))) {
4346
+ continue; // conflicting declarations, reported once by applySoftKeysToTables
4347
+ }
4109
4348
  const fkSchema = fk.SchemaName || table.SchemaName;
4110
4349
  // Look up related entity ID (SELECT query - no need to log to migration file)
4111
4350
  const relatedLookupSQL = `SELECT ID FROM ${this.qs(schema, 'Entity')} WHERE SchemaName = '${EscapeSQLString(fkSchema)}' AND BaseTable = '${EscapeSQLString(fk.RelatedTable)}'`;
@@ -4116,6 +4355,22 @@ export class ManageMetadataBase {
4116
4355
  }
4117
4356
  const relatedEntityId = relatedEntityResult.recordset[0].ID;
4118
4357
  const fieldName = EscapeSQLString(fk.FieldName);
4358
+ // The target column must exist on the related entity, and should be unique on its own:
4359
+ // a label join on a non-unique column multiplies the rows of the generated base view.
4360
+ const targetFieldsSQL = `SELECT ${this.qi('Name')}, ${this.qi('IsPrimaryKey')}, ${this.qi('IsUnique')}
4361
+ FROM ${this.qs(schema, 'EntityField')}
4362
+ WHERE ${this.qi('EntityID')} = '${relatedEntityId}'`;
4363
+ const targetFieldsRes = await this.runQuery(pool, targetFieldsSQL);
4364
+ const flagCheck = this.checkSoftFKTarget(targetFieldsRes.recordset.map(r => ({ Name: String(r.Name), IsPrimaryKey: this.isFlagSet(r.IsPrimaryKey), IsUnique: this.isFlagSet(r.IsUnique) })), fk.RelatedField, DbPlatform() === 'postgresql');
4365
+ const target = await this.confirmSoftFKTargetUnique(pool, fkSchema, fk.RelatedTable, flagCheck);
4366
+ if (target.ResolvedName === null) {
4367
+ LogWarning(` ⚠️ Soft FK ${table.SchemaName}.${table.TableName}.${fk.FieldName} targets ${fkSchema}.${fk.RelatedTable}.${fk.RelatedField}, which has no such column - skipping`);
4368
+ continue;
4369
+ }
4370
+ if (!target.IsUnique) {
4371
+ LogWarning(` ⚠️ Soft FK ${table.SchemaName}.${table.TableName}.${fk.FieldName} targets ${fkSchema}.${fk.RelatedTable}.${target.ResolvedName}, but ${target.NotUniqueReason}; a join on it can return more than one row`);
4372
+ }
4373
+ const relatedField = target.ResolvedName;
4119
4374
  const checkSQL = `SELECT ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityFieldName')}, ${this.qi('IsSoftForeignKey')}, ${this.qi('AutoUpdateRelatedEntityInfo')}
4120
4375
  FROM ${this.qs(schema, 'EntityField')}
4121
4376
  WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
@@ -4128,7 +4383,7 @@ export class ManageMetadataBase {
4128
4383
  const curRelId = String(row.RelatedEntityID ?? '').trim().toLowerCase();
4129
4384
  const curRelField = String(row.RelatedEntityFieldName ?? '').trim().toLowerCase();
4130
4385
  if (curRelId === String(relatedEntityId).trim().toLowerCase() &&
4131
- curRelField === String(fk.RelatedField).trim().toLowerCase() &&
4386
+ curRelField === relatedField.trim().toLowerCase() &&
4132
4387
  this.isFlagSet(row.IsSoftForeignKey) &&
4133
4388
  !this.isFlagSet(row.AutoUpdateRelatedEntityInfo)) {
4134
4389
  continue; // Already correctly set, skip write
@@ -4136,13 +4391,13 @@ export class ManageMetadataBase {
4136
4391
  const sSQL = `UPDATE ${this.qs(schema, 'EntityField')}
4137
4392
  SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()},
4138
4393
  ${this.qi('RelatedEntityID')} = '${relatedEntityId}',
4139
- ${this.qi('RelatedEntityFieldName')} = '${EscapeSQLString(fk.RelatedField)}',
4394
+ ${this.qi('RelatedEntityFieldName')} = '${EscapeSQLString(relatedField)}',
4140
4395
  ${this.qi('IsSoftForeignKey')} = ${this.boolLit(true)},
4141
4396
  ${this.qi('AutoUpdateRelatedEntityInfo')} = ${this.boolLit(false)}
4142
4397
  WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
4143
- const result = await this.logSQLAndExecute(pool, sSQL, `Set soft FK for ${table.SchemaName}.${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${fk.RelatedField}`);
4398
+ const result = await this.logSQLAndExecute(pool, sSQL, `Set soft FK for ${table.SchemaName}.${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${relatedField}`);
4144
4399
  if (result !== null) {
4145
- logStatus(` ✓ Set soft FK for ${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${fk.RelatedField}`);
4400
+ logStatus(` ✓ Set soft FK for ${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${relatedField}`);
4146
4401
  written++;
4147
4402
  }
4148
4403
  }
@@ -4903,6 +5158,136 @@ export class ManageMetadataBase {
4903
5158
  logStatus(` > Applied ${applied} schema name prefix/suffix rules from additionalSchemaInfo.json`);
4904
5159
  }
4905
5160
  }
5161
+ /**
5162
+ * Returns the names of entities whose BASE VIEW exposes a view-only column that MJ has no
5163
+ * `EntityField` for — the virtual-field drift probe.
5164
+ *
5165
+ * WHY THIS IS NEEDED AND WHY NOTHING ELSE FINDS IT. Pass 2 of `ManageEntityFields` is scoped to
5166
+ * `NewEntityList ∪ ModifiedEntityList`, and the only writer of `ModifiedEntityList` is the
5167
+ * reconciler pass — it lists entities something CHANGED on during THIS run. A related-entity name
5168
+ * field whose `EntityField` row was missed once therefore drops out of scope permanently: nothing
5169
+ * changes on that entity again, so it is never in the list, so pass 2 never revisits it, so the
5170
+ * row is never created. The only recovery was `forceRegeneration`, which reprocesses every entity
5171
+ * in the database to heal one.
5172
+ *
5173
+ * The cost of leaving it is not cosmetic. `BaseEntity.InnerLoad` reads the base view and then
5174
+ * looks up each returned column in metadata; a column with no `EntityField` throws, so EVERY
5175
+ * record form for that entity fails — measured at 145 entities on one imported schema.
5176
+ *
5177
+ * WHAT THE PROBE MATCHES. `vwSQLColumnsAndEntityFields` is the catalog view both dialects already
5178
+ * use for exactly this comparison (`EntityFieldID IS NULL` is how `getPendingEntityFieldsSQL`
5179
+ * finds columns needing a field). Adding `IsVirtual <> 0` narrows it to VIEW-ONLY columns: those
5180
+ * are the ones pass 2 exists to create, and they are the ones pass 1 structurally cannot see,
5181
+ * because their names are invented during Step 2's view generation and only exist in the view.
5182
+ * New PHYSICAL columns are excluded — they carry `IsVirtual = 0`, pass 1 already finds them, and
5183
+ * pulling them in here would widen the scoped pass back out to a full scan.
5184
+ *
5185
+ * The observed spelling was a `<fk>_Virtual` alias, but the suffix is incidental (it is only
5186
+ * appended on a name collision, see `sql_codegen.ts` safeAlias); the load-bearing property is
5187
+ * "view-only column with no EntityField", so the probe tests that and not the name.
5188
+ *
5189
+ * `IsVirtual <> 0` rather than `= 1` deliberately: the column is an INTEGER in the PostgreSQL view
5190
+ * and a bit-valued expression in the SQL Server one, and `<> 0` is correct for both.
5191
+ */
5192
+ async FindVirtualFieldDriftEntities(pool, excludeSchemas) {
5193
+ try {
5194
+ const excluded = (excludeSchemas ?? []).filter(sc => sc && sc.trim().length > 0);
5195
+ const schemaFilter = excluded.length > 0
5196
+ ? ` AND ${this.qi('SchemaName')} NOT IN (${excluded.map(sc => `'${sc.replace(/'/g, "''")}'`).join(',')})`
5197
+ : '';
5198
+ const sSQL = `SELECT DISTINCT ${this.qi('Entity')}
5199
+ FROM ${this.qs(MjCoreSchema(), 'vwSQLColumnsAndEntityFields')}
5200
+ WHERE ${this.qi('EntityFieldID')} IS NULL
5201
+ AND ${this.qi('IsVirtual')} <> 0
5202
+ AND ${this.qi('Entity')} IS NOT NULL${schemaFilter}`;
5203
+ const result = await this.runQuery(pool, sSQL);
5204
+ const names = (result.recordset ?? [])
5205
+ .map((r) => String(r.Entity ?? '').trim())
5206
+ .filter((n) => n.length > 0);
5207
+ if (names.length > 0) {
5208
+ logStatus(` > Virtual-field drift probe: ${names.length} entit${names.length === 1 ? 'y' : 'ies'} carry a view-only column with no EntityField — adding to the Pass 2 scope.`);
5209
+ }
5210
+ return [...new Set(names)];
5211
+ }
5212
+ catch (e) {
5213
+ // A probe that cannot run must not take the run down: the pre-probe behaviour (drift
5214
+ // stays unhealed) is strictly better than a failed CodeGen.
5215
+ logError(` > Virtual-field drift probe failed; Pass 2 scope is unchanged. ${e}`);
5216
+ return [];
5217
+ }
5218
+ }
5219
+ async pruneSupportsProtectedFieldNames(pool) {
5220
+ if (this._pruneSupportsProtectedFieldNames === null) {
5221
+ try {
5222
+ // PARAMETER_MODE = 'IN' matters: a PostgreSQL `RETURNS TABLE` function also reports its
5223
+ // OUTPUT columns here (verified on PG 16), and SQL Server reports input parameters as 'IN'
5224
+ // too, so the filter is both necessary and portable.
5225
+ const sql = `SELECT PARAMETER_NAME FROM INFORMATION_SCHEMA.PARAMETERS ` +
5226
+ `WHERE SPECIFIC_SCHEMA = '${MjCoreSchema()}' ` +
5227
+ `AND SPECIFIC_NAME LIKE 'spDeleteUnneededEntityFields%' AND PARAMETER_MODE = 'IN'`;
5228
+ const result = await this.runQuery(pool, sql);
5229
+ const rows = (result.recordset ?? []);
5230
+ this._pruneSupportsProtectedFieldNames = rows.some(r => {
5231
+ const raw = String(r.PARAMETER_NAME ?? r.parameter_name ?? '').trim();
5232
+ return raw.replace(/^@/, '').replace(/^p_/i, '').toLowerCase() === 'protectedfieldnames';
5233
+ });
5234
+ }
5235
+ catch (e) {
5236
+ // Cannot prove the parameter exists → treat it as absent. The consequence of guessing
5237
+ // wrong in this direction is "the exclusion is declined"; the other direction is
5238
+ // "metadata is deleted".
5239
+ logError(` > Could not read spDeleteUnneededEntityFields parameters; base-view column exclusions will be declined. ${e}`);
5240
+ this._pruneSupportsProtectedFieldNames = false;
5241
+ }
5242
+ }
5243
+ return this._pruneSupportsProtectedFieldNames;
5244
+ }
5245
+ /**
5246
+ * Decides whether base-view column exclusions may be applied in this run, and records the answer
5247
+ * where the (synchronous, connectionless) base-view generators can read it.
5248
+ *
5249
+ * Called during metadata management, which runs BEFORE SQL generation, so the flag is settled by
5250
+ * the time any base view is emitted. A run that never calls this leaves exclusions disabled and
5251
+ * emits `alias.*` exactly as before.
5252
+ */
5253
+ async resolveBaseViewExclusionSupport(pool) {
5254
+ const configured = (configInfo.baseViewExcludedFields ?? []).filter(f => f && f.trim().length > 0);
5255
+ if (configured.length === 0) {
5256
+ SetBaseViewExclusionsPermitted(false);
5257
+ return;
5258
+ }
5259
+ const supported = await this.pruneSupportsProtectedFieldNames(pool);
5260
+ SetBaseViewExclusionsPermitted(supported);
5261
+ if (supported) {
5262
+ LogWarning(` > baseViewExcludedFields is set (${configured.join(', ')}). Affected entities get an EXPLICIT base-view column list instead of SELECT alias.*, those columns are absent from every MJ read of the entity, and the view stops auto-absorbing new physical columns until the next CodeGen run.`);
5263
+ }
5264
+ else {
5265
+ LogWarning(` > baseViewExcludedFields is set (${configured.join(', ')}) but was DECLINED: ${MjCoreSchema()}.spDeleteUnneededEntityFields on this database does not accept @ProtectedFieldNames, so excluding a column from a base view would make CodeGen delete its EntityField row on the next run. Base views are emitted unchanged. Apply the migration that adds that parameter to enable exclusions.`);
5266
+ }
5267
+ }
5268
+ /** The configured base-view exclusions, as bare field names for the prune's protected list. */
5269
+ configuredProtectedFieldNames() {
5270
+ if (!BaseViewExclusionsPermitted()) {
5271
+ return [];
5272
+ }
5273
+ const out = new Set();
5274
+ for (const raw of configInfo.baseViewExcludedFields ?? []) {
5275
+ const entry = raw.trim();
5276
+ if (entry.length === 0) {
5277
+ continue;
5278
+ }
5279
+ // `EntityName.FieldName` narrows WHICH entity the view excludes it from, but the prune
5280
+ // protects by name across entities — a superset, and deliberately so: protecting a field
5281
+ // row that was never at risk costs nothing, while a per-entity protected list would need a
5282
+ // second parameter for the entity ids and buys no safety.
5283
+ const lastDot = entry.lastIndexOf('.');
5284
+ const field = lastDot > 0 && lastDot < entry.length - 1 ? entry.slice(lastDot + 1).trim() : entry;
5285
+ if (field.length > 0) {
5286
+ out.add(field);
5287
+ }
5288
+ }
5289
+ return [...out];
5290
+ }
4906
5291
  async deleteUnneededEntityFields(pool, excludeSchemas, entityIDs) {
4907
5292
  try {
4908
5293
  // One SP call regardless of scope: pass the entire entity ID list as a comma-delimited
@@ -4913,6 +5298,11 @@ export class ManageMetadataBase {
4913
5298
  authoredExclude: GetAuthoredExcludeSchemas(excludeSchemas),
4914
5299
  includeSchemas: configInfo.includeSchemas,
4915
5300
  entityIDs,
5301
+ // Base-view column exclusions make their columns look orphaned to this prune (the
5302
+ // catalog view resolves columns view-first), so the excluded names are handed over as a
5303
+ // protected list. Empty unless exclusions are configured AND supported, so the emitted
5304
+ // EXEC is unchanged for every install that does not use them.
5305
+ protectedFieldNames: this.configuredProtectedFieldNames(),
4916
5306
  });
4917
5307
  const sSQL = this.dbProvider.callRoutineSQL(MjCoreSchema(), 'spDeleteUnneededEntityFields', heal.Values, heal.Names);
4918
5308
  const isScoped = entityIDs !== undefined && entityIDs.length > 0;