@memberjunction/codegen-lib 6.2.2 → 6.3.0-edge.1

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 (117) hide show
  1. package/README.md +38 -1
  2. package/dist/Angular/angular-codegen.js +1 -1
  3. package/dist/Config/config.d.ts +46 -0
  4. package/dist/Config/config.d.ts.map +1 -1
  5. package/dist/Config/config.js +17 -0
  6. package/dist/Config/config.js.map +1 -1
  7. package/dist/Database/codeGenDatabaseProvider.d.ts +7 -1
  8. package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
  9. package/dist/Database/codeGenDatabaseProvider.js +23 -1
  10. package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
  11. package/dist/Database/config-retraction.d.ts +126 -0
  12. package/dist/Database/config-retraction.d.ts.map +1 -0
  13. package/dist/Database/config-retraction.js +151 -0
  14. package/dist/Database/config-retraction.js.map +1 -0
  15. package/dist/Database/manage-metadata.d.ts +196 -21
  16. package/dist/Database/manage-metadata.d.ts.map +1 -1
  17. package/dist/Database/manage-metadata.js +911 -259
  18. package/dist/Database/manage-metadata.js.map +1 -1
  19. package/dist/Database/organic-key-sync.d.ts +70 -0
  20. package/dist/Database/organic-key-sync.d.ts.map +1 -0
  21. package/dist/Database/organic-key-sync.js +83 -0
  22. package/dist/Database/organic-key-sync.js.map +1 -0
  23. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +7 -0
  24. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
  25. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +83 -19
  26. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
  27. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js +14 -0
  28. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js.map +1 -1
  29. package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.d.ts +2 -0
  30. package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.d.ts.map +1 -0
  31. package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.js +36 -0
  32. package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.js.map +1 -0
  33. package/dist/Database/providers/postgresql/__tests__/PostgreSQLHierarchyFunctions.test.js +5 -0
  34. package/dist/Database/providers/postgresql/__tests__/PostgreSQLHierarchyFunctions.test.js.map +1 -1
  35. package/dist/Database/providers/postgresql/__tests__/SoftPrimaryKeyIndex.test.js +6 -0
  36. package/dist/Database/providers/postgresql/__tests__/SoftPrimaryKeyIndex.test.js.map +1 -1
  37. package/dist/Database/providers/postgresql/metadataSupportObjects.js +64 -18
  38. package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
  39. package/dist/Database/providers/postgresql/viewFallback.d.ts +25 -0
  40. package/dist/Database/providers/postgresql/viewFallback.d.ts.map +1 -1
  41. package/dist/Database/providers/postgresql/viewFallback.js +101 -48
  42. package/dist/Database/providers/postgresql/viewFallback.js.map +1 -1
  43. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +12 -2
  44. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
  45. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +106 -36
  46. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
  47. package/dist/Database/providers/sqlserver/__tests__/BaseViewEmissionGoldenMaster.test.js +65 -7
  48. package/dist/Database/providers/sqlserver/__tests__/BaseViewEmissionGoldenMaster.test.js.map +1 -1
  49. package/dist/Database/providers/sqlserver/__tests__/BaseViewRegenDecision.test.js +30 -3
  50. package/dist/Database/providers/sqlserver/__tests__/BaseViewRegenDecision.test.js.map +1 -1
  51. package/dist/Database/providers/sqlserver/__tests__/SQLServerCodeGenProvider.test.js +41 -0
  52. package/dist/Database/providers/sqlserver/__tests__/SQLServerCodeGenProvider.test.js.map +1 -1
  53. package/dist/Database/providers/sqlserver/__tests__/SoftPrimaryKeyIndex.test.js +6 -0
  54. package/dist/Database/providers/sqlserver/__tests__/SoftPrimaryKeyIndex.test.js.map +1 -1
  55. package/dist/Database/sqlPassFailures.d.ts +26 -0
  56. package/dist/Database/sqlPassFailures.d.ts.map +1 -0
  57. package/dist/Database/sqlPassFailures.js +15 -0
  58. package/dist/Database/sqlPassFailures.js.map +1 -0
  59. package/dist/Database/sql_codegen.d.ts +85 -2
  60. package/dist/Database/sql_codegen.d.ts.map +1 -1
  61. package/dist/Database/sql_codegen.js +573 -128
  62. package/dist/Database/sql_codegen.js.map +1 -1
  63. package/dist/Database/unique-key-sets.d.ts +71 -0
  64. package/dist/Database/unique-key-sets.d.ts.map +1 -0
  65. package/dist/Database/unique-key-sets.js +140 -0
  66. package/dist/Database/unique-key-sets.js.map +1 -0
  67. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts +49 -1
  68. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts.map +1 -1
  69. package/dist/Manifest/GenerateClassRegistrationsManifest.js +392 -60
  70. package/dist/Manifest/GenerateClassRegistrationsManifest.js.map +1 -1
  71. package/dist/Misc/advanced_generation.d.ts +15 -3
  72. package/dist/Misc/advanced_generation.d.ts.map +1 -1
  73. package/dist/Misc/advanced_generation.js +50 -3
  74. package/dist/Misc/advanced_generation.js.map +1 -1
  75. package/dist/Misc/createNewUser.js +4 -4
  76. package/dist/Misc/createNewUser.js.map +1 -1
  77. package/dist/Misc/entity_subclasses_codegen.d.ts +11 -4
  78. package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
  79. package/dist/Misc/entity_subclasses_codegen.js +46 -14
  80. package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
  81. package/dist/Misc/file-write.d.ts.map +1 -1
  82. package/dist/Misc/file-write.js +16 -10
  83. package/dist/Misc/file-write.js.map +1 -1
  84. package/dist/Misc/smart-field-decision.d.ts +126 -0
  85. package/dist/Misc/smart-field-decision.d.ts.map +1 -0
  86. package/dist/Misc/smart-field-decision.js +222 -0
  87. package/dist/Misc/smart-field-decision.js.map +1 -0
  88. package/dist/Misc/sql_logging.d.ts +3 -1
  89. package/dist/Misc/sql_logging.d.ts.map +1 -1
  90. package/dist/Misc/sql_logging.js +4 -2
  91. package/dist/Misc/sql_logging.js.map +1 -1
  92. package/dist/Misc/system_integrity.d.ts +37 -0
  93. package/dist/Misc/system_integrity.d.ts.map +1 -1
  94. package/dist/Misc/system_integrity.js +74 -8
  95. package/dist/Misc/system_integrity.js.map +1 -1
  96. package/dist/Misc/typed_query_codegen.d.ts +144 -0
  97. package/dist/Misc/typed_query_codegen.d.ts.map +1 -0
  98. package/dist/Misc/typed_query_codegen.js +747 -0
  99. package/dist/Misc/typed_query_codegen.js.map +1 -0
  100. package/dist/Misc/validator-text.d.ts +14 -5
  101. package/dist/Misc/validator-text.d.ts.map +1 -1
  102. package/dist/Misc/validator-text.js +42 -13
  103. package/dist/Misc/validator-text.js.map +1 -1
  104. package/dist/index.d.ts +2 -0
  105. package/dist/index.d.ts.map +1 -1
  106. package/dist/index.js +2 -0
  107. package/dist/index.js.map +1 -1
  108. package/dist/plugins/index.d.ts +10 -0
  109. package/dist/plugins/index.d.ts.map +1 -1
  110. package/dist/plugins/index.js +22 -2
  111. package/dist/plugins/index.js.map +1 -1
  112. package/dist/runCodeGen.d.ts +6 -0
  113. package/dist/runCodeGen.d.ts.map +1 -1
  114. package/dist/runCodeGen.js +75 -16
  115. package/dist/runCodeGen.js.map +1 -1
  116. package/dist/tsconfig.tsbuildinfo +1 -0
  117. package/package.json +30 -29
@@ -31,7 +31,10 @@ import path from 'path';
31
31
  import { CanonicalJSONStringify, DeepEqualJSON } from "../Misc/util.js";
32
32
  import { TrimTrailingStatementTerminators } from "../Misc/sql_text.js";
33
33
  import { SQLLogging } from "../Misc/sql_logging.js";
34
+ import { ConfigEntityIndex, DedupeRelatedEntities, OrganicKeyNeedsUpdate, OrganicKeyRelatedRowKey, OrganicKeyRelatedRowNeedsUpdate, OrganicKeyRowKey } from "./organic-key-sync.js";
34
35
  import { ComputeFieldMetadataUpdate } from "./field-metadata-lock.js";
36
+ import { BuildCatalogUniqueKeyColumnsSQL, BuildStoredUniqueKeySetsSQL, BuildUniqueKeySetSyncSQL, DiffUniqueKeySets, GroupUniqueKeyColumns } from "./unique-key-sets.js";
37
+ import { DecideConfigValueListAction, FieldKey, NormalizeKey, NormalizeObjectName, ParseObjectName, PlanOrganicKeyRetraction, ResolveConfigEntity, SelectUndeclaredFields, } from "./config-retraction.js";
35
38
  import { TRACKED_FIELD_COLUMNS, DISPLAYNAME_REOPEN_REASONS, TYPE_REOPEN_REASONS, diffEntityFieldSnapshots, } from './entity-field-change-tracking.js';
36
39
  export { TRACKED_FIELD_COLUMNS, DISPLAYNAME_REOPEN_REASONS, TYPE_REOPEN_REASONS, DiffEntityFieldSnapshots, diffEntityFieldSnapshots, } from './entity-field-change-tracking.js';
37
40
  export class ValidatorResult {
@@ -732,9 +735,13 @@ export class ManageMetadataBase {
732
735
  /**
733
736
  * Extracts organic key configurations from the additionalSchemaInfo config file.
734
737
  * Walks all schema-keyed table arrays and collects OrganicKeys arrays with their
735
- * owning schema and table name.
738
+ * owning schema and table name. A related entity listed twice under one key (same schema and
739
+ * table) keeps only its last entry, which is what each duplicate overwriting the stored row left
740
+ * behind (#3815).
741
+ * @param warnOnDuplicates log one warning per dropped duplicate (the writing pass sets it; the
742
+ * retraction pass reads the same file and would repeat them)
736
743
  */
737
- extractOrganicKeysFromConfig(config) {
744
+ extractOrganicKeysFromConfig(config, warnOnDuplicates = false) {
738
745
  const results = [];
739
746
  for (const [key, value] of Object.entries(config)) {
740
747
  // Skip top-level non-schema keys (ISARelationships, VirtualEntities, Entities)
@@ -769,6 +776,15 @@ export class ManageMetadataBase {
769
776
  }))
770
777
  : [],
771
778
  }));
779
+ for (const ok of organicKeys) {
780
+ const { Kept, Dropped } = DedupeRelatedEntities(ok.RelatedEntities);
781
+ ok.RelatedEntities = Kept;
782
+ if (warnOnDuplicates) {
783
+ for (const dup of Dropped) {
784
+ LogWarning(` > Organic key "${ok.Name}" on ${schemaName}.${tableConfig.TableName}: related entity "${dup.SchemaName}.${dup.TableName}" is listed more than once — using its last entry`);
785
+ }
786
+ }
787
+ }
772
788
  results.push({ SchemaName: schemaName, TableName: tableConfig.TableName, OrganicKeys: organicKeys });
773
789
  }
774
790
  }
@@ -821,175 +837,237 @@ export class ManageMetadataBase {
821
837
  * Processes organic key configurations from additionalSchemaInfo.
822
838
  * For each configured organic key:
823
839
  * 1. Creates transitive bridge views if TransitiveView is defined
824
- * 2. Upserts EntityOrganicKey records (matched on EntityID + Name)
840
+ * 2. Upserts EntityOrganicKey records (matched on EntityID + Name), stamped `Source = 'Config'`:
841
+ * the file now owns a key it declares, which is what lets a later run retract it (#4535)
825
842
  * 3. Upserts EntityOrganicKeyRelatedEntity records (matched on EntityOrganicKeyID + RelatedEntityID)
826
843
  *
844
+ * Entities and existing rows are read once up front, and a row is written only when it differs
845
+ * from the file, so a run over unchanged config issues three reads and no writes (#3815).
827
846
  * All SQL is executed AND logged via LogSQLAndExecute for complete CI/CD traceability.
828
847
  * Must run AFTER entities are created.
829
848
  */
830
849
  async processOrganicKeyConfig(pool) {
850
+ const result = { success: true, createdCount: 0, updatedCount: 0, unchangedCount: 0, failedCount: 0 };
831
851
  const config = ManageMetadataBase.getSoftPKFKConfig();
832
852
  if (!config)
833
- return { success: true, createdCount: 0, updatedCount: 0, failedCount: 0 };
834
- const allOrganicKeys = this.extractOrganicKeysFromConfig(config);
853
+ return result;
854
+ const allOrganicKeys = this.extractOrganicKeysFromConfig(config, true);
835
855
  if (allOrganicKeys.length === 0)
836
- return { success: true, createdCount: 0, updatedCount: 0, failedCount: 0 };
837
- const schema = MjCoreSchema();
838
- let createdCount = 0;
839
- let updatedCount = 0;
840
- let failedCount = 0;
856
+ return result;
857
+ const entities = new ConfigEntityIndex(await this.loadEntityRefsForRetraction(pool));
858
+ const existingKeys = await this.loadOrganicKeyRows(pool);
859
+ const existingRelated = await this.loadOrganicKeyRelatedRows(pool);
860
+ const progress = this.organicKeyProgressReporter(allOrganicKeys);
841
861
  for (const tableConfig of allOrganicKeys) {
842
- // Resolve the owning entity
843
- const owner = await this.findOrganicKeyEntity(pool, tableConfig.SchemaName, tableConfig.TableName);
862
+ const owner = entities.Resolve(tableConfig.SchemaName, tableConfig.TableName);
844
863
  if (!owner) {
845
864
  // Every key declared on this table goes unapplied, so each one counts as a failure.
846
- failedCount += tableConfig.OrganicKeys.length;
865
+ result.failedCount += tableConfig.OrganicKeys.length;
847
866
  logError(` > Organic keys config: entity "${tableConfig.SchemaName}.${tableConfig.TableName}" not found — skipping its ${tableConfig.OrganicKeys.length} organic key(s)`);
867
+ for (const okConfig of tableConfig.OrganicKeys) {
868
+ progress(okConfig.RelatedEntities.length);
869
+ }
848
870
  continue;
849
871
  }
850
- const ownerEntityId = owner.ID;
851
- const ownerEntityName = owner.Name;
852
872
  for (const okConfig of tableConfig.OrganicKeys) {
853
873
  try {
854
- // Resolve every related entity BEFORE writing anything for this key. Step 1 creates
855
- // bridge views (in the database and the migration log) and step 2 records the key, so
856
- // discovering a missing related entity in step 3 would leave an orphan view and a key
857
- // with a mapping missing.
858
- const relatedEntities = await this.resolveOrganicKeyRelatedEntities(pool, okConfig);
859
- if (!relatedEntities) {
860
- failedCount++;
861
- continue;
862
- }
863
- // Step 1: Create transitive views if defined
864
- for (const re of okConfig.RelatedEntities) {
865
- if (re.TransitiveView) {
866
- const viewSchema = re.TransitiveView.SchemaName || re.SchemaName;
867
- const viewFullName = `${viewSchema}.${re.TransitiveView.Name}`;
868
- const viewSQL = this.dbProvider.generateCreateOrReplaceViewSQL(viewSchema, re.TransitiveView.Name, re.TransitiveView.SQL);
869
- // T-SQL requires CREATE [OR ALTER] VIEW to be the ONLY statement in its batch — first as
870
- // well as last — and the metadata DML logged just before it (entity-config UPDATEs, the
871
- // previous key's INSERTs) has no trailing GO. requiresOwnBatch puts the provider's
872
- // separator on both sides in the migration file ('' on PostgreSQL: nothing is added).
873
- await this.logSQLAndExecute(pool, viewSQL, `Create transitive bridge view ${viewFullName} for organic key "${okConfig.Name}" on ${ownerEntityName}`, false, true, this.dbProvider.BatchSeparator, true);
874
- // Auto-populate TransitiveObject from the view definition
875
- re.TransitiveObject = viewFullName;
876
- }
877
- }
878
- // Step 2: Upsert EntityOrganicKey (match on EntityID + Name)
879
- const existingKey = await this.runQueryWithParams(pool, `SELECT ID FROM ${this.qs(schema, 'EntityOrganicKey')} WHERE EntityID = @EntityID AND Name = @Name`, { 'EntityID': ownerEntityId, 'Name': okConfig.Name });
880
- let organicKeyId;
881
- const matchFieldNames = okConfig.MatchFieldNames.join(',');
882
- if (existingKey.recordset.length > 0) {
883
- // Update existing
884
- organicKeyId = existingKey.recordset[0].ID;
885
- const updateSQL = `UPDATE ${this.qs(schema, 'EntityOrganicKey')} SET
886
- MatchFieldNames = '${matchFieldNames}',
887
- NormalizationStrategy = '${okConfig.NormalizationStrategy || 'LowerCaseTrim'}',
888
- ${okConfig.CustomNormalizationExpression ? `CustomNormalizationExpression = '${okConfig.CustomNormalizationExpression.replace(/'/g, "''")}',` : ''}
889
- ${okConfig.Description ? `Description = '${okConfig.Description.replace(/'/g, "''")}',` : ''}
890
- Sequence = ${okConfig.Sequence ?? 0},
891
- Status = 'Active'
892
- WHERE ID = '${organicKeyId}'`;
893
- await this.logSQLAndExecute(pool, updateSQL, `Update organic key "${okConfig.Name}" on ${ownerEntityName}`);
894
- updatedCount++;
895
- logStatus(` > Organic key: Updated "${okConfig.Name}" on ${ownerEntityName}`);
896
- }
897
- else {
898
- // Insert new — use entity-lookup subquery so the logged SQL is portable across databases
899
- const ownerSubquery = this.entityIdSubquery(tableConfig.TableName, tableConfig.SchemaName);
900
- const insertSQL = `INSERT INTO ${this.qs(schema, 'EntityOrganicKey')}
901
- (EntityID, Name, ${okConfig.Description ? 'Description, ' : ''}MatchFieldNames, NormalizationStrategy, ${okConfig.CustomNormalizationExpression ? 'CustomNormalizationExpression, ' : ''}Sequence, Status)
902
- VALUES (${ownerSubquery}, '${okConfig.Name}', ${okConfig.Description ? `'${okConfig.Description.replace(/'/g, "''")}', ` : ''}'${matchFieldNames}', '${okConfig.NormalizationStrategy || 'LowerCaseTrim'}', ${okConfig.CustomNormalizationExpression ? `'${okConfig.CustomNormalizationExpression.replace(/'/g, "''")}', ` : ''}${okConfig.Sequence ?? 0}, 'Active')`;
903
- await this.logSQLAndExecute(pool, insertSQL, `Insert organic key "${okConfig.Name}" on ${ownerEntityName}`);
904
- createdCount++;
905
- logStatus(` > Organic key: Created "${okConfig.Name}" on ${ownerEntityName}`);
906
- // Fetch the new ID
907
- const newKey = await this.runQueryWithParams(pool, `SELECT ID FROM ${this.qs(schema, 'EntityOrganicKey')} WHERE EntityID = @EntityID AND Name = @Name`, { 'EntityID': ownerEntityId, 'Name': okConfig.Name });
908
- organicKeyId = newKey.recordset[0].ID;
909
- }
910
- // Step 3: Upsert EntityOrganicKeyRelatedEntity for each related entity
911
- for (const { config: reConfig, entity: relEntity } of relatedEntities) {
912
- const relEntityId = relEntity.ID;
913
- const relEntityName = relEntity.Name;
914
- // Check if this related entity mapping already exists
915
- const existingRel = await this.runQueryWithParams(pool, `SELECT ID FROM ${this.qs(schema, 'EntityOrganicKeyRelatedEntity')} WHERE EntityOrganicKeyID = @KeyID AND RelatedEntityID = @RelEntityID`, { 'KeyID': organicKeyId, 'RelEntityID': relEntityId });
916
- // Build field values
917
- const isDirect = reConfig.RelatedFieldNames && reConfig.RelatedFieldNames.length > 0;
918
- const relFieldNames = isDirect ? reConfig.RelatedFieldNames.join(',') : null;
919
- const transitiveObject = reConfig.TransitiveObject || null;
920
- const transitiveMatchFields = reConfig.TransitiveMatchFieldNames ? reConfig.TransitiveMatchFieldNames.join(',') : null;
921
- if (existingRel.recordset.length > 0) {
922
- const relId = existingRel.recordset[0].ID;
923
- const updateRelSQL = `UPDATE ${this.qs(schema, 'EntityOrganicKeyRelatedEntity')} SET
924
- RelatedEntityFieldNames = ${relFieldNames ? `'${relFieldNames}'` : 'NULL'},
925
- TransitiveObjectName = ${transitiveObject ? `'${transitiveObject}'` : 'NULL'},
926
- TransitiveObjectMatchFieldNames = ${transitiveMatchFields ? `'${transitiveMatchFields}'` : 'NULL'},
927
- TransitiveObjectOutputFieldName = ${reConfig.TransitiveOutputFieldName ? `'${reConfig.TransitiveOutputFieldName}'` : 'NULL'},
928
- RelatedEntityJoinFieldName = ${reConfig.RelatedEntityJoinFieldName ? `'${reConfig.RelatedEntityJoinFieldName}'` : 'NULL'},
929
- DisplayName = ${reConfig.DisplayName ? `'${reConfig.DisplayName.replace(/'/g, "''")}'` : 'NULL'},
930
- DisplayLocation = '${reConfig.DisplayLocation || 'After Field Tabs'}',
931
- Sequence = ${reConfig.Sequence ?? 0}
932
- WHERE ID = '${relId}'`;
933
- await this.logSQLAndExecute(pool, updateRelSQL, `Update organic key related entity: "${okConfig.Name}" → ${relEntityName}`);
934
- }
935
- else {
936
- // Use subqueries for FK references so the logged SQL is portable across databases
937
- const ownerSubquery = this.entityIdSubquery(tableConfig.TableName, tableConfig.SchemaName);
938
- const organicKeySubquery = `(SELECT ID FROM ${this.qs(schema, 'EntityOrganicKey')} WHERE EntityID = ${ownerSubquery} AND Name = '${okConfig.Name}')`;
939
- const relEntitySubquery = this.entityIdSubquery(reConfig.TableName, reConfig.SchemaName);
940
- const insertRelSQL = `INSERT INTO ${this.qs(schema, 'EntityOrganicKeyRelatedEntity')}
941
- (EntityOrganicKeyID, RelatedEntityID, RelatedEntityFieldNames,
942
- TransitiveObjectName, TransitiveObjectMatchFieldNames, TransitiveObjectOutputFieldName, RelatedEntityJoinFieldName,
943
- DisplayName, DisplayLocation, Sequence)
944
- VALUES (${organicKeySubquery}, ${relEntitySubquery},
945
- ${relFieldNames ? `'${relFieldNames}'` : 'NULL'},
946
- ${transitiveObject ? `'${transitiveObject}'` : 'NULL'},
947
- ${transitiveMatchFields ? `'${transitiveMatchFields}'` : 'NULL'},
948
- ${reConfig.TransitiveOutputFieldName ? `'${reConfig.TransitiveOutputFieldName}'` : 'NULL'},
949
- ${reConfig.RelatedEntityJoinFieldName ? `'${reConfig.RelatedEntityJoinFieldName}'` : 'NULL'},
950
- ${reConfig.DisplayName ? `'${reConfig.DisplayName.replace(/'/g, "''")}'` : 'NULL'},
951
- '${reConfig.DisplayLocation || 'After Field Tabs'}',
952
- ${reConfig.Sequence ?? 0})`;
953
- await this.logSQLAndExecute(pool, insertRelSQL, `Insert organic key related entity: "${okConfig.Name}" → ${relEntityName}`);
954
- }
955
- logStatus(` > Organic key "${okConfig.Name}": ${existingRel.recordset.length > 0 ? 'updated' : 'created'} → ${relEntityName} (${isDirect ? 'direct' : 'transitive'})`);
956
- }
874
+ const outcome = await this.applyOrganicKey(pool, entities, tableConfig, owner, okConfig, existingKeys, existingRelated);
875
+ if (outcome === 'failed')
876
+ result.failedCount++;
877
+ else if (outcome === 'created')
878
+ result.createdCount++;
879
+ else if (outcome === 'updated')
880
+ result.updatedCount++;
881
+ else
882
+ result.unchangedCount++;
957
883
  }
958
884
  catch (err) {
959
885
  // Keep going so one bad key doesn't block the others — but count it: a key that failed
960
886
  // here (bridge-view DDL the database rejected, a refused view drop, …) is missing from
961
887
  // the database, and the run must not report success for it.
962
- failedCount++;
888
+ result.failedCount++;
963
889
  const errMessage = err instanceof Error ? err.message : String(err);
964
- logError(` > Organic key config: Failed to process "${okConfig.Name}" on ${ownerEntityName}: ${errMessage}`);
890
+ logError(` > Organic key config: Failed to process "${okConfig.Name}" on ${owner.Name}: ${errMessage}`);
965
891
  }
892
+ progress(okConfig.RelatedEntities.length);
966
893
  }
967
894
  }
968
- return { success: failedCount === 0, createdCount, updatedCount, failedCount };
895
+ result.success = result.failedCount === 0;
896
+ return result;
897
+ }
898
+ /** Every this many (key, related entity) pairs, the organic-key pass logs one progress line. */
899
+ static { this.organicKeyProgressInterval = 250; }
900
+ /** Returns a callback that counts processed pairs and logs a line each time a multiple of the interval is crossed. */
901
+ organicKeyProgressReporter(allOrganicKeys) {
902
+ const total = allOrganicKeys.reduce((sum, t) => sum + t.OrganicKeys.reduce((s, ok) => s + ok.RelatedEntities.length, 0), 0);
903
+ const interval = ManageMetadataBase.organicKeyProgressInterval;
904
+ let processed = 0;
905
+ return (pairs) => {
906
+ const before = processed;
907
+ processed += pairs;
908
+ if (Math.floor(processed / interval) > Math.floor(before / interval)) {
909
+ logStatus(` > Organic keys: processed ${processed}/${total} organic key relationships`);
910
+ }
911
+ };
969
912
  }
970
913
  /**
971
- * Finds the entity an organic-key config names: by base table + schema, else by entity name.
972
- * Returns `null` when neither matches.
914
+ * Applies one organic key: bridge views, the key row, then its related-entity rows. Rows already
915
+ * matching the file are left alone. The maps are updated with what was written, so a key the file
916
+ * declares twice is compared against this run's write rather than inserted again.
973
917
  */
974
- async findOrganicKeyEntity(pool, schemaName, tableName) {
975
- const result = await this.runQueryWithParams(pool, `
976
- ${this.selectTop(1, 'ID, Name', `FROM ${this.qs(MjCoreSchema(), 'vwEntities')}
977
- WHERE (BaseTable = @TableName AND SchemaName = @SchemaName)
978
- OR Name = @TableName`, 'CASE WHEN BaseTable = @TableName AND SchemaName = @SchemaName THEN 0 ELSE 1 END')}
979
- `, { 'TableName': tableName, 'SchemaName': schemaName });
980
- const row = result.recordset[0];
981
- return row ? { ID: row.ID, Name: row.Name } : null;
918
+ async applyOrganicKey(pool, entities, tableConfig, owner, okConfig, existingKeys, existingRelated) {
919
+ const schema = MjCoreSchema();
920
+ const ownerEntityName = owner.Name;
921
+ // Resolve every related entity BEFORE writing anything for this key. Step 1 creates
922
+ // bridge views (in the database and the migration log) and step 2 records the key, so
923
+ // discovering a missing related entity in step 3 would leave an orphan view and a key
924
+ // with a mapping missing.
925
+ const relatedEntities = this.resolveOrganicKeyRelatedEntities(entities, okConfig);
926
+ if (!relatedEntities) {
927
+ return 'failed';
928
+ }
929
+ // Step 1: Create transitive views if defined
930
+ for (const re of okConfig.RelatedEntities) {
931
+ if (re.TransitiveView) {
932
+ const viewSchema = re.TransitiveView.SchemaName || re.SchemaName;
933
+ const viewFullName = `${viewSchema}.${re.TransitiveView.Name}`;
934
+ const viewSQL = this.dbProvider.generateCreateOrReplaceViewSQL(viewSchema, re.TransitiveView.Name, re.TransitiveView.SQL);
935
+ // T-SQL requires CREATE [OR ALTER] VIEW to be the ONLY statement in its batch — first as
936
+ // well as last — and the metadata DML logged just before it (entity-config UPDATEs, the
937
+ // previous key's INSERTs) has no trailing GO. requiresOwnBatch puts the provider's
938
+ // separator on both sides in the migration file ('' on PostgreSQL: nothing is added).
939
+ await this.logSQLAndExecute(pool, viewSQL, `Create transitive bridge view ${viewFullName} for organic key "${okConfig.Name}" on ${ownerEntityName}`, false, true, this.dbProvider.BatchSeparator, true);
940
+ // Auto-populate TransitiveObject from the view definition
941
+ re.TransitiveObject = viewFullName;
942
+ }
943
+ }
944
+ // Step 2: Upsert EntityOrganicKey (match on EntityID + Name)
945
+ const matchFieldNames = okConfig.MatchFieldNames.join(',');
946
+ const desiredKey = {
947
+ MatchFieldNames: matchFieldNames,
948
+ NormalizationStrategy: okConfig.NormalizationStrategy || 'LowerCaseTrim',
949
+ CustomNormalizationExpression: okConfig.CustomNormalizationExpression || undefined,
950
+ Description: okConfig.Description || undefined,
951
+ Sequence: okConfig.Sequence ?? 0,
952
+ Status: 'Active',
953
+ Source: 'Config',
954
+ };
955
+ const keyRowKey = OrganicKeyRowKey(owner.ID, okConfig.Name);
956
+ const existingKey = existingKeys.get(keyRowKey);
957
+ let keyCreated = false;
958
+ let wroteAny = false;
959
+ if (existingKey) {
960
+ if (OrganicKeyNeedsUpdate(existingKey, desiredKey)) {
961
+ const organicKeyId = existingKey.ID ?? await this.lookupOrganicKeyId(pool, owner.ID, okConfig.Name);
962
+ const updateSQL = `UPDATE ${this.qs(schema, 'EntityOrganicKey')} SET
963
+ MatchFieldNames = '${matchFieldNames}',
964
+ NormalizationStrategy = '${desiredKey.NormalizationStrategy}',
965
+ ${okConfig.CustomNormalizationExpression ? `CustomNormalizationExpression = '${okConfig.CustomNormalizationExpression.replace(/'/g, "''")}',` : ''}
966
+ ${okConfig.Description ? `Description = '${okConfig.Description.replace(/'/g, "''")}',` : ''}
967
+ Sequence = ${desiredKey.Sequence},
968
+ Status = 'Active',
969
+ Source = 'Config'
970
+ WHERE ID = '${organicKeyId}'`;
971
+ await this.logSQLAndExecute(pool, updateSQL, `Update organic key "${okConfig.Name}" on ${ownerEntityName}`);
972
+ wroteAny = true;
973
+ logStatus(` > Organic key: Updated "${okConfig.Name}" on ${ownerEntityName}`);
974
+ existingKeys.set(keyRowKey, {
975
+ ...existingKey,
976
+ ...desiredKey,
977
+ ID: organicKeyId,
978
+ CustomNormalizationExpression: desiredKey.CustomNormalizationExpression ?? existingKey.CustomNormalizationExpression,
979
+ Description: desiredKey.Description ?? existingKey.Description,
980
+ });
981
+ }
982
+ }
983
+ else {
984
+ // Insert new — use entity-lookup subquery so the logged SQL is portable across databases
985
+ const ownerSubquery = this.entityIdSubquery(tableConfig.TableName, tableConfig.SchemaName);
986
+ const insertSQL = `INSERT INTO ${this.qs(schema, 'EntityOrganicKey')}
987
+ (EntityID, Name, ${okConfig.Description ? 'Description, ' : ''}MatchFieldNames, NormalizationStrategy, ${okConfig.CustomNormalizationExpression ? 'CustomNormalizationExpression, ' : ''}Sequence, Status, Source)
988
+ VALUES (${ownerSubquery}, '${okConfig.Name}', ${okConfig.Description ? `'${okConfig.Description.replace(/'/g, "''")}', ` : ''}'${matchFieldNames}', '${desiredKey.NormalizationStrategy}', ${okConfig.CustomNormalizationExpression ? `'${okConfig.CustomNormalizationExpression.replace(/'/g, "''")}', ` : ''}${desiredKey.Sequence}, 'Active', 'Config')`;
989
+ await this.logSQLAndExecute(pool, insertSQL, `Insert organic key "${okConfig.Name}" on ${ownerEntityName}`);
990
+ keyCreated = true;
991
+ logStatus(` > Organic key: Created "${okConfig.Name}" on ${ownerEntityName}`);
992
+ existingKeys.set(keyRowKey, {
993
+ ...desiredKey,
994
+ ID: null,
995
+ CustomNormalizationExpression: desiredKey.CustomNormalizationExpression ?? null,
996
+ Description: desiredKey.Description ?? null,
997
+ });
998
+ }
999
+ // Step 3: Upsert EntityOrganicKeyRelatedEntity for each related entity
1000
+ for (const { config: reConfig, entity: relEntity } of relatedEntities) {
1001
+ const relEntityName = relEntity.Name;
1002
+ const isDirect = !!reConfig.RelatedFieldNames && reConfig.RelatedFieldNames.length > 0;
1003
+ const desiredRel = {
1004
+ RelatedEntityFieldNames: isDirect ? reConfig.RelatedFieldNames.join(',') : null,
1005
+ TransitiveObjectName: reConfig.TransitiveObject || null,
1006
+ TransitiveObjectMatchFieldNames: reConfig.TransitiveMatchFieldNames ? reConfig.TransitiveMatchFieldNames.join(',') : null,
1007
+ TransitiveObjectOutputFieldName: reConfig.TransitiveOutputFieldName || null,
1008
+ RelatedEntityJoinFieldName: reConfig.RelatedEntityJoinFieldName || null,
1009
+ DisplayName: reConfig.DisplayName || null,
1010
+ DisplayLocation: reConfig.DisplayLocation || 'After Field Tabs',
1011
+ Sequence: reConfig.Sequence ?? 0,
1012
+ };
1013
+ const relRowKey = OrganicKeyRelatedRowKey(owner.ID, okConfig.Name, relEntity.ID);
1014
+ const existingRel = existingRelated.get(relRowKey);
1015
+ const lit = (value) => (value ? `'${value}'` : 'NULL');
1016
+ const displayNameLit = desiredRel.DisplayName ? `'${desiredRel.DisplayName.replace(/'/g, "''")}'` : 'NULL';
1017
+ if (existingRel) {
1018
+ if (!OrganicKeyRelatedRowNeedsUpdate(existingRel, desiredRel)) {
1019
+ continue;
1020
+ }
1021
+ const relId = existingRel.ID ?? await this.lookupOrganicKeyRelatedId(pool, owner.ID, okConfig.Name, relEntity.ID);
1022
+ const updateRelSQL = `UPDATE ${this.qs(schema, 'EntityOrganicKeyRelatedEntity')} SET
1023
+ RelatedEntityFieldNames = ${lit(desiredRel.RelatedEntityFieldNames)},
1024
+ TransitiveObjectName = ${lit(desiredRel.TransitiveObjectName)},
1025
+ TransitiveObjectMatchFieldNames = ${lit(desiredRel.TransitiveObjectMatchFieldNames)},
1026
+ TransitiveObjectOutputFieldName = ${lit(desiredRel.TransitiveObjectOutputFieldName)},
1027
+ RelatedEntityJoinFieldName = ${lit(desiredRel.RelatedEntityJoinFieldName)},
1028
+ DisplayName = ${displayNameLit},
1029
+ DisplayLocation = '${desiredRel.DisplayLocation}',
1030
+ Sequence = ${desiredRel.Sequence}
1031
+ WHERE ID = '${relId}'`;
1032
+ await this.logSQLAndExecute(pool, updateRelSQL, `Update organic key related entity: "${okConfig.Name}" → ${relEntityName}`);
1033
+ existingRelated.set(relRowKey, { ...desiredRel, ID: relId });
1034
+ }
1035
+ else {
1036
+ // Use subqueries for FK references so the logged SQL is portable across databases
1037
+ const ownerSubquery = this.entityIdSubquery(tableConfig.TableName, tableConfig.SchemaName);
1038
+ const organicKeySubquery = `(SELECT ID FROM ${this.qs(schema, 'EntityOrganicKey')} WHERE EntityID = ${ownerSubquery} AND Name = '${okConfig.Name}')`;
1039
+ const relEntitySubquery = this.entityIdSubquery(reConfig.TableName, reConfig.SchemaName);
1040
+ const insertRelSQL = `INSERT INTO ${this.qs(schema, 'EntityOrganicKeyRelatedEntity')}
1041
+ (EntityOrganicKeyID, RelatedEntityID, RelatedEntityFieldNames,
1042
+ TransitiveObjectName, TransitiveObjectMatchFieldNames, TransitiveObjectOutputFieldName, RelatedEntityJoinFieldName,
1043
+ DisplayName, DisplayLocation, Sequence)
1044
+ VALUES (${organicKeySubquery}, ${relEntitySubquery},
1045
+ ${lit(desiredRel.RelatedEntityFieldNames)},
1046
+ ${lit(desiredRel.TransitiveObjectName)},
1047
+ ${lit(desiredRel.TransitiveObjectMatchFieldNames)},
1048
+ ${lit(desiredRel.TransitiveObjectOutputFieldName)},
1049
+ ${lit(desiredRel.RelatedEntityJoinFieldName)},
1050
+ ${displayNameLit},
1051
+ '${desiredRel.DisplayLocation}',
1052
+ ${desiredRel.Sequence})`;
1053
+ await this.logSQLAndExecute(pool, insertRelSQL, `Insert organic key related entity: "${okConfig.Name}" → ${relEntityName}`);
1054
+ existingRelated.set(relRowKey, { ...desiredRel, ID: null });
1055
+ }
1056
+ wroteAny = true;
1057
+ logStatus(` > Organic key "${okConfig.Name}": ${existingRel ? 'updated' : 'created'} → ${relEntityName} (${isDirect ? 'direct' : 'transitive'})`);
1058
+ }
1059
+ return keyCreated ? 'created' : wroteAny ? 'updated' : 'unchanged';
982
1060
  }
983
1061
  /**
984
1062
  * Resolves every related entity of an organic key, in config order. Logs each one that doesn't
985
1063
  * resolve and returns `null` if any is missing, so the caller can skip the key before writing any
986
1064
  * of it.
987
1065
  */
988
- async resolveOrganicKeyRelatedEntities(pool, okConfig) {
1066
+ resolveOrganicKeyRelatedEntities(entities, okConfig) {
989
1067
  const resolved = [];
990
1068
  let missing = 0;
991
1069
  for (const reConfig of okConfig.RelatedEntities) {
992
- const entity = await this.findOrganicKeyEntity(pool, reConfig.SchemaName, reConfig.TableName);
1070
+ const entity = entities.Resolve(reConfig.SchemaName, reConfig.TableName);
993
1071
  if (entity) {
994
1072
  resolved.push({ config: reConfig, entity });
995
1073
  }
@@ -1000,6 +1078,436 @@ export class ManageMetadataBase {
1000
1078
  }
1001
1079
  return missing === 0 ? resolved : null;
1002
1080
  }
1081
+ /** Every EntityOrganicKey row, keyed by {@link OrganicKeyRowKey}, with the columns the pass compares. */
1082
+ async loadOrganicKeyRows(pool) {
1083
+ const columns = ['ID', 'EntityID', 'Name', 'MatchFieldNames', 'NormalizationStrategy', 'CustomNormalizationExpression', 'Description', 'Sequence', 'Status', 'Source'];
1084
+ const sql = `SELECT ${columns.map(c => this.qi(c)).join(', ')} FROM ${this.qs(MjCoreSchema(), 'EntityOrganicKey')}`;
1085
+ const rows = new Map();
1086
+ for (const row of (await this.runQuery(pool, sql)).recordset) {
1087
+ const key = OrganicKeyRowKey(String(row.EntityID), String(row.Name));
1088
+ if (rows.has(key))
1089
+ continue;
1090
+ rows.set(key, {
1091
+ ID: String(row.ID),
1092
+ MatchFieldNames: String(row.MatchFieldNames),
1093
+ NormalizationStrategy: String(row.NormalizationStrategy),
1094
+ CustomNormalizationExpression: this.optionalText(row.CustomNormalizationExpression),
1095
+ Description: this.optionalText(row.Description),
1096
+ Sequence: Number(row.Sequence),
1097
+ Status: String(row.Status),
1098
+ Source: String(row.Source),
1099
+ });
1100
+ }
1101
+ return rows;
1102
+ }
1103
+ /** Every EntityOrganicKeyRelatedEntity row, keyed by {@link OrganicKeyRelatedRowKey}, with the columns the pass compares. */
1104
+ async loadOrganicKeyRelatedRows(pool) {
1105
+ const schema = MjCoreSchema();
1106
+ const q = (alias, column) => `${alias}.${this.qi(column)}`;
1107
+ const relatedColumns = ['ID', 'RelatedEntityID', 'RelatedEntityFieldNames', 'TransitiveObjectName', 'TransitiveObjectMatchFieldNames',
1108
+ 'TransitiveObjectOutputFieldName', 'RelatedEntityJoinFieldName', 'DisplayName', 'DisplayLocation', 'Sequence'];
1109
+ const sql = `SELECT ${q('k', 'EntityID')} AS ${this.qi('KeyEntityID')}, ${q('k', 'Name')} AS ${this.qi('KeyName')},
1110
+ ${relatedColumns.map(c => q('r', c)).join(', ')}
1111
+ FROM ${this.qs(schema, 'EntityOrganicKeyRelatedEntity')} r
1112
+ INNER JOIN ${this.qs(schema, 'EntityOrganicKey')} k ON ${q('k', 'ID')} = ${q('r', 'EntityOrganicKeyID')}`;
1113
+ const rows = new Map();
1114
+ for (const row of (await this.runQuery(pool, sql)).recordset) {
1115
+ const key = OrganicKeyRelatedRowKey(String(row.KeyEntityID), String(row.KeyName), String(row.RelatedEntityID));
1116
+ if (rows.has(key))
1117
+ continue;
1118
+ rows.set(key, {
1119
+ ID: String(row.ID),
1120
+ RelatedEntityFieldNames: this.optionalText(row.RelatedEntityFieldNames),
1121
+ TransitiveObjectName: this.optionalText(row.TransitiveObjectName),
1122
+ TransitiveObjectMatchFieldNames: this.optionalText(row.TransitiveObjectMatchFieldNames),
1123
+ TransitiveObjectOutputFieldName: this.optionalText(row.TransitiveObjectOutputFieldName),
1124
+ RelatedEntityJoinFieldName: this.optionalText(row.RelatedEntityJoinFieldName),
1125
+ DisplayName: this.optionalText(row.DisplayName),
1126
+ DisplayLocation: String(row.DisplayLocation),
1127
+ Sequence: Number(row.Sequence),
1128
+ });
1129
+ }
1130
+ return rows;
1131
+ }
1132
+ /** The ID of a key this run inserted, needed only when the file declares the same key twice and the second differs. */
1133
+ async lookupOrganicKeyId(pool, entityID, keyName) {
1134
+ const result = await this.runQueryWithParams(pool, `SELECT ID FROM ${this.qs(MjCoreSchema(), 'EntityOrganicKey')} WHERE EntityID = @EntityID AND Name = @Name`, { 'EntityID': entityID, 'Name': keyName });
1135
+ return String(result.recordset[0].ID);
1136
+ }
1137
+ /** The ID of a related-entity row this run inserted; same rare path as {@link lookupOrganicKeyId}. */
1138
+ async lookupOrganicKeyRelatedId(pool, entityID, keyName, relatedEntityID) {
1139
+ const keyId = await this.lookupOrganicKeyId(pool, entityID, keyName);
1140
+ const result = await this.runQueryWithParams(pool, `SELECT ID FROM ${this.qs(MjCoreSchema(), 'EntityOrganicKeyRelatedEntity')} WHERE EntityOrganicKeyID = @KeyID AND RelatedEntityID = @RelEntityID`, { 'KeyID': keyId, 'RelEntityID': relatedEntityID });
1141
+ return String(result.recordset[0].ID);
1142
+ }
1143
+ // ─── Retraction of declarations removed from additionalSchemaInfo (#4535) ───────────────────
1144
+ /** A nullable text column as a string or null. */
1145
+ optionalText(value) {
1146
+ return value === null || value === undefined ? null : String(value);
1147
+ }
1148
+ /**
1149
+ * Loads every organic key joined to its related-entity rows, for {@link PlanOrganicKeyRetraction}.
1150
+ * Null when no additionalSchemaInfo is loaded (nothing to retract) or the query fails (the
1151
+ * retraction pass then leaves organic keys alone).
1152
+ */
1153
+ async loadOrganicKeyStateForRetraction(pool) {
1154
+ if (!ManageMetadataBase.GetSoftPKFKConfig()) {
1155
+ return null;
1156
+ }
1157
+ try {
1158
+ const schema = MjCoreSchema();
1159
+ const q = (alias, column) => `${alias}.${this.qi(column)}`;
1160
+ const sql = `SELECT ${q('k', 'ID')} AS ${this.qi('KeyID')}, ${q('k', 'Name')} AS ${this.qi('KeyName')}, ${q('k', 'Source')} AS ${this.qi('KeySource')},
1161
+ ${q('k', 'EntityID')} AS ${this.qi('EntityID')}, ${q('e', 'Name')} AS ${this.qi('EntityName')},
1162
+ ${q('e', 'SchemaName')} AS ${this.qi('SchemaName')}, ${q('e', 'BaseTable')} AS ${this.qi('BaseTable')},
1163
+ ${q('r', 'ID')} AS ${this.qi('RelatedRowID')}, ${q('r', 'RelatedEntityID')} AS ${this.qi('RelatedEntityID')},
1164
+ ${q('re', 'Name')} AS ${this.qi('RelatedEntityName')}, ${q('re', 'SchemaName')} AS ${this.qi('RelatedSchemaName')},
1165
+ ${q('re', 'BaseTable')} AS ${this.qi('RelatedBaseTable')}, ${q('r', 'TransitiveObjectName')} AS ${this.qi('TransitiveObjectName')}
1166
+ FROM ${this.qs(schema, 'EntityOrganicKey')} k
1167
+ INNER JOIN ${this.qs(schema, 'Entity')} e ON ${q('e', 'ID')} = ${q('k', 'EntityID')}
1168
+ LEFT OUTER JOIN ${this.qs(schema, 'EntityOrganicKeyRelatedEntity')} r ON ${q('r', 'EntityOrganicKeyID')} = ${q('k', 'ID')}
1169
+ LEFT OUTER JOIN ${this.qs(schema, 'Entity')} re ON ${q('re', 'ID')} = ${q('r', 'RelatedEntityID')}
1170
+ ORDER BY ${q('k', 'EntityID')}, ${q('k', 'Name')}, ${q('r', 'Sequence')}, ${q('r', 'ID')}`;
1171
+ const result = await this.runQuery(pool, sql);
1172
+ return result.recordset.map((row) => ({
1173
+ KeyID: String(row.KeyID),
1174
+ KeyName: String(row.KeyName),
1175
+ KeySource: String(row.KeySource),
1176
+ EntityID: String(row.EntityID),
1177
+ EntityName: String(row.EntityName),
1178
+ SchemaName: String(row.SchemaName),
1179
+ BaseTable: String(row.BaseTable),
1180
+ RelatedRowID: this.optionalText(row.RelatedRowID),
1181
+ RelatedEntityID: this.optionalText(row.RelatedEntityID),
1182
+ RelatedEntityName: this.optionalText(row.RelatedEntityName),
1183
+ RelatedSchemaName: this.optionalText(row.RelatedSchemaName),
1184
+ RelatedBaseTable: this.optionalText(row.RelatedBaseTable),
1185
+ TransitiveObjectName: this.optionalText(row.TransitiveObjectName),
1186
+ }));
1187
+ }
1188
+ catch (e) {
1189
+ logError(` > Could not load organic keys for the retraction pass; organic keys are left alone this run: ${e instanceof Error ? e.message : String(e)}`);
1190
+ return null;
1191
+ }
1192
+ }
1193
+ /** Every entity, as far as matching config entries and spotting a view that backs an entity needs. */
1194
+ async loadEntityRefsForRetraction(pool) {
1195
+ const sql = `SELECT ${this.qi('ID')}, ${this.qi('Name')}, ${this.qi('SchemaName')}, ${this.qi('BaseTable')}, ${this.qi('BaseView')}
1196
+ FROM ${this.qs(MjCoreSchema(), 'Entity')}`;
1197
+ const result = await this.runQuery(pool, sql);
1198
+ return result.recordset.map((row) => ({
1199
+ ID: String(row.ID),
1200
+ Name: String(row.Name),
1201
+ SchemaName: String(row.SchemaName),
1202
+ BaseTable: String(row.BaseTable),
1203
+ BaseView: this.optionalText(row.BaseView),
1204
+ }));
1205
+ }
1206
+ /**
1207
+ * Fields CodeGen set as soft foreign keys. External-data-source entities are left out: their soft
1208
+ * FKs come from introspecting the remote schema, not from the file.
1209
+ */
1210
+ async loadSoftForeignKeyFieldsForRetraction(pool) {
1211
+ const schema = MjCoreSchema();
1212
+ const q = (alias, column) => `${alias}.${this.qi(column)}`;
1213
+ const externalClause = (await this.entityHasExternalDataSourceColumn(pool))
1214
+ ? ` AND ${q('e', 'ExternalDataSourceID')} IS NULL`
1215
+ : '';
1216
+ const sql = `SELECT ${q('e', 'ID')} AS ${this.qi('EntityID')}, ${q('e', 'Name')} AS ${this.qi('EntityName')},
1217
+ ${q('e', 'SchemaName')} AS ${this.qi('SchemaName')}, ${q('e', 'BaseTable')} AS ${this.qi('BaseTable')},
1218
+ ${q('ef', 'Name')} AS ${this.qi('FieldName')}, ${q('re', 'Name')} AS ${this.qi('RelatedEntityName')},
1219
+ ${q('re', 'SchemaName')} AS ${this.qi('RelatedSchemaName')}, ${q('re', 'BaseTable')} AS ${this.qi('RelatedBaseTable')}
1220
+ FROM ${this.qs(schema, 'EntityField')} ef
1221
+ INNER JOIN ${this.qs(schema, 'vwEntities')} e ON ${q('e', 'ID')} = ${q('ef', 'EntityID')}
1222
+ LEFT OUTER JOIN ${this.qs(schema, 'vwEntities')} re ON ${q('re', 'ID')} = ${q('ef', 'RelatedEntityID')}
1223
+ WHERE ${q('ef', 'IsSoftForeignKey')} = ${this.boolLit(true)}${externalClause}
1224
+ ORDER BY ${q('e', 'Name')}, ${q('ef', 'Name')}`;
1225
+ const result = await this.runQuery(pool, sql);
1226
+ return result.recordset.map((row) => ({
1227
+ EntityID: String(row.EntityID),
1228
+ EntityName: String(row.EntityName),
1229
+ SchemaName: String(row.SchemaName),
1230
+ BaseTable: String(row.BaseTable),
1231
+ FieldName: String(row.FieldName),
1232
+ RelatedEntityName: this.optionalText(row.RelatedEntityName),
1233
+ RelatedSchemaName: this.optionalText(row.RelatedSchemaName),
1234
+ RelatedBaseTable: this.optionalText(row.RelatedBaseTable),
1235
+ }));
1236
+ }
1237
+ /** Fields holding value-list rows CodeGen wrote from the file (`Source = 'Config'`). */
1238
+ async loadConfigValueListFieldsForRetraction(pool) {
1239
+ const schema = MjCoreSchema();
1240
+ const q = (alias, column) => `${alias}.${this.qi(column)}`;
1241
+ const sql = `SELECT ${q('e', 'ID')} AS ${this.qi('EntityID')}, ${q('e', 'Name')} AS ${this.qi('EntityName')},
1242
+ ${q('e', 'SchemaName')} AS ${this.qi('SchemaName')}, ${q('e', 'BaseTable')} AS ${this.qi('BaseTable')},
1243
+ ${q('ef', 'Name')} AS ${this.qi('FieldName')}, COUNT(*) AS ${this.qi('ConfigValueCount')}
1244
+ FROM ${this.qs(schema, 'EntityFieldValue')} efv
1245
+ INNER JOIN ${this.qs(schema, 'EntityField')} ef ON ${q('ef', 'ID')} = ${q('efv', 'EntityFieldID')}
1246
+ INNER JOIN ${this.qs(schema, 'Entity')} e ON ${q('e', 'ID')} = ${q('ef', 'EntityID')}
1247
+ WHERE ${q('efv', 'Source')} = 'Config'
1248
+ GROUP BY ${q('e', 'ID')}, ${q('e', 'Name')}, ${q('e', 'SchemaName')}, ${q('e', 'BaseTable')}, ${q('ef', 'Name')}
1249
+ ORDER BY ${q('e', 'Name')}, ${q('ef', 'Name')}`;
1250
+ const result = await this.runQuery(pool, sql);
1251
+ return result.recordset.map((row) => ({
1252
+ EntityID: String(row.EntityID),
1253
+ EntityName: String(row.EntityName),
1254
+ SchemaName: String(row.SchemaName),
1255
+ BaseTable: String(row.BaseTable),
1256
+ FieldName: String(row.FieldName),
1257
+ // PostgreSQL returns COUNT(*) as bigint, which the pg driver delivers as a string
1258
+ ConfigValueCount: Number(row.ConfigValueCount),
1259
+ }));
1260
+ }
1261
+ /**
1262
+ * Works out what the file no longer declares. Only entities whose table the file still lists are
1263
+ * considered, and only rows CodeGen wrote from the file.
1264
+ * @param organicKeysBefore organic key state before this run's config pass; null skips organic keys
1265
+ */
1266
+ async buildConfigRetractionPlan(pool, config, organicKeysBefore) {
1267
+ const entities = await this.loadEntityRefsForRetraction(pool);
1268
+ // Soft keys: table entries and VirtualEntities entries, resolved on schema + table like the writer.
1269
+ const listed = new Set();
1270
+ const declaredForeignKeys = new Set();
1271
+ for (const table of [...this.extractTablesFromConfig(config), ...this.virtualEntityConfigsAsTableConfigs(config)]) {
1272
+ const entity = ResolveConfigEntity(entities, table.SchemaName, table.TableName, false);
1273
+ if (!entity) {
1274
+ continue;
1275
+ }
1276
+ listed.add(NormalizeKey(entity.ID));
1277
+ for (const fk of table.ForeignKeys ?? []) {
1278
+ declaredForeignKeys.add(FieldKey(entity.ID, fk.FieldName));
1279
+ }
1280
+ }
1281
+ const declaredValueLists = new Set();
1282
+ for (const [schemaTable, fields] of this.extractFieldValueLists(config)) {
1283
+ const dot = schemaTable.indexOf('.');
1284
+ const entity = ResolveConfigEntity(entities, schemaTable.slice(0, dot), schemaTable.slice(dot + 1), false);
1285
+ if (!entity) {
1286
+ continue;
1287
+ }
1288
+ listed.add(NormalizeKey(entity.ID));
1289
+ for (const f of fields) {
1290
+ declaredValueLists.add(FieldKey(entity.ID, f.FieldName));
1291
+ }
1292
+ }
1293
+ const softForeignKeys = SelectUndeclaredFields(await this.loadSoftForeignKeyFieldsForRetraction(pool), listed, declaredForeignKeys);
1294
+ const valueLists = SelectUndeclaredFields(await this.loadConfigValueListFieldsForRetraction(pool), listed, declaredValueLists);
1295
+ let organicKeys = { Keys: [], RelatedRows: [], BridgeObjects: [] };
1296
+ const organicKeysAfter = organicKeysBefore ? await this.loadOrganicKeyStateForRetraction(pool) : null;
1297
+ if (organicKeysBefore && organicKeysAfter) {
1298
+ // Organic keys resolve their tables the way processOrganicKeyConfig does: by table, else by entity name.
1299
+ const organicListed = new Set(listed);
1300
+ const declaredKeys = [];
1301
+ const declaredTransitiveObjects = new Set();
1302
+ for (const tableConfig of this.extractOrganicKeysFromConfig(config)) {
1303
+ const owner = ResolveConfigEntity(entities, tableConfig.SchemaName, tableConfig.TableName, true);
1304
+ if (owner) {
1305
+ organicListed.add(NormalizeKey(owner.ID));
1306
+ }
1307
+ for (const ok of tableConfig.OrganicKeys) {
1308
+ let relatedIDs = new Set();
1309
+ for (const re of ok.RelatedEntities) {
1310
+ if (re.TransitiveView) {
1311
+ declaredTransitiveObjects.add(NormalizeObjectName(`${re.TransitiveView.SchemaName || re.SchemaName}.${re.TransitiveView.Name}`));
1312
+ }
1313
+ if (re.TransitiveObject) {
1314
+ declaredTransitiveObjects.add(NormalizeObjectName(re.TransitiveObject));
1315
+ }
1316
+ const related = ResolveConfigEntity(entities, re.SchemaName, re.TableName, true);
1317
+ if (!related) {
1318
+ relatedIDs = null;
1319
+ }
1320
+ else if (relatedIDs) {
1321
+ relatedIDs.add(NormalizeKey(related.ID));
1322
+ }
1323
+ }
1324
+ if (owner) {
1325
+ declaredKeys.push({ EntityID: owner.ID, Name: ok.Name, RelatedEntityIDs: relatedIDs });
1326
+ }
1327
+ }
1328
+ }
1329
+ organicKeys = PlanOrganicKeyRetraction({
1330
+ Before: organicKeysBefore,
1331
+ After: organicKeysAfter,
1332
+ ListedEntityIDs: organicListed,
1333
+ Declared: declaredKeys,
1334
+ DeclaredTransitiveObjects: declaredTransitiveObjects,
1335
+ });
1336
+ }
1337
+ return {
1338
+ SoftForeignKeys: softForeignKeys,
1339
+ ValueLists: valueLists,
1340
+ OrganicKeys: organicKeys,
1341
+ BridgeViews: await this.resolveDroppableBridgeViews(pool, organicKeys.BridgeObjects, entities),
1342
+ };
1343
+ }
1344
+ /**
1345
+ * The bridge objects that can be dropped: views (a table is never dropped) that exist and do not
1346
+ * back an entity. The rest are reported and left in place.
1347
+ */
1348
+ async resolveDroppableBridgeViews(pool, bridgeObjects, entities) {
1349
+ const views = [];
1350
+ for (const objectName of bridgeObjects) {
1351
+ const parsed = ParseObjectName(objectName);
1352
+ if (!parsed) {
1353
+ logStatus(` Bridge object "${objectName}" is no longer used but names no schema — left in place`);
1354
+ continue;
1355
+ }
1356
+ const schema = NormalizeKey(parsed.SchemaName);
1357
+ const name = NormalizeKey(parsed.ObjectName);
1358
+ const backsEntity = entities.some(e => NormalizeKey(e.SchemaName) === schema &&
1359
+ (NormalizeKey(e.BaseTable) === name || NormalizeKey(e.BaseView) === name));
1360
+ if (backsEntity) {
1361
+ logStatus(` Bridge object ${objectName} is no longer used by an organic key but backs an entity — left in place`);
1362
+ continue;
1363
+ }
1364
+ const exists = await this.runQueryWithParams(pool, this.dbProvider.getViewExistsSQL(), { ViewName: parsed.ObjectName, SchemaName: parsed.SchemaName });
1365
+ if (exists.recordset.length === 0) {
1366
+ continue; // already gone, or a table: nothing to drop
1367
+ }
1368
+ views.push({ SchemaName: parsed.SchemaName, ViewName: parsed.ObjectName });
1369
+ }
1370
+ return views;
1371
+ }
1372
+ /** One line per item in the plan, for the run log. */
1373
+ describeConfigRetractionPlan(plan, applying) {
1374
+ const verb = applying ? 'Removing' : 'Would remove';
1375
+ const lines = [];
1376
+ for (const fk of plan.SoftForeignKeys) {
1377
+ lines.push(`${verb} soft FK ${fk.SchemaName}.${fk.BaseTable}.${fk.FieldName} → ${fk.RelatedEntityName ?? '(missing entity)'}`);
1378
+ }
1379
+ for (const vl of plan.ValueLists) {
1380
+ lines.push(`${verb} value list of ${vl.SchemaName}.${vl.BaseTable}.${vl.FieldName} (${vl.ConfigValueCount} value${vl.ConfigValueCount === 1 ? '' : 's'})`);
1381
+ }
1382
+ for (const key of plan.OrganicKeys.Keys) {
1383
+ lines.push(`${verb} organic key "${key.KeyName}" on ${key.EntityName}, with its related entities`);
1384
+ }
1385
+ for (const row of plan.OrganicKeys.RelatedRows) {
1386
+ lines.push(`${verb} related entity ${row.RelatedEntityName ?? row.RelatedEntityID} from organic key "${row.KeyName}" on ${row.EntityName}`);
1387
+ }
1388
+ for (const view of plan.BridgeViews) {
1389
+ lines.push(`${verb} unused bridge view ${view.SchemaName}.${view.ViewName}`);
1390
+ }
1391
+ return lines;
1392
+ }
1393
+ /**
1394
+ * Retracts what CodeGen wrote from additionalSchemaInfo and the file no longer declares: soft
1395
+ * foreign keys (with their generated relationships), value lists, and organic keys (with their
1396
+ * related entities and bridge views no longer used). Reports the plan on every run; applies it only
1397
+ * when `retractRemovedSoftKeys` is on. Every change goes through the migration log.
1398
+ * @param organicKeysBefore organic key state captured before processOrganicKeyConfig ran
1399
+ */
1400
+ async retractRemovedConfigDeclarations(pool, organicKeysBefore) {
1401
+ const config = ManageMetadataBase.GetSoftPKFKConfig();
1402
+ if (!config) {
1403
+ return true; // no file, or an unreadable one: never retract on that signal
1404
+ }
1405
+ try {
1406
+ const plan = await this.buildConfigRetractionPlan(pool, config, organicKeysBefore);
1407
+ const applying = configInfo.retractRemovedSoftKeys === true;
1408
+ const lines = this.describeConfigRetractionPlan(plan, applying);
1409
+ if (lines.length === 0) {
1410
+ return true;
1411
+ }
1412
+ for (const line of lines) {
1413
+ logStatus(` ${line}`);
1414
+ }
1415
+ const summary = `${plan.SoftForeignKeys.length} soft FK(s), ${plan.ValueLists.length} value list(s), ` +
1416
+ `${plan.OrganicKeys.Keys.length} organic key(s), ${plan.OrganicKeys.RelatedRows.length} organic-key related entit(ies) ` +
1417
+ `and ${plan.BridgeViews.length} bridge view(s)`;
1418
+ if (!applying) {
1419
+ LogWarning(` additionalSchemaInfo no longer declares ${summary} that CodeGen created from it. ` +
1420
+ `Set retractRemovedSoftKeys: true in mj.config.cjs to remove them.`);
1421
+ return true;
1422
+ }
1423
+ logStatus(` Retracting ${summary} that additionalSchemaInfo no longer declares`);
1424
+ await this.applyConfigRetractionPlan(pool, plan);
1425
+ return true;
1426
+ }
1427
+ catch (e) {
1428
+ logError(` Error retracting declarations removed from additionalSchemaInfo: ${e instanceof Error ? e.message : String(e)}`);
1429
+ return false;
1430
+ }
1431
+ }
1432
+ /**
1433
+ * Applies a retraction plan. Statements identify rows by entity schema + table and by name rather
1434
+ * than by ID, so the logged migration applies to any database. Bridge views are dropped last, after
1435
+ * nothing references them; a view the database refuses to drop is reported and left in place.
1436
+ */
1437
+ async applyConfigRetractionPlan(pool, plan) {
1438
+ const schema = MjCoreSchema();
1439
+ const esc = (value) => EscapeSQLString(value);
1440
+ const entityRef = (schemaName, baseTable) => this.entityIdSubquery(esc(baseTable), esc(schemaName));
1441
+ const modifiedEntities = [];
1442
+ for (const fk of plan.SoftForeignKeys) {
1443
+ const child = entityRef(fk.SchemaName, fk.BaseTable);
1444
+ const statements = [];
1445
+ if (fk.RelatedSchemaName && fk.RelatedBaseTable) {
1446
+ statements.push(`DELETE FROM ${this.qs(schema, 'EntityRelationship')}
1447
+ WHERE ${this.qi('EntityID')} = ${entityRef(fk.RelatedSchemaName, fk.RelatedBaseTable)}
1448
+ AND ${this.qi('RelatedEntityID')} = ${child}
1449
+ AND ${this.qi('RelatedEntityJoinField')} = '${esc(fk.FieldName)}'
1450
+ AND ${this.qi('Type')} = 'One To Many'
1451
+ AND ${this.qi('AutoUpdateFromSchema')} = ${this.boolLit(true)}`);
1452
+ }
1453
+ statements.push(`UPDATE ${this.qs(schema, 'EntityField')}
1454
+ SET ${this.qi(EntityInfo.UpdatedAtFieldName)} = ${this.utcNow()},
1455
+ ${this.qi('RelatedEntityID')} = NULL,
1456
+ ${this.qi('RelatedEntityFieldName')} = NULL,
1457
+ ${this.qi('IsSoftForeignKey')} = ${this.boolLit(false)},
1458
+ ${this.qi('AutoUpdateRelatedEntityInfo')} = ${this.boolLit(true)}
1459
+ WHERE ${this.qi('EntityID')} = ${child}
1460
+ AND ${this.qi('Name')} = '${esc(fk.FieldName)}'
1461
+ AND ${this.qi('IsSoftForeignKey')} = ${this.boolLit(true)}`);
1462
+ await this.logSQLBatchAndExecute(pool, statements, `Retract soft FK ${fk.SchemaName}.${fk.BaseTable}.${fk.FieldName} removed from additionalSchemaInfo`);
1463
+ modifiedEntities.push(fk.EntityName);
1464
+ }
1465
+ for (const vl of plan.ValueLists) {
1466
+ const entity = entityRef(vl.SchemaName, vl.BaseTable);
1467
+ const fieldID = `(SELECT ${this.qi('ID')} FROM ${this.qs(schema, 'EntityField')} WHERE ${this.qi('EntityID')} = ${entity} AND ${this.qi('Name')} = '${esc(vl.FieldName)}')`;
1468
+ await this.logSQLBatchAndExecute(pool, [
1469
+ `DELETE FROM ${this.qs(schema, 'EntityFieldValue')} WHERE ${this.qi('EntityFieldID')} = ${fieldID} AND ${this.qi('Source')} = 'Config'`,
1470
+ `UPDATE ${this.qs(schema, 'EntityField')} SET ${this.qi('ValueListType')} = 'None'
1471
+ WHERE ${this.qi('EntityID')} = ${entity} AND ${this.qi('Name')} = '${esc(vl.FieldName)}'
1472
+ AND NOT EXISTS (SELECT 1 FROM ${this.qs(schema, 'EntityFieldValue')} efv WHERE efv.${this.qi('EntityFieldID')} = ${this.qi('EntityField')}.${this.qi('ID')})`,
1473
+ ], `Retract value list of ${vl.SchemaName}.${vl.BaseTable}.${vl.FieldName} removed from additionalSchemaInfo`);
1474
+ modifiedEntities.push(vl.EntityName);
1475
+ }
1476
+ const keyRef = (row) => `(SELECT ${this.qi('ID')} FROM ${this.qs(schema, 'EntityOrganicKey')} WHERE ${this.qi('EntityID')} = ${entityRef(row.SchemaName, row.BaseTable)} AND ${this.qi('Name')} = '${esc(row.KeyName)}')`;
1477
+ for (const row of plan.OrganicKeys.RelatedRows) {
1478
+ if (!row.RelatedSchemaName || !row.RelatedBaseTable) {
1479
+ continue;
1480
+ }
1481
+ await this.logSQLAndExecute(pool, `DELETE FROM ${this.qs(schema, 'EntityOrganicKeyRelatedEntity')}
1482
+ WHERE ${this.qi('EntityOrganicKeyID')} = ${keyRef(row)} AND ${this.qi('RelatedEntityID')} = ${entityRef(row.RelatedSchemaName, row.RelatedBaseTable)}`, `Retract related entity ${row.RelatedEntityName} of organic key "${row.KeyName}" on ${row.EntityName}`);
1483
+ }
1484
+ for (const key of plan.OrganicKeys.Keys) {
1485
+ await this.logSQLBatchAndExecute(pool, [
1486
+ `DELETE FROM ${this.qs(schema, 'EntityOrganicKeyRelatedEntity')} WHERE ${this.qi('EntityOrganicKeyID')} = ${keyRef(key)}`,
1487
+ `DELETE FROM ${this.qs(schema, 'EntityOrganicKey')}
1488
+ WHERE ${this.qi('EntityID')} = ${entityRef(key.SchemaName, key.BaseTable)} AND ${this.qi('Name')} = '${esc(key.KeyName)}' AND ${this.qi('Source')} = 'Config'`,
1489
+ ], `Retract organic key "${key.KeyName}" on ${key.EntityName}`);
1490
+ }
1491
+ for (const view of plan.BridgeViews) {
1492
+ try {
1493
+ await this.logSQLAndExecute(pool, this.dbProvider.dropObjectSQL('VIEW', view.SchemaName, view.ViewName), `Drop bridge view ${view.SchemaName}.${view.ViewName}, no longer used by any organic key`);
1494
+ }
1495
+ catch (e) {
1496
+ LogWarning(` Could not drop bridge view ${view.SchemaName}.${view.ViewName}; it is left in place: ${e instanceof Error ? e.message : String(e)}`);
1497
+ }
1498
+ }
1499
+ if (modifiedEntities.length > 0) {
1500
+ // Pass 2 re-syncs these entities' fields; the refreshed metadata lets the SQL generation
1501
+ // that follows drop the retracted joins from their base views.
1502
+ ManageMetadataBase.AddNewEntitiesToModifiedList(modifiedEntities);
1503
+ await this.refreshMetadataAfterRetraction();
1504
+ }
1505
+ }
1506
+ /** Reloads the metadata cache after retracted soft FKs or value lists changed field metadata. */
1507
+ async refreshMetadataAfterRetraction() {
1508
+ const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
1509
+ await md.Refresh();
1510
+ }
1003
1511
  /**
1004
1512
  * Builds the entity lookup behind {@link processISARelationshipConfig}: match on Name first, else
1005
1513
  * on BaseTable, optionally constrained to a schema.
@@ -2282,15 +2790,23 @@ export class ManageMetadataBase {
2282
2790
  logStatus(` > Updated attributes on ${entityConfigResult.updatedCount} entit${entityConfigResult.updatedCount === 1 ? 'y' : 'ies'} from config`);
2283
2791
  }
2284
2792
  // Config-driven organic key setup — create bridge views and upsert organic key metadata
2285
- // Must run AFTER entities exist
2793
+ // Must run AFTER entities exist. The state before it runs is kept for the retraction pass
2794
+ // below: a related row the pass reshapes in place loses the bridge view it referenced.
2795
+ const organicKeysBeforeConfig = await this.loadOrganicKeyStateForRetraction(pool);
2286
2796
  const organicKeyResult = await this.processOrganicKeyConfig(pool);
2287
- if (organicKeyResult.createdCount > 0 || organicKeyResult.updatedCount > 0) {
2288
- logStatus(` > Organic keys: ${organicKeyResult.createdCount} created, ${organicKeyResult.updatedCount} updated from config`);
2797
+ if (organicKeyResult.createdCount > 0 || organicKeyResult.updatedCount > 0 || organicKeyResult.unchangedCount > 0) {
2798
+ logStatus(` > Organic keys: ${organicKeyResult.createdCount} created, ${organicKeyResult.updatedCount} updated, ${organicKeyResult.unchangedCount} unchanged from config`);
2289
2799
  }
2290
2800
  if (!organicKeyResult.success) {
2291
2801
  logError(` Error processing organic keys: ${organicKeyResult.failedCount} key(s) failed and were not applied — see the errors above`);
2292
2802
  bSuccess = false;
2293
2803
  }
2804
+ // Soft FKs, value lists and organic keys that CodeGen wrote from additionalSchemaInfo and the
2805
+ // file no longer declares: reported, or removed when retractRemovedSoftKeys is on (#4535).
2806
+ if (!await this.retractRemovedConfigDeclarations(pool, organicKeysBeforeConfig)) {
2807
+ logError(' Error retracting declarations removed from additionalSchemaInfo — see the errors above');
2808
+ bSuccess = false;
2809
+ }
2294
2810
  // Config-driven base-view materialization — emit the physical table + wrapper view and
2295
2811
  // attach an "MJ: Materialized Results" row to the existing entity. Runs AFTER entity fields
2296
2812
  // are managed so the snapshot shape reflects the current base view (plan §4.1).
@@ -4321,6 +4837,14 @@ export class ManageMetadataBase {
4321
4837
  bSuccess = false;
4322
4838
  }
4323
4839
  logStatus(` Updated existing entity fields from schema in ${(new Date().getTime() - step3StartTime.getTime()) / 1000} seconds`);
4840
+ // Unique keys as column sets (#4536). Unscoped: an index can be added or dropped without any
4841
+ // column changing, so the entity would not be in this pass's filter. One catalog read.
4842
+ const stepUniqueKeysStartTime = new Date();
4843
+ if (!await this.syncEntityUniqueKeys(pool, excludeSchemas)) {
4844
+ logError('Error syncing entity unique keys from schema');
4845
+ bSuccess = false;
4846
+ }
4847
+ logStatus(` Synced entity unique keys from schema in ${(new Date().getTime() - stepUniqueKeysStartTime.getTime()) / 1000} seconds`);
4324
4848
  // Apply soft PK/FK configuration if config file exists
4325
4849
  const stepConfigStartTime = new Date();
4326
4850
  if (!await this.applySoftPKFKConfig(pool)) {
@@ -4393,7 +4917,13 @@ export class ManageMetadataBase {
4393
4917
  // default is precisely the one that ends up flagged searchable with nothing searchable on
4394
4918
  // it. Ordered after it so the model's choices, where it did run, are already applied and
4395
4919
  // the seed only fills a genuine gap. See buildSearchFlagHygieneSQL.
4396
- if (!await this.applySearchFlagHygiene(pool, excludeSchemas)) {
4920
+ // Scoped by the authored exclude list and the include list, never the compiled exclude list:
4921
+ // that one names every other schema on the publisher's database, so a capture carrying it
4922
+ // would touch entities in schemas this run does not own on a host (#6384).
4923
+ if (!await this.applySearchFlagHygiene(pool, {
4924
+ IncludeSchemas: configInfo.includeSchemas,
4925
+ AuthoredExclude: GetAuthoredExcludeSchemas(excludeSchemas),
4926
+ })) {
4397
4927
  logError('Error applying search flag hygiene');
4398
4928
  // FATAL, unlike advanced generation. This pass compares before it writes, so a failure
4399
4929
  // means the probes could not run — and because nothing is written in that case, the pass
@@ -4841,8 +5371,9 @@ export class ManageMetadataBase {
4841
5371
  /**
4842
5372
  * Applies soft value-list configuration from Fields[] entries in additionalSchemaInfo.json.
4843
5373
  * Runs AFTER manageEntityFieldValuesAndValidatorFunctions() so CHECK-constraint-derived
4844
- * values are already in the database. If EntityFieldValue rows already exist for a field
4845
- * (from CHECK constraints), the soft-enum pass skips that field — CHECK is authoritative.
5374
+ * values are already in the database. A field whose list a CHECK constraint owns is skipped, as
5375
+ * is a field holding a different list that was not written from the file. Rows written here are
5376
+ * stamped `Source = 'Config'`, which is what lets a later run retract them (#4535).
4846
5377
  */
4847
5378
  async applyValueListConfig(pool) {
4848
5379
  const config = ManageMetadataBase.getSoftPKFKConfig();
@@ -4865,7 +5396,7 @@ export class ManageMetadataBase {
4865
5396
  totalSkipped += result.skipped;
4866
5397
  }
4867
5398
  if (totalApplied > 0 || totalSkipped > 0) {
4868
- logStatus(` Applied ${totalApplied} soft value-list(s), skipped ${totalSkipped} (CHECK-authoritative)`);
5399
+ logStatus(` Applied ${totalApplied} soft value-list(s), skipped ${totalSkipped} (owned by a CHECK constraint or entered by hand, or field not found)`);
4869
5400
  }
4870
5401
  return true;
4871
5402
  }
@@ -4875,23 +5406,24 @@ export class ManageMetadataBase {
4875
5406
  }
4876
5407
  }
4877
5408
  /**
4878
- * Applies value-list fields for a single table. For each field, checks if
4879
- * EntityFieldValue rows already exist (from CHECK constraints) and skips if so.
5409
+ * Applies value-list fields for a single table, skipping fields whose list the file does not own
5410
+ * (see {@link applyValueListForField}).
4880
5411
  */
4881
5412
  async applyValueListsForTable(pool, schemaName, tableName, fields, allEntityFieldValues) {
4882
5413
  const schema = MjCoreSchema();
4883
5414
  let applied = 0;
4884
5415
  let skipped = 0;
4885
5416
  // Look up entity ID
4886
- const entityLookupSQL = `SELECT ID FROM ${this.qs(schema, 'Entity')} WHERE SchemaName = '${schemaName}' AND BaseTable = '${tableName}'`;
5417
+ const entityLookupSQL = `SELECT ID, ${this.qi('Name')} FROM ${this.qs(schema, 'Entity')} WHERE SchemaName = '${schemaName}' AND BaseTable = '${tableName}'`;
4887
5418
  const entityResult = await this.runQuery(pool, entityLookupSQL);
4888
5419
  if (entityResult.recordset.length === 0) {
4889
5420
  logStatus(` ⚠️ Entity not found for ${schemaName}.${tableName} — skipping soft value-lists`);
4890
5421
  return { applied, skipped };
4891
5422
  }
4892
5423
  const entityId = entityResult.recordset[0].ID;
5424
+ const entityName = entityResult.recordset[0].Name;
4893
5425
  for (const fieldCfg of fields) {
4894
- const fieldResult = await this.applyValueListForField(pool, schema, entityId, schemaName, tableName, fieldCfg, allEntityFieldValues);
5426
+ const fieldResult = await this.applyValueListForField(pool, schema, entityId, entityName, schemaName, tableName, fieldCfg, allEntityFieldValues);
4895
5427
  if (fieldResult === 'applied')
4896
5428
  applied++;
4897
5429
  else
@@ -4902,7 +5434,7 @@ export class ManageMetadataBase {
4902
5434
  /**
4903
5435
  * Applies value-list config for a single field. Returns 'applied' or 'skipped'.
4904
5436
  */
4905
- async applyValueListForField(pool, schema, entityId, schemaName, tableName, fieldCfg, allEntityFieldValues) {
5437
+ async applyValueListForField(pool, schema, entityId, entityName, schemaName, tableName, fieldCfg, allEntityFieldValues) {
4906
5438
  // Look up EntityField ID
4907
5439
  const efSQL = `SELECT ID, ValueListType FROM ${this.qs(schema, 'EntityField')} WHERE EntityID = '${entityId}' AND Name = '${fieldCfg.FieldName}'`;
4908
5440
  const efResult = await this.runQuery(pool, efSQL);
@@ -4912,20 +5444,33 @@ export class ManageMetadataBase {
4912
5444
  }
4913
5445
  const efRecord = efResult.recordset[0];
4914
5446
  const entityFieldID = efRecord.ID;
4915
- // CHECK constraint is authoritative — if EntityFieldValue rows already exist, skip
4916
- const existing = allEntityFieldValues.filter((efv) => String(efv.EntityFieldID) === String(entityFieldID));
5447
+ // A CHECK constraint is authoritative, and a list someone entered by hand is theirs: the file
5448
+ // writes the list only when it is empty, already the file's, or holds exactly the declared values.
5449
+ const existing = allEntityFieldValues.filter(efv => String(efv.EntityFieldID) === String(entityFieldID));
4917
5450
  const currentValueListType = (efRecord.ValueListType || '').trim().toLowerCase();
4918
- if (existing.length > 0 && currentValueListType !== 'none' && currentValueListType !== '') {
5451
+ const sortedValues = [...fieldCfg.PossibleValues].sort();
5452
+ const action = DecideConfigValueListAction(existing, sortedValues);
5453
+ if (action === 'SkipCheck') {
4919
5454
  return 'skipped';
4920
5455
  }
4921
- // Apply: sync values and set ValueListType
4922
- const sortedValues = [...fieldCfg.PossibleValues].sort();
4923
- await this.syncEntityFieldValues(pool, entityFieldID, sortedValues, allEntityFieldValues);
5456
+ if (action === 'SkipManual') {
5457
+ logStatus(` ⚠️ ${schemaName}.${tableName}.${fieldCfg.FieldName} has a value list that was not written from additionalSchemaInfo and differs from it — leaving it as it is`);
5458
+ return 'skipped';
5459
+ }
5460
+ // Apply: sync values (stamping them as Config) and set ValueListType. syncEntityFieldValues
5461
+ // matches rows on the field ID exactly as the list was loaded, so pass that value through.
5462
+ const loadedFieldID = existing.length > 0 ? existing[0].EntityFieldID : entityFieldID;
5463
+ let listChanged = await this.syncEntityFieldValues(pool, loadedFieldID, sortedValues, allEntityFieldValues, 'Config');
4924
5464
  // Update ValueListType
4925
5465
  const newType = fieldCfg.ValueListType;
4926
5466
  if (currentValueListType !== newType.toLowerCase()) {
4927
5467
  const updateSQL = `UPDATE ${this.qs(schema, 'EntityField')} SET ValueListType='${newType}' WHERE ID='${entityFieldID}'`;
4928
5468
  await this.logSQLAndExecute(pool, updateSQL, `Set soft ValueListType='${newType}' for ${schemaName}.${tableName}.${fieldCfg.FieldName}`);
5469
+ listChanged = true;
5470
+ }
5471
+ if (listChanged) {
5472
+ // the generated union / Zod enum for this field changed, so its schema must be re-emitted
5473
+ ManageMetadataBase.AddNewEntitiesToModifiedList([entityName]);
4929
5474
  }
4930
5475
  logStatus(` ✓ Applied soft value-list for ${tableName}.${fieldCfg.FieldName} (${sortedValues.length} values, type=${newType})`);
4931
5476
  return 'applied';
@@ -5371,47 +5916,40 @@ export class ManageMetadataBase {
5371
5916
  const newEntityFieldsResult = await this.runQuery(pool, sSQL);
5372
5917
  const newEntityFields = newEntityFieldsResult.recordset;
5373
5918
  if (newEntityFields.length > 0) {
5374
- const transaction = await pool.beginTransaction();
5375
- try {
5376
- // wrap in a transaction so we get all of it or none of it.
5377
- // [Large Schema Series] Batch the per-field INSERTs. Previously this
5378
- // issued one LogSQLAndExecute — a DB round-trip AND a synchronous
5379
- // migration-log append — PER field, i.e. ~40k on a 2,000-table
5380
- // install (~37s). Collect each row's INSERT SQL (unchanged, conflict
5381
- // guards intact) and flush in chunks through LogSQLBatchAndExecute,
5382
- // which terminates + joins the statements and sends each chunk as a
5383
- // single round-trip + single log append while preserving the exact
5384
- // per-row SQL and the replayable migration-file output. Both dialects.
5385
- // Batch size is configurable via `metadataInsertBatchSize` (default 250).
5386
- const CHUNK_SIZE = configInfo.metadataInsertBatchSize ?? 250;
5387
- const inserts = [];
5388
- for (let i = 0; i < newEntityFields.length; ++i) {
5389
- const n = newEntityFields[i];
5390
- if (n.EntityID !== null && n.EntityID !== undefined && n.EntityID.length > 0) {
5391
- // need to check for null entity id = that is because the above query can return candidate Entity Fields but the entities may not have been created if the entities
5392
- // that would have been created violate rules - such as not having an ID column, etc.
5393
- const newEntityFieldUUID = this.createNewUUID();
5394
- inserts.push(this.getPendingEntityFieldINSERTSQL(newEntityFieldUUID, n));
5395
- ManageMetadataBase.registerNewField(n.EntityID, n.FieldName);
5396
- }
5919
+ // Not atomic: each chunk below commits on its own. A failed chunk leaves the earlier ones
5920
+ // in place, and a re-run repairs that, since the pending-field SELECT above only returns
5921
+ // columns that have no EntityField row yet.
5922
+ // [Large Schema Series] Batch the per-field INSERTs. Previously this
5923
+ // issued one LogSQLAndExecute — a DB round-trip AND a synchronous
5924
+ // migration-log append — PER field, i.e. ~40k on a 2,000-table
5925
+ // install (~37s). Collect each row's INSERT SQL (unchanged, conflict
5926
+ // guards intact) and flush in chunks through LogSQLBatchAndExecute,
5927
+ // which terminates + joins the statements and sends each chunk as a
5928
+ // single round-trip + single log append while preserving the exact
5929
+ // per-row SQL and the replayable migration-file output. Both dialects.
5930
+ // Batch size is configurable via `metadataInsertBatchSize` (default 250).
5931
+ const CHUNK_SIZE = configInfo.metadataInsertBatchSize ?? 250;
5932
+ const inserts = [];
5933
+ for (let i = 0; i < newEntityFields.length; ++i) {
5934
+ const n = newEntityFields[i];
5935
+ if (n.EntityID !== null && n.EntityID !== undefined && n.EntityID.length > 0) {
5936
+ // need to check for null entity id = that is because the above query can return candidate Entity Fields but the entities may not have been created if the entities
5937
+ // that would have been created violate rules - such as not having an ID column, etc.
5938
+ const newEntityFieldUUID = this.createNewUUID();
5939
+ inserts.push(this.getPendingEntityFieldINSERTSQL(newEntityFieldUUID, n));
5940
+ ManageMetadataBase.registerNewField(n.EntityID, n.FieldName);
5397
5941
  }
5398
- for (let i = 0; i < inserts.length; i += CHUNK_SIZE) {
5399
- const chunk = inserts.slice(i, i + CHUNK_SIZE);
5400
- try {
5401
- await this.logSQLBatchAndExecute(pool, chunk, `SQL text to insert ${chunk.length} new entity field(s)`);
5402
- // an error blows up the transaction (all-or-nothing), which is what we want
5403
- }
5404
- catch (e) {
5405
- // catch for debug context, then let the transaction die
5406
- logError(`Error inserting new entity field batch (rows ${i}..${i + chunk.length}).`);
5407
- throw e;
5408
- }
5409
- }
5410
- await transaction.commit();
5411
5942
  }
5412
- catch (e) {
5413
- await transaction.rollback();
5414
- throw e;
5943
+ for (let i = 0; i < inserts.length; i += CHUNK_SIZE) {
5944
+ const chunk = inserts.slice(i, i + CHUNK_SIZE);
5945
+ try {
5946
+ await this.logSQLBatchAndExecute(pool, chunk, `SQL text to insert ${chunk.length} new entity field(s)`);
5947
+ }
5948
+ catch (e) {
5949
+ // catch for debug context, then stop: the remaining chunks are left for a re-run
5950
+ logError(`Error inserting new entity field batch (rows ${i}..${i + chunk.length}).`);
5951
+ throw e;
5952
+ }
5415
5953
  }
5416
5954
  // if we get here now send a distinct list of the entities that had new fields to the modified entity list
5417
5955
  // column in the resultset is called EntityName, we dont have to dedupe them here because the method below
@@ -5521,6 +6059,43 @@ export class ManageMetadataBase {
5521
6059
  return false;
5522
6060
  }
5523
6061
  }
6062
+ /**
6063
+ * Makes `EntityUniqueKey` match the database catalog (#4536): one row per unique index or unique
6064
+ * constraint on each entity's base table, with its key columns in order. Only entities outside
6065
+ * `excludeSchemas` are read or written. See unique-key-sets.ts.
6066
+ */
6067
+ async syncEntityUniqueKeys(pool, excludeSchemas) {
6068
+ try {
6069
+ const schema = MjCoreSchema();
6070
+ const catalog = await this.runQuery(pool, BuildCatalogUniqueKeyColumnsSQL(this.dialect, schema, excludeSchemas));
6071
+ const storedRes = await this.runQuery(pool, BuildStoredUniqueKeySetsSQL(this.dialect, schema, excludeSchemas));
6072
+ const desired = GroupUniqueKeyColumns(catalog.recordset.map((r) => ({
6073
+ EntityID: String(r.EntityID),
6074
+ IndexName: String(r.IndexName),
6075
+ ColumnName: String(r.ColumnName),
6076
+ KeyOrdinal: Number(r.KeyOrdinal),
6077
+ FilterDefinition: r.FilterDefinition == null ? null : String(r.FilterDefinition),
6078
+ })));
6079
+ const stored = storedRes.recordset.map((r) => ({
6080
+ ID: String(r.ID),
6081
+ EntityID: String(r.EntityID),
6082
+ Name: String(r.Name),
6083
+ FieldNames: String(r.FieldNames),
6084
+ FilterDefinition: r.FilterDefinition == null ? null : String(r.FilterDefinition),
6085
+ }));
6086
+ const changes = DiffUniqueKeySets(desired, stored);
6087
+ const statements = BuildUniqueKeySetSyncSQL(this.dialect, schema, changes, () => uuidv4());
6088
+ if (statements.length > 0) {
6089
+ await this.logSQLBatchAndExecute(pool, statements, `SQL text to sync entity unique keys (${changes.Inserts.length} added, ${changes.Updates.length} updated, ${changes.Deletes.length} removed)`);
6090
+ logStatus(` > Entity unique keys: ${changes.Inserts.length} added, ${changes.Updates.length} updated, ${changes.Deletes.length} removed`);
6091
+ }
6092
+ return true;
6093
+ }
6094
+ catch (e) {
6095
+ logError(`Error syncing entity unique keys: ${e}`);
6096
+ return false;
6097
+ }
6098
+ }
5524
6099
  /**
5525
6100
  * Syncs SchemaInfo records from database schemas, capturing extended properties as descriptions.
5526
6101
  * Creates new SchemaInfo records for schemas that don't exist yet and updates descriptions
@@ -5862,7 +6437,7 @@ export class ManageMetadataBase {
5862
6437
  // dropdown reads 1, 2, 10 rather than the lexical 1, 10, 2 — still fully deterministic.
5863
6438
  ManageMetadataBase.sortCheckConstraintValues(parsedValues);
5864
6439
  // we have parsed values from the check constraint, so sync them with the entity field values
5865
- await this.syncEntityFieldValues(pool, r.EntityFieldID, parsedValues, allEntityFieldValues);
6440
+ let listChanged = await this.syncEntityFieldValues(pool, r.EntityFieldID, parsedValues, allEntityFieldValues, 'Check');
5866
6441
  // finally, make sure the ValueListType column within the EntityField table is set to "List" because for check constraints we only allow the values specified in the list.
5867
6442
  // check to see if the ValueListType is already set to "List", if not, update it
5868
6443
  const sSQLCheck = `SELECT ValueListType FROM ${this.qs(MjCoreSchema(), 'EntityField')} WHERE ID='${r.EntityFieldID}'`;
@@ -5871,6 +6446,12 @@ export class ManageMetadataBase {
5871
6446
  if (checkResult && checkResult.length > 0 && checkResult[0].ValueListType.trim().toLowerCase() !== 'list') {
5872
6447
  const sSQL = `UPDATE ${this.qs(MjCoreSchema(), 'EntityField')} SET ValueListType='List' WHERE ID='${r.EntityFieldID}'`;
5873
6448
  await this.logSQLAndExecute(pool, sSQL, `SQL text to update ValueListType for entity field ID ${r.EntityFieldID}`);
6449
+ listChanged = true;
6450
+ }
6451
+ if (listChanged && r.EntityName) {
6452
+ // a migration that only changes a CHECK value list changes the generated union and
6453
+ // Zod enum, so the entity's schema must be re-emitted even with dirtySchemaOnly (#6207)
6454
+ ManageMetadataBase.AddNewEntitiesToModifiedList([r.EntityName]);
5874
6455
  }
5875
6456
  }
5876
6457
  else {
@@ -6073,59 +6654,26 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6073
6654
  static EntityFieldValueCode(value) {
6074
6655
  return value.length <= ManageMetadataBase.EntityFieldValueCodeMaxLength ? value : null;
6075
6656
  }
6076
- async syncEntityFieldValues(ds, entityFieldID, possibleValues, allEntityFieldValues) {
6657
+ /**
6658
+ * Makes a field's EntityFieldValue rows match `possibleValues`: deletes the rows not in the list,
6659
+ * inserts the missing ones, and fixes the Sequence of the rest. Every row it leaves behind carries
6660
+ * `source`, so a row of another origin that holds a listed value is claimed by the writer (#4535).
6661
+ * Callers decide beforehand whether they own the list (see {@link DecideConfigValueListAction}).
6662
+ *
6663
+ * The statements for the field are sent as one batch that the database applies atomically (see
6664
+ * {@link AtomicBatchSQL}), so a failure leaves the field's rows as they were.
6665
+ *
6666
+ * @returns true when any row was added, removed, re-sequenced or re-stamped, so the caller can mark
6667
+ * the entity modified: a changed list changes the generated union and Zod enum (#6207). False when
6668
+ * nothing changed or the batch failed (and was rolled back).
6669
+ */
6670
+ async syncEntityFieldValues(ds, entityFieldID, possibleValues, allEntityFieldValues, source) {
6077
6671
  try {
6078
- // first, get a list of all of the existing entity field values for the field already in the database
6079
- const existingValues = allEntityFieldValues.filter((efv) => efv.EntityFieldID === entityFieldID);
6080
- // now, loop through the possible values and add any that are not already in the database
6081
- // Step 1: for any existing value that is NOT in the list of possible Values, delete it
6082
- let numRemoved = 0;
6083
- const transaction = await ds.beginTransaction();
6084
- try {
6085
- for (const ev of existingValues) {
6086
- if (!possibleValues.find(v => v === ev.Value)) {
6087
- // delete the value from the database
6088
- const sSQLDelete = `DELETE FROM ${this.qs(MjCoreSchema(), 'EntityFieldValue')} WHERE ID='${ev.ID}'`;
6089
- await this.logSQLAndExecute(ds, sSQLDelete, `SQL text to delete entity field value ID ${ev.ID}`);
6090
- numRemoved++;
6091
- }
6092
- }
6093
- // Step 2: for any possible value that is NOT in the list of existing values, add it
6094
- let numAdded = 0;
6095
- for (const v of possibleValues) {
6096
- if (!existingValues.find((ev) => ev.Value === v)) {
6097
- // Generate a UUID for this new EntityFieldValue record
6098
- const newId = uuidv4();
6099
- // add the value to the database with explicit ID. Code is NULL ("same as Value") when
6100
- // the value is longer than the Code column; copying it overflowed that column (#2577).
6101
- const code = ManageMetadataBase.EntityFieldValueCode(v);
6102
- const sSQLInsert = `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityFieldValue')}
6103
- (${this.qi('ID')}, ${this.qi('EntityFieldID')}, ${this.qi('Sequence')}, ${this.qi('Value')}, ${this.qi('Code')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')})
6104
- VALUES
6105
- ('${newId}', '${entityFieldID}', ${1 + possibleValues.indexOf(v)}, '${EscapeSQLString(v)}', ${code === null ? 'NULL' : `'${EscapeSQLString(code)}'`}, ${this.utcNow()}, ${this.utcNow()})`;
6106
- await this.logSQLAndExecute(ds, sSQLInsert, `SQL text to insert entity field value with ID ${newId}`);
6107
- numAdded++;
6108
- }
6109
- }
6110
- // Step 3: finally, for the existing values that are in the list of possible values, update the sequence to match the order in the possible values list
6111
- let numUpdated = 0;
6112
- for (const v of possibleValues) {
6113
- const ev = existingValues.find((ev) => ev.Value === v);
6114
- // NOTE: We are using != below for comparing Sequence instead of strict !== in case the
6115
- // DB returns a string for Sequence instead of a number.
6116
- if (ev && ev.Sequence != 1 + possibleValues.indexOf(v)) {
6117
- // update the sequence to match the order in the possible values list, if it doesn't already match
6118
- const sSQLUpdate = `UPDATE ${this.qs(MjCoreSchema(), 'EntityFieldValue')} SET Sequence=${1 + possibleValues.indexOf(v)} WHERE ID='${ev.ID}'`;
6119
- await this.logSQLAndExecute(ds, sSQLUpdate, `SQL text to update entity field value sequence`);
6120
- numUpdated++;
6121
- }
6122
- }
6123
- await transaction.commit();
6124
- }
6125
- catch (e) {
6126
- await transaction.rollback();
6127
- throw e;
6672
+ const statements = this.entityFieldValueSyncStatements(entityFieldID, possibleValues, allEntityFieldValues, source);
6673
+ if (statements.length === 0) {
6674
+ return false;
6128
6675
  }
6676
+ await this.logSQLBatchAndExecuteAtomically(ds, statements, `SQL text to sync ${statements.length} entity field value row(s) for entity field ID ${entityFieldID}`);
6129
6677
  return true;
6130
6678
  }
6131
6679
  catch (e) {
@@ -6133,6 +6681,54 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6133
6681
  return false;
6134
6682
  }
6135
6683
  }
6684
+ /**
6685
+ * The DELETE, INSERT and UPDATE statements that make a field's EntityFieldValue rows match
6686
+ * `possibleValues` (see {@link syncEntityFieldValues}); empty when the rows already match.
6687
+ */
6688
+ entityFieldValueSyncStatements(entityFieldID, possibleValues, allEntityFieldValues, source) {
6689
+ const statements = [];
6690
+ const existingValues = allEntityFieldValues.filter(efv => efv.EntityFieldID === entityFieldID);
6691
+ // Step 1: for any existing value that is NOT in the list of possible Values, delete it
6692
+ for (const ev of existingValues) {
6693
+ if (!possibleValues.find(v => v === ev.Value)) {
6694
+ statements.push(`DELETE FROM ${this.qs(MjCoreSchema(), 'EntityFieldValue')} WHERE ID='${ev.ID}'`);
6695
+ }
6696
+ }
6697
+ // Step 2: for any possible value that is NOT in the list of existing values, add it
6698
+ for (const v of possibleValues) {
6699
+ if (!existingValues.find((ev) => ev.Value === v)) {
6700
+ // Generate a UUID for this new EntityFieldValue record
6701
+ const newId = uuidv4();
6702
+ // add the value to the database with explicit ID. Code is NULL ("same as Value") when
6703
+ // the value is longer than the Code column; copying it overflowed that column (#2577).
6704
+ const code = ManageMetadataBase.EntityFieldValueCode(v);
6705
+ statements.push(`INSERT INTO ${this.qs(MjCoreSchema(), 'EntityFieldValue')}
6706
+ (${this.qi('ID')}, ${this.qi('EntityFieldID')}, ${this.qi('Sequence')}, ${this.qi('Value')}, ${this.qi('Code')}, ${this.qi('Source')}, ${this.qi('__mj_CreatedAt')}, ${this.qi('__mj_UpdatedAt')})
6707
+ VALUES
6708
+ ('${newId}', '${entityFieldID}', ${1 + possibleValues.indexOf(v)}, '${EscapeSQLString(v)}', ${code === null ? 'NULL' : `'${EscapeSQLString(code)}'`}, '${source}', ${this.utcNow()}, ${this.utcNow()})`);
6709
+ }
6710
+ }
6711
+ // Step 3: finally, for the existing values that are in the list of possible values, update the sequence to match
6712
+ // the order in the possible values list, and claim the row for this writer if another origin is recorded on it
6713
+ for (const v of possibleValues) {
6714
+ const ev = existingValues.find(ev => ev.Value === v);
6715
+ if (!ev) {
6716
+ continue;
6717
+ }
6718
+ const sets = [];
6719
+ // NOTE: Number() rather than a strict comparison in case the DB returns a string for Sequence.
6720
+ if (Number(ev.Sequence) !== 1 + possibleValues.indexOf(v)) {
6721
+ sets.push(`Sequence=${1 + possibleValues.indexOf(v)}`);
6722
+ }
6723
+ if (ev.Source !== source) {
6724
+ sets.push(`${this.qi('Source')}='${source}'`);
6725
+ }
6726
+ if (sets.length > 0) {
6727
+ statements.push(`UPDATE ${this.qs(MjCoreSchema(), 'EntityFieldValue')} SET ${sets.join(', ')} WHERE ID='${ev.ID}'`);
6728
+ }
6729
+ }
6730
+ return statements;
6731
+ }
6136
6732
  /**
6137
6733
  * Parses a column-level CHECK constraint into the list of values it permits, or returns null when the
6138
6734
  * constraint is not a simple value list (a range, a `LEN()` predicate, a mixed condition, and so on).
@@ -6514,21 +7110,20 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
6514
7110
  const newEntities = newEntitiesResult.recordset;
6515
7111
  if (newEntities && newEntities.length > 0) {
6516
7112
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
6517
- const transaction = await pool.beginTransaction();
6518
- // The in-run list of new entity names is process-static. Names pushed by a batch that is then
6519
- // rolled back must not survive into the next run of the same process (in-process CodeGen runs
7113
+ // Not atomic: each entity's writes commit as they run, so a failure part-way leaves the
7114
+ // entities before it in place. A re-run repairs that: the SELECT above only returns tables
7115
+ // that have no entity yet.
7116
+ // The in-run list of new entity names is process-static. Names pushed by a batch that then
7117
+ // fails must not survive into the next run of the same process (in-process CodeGen runs
6520
7118
  // many times per process), or every one of them reads as "taken" and gets a schema suffix.
6521
7119
  const newEntityNamesBefore = ManageMetadataBase.newEntityList.length;
6522
7120
  try {
6523
- // wrap in a transaction so we get all of it or none of it
6524
7121
  for (let i = 0; i < newEntities.length; ++i) {
6525
7122
  // process each of the new entities
6526
7123
  await this.createNewEntity(pool, newEntities[i], md, currentUser);
6527
7124
  }
6528
- await transaction.commit();
6529
7125
  }
6530
7126
  catch (e) {
6531
- await transaction.rollback();
6532
7127
  ManageMetadataBase.newEntityList.length = newEntityNamesBefore;
6533
7128
  throw e;
6534
7129
  }
@@ -8207,6 +8802,9 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
8207
8802
  *
8208
8803
  * Winner selection (deterministic, mirrors `EntityInfo.NameField`'s runtime
8209
8804
  * preference and the v5.41 metadata backfill):
8805
+ * 0. **Pinned** — a flagged field pinned with `AutoUpdateIsNameField=0` wins, eligible or
8806
+ * not (a virtual name field such as `MJ: Employees.FirstLast` is a legitimate pin). With
8807
+ * several pinned, the literal `Name` wins, else the first in field order (#6554).
8210
8808
  * 1. **Stability** — if exactly one currently-flagged field is still eligible, it
8211
8809
  * stays the winner regardless of what the LLM proposes. An already-valid single
8212
8810
  * name field never drifts.
@@ -8223,7 +8821,9 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
8223
8821
  * Every NON-winner with `IsNameField=1` and `AutoUpdateIsNameField=1` is CLEARED, so
8224
8822
  * historical accumulation self-heals on the next analysis pass. Fields pinned with
8225
8823
  * `AutoUpdateIsNameField=0` are never touched in either direction — the user owns
8226
- * them, and `EntityInfo.NameField`'s literal-`Name` preference arbitrates at runtime.
8824
+ * them. Because a pin always wins (step 0), an auto-flagged field beside a pin is
8825
+ * cleared rather than left as a second name field (#6554); two pins are left alone
8826
+ * and reported by the integrity check.
8227
8827
  */
8228
8828
  applyNameFieldUpdates(sqlStatements, fields, result, entity) {
8229
8829
  const nameFieldNames = result.nameFields ?? [];
@@ -8264,7 +8864,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
8264
8864
  }
8265
8865
  /**
8266
8866
  * Picks the single IsNameField winner for an entity per the rules documented on
8267
- * {@link applyNameFieldUpdates}: stable current winner → deterministic repair
8867
+ * {@link applyNameFieldUpdates}: a pinned flag → stable current winner → deterministic repair
8268
8868
  * (literal `Name`, then field order) → first eligible LLM candidate → PRESERVE an
8269
8869
  * existing type-safe flag rather than clearing it with nothing to put in its place.
8270
8870
  * Returns null only when every flagged field is actively WRONG (a PK, a non-text
@@ -8273,6 +8873,13 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
8273
8873
  * at a uniqueidentifier or a blob.
8274
8874
  */
8275
8875
  selectNameFieldWinner(fields, rankedCandidates) {
8876
+ // 0. PINNED — a user-pinned flag wins even when it is not eligible here (a virtual or
8877
+ // view-only name field). Ignoring it let the pass flag a second field the clear loop
8878
+ // then could not reconcile, leaving two name fields (#6554).
8879
+ const pinnedFlagged = fields.filter(f => f.IsNameField && !f.AutoUpdateIsNameField);
8880
+ if (pinnedFlagged.length > 0) {
8881
+ return this.preferLiteralNameField(pinnedFlagged);
8882
+ }
8276
8883
  const eligibleFlagged = fields.filter(f => f.IsNameField && this.isFieldEligibleForNameField(f));
8277
8884
  if (eligibleFlagged.length === 1) {
8278
8885
  return eligibleFlagged[0];
@@ -8567,7 +9174,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
8567
9174
  * Written as `UPDATE ... WHERE <key> IN (subquery)` rather than `UPDATE ... FROM ... JOIN`,
8568
9175
  * which is T-SQL-only. The subquery form is ANSI and runs unchanged on both platforms.
8569
9176
  */
8570
- buildSearchFlagHygieneSQL(excludeSchemas) {
9177
+ buildSearchFlagHygieneSQL(scope) {
8571
9178
  const coreSchema = MjCoreSchema();
8572
9179
  const entity = this.qs(coreSchema, 'Entity');
8573
9180
  const entityField = this.qs(coreSchema, 'EntityField');
@@ -8614,9 +9221,17 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
8614
9221
  const entityShapeFilter = `AND NOT (${shapeClauses})`;
8615
9222
  // Schema names are configuration, not literals we control: double any apostrophe rather
8616
9223
  // than interpolating it straight into the statement.
8617
- const schemaFilter = excludeSchemas.length > 0
8618
- ? `AND e.${this.qi('SchemaName')} NOT IN (${excludeSchemas.map(sc => `'${sc.replace(/'/g, "''")}'`).join(',')})`
8619
- : '';
9224
+ //
9225
+ // The filter names only what the config authored: `includeSchemas` as an IN list, the
9226
+ // authored excludes as NOT IN. Never the compiled exclude list (#6384): with
9227
+ // `includeSchemas` set, that list holds every other schema on the publisher's database, and
9228
+ // a capture replayed on a host would then touch entities in schemas this run does not own.
9229
+ const schemaList = (schemas) => schemas.map(sc => `'${sc.replace(/'/g, "''")}'`).join(',');
9230
+ const includeSchemas = scope.IncludeSchemas ?? [];
9231
+ const schemaFilter = [
9232
+ includeSchemas.length > 0 ? `AND e.${this.qi('SchemaName')} IN (${schemaList(includeSchemas)})` : '',
9233
+ scope.AuthoredExclude.length > 0 ? `AND e.${this.qi('SchemaName')} NOT IN (${schemaList(scope.AuthoredExclude)})` : '',
9234
+ ].filter(clause => clause.length > 0).join('\n ');
8620
9235
  // "This entity has nothing a user search can match." Mirrors
8621
9236
  // `EntityInfo.HasSearchFields` and the runtime screen in EntitySearchProvider.
8622
9237
  const noSearchableField = `NOT EXISTS (
@@ -8722,9 +9337,9 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
8722
9337
  * idempotent — the data converged, the log did not. So each statement is emitted only when its
8723
9338
  * own candidate probe finds work.
8724
9339
  */
8725
- async applySearchFlagHygiene(pool, excludeSchemas) {
9340
+ async applySearchFlagHygiene(pool, scope) {
8726
9341
  try {
8727
- const { seedSQL, clearSQL, seedProbeSQL, clearProbeSQL } = this.buildSearchFlagHygieneSQL(excludeSchemas);
9342
+ const { seedSQL, clearSQL, seedProbeSQL, clearProbeSQL } = this.buildSearchFlagHygieneSQL(scope);
8728
9343
  // Order matters: seeding first means an entity whose name field was just flagged is no
8729
9344
  // longer a candidate for having its AllowUserSearchAPI cleared. Reversed, the pass would
8730
9345
  // disable search on an entity it was about to make searchable.
@@ -9352,6 +9967,26 @@ WHERE
9352
9967
  * `undefined` (no execution) when nothing remains.
9353
9968
  */
9354
9969
  async logSQLBatchAndExecute(pool, statements, description, isRecurringScript = false, includeBatchSeparator = false, batchSeparator = 'GO') {
9970
+ const terminated = ManageMetadataBase.TerminateStatements(statements);
9971
+ if (terminated.length === 0)
9972
+ return undefined;
9973
+ return await this.logSQLAndExecute(pool, terminated.join('\n'), description, isRecurringScript, includeBatchSeparator, batchSeparator);
9974
+ }
9975
+ /**
9976
+ * Like {@link logSQLBatchAndExecute}, but the database applies the batch all or nothing (see
9977
+ * {@link AtomicBatchSQL}). The migration log gets the plain statements, as before: a migration
9978
+ * already runs as one unit, and a transaction wrapper there would have to survive the
9979
+ * PostgreSQL conversion.
9980
+ */
9981
+ async logSQLBatchAndExecuteAtomically(pool, statements, description) {
9982
+ const terminated = ManageMetadataBase.TerminateStatements(statements);
9983
+ if (terminated.length === 0)
9984
+ return;
9985
+ const logged = this.qsql(terminated.join('\n'));
9986
+ await SQLLogging.LogSQLAndExecute(pool, logged, description, false, false, undefined, false, ManageMetadataBase.AtomicBatchSQL(logged, DbPlatform()));
9987
+ }
9988
+ /** Each statement trimmed of trailing terminators and re-terminated with one `;`; empty ones dropped. */
9989
+ static TerminateStatements(statements) {
9355
9990
  const terminated = [];
9356
9991
  for (const s of statements) {
9357
9992
  const trimmed = TrimTrailingStatementTerminators(s ?? '');
@@ -9359,9 +9994,26 @@ WHERE
9359
9994
  continue;
9360
9995
  terminated.push(`${trimmed};`);
9361
9996
  }
9362
- if (terminated.length === 0)
9363
- return undefined;
9364
- return await this.logSQLAndExecute(pool, terminated.join('\n'), description, isRecurringScript, includeBatchSeparator, batchSeparator);
9997
+ return terminated;
9998
+ }
9999
+ /**
10000
+ * The text that makes a batch of terminated statements apply all or nothing.
10001
+ *
10002
+ * - SQL Server: `SET XACT_ABORT ON`, then an explicit transaction inside TRY/CATCH. The CATCH rolls
10003
+ * back and re-throws, so the caller sees the original error. A client-side timeout is an
10004
+ * attention signal that skips the CATCH; `XACT_ABORT` makes the server roll the transaction back
10005
+ * then, so the pooled connection is not handed to later writes with the transaction still open
10006
+ * (those writes would be undone when the connection closes). The option lasts only for this
10007
+ * call: `query()` runs the text through `sp_executesql`, and a SET there ends with it.
10008
+ * - PostgreSQL: the batch unchanged. Several statements sent in one simple query already run as
10009
+ * one implicit transaction that rolls back on any error; an explicit `BEGIN … COMMIT` there would
10010
+ * instead leave the pooled connection in an aborted transaction after a failure.
10011
+ */
10012
+ static AtomicBatchSQL(batch, platform) {
10013
+ if (platform === 'postgresql') {
10014
+ return batch;
10015
+ }
10016
+ return `SET XACT_ABORT ON;\nBEGIN TRY\nBEGIN TRANSACTION;\n${batch}\nCOMMIT TRANSACTION;\nEND TRY\nBEGIN CATCH\nIF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;\nTHROW;\nEND CATCH`;
9365
10017
  }
9366
10018
  }
9367
10019
  //# sourceMappingURL=manage-metadata.js.map