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

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 (70) hide show
  1. package/README.md +7 -0
  2. package/dist/Angular/angular-codegen.d.ts.map +1 -1
  3. package/dist/Angular/angular-codegen.js +2 -0
  4. package/dist/Angular/angular-codegen.js.map +1 -1
  5. package/dist/Config/config.d.ts +162 -0
  6. package/dist/Config/config.d.ts.map +1 -1
  7. package/dist/Config/config.js +81 -2
  8. package/dist/Config/config.js.map +1 -1
  9. package/dist/Database/codeGenDatabaseProvider.d.ts +205 -6
  10. package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
  11. package/dist/Database/codeGenDatabaseProvider.js +367 -5
  12. package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
  13. package/dist/Database/heal-schema-params.d.ts +7 -0
  14. package/dist/Database/heal-schema-params.d.ts.map +1 -1
  15. package/dist/Database/heal-schema-params.js +5 -0
  16. package/dist/Database/heal-schema-params.js.map +1 -1
  17. package/dist/Database/manage-metadata.d.ts +290 -7
  18. package/dist/Database/manage-metadata.d.ts.map +1 -1
  19. package/dist/Database/manage-metadata.js +737 -67
  20. package/dist/Database/manage-metadata.js.map +1 -1
  21. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +61 -8
  22. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
  23. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +238 -48
  24. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
  25. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.d.ts +2 -0
  26. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.d.ts.map +1 -0
  27. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js +127 -0
  28. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js.map +1 -0
  29. package/dist/Database/providers/postgresql/metadataSupportObjects.js +200 -8
  30. package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
  31. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +63 -13
  32. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
  33. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +204 -72
  34. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
  35. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.d.ts +2 -0
  36. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.d.ts.map +1 -0
  37. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js +141 -0
  38. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js.map +1 -0
  39. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts +47 -0
  40. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts.map +1 -0
  41. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js +167 -0
  42. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js.map +1 -0
  43. package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts +31 -0
  44. package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts.map +1 -0
  45. package/dist/Database/providers/sqlserver/sqlServerScriptText.js +116 -0
  46. package/dist/Database/providers/sqlserver/sqlServerScriptText.js.map +1 -0
  47. package/dist/Database/sql.d.ts +13 -0
  48. package/dist/Database/sql.d.ts.map +1 -1
  49. package/dist/Database/sql.js +39 -8
  50. package/dist/Database/sql.js.map +1 -1
  51. package/dist/Database/sql_codegen.d.ts +176 -4
  52. package/dist/Database/sql_codegen.d.ts.map +1 -1
  53. package/dist/Database/sql_codegen.js +676 -37
  54. package/dist/Database/sql_codegen.js.map +1 -1
  55. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts +9 -0
  56. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts.map +1 -1
  57. package/dist/Manifest/GenerateClassRegistrationsManifest.js +28 -7
  58. package/dist/Manifest/GenerateClassRegistrationsManifest.js.map +1 -1
  59. package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
  60. package/dist/Misc/entity_subclasses_codegen.js +18 -2
  61. package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
  62. package/dist/Misc/system_integrity.d.ts +48 -0
  63. package/dist/Misc/system_integrity.d.ts.map +1 -1
  64. package/dist/Misc/system_integrity.js +151 -75
  65. package/dist/Misc/system_integrity.js.map +1 -1
  66. package/dist/runCodeGen.d.ts +35 -3
  67. package/dist/runCodeGen.d.ts.map +1 -1
  68. package/dist/runCodeGen.js +135 -45
  69. package/dist/runCodeGen.js.map +1 -1
  70. package/package.json +29 -29
@@ -1,9 +1,9 @@
1
- import { EntityInfo, Metadata, ShouldJoinRecordGeoCodes, HasNativeLatLngFields, NativeLatitudeField, NativeLongitudeField, ListEmbeddedGeoSpecs } from '@memberjunction/core';
1
+ import { EntityInfo, IsValidSQLIdentifier, Metadata, ShouldJoinRecordGeoCodes, HasNativeLatLngFields, NativeLatitudeField, NativeLongitudeField, ListEmbeddedGeoSpecs } from '@memberjunction/core';
2
2
  import { logError, logStatus, LogWarning, StartSpinner, UpdateSpinner, SucceedSpinner, FailSpinner } from '../Misc/status_logging.js';
3
3
  import * as fs from 'fs';
4
4
  import path from 'path';
5
5
  import { SQLUtilityBase } from './sql.js';
6
- import { CodeGenDatabaseProvider } from './codeGenDatabaseProvider.js';
6
+ import { CodeGenDatabaseProvider, OrderAlternateBaseViewsTopologically } from './codeGenDatabaseProvider.js';
7
7
  import { AutoIndexForeignKeys, AutoIndexSoftPrimaryKeys, configInfo, CustomSqlScripts, mjCoreSchema } from '../Config/config.js';
8
8
  import { EntityInCustomBaseViewRefreshScope, ShouldEmitCascadeForRelatedEntity } from './schema-filters.js';
9
9
  import { ManageMetadataBase } from './manage-metadata.js';
@@ -31,6 +31,106 @@ export function EntitiesNotInExcludedSchemas(entities, excludeSchemas) {
31
31
  export function entitiesNotInExcludedSchemas(entities, excludeSchemas) {
32
32
  return EntitiesNotInExcludedSchemas(entities, excludeSchemas);
33
33
  }
34
+ function stripSQLCommentsAndStringsForAudit(sql) {
35
+ return sql
36
+ .replace(/--[^\r\n]*/g, ' ')
37
+ .replace(/\/\*[\s\S]*?\*\//g, ' ')
38
+ .replace(/'(?:''|[^'])*'/g, "''");
39
+ }
40
+ function escapeRegExpForAudit(s) {
41
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
42
+ }
43
+ function checkAlternateViewExpectedDependency(input) {
44
+ const alt = input.alternateView;
45
+ const expectedSchema = alt.ParentView ? alt.ParentView.EffectiveSchemaName : input.entitySchemaName;
46
+ const expectedObject = alt.ParentView ? alt.ParentView.ViewName : input.baseViewName;
47
+ if (input.dependencies.length > 0) {
48
+ return input.dependencies.some((d) => d.ReferencedObject.toLowerCase() === expectedObject.toLowerCase() &&
49
+ (!d.ReferencedSchema || d.ReferencedSchema.toLowerCase() === expectedSchema.toLowerCase()));
50
+ }
51
+ if (!input.viewDefinition) {
52
+ return false;
53
+ }
54
+ const stripped = stripSQLCommentsAndStringsForAudit(input.viewDefinition);
55
+ const identBoundary = new RegExp(`(?:^|[^A-Za-z0-9_])[\\[""]?${escapeRegExpForAudit(expectedObject)}[\\]""]?(?=$|[^A-Za-z0-9_])`, 'i');
56
+ return identBoundary.test(stripped);
57
+ }
58
+ function findClockExpressionsInViewDefinition(viewDefinition) {
59
+ if (!viewDefinition) {
60
+ return [];
61
+ }
62
+ const stripped = stripSQLCommentsAndStringsForAudit(viewDefinition);
63
+ const clockMatches = new Set();
64
+ const fnCallRegex = /\b(GETDATE|GETUTCDATE|SYSDATETIME|SYSDATETIMEOFFSET|SYSUTCDATETIME|NOW|CLOCK_TIMESTAMP|STATEMENT_TIMESTAMP|TRANSACTION_TIMESTAMP)\s*\(/gi;
65
+ let m;
66
+ while ((m = fnCallRegex.exec(stripped)) !== null) {
67
+ clockMatches.add(m[1].toUpperCase() + '()');
68
+ }
69
+ const kwClockRegex = /\b(CURRENT_TIMESTAMP|LOCALTIMESTAMP|CURRENT_DATE|CURRENT_TIME)\b/gi;
70
+ while ((m = kwClockRegex.exec(stripped)) !== null) {
71
+ clockMatches.add(m[1].toUpperCase());
72
+ }
73
+ return [...clockMatches];
74
+ }
75
+ function isEntityHierarchyFunction(objectName) {
76
+ return /^fn_?[a-z0-9_]+_get_(?:root_id|hierarchy_meta|descendants|ancestors)$/i.test(objectName);
77
+ }
78
+ function findExternalDependenciesForDefaultCache(input) {
79
+ if (input.dependencies.length === 0) {
80
+ return [];
81
+ }
82
+ const allowedRelations = new Set([
83
+ `${input.entitySchemaName}.${input.baseViewName}`.toLowerCase(),
84
+ ...input.registeredAlternateViewNames,
85
+ ]);
86
+ const externalRelations = [];
87
+ for (const dep of input.dependencies) {
88
+ const depType = (dep.ReferencedType ?? '').toUpperCase();
89
+ if (depType.includes('FUNCTION') && isEntityHierarchyFunction(dep.ReferencedObject)) {
90
+ continue;
91
+ }
92
+ const depSchema = dep.ReferencedSchema || input.entitySchemaName;
93
+ const depKey = `${depSchema}.${dep.ReferencedObject}`.toLowerCase();
94
+ if (!allowedRelations.has(depKey) && !externalRelations.includes(`${depSchema}.${dep.ReferencedObject}`)) {
95
+ externalRelations.push(`${depSchema}.${dep.ReferencedObject}`);
96
+ }
97
+ }
98
+ return externalRelations;
99
+ }
100
+ /**
101
+ * Pure parity and safety evaluator for a registered alternate base view (Phase 4.3).
102
+ */
103
+ export function EvaluateAlternateBaseViewParityAndSafety(input) {
104
+ const warnings = [];
105
+ const alt = input.alternateView;
106
+ const qualifiedAlt = `${alt.EffectiveSchemaName}.${alt.ViewName}`;
107
+ if (!input.viewExists) {
108
+ warnings.push(`[AlternateBaseView] Entity '${input.entityName}' alternate view '${alt.Name}' (${qualifiedAlt}) does not exist in the database.`);
109
+ return warnings;
110
+ }
111
+ const altColSet = new Set(input.viewColumns.map((c) => c.toLowerCase()));
112
+ const missingCols = input.baseViewColumns.filter((c) => !altColSet.has(c.toLowerCase()));
113
+ if (missingCols.length > 0) {
114
+ warnings.push(`[AlternateBaseView] Entity '${input.entityName}' alternate view '${alt.Name}' (${qualifiedAlt}) is missing column(s) from BaseView '${input.baseViewName}': ${missingCols.join(', ')}. Alternate base views must project the exact column set of BaseView (D10).`);
115
+ }
116
+ if (!checkAlternateViewExpectedDependency(input)) {
117
+ const expectedSchema = alt.ParentView ? alt.ParentView.EffectiveSchemaName : input.entitySchemaName;
118
+ const expectedObject = alt.ParentView ? alt.ParentView.ViewName : input.baseViewName;
119
+ const expectedLabel = alt.ParentView ? `parent alternate view '${alt.ParentView.Name}'` : 'BaseView';
120
+ warnings.push(`[AlternateBaseView] Entity '${input.entityName}' alternate view '${alt.Name}' (${qualifiedAlt}) does not depend on ${expectedLabel} '${expectedSchema}.${expectedObject}' (breaks D10).`);
121
+ }
122
+ if (alt.CachePolicy === 'Default') {
123
+ const clockMatches = findClockExpressionsInViewDefinition(input.viewDefinition);
124
+ if (clockMatches.length > 0) {
125
+ warnings.push(`[AlternateBaseView] Entity '${input.entityName}' alternate view '${alt.Name}' (${qualifiedAlt}) references clock expression(s) (${clockMatches.join(', ')}) while CachePolicy = 'Default'. Set CachePolicy = 'Bypass' so time-sensitive predicates do not serve stale cached results.`);
126
+ }
127
+ const externalRelations = findExternalDependenciesForDefaultCache(input);
128
+ if (externalRelations.length > 0) {
129
+ warnings.push(`[AlternateBaseView] Entity '${input.entityName}' alternate view '${alt.Name}' (${qualifiedAlt}) depends on external relation(s) (${externalRelations.join(', ')}) while CachePolicy = 'Default'. Cache invalidation only tracks saves to '${input.entityName}'; consider setting CachePolicy = 'Bypass'.`);
130
+ }
131
+ }
132
+ return warnings;
133
+ }
34
134
  /**
35
135
  * This class is responsible for generating database level objects like views, stored procedures, permissions, etc. You can sub-class this class to create your own SQL generation logic or implement support for other
36
136
  * databases. The base class implements support for SQL Server. In future versions of MJ, we will break out an abstract base class that has the skeleton of the logic and then the SQL Server version will be a sub-class
@@ -79,6 +179,24 @@ export class SQLCodeGenBase {
79
179
  * while the entity itself is not in newEntityList/modifiedEntityList.
80
180
  */
81
181
  this.existingRoutines = null;
182
+ /**
183
+ * Map of `schema.routine` (lowercased) to its live `OBJECT_DEFINITION` text on SQL Server,
184
+ * used by {@link isRoutineSaveReturnModeChanged} to detect when `Entity.Configuration.SaveReturnMode`
185
+ * changed via `mj sync push` without a physical table/column change, and by
186
+ * {@link isRoutineDefinitionDrifted} to detect any other difference from the generated body.
187
+ */
188
+ this.existingRoutineDefinitions = null;
189
+ /**
190
+ * `schema.routine` keys of CRUD routines whose live definition differed from the body generated
191
+ * this run, so they were force-logged and re-executed. Reported once after generation.
192
+ */
193
+ this.driftedRoutines = new Set();
194
+ /**
195
+ * Names of LAYERED entities whose generated inner view was written to the migration log this
196
+ * run. Their application-owned outer view must be refreshed in the same migration, even when the
197
+ * entity is on neither the new nor the modified list (the inner view changed on its own).
198
+ */
199
+ this.layeredEntitiesWithLoggedInnerView = new Set();
82
200
  }
83
201
  get SQLUtilityObject() {
84
202
  return this._sqlUtilityObject;
@@ -92,6 +210,9 @@ export class SQLCodeGenBase {
92
210
  async ManageSQLScriptsAndExecution(pool, entities, directory, currentUser) {
93
211
  try {
94
212
  this.existingRoutines = null;
213
+ this.existingRoutineDefinitions = null;
214
+ this.driftedRoutines = new Set();
215
+ this.layeredEntitiesWithLoggedInnerView = new Set();
95
216
  // Build list of entities qualified for forced regeneration if entityWhereClause is provided
96
217
  if (configInfo.forceRegeneration?.enabled && configInfo.forceRegeneration?.entityWhereClause) {
97
218
  this.filterEntitiesQualifiedForRegeneration = true; // Enable filtering
@@ -122,11 +243,15 @@ export class SQLCodeGenBase {
122
243
  // objects like spCreate for a given entity might reference the vw for that entity
123
244
  StartSpinner('Running custom SQL scripts...');
124
245
  const startTime = new Date();
125
- if (!await this.RunCustomSQLScripts(pool, 'before-sql')) {
246
+ // A failed before-sql script fails the step but does not stop the run: the remaining steps
247
+ // still run so the final result lists every failure, not just the first.
248
+ const beforeScriptsSucceeded = await this.RunCustomSQLScripts(pool, 'before-sql');
249
+ if (!beforeScriptsSucceeded) {
126
250
  FailSpinner('Failed to run custom SQL scripts');
127
- return false;
128
251
  }
129
- SucceedSpinner(`Custom SQL scripts completed (${(new Date().getTime() - startTime.getTime()) / 1000}s)`);
252
+ else {
253
+ SucceedSpinner(`Custom SQL scripts completed (${(new Date().getTime() - startTime.getTime()) / 1000}s)`);
254
+ }
130
255
  await this.loadExistingRoutines(pool, entities);
131
256
  // ALWAYS use the first filter where we only include entities that have IncludeInAPI = 1
132
257
  // Entities are already sorted by name in PostProcessEntityMetadata (see providerBase.ts)
@@ -300,7 +425,7 @@ export class SQLCodeGenBase {
300
425
  }
301
426
  // Initialize from entityGenSuccess so any per-batch failures from
302
427
  // STEP 2(b)/(c) carry forward instead of being lost. Bug 2 fix.
303
- let overallSuccess = entityGenSuccess;
428
+ let overallSuccess = entityGenSuccess && beforeScriptsSucceeded;
304
429
  if (!executionSuccess) {
305
430
  FailSpinner('Failed to execute entity SQL files');
306
431
  TempBatchFile.cleanup(); // Cleanup on error
@@ -313,6 +438,22 @@ export class SQLCodeGenBase {
313
438
  const step2eEndTime = new Date();
314
439
  SucceedSpinner(`SQL execution completed (${(step2eEndTime.getTime() - step2eStartTime.getTime()) / 1000}s)`);
315
440
  }
441
+ this.reportDriftedRoutines();
442
+ // STEP 2(f) - refresh every application-owned base view NOW, before STEP 3's field sync.
443
+ // SQL Server freezes a non-schemabound view's column list at CREATE time, so recreating a
444
+ // layered entity's inner view in STEP 2(e) does not update the outer view's sys.columns.
445
+ // STEP 3 decides which EntityField rows are orphaned from that outer view, so a stale
446
+ // outer view made it delete the rows for columns added this run (#4336). The same refresh
447
+ // is written to the migration log here, ahead of any field-sync SQL, so a replay of the
448
+ // migration runs in the same order. STEP 4.5 still emits its refresh as a safety net.
449
+ StartSpinner('Refreshing custom base views...');
450
+ if (!await this.RefreshCustomBaseViewsLive(pool, includedEntities)) {
451
+ FailSpinner('Failed to refresh one or more custom base views');
452
+ overallSuccess = false;
453
+ }
454
+ else {
455
+ SucceedSpinner('Custom base views refreshed');
456
+ }
316
457
  const manageMD = MJGlobal.Instance.ClassFactory.CreateInstance(ManageMetadataBase);
317
458
  // STEP 3 - re-run the process to manage entity fields since the Step 1 and 2 above might have resulted in differences in base view columns compared to what we had at first
318
459
  // we CAN skip the entity field values part because that wouldn't change from the first time we ran it
@@ -320,13 +461,30 @@ export class SQLCodeGenBase {
320
461
  //
321
462
  // Pass 1 (in manage-metadata.ts) already discovered all changes and populated _newEntityList ∪ _modifiedEntityList.
322
463
  // Pass 2 (this call) only re-runs to pick up new virtual fields from regenerated views and to apply advanced
323
- // generation. Scoping to changed entities collapses the SP scans to seeks; an empty list means no work to do.
464
+ // generation. Scoping to changed entities collapses the SP scans to seeks; an empty list means no schema-sync
465
+ // work to do. The filter does NOT scope the orphan prune: Step 2 regenerated every included entity's base
466
+ // view, so a view can LOSE columns on an entity that is on neither list, and by definition that entity is
467
+ // outside the filter (#4050). manageEntityFields runs the prune unscoped, before its empty-filter fast exit,
468
+ // and folds the entities it pruned into this pass's scope.
324
469
  // forceRegeneration override skips the scoping so all entities get reprocessed (used when prompts change, etc.).
470
+ //
471
+ // The two lists only ever contain entities something changed on during THIS run, so an
472
+ // entity whose virtual-field row was missed once drops out of scope forever and its
473
+ // record forms stay broken until someone runs forceRegeneration over the whole database.
474
+ // The drift probe closes that: it asks the catalog which entities have a view-only
475
+ // column with no EntityField and unions those in, so recovery is a normal run.
476
+ // Layered entities whose inner view was rebuilt this run are added as well: STEP 2(f) just
477
+ // refreshed their outer view, which can now expose columns that need EntityField rows.
478
+ const driftEntities = configInfo.forceRegeneration?.enabled
479
+ ? []
480
+ : await manageMD.FindVirtualFieldDriftEntities(pool, configInfo.excludeSchemas);
325
481
  const pass2EntityFilter = configInfo.forceRegeneration?.enabled
326
482
  ? undefined
327
483
  : [...new Set([
328
484
  ...ManageMetadataBase.newEntityList,
329
485
  ...ManageMetadataBase.modifiedEntityList,
486
+ ...driftEntities,
487
+ ...this.layeredEntitiesWithLoggedInnerView,
330
488
  ])];
331
489
  StartSpinner('Managing entity fields metadata...');
332
490
  if (!await manageMD.manageEntityFields(pool, configInfo.excludeSchemas, true, true, currentUser, false, false, pass2EntityFilter)) {
@@ -404,6 +562,7 @@ export class SQLCodeGenBase {
404
562
  // STEP 4.5 - Emit sp_refreshview for modified custom base view entities into the
405
563
  // migration log file so other environments pick up schema changes automatically.
406
564
  this.emitCustomBaseViewRefreshes();
565
+ await this.validateAlternateBaseViewsForEntities(pool, includedEntities);
407
566
  // STEP 5 - execute any custom SQL scripts that should run afterwards
408
567
  StartSpinner('Running post-generation SQL scripts...');
409
568
  const step5StartTime = new Date();
@@ -645,8 +804,11 @@ export class SQLCodeGenBase {
645
804
  // captured-dependent-restore fails because it doesn't know that
646
805
  // dependent will be re-emitted in a subsequent batch.
647
806
  const willRegenerate = options.willRegenerate ?? new Set(options.entities.map(e => `${e.SchemaName}.${e.BaseView}`));
807
+ const phaseLabel = options.progressLabel ?? (options.onlyPermissions ? 'Applying permissions' : 'Generating SQL');
808
+ const phaseStart = Date.now();
648
809
  for (let i = 0; i < totalEntities; i += options.batchSize) {
649
810
  const batch = options.entities.slice(i, i + options.batchSize);
811
+ this.reportEntityBatchProgress(phaseLabel, i, totalEntities, batch[0], phaseStart);
650
812
  const promises = batch.map(async (e) => {
651
813
  const pkeyField = e.Fields.find(f => f.IsPrimaryKey);
652
814
  if (!pkeyField) {
@@ -765,12 +927,17 @@ export class SQLCodeGenBase {
765
927
  logError(`Phased execution for ${options.entity.SchemaName}.${options.entity.Name} failed in phase "${where}": ${phaseResult.error?.message ?? '(no message)'}`);
766
928
  return { Success: false, Files: files };
767
929
  }
930
+ await this.validateAlternateBaseViews(options.pool, options.entity);
768
931
  return { Success: true, Files: files };
769
932
  }
770
933
  // Fallback: original monolithic path (SQL Server; also the path when
771
934
  // `onlyPermissions` is set — then we just want the permissions SQL).
935
+ const execSuccess = await this.SQLUtilityObject.executeSQLScript(options.pool, sql + "\n\nGO\n\n" + permissionsSQL, true);
936
+ if (execSuccess && !options.onlyPermissions) {
937
+ await this.validateAlternateBaseViews(options.pool, options.entity);
938
+ }
772
939
  return {
773
- Success: await this.SQLUtilityObject.executeSQLScript(options.pool, sql + "\n\nGO\n\n" + permissionsSQL, true),
940
+ Success: execSuccess,
774
941
  Files: files
775
942
  };
776
943
  }
@@ -827,6 +994,28 @@ export class SQLCodeGenBase {
827
994
  const crudDeleteSQL = entity.AllowDeleteAPI && entity.spDeleteGenerated && !entity.VirtualEntity
828
995
  ? await this.generateSPDelete(entity, pool)
829
996
  : '';
997
+ // Full-text search DDL. Without its own phase the generated
998
+ // *.fulltext.generated.sql is written to disk and then never executed on
999
+ // any provider that implements executeEntityPhased — nothing in the
1000
+ // phase list carried it. The search objects were therefore absent while
1001
+ // applyPermissions still GRANTed EXECUTE on the search function, and the
1002
+ // resulting `function does not exist` failed the whole CodeGen run.
1003
+ // Generated here (not in the provider) because building it needs the
1004
+ // internal generators and a pool round trip for the PK index name.
1005
+ let ftsSQL = '';
1006
+ if (entity.FullTextSearchEnabled && !entity.VirtualEntity) {
1007
+ try {
1008
+ const ft = await this.GenerateEntityFullTextSearchSQL(pool, entity);
1009
+ ftsSQL = ft.sql;
1010
+ }
1011
+ catch (e) {
1012
+ return {
1013
+ success: false,
1014
+ phase: 'fulltext-generate',
1015
+ error: e instanceof Error ? e : new Error(String(e)),
1016
+ };
1017
+ }
1018
+ }
830
1019
  return this._dbProvider.executeEntityPhased({
831
1020
  entity,
832
1021
  tvfSQL,
@@ -834,6 +1023,7 @@ export class SQLCodeGenBase {
834
1023
  crudCreateSQL,
835
1024
  crudUpdateSQL,
836
1025
  crudDeleteSQL,
1026
+ ftsSQL,
837
1027
  viewPermSQL: viewPieces.viewPermSQL,
838
1028
  willRegenerate,
839
1029
  });
@@ -985,6 +1175,11 @@ export class SQLCodeGenBase {
985
1175
  // Normalize whitespace for fair comparison: collapse runs of whitespace to single space
986
1176
  return body.replace(/\s+/g, ' ').trim();
987
1177
  }
1178
+ /**
1179
+ * Writes generated SQL to the migration log (and the temp batch executed on SQL Server) when the
1180
+ * entity is new/modified, a force-regeneration rule matches, or `forceLog` is set. Returns whether
1181
+ * the SQL was logged.
1182
+ */
988
1183
  logSQLForNewOrModifiedEntity(entity, sql, description, logSql = false, forceLog = false) {
989
1184
  // Check if we should log this SQL
990
1185
  let shouldLog = forceLog;
@@ -1041,6 +1236,7 @@ export class SQLCodeGenBase {
1041
1236
  TempBatchFile.appendToTempBatchFile(sql, entity.SchemaName);
1042
1237
  }
1043
1238
  LogIf(configInfo.verboseOutput, `SQL Generated for ${entity.Name}: ${description}`);
1239
+ return shouldLog;
1044
1240
  }
1045
1241
  /**
1046
1242
  * Emits sp_refreshview statements into the migration log file for modified custom base view
@@ -1059,6 +1255,69 @@ export class SQLCodeGenBase {
1059
1255
  const refreshSQL = this.buildCustomBaseViewRefreshSQL(qualifyingEntities);
1060
1256
  SQLLogging.appendToSQLLogFile(refreshSQL, 'Refresh custom base views for modified entities so schema changes are picked up');
1061
1257
  }
1258
+ /**
1259
+ * Executes the custom base view refresh ({@link buildCustomBaseViewRefreshSQL}: inner view, then
1260
+ * the guarded outer view, then its rebind and alternate views) against the live database for
1261
+ * EVERY included entity whose base view is application-owned, and writes the refresh for the
1262
+ * entities whose views changed this run into the migration log.
1263
+ *
1264
+ * Runs right after STEP 2(e), so the outer views expose the columns the regenerated inner views
1265
+ * now have before STEP 3 compares EntityField rows against them (#4336). Every entity is
1266
+ * attempted; failures are logged together and make the step return `false`.
1267
+ *
1268
+ * Only the entities on the new/modified lists, plus layered entities whose inner view was logged
1269
+ * this run, go into the migration log. Logging every custom view on every run would make a
1270
+ * capture non-empty when nothing changed.
1271
+ */
1272
+ async RefreshCustomBaseViewsLive(pool, includedEntities) {
1273
+ if (!this._dbProvider.NeedsViewRefresh) {
1274
+ return true; // PostgreSQL rebinds layered views in its phased executor
1275
+ }
1276
+ const targets = this.getCustomBaseViewEntitiesForLiveRefresh(includedEntities);
1277
+ if (targets.length === 0) {
1278
+ return true;
1279
+ }
1280
+ const failures = [];
1281
+ for (const entity of targets) {
1282
+ const refreshSQL = this.buildCustomBaseViewRefreshSQL([entity]);
1283
+ if (refreshSQL.trim().length === 0) {
1284
+ continue;
1285
+ }
1286
+ try {
1287
+ await pool.query(refreshSQL);
1288
+ }
1289
+ catch (e) {
1290
+ failures.push(`${entity.SchemaName}.${entity.BaseView} (${entity.Name}): ${e instanceof Error ? e.message : String(e)}`);
1291
+ }
1292
+ }
1293
+ const toLog = targets.filter(e => this.shouldLogCustomBaseViewRefresh(e));
1294
+ if (toLog.length > 0) {
1295
+ await SQLLogging.AppendToSQLLogFile(this.buildCustomBaseViewRefreshSQL(toLog), 'Refresh custom base views before entity field sync so new columns are not pruned');
1296
+ }
1297
+ if (failures.length > 0) {
1298
+ logError(`Custom base view refresh failed for ${failures.length} of ${targets.length} view(s):\n${failures.map(f => ` - ${f}`).join('\n')}`);
1299
+ return false;
1300
+ }
1301
+ return true;
1302
+ }
1303
+ /**
1304
+ * Included entities whose base view is application-owned (fully custom or layered), that have a
1305
+ * base view, are not virtual or externally sourced, and are in the custom-view refresh scope.
1306
+ */
1307
+ getCustomBaseViewEntitiesForLiveRefresh(includedEntities) {
1308
+ return includedEntities.filter(e => !e.BaseViewGenerated &&
1309
+ e.IncludeInAPI &&
1310
+ !e.VirtualEntity &&
1311
+ !e.ExternalDataSourceID &&
1312
+ !!e.BaseView &&
1313
+ EntityInCustomBaseViewRefreshScope(e.SchemaName, configInfo.excludeSchemas ?? [], configInfo.includeSchemas));
1314
+ }
1315
+ /** True when this run's migration log must carry the entity's custom base view refresh. */
1316
+ shouldLogCustomBaseViewRefresh(entity) {
1317
+ return ManageMetadataBase.newEntityList.includes(entity.Name) ||
1318
+ ManageMetadataBase.modifiedEntityList.includes(entity.Name) ||
1319
+ this.layeredEntitiesWithLoggedInnerView.has(entity.Name);
1320
+ }
1062
1321
  /**
1063
1322
  * Returns entities from the modified and new entity lists that have custom base views
1064
1323
  * (BaseViewGenerated === false), are included in the API, and are not virtual.
@@ -1095,8 +1354,9 @@ export class SQLCodeGenBase {
1095
1354
  return entities
1096
1355
  .map(e => {
1097
1356
  const outer = this._dbProvider.generateViewRefreshSQL(e.SchemaName, e.BaseView);
1357
+ const altSteps = this.getAlternateBaseViewRefreshStatements(e);
1098
1358
  if (!e.HasLayeredBaseView) {
1099
- return outer; // fully custom — one view, and it is a standing prerequisite
1359
+ return [outer, ...altSteps].filter((s) => s && s.trim().length > 0).join('\n'); // fully custom — one view, and it is a standing prerequisite
1100
1360
  }
1101
1361
  const inner = this._dbProvider.generateViewRefreshSQL(e.SchemaName, e.GeneratedViewName);
1102
1362
  const rebind = this._dbProvider.generateLayeredOuterRebindSQL(e);
@@ -1106,7 +1366,7 @@ export class SQLCodeGenBase {
1106
1366
  const rebindSql = rebind.trim().length > 0
1107
1367
  ? this.guardOnApplicationOwnedView(e, rebind.trim())
1108
1368
  : '';
1109
- return [inner, outerSql, rebindSql].filter((s) => s && s.trim().length > 0).join('\n');
1369
+ return [inner, outerSql, rebindSql, ...altSteps].filter((s) => s && s.trim().length > 0).join('\n');
1110
1370
  })
1111
1371
  .join('\n');
1112
1372
  }
@@ -1206,7 +1466,10 @@ export class SQLCodeGenBase {
1206
1466
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('view', options.entity.SchemaName, options.entity.GeneratedViewName, false, true));
1207
1467
  if (options.writeFiles) {
1208
1468
  this.writeFileIfChanged(filePath, s);
1209
- this.logSQLForNewOrModifiedEntity(options.entity, s, `Base View SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, baseViewChanged);
1469
+ const viewLogged = this.logSQLForNewOrModifiedEntity(options.entity, s, `Base View SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, baseViewChanged);
1470
+ if (viewLogged && options.entity.HasLayeredBaseView) {
1471
+ this.layeredEntitiesWithLoggedInnerView.add(options.entity.Name);
1472
+ }
1210
1473
  files.push(filePath);
1211
1474
  }
1212
1475
  sRet += s + '\n' + this._dbProvider.BatchSeparator + '\n';
@@ -1219,9 +1482,10 @@ export class SQLCodeGenBase {
1219
1482
  // pass. This copy is what gets written to the permissions FILE and logged into the
1220
1483
  // migration, so leaving it unguarded would fail on other environments even though the
1221
1484
  // executed copy (generateCustomBaseViewRefreshAndPermissions, below) is guarded.
1222
- const permBody = options.entity.HasLayeredBaseView && rawPermBody.trim().length > 0
1485
+ const altPermBody = this.generateAlternateBaseViewsPermissionsSQL(options.entity);
1486
+ const permBody = (options.entity.HasLayeredBaseView && rawPermBody.trim().length > 0
1223
1487
  ? '\n' + this.guardOnApplicationOwnedView(options.entity, rawPermBody.trim())
1224
- : rawPermBody;
1488
+ : rawPermBody) + altPermBody;
1225
1489
  const s = permHeader + permBody;
1226
1490
  if (s.length > 0)
1227
1491
  permissionsSQL += s + '\n' + this._dbProvider.BatchSeparator + '\n';
@@ -1243,6 +1507,8 @@ export class SQLCodeGenBase {
1243
1507
  // CREATE SP
1244
1508
  if (options.entity.AllowCreateAPI && !options.entity.VirtualEntity) {
1245
1509
  const spName = this.GetSPName(options.entity, SPType.Create);
1510
+ // Recomputed with the generated body below, so drift from the live definition counts too.
1511
+ let routineForceLog = this.forceLogForRoutine(options.entity, spName, baseViewChanged);
1246
1512
  // Only generate if spCreateGenerated is true (respects custom SPs where it's false)
1247
1513
  // forceRegeneration only forces regeneration of SPs where spCreateGenerated=true
1248
1514
  if (!options.onlyPermissions && options.entity.spCreateGenerated) {
@@ -1251,7 +1517,8 @@ export class SQLCodeGenBase {
1251
1517
  if (options.writeFiles) {
1252
1518
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, false, true));
1253
1519
  this.writeFileIfChanged(filePath, s);
1254
- this.logSQLForNewOrModifiedEntity(options.entity, s, `spCreate SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, this.forceLogForRoutine(options.entity, spName, baseViewChanged));
1520
+ routineForceLog = this.forceLogForRoutine(options.entity, spName, baseViewChanged, s);
1521
+ this.logSQLForNewOrModifiedEntity(options.entity, s, `spCreate SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
1255
1522
  files.push(filePath);
1256
1523
  }
1257
1524
  sRet += s + '\n' + this._dbProvider.BatchSeparator + '\n';
@@ -1262,7 +1529,7 @@ export class SQLCodeGenBase {
1262
1529
  if (options.writeFiles) {
1263
1530
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, true, true));
1264
1531
  this.writeFileIfChanged(filePath, s);
1265
- this.logSQLForNewOrModifiedEntity(options.entity, s, `spCreate Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, this.forceLogForRoutine(options.entity, spName, baseViewChanged));
1532
+ this.logSQLForNewOrModifiedEntity(options.entity, s, `spCreate Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
1266
1533
  files.push(filePath);
1267
1534
  }
1268
1535
  // now, append the permissions to the return string IF we did NOT generate the proc - because if we generated the proc, that
@@ -1273,6 +1540,8 @@ export class SQLCodeGenBase {
1273
1540
  // UPDATE SP
1274
1541
  if (options.entity.AllowUpdateAPI && !options.entity.VirtualEntity) {
1275
1542
  const spName = this.GetSPName(options.entity, SPType.Update);
1543
+ // Recomputed with the generated body below, so drift from the live definition counts too.
1544
+ let routineForceLog = this.forceLogForRoutine(options.entity, spName, baseViewChanged);
1276
1545
  // Only generate if spUpdateGenerated is true (respects custom SPs where it's false)
1277
1546
  // forceRegeneration only forces regeneration of SPs where spUpdateGenerated=true
1278
1547
  if (!options.onlyPermissions && options.entity.spUpdateGenerated) {
@@ -1281,7 +1550,8 @@ export class SQLCodeGenBase {
1281
1550
  if (options.writeFiles) {
1282
1551
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, false, true));
1283
1552
  this.writeFileIfChanged(filePath, s);
1284
- this.logSQLForNewOrModifiedEntity(options.entity, s, `spUpdate SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, this.forceLogForRoutine(options.entity, spName, baseViewChanged));
1553
+ routineForceLog = this.forceLogForRoutine(options.entity, spName, baseViewChanged, s);
1554
+ this.logSQLForNewOrModifiedEntity(options.entity, s, `spUpdate SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
1285
1555
  files.push(filePath);
1286
1556
  }
1287
1557
  sRet += s + '\n' + this._dbProvider.BatchSeparator + '\n';
@@ -1292,7 +1562,7 @@ export class SQLCodeGenBase {
1292
1562
  if (options.writeFiles) {
1293
1563
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, true, true));
1294
1564
  this.writeFileIfChanged(filePath, s);
1295
- this.logSQLForNewOrModifiedEntity(options.entity, s, `spUpdate Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, this.forceLogForRoutine(options.entity, spName, baseViewChanged));
1565
+ this.logSQLForNewOrModifiedEntity(options.entity, s, `spUpdate Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
1296
1566
  files.push(filePath);
1297
1567
  }
1298
1568
  // now, append the permissions to the return string IF we did NOT generate the proc - because if we generated the proc, that
@@ -1303,6 +1573,8 @@ export class SQLCodeGenBase {
1303
1573
  // DELETE SP
1304
1574
  if (options.entity.AllowDeleteAPI && !options.entity.VirtualEntity) {
1305
1575
  const spName = this.GetSPName(options.entity, SPType.Delete);
1576
+ // Recomputed with the generated body below, so drift from the live definition counts too.
1577
+ let routineForceLog = this.forceLogForRoutine(options.entity, spName, baseViewChanged);
1306
1578
  // Only generate if spDeleteGenerated is true (respects custom SPs where it's false)
1307
1579
  // OR if this entity has cascade delete dependencies that require regeneration
1308
1580
  // forceRegeneration only forces regeneration of SPs where spDeleteGenerated=true
@@ -1317,7 +1589,8 @@ export class SQLCodeGenBase {
1317
1589
  if (options.writeFiles) {
1318
1590
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, false, true));
1319
1591
  this.writeFileIfChanged(filePath, s);
1320
- this.logSQLForNewOrModifiedEntity(options.entity, s, `spDelete SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, this.forceLogForRoutine(options.entity, spName, baseViewChanged));
1592
+ routineForceLog = this.forceLogForRoutine(options.entity, spName, baseViewChanged, s);
1593
+ this.logSQLForNewOrModifiedEntity(options.entity, s, `spDelete SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
1321
1594
  files.push(filePath);
1322
1595
  }
1323
1596
  sRet += s + '\n' + this._dbProvider.BatchSeparator + '\n';
@@ -1328,7 +1601,7 @@ export class SQLCodeGenBase {
1328
1601
  if (options.writeFiles) {
1329
1602
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, true, true));
1330
1603
  this.writeFileIfChanged(filePath, s);
1331
- this.logSQLForNewOrModifiedEntity(options.entity, s, `spDelete Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, this.forceLogForRoutine(options.entity, spName, baseViewChanged));
1604
+ this.logSQLForNewOrModifiedEntity(options.entity, s, `spDelete Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
1332
1605
  files.push(filePath);
1333
1606
  }
1334
1607
  // now, append the permissions to the return string IF we did NOT generate the proc - because if we generated the proc, that
@@ -1385,10 +1658,12 @@ export class SQLCodeGenBase {
1385
1658
  /**
1386
1659
  * Snapshot every CRUD routine currently in the database (one query) so
1387
1660
  * generate-and-log can force-emit CREATE PROC for objects that vanished
1388
- * without the entity landing on newEntityList/modifiedEntityList.
1661
+ * without the entity landing on newEntityList/modifiedEntityList, or whose
1662
+ * return-row mode (`SaveReturnMode`) changed via `mj sync push`.
1389
1663
  */
1390
1664
  async loadExistingRoutines(pool, entities) {
1391
1665
  this.existingRoutines = new Set();
1666
+ this.existingRoutineDefinitions = null;
1392
1667
  const schemas = [...new Set(entities.map((e) => e.SchemaName).filter((s) => !!s))];
1393
1668
  const sql = this._dbProvider.getRoutineNamesBySchemaSQL(schemas);
1394
1669
  if (!sql || !sql.trim()) {
@@ -1403,10 +1678,25 @@ export class SQLCodeGenBase {
1403
1678
  this.existingRoutines.add(`${schemaName}.${routineName}`);
1404
1679
  }
1405
1680
  }
1681
+ if (this._dbProvider.PlatformKey === 'sqlserver' && schemas.length > 0) {
1682
+ const inList = schemas.map((s) => `'${s.replace(/'/g, "''")}'`).join(', ');
1683
+ const defResult = await pool.query(`SELECT s.name AS schema_name, p.name AS routine_name, OBJECT_DEFINITION(p.object_id) AS routine_definition ` +
1684
+ `FROM sys.procedures p INNER JOIN sys.schemas s ON s.schema_id = p.schema_id WHERE s.name IN (${inList})`);
1685
+ this.existingRoutineDefinitions = new Map();
1686
+ for (const row of defResult.recordset ?? []) {
1687
+ const schemaName = String(row.schema_name ?? '').toLowerCase();
1688
+ const routineName = String(row.routine_name ?? '').toLowerCase();
1689
+ const routineDef = row.routine_definition != null ? String(row.routine_definition) : '';
1690
+ if (schemaName && routineName && routineDef) {
1691
+ this.existingRoutineDefinitions.set(`${schemaName}.${routineName}`, routineDef);
1692
+ }
1693
+ }
1694
+ }
1406
1695
  }
1407
1696
  catch (e) {
1408
1697
  LogWarning(`Could not load existing CRUD routines (missing-proc self-heal disabled this run): ${e instanceof Error ? e.message : String(e)}`);
1409
1698
  this.existingRoutines = null;
1699
+ this.existingRoutineDefinitions = null;
1410
1700
  }
1411
1701
  }
1412
1702
  isRoutineMissing(schema, routineName) {
@@ -1415,8 +1705,88 @@ export class SQLCodeGenBase {
1415
1705
  }
1416
1706
  return !this.existingRoutines.has(`${schema}.${routineName}`.toLowerCase());
1417
1707
  }
1418
- forceLogForRoutine(entity, routineName, baseViewChanged) {
1419
- return baseViewChanged || this.isRoutineMissing(entity.SchemaName, routineName);
1708
+ /**
1709
+ * Returns true when `spCreate` or `spUpdate` in the database was generated under a different
1710
+ * `SaveReturnMode` (`'full'` vs `'datestamps_only'`) than the entity's current metadata.
1711
+ * This ensures that when `Entity.Configuration.SaveReturnMode` is updated via `mj sync push`,
1712
+ * the subsequent `mj codegen` run automatically logs and executes the updated stored procedures.
1713
+ */
1714
+ isRoutineSaveReturnModeChanged(entity, routineName) {
1715
+ if (!this.existingRoutineDefinitions || !entity.BaseView) {
1716
+ return false;
1717
+ }
1718
+ const createSpName = this.GetSPName(entity, SPType.Create).toLowerCase();
1719
+ const updateSpName = this.GetSPName(entity, SPType.Update).toLowerCase();
1720
+ const lowerRoutine = routineName.toLowerCase();
1721
+ if (lowerRoutine !== createSpName && lowerRoutine !== updateSpName) {
1722
+ return false;
1723
+ }
1724
+ const def = this.existingRoutineDefinitions.get(`${entity.SchemaName}.${routineName}`.toLowerCase());
1725
+ if (!def) {
1726
+ return false;
1727
+ }
1728
+ const selectsFromBaseView = def.toLowerCase().includes(`[${entity.BaseView.toLowerCase()}]`);
1729
+ if (entity.SaveReturnMode === 'datestamps_only') {
1730
+ return selectsFromBaseView;
1731
+ }
1732
+ return !selectsFromBaseView;
1733
+ }
1734
+ /**
1735
+ * Returns true when the live definition of the entity's spCreate / spUpdate / spDelete differs
1736
+ * from `generatedSQL`, the body CodeGen generated for it this run, after both are normalized by
1737
+ * the provider (comments, header, DROP batch, `GO` and whitespace removed).
1738
+ *
1739
+ * This catches drift that never reaches the new/modified entity lists: a column default or type
1740
+ * synced by `R__RefreshMetadata` before CodeGen ran (#5636), or a cascade target whose column a
1741
+ * migration dropped together with its EntityField row (#3343). Returns false when the live
1742
+ * definitions were not loaded (PostgreSQL, or the catalog query failed), when the routine is
1743
+ * missing (handled by {@link isRoutineMissing}), or when either side cannot be normalized.
1744
+ */
1745
+ isRoutineDefinitionDrifted(entity, routineName, generatedSQL) {
1746
+ if (!this.existingRoutineDefinitions || !generatedSQL) {
1747
+ return false;
1748
+ }
1749
+ const lowerRoutine = routineName.toLowerCase();
1750
+ const crudNames = [SPType.Create, SPType.Update, SPType.Delete].map(t => this.GetSPName(entity, t).toLowerCase());
1751
+ if (!crudNames.includes(lowerRoutine)) {
1752
+ return false;
1753
+ }
1754
+ const key = `${entity.SchemaName}.${routineName}`.toLowerCase();
1755
+ const liveDefinition = this.existingRoutineDefinitions.get(key);
1756
+ if (!liveDefinition) {
1757
+ return false;
1758
+ }
1759
+ const generated = this._dbProvider.NormalizeRoutineDefinitionForComparison(generatedSQL);
1760
+ const live = this._dbProvider.NormalizeRoutineDefinitionForComparison(liveDefinition);
1761
+ if (generated === null || live === null) {
1762
+ return false;
1763
+ }
1764
+ if (generated !== live) {
1765
+ this.driftedRoutines.add(key);
1766
+ return true;
1767
+ }
1768
+ return false;
1769
+ }
1770
+ /**
1771
+ * Whether a CRUD routine's SQL must be logged and executed regardless of the new/modified lists.
1772
+ * `generatedSQL`, when given, is the body generated this run and enables the live-definition drift
1773
+ * check ({@link isRoutineDefinitionDrifted}).
1774
+ */
1775
+ forceLogForRoutine(entity, routineName, baseViewChanged, generatedSQL) {
1776
+ return baseViewChanged ||
1777
+ this.isRoutineMissing(entity.SchemaName, routineName) ||
1778
+ this.isRoutineSaveReturnModeChanged(entity, routineName) ||
1779
+ (generatedSQL !== undefined && this.isRoutineDefinitionDrifted(entity, routineName, generatedSQL));
1780
+ }
1781
+ /** Logs the CRUD routines that were regenerated because their live definition had drifted. */
1782
+ reportDriftedRoutines() {
1783
+ if (this.driftedRoutines.size === 0) {
1784
+ return;
1785
+ }
1786
+ const names = [...this.driftedRoutines].sort();
1787
+ const shown = names.slice(0, 20).map(n => ` - ${n}`).join('\n');
1788
+ const more = names.length > 20 ? `\n … and ${names.length - 20} more` : '';
1789
+ logStatus(`Regenerated ${names.length} CRUD routine(s) whose live definition differed from the generated body:\n${shown}${more}`);
1420
1790
  }
1421
1791
  GetEntityPermissionFileNames(entity) {
1422
1792
  const files = [];
@@ -1492,28 +1862,66 @@ export class SQLCodeGenBase {
1492
1862
  throw new Error(`FullTextIndexGenerated is true for entity ${entity.Name}, but no fields are marked as FullTextSearchEnabled`);
1493
1863
  if (entity.FullTextSearchFunctionGenerated && searchFields.length === 0)
1494
1864
  throw new Error(`FullTextSearchFunctionGenerated is true for entity ${entity.Name}, but no fields are marked as FullTextSearchEnabled`);
1495
- // Get the primary key index name (needed for full text index)
1865
+ // Get the primary key index name — but ONLY for a provider whose full-text DDL actually
1866
+ // embeds it. `GetEntityPrimaryKeyIndexName` THROWS when the table has no PRIMARY KEY
1867
+ // constraint, and on PostgreSQL that is a legitimate shape: MJ's primary key can be a soft
1868
+ // key declared in metadata only. Asking unconditionally turned a SQL-Server requirement
1869
+ // (`CREATE FULLTEXT INDEX … KEY INDEX <name>`) into a precondition that no such table can
1870
+ // satisfy, so full-text search could never be generated for it — on a platform that builds
1871
+ // a GIN index over a tsvector and never looks at the name.
1496
1872
  let primaryKeyIndexName = '';
1497
- if (entity.FullTextIndexGenerated) {
1873
+ if (entity.FullTextIndexGenerated && this._dbProvider.FullTextIndexNeedsPrimaryKeyIndexName) {
1498
1874
  primaryKeyIndexName = await this.GetEntityPrimaryKeyIndexName(pool, entity);
1499
1875
  }
1500
- // If the function name is not set, save it to the DB
1501
- const functionName = entity.FullTextSearchFunction && entity.FullTextSearchFunction.length > 0
1502
- ? entity.FullTextSearchFunction
1503
- : `fnSearch${entity.CodeName}`;
1504
- if (entity.FullTextSearchFunctionGenerated && (!entity.FullTextSearchFunction || entity.FullTextSearchFunction.length === 0)) {
1876
+ // Say what enabling full-text search costs, at the one moment the person who enabled it is
1877
+ // still in the room. The objects below are charged on every write to the table from here on
1878
+ // and are not removed by turning the entity's flags back off.
1879
+ const costDisclosure = this._dbProvider.FullTextSearchCostDisclosure(entity, searchFields);
1880
+ if (costDisclosure) {
1881
+ LogWarning(` > ${costDisclosure}`);
1882
+ }
1883
+ // Delegate SQL generation to the provider FIRST — the provider owns the
1884
+ // platform's naming scheme, and the name it used is what actually exists
1885
+ // in the database. PostgreSQL creates `fn_search_<snake(BaseTable)>`;
1886
+ // deriving the name here instead (the SQL Server `fnSearch<CodeName>`
1887
+ // form) recorded a function that never exists on PG, and runtime search
1888
+ // then called a name that was never created.
1889
+ const result = this._dbProvider.generateFullTextSearch(entity, searchFields, primaryKeyIndexName);
1890
+ const functionName = result.functionName && result.functionName.length > 0
1891
+ ? result.functionName
1892
+ : (entity.FullTextSearchFunction && entity.FullTextSearchFunction.length > 0
1893
+ ? entity.FullTextSearchFunction
1894
+ : `fnSearch${entity.CodeName}`);
1895
+ // Persist the provider-derived name whenever the stored one DIFFERS, not
1896
+ // only when it is empty. An empty-only condition can never correct a row
1897
+ // stamped with the wrong platform's scheme by an earlier run, because the
1898
+ // wrong name is still a non-empty one.
1899
+ if (entity.FullTextSearchFunctionGenerated && entity.FullTextSearchFunction !== functionName) {
1505
1900
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
1506
- const u = UserCache.Instance.Users[0];
1901
+ // Guard the ARRAY, not only its first element. An unrefreshed cache holds `[]` today, but
1902
+ // a holder carrying an older GenericDatabaseProvider leaves `_users` undefined, and
1903
+ // `.Users[0]` against that throws a bare `TypeError: Cannot read properties of undefined
1904
+ // (reading '0')` BEFORE the guard below can say anything at all. The declared type is
1905
+ // widened here because the runtime value is the thing being guarded.
1906
+ //
1907
+ // Fatal on purpose: the write-back is the ONLY thing that records the function name.
1908
+ // Skipping it would leave `Entity.FullTextSearchFunction` empty while the DDL still
1909
+ // creates the function, so CodeGen would report success and runtime search would look
1910
+ // for a name no row carries.
1911
+ const cachedUsers = UserCache.Instance.Users;
1912
+ const u = cachedUsers?.[0];
1507
1913
  if (!u)
1508
- throw new Error('Could not find the first user in the cache, cant generate the full text search function without a user');
1914
+ throw new Error(`Cannot record the full-text search function name for entity ${entity.Name}: the CodeGen user cache holds no users, ` +
1915
+ `so there is no user to write __mj.Entity.FullTextSearchFunction as. The cache is populated by the provider's ` +
1916
+ `SetupDataSource via UserCache.Instance.Refresh() — verify that it ran for this connection and that __mj.User has ` +
1917
+ `at least one row. To complete this run without the write-back, set FullTextSearchFunction to '${functionName}' on ` +
1918
+ `entity ${entity.Name}; that is the name CodeGen is trying to record, so the write-back becomes unnecessary.`);
1509
1919
  const e = await md.GetEntityObject('MJ: Entities', u);
1510
1920
  await e.Load(entity.ID);
1511
1921
  e.FullTextSearchFunction = functionName;
1512
1922
  if (!await e.Save())
1513
1923
  throw new Error(`Could not update the FullTextSearchFunction for entity ${entity.Name}`);
1514
1924
  }
1515
- // Delegate SQL generation to the provider
1516
- const result = this._dbProvider.generateFullTextSearch(entity, searchFields, primaryKeyIndexName);
1517
1925
  // Add permissions if function was generated
1518
1926
  if (entity.FullTextSearchFunctionGenerated) {
1519
1927
  result.sql += this.generateFullTextSearchFunctionPermissions(entity, functionName) + '\n\n' + this._dbProvider.BatchSeparator + '\n';
@@ -1544,6 +1952,32 @@ export class SQLCodeGenBase {
1544
1952
  generateAllEntitiesSQLFileHeader() {
1545
1953
  return this.GenerateAllEntitiesSQLFileHeader();
1546
1954
  }
1955
+ /**
1956
+ * Emits the one live progress line for the entity generation/permissions loop: which phase, how
1957
+ * far through, which entity is being worked on, and how long the phase has been running.
1958
+ *
1959
+ * WHY. The spinner already re-renders an elapsed timer every 100 ms, so a long run is not silent
1960
+ * — but the message it re-renders was set ONCE before the loop ("Generating SQL for 1,200
1961
+ * entities…") and never changed again. A run that has been sitting on entity 3 for four minutes
1962
+ * and a run that is on entity 1,180 render identically, which makes a stall and normal progress
1963
+ * indistinguishable. `N/total` is the whole difference.
1964
+ *
1965
+ * Called per BATCH rather than per entity: the batch is the unit of concurrency (its members run
1966
+ * under one `Promise.all`), so a per-entity line would just interleave five entities' names at
1967
+ * random. The named entity is the batch's first, which is what the run is demonstrably on.
1968
+ *
1969
+ * `UpdateSpinner` covers both output modes by construction — in verbose mode it routes to
1970
+ * `logStatus`, so a verbose run gets the same information as a line per batch instead of a
1971
+ * re-rendered spinner.
1972
+ */
1973
+ reportEntityBatchProgress(phaseLabel, completed, total, currentEntity, phaseStartMs) {
1974
+ if (total === 0) {
1975
+ return;
1976
+ }
1977
+ const elapsed = ((Date.now() - phaseStartMs) / 1000).toFixed(1);
1978
+ const where = currentEntity ? ` — ${currentEntity.SchemaName}.${currentEntity.Name}` : '';
1979
+ UpdateSpinner(`${phaseLabel}: ${completed}/${total} entities, ${elapsed}s elapsed${where}`);
1980
+ }
1547
1981
  GenerateSingleEntitySQLFileHeader(entity, itemName) {
1548
1982
  return this._dbProvider.generateSQLFileHeader(entity, itemName);
1549
1983
  }
@@ -1583,9 +2017,18 @@ export class SQLCodeGenBase {
1583
2017
  /**
1584
2018
  * Detects self-referential foreign keys in an entity (e.g., ParentTaskID pointing back to Task table)
1585
2019
  * Returns array of field info objects representing recursive relationships
2020
+ *
2021
+ * A column that IS the entity's own primary key is excluded. It can carry a self-referencing
2022
+ * `RelatedEntityID` — FK auto-detection matches a `<prefix>_key`-style column to its own table
2023
+ * and does not exclude that table's own key — but "my parent is me" is not a hierarchy. The
2024
+ * generated recursive CTE then joins the key to itself and selects the same column three times,
2025
+ * which the database rejects outright: 15 entities on one Postgres instance failed to compile
2026
+ * with `column reference "tea_key" is ambiguous`. Nothing downstream can recover from that, and
2027
+ * a real hierarchy always parents on a DIFFERENT column, so excluding the key loses nothing.
1586
2028
  */
1587
2029
  detectRecursiveForeignKeys(entity) {
1588
2030
  const hierarchyFKs = entity.Fields.filter(field => field.RelatedEntityID != null &&
2031
+ !field.IsPrimaryKey &&
1589
2032
  UUIDsEqual(field.RelatedEntityID, entity.ID) &&
1590
2033
  !field.IsVirtual &&
1591
2034
  field.IsHierarchy === true);
@@ -1801,14 +2244,15 @@ export class SQLCodeGenBase {
1801
2244
  // sites because generateBaseView concatenates this onto the view DDL and the phased
1802
2245
  // executor consumes it separately — both need it.
1803
2246
  const rawPermissions = this.generateViewPermissions(entity);
2247
+ const altPermissions = this.generateAlternateBaseViewsPermissionsSQL(entity);
1804
2248
  // The leading newline must stay OUTSIDE the guard. `generateViewPermissions` returns
1805
2249
  // "\nGRANT ..." and the view DDL it is concatenated onto ends in `GO`; wrapping the string
1806
2250
  // verbatim pulls that newline inside the sp_executesql literal and emits `GOIF OBJECT_ID`,
1807
2251
  // fusing the batch separator to the next statement. Non-layered entities keep the raw
1808
2252
  // string byte-for-byte so this cannot churn every other entity's generated SQL.
1809
- const permissions = entity.HasLayeredBaseView && rawPermissions.trim().length > 0
2253
+ const permissions = (entity.HasLayeredBaseView && rawPermissions.trim().length > 0
1810
2254
  ? '\n' + this.guardOnApplicationOwnedView(entity, rawPermissions.trim())
1811
- : rawPermissions;
2255
+ : rawPermissions) + altPermissions;
1812
2256
  // Detect recursive foreign keys and generate TVF joins and root field selects
1813
2257
  const recursiveFKs = this.detectRecursiveForeignKeys(entity);
1814
2258
  const rootFields = recursiveFKs.length > 0 ? this.generateRootFieldSelects(entity, recursiveFKs, classNameFirstChar) : '';
@@ -1825,8 +2269,16 @@ export class SQLCodeGenBase {
1825
2269
  rootFieldsSelect: rootFields,
1826
2270
  rootJoins: rootJoins,
1827
2271
  };
2272
+ let viewSQL = this._dbProvider.generateBaseView(context);
2273
+ if (!entity.HasLayeredBaseView && this._dbProvider.NeedsViewRefresh) {
2274
+ const altRefreshStatements = this.getAlternateBaseViewRefreshStatements(entity);
2275
+ if (altRefreshStatements.length > 0) {
2276
+ const separator = '\n' + this._dbProvider.BatchSeparator + '\n';
2277
+ viewSQL += separator + altRefreshStatements.join(separator);
2278
+ }
2279
+ }
1828
2280
  return {
1829
- viewSQL: this._dbProvider.generateBaseView(context),
2281
+ viewSQL,
1830
2282
  viewPermSQL: permissions,
1831
2283
  };
1832
2284
  }
@@ -1837,6 +2289,189 @@ export class SQLCodeGenBase {
1837
2289
  generateViewPermissions(entity) {
1838
2290
  return this._dbProvider.generateViewPermissions(entity);
1839
2291
  }
2292
+ /**
2293
+ * Validates that an alternate base view's `EffectiveSchemaName` and `ViewName`
2294
+ * (and its `ParentView`'s when present) are valid SQL identifiers before splicing
2295
+ * into generated DDL or catalog queries.
2296
+ */
2297
+ hasValidAlternateViewIdentifiers(entity, altView) {
2298
+ if (!IsValidSQLIdentifier(altView.EffectiveSchemaName) || !IsValidSQLIdentifier(altView.ViewName)) {
2299
+ logError(`[AlternateBaseView] Skipping alternate view '${altView.Name}' on entity '${entity.Name}': invalid SQL identifier '${altView.EffectiveSchemaName}.${altView.ViewName}'.`);
2300
+ return false;
2301
+ }
2302
+ if (altView.ParentView && (!IsValidSQLIdentifier(altView.ParentView.EffectiveSchemaName) || !IsValidSQLIdentifier(altView.ParentView.ViewName))) {
2303
+ logError(`[AlternateBaseView] Skipping alternate view '${altView.Name}' on entity '${entity.Name}': parent view has invalid SQL identifier '${altView.ParentView.EffectiveSchemaName}.${altView.ParentView.ViewName}'.`);
2304
+ return false;
2305
+ }
2306
+ return true;
2307
+ }
2308
+ /**
2309
+ * Returns all registered alternate base views with valid SQL identifiers for `entity`
2310
+ * (including `Status === 'Disabled'`), ordered topologically by `ParentID`.
2311
+ */
2312
+ getOrderedAllAlternateBaseViews(entity) {
2313
+ const views = (entity.AlternateBaseViews ?? []).filter((v) => this.hasValidAlternateViewIdentifiers(entity, v));
2314
+ return OrderAlternateBaseViewsTopologically(views);
2315
+ }
2316
+ /**
2317
+ * Returns usable (`Status !== 'Disabled'`) alternate base views for `entity`,
2318
+ * ordered topologically by `ParentID` so parent views precede derived child views.
2319
+ */
2320
+ getOrderedAlternateBaseViews(entity) {
2321
+ return this.getOrderedAllAlternateBaseViews(entity).filter((v) => v.Status !== 'Disabled');
2322
+ }
2323
+ /**
2324
+ * Builds guarded refresh/rebind statements for each registered alternate base view on `entity`
2325
+ * (including `Disabled` views so `Active` children of a `Disabled` parent and re-enabled views
2326
+ * never hold stale column metadata) in topological `ParentID` order.
2327
+ */
2328
+ getAlternateBaseViewRefreshStatements(entity) {
2329
+ if (entity.VirtualEntity) {
2330
+ return [];
2331
+ }
2332
+ const ordered = this.getOrderedAllAlternateBaseViews(entity);
2333
+ if (ordered.length === 0) {
2334
+ return [];
2335
+ }
2336
+ const statements = [];
2337
+ for (const altView of ordered) {
2338
+ const schema = altView.EffectiveSchemaName;
2339
+ const viewName = altView.ViewName;
2340
+ if (this._dbProvider.NeedsViewRefresh) {
2341
+ const refresh = this._dbProvider.generateViewRefreshSQL(schema, viewName);
2342
+ if (refresh.trim().length > 0) {
2343
+ statements.push(this._dbProvider.generateIfViewExistsSQL(schema, viewName, refresh.trim()));
2344
+ }
2345
+ }
2346
+ const innerViewName = altView.ParentView ? altView.ParentView.ViewName : entity.BaseView;
2347
+ const rebind = this._dbProvider.GenerateAlternateBaseViewRebindSQL(entity, schema, viewName, innerViewName);
2348
+ if (rebind.trim().length > 0) {
2349
+ statements.push(this._dbProvider.generateIfViewExistsSQL(schema, viewName, rebind.trim()));
2350
+ }
2351
+ }
2352
+ return statements;
2353
+ }
2354
+ /**
2355
+ * Generates guarded permission statements for each registered alternate base view on `entity`:
2356
+ * - Usable (`Active` / `Deprecated`) views receive `GenerateViewPermissionsForTarget` (REVOKE + GRANT SELECT + FLS DENY SELECT).
2357
+ * - `Disabled` views receive `GenerateDisabledViewRevokePermissionsForTarget` (REVOKE SELECT) so disabling a view revokes database read grants.
2358
+ */
2359
+ generateAlternateBaseViewsPermissionsSQL(entity) {
2360
+ const ordered = this.getOrderedAllAlternateBaseViews(entity);
2361
+ if (ordered.length === 0) {
2362
+ return '';
2363
+ }
2364
+ let sOutput = '';
2365
+ for (const altView of ordered) {
2366
+ const rawPerm = altView.Status === 'Disabled'
2367
+ ? this._dbProvider.GenerateDisabledViewRevokePermissionsForTarget(entity, altView.EffectiveSchemaName, altView.ViewName)
2368
+ : this._dbProvider.GenerateViewPermissionsForTarget(entity, altView.EffectiveSchemaName, altView.ViewName);
2369
+ if (rawPerm.trim().length > 0) {
2370
+ sOutput += '\n' + this._dbProvider.generateIfViewExistsSQL(altView.EffectiveSchemaName, altView.ViewName, rawPerm.trim());
2371
+ }
2372
+ }
2373
+ return sOutput;
2374
+ }
2375
+ async validateAlternateBaseViewsForEntities(pool, entities) {
2376
+ if (!pool || typeof pool.query !== 'function') {
2377
+ return;
2378
+ }
2379
+ for (const entity of entities) {
2380
+ await this.validateAlternateBaseViews(pool, entity);
2381
+ }
2382
+ }
2383
+ /**
2384
+ * Audits each usable alternate base view on `entity` for column parity with `BaseView`,
2385
+ * catalog dependency on `BaseView` / `ParentView` (D10), and `CachePolicy = 'Default'`
2386
+ * safety (clock functions or external relation dependencies). Logs warnings via `LogWarning`.
2387
+ */
2388
+ async validateAlternateBaseViews(pool, entity) {
2389
+ if (!pool || typeof pool.query !== 'function') {
2390
+ return;
2391
+ }
2392
+ const ordered = this.getOrderedAlternateBaseViews(entity);
2393
+ if (ordered.length === 0) {
2394
+ return;
2395
+ }
2396
+ const baseViewColumns = entity.Fields.map((f) => f.Name);
2397
+ const registeredAltNames = new Set(this.getOrderedAllAlternateBaseViews(entity).map((v) => `${v.EffectiveSchemaName}.${v.ViewName}`.toLowerCase()));
2398
+ for (const altView of ordered) {
2399
+ await this.auditSingleAlternateBaseView(pool, entity, altView, baseViewColumns, registeredAltNames);
2400
+ }
2401
+ }
2402
+ async auditSingleAlternateBaseView(pool, entity, altView, baseViewColumns, registeredAltNames) {
2403
+ try {
2404
+ const facts = await this.fetchAlternateViewCatalogFacts(pool, entity, altView);
2405
+ const parentView = altView.ParentView;
2406
+ const warnings = EvaluateAlternateBaseViewParityAndSafety({
2407
+ entityName: entity.Name,
2408
+ entitySchemaName: entity.SchemaName,
2409
+ baseViewName: entity.BaseView,
2410
+ baseViewColumns,
2411
+ registeredAlternateViewNames: registeredAltNames,
2412
+ alternateView: {
2413
+ Name: altView.Name,
2414
+ EffectiveSchemaName: altView.EffectiveSchemaName,
2415
+ ViewName: altView.ViewName,
2416
+ CachePolicy: altView.CachePolicy,
2417
+ ParentView: parentView
2418
+ ? {
2419
+ Name: parentView.Name,
2420
+ EffectiveSchemaName: parentView.EffectiveSchemaName,
2421
+ ViewName: parentView.ViewName,
2422
+ }
2423
+ : undefined,
2424
+ },
2425
+ viewExists: facts.viewExists,
2426
+ viewColumns: facts.viewColumns,
2427
+ viewDefinition: facts.viewDefinition,
2428
+ dependencies: facts.dependencies,
2429
+ });
2430
+ for (const warning of warnings) {
2431
+ LogWarning(` ⚠️ ${warning}`);
2432
+ }
2433
+ }
2434
+ catch (e) {
2435
+ LogIf(configInfo.verboseOutput, `Could not audit alternate base view ${altView.Name} on ${entity.Name}: ${e}`);
2436
+ }
2437
+ }
2438
+ async fetchAlternateViewCatalogFacts(pool, entity, altView) {
2439
+ const colSQL = this._dbProvider.getViewColumnsSQL(altView.EffectiveSchemaName, altView.ViewName);
2440
+ const colResult = await pool.query(colSQL);
2441
+ const viewColumns = (colResult.recordset ?? [])
2442
+ .map((r) => String(r.FieldName ?? r.fieldname ?? ''))
2443
+ .filter((n) => n.length > 0);
2444
+ const viewExists = viewColumns.length > 0;
2445
+ let viewDefinition = null;
2446
+ let dependencies = [];
2447
+ if (viewExists) {
2448
+ try {
2449
+ const defSQL = this._dbProvider.getViewDefinitionSQL(altView.EffectiveSchemaName, altView.ViewName);
2450
+ const defRes = await pool.query(defSQL);
2451
+ viewDefinition = defRes.recordset?.[0]?.ViewDefinition ?? defRes.recordset?.[0]?.viewdefinition ?? null;
2452
+ }
2453
+ catch (err) {
2454
+ LogWarning(` ⚠️ [AlternateBaseView] Could not inspect view definition for ${altView.EffectiveSchemaName}.${altView.ViewName} on '${entity.Name}': ${err instanceof Error ? err.message : String(err)}`);
2455
+ }
2456
+ try {
2457
+ const depSQL = this._dbProvider.getViewDependenciesSQL(altView.EffectiveSchemaName, altView.ViewName);
2458
+ if (depSQL && depSQL.trim().length > 0) {
2459
+ const depRes = await pool.query(depSQL);
2460
+ dependencies = (depRes.recordset ?? [])
2461
+ .map((r) => ({
2462
+ ReferencedSchema: String(r.ReferencedSchema ?? r.referencedschema ?? ''),
2463
+ ReferencedObject: String(r.ReferencedObject ?? r.referencedobject ?? ''),
2464
+ ReferencedType: r.ReferencedType != null ? String(r.ReferencedType) : undefined,
2465
+ }))
2466
+ .filter((d) => d.ReferencedObject.length > 0);
2467
+ }
2468
+ }
2469
+ catch (err) {
2470
+ LogWarning(` ⚠️ [AlternateBaseView] Could not inspect catalog dependencies for ${altView.EffectiveSchemaName}.${altView.ViewName} on '${entity.Name}': ${err instanceof Error ? err.message : String(err)}`);
2471
+ }
2472
+ }
2473
+ return { viewExists, viewColumns, viewDefinition, dependencies };
2474
+ }
1840
2475
  /**
1841
2476
  * Emits the refresh + permission statements for an entity whose `BaseView` CodeGen does NOT
1842
2477
  * write — fully custom, or the application-owned outer half of a layered entity.
@@ -1872,7 +2507,11 @@ export class SQLCodeGenBase {
1872
2507
  sOutput += this.guardOnApplicationOwnedView(entity, rebindSQL.trim()) + separator;
1873
2508
  }
1874
2509
  }
1875
- return sOutput + permissionsHeader + this.guardOnApplicationOwnedView(entity, permissionsBody) + separator;
2510
+ for (const altRefresh of this.getAlternateBaseViewRefreshStatements(entity)) {
2511
+ sOutput += altRefresh + separator;
2512
+ }
2513
+ const altPermSQL = this.generateAlternateBaseViewsPermissionsSQL(entity);
2514
+ return sOutput + permissionsHeader + this.guardOnApplicationOwnedView(entity, permissionsBody) + altPermSQL + separator;
1876
2515
  }
1877
2516
  /**
1878
2517
  * Wraps SQL in an existence check on the application-owned `BaseView`, but only for a layered