@memberjunction/codegen-lib 6.3.0-edge.0 → 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.
- package/README.md +37 -1
- package/dist/Config/config.d.ts +36 -0
- package/dist/Config/config.d.ts.map +1 -1
- package/dist/Config/config.js +10 -0
- package/dist/Config/config.js.map +1 -1
- package/dist/Database/codeGenDatabaseProvider.d.ts +7 -1
- package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
- package/dist/Database/codeGenDatabaseProvider.js +23 -1
- package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
- package/dist/Database/manage-metadata.d.ts +54 -15
- package/dist/Database/manage-metadata.d.ts.map +1 -1
- package/dist/Database/manage-metadata.js +306 -144
- package/dist/Database/manage-metadata.js.map +1 -1
- package/dist/Database/organic-key-sync.d.ts +70 -0
- package/dist/Database/organic-key-sync.d.ts.map +1 -0
- package/dist/Database/organic-key-sync.js +83 -0
- package/dist/Database/organic-key-sync.js.map +1 -0
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +7 -0
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +74 -16
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
- package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js +14 -0
- package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js.map +1 -1
- package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.d.ts +2 -0
- package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.d.ts.map +1 -0
- package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.js +36 -0
- package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.js.map +1 -0
- package/dist/Database/providers/postgresql/__tests__/PostgreSQLHierarchyFunctions.test.js +5 -0
- package/dist/Database/providers/postgresql/__tests__/PostgreSQLHierarchyFunctions.test.js.map +1 -1
- package/dist/Database/providers/postgresql/__tests__/SoftPrimaryKeyIndex.test.js +6 -0
- package/dist/Database/providers/postgresql/__tests__/SoftPrimaryKeyIndex.test.js.map +1 -1
- package/dist/Database/providers/postgresql/metadataSupportObjects.js +43 -11
- package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
- package/dist/Database/providers/postgresql/viewFallback.d.ts +25 -0
- package/dist/Database/providers/postgresql/viewFallback.d.ts.map +1 -1
- package/dist/Database/providers/postgresql/viewFallback.js +101 -48
- package/dist/Database/providers/postgresql/viewFallback.js.map +1 -1
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +12 -2
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +96 -32
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
- package/dist/Database/providers/sqlserver/__tests__/BaseViewEmissionGoldenMaster.test.js +4 -3
- package/dist/Database/providers/sqlserver/__tests__/BaseViewEmissionGoldenMaster.test.js.map +1 -1
- package/dist/Database/providers/sqlserver/__tests__/SQLServerCodeGenProvider.test.js +41 -0
- package/dist/Database/providers/sqlserver/__tests__/SQLServerCodeGenProvider.test.js.map +1 -1
- package/dist/Database/providers/sqlserver/__tests__/SoftPrimaryKeyIndex.test.js +6 -0
- package/dist/Database/providers/sqlserver/__tests__/SoftPrimaryKeyIndex.test.js.map +1 -1
- package/dist/Database/sql_codegen.d.ts +74 -2
- package/dist/Database/sql_codegen.d.ts.map +1 -1
- package/dist/Database/sql_codegen.js +536 -125
- package/dist/Database/sql_codegen.js.map +1 -1
- package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts +49 -1
- package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts.map +1 -1
- package/dist/Manifest/GenerateClassRegistrationsManifest.js +392 -60
- package/dist/Manifest/GenerateClassRegistrationsManifest.js.map +1 -1
- package/dist/Misc/advanced_generation.d.ts +15 -3
- package/dist/Misc/advanced_generation.d.ts.map +1 -1
- package/dist/Misc/advanced_generation.js +50 -3
- package/dist/Misc/advanced_generation.js.map +1 -1
- package/dist/Misc/createNewUser.js +4 -4
- package/dist/Misc/createNewUser.js.map +1 -1
- package/dist/Misc/entity_subclasses_codegen.d.ts +11 -4
- package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
- package/dist/Misc/entity_subclasses_codegen.js +46 -14
- package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
- package/dist/Misc/smart-field-decision.d.ts +126 -0
- package/dist/Misc/smart-field-decision.d.ts.map +1 -0
- package/dist/Misc/smart-field-decision.js +222 -0
- package/dist/Misc/smart-field-decision.js.map +1 -0
- package/dist/Misc/system_integrity.d.ts +9 -0
- package/dist/Misc/system_integrity.d.ts.map +1 -1
- package/dist/Misc/system_integrity.js +20 -1
- package/dist/Misc/system_integrity.js.map +1 -1
- package/dist/Misc/typed_query_codegen.d.ts +22 -8
- package/dist/Misc/typed_query_codegen.d.ts.map +1 -1
- package/dist/Misc/typed_query_codegen.js +23 -2
- package/dist/Misc/typed_query_codegen.js.map +1 -1
- package/dist/Misc/validator-text.d.ts +14 -5
- package/dist/Misc/validator-text.d.ts.map +1 -1
- package/dist/Misc/validator-text.js +42 -13
- package/dist/Misc/validator-text.js.map +1 -1
- package/dist/plugins/index.d.ts +10 -0
- package/dist/plugins/index.d.ts.map +1 -1
- package/dist/plugins/index.js +22 -2
- package/dist/plugins/index.js.map +1 -1
- package/dist/runCodeGen.d.ts +6 -0
- package/dist/runCodeGen.d.ts.map +1 -1
- package/dist/runCodeGen.js +12 -3
- package/dist/runCodeGen.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +30 -29
|
@@ -31,6 +31,7 @@ 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";
|
|
35
36
|
import { BuildCatalogUniqueKeyColumnsSQL, BuildStoredUniqueKeySetsSQL, BuildUniqueKeySetSyncSQL, DiffUniqueKeySets, GroupUniqueKeyColumns } from "./unique-key-sets.js";
|
|
36
37
|
import { DecideConfigValueListAction, FieldKey, NormalizeKey, NormalizeObjectName, ParseObjectName, PlanOrganicKeyRetraction, ResolveConfigEntity, SelectUndeclaredFields, } from "./config-retraction.js";
|
|
@@ -734,9 +735,13 @@ export class ManageMetadataBase {
|
|
|
734
735
|
/**
|
|
735
736
|
* Extracts organic key configurations from the additionalSchemaInfo config file.
|
|
736
737
|
* Walks all schema-keyed table arrays and collects OrganicKeys arrays with their
|
|
737
|
-
* 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)
|
|
738
743
|
*/
|
|
739
|
-
extractOrganicKeysFromConfig(config) {
|
|
744
|
+
extractOrganicKeysFromConfig(config, warnOnDuplicates = false) {
|
|
740
745
|
const results = [];
|
|
741
746
|
for (const [key, value] of Object.entries(config)) {
|
|
742
747
|
// Skip top-level non-schema keys (ISARelationships, VirtualEntities, Entities)
|
|
@@ -771,6 +776,15 @@ export class ManageMetadataBase {
|
|
|
771
776
|
}))
|
|
772
777
|
: [],
|
|
773
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
|
+
}
|
|
774
788
|
results.push({ SchemaName: schemaName, TableName: tableConfig.TableName, OrganicKeys: organicKeys });
|
|
775
789
|
}
|
|
776
790
|
}
|
|
@@ -827,173 +841,233 @@ export class ManageMetadataBase {
|
|
|
827
841
|
* the file now owns a key it declares, which is what lets a later run retract it (#4535)
|
|
828
842
|
* 3. Upserts EntityOrganicKeyRelatedEntity records (matched on EntityOrganicKeyID + RelatedEntityID)
|
|
829
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).
|
|
830
846
|
* All SQL is executed AND logged via LogSQLAndExecute for complete CI/CD traceability.
|
|
831
847
|
* Must run AFTER entities are created.
|
|
832
848
|
*/
|
|
833
849
|
async processOrganicKeyConfig(pool) {
|
|
850
|
+
const result = { success: true, createdCount: 0, updatedCount: 0, unchangedCount: 0, failedCount: 0 };
|
|
834
851
|
const config = ManageMetadataBase.getSoftPKFKConfig();
|
|
835
852
|
if (!config)
|
|
836
|
-
return
|
|
837
|
-
const allOrganicKeys = this.extractOrganicKeysFromConfig(config);
|
|
853
|
+
return result;
|
|
854
|
+
const allOrganicKeys = this.extractOrganicKeysFromConfig(config, true);
|
|
838
855
|
if (allOrganicKeys.length === 0)
|
|
839
|
-
return
|
|
840
|
-
const
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
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);
|
|
844
861
|
for (const tableConfig of allOrganicKeys) {
|
|
845
|
-
|
|
846
|
-
const owner = await this.findOrganicKeyEntity(pool, tableConfig.SchemaName, tableConfig.TableName);
|
|
862
|
+
const owner = entities.Resolve(tableConfig.SchemaName, tableConfig.TableName);
|
|
847
863
|
if (!owner) {
|
|
848
864
|
// Every key declared on this table goes unapplied, so each one counts as a failure.
|
|
849
|
-
failedCount += tableConfig.OrganicKeys.length;
|
|
865
|
+
result.failedCount += tableConfig.OrganicKeys.length;
|
|
850
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
|
+
}
|
|
851
870
|
continue;
|
|
852
871
|
}
|
|
853
|
-
const ownerEntityId = owner.ID;
|
|
854
|
-
const ownerEntityName = owner.Name;
|
|
855
872
|
for (const okConfig of tableConfig.OrganicKeys) {
|
|
856
873
|
try {
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
if (
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
// Step 1: Create transitive views if defined
|
|
867
|
-
for (const re of okConfig.RelatedEntities) {
|
|
868
|
-
if (re.TransitiveView) {
|
|
869
|
-
const viewSchema = re.TransitiveView.SchemaName || re.SchemaName;
|
|
870
|
-
const viewFullName = `${viewSchema}.${re.TransitiveView.Name}`;
|
|
871
|
-
const viewSQL = this.dbProvider.generateCreateOrReplaceViewSQL(viewSchema, re.TransitiveView.Name, re.TransitiveView.SQL);
|
|
872
|
-
// T-SQL requires CREATE [OR ALTER] VIEW to be the ONLY statement in its batch — first as
|
|
873
|
-
// well as last — and the metadata DML logged just before it (entity-config UPDATEs, the
|
|
874
|
-
// previous key's INSERTs) has no trailing GO. requiresOwnBatch puts the provider's
|
|
875
|
-
// separator on both sides in the migration file ('' on PostgreSQL: nothing is added).
|
|
876
|
-
await this.logSQLAndExecute(pool, viewSQL, `Create transitive bridge view ${viewFullName} for organic key "${okConfig.Name}" on ${ownerEntityName}`, false, true, this.dbProvider.BatchSeparator, true);
|
|
877
|
-
// Auto-populate TransitiveObject from the view definition
|
|
878
|
-
re.TransitiveObject = viewFullName;
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
// Step 2: Upsert EntityOrganicKey (match on EntityID + Name)
|
|
882
|
-
const existingKey = await this.runQueryWithParams(pool, `SELECT ID FROM ${this.qs(schema, 'EntityOrganicKey')} WHERE EntityID = @EntityID AND Name = @Name`, { 'EntityID': ownerEntityId, 'Name': okConfig.Name });
|
|
883
|
-
let organicKeyId;
|
|
884
|
-
const matchFieldNames = okConfig.MatchFieldNames.join(',');
|
|
885
|
-
if (existingKey.recordset.length > 0) {
|
|
886
|
-
// Update existing
|
|
887
|
-
organicKeyId = existingKey.recordset[0].ID;
|
|
888
|
-
const updateSQL = `UPDATE ${this.qs(schema, 'EntityOrganicKey')} SET
|
|
889
|
-
MatchFieldNames = '${matchFieldNames}',
|
|
890
|
-
NormalizationStrategy = '${okConfig.NormalizationStrategy || 'LowerCaseTrim'}',
|
|
891
|
-
${okConfig.CustomNormalizationExpression ? `CustomNormalizationExpression = '${okConfig.CustomNormalizationExpression.replace(/'/g, "''")}',` : ''}
|
|
892
|
-
${okConfig.Description ? `Description = '${okConfig.Description.replace(/'/g, "''")}',` : ''}
|
|
893
|
-
Sequence = ${okConfig.Sequence ?? 0},
|
|
894
|
-
Status = 'Active',
|
|
895
|
-
Source = 'Config'
|
|
896
|
-
WHERE ID = '${organicKeyId}'`;
|
|
897
|
-
await this.logSQLAndExecute(pool, updateSQL, `Update organic key "${okConfig.Name}" on ${ownerEntityName}`);
|
|
898
|
-
updatedCount++;
|
|
899
|
-
logStatus(` > Organic key: Updated "${okConfig.Name}" on ${ownerEntityName}`);
|
|
900
|
-
}
|
|
901
|
-
else {
|
|
902
|
-
// Insert new — use entity-lookup subquery so the logged SQL is portable across databases
|
|
903
|
-
const ownerSubquery = this.entityIdSubquery(tableConfig.TableName, tableConfig.SchemaName);
|
|
904
|
-
const insertSQL = `INSERT INTO ${this.qs(schema, 'EntityOrganicKey')}
|
|
905
|
-
(EntityID, Name, ${okConfig.Description ? 'Description, ' : ''}MatchFieldNames, NormalizationStrategy, ${okConfig.CustomNormalizationExpression ? 'CustomNormalizationExpression, ' : ''}Sequence, Status, Source)
|
|
906
|
-
VALUES (${ownerSubquery}, '${okConfig.Name}', ${okConfig.Description ? `'${okConfig.Description.replace(/'/g, "''")}', ` : ''}'${matchFieldNames}', '${okConfig.NormalizationStrategy || 'LowerCaseTrim'}', ${okConfig.CustomNormalizationExpression ? `'${okConfig.CustomNormalizationExpression.replace(/'/g, "''")}', ` : ''}${okConfig.Sequence ?? 0}, 'Active', 'Config')`;
|
|
907
|
-
await this.logSQLAndExecute(pool, insertSQL, `Insert organic key "${okConfig.Name}" on ${ownerEntityName}`);
|
|
908
|
-
createdCount++;
|
|
909
|
-
logStatus(` > Organic key: Created "${okConfig.Name}" on ${ownerEntityName}`);
|
|
910
|
-
// Fetch the new ID
|
|
911
|
-
const newKey = await this.runQueryWithParams(pool, `SELECT ID FROM ${this.qs(schema, 'EntityOrganicKey')} WHERE EntityID = @EntityID AND Name = @Name`, { 'EntityID': ownerEntityId, 'Name': okConfig.Name });
|
|
912
|
-
organicKeyId = newKey.recordset[0].ID;
|
|
913
|
-
}
|
|
914
|
-
// Step 3: Upsert EntityOrganicKeyRelatedEntity for each related entity
|
|
915
|
-
for (const { config: reConfig, entity: relEntity } of relatedEntities) {
|
|
916
|
-
const relEntityId = relEntity.ID;
|
|
917
|
-
const relEntityName = relEntity.Name;
|
|
918
|
-
// Check if this related entity mapping already exists
|
|
919
|
-
const existingRel = await this.runQueryWithParams(pool, `SELECT ID FROM ${this.qs(schema, 'EntityOrganicKeyRelatedEntity')} WHERE EntityOrganicKeyID = @KeyID AND RelatedEntityID = @RelEntityID`, { 'KeyID': organicKeyId, 'RelEntityID': relEntityId });
|
|
920
|
-
// Build field values
|
|
921
|
-
const isDirect = reConfig.RelatedFieldNames && reConfig.RelatedFieldNames.length > 0;
|
|
922
|
-
const relFieldNames = isDirect ? reConfig.RelatedFieldNames.join(',') : null;
|
|
923
|
-
const transitiveObject = reConfig.TransitiveObject || null;
|
|
924
|
-
const transitiveMatchFields = reConfig.TransitiveMatchFieldNames ? reConfig.TransitiveMatchFieldNames.join(',') : null;
|
|
925
|
-
if (existingRel.recordset.length > 0) {
|
|
926
|
-
const relId = existingRel.recordset[0].ID;
|
|
927
|
-
const updateRelSQL = `UPDATE ${this.qs(schema, 'EntityOrganicKeyRelatedEntity')} SET
|
|
928
|
-
RelatedEntityFieldNames = ${relFieldNames ? `'${relFieldNames}'` : 'NULL'},
|
|
929
|
-
TransitiveObjectName = ${transitiveObject ? `'${transitiveObject}'` : 'NULL'},
|
|
930
|
-
TransitiveObjectMatchFieldNames = ${transitiveMatchFields ? `'${transitiveMatchFields}'` : 'NULL'},
|
|
931
|
-
TransitiveObjectOutputFieldName = ${reConfig.TransitiveOutputFieldName ? `'${reConfig.TransitiveOutputFieldName}'` : 'NULL'},
|
|
932
|
-
RelatedEntityJoinFieldName = ${reConfig.RelatedEntityJoinFieldName ? `'${reConfig.RelatedEntityJoinFieldName}'` : 'NULL'},
|
|
933
|
-
DisplayName = ${reConfig.DisplayName ? `'${reConfig.DisplayName.replace(/'/g, "''")}'` : 'NULL'},
|
|
934
|
-
DisplayLocation = '${reConfig.DisplayLocation || 'After Field Tabs'}',
|
|
935
|
-
Sequence = ${reConfig.Sequence ?? 0}
|
|
936
|
-
WHERE ID = '${relId}'`;
|
|
937
|
-
await this.logSQLAndExecute(pool, updateRelSQL, `Update organic key related entity: "${okConfig.Name}" → ${relEntityName}`);
|
|
938
|
-
}
|
|
939
|
-
else {
|
|
940
|
-
// Use subqueries for FK references so the logged SQL is portable across databases
|
|
941
|
-
const ownerSubquery = this.entityIdSubquery(tableConfig.TableName, tableConfig.SchemaName);
|
|
942
|
-
const organicKeySubquery = `(SELECT ID FROM ${this.qs(schema, 'EntityOrganicKey')} WHERE EntityID = ${ownerSubquery} AND Name = '${okConfig.Name}')`;
|
|
943
|
-
const relEntitySubquery = this.entityIdSubquery(reConfig.TableName, reConfig.SchemaName);
|
|
944
|
-
const insertRelSQL = `INSERT INTO ${this.qs(schema, 'EntityOrganicKeyRelatedEntity')}
|
|
945
|
-
(EntityOrganicKeyID, RelatedEntityID, RelatedEntityFieldNames,
|
|
946
|
-
TransitiveObjectName, TransitiveObjectMatchFieldNames, TransitiveObjectOutputFieldName, RelatedEntityJoinFieldName,
|
|
947
|
-
DisplayName, DisplayLocation, Sequence)
|
|
948
|
-
VALUES (${organicKeySubquery}, ${relEntitySubquery},
|
|
949
|
-
${relFieldNames ? `'${relFieldNames}'` : 'NULL'},
|
|
950
|
-
${transitiveObject ? `'${transitiveObject}'` : 'NULL'},
|
|
951
|
-
${transitiveMatchFields ? `'${transitiveMatchFields}'` : 'NULL'},
|
|
952
|
-
${reConfig.TransitiveOutputFieldName ? `'${reConfig.TransitiveOutputFieldName}'` : 'NULL'},
|
|
953
|
-
${reConfig.RelatedEntityJoinFieldName ? `'${reConfig.RelatedEntityJoinFieldName}'` : 'NULL'},
|
|
954
|
-
${reConfig.DisplayName ? `'${reConfig.DisplayName.replace(/'/g, "''")}'` : 'NULL'},
|
|
955
|
-
'${reConfig.DisplayLocation || 'After Field Tabs'}',
|
|
956
|
-
${reConfig.Sequence ?? 0})`;
|
|
957
|
-
await this.logSQLAndExecute(pool, insertRelSQL, `Insert organic key related entity: "${okConfig.Name}" → ${relEntityName}`);
|
|
958
|
-
}
|
|
959
|
-
logStatus(` > Organic key "${okConfig.Name}": ${existingRel.recordset.length > 0 ? 'updated' : 'created'} → ${relEntityName} (${isDirect ? 'direct' : 'transitive'})`);
|
|
960
|
-
}
|
|
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++;
|
|
961
883
|
}
|
|
962
884
|
catch (err) {
|
|
963
885
|
// Keep going so one bad key doesn't block the others — but count it: a key that failed
|
|
964
886
|
// here (bridge-view DDL the database rejected, a refused view drop, …) is missing from
|
|
965
887
|
// the database, and the run must not report success for it.
|
|
966
|
-
failedCount++;
|
|
888
|
+
result.failedCount++;
|
|
967
889
|
const errMessage = err instanceof Error ? err.message : String(err);
|
|
968
|
-
logError(` > Organic key config: Failed to process "${okConfig.Name}" on ${
|
|
890
|
+
logError(` > Organic key config: Failed to process "${okConfig.Name}" on ${owner.Name}: ${errMessage}`);
|
|
969
891
|
}
|
|
892
|
+
progress(okConfig.RelatedEntities.length);
|
|
970
893
|
}
|
|
971
894
|
}
|
|
972
|
-
|
|
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
|
+
};
|
|
973
912
|
}
|
|
974
913
|
/**
|
|
975
|
-
*
|
|
976
|
-
*
|
|
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.
|
|
977
917
|
*/
|
|
978
|
-
async
|
|
979
|
-
const
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
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';
|
|
986
1060
|
}
|
|
987
1061
|
/**
|
|
988
1062
|
* Resolves every related entity of an organic key, in config order. Logs each one that doesn't
|
|
989
1063
|
* resolve and returns `null` if any is missing, so the caller can skip the key before writing any
|
|
990
1064
|
* of it.
|
|
991
1065
|
*/
|
|
992
|
-
|
|
1066
|
+
resolveOrganicKeyRelatedEntities(entities, okConfig) {
|
|
993
1067
|
const resolved = [];
|
|
994
1068
|
let missing = 0;
|
|
995
1069
|
for (const reConfig of okConfig.RelatedEntities) {
|
|
996
|
-
const entity =
|
|
1070
|
+
const entity = entities.Resolve(reConfig.SchemaName, reConfig.TableName);
|
|
997
1071
|
if (entity) {
|
|
998
1072
|
resolved.push({ config: reConfig, entity });
|
|
999
1073
|
}
|
|
@@ -1004,6 +1078,68 @@ export class ManageMetadataBase {
|
|
|
1004
1078
|
}
|
|
1005
1079
|
return missing === 0 ? resolved : null;
|
|
1006
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
|
+
}
|
|
1007
1143
|
// ─── Retraction of declarations removed from additionalSchemaInfo (#4535) ───────────────────
|
|
1008
1144
|
/** A nullable text column as a string or null. */
|
|
1009
1145
|
optionalText(value) {
|
|
@@ -2658,8 +2794,8 @@ export class ManageMetadataBase {
|
|
|
2658
2794
|
// below: a related row the pass reshapes in place loses the bridge view it referenced.
|
|
2659
2795
|
const organicKeysBeforeConfig = await this.loadOrganicKeyStateForRetraction(pool);
|
|
2660
2796
|
const organicKeyResult = await this.processOrganicKeyConfig(pool);
|
|
2661
|
-
if (organicKeyResult.createdCount > 0 || organicKeyResult.updatedCount > 0) {
|
|
2662
|
-
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`);
|
|
2663
2799
|
}
|
|
2664
2800
|
if (!organicKeyResult.success) {
|
|
2665
2801
|
logError(` Error processing organic keys: ${organicKeyResult.failedCount} key(s) failed and were not applied — see the errors above`);
|
|
@@ -4781,7 +4917,13 @@ export class ManageMetadataBase {
|
|
|
4781
4917
|
// default is precisely the one that ends up flagged searchable with nothing searchable on
|
|
4782
4918
|
// it. Ordered after it so the model's choices, where it did run, are already applied and
|
|
4783
4919
|
// the seed only fills a genuine gap. See buildSearchFlagHygieneSQL.
|
|
4784
|
-
|
|
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
|
+
})) {
|
|
4785
4927
|
logError('Error applying search flag hygiene');
|
|
4786
4928
|
// FATAL, unlike advanced generation. This pass compares before it writes, so a failure
|
|
4787
4929
|
// means the probes could not run — and because nothing is written in that case, the pass
|
|
@@ -8660,6 +8802,9 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
8660
8802
|
*
|
|
8661
8803
|
* Winner selection (deterministic, mirrors `EntityInfo.NameField`'s runtime
|
|
8662
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).
|
|
8663
8808
|
* 1. **Stability** — if exactly one currently-flagged field is still eligible, it
|
|
8664
8809
|
* stays the winner regardless of what the LLM proposes. An already-valid single
|
|
8665
8810
|
* name field never drifts.
|
|
@@ -8676,7 +8821,9 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
8676
8821
|
* Every NON-winner with `IsNameField=1` and `AutoUpdateIsNameField=1` is CLEARED, so
|
|
8677
8822
|
* historical accumulation self-heals on the next analysis pass. Fields pinned with
|
|
8678
8823
|
* `AutoUpdateIsNameField=0` are never touched in either direction — the user owns
|
|
8679
|
-
* them,
|
|
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.
|
|
8680
8827
|
*/
|
|
8681
8828
|
applyNameFieldUpdates(sqlStatements, fields, result, entity) {
|
|
8682
8829
|
const nameFieldNames = result.nameFields ?? [];
|
|
@@ -8717,7 +8864,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
8717
8864
|
}
|
|
8718
8865
|
/**
|
|
8719
8866
|
* Picks the single IsNameField winner for an entity per the rules documented on
|
|
8720
|
-
* {@link applyNameFieldUpdates}: stable current winner → deterministic repair
|
|
8867
|
+
* {@link applyNameFieldUpdates}: a pinned flag → stable current winner → deterministic repair
|
|
8721
8868
|
* (literal `Name`, then field order) → first eligible LLM candidate → PRESERVE an
|
|
8722
8869
|
* existing type-safe flag rather than clearing it with nothing to put in its place.
|
|
8723
8870
|
* Returns null only when every flagged field is actively WRONG (a PK, a non-text
|
|
@@ -8726,6 +8873,13 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
8726
8873
|
* at a uniqueidentifier or a blob.
|
|
8727
8874
|
*/
|
|
8728
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
|
+
}
|
|
8729
8883
|
const eligibleFlagged = fields.filter(f => f.IsNameField && this.isFieldEligibleForNameField(f));
|
|
8730
8884
|
if (eligibleFlagged.length === 1) {
|
|
8731
8885
|
return eligibleFlagged[0];
|
|
@@ -9020,7 +9174,7 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
9020
9174
|
* Written as `UPDATE ... WHERE <key> IN (subquery)` rather than `UPDATE ... FROM ... JOIN`,
|
|
9021
9175
|
* which is T-SQL-only. The subquery form is ANSI and runs unchanged on both platforms.
|
|
9022
9176
|
*/
|
|
9023
|
-
buildSearchFlagHygieneSQL(
|
|
9177
|
+
buildSearchFlagHygieneSQL(scope) {
|
|
9024
9178
|
const coreSchema = MjCoreSchema();
|
|
9025
9179
|
const entity = this.qs(coreSchema, 'Entity');
|
|
9026
9180
|
const entityField = this.qs(coreSchema, 'EntityField');
|
|
@@ -9067,9 +9221,17 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
9067
9221
|
const entityShapeFilter = `AND NOT (${shapeClauses})`;
|
|
9068
9222
|
// Schema names are configuration, not literals we control: double any apostrophe rather
|
|
9069
9223
|
// than interpolating it straight into the statement.
|
|
9070
|
-
|
|
9071
|
-
|
|
9072
|
-
|
|
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 ');
|
|
9073
9235
|
// "This entity has nothing a user search can match." Mirrors
|
|
9074
9236
|
// `EntityInfo.HasSearchFields` and the runtime screen in EntitySearchProvider.
|
|
9075
9237
|
const noSearchableField = `NOT EXISTS (
|
|
@@ -9175,9 +9337,9 @@ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)
|
|
|
9175
9337
|
* idempotent — the data converged, the log did not. So each statement is emitted only when its
|
|
9176
9338
|
* own candidate probe finds work.
|
|
9177
9339
|
*/
|
|
9178
|
-
async applySearchFlagHygiene(pool,
|
|
9340
|
+
async applySearchFlagHygiene(pool, scope) {
|
|
9179
9341
|
try {
|
|
9180
|
-
const { seedSQL, clearSQL, seedProbeSQL, clearProbeSQL } = this.buildSearchFlagHygieneSQL(
|
|
9342
|
+
const { seedSQL, clearSQL, seedProbeSQL, clearProbeSQL } = this.buildSearchFlagHygieneSQL(scope);
|
|
9181
9343
|
// Order matters: seeding first means an entity whose name field was just flagged is no
|
|
9182
9344
|
// longer a candidate for having its AllowUserSearchAPI cleared. Reversed, the pass would
|
|
9183
9345
|
// disable search on an entity it was about to make searchable.
|