@memberjunction/codegen-lib 6.2.0-edge.1 → 6.2.0-edge.2

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 (23) hide show
  1. package/README.md +25 -23
  2. package/dist/Database/manage-metadata.d.ts +84 -5
  3. package/dist/Database/manage-metadata.d.ts.map +1 -1
  4. package/dist/Database/manage-metadata.js +304 -129
  5. package/dist/Database/manage-metadata.js.map +1 -1
  6. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
  7. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +62 -39
  8. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
  9. package/dist/Database/providers/postgresql/__tests__/LayeredBaseViewPermissions.test.d.ts +2 -0
  10. package/dist/Database/providers/postgresql/__tests__/LayeredBaseViewPermissions.test.d.ts.map +1 -0
  11. package/dist/Database/providers/postgresql/__tests__/LayeredBaseViewPermissions.test.js +72 -0
  12. package/dist/Database/providers/postgresql/__tests__/LayeredBaseViewPermissions.test.js.map +1 -0
  13. package/dist/Database/providers/postgresql/__tests__/ViewRegenDependents.test.d.ts +2 -0
  14. package/dist/Database/providers/postgresql/__tests__/ViewRegenDependents.test.d.ts.map +1 -0
  15. package/dist/Database/providers/postgresql/__tests__/ViewRegenDependents.test.js +53 -0
  16. package/dist/Database/providers/postgresql/__tests__/ViewRegenDependents.test.js.map +1 -0
  17. package/dist/Database/sql.d.ts.map +1 -1
  18. package/dist/Database/sql.js +13 -0
  19. package/dist/Database/sql.js.map +1 -1
  20. package/dist/Database/sql_codegen.d.ts.map +1 -1
  21. package/dist/Database/sql_codegen.js +5 -1
  22. package/dist/Database/sql_codegen.js.map +1 -1
  23. package/package.json +29 -29
@@ -22,7 +22,7 @@ import { CodeGenReporter } from "../Misc/codegen-reporter.js";
22
22
  import { ApplySearchableFieldsCap, DefaultPredicateFor, EntityLevelEnableBlockedReason, IsNarrativeFieldName, MAX_SEARCHABLE_FIELDS_PER_ENTITY, NAME_LIKE_FIELD_NAMES, NormalizePredicate, NormalizeSmartFieldResultShape, } from "./search-guardrails.js";
23
23
  import { MapExternalNativeTypeToMJ } from "../Misc/externalTypeMapping.js";
24
24
  import { SQLParser } from "@memberjunction/sql-parser";
25
- import { createDisplayName, generatePluralName, MJGlobal, ResolveSingleEntityResourceTarget, stripTrailingChars, UUIDsEqual } from "@memberjunction/global";
25
+ import { createDisplayName, EscapeSQLString, generatePluralName, MJGlobal, ResolveSingleEntityResourceTarget, stripTrailingChars, UUIDsEqual } from "@memberjunction/global";
26
26
  import { v4 as uuidv4, v5 as uuidv5 } from 'uuid';
27
27
  import * as fs from 'fs';
28
28
  import path from 'path';
@@ -596,6 +596,28 @@ export class ManageMetadataBase {
596
596
  ForeignKeys: Array.isArray(ve.ForeignKeys) ? ve.ForeignKeys : undefined,
597
597
  }));
598
598
  }
599
+ /**
600
+ * Schema a VirtualEntities entry resolves to when it names none. Same default as table entries.
601
+ */
602
+ resolveVirtualEntitySchema(ve) {
603
+ const schema = ve.SchemaName?.trim();
604
+ return schema && schema.length > 0 ? schema : 'dbo';
605
+ }
606
+ /**
607
+ * VirtualEntities entries that declare keys, in the table-entry shape the soft key writer consumes.
608
+ * A virtual entity stores its view name in BaseTable, so the existing SchemaName + BaseTable lookup applies.
609
+ */
610
+ virtualEntityConfigsAsTableConfigs(config) {
611
+ return this.extractVirtualEntitiesFromConfig(config)
612
+ .filter(ve => (ve.PrimaryKey?.length ?? 0) > 0 || (ve.ForeignKeys?.length ?? 0) > 0)
613
+ .map(ve => ({
614
+ SchemaName: this.resolveVirtualEntitySchema(ve),
615
+ TableName: ve.ViewName,
616
+ Description: ve.Description,
617
+ PrimaryKey: (ve.PrimaryKey ?? []).map(fieldName => ({ FieldName: fieldName })),
618
+ ForeignKeys: ve.ForeignKeys ?? [],
619
+ }));
620
+ }
599
621
  /**
600
622
  * Extracts the MaterializedBaseViews array from the additionalSchemaInfo config file.
601
623
  * Each entry declares a 1:1 base-view materialization of an existing entity (plan §4.1).
@@ -1214,58 +1236,87 @@ export class ManageMetadataBase {
1214
1236
  return { success: true, updatedCount };
1215
1237
  }
1216
1238
  /**
1217
- * Processes virtual entity configurations from the additionalSchemaInfo config.
1218
- * For each configured virtual entity, checks if it already exists and creates
1219
- * it if not. Uses the spCreateVirtualEntity stored procedure.
1220
- * Must run BEFORE manageVirtualEntities() so newly created entities get field-synced.
1239
+ * Creates the virtual entities declared in additionalSchemaInfo that do not exist yet.
1240
+ * Creation is two logged statements (Entity row with a CodeGen-generated ID, then the first key
1241
+ * column) so the CodeGen_Run capture replays on any database. Each new entity joins its schema's
1242
+ * application, gets the default permissions, and is registered in NewEntityList so pass 2 and
1243
+ * file generation include it in this same run. Must run BEFORE manageVirtualEntities().
1244
+ * An entry whose EntityName is already in use is skipped before anything is written to the capture.
1221
1245
  */
1222
- async processVirtualEntityConfig(pool, currentUser) {
1223
- const config = ManageMetadataBase.getSoftPKFKConfig();
1246
+ async processVirtualEntityConfig(pool, currentUser, md) {
1247
+ const config = ManageMetadataBase.GetSoftPKFKConfig();
1224
1248
  if (!config)
1225
- return { success: true, createdCount: 0 };
1249
+ return { success: true, createdCount: 0, createdEntityNames: [] };
1226
1250
  const virtualEntities = this.extractVirtualEntitiesFromConfig(config);
1227
1251
  if (virtualEntities.length === 0)
1228
- return { success: true, createdCount: 0 };
1229
- let createdCount = 0;
1252
+ return { success: true, createdCount: 0, createdEntityNames: [] };
1253
+ const createdEntityNames = [];
1254
+ const existingEntityNames = md.Entities.map(e => e.Name);
1230
1255
  const schema = MjCoreSchema();
1231
1256
  for (const ve of virtualEntities) {
1232
- const viewSchema = ve.SchemaName || schema;
1257
+ const viewSchema = this.resolveVirtualEntitySchema(ve);
1233
1258
  const viewName = ve.ViewName;
1234
- const entityName = ve.EntityName || this.deriveEntityNameFromView(viewName);
1235
- const pkField = ve.PrimaryKey?.[0] || 'ID';
1259
+ const configuredName = ve.EntityName || this.deriveEntityNameFromView(viewName);
1236
1260
  // Check if entity already exists for this view
1237
1261
  const existsResult = await this.runQueryWithParams(pool, `SELECT ID FROM ${this.qs(schema, 'vwEntities')} WHERE BaseView = @ViewName AND SchemaName = @SchemaName`, { 'ViewName': viewName, 'SchemaName': viewSchema });
1238
1262
  if (existsResult.recordset.length > 0) {
1239
- logStatus(` > Virtual entity "${entityName}" already exists for view [${viewSchema}].[${viewName}], skipping creation`);
1263
+ logStatus(` > Virtual entity "${configuredName}" already exists for view [${viewSchema}].[${viewName}], skipping creation`);
1240
1264
  continue;
1241
1265
  }
1242
1266
  // Verify the view actually exists in the database
1243
1267
  const viewExistsResult = await this.runQueryWithParams(pool, this.dbProvider.getViewExistsSQL(), { 'ViewName': viewName, 'SchemaName': viewSchema });
1244
1268
  if (viewExistsResult.recordset.length === 0) {
1245
- logError(` > View [${viewSchema}].[${viewName}] does not exist — skipping virtual entity creation for "${entityName}"`);
1269
+ logError(` > View [${viewSchema}].[${viewName}] does not exist — skipping virtual entity creation for "${configuredName}"`);
1246
1270
  continue;
1247
1271
  }
1248
- // Create the virtual entity via the stored procedure
1249
- try {
1250
- const createResult = await pool.executeStoredProcedure(`${this.qs(schema, 'spCreateVirtualEntity')}`, { 'Name': entityName, 'BaseView': viewName, 'SchemaName': viewSchema, 'PrimaryKeyFieldName': pkField, 'Description': ve.Description || null });
1251
- const newEntityId = createResult.recordset?.[0]?.['']
1252
- || createResult.recordset?.[0]?.ID
1253
- || createResult.recordset?.[0]?.Column0;
1254
- logStatus(` > Created virtual entity "${entityName}" (ID: ${newEntityId}) for view [${viewSchema}].[${viewName}]`);
1255
- createdCount++;
1256
- // Add virtual entity to the application for its schema and set default permissions
1257
- // (same logic as table-backed entities)
1258
- if (newEntityId) {
1259
- await this.addEntityToApplicationForSchema(pool, newEntityId, entityName, viewSchema, currentUser);
1260
- await this.addDefaultPermissionsForEntity(pool, newEntityId, entityName);
1261
- }
1272
+ const entityName = this.resolveVirtualEntityName(ve, viewSchema, existingEntityNames);
1273
+ if (!entityName) {
1274
+ logError(` > Entity name "${configuredName}" is already in use — skipping virtual entity creation for view [${viewSchema}].[${viewName}]. Set a different EntityName.`);
1275
+ continue;
1262
1276
  }
1263
- catch (err) {
1264
- const errMessage = err instanceof Error ? err.message : String(err);
1265
- logError(` > Failed to create virtual entity "${entityName}": ${errMessage}`);
1277
+ if (entityName !== configuredName) {
1278
+ logStatus(` > Entity name "${configuredName}" is already in use; using "${entityName}" for view [${viewSchema}].[${viewName}]`);
1279
+ }
1280
+ if (await this.createVirtualEntityFromConfig(pool, ve, entityName, viewSchema, currentUser)) {
1281
+ createdEntityNames.push(entityName);
1266
1282
  }
1267
1283
  }
1268
- return { success: true, createdCount };
1284
+ return { success: true, createdCount: createdEntityNames.length, createdEntityNames };
1285
+ }
1286
+ /**
1287
+ * Name for a new config-declared virtual entity, or null when its EntityName is already in use.
1288
+ * A name derived from the view gets the same collision suffix as a table-backed entity. Names are
1289
+ * compared without case, as UQ_Entity_Name does, and include the names created earlier in this run.
1290
+ */
1291
+ resolveVirtualEntityName(ve, viewSchema, existingEntityNames) {
1292
+ if (ve.EntityName) {
1293
+ return this.ResolveUniqueEntityName(ve.EntityName, viewSchema, existingEntityNames).suffix === '' ? ve.EntityName : null;
1294
+ }
1295
+ return this.ResolveUniqueEntityName(this.deriveEntityNameFromView(ve.ViewName), viewSchema, existingEntityNames).name;
1296
+ }
1297
+ /**
1298
+ * Writes the logged Entity INSERT and key seed for one config-declared virtual entity, registers it
1299
+ * in NewEntityList, adds it to its schema's application and grants the default permissions.
1300
+ * @returns true when the entity rows were written, even if the application or permission step failed
1301
+ */
1302
+ async createVirtualEntityFromConfig(pool, ve, entityName, viewSchema, currentUser) {
1303
+ const pkFields = ve.PrimaryKey && ve.PrimaryKey.length > 0 ? ve.PrimaryKey : ['ID'];
1304
+ let created = false;
1305
+ try {
1306
+ const newEntityId = this.createNewUUID();
1307
+ await this.logSQLAndExecute(pool, this.buildVirtualEntityInsertSQL(newEntityId, entityName, viewSchema, ve.ViewName, ve.Description ?? null), `SQL generated to create new virtual entity ${entityName}`);
1308
+ await this.logSQLAndExecute(pool, this.buildVirtualEntityPlaceholderPKSQL(this.createNewUUID(), newEntityId, pkFields[0], pkFields.length === 1), `SQL generated to seed primary key field ${pkFields[0]} for virtual entity ${entityName}`);
1309
+ logStatus(` > Created virtual entity "${entityName}" (ID: ${newEntityId}) for view [${viewSchema}].[${ve.ViewName}]`);
1310
+ ManageMetadataBase.NewEntityList.push(entityName);
1311
+ created = true;
1312
+ await this.addEntityToApplicationForSchema(pool, newEntityId, entityName, viewSchema, currentUser);
1313
+ await this.addDefaultPermissionsForEntity(pool, newEntityId, entityName);
1314
+ }
1315
+ catch (err) {
1316
+ const errMessage = err instanceof Error ? err.message : String(err);
1317
+ logError(` > Failed to create virtual entity "${entityName}": ${errMessage}`);
1318
+ }
1319
+ return created;
1269
1320
  }
1270
1321
  /**
1271
1322
  * Processes base-view materialization declarations from additionalSchemaInfo (plan §4.1).
@@ -2110,7 +2161,7 @@ export class ManageMetadataBase {
2110
2161
  }
2111
2162
  // Config-driven virtual entity creation — run BEFORE manageVirtualEntities
2112
2163
  // so newly created entities get their fields synced in the next step
2113
- const vecResult = await this.processVirtualEntityConfig(pool, currentUser);
2164
+ const vecResult = await this.processVirtualEntityConfig(pool, currentUser, md);
2114
2165
  if (vecResult.createdCount > 0) {
2115
2166
  logStatus(` > Created ${vecResult.createdCount} virtual entit${vecResult.createdCount === 1 ? 'y' : 'ies'} from config`);
2116
2167
  // Refresh metadata so manageVirtualEntities can find the newly-created entities
@@ -2130,6 +2181,11 @@ export class ManageMetadataBase {
2130
2181
  logError(' Error managing virtual entities');
2131
2182
  bSuccess = false;
2132
2183
  }
2184
+ // VirtualEntities keys apply after the view-column sync, so a new entity or a new view column
2185
+ // gets its configured key in this run — the same second pass external entities get below.
2186
+ if (!await this.applyConfiguredVirtualEntityKeys(pool, excludeSchemas, md)) {
2187
+ bSuccess = false;
2188
+ }
2133
2189
  // External-data-source entities: introspect the REMOTE schema and sync their EntityField rows
2134
2190
  // (the remote analogue of reading the local view's columns for a virtual entity).
2135
2191
  const eeResult = await this.manageExternalEntities(pool, currentUser);
@@ -2600,7 +2656,8 @@ export class ManageMetadataBase {
2600
2656
  const entity = md.EntityByName(virtualEntity.Name);
2601
2657
  if (entity) {
2602
2658
  const removeList = [];
2603
- const fieldsToRemove = entity.Fields.filter(f => !veFields.find((vf) => vf.FieldName === f.Name));
2659
+ // Same case-insensitive match as manageSingleVirtualEntityField, which keeps the row and fixes its casing
2660
+ const fieldsToRemove = entity.Fields.filter(f => !veFields.find((vf) => vf.FieldName.trim().toLowerCase() === f.Name.trim().toLowerCase()));
2604
2661
  for (const f of fieldsToRemove) {
2605
2662
  removeList.push(f.ID);
2606
2663
  }
@@ -2610,9 +2667,11 @@ export class ManageMetadataBase {
2610
2667
  await this.logSQLAndExecute(pool, sqlRemove, `SQL text to remove fields from entity ${virtualEntity.Name}`);
2611
2668
  bUpdated = true;
2612
2669
  }
2613
- // check to see if any of the fields in the virtual entity have Pkey attribute set. If not, we will default to the first field
2614
- // as pkey and user can change this.
2615
- const hasPkey = entity.Fields.find(f => f.IsPrimaryKey) !== undefined;
2670
+ // A key must survive the removal above; otherwise the first view column becomes the key.
2671
+ const hasPkey = this.virtualEntityHasPrimaryKey(entity.Fields, new Set(removeList));
2672
+ if (!hasPkey) {
2673
+ logStatus(` ⚠️ Virtual entity ${virtualEntity.Name} has no primary key; using first view column ${veFields[0].FieldName}. Set PrimaryKey in additionalSchemaInfo to choose the key.`);
2674
+ }
2616
2675
  // now create/update the fields that are in the view
2617
2676
  for (let i = 0; i < veFields.length; i++) {
2618
2677
  const vef = veFields[i];
@@ -2645,6 +2704,13 @@ export class ManageMetadataBase {
2645
2704
  resolvePrimaryKeyFlags(makePrimaryKey, singleColumnPrimaryKey) {
2646
2705
  return { wantPrimaryKey: makePrimaryKey, wantUnique: makePrimaryKey && singleColumnPrimaryKey };
2647
2706
  }
2707
+ /**
2708
+ * True when a key field survives the removal of view columns that no longer exist.
2709
+ * The cached field list still holds rows the sync just deleted, so they must be excluded.
2710
+ */
2711
+ virtualEntityHasPrimaryKey(fields, removedFieldIDs) {
2712
+ return fields.some(f => f.IsPrimaryKey && !removedFieldIDs.has(f.ID));
2713
+ }
2648
2714
  /**
2649
2715
  * Whether a field's PK/Unique flags need to change. In RECONCILE mode (external entities, whose
2650
2716
  * introspected PK set is authoritative across ALL fields) we sync in BOTH directions — setting the
@@ -2687,7 +2753,9 @@ export class ManageMetadataBase {
2687
2753
  // bootstrap, not authoritative) we only SET on acquisition and never clear, to avoid wiping a
2688
2754
  // legitimately-configured PK — and we avoid re-UPDATING an unchanged row every run.
2689
2755
  const pkFlagsChanged = this.primaryKeyFlagsChanged({ isPrimaryKey: field.IsPrimaryKey, isUnique: field.IsUnique }, { wantPrimaryKey, wantUnique }, makePrimaryKey, reconcilePrimaryKey);
2690
- if (pkFlagsChanged ||
2756
+ // The match above ignores case; the stored name takes the view column's exact casing.
2757
+ const nameChanged = field.Name !== veField.FieldName;
2758
+ if (pkFlagsChanged || nameChanged ||
2691
2759
  field.Type.trim().toLowerCase() !== veField.Type.trim().toLowerCase() ||
2692
2760
  field.Length !== veField.Length ||
2693
2761
  field.AllowsNull !== veField.AllowsNull ||
@@ -2698,6 +2766,7 @@ export class ManageMetadataBase {
2698
2766
  const sqlUpdate = `UPDATE
2699
2767
  ${this.qs(MjCoreSchema(), 'EntityField')}
2700
2768
  SET
2769
+ ${nameChanged ? `Name='${EscapeSQLString(veField.FieldName)}',` : ''}
2701
2770
  Sequence=${fieldSequence},
2702
2771
  Type='${veField.Type}',
2703
2772
  AllowsNull=${this.boolLit(veField.AllowsNull)},
@@ -3854,6 +3923,8 @@ export class ManageMetadataBase {
3854
3923
  * For soft PKs: Sets BOTH IsPrimaryKey=1 AND IsSoftPrimaryKey=1 (IsPrimaryKey is source of truth, IsSoftPrimaryKey protects from schema sync).
3855
3924
  * For soft FKs: Sets RelatedEntityID/RelatedEntityFieldName + IsSoftForeignKey=1 (RelatedEntityID is source of truth, IsSoftForeignKey protects from schema sync).
3856
3925
  * All UPDATE statements are logged to migration files via LogSQLAndExecute() for CI/CD traceability.
3926
+ * Covers table entries only. VirtualEntities entries are applied after the view-column sync by
3927
+ * {@link applyVirtualEntitySoftKeys}.
3857
3928
  */
3858
3929
  async applySoftPKFKConfig(pool) {
3859
3930
  // Check if additionalSchemaInfo is configured in mj.config.cjs
@@ -3872,100 +3943,11 @@ export class ManageMetadataBase {
3872
3943
  if (!config) {
3873
3944
  return true;
3874
3945
  }
3875
- let totalPKs = 0;
3876
- let totalFKs = 0;
3877
- const schema = MjCoreSchema();
3878
3946
  // Config supports two formats:
3879
3947
  // 1. Schema-as-key (template format): { "dbo": [{ "TableName": "Orders", ... }] }
3880
3948
  // 2. Flat tables array (legacy format): { "tables": [{ "SchemaName": "dbo", "TableName": "Orders", ... }] }
3881
3949
  // Both use PascalCase property names.
3882
- const tables = this.extractTablesFromConfig(config);
3883
- for (const table of tables) {
3884
- const tableSchema = table.SchemaName;
3885
- const tableName = table.TableName;
3886
- // Look up entity ID (SELECT query - no need to log to migration file)
3887
- const entityLookupSQL = `SELECT ID FROM ${this.qs(schema, 'Entity')} WHERE SchemaName = '${tableSchema}' AND BaseTable = '${tableName}'`;
3888
- const entityResult = await this.runQuery(pool, entityLookupSQL);
3889
- if (entityResult.recordset.length === 0) {
3890
- logStatus(` ⚠️ Entity not found for ${tableSchema}.${tableName} - skipping`);
3891
- continue;
3892
- }
3893
- const entityId = entityResult.recordset[0].ID;
3894
- // Process primary keys - set BOTH IsPrimaryKey = 1 AND IsSoftPrimaryKey = 1
3895
- // IsPrimaryKey is the source of truth, IsSoftPrimaryKey protects it from schema sync
3896
- const primaryKeys = table.PrimaryKey || [];
3897
- if (primaryKeys.length > 0) {
3898
- for (const pk of primaryKeys) {
3899
- const checkSQL = `SELECT ${this.qi('IsPrimaryKey')}, ${this.qi('IsSoftPrimaryKey')}
3900
- FROM ${this.qs(schema, 'EntityField')}
3901
- WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${pk.FieldName}'`;
3902
- const checkRes = await this.runQuery(pool, checkSQL);
3903
- if (checkRes.recordset.length > 0) {
3904
- const row = checkRes.recordset[0];
3905
- const isPk = row.IsPrimaryKey === true || row.IsPrimaryKey === 1 || row.IsPrimaryKey === '1';
3906
- const isSoftPk = row.IsSoftPrimaryKey === true || row.IsSoftPrimaryKey === 1 || row.IsSoftPrimaryKey === '1';
3907
- if (isPk && isSoftPk) {
3908
- continue; // Already correctly set, skip write
3909
- }
3910
- }
3911
- const sSQL = `UPDATE ${this.qs(schema, 'EntityField')}
3912
- SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()},
3913
- ${this.qi('IsPrimaryKey')} = ${this.boolLit(true)},
3914
- ${this.qi('IsSoftPrimaryKey')} = ${this.boolLit(true)}
3915
- WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${pk.FieldName}'`;
3916
- const result = await this.logSQLAndExecute(pool, sSQL, `Set soft PK for ${tableSchema}.${tableName}.${pk.FieldName}`);
3917
- if (result !== null) {
3918
- logStatus(` ✓ Set IsPrimaryKey=1, IsSoftPrimaryKey=1 for ${tableName}.${pk.FieldName}`);
3919
- totalPKs++;
3920
- }
3921
- }
3922
- }
3923
- // Process foreign keys - set RelatedEntityID, RelatedEntityFieldName, and IsSoftForeignKey = 1
3924
- const foreignKeys = table.ForeignKeys || [];
3925
- if (foreignKeys.length > 0) {
3926
- for (const fk of foreignKeys) {
3927
- const fkSchema = fk.SchemaName || tableSchema;
3928
- // Look up related entity ID (SELECT query - no need to log to migration file)
3929
- const relatedLookupSQL = `SELECT ID FROM ${this.qs(schema, 'Entity')} WHERE SchemaName = '${fkSchema}' AND BaseTable = '${fk.RelatedTable}'`;
3930
- const relatedEntityResult = await this.runQuery(pool, relatedLookupSQL);
3931
- if (relatedEntityResult.recordset.length === 0) {
3932
- logStatus(` ⚠️ Related entity not found for ${fkSchema}.${fk.RelatedTable} - skipping FK ${fk.FieldName}`);
3933
- continue;
3934
- }
3935
- const relatedEntityId = relatedEntityResult.recordset[0].ID;
3936
- const checkSQL = `SELECT ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityFieldName')}, ${this.qi('IsSoftForeignKey')}, ${this.qi('AutoUpdateRelatedEntityInfo')}
3937
- FROM ${this.qs(schema, 'EntityField')}
3938
- WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fk.FieldName}'`;
3939
- const checkRes = await this.runQuery(pool, checkSQL);
3940
- if (checkRes.recordset.length > 0) {
3941
- const row = checkRes.recordset[0];
3942
- const curRelId = String(row.RelatedEntityID ?? '').trim().toLowerCase();
3943
- const curRelField = String(row.RelatedEntityFieldName ?? '').trim().toLowerCase();
3944
- const curSoftFk = row.IsSoftForeignKey === true || row.IsSoftForeignKey === 1 || row.IsSoftForeignKey === '1';
3945
- const curAutoUpdate = row.AutoUpdateRelatedEntityInfo === true || row.AutoUpdateRelatedEntityInfo === 1 || row.AutoUpdateRelatedEntityInfo === '1';
3946
- if (curRelId === String(relatedEntityId).trim().toLowerCase() &&
3947
- curRelField === String(fk.RelatedField).trim().toLowerCase() &&
3948
- curSoftFk &&
3949
- !curAutoUpdate) {
3950
- continue; // Already correctly set, skip write
3951
- }
3952
- }
3953
- const sSQL = `UPDATE ${this.qs(schema, 'EntityField')}
3954
- SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()},
3955
- ${this.qi('RelatedEntityID')} = '${relatedEntityId}',
3956
- ${this.qi('RelatedEntityFieldName')} = '${fk.RelatedField}',
3957
- ${this.qi('IsSoftForeignKey')} = ${this.boolLit(true)},
3958
- ${this.qi('AutoUpdateRelatedEntityInfo')} = ${this.boolLit(false)}
3959
- WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fk.FieldName}'`;
3960
- const result = await this.logSQLAndExecute(pool, sSQL, `Set soft FK for ${tableSchema}.${tableName}.${fk.FieldName} → ${fk.RelatedTable}.${fk.RelatedField}`);
3961
- if (result !== null) {
3962
- logStatus(` ✓ Set soft FK for ${tableName}.${fk.FieldName} → ${fk.RelatedTable}.${fk.RelatedField}`);
3963
- totalFKs++;
3964
- }
3965
- }
3966
- }
3967
- }
3968
- logStatus(` Applied ${totalPKs} soft PK(s) and ${totalFKs} soft FK(s) from configuration`);
3950
+ await this.applySoftKeysToTables(pool, this.extractTablesFromConfig(config), false);
3969
3951
  return true;
3970
3952
  }
3971
3953
  catch (e) {
@@ -3973,6 +3955,166 @@ export class ManageMetadataBase {
3973
3955
  return false;
3974
3956
  }
3975
3957
  }
3958
+ /**
3959
+ * Applies the PrimaryKey and ForeignKeys of VirtualEntities entries. Runs after the view-column
3960
+ * sync, so it sees the fields of entities and view columns created in the same run. On a
3961
+ * composite key it also clears IsUnique, which spCreateVirtualEntity set on the first column.
3962
+ * @returns success, and the number of UPDATEs written
3963
+ */
3964
+ async applyVirtualEntitySoftKeys(pool) {
3965
+ const config = ManageMetadataBase.GetSoftPKFKConfig();
3966
+ const entries = config ? this.virtualEntityConfigsAsTableConfigs(config) : [];
3967
+ if (entries.length === 0) {
3968
+ return { success: true, writeCount: 0 };
3969
+ }
3970
+ try {
3971
+ logStatus(` Applying configured keys for ${entries.length} virtual entit${entries.length === 1 ? 'y' : 'ies'}...`);
3972
+ return { success: true, writeCount: await this.applySoftKeysToTables(pool, entries, true) };
3973
+ }
3974
+ catch (e) {
3975
+ logError(`Error applying VirtualEntities soft PK/FK configuration: ${e}`);
3976
+ return { success: false, writeCount: 0 };
3977
+ }
3978
+ }
3979
+ /**
3980
+ * Applies the VirtualEntities keys, then refreshes metadata and rebuilds relationships when a key
3981
+ * changed. Runs on every CodeGen run, right after the view-column sync.
3982
+ */
3983
+ async applyConfiguredVirtualEntityKeys(pool, excludeSchemas, md) {
3984
+ const { success, writeCount } = await this.applyVirtualEntitySoftKeys(pool);
3985
+ if (!success) {
3986
+ logError(' Error applying soft PK/FK configuration for virtual entities');
3987
+ return false;
3988
+ }
3989
+ if (writeCount === 0) {
3990
+ return true;
3991
+ }
3992
+ await md.Refresh();
3993
+ logStatus(' Managing virtual-entity relationships...');
3994
+ if (!await this.manageEntityRelationships(pool, excludeSchemas, md)) {
3995
+ logError(' Error managing virtual-entity relationships');
3996
+ return false;
3997
+ }
3998
+ return true;
3999
+ }
4000
+ /**
4001
+ * Writes the soft keys of each config entry, compare-first: a column that is already set, or that
4002
+ * does not exist, gets no UPDATE.
4003
+ * @param clearUniqueOnCompositeKey clear IsUnique on the columns of a multi-column key. Only for
4004
+ * virtual entities: no schema sync maintains their IsUnique.
4005
+ * @returns the number of UPDATEs written
4006
+ */
4007
+ async applySoftKeysToTables(pool, tables, clearUniqueOnCompositeKey) {
4008
+ let totalPKs = 0;
4009
+ let totalFKs = 0;
4010
+ for (const table of tables) {
4011
+ // Look up entity ID (SELECT query - no need to log to migration file)
4012
+ const entityLookupSQL = `SELECT ID FROM ${this.qs(MjCoreSchema(), 'Entity')} WHERE SchemaName = '${EscapeSQLString(table.SchemaName)}' AND BaseTable = '${EscapeSQLString(table.TableName)}'`;
4013
+ const entityResult = await this.runQuery(pool, entityLookupSQL);
4014
+ if (entityResult.recordset.length === 0) {
4015
+ logStatus(` ⚠️ Entity not found for ${table.SchemaName}.${table.TableName} - skipping`);
4016
+ continue;
4017
+ }
4018
+ const entityId = entityResult.recordset[0].ID;
4019
+ const primaryKeys = table.PrimaryKey || [];
4020
+ totalPKs += await this.applySoftPrimaryKeys(pool, table, entityId, clearUniqueOnCompositeKey && primaryKeys.length > 1);
4021
+ totalFKs += await this.applySoftForeignKeys(pool, table, entityId);
4022
+ }
4023
+ logStatus(` Applied ${totalPKs} soft PK(s) and ${totalFKs} soft FK(s) from configuration`);
4024
+ return totalPKs + totalFKs;
4025
+ }
4026
+ /**
4027
+ * Sets IsPrimaryKey = 1 AND IsSoftPrimaryKey = 1 on each configured key column.
4028
+ * IsPrimaryKey is the source of truth, IsSoftPrimaryKey protects it from schema sync.
4029
+ * @returns the number of UPDATEs written
4030
+ */
4031
+ async applySoftPrimaryKeys(pool, table, entityId, clearUnique) {
4032
+ const schema = MjCoreSchema();
4033
+ let written = 0;
4034
+ for (const pk of table.PrimaryKey || []) {
4035
+ const fieldName = EscapeSQLString(pk.FieldName);
4036
+ const checkSQL = `SELECT ${this.qi('IsPrimaryKey')}, ${this.qi('IsSoftPrimaryKey')}, ${this.qi('IsUnique')}
4037
+ FROM ${this.qs(schema, 'EntityField')}
4038
+ WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
4039
+ const checkRes = await this.runQuery(pool, checkSQL);
4040
+ if (checkRes.recordset.length === 0) {
4041
+ logStatus(` ⚠️ Field ${table.TableName}.${pk.FieldName} not found - skipping soft PK`);
4042
+ continue;
4043
+ }
4044
+ const row = checkRes.recordset[0];
4045
+ if (this.isFlagSet(row.IsPrimaryKey) && this.isFlagSet(row.IsSoftPrimaryKey) && !(clearUnique && this.isFlagSet(row.IsUnique))) {
4046
+ continue; // Already correctly set, skip write
4047
+ }
4048
+ const clearUniqueSQL = clearUnique ? `,
4049
+ ${this.qi('IsUnique')} = ${this.boolLit(false)}` : '';
4050
+ const sSQL = `UPDATE ${this.qs(schema, 'EntityField')}
4051
+ SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()},
4052
+ ${this.qi('IsPrimaryKey')} = ${this.boolLit(true)},
4053
+ ${this.qi('IsSoftPrimaryKey')} = ${this.boolLit(true)}${clearUniqueSQL}
4054
+ WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
4055
+ const result = await this.logSQLAndExecute(pool, sSQL, `Set soft PK for ${table.SchemaName}.${table.TableName}.${pk.FieldName}`);
4056
+ if (result !== null) {
4057
+ logStatus(` ✓ Set IsPrimaryKey=1, IsSoftPrimaryKey=1 for ${table.TableName}.${pk.FieldName}`);
4058
+ written++;
4059
+ }
4060
+ }
4061
+ return written;
4062
+ }
4063
+ /**
4064
+ * Sets RelatedEntityID, RelatedEntityFieldName and IsSoftForeignKey = 1 on each configured foreign
4065
+ * key column. RelatedEntityID is the source of truth, IsSoftForeignKey protects it from schema sync.
4066
+ * @returns the number of UPDATEs written
4067
+ */
4068
+ async applySoftForeignKeys(pool, table, entityId) {
4069
+ const schema = MjCoreSchema();
4070
+ let written = 0;
4071
+ for (const fk of table.ForeignKeys || []) {
4072
+ const fkSchema = fk.SchemaName || table.SchemaName;
4073
+ // Look up related entity ID (SELECT query - no need to log to migration file)
4074
+ const relatedLookupSQL = `SELECT ID FROM ${this.qs(schema, 'Entity')} WHERE SchemaName = '${EscapeSQLString(fkSchema)}' AND BaseTable = '${EscapeSQLString(fk.RelatedTable)}'`;
4075
+ const relatedEntityResult = await this.runQuery(pool, relatedLookupSQL);
4076
+ if (relatedEntityResult.recordset.length === 0) {
4077
+ logStatus(` ⚠️ Related entity not found for ${fkSchema}.${fk.RelatedTable} - skipping FK ${fk.FieldName}`);
4078
+ continue;
4079
+ }
4080
+ const relatedEntityId = relatedEntityResult.recordset[0].ID;
4081
+ const fieldName = EscapeSQLString(fk.FieldName);
4082
+ const checkSQL = `SELECT ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityFieldName')}, ${this.qi('IsSoftForeignKey')}, ${this.qi('AutoUpdateRelatedEntityInfo')}
4083
+ FROM ${this.qs(schema, 'EntityField')}
4084
+ WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
4085
+ const checkRes = await this.runQuery(pool, checkSQL);
4086
+ if (checkRes.recordset.length === 0) {
4087
+ logStatus(` ⚠️ Field ${table.TableName}.${fk.FieldName} not found - skipping soft FK`);
4088
+ continue;
4089
+ }
4090
+ const row = checkRes.recordset[0];
4091
+ const curRelId = String(row.RelatedEntityID ?? '').trim().toLowerCase();
4092
+ const curRelField = String(row.RelatedEntityFieldName ?? '').trim().toLowerCase();
4093
+ if (curRelId === String(relatedEntityId).trim().toLowerCase() &&
4094
+ curRelField === String(fk.RelatedField).trim().toLowerCase() &&
4095
+ this.isFlagSet(row.IsSoftForeignKey) &&
4096
+ !this.isFlagSet(row.AutoUpdateRelatedEntityInfo)) {
4097
+ continue; // Already correctly set, skip write
4098
+ }
4099
+ const sSQL = `UPDATE ${this.qs(schema, 'EntityField')}
4100
+ SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()},
4101
+ ${this.qi('RelatedEntityID')} = '${relatedEntityId}',
4102
+ ${this.qi('RelatedEntityFieldName')} = '${EscapeSQLString(fk.RelatedField)}',
4103
+ ${this.qi('IsSoftForeignKey')} = ${this.boolLit(true)},
4104
+ ${this.qi('AutoUpdateRelatedEntityInfo')} = ${this.boolLit(false)}
4105
+ WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
4106
+ const result = await this.logSQLAndExecute(pool, sSQL, `Set soft FK for ${table.SchemaName}.${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${fk.RelatedField}`);
4107
+ if (result !== null) {
4108
+ logStatus(` ✓ Set soft FK for ${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${fk.RelatedField}`);
4109
+ written++;
4110
+ }
4111
+ }
4112
+ return written;
4113
+ }
4114
+ /** True for a bit column value as the SQL Server and PostgreSQL drivers return it. */
4115
+ isFlagSet(value) {
4116
+ return value === true || value === 1 || value === '1';
4117
+ }
3976
4118
  /**
3977
4119
  * Applies soft value-list configuration from Fields[] entries in additionalSchemaInfo.json.
3978
4120
  * Runs AFTER manageEntityFieldValuesAndValidatorFunctions() so CHECK-constraint-derived
@@ -6069,6 +6211,39 @@ export class ManageMetadataBase {
6069
6211
  resolveUniqueEntityName(desiredName, schemaName, takenNames) {
6070
6212
  return this.ResolveUniqueEntityName(desiredName, schemaName, takenNames);
6071
6213
  }
6214
+ /**
6215
+ * INSERT for a config-declared virtual entity's Entity row. Logged rather than a stored-procedure
6216
+ * call so the CodeGen_Run capture replays it with the same ID on every database, exactly like
6217
+ * table-backed entities. Column set and flags match spCreateVirtualEntity, plus Description.
6218
+ */
6219
+ buildVirtualEntityInsertSQL(entityId, entityName, viewSchema, viewName, description) {
6220
+ const q = (name) => this.qi(name);
6221
+ const lit = (value) => `'${EscapeSQLString(value)}'`;
6222
+ return `INSERT INTO ${this.qs(MjCoreSchema(), 'Entity')} (
6223
+ ${q('ID')}, ${q('Name')}, ${q('Description')}, ${q('BaseTable')}, ${q('BaseView')}, ${q('SchemaName')},
6224
+ ${q('VirtualEntity')}, ${q('IncludeInAPI')}, ${q('AllowCreateAPI')}, ${q('AllowUpdateAPI')}, ${q('AllowDeleteAPI')},
6225
+ ${q('AllowRecordMerge')}, ${q('TrackRecordChanges')}, ${q('__mj_CreatedAt')}, ${q('__mj_UpdatedAt')}
6226
+ ) VALUES (
6227
+ ${this.uuidLit(entityId)}, ${lit(entityName)}, ${description ? lit(description) : 'NULL'}, ${lit(viewName)}, ${lit(viewName)}, ${lit(viewSchema)},
6228
+ ${this.boolLit(true)}, ${this.boolLit(true)}, ${this.boolLit(false)}, ${this.boolLit(false)}, ${this.boolLit(false)},
6229
+ ${this.boolLit(false)}, ${this.boolLit(false)}, ${this.utcNow()}, ${this.utcNow()}
6230
+ )`;
6231
+ }
6232
+ /**
6233
+ * Seeds the first configured key column before the view-column sync runs, so the sync sees a key
6234
+ * and does not promote the first view column. Type is a placeholder the sync replaces.
6235
+ */
6236
+ buildVirtualEntityPlaceholderPKSQL(fieldId, entityId, pkFieldName, singleColumnPrimaryKey) {
6237
+ const q = (name) => this.qi(name);
6238
+ const { wantPrimaryKey, wantUnique } = this.resolvePrimaryKeyFlags(true, singleColumnPrimaryKey);
6239
+ return `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityField')} (
6240
+ ${q('ID')}, ${q('EntityID')}, ${q('Sequence')}, ${q('Name')}, ${q('IsPrimaryKey')}, ${q('IsUnique')}, ${q('Type')},
6241
+ ${q('__mj_CreatedAt')}, ${q('__mj_UpdatedAt')}
6242
+ ) VALUES (
6243
+ ${this.uuidLit(fieldId)}, ${this.uuidLit(entityId)}, ${this.applyTimeEntityFieldSequenceSQL(entityId)}, '${EscapeSQLString(pkFieldName)}',
6244
+ ${this.boolLit(wantPrimaryKey)}, ${this.boolLit(wantUnique)}, 'int', ${this.utcNow()}, ${this.utcNow()}
6245
+ )`;
6246
+ }
6072
6247
  createNewEntityInsertSQL(newEntityUUID, newEntityName, newEntity, newEntitySuffix, newEntityDisplayName) {
6073
6248
  const newEntityDefaults = configInfo.newEntityDefaults;
6074
6249
  const newEntityDescriptionEscaped = newEntity.EntityDescription ? `'${newEntity.EntityDescription.replace(/'/g, "''")}'` : null;