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

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 (79) hide show
  1. package/README.md +38 -23
  2. package/dist/Angular/angular-codegen.d.ts +15 -0
  3. package/dist/Angular/angular-codegen.d.ts.map +1 -1
  4. package/dist/Angular/angular-codegen.js +54 -13
  5. package/dist/Angular/angular-codegen.js.map +1 -1
  6. package/dist/Config/config.d.ts +15 -24
  7. package/dist/Config/config.d.ts.map +1 -1
  8. package/dist/Config/config.js +2 -5
  9. package/dist/Config/config.js.map +1 -1
  10. package/dist/Config/integrity-check-schema.d.ts +22 -0
  11. package/dist/Config/integrity-check-schema.d.ts.map +1 -0
  12. package/dist/Config/integrity-check-schema.js +18 -0
  13. package/dist/Config/integrity-check-schema.js.map +1 -0
  14. package/dist/Database/json-check-validators.d.ts +98 -0
  15. package/dist/Database/json-check-validators.d.ts.map +1 -0
  16. package/dist/Database/json-check-validators.js +196 -0
  17. package/dist/Database/json-check-validators.js.map +1 -0
  18. package/dist/Database/manage-metadata.d.ts +111 -5
  19. package/dist/Database/manage-metadata.d.ts.map +1 -1
  20. package/dist/Database/manage-metadata.js +392 -130
  21. package/dist/Database/manage-metadata.js.map +1 -1
  22. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
  23. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +62 -39
  24. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
  25. package/dist/Database/providers/postgresql/__tests__/LayeredBaseViewPermissions.test.d.ts +2 -0
  26. package/dist/Database/providers/postgresql/__tests__/LayeredBaseViewPermissions.test.d.ts.map +1 -0
  27. package/dist/Database/providers/postgresql/__tests__/LayeredBaseViewPermissions.test.js +72 -0
  28. package/dist/Database/providers/postgresql/__tests__/LayeredBaseViewPermissions.test.js.map +1 -0
  29. package/dist/Database/providers/postgresql/__tests__/ViewRegenDependents.test.d.ts +2 -0
  30. package/dist/Database/providers/postgresql/__tests__/ViewRegenDependents.test.d.ts.map +1 -0
  31. package/dist/Database/providers/postgresql/__tests__/ViewRegenDependents.test.js +53 -0
  32. package/dist/Database/providers/postgresql/__tests__/ViewRegenDependents.test.js.map +1 -0
  33. package/dist/Database/sql.d.ts.map +1 -1
  34. package/dist/Database/sql.js +13 -0
  35. package/dist/Database/sql.js.map +1 -1
  36. package/dist/Database/sql_codegen.d.ts.map +1 -1
  37. package/dist/Database/sql_codegen.js +5 -1
  38. package/dist/Database/sql_codegen.js.map +1 -1
  39. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts.map +1 -1
  40. package/dist/Manifest/GenerateClassRegistrationsManifest.js +7 -4
  41. package/dist/Manifest/GenerateClassRegistrationsManifest.js.map +1 -1
  42. package/dist/Misc/advanced_generation.d.ts +42 -0
  43. package/dist/Misc/advanced_generation.d.ts.map +1 -1
  44. package/dist/Misc/advanced_generation.js +50 -0
  45. package/dist/Misc/advanced_generation.js.map +1 -1
  46. package/dist/Misc/entity_subclasses_codegen.d.ts +50 -0
  47. package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
  48. package/dist/Misc/entity_subclasses_codegen.js +185 -68
  49. package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
  50. package/dist/Misc/graphql_server_codegen.d.ts.map +1 -1
  51. package/dist/Misc/graphql_server_codegen.js +3 -5
  52. package/dist/Misc/graphql_server_codegen.js.map +1 -1
  53. package/dist/Misc/json-type-model.d.ts +148 -0
  54. package/dist/Misc/json-type-model.d.ts.map +1 -0
  55. package/dist/Misc/json-type-model.js +421 -0
  56. package/dist/Misc/json-type-model.js.map +1 -0
  57. package/dist/Misc/json-type-rules.d.ts +90 -0
  58. package/dist/Misc/json-type-rules.d.ts.map +1 -0
  59. package/dist/Misc/json-type-rules.js +274 -0
  60. package/dist/Misc/json-type-rules.js.map +1 -0
  61. package/dist/Misc/json-type-zod.d.ts +41 -0
  62. package/dist/Misc/json-type-zod.d.ts.map +1 -0
  63. package/dist/Misc/json-type-zod.js +390 -0
  64. package/dist/Misc/json-type-zod.js.map +1 -0
  65. package/dist/Misc/runCommand.d.ts.map +1 -1
  66. package/dist/Misc/runCommand.js +13 -5
  67. package/dist/Misc/runCommand.js.map +1 -1
  68. package/dist/Misc/system_integrity.d.ts +27 -0
  69. package/dist/Misc/system_integrity.d.ts.map +1 -1
  70. package/dist/Misc/system_integrity.js +17 -0
  71. package/dist/Misc/system_integrity.js.map +1 -1
  72. package/dist/Misc/validator-text.d.ts +11 -0
  73. package/dist/Misc/validator-text.d.ts.map +1 -0
  74. package/dist/Misc/validator-text.js +15 -0
  75. package/dist/Misc/validator-text.js.map +1 -0
  76. package/dist/runCodeGen.d.ts.map +1 -1
  77. package/dist/runCodeGen.js +34 -13
  78. package/dist/runCodeGen.js.map +1 -1
  79. package/package.json +29 -29
@@ -13,16 +13,17 @@ import './providers/sqlserver/SQLServerCodeGenProvider.js';
13
13
  import { configInfo, currentWorkingDirectory, DbPlatform, GetSettingValue, MjCoreSchema, OutputDir } from '../Config/config.js';
14
14
  import { CodeNameFromString, EntityFieldInfo, EntityInfo, ExternalDataSourceReadRouter, ExtractActualDefaultValue, LogError, LogStatus, Metadata, RunQuerySQLFilterManager, SeverityType } from "@memberjunction/core";
15
15
  import { MJEntityFieldSchema } from "@memberjunction/core-entities";
16
- import { logError, LogMessage, logStatus, StartSpinner, UpdateSpinner, SucceedSpinner } from "../Misc/status_logging.js";
16
+ import { logError, LogMessage, logStatus, LogWarning, StartSpinner, UpdateSpinner, SucceedSpinner } from "../Misc/status_logging.js";
17
17
  import { SQLUtilityBase } from "./sql.js";
18
18
  import { ApplyIncludeSchemaScope } from "./schema-scope.js";
19
19
  import { BuildHealSchemaRoutineParams, GetAuthoredExcludeSchemas, SnapshotAuthoredExcludeSchemas } from "./heal-schema-params.js";
20
+ import { JSON_VALIDATOR_CATEGORY_NAME, ResolveJSONCheckValidators } from "./json-check-validators.js";
20
21
  import { AdvancedGeneration, IsPlausibleEntityName } from "../Misc/advanced_generation.js";
21
22
  import { CodeGenReporter } from "../Misc/codegen-reporter.js";
22
23
  import { ApplySearchableFieldsCap, DefaultPredicateFor, EntityLevelEnableBlockedReason, IsNarrativeFieldName, MAX_SEARCHABLE_FIELDS_PER_ENTITY, NAME_LIKE_FIELD_NAMES, NormalizePredicate, NormalizeSmartFieldResultShape, } from "./search-guardrails.js";
23
24
  import { MapExternalNativeTypeToMJ } from "../Misc/externalTypeMapping.js";
24
25
  import { SQLParser } from "@memberjunction/sql-parser";
25
- import { createDisplayName, generatePluralName, MJGlobal, ResolveSingleEntityResourceTarget, stripTrailingChars, UUIDsEqual } from "@memberjunction/global";
26
+ import { createDisplayName, EscapeSQLString, generatePluralName, MJGlobal, ResolveSingleEntityResourceTarget, stripTrailingChars, UUIDsEqual } from "@memberjunction/global";
26
27
  import { v4 as uuidv4, v5 as uuidv5 } from 'uuid';
27
28
  import * as fs from 'fs';
28
29
  import path from 'path';
@@ -469,6 +470,23 @@ export class ManageMetadataBase {
469
470
  }
470
471
  }
471
472
  static { this._generatedValidators = []; }
473
+ static { this._generatedJSONValidators = []; }
474
+ /**
475
+ * Globally scoped translations of the SQL `@CHECK` rules of opted-in JSONTypes, loaded from
476
+ * `__mj.GeneratedCode` (and extended by generation). Consumed when entity subclasses are emitted.
477
+ */
478
+ static get GeneratedJSONValidators() {
479
+ return this._generatedJSONValidators;
480
+ }
481
+ static { this._entitiesWithNewJSONValidators = []; }
482
+ /**
483
+ * Entities bound to a JSONType whose SQL `@CHECK` translation was newly generated this run. Their
484
+ * generated files must be rebuilt even though no column changed, or a full run pays for the
485
+ * translation and then skips emitting it (dirty-schema scoped emit only sees schema changes).
486
+ */
487
+ static get EntitiesWithNewJSONValidators() {
488
+ return this._entitiesWithNewJSONValidators;
489
+ }
472
490
  /**
473
491
  * Globally scoped list of validators that have been generated during the metadata management process.
474
492
  */
@@ -596,6 +614,28 @@ export class ManageMetadataBase {
596
614
  ForeignKeys: Array.isArray(ve.ForeignKeys) ? ve.ForeignKeys : undefined,
597
615
  }));
598
616
  }
617
+ /**
618
+ * Schema a VirtualEntities entry resolves to when it names none. Same default as table entries.
619
+ */
620
+ resolveVirtualEntitySchema(ve) {
621
+ const schema = ve.SchemaName?.trim();
622
+ return schema && schema.length > 0 ? schema : 'dbo';
623
+ }
624
+ /**
625
+ * VirtualEntities entries that declare keys, in the table-entry shape the soft key writer consumes.
626
+ * A virtual entity stores its view name in BaseTable, so the existing SchemaName + BaseTable lookup applies.
627
+ */
628
+ virtualEntityConfigsAsTableConfigs(config) {
629
+ return this.extractVirtualEntitiesFromConfig(config)
630
+ .filter(ve => (ve.PrimaryKey?.length ?? 0) > 0 || (ve.ForeignKeys?.length ?? 0) > 0)
631
+ .map(ve => ({
632
+ SchemaName: this.resolveVirtualEntitySchema(ve),
633
+ TableName: ve.ViewName,
634
+ Description: ve.Description,
635
+ PrimaryKey: (ve.PrimaryKey ?? []).map(fieldName => ({ FieldName: fieldName })),
636
+ ForeignKeys: ve.ForeignKeys ?? [],
637
+ }));
638
+ }
599
639
  /**
600
640
  * Extracts the MaterializedBaseViews array from the additionalSchemaInfo config file.
601
641
  * Each entry declares a 1:1 base-view materialization of an existing entity (plan §4.1).
@@ -1214,58 +1254,87 @@ export class ManageMetadataBase {
1214
1254
  return { success: true, updatedCount };
1215
1255
  }
1216
1256
  /**
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.
1257
+ * Creates the virtual entities declared in additionalSchemaInfo that do not exist yet.
1258
+ * Creation is two logged statements (Entity row with a CodeGen-generated ID, then the first key
1259
+ * column) so the CodeGen_Run capture replays on any database. Each new entity joins its schema's
1260
+ * application, gets the default permissions, and is registered in NewEntityList so pass 2 and
1261
+ * file generation include it in this same run. Must run BEFORE manageVirtualEntities().
1262
+ * An entry whose EntityName is already in use is skipped before anything is written to the capture.
1221
1263
  */
1222
- async processVirtualEntityConfig(pool, currentUser) {
1223
- const config = ManageMetadataBase.getSoftPKFKConfig();
1264
+ async processVirtualEntityConfig(pool, currentUser, md) {
1265
+ const config = ManageMetadataBase.GetSoftPKFKConfig();
1224
1266
  if (!config)
1225
- return { success: true, createdCount: 0 };
1267
+ return { success: true, createdCount: 0, createdEntityNames: [] };
1226
1268
  const virtualEntities = this.extractVirtualEntitiesFromConfig(config);
1227
1269
  if (virtualEntities.length === 0)
1228
- return { success: true, createdCount: 0 };
1229
- let createdCount = 0;
1270
+ return { success: true, createdCount: 0, createdEntityNames: [] };
1271
+ const createdEntityNames = [];
1272
+ const existingEntityNames = md.Entities.map(e => e.Name);
1230
1273
  const schema = MjCoreSchema();
1231
1274
  for (const ve of virtualEntities) {
1232
- const viewSchema = ve.SchemaName || schema;
1275
+ const viewSchema = this.resolveVirtualEntitySchema(ve);
1233
1276
  const viewName = ve.ViewName;
1234
- const entityName = ve.EntityName || this.deriveEntityNameFromView(viewName);
1235
- const pkField = ve.PrimaryKey?.[0] || 'ID';
1277
+ const configuredName = ve.EntityName || this.deriveEntityNameFromView(viewName);
1236
1278
  // Check if entity already exists for this view
1237
1279
  const existsResult = await this.runQueryWithParams(pool, `SELECT ID FROM ${this.qs(schema, 'vwEntities')} WHERE BaseView = @ViewName AND SchemaName = @SchemaName`, { 'ViewName': viewName, 'SchemaName': viewSchema });
1238
1280
  if (existsResult.recordset.length > 0) {
1239
- logStatus(` > Virtual entity "${entityName}" already exists for view [${viewSchema}].[${viewName}], skipping creation`);
1281
+ logStatus(` > Virtual entity "${configuredName}" already exists for view [${viewSchema}].[${viewName}], skipping creation`);
1240
1282
  continue;
1241
1283
  }
1242
1284
  // Verify the view actually exists in the database
1243
1285
  const viewExistsResult = await this.runQueryWithParams(pool, this.dbProvider.getViewExistsSQL(), { 'ViewName': viewName, 'SchemaName': viewSchema });
1244
1286
  if (viewExistsResult.recordset.length === 0) {
1245
- logError(` > View [${viewSchema}].[${viewName}] does not exist — skipping virtual entity creation for "${entityName}"`);
1287
+ logError(` > View [${viewSchema}].[${viewName}] does not exist — skipping virtual entity creation for "${configuredName}"`);
1246
1288
  continue;
1247
1289
  }
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
- }
1290
+ const entityName = this.resolveVirtualEntityName(ve, viewSchema, existingEntityNames);
1291
+ if (!entityName) {
1292
+ logError(` > Entity name "${configuredName}" is already in use — skipping virtual entity creation for view [${viewSchema}].[${viewName}]. Set a different EntityName.`);
1293
+ continue;
1262
1294
  }
1263
- catch (err) {
1264
- const errMessage = err instanceof Error ? err.message : String(err);
1265
- logError(` > Failed to create virtual entity "${entityName}": ${errMessage}`);
1295
+ if (entityName !== configuredName) {
1296
+ logStatus(` > Entity name "${configuredName}" is already in use; using "${entityName}" for view [${viewSchema}].[${viewName}]`);
1266
1297
  }
1298
+ if (await this.createVirtualEntityFromConfig(pool, ve, entityName, viewSchema, currentUser)) {
1299
+ createdEntityNames.push(entityName);
1300
+ }
1301
+ }
1302
+ return { success: true, createdCount: createdEntityNames.length, createdEntityNames };
1303
+ }
1304
+ /**
1305
+ * Name for a new config-declared virtual entity, or null when its EntityName is already in use.
1306
+ * A name derived from the view gets the same collision suffix as a table-backed entity. Names are
1307
+ * compared without case, as UQ_Entity_Name does, and include the names created earlier in this run.
1308
+ */
1309
+ resolveVirtualEntityName(ve, viewSchema, existingEntityNames) {
1310
+ if (ve.EntityName) {
1311
+ return this.ResolveUniqueEntityName(ve.EntityName, viewSchema, existingEntityNames).suffix === '' ? ve.EntityName : null;
1312
+ }
1313
+ return this.ResolveUniqueEntityName(this.deriveEntityNameFromView(ve.ViewName), viewSchema, existingEntityNames).name;
1314
+ }
1315
+ /**
1316
+ * Writes the logged Entity INSERT and key seed for one config-declared virtual entity, registers it
1317
+ * in NewEntityList, adds it to its schema's application and grants the default permissions.
1318
+ * @returns true when the entity rows were written, even if the application or permission step failed
1319
+ */
1320
+ async createVirtualEntityFromConfig(pool, ve, entityName, viewSchema, currentUser) {
1321
+ const pkFields = ve.PrimaryKey && ve.PrimaryKey.length > 0 ? ve.PrimaryKey : ['ID'];
1322
+ let created = false;
1323
+ try {
1324
+ const newEntityId = this.createNewUUID();
1325
+ await this.logSQLAndExecute(pool, this.buildVirtualEntityInsertSQL(newEntityId, entityName, viewSchema, ve.ViewName, ve.Description ?? null), `SQL generated to create new virtual entity ${entityName}`);
1326
+ 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}`);
1327
+ logStatus(` > Created virtual entity "${entityName}" (ID: ${newEntityId}) for view [${viewSchema}].[${ve.ViewName}]`);
1328
+ ManageMetadataBase.NewEntityList.push(entityName);
1329
+ created = true;
1330
+ await this.addEntityToApplicationForSchema(pool, newEntityId, entityName, viewSchema, currentUser);
1331
+ await this.addDefaultPermissionsForEntity(pool, newEntityId, entityName);
1332
+ }
1333
+ catch (err) {
1334
+ const errMessage = err instanceof Error ? err.message : String(err);
1335
+ logError(` > Failed to create virtual entity "${entityName}": ${errMessage}`);
1267
1336
  }
1268
- return { success: true, createdCount };
1337
+ return created;
1269
1338
  }
1270
1339
  /**
1271
1340
  * Processes base-view materialization declarations from additionalSchemaInfo (plan §4.1).
@@ -2110,7 +2179,7 @@ export class ManageMetadataBase {
2110
2179
  }
2111
2180
  // Config-driven virtual entity creation — run BEFORE manageVirtualEntities
2112
2181
  // so newly created entities get their fields synced in the next step
2113
- const vecResult = await this.processVirtualEntityConfig(pool, currentUser);
2182
+ const vecResult = await this.processVirtualEntityConfig(pool, currentUser, md);
2114
2183
  if (vecResult.createdCount > 0) {
2115
2184
  logStatus(` > Created ${vecResult.createdCount} virtual entit${vecResult.createdCount === 1 ? 'y' : 'ies'} from config`);
2116
2185
  // Refresh metadata so manageVirtualEntities can find the newly-created entities
@@ -2130,6 +2199,11 @@ export class ManageMetadataBase {
2130
2199
  logError(' Error managing virtual entities');
2131
2200
  bSuccess = false;
2132
2201
  }
2202
+ // VirtualEntities keys apply after the view-column sync, so a new entity or a new view column
2203
+ // gets its configured key in this run — the same second pass external entities get below.
2204
+ if (!await this.applyConfiguredVirtualEntityKeys(pool, excludeSchemas, md)) {
2205
+ bSuccess = false;
2206
+ }
2133
2207
  // External-data-source entities: introspect the REMOTE schema and sync their EntityField rows
2134
2208
  // (the remote analogue of reading the local view's columns for a virtual entity).
2135
2209
  const eeResult = await this.manageExternalEntities(pool, currentUser);
@@ -2600,7 +2674,8 @@ export class ManageMetadataBase {
2600
2674
  const entity = md.EntityByName(virtualEntity.Name);
2601
2675
  if (entity) {
2602
2676
  const removeList = [];
2603
- const fieldsToRemove = entity.Fields.filter(f => !veFields.find((vf) => vf.FieldName === f.Name));
2677
+ // Same case-insensitive match as manageSingleVirtualEntityField, which keeps the row and fixes its casing
2678
+ const fieldsToRemove = entity.Fields.filter(f => !veFields.find((vf) => vf.FieldName.trim().toLowerCase() === f.Name.trim().toLowerCase()));
2604
2679
  for (const f of fieldsToRemove) {
2605
2680
  removeList.push(f.ID);
2606
2681
  }
@@ -2610,9 +2685,11 @@ export class ManageMetadataBase {
2610
2685
  await this.logSQLAndExecute(pool, sqlRemove, `SQL text to remove fields from entity ${virtualEntity.Name}`);
2611
2686
  bUpdated = true;
2612
2687
  }
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;
2688
+ // A key must survive the removal above; otherwise the first view column becomes the key.
2689
+ const hasPkey = this.virtualEntityHasPrimaryKey(entity.Fields, new Set(removeList));
2690
+ if (!hasPkey) {
2691
+ logStatus(` ⚠️ Virtual entity ${virtualEntity.Name} has no primary key; using first view column ${veFields[0].FieldName}. Set PrimaryKey in additionalSchemaInfo to choose the key.`);
2692
+ }
2616
2693
  // now create/update the fields that are in the view
2617
2694
  for (let i = 0; i < veFields.length; i++) {
2618
2695
  const vef = veFields[i];
@@ -2645,6 +2722,13 @@ export class ManageMetadataBase {
2645
2722
  resolvePrimaryKeyFlags(makePrimaryKey, singleColumnPrimaryKey) {
2646
2723
  return { wantPrimaryKey: makePrimaryKey, wantUnique: makePrimaryKey && singleColumnPrimaryKey };
2647
2724
  }
2725
+ /**
2726
+ * True when a key field survives the removal of view columns that no longer exist.
2727
+ * The cached field list still holds rows the sync just deleted, so they must be excluded.
2728
+ */
2729
+ virtualEntityHasPrimaryKey(fields, removedFieldIDs) {
2730
+ return fields.some(f => f.IsPrimaryKey && !removedFieldIDs.has(f.ID));
2731
+ }
2648
2732
  /**
2649
2733
  * Whether a field's PK/Unique flags need to change. In RECONCILE mode (external entities, whose
2650
2734
  * introspected PK set is authoritative across ALL fields) we sync in BOTH directions — setting the
@@ -2687,7 +2771,9 @@ export class ManageMetadataBase {
2687
2771
  // bootstrap, not authoritative) we only SET on acquisition and never clear, to avoid wiping a
2688
2772
  // legitimately-configured PK — and we avoid re-UPDATING an unchanged row every run.
2689
2773
  const pkFlagsChanged = this.primaryKeyFlagsChanged({ isPrimaryKey: field.IsPrimaryKey, isUnique: field.IsUnique }, { wantPrimaryKey, wantUnique }, makePrimaryKey, reconcilePrimaryKey);
2690
- if (pkFlagsChanged ||
2774
+ // The match above ignores case; the stored name takes the view column's exact casing.
2775
+ const nameChanged = field.Name !== veField.FieldName;
2776
+ if (pkFlagsChanged || nameChanged ||
2691
2777
  field.Type.trim().toLowerCase() !== veField.Type.trim().toLowerCase() ||
2692
2778
  field.Length !== veField.Length ||
2693
2779
  field.AllowsNull !== veField.AllowsNull ||
@@ -2698,6 +2784,7 @@ export class ManageMetadataBase {
2698
2784
  const sqlUpdate = `UPDATE
2699
2785
  ${this.qs(MjCoreSchema(), 'EntityField')}
2700
2786
  SET
2787
+ ${nameChanged ? `Name='${EscapeSQLString(veField.FieldName)}',` : ''}
2701
2788
  Sequence=${fieldSequence},
2702
2789
  Type='${veField.Type}',
2703
2790
  AllowsNull=${this.boolLit(veField.AllowsNull)},
@@ -3854,6 +3941,8 @@ export class ManageMetadataBase {
3854
3941
  * For soft PKs: Sets BOTH IsPrimaryKey=1 AND IsSoftPrimaryKey=1 (IsPrimaryKey is source of truth, IsSoftPrimaryKey protects from schema sync).
3855
3942
  * For soft FKs: Sets RelatedEntityID/RelatedEntityFieldName + IsSoftForeignKey=1 (RelatedEntityID is source of truth, IsSoftForeignKey protects from schema sync).
3856
3943
  * All UPDATE statements are logged to migration files via LogSQLAndExecute() for CI/CD traceability.
3944
+ * Covers table entries only. VirtualEntities entries are applied after the view-column sync by
3945
+ * {@link applyVirtualEntitySoftKeys}.
3857
3946
  */
3858
3947
  async applySoftPKFKConfig(pool) {
3859
3948
  // Check if additionalSchemaInfo is configured in mj.config.cjs
@@ -3872,100 +3961,11 @@ export class ManageMetadataBase {
3872
3961
  if (!config) {
3873
3962
  return true;
3874
3963
  }
3875
- let totalPKs = 0;
3876
- let totalFKs = 0;
3877
- const schema = MjCoreSchema();
3878
3964
  // Config supports two formats:
3879
3965
  // 1. Schema-as-key (template format): { "dbo": [{ "TableName": "Orders", ... }] }
3880
3966
  // 2. Flat tables array (legacy format): { "tables": [{ "SchemaName": "dbo", "TableName": "Orders", ... }] }
3881
3967
  // 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`);
3968
+ await this.applySoftKeysToTables(pool, this.extractTablesFromConfig(config), false);
3969
3969
  return true;
3970
3970
  }
3971
3971
  catch (e) {
@@ -3973,6 +3973,166 @@ export class ManageMetadataBase {
3973
3973
  return false;
3974
3974
  }
3975
3975
  }
3976
+ /**
3977
+ * Applies the PrimaryKey and ForeignKeys of VirtualEntities entries. Runs after the view-column
3978
+ * sync, so it sees the fields of entities and view columns created in the same run. On a
3979
+ * composite key it also clears IsUnique, which spCreateVirtualEntity set on the first column.
3980
+ * @returns success, and the number of UPDATEs written
3981
+ */
3982
+ async applyVirtualEntitySoftKeys(pool) {
3983
+ const config = ManageMetadataBase.GetSoftPKFKConfig();
3984
+ const entries = config ? this.virtualEntityConfigsAsTableConfigs(config) : [];
3985
+ if (entries.length === 0) {
3986
+ return { success: true, writeCount: 0 };
3987
+ }
3988
+ try {
3989
+ logStatus(` Applying configured keys for ${entries.length} virtual entit${entries.length === 1 ? 'y' : 'ies'}...`);
3990
+ return { success: true, writeCount: await this.applySoftKeysToTables(pool, entries, true) };
3991
+ }
3992
+ catch (e) {
3993
+ logError(`Error applying VirtualEntities soft PK/FK configuration: ${e}`);
3994
+ return { success: false, writeCount: 0 };
3995
+ }
3996
+ }
3997
+ /**
3998
+ * Applies the VirtualEntities keys, then refreshes metadata and rebuilds relationships when a key
3999
+ * changed. Runs on every CodeGen run, right after the view-column sync.
4000
+ */
4001
+ async applyConfiguredVirtualEntityKeys(pool, excludeSchemas, md) {
4002
+ const { success, writeCount } = await this.applyVirtualEntitySoftKeys(pool);
4003
+ if (!success) {
4004
+ logError(' Error applying soft PK/FK configuration for virtual entities');
4005
+ return false;
4006
+ }
4007
+ if (writeCount === 0) {
4008
+ return true;
4009
+ }
4010
+ await md.Refresh();
4011
+ logStatus(' Managing virtual-entity relationships...');
4012
+ if (!await this.manageEntityRelationships(pool, excludeSchemas, md)) {
4013
+ logError(' Error managing virtual-entity relationships');
4014
+ return false;
4015
+ }
4016
+ return true;
4017
+ }
4018
+ /**
4019
+ * Writes the soft keys of each config entry, compare-first: a column that is already set, or that
4020
+ * does not exist, gets no UPDATE.
4021
+ * @param clearUniqueOnCompositeKey clear IsUnique on the columns of a multi-column key. Only for
4022
+ * virtual entities: no schema sync maintains their IsUnique.
4023
+ * @returns the number of UPDATEs written
4024
+ */
4025
+ async applySoftKeysToTables(pool, tables, clearUniqueOnCompositeKey) {
4026
+ let totalPKs = 0;
4027
+ let totalFKs = 0;
4028
+ for (const table of tables) {
4029
+ // Look up entity ID (SELECT query - no need to log to migration file)
4030
+ const entityLookupSQL = `SELECT ID FROM ${this.qs(MjCoreSchema(), 'Entity')} WHERE SchemaName = '${EscapeSQLString(table.SchemaName)}' AND BaseTable = '${EscapeSQLString(table.TableName)}'`;
4031
+ const entityResult = await this.runQuery(pool, entityLookupSQL);
4032
+ if (entityResult.recordset.length === 0) {
4033
+ logStatus(` ⚠️ Entity not found for ${table.SchemaName}.${table.TableName} - skipping`);
4034
+ continue;
4035
+ }
4036
+ const entityId = entityResult.recordset[0].ID;
4037
+ const primaryKeys = table.PrimaryKey || [];
4038
+ totalPKs += await this.applySoftPrimaryKeys(pool, table, entityId, clearUniqueOnCompositeKey && primaryKeys.length > 1);
4039
+ totalFKs += await this.applySoftForeignKeys(pool, table, entityId);
4040
+ }
4041
+ logStatus(` Applied ${totalPKs} soft PK(s) and ${totalFKs} soft FK(s) from configuration`);
4042
+ return totalPKs + totalFKs;
4043
+ }
4044
+ /**
4045
+ * Sets IsPrimaryKey = 1 AND IsSoftPrimaryKey = 1 on each configured key column.
4046
+ * IsPrimaryKey is the source of truth, IsSoftPrimaryKey protects it from schema sync.
4047
+ * @returns the number of UPDATEs written
4048
+ */
4049
+ async applySoftPrimaryKeys(pool, table, entityId, clearUnique) {
4050
+ const schema = MjCoreSchema();
4051
+ let written = 0;
4052
+ for (const pk of table.PrimaryKey || []) {
4053
+ const fieldName = EscapeSQLString(pk.FieldName);
4054
+ const checkSQL = `SELECT ${this.qi('IsPrimaryKey')}, ${this.qi('IsSoftPrimaryKey')}, ${this.qi('IsUnique')}
4055
+ FROM ${this.qs(schema, 'EntityField')}
4056
+ WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
4057
+ const checkRes = await this.runQuery(pool, checkSQL);
4058
+ if (checkRes.recordset.length === 0) {
4059
+ logStatus(` ⚠️ Field ${table.TableName}.${pk.FieldName} not found - skipping soft PK`);
4060
+ continue;
4061
+ }
4062
+ const row = checkRes.recordset[0];
4063
+ if (this.isFlagSet(row.IsPrimaryKey) && this.isFlagSet(row.IsSoftPrimaryKey) && !(clearUnique && this.isFlagSet(row.IsUnique))) {
4064
+ continue; // Already correctly set, skip write
4065
+ }
4066
+ const clearUniqueSQL = clearUnique ? `,
4067
+ ${this.qi('IsUnique')} = ${this.boolLit(false)}` : '';
4068
+ const sSQL = `UPDATE ${this.qs(schema, 'EntityField')}
4069
+ SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()},
4070
+ ${this.qi('IsPrimaryKey')} = ${this.boolLit(true)},
4071
+ ${this.qi('IsSoftPrimaryKey')} = ${this.boolLit(true)}${clearUniqueSQL}
4072
+ WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
4073
+ const result = await this.logSQLAndExecute(pool, sSQL, `Set soft PK for ${table.SchemaName}.${table.TableName}.${pk.FieldName}`);
4074
+ if (result !== null) {
4075
+ logStatus(` ✓ Set IsPrimaryKey=1, IsSoftPrimaryKey=1 for ${table.TableName}.${pk.FieldName}`);
4076
+ written++;
4077
+ }
4078
+ }
4079
+ return written;
4080
+ }
4081
+ /**
4082
+ * Sets RelatedEntityID, RelatedEntityFieldName and IsSoftForeignKey = 1 on each configured foreign
4083
+ * key column. RelatedEntityID is the source of truth, IsSoftForeignKey protects it from schema sync.
4084
+ * @returns the number of UPDATEs written
4085
+ */
4086
+ async applySoftForeignKeys(pool, table, entityId) {
4087
+ const schema = MjCoreSchema();
4088
+ let written = 0;
4089
+ for (const fk of table.ForeignKeys || []) {
4090
+ const fkSchema = fk.SchemaName || table.SchemaName;
4091
+ // Look up related entity ID (SELECT query - no need to log to migration file)
4092
+ const relatedLookupSQL = `SELECT ID FROM ${this.qs(schema, 'Entity')} WHERE SchemaName = '${EscapeSQLString(fkSchema)}' AND BaseTable = '${EscapeSQLString(fk.RelatedTable)}'`;
4093
+ const relatedEntityResult = await this.runQuery(pool, relatedLookupSQL);
4094
+ if (relatedEntityResult.recordset.length === 0) {
4095
+ logStatus(` ⚠️ Related entity not found for ${fkSchema}.${fk.RelatedTable} - skipping FK ${fk.FieldName}`);
4096
+ continue;
4097
+ }
4098
+ const relatedEntityId = relatedEntityResult.recordset[0].ID;
4099
+ const fieldName = EscapeSQLString(fk.FieldName);
4100
+ const checkSQL = `SELECT ${this.qi('RelatedEntityID')}, ${this.qi('RelatedEntityFieldName')}, ${this.qi('IsSoftForeignKey')}, ${this.qi('AutoUpdateRelatedEntityInfo')}
4101
+ FROM ${this.qs(schema, 'EntityField')}
4102
+ WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
4103
+ const checkRes = await this.runQuery(pool, checkSQL);
4104
+ if (checkRes.recordset.length === 0) {
4105
+ logStatus(` ⚠️ Field ${table.TableName}.${fk.FieldName} not found - skipping soft FK`);
4106
+ continue;
4107
+ }
4108
+ const row = checkRes.recordset[0];
4109
+ const curRelId = String(row.RelatedEntityID ?? '').trim().toLowerCase();
4110
+ const curRelField = String(row.RelatedEntityFieldName ?? '').trim().toLowerCase();
4111
+ if (curRelId === String(relatedEntityId).trim().toLowerCase() &&
4112
+ curRelField === String(fk.RelatedField).trim().toLowerCase() &&
4113
+ this.isFlagSet(row.IsSoftForeignKey) &&
4114
+ !this.isFlagSet(row.AutoUpdateRelatedEntityInfo)) {
4115
+ continue; // Already correctly set, skip write
4116
+ }
4117
+ const sSQL = `UPDATE ${this.qs(schema, 'EntityField')}
4118
+ SET ${this.qi(EntityInfo.UpdatedAtFieldName)}=${this.utcNow()},
4119
+ ${this.qi('RelatedEntityID')} = '${relatedEntityId}',
4120
+ ${this.qi('RelatedEntityFieldName')} = '${EscapeSQLString(fk.RelatedField)}',
4121
+ ${this.qi('IsSoftForeignKey')} = ${this.boolLit(true)},
4122
+ ${this.qi('AutoUpdateRelatedEntityInfo')} = ${this.boolLit(false)}
4123
+ WHERE ${this.qi('EntityID')} = '${entityId}' AND ${this.qi('Name')} = '${fieldName}'`;
4124
+ const result = await this.logSQLAndExecute(pool, sSQL, `Set soft FK for ${table.SchemaName}.${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${fk.RelatedField}`);
4125
+ if (result !== null) {
4126
+ logStatus(` ✓ Set soft FK for ${table.TableName}.${fk.FieldName} → ${fk.RelatedTable}.${fk.RelatedField}`);
4127
+ written++;
4128
+ }
4129
+ }
4130
+ return written;
4131
+ }
4132
+ /** True for a bit column value as the SQL Server and PostgreSQL drivers return it. */
4133
+ isFlagSet(value) {
4134
+ return value === true || value === 1 || value === '1';
4135
+ }
3976
4136
  /**
3977
4137
  * Applies soft value-list configuration from Fields[] entries in additionalSchemaInfo.json.
3978
4138
  * Runs AFTER manageEntityFieldValuesAndValidatorFunctions() so CHECK-constraint-derived
@@ -4837,6 +4997,8 @@ export class ManageMetadataBase {
4837
4997
  }
4838
4998
  // await the completion of all generation promises here
4839
4999
  await Promise.all(generationPromises);
5000
+ // SQL @CHECK rules on opted-in JSONTypes: same load-always / generate-when-allowed contract
5001
+ await this.manageJSONCheckValidators(pool, allEntityFields, currentUser, !skipDBUpdate);
4840
5002
  return true;
4841
5003
  }
4842
5004
  catch (e) {
@@ -4844,6 +5006,73 @@ export class ManageMetadataBase {
4844
5006
  return false;
4845
5007
  }
4846
5008
  }
5009
+ /**
5010
+ * Loads (always) and generates (only when `generateNewCode` and the `ParseCheckConstraints`
5011
+ * feature allow) the TypeScript translations of SQL `@CHECK` rules written on opted-in JSONTypes,
5012
+ * then publishes them on {@link GeneratedJSONValidators} for the entity emitter.
5013
+ *
5014
+ * Failures are logged and never fail the run: a missing translation only means that one rule is
5015
+ * not emitted, which the emitter reports.
5016
+ */
5017
+ async manageJSONCheckValidators(pool, allEntityFields, currentUser, generateNewCode) {
5018
+ try {
5019
+ const store = this.buildJSONCheckStore(pool);
5020
+ const resolved = await ResolveJSONCheckValidators({
5021
+ Fields: allEntityFields,
5022
+ GenerateNew: generateNewCode,
5023
+ Store: store,
5024
+ Translator: this.createJSONCheckTranslator(),
5025
+ CurrentUser: currentUser,
5026
+ ReportError: (message) => logError(message),
5027
+ ReportWarning: (message) => LogWarning(message),
5028
+ });
5029
+ const newTypes = new Set(resolved.filter((r) => r.WasGenerated).map((r) => r.JSONTypeName));
5030
+ const newEntities = allEntityFields.filter((f) => f.JSONType && newTypes.has(f.JSONType.trim())).map((f) => f.Entity);
5031
+ ManageMetadataBase._entitiesWithNewJSONValidators = [...new Set([...ManageMetadataBase._entitiesWithNewJSONValidators, ...newEntities])];
5032
+ const resolvedKeys = new Set(resolved.map((r) => r.Key));
5033
+ ManageMetadataBase._generatedJSONValidators = [
5034
+ ...ManageMetadataBase._generatedJSONValidators.filter((r) => !resolvedKeys.has(r.Key)),
5035
+ ...resolved,
5036
+ ];
5037
+ }
5038
+ catch (e) {
5039
+ logError(`Error resolving JSON @CHECK validators: ${e instanceof Error ? e.message : String(e)}`);
5040
+ }
5041
+ }
5042
+ /** The model-backed translator for SQL `@CHECK` rules; a seam so tests can supply a stub. */
5043
+ createJSONCheckTranslator() {
5044
+ return new AdvancedGeneration();
5045
+ }
5046
+ /** `__mj.GeneratedCode` access for the JSON-validators category. */
5047
+ buildJSONCheckStore(pool) {
5048
+ const lit = (v) => this.dialect.QuoteStringLiteral(v);
5049
+ const codes = this.qs(MjCoreSchema(), 'GeneratedCode');
5050
+ const categories = this.qs(MjCoreSchema(), 'vwGeneratedCodeCategories');
5051
+ const categoryLookup = `(SELECT ${this.qi('ID')} FROM ${categories} WHERE ${this.qi('Name')}=${lit(JSON_VALIDATOR_CATEGORY_NAME)})`;
5052
+ return {
5053
+ LoadCached: async () => {
5054
+ const sql = `SELECT ${this.qi('ID')}, ${this.qi('Source')}, ${this.qi('Name')}, ${this.qi('Code')}, ${this.qi('Description')} FROM ${codes} WHERE ${this.qi('CategoryID')} = ${categoryLookup} AND ${this.qi('Status')}=${lit('Approved')}`;
5055
+ const result = await this.runQuery(pool, sql);
5056
+ return result.recordset.map((r) => ({
5057
+ ID: String(r.ID), Source: String(r.Source), Name: String(r.Name), Code: String(r.Code), Description: r.Description == null ? null : String(r.Description),
5058
+ }));
5059
+ },
5060
+ Persist: async (entry) => {
5061
+ const categoryRows = (await this.runQuery(pool, `SELECT ${this.qi('ID')} FROM ${categories} WHERE ${this.qi('Name')}=${lit(JSON_VALIDATOR_CATEGORY_NAME)}`)).recordset;
5062
+ if (categoryRows.length === 0) {
5063
+ LogWarning(`GeneratedCode category '${JSON_VALIDATOR_CATEGORY_NAME}' does not exist in this database (run 'mj sync push' for metadata/generated-code-categories); the validator generated for '${entry.Key}' is used for this run only and will be regenerated next time`);
5064
+ return;
5065
+ }
5066
+ entry.GeneratedCodeID = uuidv4();
5067
+ // Scoped to Approved exactly like LoadCached: otherwise a non-Approved row with this key makes
5068
+ // every run regenerate (LoadCached misses it) and then skip the insert (this check hits it).
5069
+ const checkQuery = `SELECT 1 FROM ${codes} WHERE ${this.qi('CategoryID')} = ${categoryLookup} AND ${this.qi('Source')} = ${lit(entry.Key)} AND ${this.qi('Status')}=${lit('Approved')}`;
5070
+ const insertSQL = `INSERT INTO ${codes} (${['ID', 'CategoryID', 'GeneratedByModelID', 'GeneratedAt', 'Language', 'Status', 'Source', 'Code', 'Description', 'Name'].map((c) => this.qi(c)).join(', ')})
5071
+ VALUES (${lit(entry.GeneratedCodeID)}, ${categoryLookup}, ${lit(entry.AIModelID)}, ${this.utcNow()}, ${lit('TypeScript')}, ${lit('Approved')}, ${lit(entry.Key)}, ${lit(entry.FunctionText)}, ${lit(entry.FunctionDescription)}, ${lit(entry.FunctionName)})`;
5072
+ await this.logSQLAndExecute(pool, `${this.dbProvider.conditionalInsertSQL(checkQuery, insertSQL)};`, `Generated JSON @CHECK validator ${entry.Key}`);
5073
+ },
5074
+ };
5075
+ }
4847
5076
  /**
4848
5077
  * This method will load all generated code from the database - this is intended to be used when you are bypassing managing the metadata.
4849
5078
  * @param pool
@@ -6069,6 +6298,39 @@ export class ManageMetadataBase {
6069
6298
  resolveUniqueEntityName(desiredName, schemaName, takenNames) {
6070
6299
  return this.ResolveUniqueEntityName(desiredName, schemaName, takenNames);
6071
6300
  }
6301
+ /**
6302
+ * INSERT for a config-declared virtual entity's Entity row. Logged rather than a stored-procedure
6303
+ * call so the CodeGen_Run capture replays it with the same ID on every database, exactly like
6304
+ * table-backed entities. Column set and flags match spCreateVirtualEntity, plus Description.
6305
+ */
6306
+ buildVirtualEntityInsertSQL(entityId, entityName, viewSchema, viewName, description) {
6307
+ const q = (name) => this.qi(name);
6308
+ const lit = (value) => `'${EscapeSQLString(value)}'`;
6309
+ return `INSERT INTO ${this.qs(MjCoreSchema(), 'Entity')} (
6310
+ ${q('ID')}, ${q('Name')}, ${q('Description')}, ${q('BaseTable')}, ${q('BaseView')}, ${q('SchemaName')},
6311
+ ${q('VirtualEntity')}, ${q('IncludeInAPI')}, ${q('AllowCreateAPI')}, ${q('AllowUpdateAPI')}, ${q('AllowDeleteAPI')},
6312
+ ${q('AllowRecordMerge')}, ${q('TrackRecordChanges')}, ${q('__mj_CreatedAt')}, ${q('__mj_UpdatedAt')}
6313
+ ) VALUES (
6314
+ ${this.uuidLit(entityId)}, ${lit(entityName)}, ${description ? lit(description) : 'NULL'}, ${lit(viewName)}, ${lit(viewName)}, ${lit(viewSchema)},
6315
+ ${this.boolLit(true)}, ${this.boolLit(true)}, ${this.boolLit(false)}, ${this.boolLit(false)}, ${this.boolLit(false)},
6316
+ ${this.boolLit(false)}, ${this.boolLit(false)}, ${this.utcNow()}, ${this.utcNow()}
6317
+ )`;
6318
+ }
6319
+ /**
6320
+ * Seeds the first configured key column before the view-column sync runs, so the sync sees a key
6321
+ * and does not promote the first view column. Type is a placeholder the sync replaces.
6322
+ */
6323
+ buildVirtualEntityPlaceholderPKSQL(fieldId, entityId, pkFieldName, singleColumnPrimaryKey) {
6324
+ const q = (name) => this.qi(name);
6325
+ const { wantPrimaryKey, wantUnique } = this.resolvePrimaryKeyFlags(true, singleColumnPrimaryKey);
6326
+ return `INSERT INTO ${this.qs(MjCoreSchema(), 'EntityField')} (
6327
+ ${q('ID')}, ${q('EntityID')}, ${q('Sequence')}, ${q('Name')}, ${q('IsPrimaryKey')}, ${q('IsUnique')}, ${q('Type')},
6328
+ ${q('__mj_CreatedAt')}, ${q('__mj_UpdatedAt')}
6329
+ ) VALUES (
6330
+ ${this.uuidLit(fieldId)}, ${this.uuidLit(entityId)}, ${this.applyTimeEntityFieldSequenceSQL(entityId)}, '${EscapeSQLString(pkFieldName)}',
6331
+ ${this.boolLit(wantPrimaryKey)}, ${this.boolLit(wantUnique)}, 'int', ${this.utcNow()}, ${this.utcNow()}
6332
+ )`;
6333
+ }
6072
6334
  createNewEntityInsertSQL(newEntityUUID, newEntityName, newEntity, newEntitySuffix, newEntityDisplayName) {
6073
6335
  const newEntityDefaults = configInfo.newEntityDefaults;
6074
6336
  const newEntityDescriptionEscaped = newEntity.EntityDescription ? `'${newEntity.EntityDescription.replace(/'/g, "''")}'` : null;