@memberjunction/codegen-lib 6.2.0-edge.5 → 6.2.0-edge.7

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 (105) hide show
  1. package/README.md +1 -0
  2. package/dist/Angular/angular-codegen.d.ts +12 -1
  3. package/dist/Angular/angular-codegen.d.ts.map +1 -1
  4. package/dist/Angular/angular-codegen.js +36 -1
  5. package/dist/Angular/angular-codegen.js.map +1 -1
  6. package/dist/Config/config.d.ts +301 -0
  7. package/dist/Config/config.d.ts.map +1 -1
  8. package/dist/Config/config.js +188 -84
  9. package/dist/Config/config.js.map +1 -1
  10. package/dist/Database/codeGenDatabaseProvider.d.ts +101 -4
  11. package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
  12. package/dist/Database/codeGenDatabaseProvider.js +170 -4
  13. package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
  14. package/dist/Database/manage-metadata.d.ts +379 -24
  15. package/dist/Database/manage-metadata.d.ts.map +1 -1
  16. package/dist/Database/manage-metadata.js +1021 -237
  17. package/dist/Database/manage-metadata.js.map +1 -1
  18. package/dist/Database/materializationAnalysis.d.ts +18 -4
  19. package/dist/Database/materializationAnalysis.d.ts.map +1 -1
  20. package/dist/Database/materializationAnalysis.js +113 -99
  21. package/dist/Database/materializationAnalysis.js.map +1 -1
  22. package/dist/Database/materializationBroadRender.d.ts +7 -3
  23. package/dist/Database/materializationBroadRender.d.ts.map +1 -1
  24. package/dist/Database/materializationBroadRender.js +89 -56
  25. package/dist/Database/materializationBroadRender.js.map +1 -1
  26. package/dist/Database/materializationParamClassifier.d.ts +1 -1
  27. package/dist/Database/materializationParamClassifier.js +2 -2
  28. package/dist/Database/materializationParamVerifier.d.ts +1 -1
  29. package/dist/Database/materializationParamVerifier.d.ts.map +1 -1
  30. package/dist/Database/materializationParamVerifier.js +127 -221
  31. package/dist/Database/materializationParamVerifier.js.map +1 -1
  32. package/dist/Database/materializationSqlAst.d.ts +107 -79
  33. package/dist/Database/materializationSqlAst.d.ts.map +1 -1
  34. package/dist/Database/materializationSqlAst.js +307 -134
  35. package/dist/Database/materializationSqlAst.js.map +1 -1
  36. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +25 -5
  37. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
  38. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +135 -26
  39. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
  40. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js +9 -5
  41. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js.map +1 -1
  42. package/dist/Database/providers/postgresql/metadataSupportObjects.js +289 -90
  43. package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
  44. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +48 -12
  45. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
  46. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +146 -54
  47. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
  48. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js +66 -0
  49. package/dist/Database/providers/sqlserver/__tests__/VerifiedJoinIndexes.test.js.map +1 -1
  50. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts +47 -0
  51. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts.map +1 -0
  52. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js +167 -0
  53. package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js.map +1 -0
  54. package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts +31 -0
  55. package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts.map +1 -0
  56. package/dist/Database/providers/sqlserver/sqlServerScriptText.js +116 -0
  57. package/dist/Database/providers/sqlserver/sqlServerScriptText.js.map +1 -0
  58. package/dist/Database/queryRebindPass.d.ts +37 -0
  59. package/dist/Database/queryRebindPass.d.ts.map +1 -0
  60. package/dist/Database/queryRebindPass.js +110 -0
  61. package/dist/Database/queryRebindPass.js.map +1 -0
  62. package/dist/Database/schema-scope.d.ts +12 -0
  63. package/dist/Database/schema-scope.d.ts.map +1 -1
  64. package/dist/Database/schema-scope.js +15 -0
  65. package/dist/Database/schema-scope.js.map +1 -1
  66. package/dist/Database/sql.d.ts +13 -0
  67. package/dist/Database/sql.d.ts.map +1 -1
  68. package/dist/Database/sql.js +39 -8
  69. package/dist/Database/sql.js.map +1 -1
  70. package/dist/Database/sql_codegen.d.ts +212 -6
  71. package/dist/Database/sql_codegen.d.ts.map +1 -1
  72. package/dist/Database/sql_codegen.js +765 -63
  73. package/dist/Database/sql_codegen.js.map +1 -1
  74. package/dist/Misc/advanced_generation.d.ts +129 -5
  75. package/dist/Misc/advanced_generation.d.ts.map +1 -1
  76. package/dist/Misc/advanced_generation.js +212 -8
  77. package/dist/Misc/advanced_generation.js.map +1 -1
  78. package/dist/Misc/display-name-heuristics.d.ts +57 -0
  79. package/dist/Misc/display-name-heuristics.d.ts.map +1 -0
  80. package/dist/Misc/display-name-heuristics.js +97 -0
  81. package/dist/Misc/display-name-heuristics.js.map +1 -0
  82. package/dist/Misc/entity_subclasses_codegen.d.ts +31 -3
  83. package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
  84. package/dist/Misc/entity_subclasses_codegen.js +79 -17
  85. package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
  86. package/dist/Misc/remote_operations_codegen.d.ts.map +1 -1
  87. package/dist/Misc/remote_operations_codegen.js +21 -4
  88. package/dist/Misc/remote_operations_codegen.js.map +1 -1
  89. package/dist/Misc/sql_logging.d.ts +12 -0
  90. package/dist/Misc/sql_logging.d.ts.map +1 -1
  91. package/dist/Misc/sql_logging.js +21 -8
  92. package/dist/Misc/sql_logging.js.map +1 -1
  93. package/dist/Misc/system_integrity.d.ts +48 -0
  94. package/dist/Misc/system_integrity.d.ts.map +1 -1
  95. package/dist/Misc/system_integrity.js +151 -75
  96. package/dist/Misc/system_integrity.js.map +1 -1
  97. package/dist/Misc/validator-text.d.ts +17 -0
  98. package/dist/Misc/validator-text.d.ts.map +1 -1
  99. package/dist/Misc/validator-text.js +59 -0
  100. package/dist/Misc/validator-text.js.map +1 -1
  101. package/dist/runCodeGen.d.ts +37 -3
  102. package/dist/runCodeGen.d.ts.map +1 -1
  103. package/dist/runCodeGen.js +161 -51
  104. package/dist/runCodeGen.js.map +1 -1
  105. 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,174 @@ export function EntitiesNotInExcludedSchemas(entities, excludeSchemas) {
31
31
  export function entitiesNotInExcludedSchemas(entities, excludeSchemas) {
32
32
  return EntitiesNotInExcludedSchemas(entities, excludeSchemas);
33
33
  }
34
+ /**
35
+ * The parent columns an IS-A child's generated base view selects, in parent-chain order and each
36
+ * parent's field order. The child's view joins each parent's BASE TABLE, so a column qualifies only
37
+ * if it is physically on that table:
38
+ * - primary keys are shared with the child and `__mj_` columns are the child's own;
39
+ * - a view-only virtual field (`IsVirtual` and not `IsComputed`) is not on the table and is skipped;
40
+ * - a computed column (`IsVirtual` and `IsComputed`, e.g. a persisted `DisplayName`) IS on the
41
+ * table and is selected (#5899), unless an ancestor further up the chain also has a field of that
42
+ * name: then the row on this parent is an inherited mirror and the ancestor's join supplies it.
43
+ * A name is selected once even if two parents carry it.
44
+ */
45
+ export function InheritedParentColumns(entity) {
46
+ if (!entity.IsChildType)
47
+ return [];
48
+ const chain = entity.ParentChain;
49
+ const columns = [];
50
+ const seen = new Set();
51
+ for (let i = 0; i < chain.length; i++) {
52
+ const parent = chain[i];
53
+ const ancestorFieldNames = new Set(chain.slice(i + 1).flatMap(a => a.Fields.map(f => f.Name.toLowerCase())));
54
+ for (const field of parent.Fields) {
55
+ if (field.IsPrimaryKey || field.Name.startsWith('__mj_'))
56
+ continue;
57
+ if (field.IsVirtual && (!field.IsComputed || ancestorFieldNames.has(field.Name.toLowerCase())))
58
+ continue;
59
+ const key = field.Name.toLowerCase();
60
+ if (seen.has(key))
61
+ continue;
62
+ seen.add(key);
63
+ columns.push({ Alias: `__mj_isa_p${i + 1}`, Parent: parent, Field: field });
64
+ }
65
+ }
66
+ return columns;
67
+ }
68
+ /**
69
+ * Compares out-of-scope IS-A children's live view columns against the parent columns their view
70
+ * would select ({@link InheritedParentColumns}). Only children with at least one in-scope parent are
71
+ * considered: a parent app's run adds the column but cannot regenerate a sibling app's view (#4821).
72
+ * `liveColumns` maps `schema.view` (lower case) to the view's column names; a view absent from the
73
+ * map does not exist or was not read, and is skipped rather than reported as missing every column.
74
+ */
75
+ export function FindOutOfScopeISAChildDrift(entities, excludeSchemas, liveColumns) {
76
+ const excluded = new Set(excludeSchemas.map(s => s.trim().toLowerCase()));
77
+ const drift = [];
78
+ for (const child of OutOfScopeISAChildrenWithInScopeParent(entities, excludeSchemas)) {
79
+ const viewName = child.GeneratedViewName;
80
+ const live = liveColumns.get(`${child.SchemaName.trim()}.${viewName.trim()}`.toLowerCase());
81
+ if (!live)
82
+ continue;
83
+ const missing = InheritedParentColumns(child)
84
+ .filter(c => !excluded.has(c.Parent.SchemaName.trim().toLowerCase()))
85
+ .map(c => c.Field.Name)
86
+ .filter(name => !live.has(name.trim().toLowerCase()));
87
+ if (missing.length > 0) {
88
+ drift.push({ ChildName: child.Name, ChildSchema: child.SchemaName, ViewName: viewName, MissingColumns: missing });
89
+ }
90
+ }
91
+ return drift;
92
+ }
93
+ /** IS-A children in an excluded schema with at least one parent in this run's scope. */
94
+ export function OutOfScopeISAChildrenWithInScopeParent(entities, excludeSchemas) {
95
+ const excluded = new Set(excludeSchemas.map(s => s.trim().toLowerCase()));
96
+ return entities.filter(e => e.IsChildType &&
97
+ !e.VirtualEntity &&
98
+ !e.ExternalDataSourceID &&
99
+ excluded.has(e.SchemaName.trim().toLowerCase()) &&
100
+ e.ParentChain.some(p => !excluded.has(p.SchemaName.trim().toLowerCase())));
101
+ }
102
+ function stripSQLCommentsAndStringsForAudit(sql) {
103
+ return sql
104
+ .replace(/--[^\r\n]*/g, ' ')
105
+ .replace(/\/\*[\s\S]*?\*\//g, ' ')
106
+ .replace(/'(?:''|[^'])*'/g, "''");
107
+ }
108
+ function escapeRegExpForAudit(s) {
109
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
110
+ }
111
+ function checkAlternateViewExpectedDependency(input) {
112
+ const alt = input.alternateView;
113
+ const expectedSchema = alt.ParentView ? alt.ParentView.EffectiveSchemaName : input.entitySchemaName;
114
+ const expectedObject = alt.ParentView ? alt.ParentView.ViewName : input.baseViewName;
115
+ if (input.dependencies.length > 0) {
116
+ return input.dependencies.some((d) => d.ReferencedObject.toLowerCase() === expectedObject.toLowerCase() &&
117
+ (!d.ReferencedSchema || d.ReferencedSchema.toLowerCase() === expectedSchema.toLowerCase()));
118
+ }
119
+ if (!input.viewDefinition) {
120
+ return false;
121
+ }
122
+ const stripped = stripSQLCommentsAndStringsForAudit(input.viewDefinition);
123
+ const identBoundary = new RegExp(`(?:^|[^A-Za-z0-9_])[\\[""]?${escapeRegExpForAudit(expectedObject)}[\\]""]?(?=$|[^A-Za-z0-9_])`, 'i');
124
+ return identBoundary.test(stripped);
125
+ }
126
+ function findClockExpressionsInViewDefinition(viewDefinition) {
127
+ if (!viewDefinition) {
128
+ return [];
129
+ }
130
+ const stripped = stripSQLCommentsAndStringsForAudit(viewDefinition);
131
+ const clockMatches = new Set();
132
+ const fnCallRegex = /\b(GETDATE|GETUTCDATE|SYSDATETIME|SYSDATETIMEOFFSET|SYSUTCDATETIME|NOW|CLOCK_TIMESTAMP|STATEMENT_TIMESTAMP|TRANSACTION_TIMESTAMP)\s*\(/gi;
133
+ let m;
134
+ while ((m = fnCallRegex.exec(stripped)) !== null) {
135
+ clockMatches.add(m[1].toUpperCase() + '()');
136
+ }
137
+ const kwClockRegex = /\b(CURRENT_TIMESTAMP|LOCALTIMESTAMP|CURRENT_DATE|CURRENT_TIME)\b/gi;
138
+ while ((m = kwClockRegex.exec(stripped)) !== null) {
139
+ clockMatches.add(m[1].toUpperCase());
140
+ }
141
+ return [...clockMatches];
142
+ }
143
+ function isEntityHierarchyFunction(objectName) {
144
+ return /^fn_?[a-z0-9_]+_get_(?:root_id|hierarchy_meta|descendants|ancestors)$/i.test(objectName);
145
+ }
146
+ function findExternalDependenciesForDefaultCache(input) {
147
+ if (input.dependencies.length === 0) {
148
+ return [];
149
+ }
150
+ const allowedRelations = new Set([
151
+ `${input.entitySchemaName}.${input.baseViewName}`.toLowerCase(),
152
+ ...input.registeredAlternateViewNames,
153
+ ]);
154
+ const externalRelations = [];
155
+ for (const dep of input.dependencies) {
156
+ const depType = (dep.ReferencedType ?? '').toUpperCase();
157
+ if (depType.includes('FUNCTION') && isEntityHierarchyFunction(dep.ReferencedObject)) {
158
+ continue;
159
+ }
160
+ const depSchema = dep.ReferencedSchema || input.entitySchemaName;
161
+ const depKey = `${depSchema}.${dep.ReferencedObject}`.toLowerCase();
162
+ if (!allowedRelations.has(depKey) && !externalRelations.includes(`${depSchema}.${dep.ReferencedObject}`)) {
163
+ externalRelations.push(`${depSchema}.${dep.ReferencedObject}`);
164
+ }
165
+ }
166
+ return externalRelations;
167
+ }
168
+ /**
169
+ * Pure parity and safety evaluator for a registered alternate base view (Phase 4.3).
170
+ */
171
+ export function EvaluateAlternateBaseViewParityAndSafety(input) {
172
+ const warnings = [];
173
+ const alt = input.alternateView;
174
+ const qualifiedAlt = `${alt.EffectiveSchemaName}.${alt.ViewName}`;
175
+ if (!input.viewExists) {
176
+ warnings.push(`[AlternateBaseView] Entity '${input.entityName}' alternate view '${alt.Name}' (${qualifiedAlt}) does not exist in the database.`);
177
+ return warnings;
178
+ }
179
+ const altColSet = new Set(input.viewColumns.map((c) => c.toLowerCase()));
180
+ const missingCols = input.baseViewColumns.filter((c) => !altColSet.has(c.toLowerCase()));
181
+ if (missingCols.length > 0) {
182
+ 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).`);
183
+ }
184
+ if (!checkAlternateViewExpectedDependency(input)) {
185
+ const expectedSchema = alt.ParentView ? alt.ParentView.EffectiveSchemaName : input.entitySchemaName;
186
+ const expectedObject = alt.ParentView ? alt.ParentView.ViewName : input.baseViewName;
187
+ const expectedLabel = alt.ParentView ? `parent alternate view '${alt.ParentView.Name}'` : 'BaseView';
188
+ warnings.push(`[AlternateBaseView] Entity '${input.entityName}' alternate view '${alt.Name}' (${qualifiedAlt}) does not depend on ${expectedLabel} '${expectedSchema}.${expectedObject}' (breaks D10).`);
189
+ }
190
+ if (alt.CachePolicy === 'Default') {
191
+ const clockMatches = findClockExpressionsInViewDefinition(input.viewDefinition);
192
+ if (clockMatches.length > 0) {
193
+ 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.`);
194
+ }
195
+ const externalRelations = findExternalDependenciesForDefaultCache(input);
196
+ if (externalRelations.length > 0) {
197
+ 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'.`);
198
+ }
199
+ }
200
+ return warnings;
201
+ }
34
202
  /**
35
203
  * 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
204
  * 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
@@ -82,9 +250,26 @@ export class SQLCodeGenBase {
82
250
  /**
83
251
  * Map of `schema.routine` (lowercased) to its live `OBJECT_DEFINITION` text on SQL Server,
84
252
  * used by {@link isRoutineSaveReturnModeChanged} to detect when `Entity.Configuration.SaveReturnMode`
85
- * changed via `mj sync push` without a physical table/column change.
253
+ * changed via `mj sync push` without a physical table/column change, and by
254
+ * {@link isRoutineDefinitionDrifted} to detect any other difference from the generated body.
86
255
  */
87
256
  this.existingRoutineDefinitions = null;
257
+ /**
258
+ * `schema.routine` keys of CRUD routines whose live definition differed from the body generated
259
+ * this run, so they were force-logged and re-executed. Reported once after generation.
260
+ */
261
+ this.driftedRoutines = new Set();
262
+ /**
263
+ * Names of LAYERED entities whose generated inner view was written to the migration log this
264
+ * run. Their application-owned outer view must be refreshed in the same migration, even when the
265
+ * entity is on neither the new nor the modified list (the inner view changed on its own).
266
+ */
267
+ this.layeredEntitiesWithLoggedInnerView = new Set();
268
+ /**
269
+ * Names of LAYERED entities whose outer-view refresh was written right after their inner view
270
+ * ({@link logLayeredOuterViewRefresh}). STEP 2(f) does not log their refresh a second time.
271
+ */
272
+ this.layeredEntitiesWithInlineRefresh = new Set();
88
273
  }
89
274
  get SQLUtilityObject() {
90
275
  return this._sqlUtilityObject;
@@ -99,6 +284,9 @@ export class SQLCodeGenBase {
99
284
  try {
100
285
  this.existingRoutines = null;
101
286
  this.existingRoutineDefinitions = null;
287
+ this.driftedRoutines = new Set();
288
+ this.layeredEntitiesWithLoggedInnerView = new Set();
289
+ this.layeredEntitiesWithInlineRefresh = new Set();
102
290
  // Build list of entities qualified for forced regeneration if entityWhereClause is provided
103
291
  if (configInfo.forceRegeneration?.enabled && configInfo.forceRegeneration?.entityWhereClause) {
104
292
  this.filterEntitiesQualifiedForRegeneration = true; // Enable filtering
@@ -129,11 +317,15 @@ export class SQLCodeGenBase {
129
317
  // objects like spCreate for a given entity might reference the vw for that entity
130
318
  StartSpinner('Running custom SQL scripts...');
131
319
  const startTime = new Date();
132
- if (!await this.RunCustomSQLScripts(pool, 'before-sql')) {
320
+ // A failed before-sql script fails the step but does not stop the run: the remaining steps
321
+ // still run so the final result lists every failure, not just the first.
322
+ const beforeScriptsSucceeded = await this.RunCustomSQLScripts(pool, 'before-sql');
323
+ if (!beforeScriptsSucceeded) {
133
324
  FailSpinner('Failed to run custom SQL scripts');
134
- return false;
135
325
  }
136
- SucceedSpinner(`Custom SQL scripts completed (${(new Date().getTime() - startTime.getTime()) / 1000}s)`);
326
+ else {
327
+ SucceedSpinner(`Custom SQL scripts completed (${(new Date().getTime() - startTime.getTime()) / 1000}s)`);
328
+ }
137
329
  await this.loadExistingRoutines(pool, entities);
138
330
  // ALWAYS use the first filter where we only include entities that have IncludeInAPI = 1
139
331
  // Entities are already sorted by name in PostProcessEntityMetadata (see providerBase.ts)
@@ -148,9 +340,11 @@ export class SQLCodeGenBase {
148
340
  StartSpinner('Analyzing cascade delete dependencies...');
149
341
  await this.markEntitiesForCascadeDeleteRegeneration(pool, includedEntities);
150
342
  SucceedSpinner('Cascade delete dependency analysis completed');
151
- // STEP 2(a) - clean out all *.generated.sql and *.permissions.generated.sql files from the directory
343
+ // STEP 2(a) - clean out all *.generated.sql and *.permissions.generated.sql files from the directory.
344
+ // Only in-scope schemas' directories (#3384): STEP 2(b) rewrites those, and an out-of-scope
345
+ // schema's files are another run's to regenerate, so deleting them would leave them missing.
152
346
  StartSpinner('Cleaning generated files...');
153
- this.DeleteGeneratedEntityFiles(directory, baselineEntities);
347
+ this.DeleteGeneratedEntityFiles(directory, includedEntities);
154
348
  SucceedSpinner('Cleaned generated files');
155
349
  // STEP 2(a.5) - field-level security / permission-reconciliation run context.
156
350
  // One async pass over the live catalog (permission state + service-login role
@@ -307,7 +501,7 @@ export class SQLCodeGenBase {
307
501
  }
308
502
  // Initialize from entityGenSuccess so any per-batch failures from
309
503
  // STEP 2(b)/(c) carry forward instead of being lost. Bug 2 fix.
310
- let overallSuccess = entityGenSuccess;
504
+ let overallSuccess = entityGenSuccess && beforeScriptsSucceeded;
311
505
  if (!executionSuccess) {
312
506
  FailSpinner('Failed to execute entity SQL files');
313
507
  TempBatchFile.cleanup(); // Cleanup on error
@@ -320,6 +514,25 @@ export class SQLCodeGenBase {
320
514
  const step2eEndTime = new Date();
321
515
  SucceedSpinner(`SQL execution completed (${(step2eEndTime.getTime() - step2eStartTime.getTime()) / 1000}s)`);
322
516
  }
517
+ this.reportDriftedRoutines();
518
+ // STEP 2(f) - refresh every application-owned base view NOW, before STEP 3's field sync.
519
+ // SQL Server freezes a non-schemabound view's column list at CREATE time, so recreating a
520
+ // layered entity's inner view in STEP 2(e) does not update the outer view's sys.columns.
521
+ // STEP 3 decides which EntityField rows are orphaned from that outer view, so a stale
522
+ // outer view made it delete the rows for columns added this run (#4336). The same refresh
523
+ // is written to the migration log here, ahead of any field-sync SQL, so a replay of the
524
+ // migration runs in the same order. STEP 4.5 still emits its refresh as a safety net.
525
+ // A layered entity whose inner view was logged already had its refresh executed in the
526
+ // STEP 2(e) batch, between the inner view and its CRUD routines (#4927); this pass
527
+ // re-runs it live and does not log it a second time.
528
+ StartSpinner('Refreshing custom base views...');
529
+ if (!await this.RefreshCustomBaseViewsLive(pool, includedEntities)) {
530
+ FailSpinner('Failed to refresh one or more custom base views');
531
+ overallSuccess = false;
532
+ }
533
+ else {
534
+ SucceedSpinner('Custom base views refreshed');
535
+ }
323
536
  const manageMD = MJGlobal.Instance.ClassFactory.CreateInstance(ManageMetadataBase);
324
537
  // 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
325
538
  // we CAN skip the entity field values part because that wouldn't change from the first time we ran it
@@ -327,7 +540,11 @@ export class SQLCodeGenBase {
327
540
  //
328
541
  // Pass 1 (in manage-metadata.ts) already discovered all changes and populated _newEntityList ∪ _modifiedEntityList.
329
542
  // Pass 2 (this call) only re-runs to pick up new virtual fields from regenerated views and to apply advanced
330
- // generation. Scoping to changed entities collapses the SP scans to seeks; an empty list means no work to do.
543
+ // generation. Scoping to changed entities collapses the SP scans to seeks; an empty list means no schema-sync
544
+ // work to do. The filter does NOT scope the orphan prune: Step 2 regenerated every included entity's base
545
+ // view, so a view can LOSE columns on an entity that is on neither list, and by definition that entity is
546
+ // outside the filter (#4050). manageEntityFields runs the prune unscoped, before its empty-filter fast exit,
547
+ // and folds the entities it pruned into this pass's scope.
331
548
  // forceRegeneration override skips the scoping so all entities get reprocessed (used when prompts change, etc.).
332
549
  //
333
550
  // The two lists only ever contain entities something changed on during THIS run, so an
@@ -335,6 +552,8 @@ export class SQLCodeGenBase {
335
552
  // record forms stay broken until someone runs forceRegeneration over the whole database.
336
553
  // The drift probe closes that: it asks the catalog which entities have a view-only
337
554
  // column with no EntityField and unions those in, so recovery is a normal run.
555
+ // Layered entities whose inner view was rebuilt this run are added as well: STEP 2(f) just
556
+ // refreshed their outer view, which can now expose columns that need EntityField rows.
338
557
  const driftEntities = configInfo.forceRegeneration?.enabled
339
558
  ? []
340
559
  : await manageMD.FindVirtualFieldDriftEntities(pool, configInfo.excludeSchemas);
@@ -344,6 +563,7 @@ export class SQLCodeGenBase {
344
563
  ...ManageMetadataBase.newEntityList,
345
564
  ...ManageMetadataBase.modifiedEntityList,
346
565
  ...driftEntities,
566
+ ...this.layeredEntitiesWithLoggedInnerView,
347
567
  ])];
348
568
  StartSpinner('Managing entity fields metadata...');
349
569
  if (!await manageMD.manageEntityFields(pool, configInfo.excludeSchemas, true, true, currentUser, false, false, pass2EntityFilter)) {
@@ -354,6 +574,11 @@ export class SQLCodeGenBase {
354
574
  SucceedSpinner('Entity fields metadata updated');
355
575
  }
356
576
  // no logStatus/timer for this because manageEntityFields() has its own internal logging for this including the total, so it is redundant to log it here
577
+ // STEP 3.1 - stale One To Many relationships (#2071). Runs after Pass 2's unscoped field prune,
578
+ // so the fields of dropped FK columns are gone. Report-only unless cleanupStaleRelationships is set.
579
+ if (!await this.CleanupStaleRelationships(pool, manageMD)) {
580
+ overallSuccess = false;
581
+ }
357
582
  // STEP 3.5 - Late-phase view regeneration
358
583
  // Some late-phase changes (e.g., SupportsGeoCoding toggled during advanced generation)
359
584
  // affect view structure but happen AFTER views were already generated in Step 2.
@@ -421,6 +646,7 @@ export class SQLCodeGenBase {
421
646
  // STEP 4.5 - Emit sp_refreshview for modified custom base view entities into the
422
647
  // migration log file so other environments pick up schema changes automatically.
423
648
  this.emitCustomBaseViewRefreshes();
649
+ await this.validateAlternateBaseViewsForEntities(pool, includedEntities);
424
650
  // STEP 5 - execute any custom SQL scripts that should run afterwards
425
651
  StartSpinner('Running post-generation SQL scripts...');
426
652
  const step5StartTime = new Date();
@@ -437,6 +663,8 @@ export class SQLCodeGenBase {
437
663
  // now - we need to tell our metadata object to refresh itself
438
664
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
439
665
  await md.Refresh();
666
+ // Advisory only: an out-of-scope IS-A child's view is another app's to regenerate.
667
+ await this.WarnOnOutOfScopeISAChildDrift(pool, md.Entities, configInfo.excludeSchemas ?? []);
440
668
  return overallSuccess;
441
669
  }
442
670
  catch (err) {
@@ -713,6 +941,26 @@ export class SQLCodeGenBase {
713
941
  async generateAndExecuteEntitySQLToSeparateFiles(options) {
714
942
  return this.GenerateAndExecuteEntitySQLToSeparateFiles(options);
715
943
  }
944
+ /**
945
+ * Finds stale One To Many EntityRelationship rows among in-scope entities and, when the
946
+ * `cleanupStaleRelationships` config option is set, deletes them; otherwise each one is logged as a
947
+ * warning (#2071). Refreshes the global metadata only when rows were deleted, so the late-phase
948
+ * regeneration that follows sees the current relationships.
949
+ * @returns false when the cleanup failed
950
+ */
951
+ async CleanupStaleRelationships(pool, manageMD) {
952
+ const dryRun = configInfo.cleanupStaleRelationships !== true;
953
+ if (!await manageMD.CleanupStaleEntityRelationships(pool, configInfo.excludeSchemas ?? [], { DryRun: dryRun })) {
954
+ logError('Failed to check for stale entity relationships');
955
+ return false;
956
+ }
957
+ if (manageMD.StaleRelationshipsRemoved > 0) {
958
+ logStatus(` Removed ${manageMD.StaleRelationshipsRemoved} stale entity relationship(s); refreshing metadata`);
959
+ const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
960
+ await md.Refresh();
961
+ }
962
+ return true;
963
+ }
716
964
  DeleteGeneratedEntityFiles(directory, entities) {
717
965
  try {
718
966
  // for the schemas associated with the specified entities, clean out all the generated files
@@ -785,12 +1033,17 @@ export class SQLCodeGenBase {
785
1033
  logError(`Phased execution for ${options.entity.SchemaName}.${options.entity.Name} failed in phase "${where}": ${phaseResult.error?.message ?? '(no message)'}`);
786
1034
  return { Success: false, Files: files };
787
1035
  }
1036
+ await this.validateAlternateBaseViews(options.pool, options.entity);
788
1037
  return { Success: true, Files: files };
789
1038
  }
790
1039
  // Fallback: original monolithic path (SQL Server; also the path when
791
1040
  // `onlyPermissions` is set — then we just want the permissions SQL).
1041
+ const execSuccess = await this.SQLUtilityObject.executeSQLScript(options.pool, sql + "\n\nGO\n\n" + permissionsSQL, true);
1042
+ if (execSuccess && !options.onlyPermissions) {
1043
+ await this.validateAlternateBaseViews(options.pool, options.entity);
1044
+ }
792
1045
  return {
793
- Success: await this.SQLUtilityObject.executeSQLScript(options.pool, sql + "\n\nGO\n\n" + permissionsSQL, true),
1046
+ Success: execSuccess,
794
1047
  Files: files
795
1048
  };
796
1049
  }
@@ -847,6 +1100,28 @@ export class SQLCodeGenBase {
847
1100
  const crudDeleteSQL = entity.AllowDeleteAPI && entity.spDeleteGenerated && !entity.VirtualEntity
848
1101
  ? await this.generateSPDelete(entity, pool)
849
1102
  : '';
1103
+ // Full-text search DDL. Without its own phase the generated
1104
+ // *.fulltext.generated.sql is written to disk and then never executed on
1105
+ // any provider that implements executeEntityPhased — nothing in the
1106
+ // phase list carried it. The search objects were therefore absent while
1107
+ // applyPermissions still GRANTed EXECUTE on the search function, and the
1108
+ // resulting `function does not exist` failed the whole CodeGen run.
1109
+ // Generated here (not in the provider) because building it needs the
1110
+ // internal generators and a pool round trip for the PK index name.
1111
+ let ftsSQL = '';
1112
+ if (entity.FullTextSearchEnabled && !entity.VirtualEntity) {
1113
+ try {
1114
+ const ft = await this.GenerateEntityFullTextSearchSQL(pool, entity);
1115
+ ftsSQL = ft.sql;
1116
+ }
1117
+ catch (e) {
1118
+ return {
1119
+ success: false,
1120
+ phase: 'fulltext-generate',
1121
+ error: e instanceof Error ? e : new Error(String(e)),
1122
+ };
1123
+ }
1124
+ }
850
1125
  return this._dbProvider.executeEntityPhased({
851
1126
  entity,
852
1127
  tvfSQL,
@@ -854,6 +1129,7 @@ export class SQLCodeGenBase {
854
1129
  crudCreateSQL,
855
1130
  crudUpdateSQL,
856
1131
  crudDeleteSQL,
1132
+ ftsSQL,
857
1133
  viewPermSQL: viewPieces.viewPermSQL,
858
1134
  willRegenerate,
859
1135
  });
@@ -1005,6 +1281,11 @@ export class SQLCodeGenBase {
1005
1281
  // Normalize whitespace for fair comparison: collapse runs of whitespace to single space
1006
1282
  return body.replace(/\s+/g, ' ').trim();
1007
1283
  }
1284
+ /**
1285
+ * Writes generated SQL to the migration log (and the temp batch executed on SQL Server) when the
1286
+ * entity is new/modified, a force-regeneration rule matches, or `forceLog` is set. Returns whether
1287
+ * the SQL was logged.
1288
+ */
1008
1289
  logSQLForNewOrModifiedEntity(entity, sql, description, logSql = false, forceLog = false) {
1009
1290
  // Check if we should log this SQL
1010
1291
  let shouldLog = forceLog;
@@ -1061,6 +1342,7 @@ export class SQLCodeGenBase {
1061
1342
  TempBatchFile.appendToTempBatchFile(sql, entity.SchemaName);
1062
1343
  }
1063
1344
  LogIf(configInfo.verboseOutput, `SQL Generated for ${entity.Name}: ${description}`);
1345
+ return shouldLog;
1064
1346
  }
1065
1347
  /**
1066
1348
  * Emits sp_refreshview statements into the migration log file for modified custom base view
@@ -1079,6 +1361,96 @@ export class SQLCodeGenBase {
1079
1361
  const refreshSQL = this.buildCustomBaseViewRefreshSQL(qualifyingEntities);
1080
1362
  SQLLogging.appendToSQLLogFile(refreshSQL, 'Refresh custom base views for modified entities so schema changes are picked up');
1081
1363
  }
1364
+ /**
1365
+ * Executes the custom base view refresh ({@link buildCustomBaseViewRefreshSQL}: inner view, then
1366
+ * the guarded outer view, then its rebind and alternate views) against the live database for
1367
+ * EVERY included entity whose base view is application-owned, and writes the refresh for the
1368
+ * entities whose views changed this run into the migration log.
1369
+ *
1370
+ * Runs right after STEP 2(e), so the outer views expose the columns the regenerated inner views
1371
+ * now have before STEP 3 compares EntityField rows against them (#4336). Every entity is
1372
+ * attempted; failures are logged together and make the step return `false`.
1373
+ *
1374
+ * Only the entities on the new/modified lists, plus layered entities whose inner view was logged
1375
+ * this run, go into the migration log. Logging every custom view on every run would make a
1376
+ * capture non-empty when nothing changed.
1377
+ */
1378
+ async RefreshCustomBaseViewsLive(pool, includedEntities) {
1379
+ if (!this._dbProvider.NeedsViewRefresh) {
1380
+ return true; // PostgreSQL rebinds layered views in its phased executor
1381
+ }
1382
+ const targets = this.getCustomBaseViewEntitiesForLiveRefresh(includedEntities);
1383
+ if (targets.length === 0) {
1384
+ return true;
1385
+ }
1386
+ const failures = [];
1387
+ for (const entity of targets) {
1388
+ const refreshSQL = this.buildCustomBaseViewRefreshSQL([entity]);
1389
+ if (refreshSQL.trim().length === 0) {
1390
+ continue;
1391
+ }
1392
+ try {
1393
+ await pool.query(refreshSQL);
1394
+ }
1395
+ catch (e) {
1396
+ failures.push(`${entity.SchemaName}.${entity.BaseView} (${entity.Name}): ${e instanceof Error ? e.message : String(e)}`);
1397
+ }
1398
+ }
1399
+ // A layered entity whose refresh already follows its inner view in the log is not logged again.
1400
+ const toLog = targets.filter(e => this.shouldLogCustomBaseViewRefresh(e) && !this.layeredEntitiesWithInlineRefresh.has(e.Name));
1401
+ if (toLog.length > 0) {
1402
+ await SQLLogging.AppendToSQLLogFile(this.buildCustomBaseViewRefreshSQL(toLog), 'Refresh custom base views before entity field sync so new columns are not pruned');
1403
+ }
1404
+ if (failures.length > 0) {
1405
+ logError(`Custom base view refresh failed for ${failures.length} of ${targets.length} view(s):\n${failures.map(f => ` - ${f}`).join('\n')}`);
1406
+ return false;
1407
+ }
1408
+ return true;
1409
+ }
1410
+ /**
1411
+ * Included entities whose base view is application-owned (fully custom or layered), that have a
1412
+ * base view, are not virtual or externally sourced, and are in the custom-view refresh scope.
1413
+ */
1414
+ getCustomBaseViewEntitiesForLiveRefresh(includedEntities) {
1415
+ return includedEntities.filter(e => !e.BaseViewGenerated &&
1416
+ e.IncludeInAPI &&
1417
+ !e.VirtualEntity &&
1418
+ !e.ExternalDataSourceID &&
1419
+ !!e.BaseView &&
1420
+ EntityInCustomBaseViewRefreshScope(e.SchemaName, configInfo.excludeSchemas ?? [], configInfo.includeSchemas));
1421
+ }
1422
+ /**
1423
+ * Writes the layered entity's view refresh ({@link buildCustomBaseViewRefreshSQL}: inner view,
1424
+ * then the guarded outer view, its rebind and alternate views) into the migration log AND the
1425
+ * temp batch STEP 2(e) executes, right after the inner view and before the entity's CRUD routines
1426
+ * (#4927). The application-owned outer view selects `g.*`, and SQL Server freezes that column list
1427
+ * when the view is created; when the inner view's columns change, the routines that read the
1428
+ * outer view fail to compile until it is refreshed. STEP 2(f) refreshes the outer view too, but
1429
+ * only after the batch has run, which is too late for the routines in it.
1430
+ *
1431
+ * Called only when the inner view was logged, whether or not the entity is on the new/modified
1432
+ * lists. No-op on platforms that rebind views themselves (PostgreSQL's phased executor).
1433
+ */
1434
+ logLayeredOuterViewRefresh(entity) {
1435
+ if (!this._dbProvider.NeedsViewRefresh || !entity.HasLayeredBaseView || !entity.BaseView ||
1436
+ entity.VirtualEntity || entity.ExternalDataSourceID) {
1437
+ return;
1438
+ }
1439
+ const refreshSQL = this.buildCustomBaseViewRefreshSQL([entity]);
1440
+ if (refreshSQL.trim().length === 0) {
1441
+ return;
1442
+ }
1443
+ // Closed with its own batch separator: the migration log appends units without one, and the
1444
+ // unit that follows may start with a statement that must open its batch.
1445
+ this.logSQLForNewOrModifiedEntity(entity, `${refreshSQL}\n${this._dbProvider.BatchSeparator}`, `Refresh layered base view for ${entity.Name} after its inner view changed`, true, true);
1446
+ this.layeredEntitiesWithInlineRefresh.add(entity.Name);
1447
+ }
1448
+ /** True when this run's migration log must carry the entity's custom base view refresh. */
1449
+ shouldLogCustomBaseViewRefresh(entity) {
1450
+ return ManageMetadataBase.newEntityList.includes(entity.Name) ||
1451
+ ManageMetadataBase.modifiedEntityList.includes(entity.Name) ||
1452
+ this.layeredEntitiesWithLoggedInnerView.has(entity.Name);
1453
+ }
1082
1454
  /**
1083
1455
  * Returns entities from the modified and new entity lists that have custom base views
1084
1456
  * (BaseViewGenerated === false), are included in the API, and are not virtual.
@@ -1115,8 +1487,9 @@ export class SQLCodeGenBase {
1115
1487
  return entities
1116
1488
  .map(e => {
1117
1489
  const outer = this._dbProvider.generateViewRefreshSQL(e.SchemaName, e.BaseView);
1490
+ const altSteps = this.getAlternateBaseViewRefreshStatements(e);
1118
1491
  if (!e.HasLayeredBaseView) {
1119
- return outer; // fully custom — one view, and it is a standing prerequisite
1492
+ return [outer, ...altSteps].filter((s) => s && s.trim().length > 0).join('\n'); // fully custom — one view, and it is a standing prerequisite
1120
1493
  }
1121
1494
  const inner = this._dbProvider.generateViewRefreshSQL(e.SchemaName, e.GeneratedViewName);
1122
1495
  const rebind = this._dbProvider.generateLayeredOuterRebindSQL(e);
@@ -1126,7 +1499,7 @@ export class SQLCodeGenBase {
1126
1499
  const rebindSql = rebind.trim().length > 0
1127
1500
  ? this.guardOnApplicationOwnedView(e, rebind.trim())
1128
1501
  : '';
1129
- return [inner, outerSql, rebindSql].filter((s) => s && s.trim().length > 0).join('\n');
1502
+ return [inner, outerSql, rebindSql, ...altSteps].filter((s) => s && s.trim().length > 0).join('\n');
1130
1503
  })
1131
1504
  .join('\n');
1132
1505
  }
@@ -1226,7 +1599,11 @@ export class SQLCodeGenBase {
1226
1599
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('view', options.entity.SchemaName, options.entity.GeneratedViewName, false, true));
1227
1600
  if (options.writeFiles) {
1228
1601
  this.writeFileIfChanged(filePath, s);
1229
- this.logSQLForNewOrModifiedEntity(options.entity, s, `Base View SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, baseViewChanged);
1602
+ const viewLogged = this.logSQLForNewOrModifiedEntity(options.entity, s, `Base View SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, baseViewChanged);
1603
+ if (viewLogged && options.entity.HasLayeredBaseView) {
1604
+ this.layeredEntitiesWithLoggedInnerView.add(options.entity.Name);
1605
+ this.logLayeredOuterViewRefresh(options.entity);
1606
+ }
1230
1607
  files.push(filePath);
1231
1608
  }
1232
1609
  sRet += s + '\n' + this._dbProvider.BatchSeparator + '\n';
@@ -1239,9 +1616,10 @@ export class SQLCodeGenBase {
1239
1616
  // pass. This copy is what gets written to the permissions FILE and logged into the
1240
1617
  // migration, so leaving it unguarded would fail on other environments even though the
1241
1618
  // executed copy (generateCustomBaseViewRefreshAndPermissions, below) is guarded.
1242
- const permBody = options.entity.HasLayeredBaseView && rawPermBody.trim().length > 0
1619
+ const altPermBody = this.generateAlternateBaseViewsPermissionsSQL(options.entity);
1620
+ const permBody = (options.entity.HasLayeredBaseView && rawPermBody.trim().length > 0
1243
1621
  ? '\n' + this.guardOnApplicationOwnedView(options.entity, rawPermBody.trim())
1244
- : rawPermBody;
1622
+ : rawPermBody) + altPermBody;
1245
1623
  const s = permHeader + permBody;
1246
1624
  if (s.length > 0)
1247
1625
  permissionsSQL += s + '\n' + this._dbProvider.BatchSeparator + '\n';
@@ -1263,6 +1641,8 @@ export class SQLCodeGenBase {
1263
1641
  // CREATE SP
1264
1642
  if (options.entity.AllowCreateAPI && !options.entity.VirtualEntity) {
1265
1643
  const spName = this.GetSPName(options.entity, SPType.Create);
1644
+ // Recomputed with the generated body below, so drift from the live definition counts too.
1645
+ let routineForceLog = this.forceLogForRoutine(options.entity, spName, baseViewChanged);
1266
1646
  // Only generate if spCreateGenerated is true (respects custom SPs where it's false)
1267
1647
  // forceRegeneration only forces regeneration of SPs where spCreateGenerated=true
1268
1648
  if (!options.onlyPermissions && options.entity.spCreateGenerated) {
@@ -1271,7 +1651,8 @@ export class SQLCodeGenBase {
1271
1651
  if (options.writeFiles) {
1272
1652
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, false, true));
1273
1653
  this.writeFileIfChanged(filePath, s);
1274
- this.logSQLForNewOrModifiedEntity(options.entity, s, `spCreate SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, this.forceLogForRoutine(options.entity, spName, baseViewChanged));
1654
+ routineForceLog = this.forceLogForRoutine(options.entity, spName, baseViewChanged, s);
1655
+ this.logSQLForNewOrModifiedEntity(options.entity, s, `spCreate SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
1275
1656
  files.push(filePath);
1276
1657
  }
1277
1658
  sRet += s + '\n' + this._dbProvider.BatchSeparator + '\n';
@@ -1282,7 +1663,7 @@ export class SQLCodeGenBase {
1282
1663
  if (options.writeFiles) {
1283
1664
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, true, true));
1284
1665
  this.writeFileIfChanged(filePath, s);
1285
- this.logSQLForNewOrModifiedEntity(options.entity, s, `spCreate Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, this.forceLogForRoutine(options.entity, spName, baseViewChanged));
1666
+ this.logSQLForNewOrModifiedEntity(options.entity, s, `spCreate Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
1286
1667
  files.push(filePath);
1287
1668
  }
1288
1669
  // now, append the permissions to the return string IF we did NOT generate the proc - because if we generated the proc, that
@@ -1293,6 +1674,8 @@ export class SQLCodeGenBase {
1293
1674
  // UPDATE SP
1294
1675
  if (options.entity.AllowUpdateAPI && !options.entity.VirtualEntity) {
1295
1676
  const spName = this.GetSPName(options.entity, SPType.Update);
1677
+ // Recomputed with the generated body below, so drift from the live definition counts too.
1678
+ let routineForceLog = this.forceLogForRoutine(options.entity, spName, baseViewChanged);
1296
1679
  // Only generate if spUpdateGenerated is true (respects custom SPs where it's false)
1297
1680
  // forceRegeneration only forces regeneration of SPs where spUpdateGenerated=true
1298
1681
  if (!options.onlyPermissions && options.entity.spUpdateGenerated) {
@@ -1301,7 +1684,8 @@ export class SQLCodeGenBase {
1301
1684
  if (options.writeFiles) {
1302
1685
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, false, true));
1303
1686
  this.writeFileIfChanged(filePath, s);
1304
- this.logSQLForNewOrModifiedEntity(options.entity, s, `spUpdate SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, this.forceLogForRoutine(options.entity, spName, baseViewChanged));
1687
+ routineForceLog = this.forceLogForRoutine(options.entity, spName, baseViewChanged, s);
1688
+ this.logSQLForNewOrModifiedEntity(options.entity, s, `spUpdate SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
1305
1689
  files.push(filePath);
1306
1690
  }
1307
1691
  sRet += s + '\n' + this._dbProvider.BatchSeparator + '\n';
@@ -1312,7 +1696,7 @@ export class SQLCodeGenBase {
1312
1696
  if (options.writeFiles) {
1313
1697
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, true, true));
1314
1698
  this.writeFileIfChanged(filePath, s);
1315
- this.logSQLForNewOrModifiedEntity(options.entity, s, `spUpdate Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, this.forceLogForRoutine(options.entity, spName, baseViewChanged));
1699
+ this.logSQLForNewOrModifiedEntity(options.entity, s, `spUpdate Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
1316
1700
  files.push(filePath);
1317
1701
  }
1318
1702
  // now, append the permissions to the return string IF we did NOT generate the proc - because if we generated the proc, that
@@ -1323,6 +1707,8 @@ export class SQLCodeGenBase {
1323
1707
  // DELETE SP
1324
1708
  if (options.entity.AllowDeleteAPI && !options.entity.VirtualEntity) {
1325
1709
  const spName = this.GetSPName(options.entity, SPType.Delete);
1710
+ // Recomputed with the generated body below, so drift from the live definition counts too.
1711
+ let routineForceLog = this.forceLogForRoutine(options.entity, spName, baseViewChanged);
1326
1712
  // Only generate if spDeleteGenerated is true (respects custom SPs where it's false)
1327
1713
  // OR if this entity has cascade delete dependencies that require regeneration
1328
1714
  // forceRegeneration only forces regeneration of SPs where spDeleteGenerated=true
@@ -1337,7 +1723,8 @@ export class SQLCodeGenBase {
1337
1723
  if (options.writeFiles) {
1338
1724
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, false, true));
1339
1725
  this.writeFileIfChanged(filePath, s);
1340
- this.logSQLForNewOrModifiedEntity(options.entity, s, `spDelete SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, this.forceLogForRoutine(options.entity, spName, baseViewChanged));
1726
+ routineForceLog = this.forceLogForRoutine(options.entity, spName, baseViewChanged, s);
1727
+ this.logSQLForNewOrModifiedEntity(options.entity, s, `spDelete SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
1341
1728
  files.push(filePath);
1342
1729
  }
1343
1730
  sRet += s + '\n' + this._dbProvider.BatchSeparator + '\n';
@@ -1348,7 +1735,7 @@ export class SQLCodeGenBase {
1348
1735
  if (options.writeFiles) {
1349
1736
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, true, true));
1350
1737
  this.writeFileIfChanged(filePath, s);
1351
- this.logSQLForNewOrModifiedEntity(options.entity, s, `spDelete Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, this.forceLogForRoutine(options.entity, spName, baseViewChanged));
1738
+ this.logSQLForNewOrModifiedEntity(options.entity, s, `spDelete Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
1352
1739
  files.push(filePath);
1353
1740
  }
1354
1741
  // now, append the permissions to the return string IF we did NOT generate the proc - because if we generated the proc, that
@@ -1478,10 +1865,62 @@ export class SQLCodeGenBase {
1478
1865
  }
1479
1866
  return !selectsFromBaseView;
1480
1867
  }
1481
- forceLogForRoutine(entity, routineName, baseViewChanged) {
1868
+ /**
1869
+ * Returns true when the live definition of the entity's spCreate / spUpdate / spDelete differs
1870
+ * from `generatedSQL`, the body CodeGen generated for it this run, after both are normalized by
1871
+ * the provider (comments, header, DROP batch, `GO` and whitespace removed).
1872
+ *
1873
+ * This catches drift that never reaches the new/modified entity lists: a column default or type
1874
+ * synced by `R__RefreshMetadata` before CodeGen ran (#5636), or a cascade target whose column a
1875
+ * migration dropped together with its EntityField row (#3343). Returns false when the live
1876
+ * definitions were not loaded (PostgreSQL, or the catalog query failed), when the routine is
1877
+ * missing (handled by {@link isRoutineMissing}), or when either side cannot be normalized.
1878
+ */
1879
+ isRoutineDefinitionDrifted(entity, routineName, generatedSQL) {
1880
+ if (!this.existingRoutineDefinitions || !generatedSQL) {
1881
+ return false;
1882
+ }
1883
+ const lowerRoutine = routineName.toLowerCase();
1884
+ const crudNames = [SPType.Create, SPType.Update, SPType.Delete].map(t => this.GetSPName(entity, t).toLowerCase());
1885
+ if (!crudNames.includes(lowerRoutine)) {
1886
+ return false;
1887
+ }
1888
+ const key = `${entity.SchemaName}.${routineName}`.toLowerCase();
1889
+ const liveDefinition = this.existingRoutineDefinitions.get(key);
1890
+ if (!liveDefinition) {
1891
+ return false;
1892
+ }
1893
+ const generated = this._dbProvider.NormalizeRoutineDefinitionForComparison(generatedSQL);
1894
+ const live = this._dbProvider.NormalizeRoutineDefinitionForComparison(liveDefinition);
1895
+ if (generated === null || live === null) {
1896
+ return false;
1897
+ }
1898
+ if (generated !== live) {
1899
+ this.driftedRoutines.add(key);
1900
+ return true;
1901
+ }
1902
+ return false;
1903
+ }
1904
+ /**
1905
+ * Whether a CRUD routine's SQL must be logged and executed regardless of the new/modified lists.
1906
+ * `generatedSQL`, when given, is the body generated this run and enables the live-definition drift
1907
+ * check ({@link isRoutineDefinitionDrifted}).
1908
+ */
1909
+ forceLogForRoutine(entity, routineName, baseViewChanged, generatedSQL) {
1482
1910
  return baseViewChanged ||
1483
1911
  this.isRoutineMissing(entity.SchemaName, routineName) ||
1484
- this.isRoutineSaveReturnModeChanged(entity, routineName);
1912
+ this.isRoutineSaveReturnModeChanged(entity, routineName) ||
1913
+ (generatedSQL !== undefined && this.isRoutineDefinitionDrifted(entity, routineName, generatedSQL));
1914
+ }
1915
+ /** Logs the CRUD routines that were regenerated because their live definition had drifted. */
1916
+ reportDriftedRoutines() {
1917
+ if (this.driftedRoutines.size === 0) {
1918
+ return;
1919
+ }
1920
+ const names = [...this.driftedRoutines].sort();
1921
+ const shown = names.slice(0, 20).map(n => ` - ${n}`).join('\n');
1922
+ const more = names.length > 20 ? `\n … and ${names.length - 20} more` : '';
1923
+ logStatus(`Regenerated ${names.length} CRUD routine(s) whose live definition differed from the generated body:\n${shown}${more}`);
1485
1924
  }
1486
1925
  GetEntityPermissionFileNames(entity) {
1487
1926
  const files = [];
@@ -1557,26 +1996,17 @@ export class SQLCodeGenBase {
1557
1996
  throw new Error(`FullTextIndexGenerated is true for entity ${entity.Name}, but no fields are marked as FullTextSearchEnabled`);
1558
1997
  if (entity.FullTextSearchFunctionGenerated && searchFields.length === 0)
1559
1998
  throw new Error(`FullTextSearchFunctionGenerated is true for entity ${entity.Name}, but no fields are marked as FullTextSearchEnabled`);
1560
- // Get the primary key index name (needed for full text index)
1999
+ // Get the primary key index name — but ONLY for a provider whose full-text DDL actually
2000
+ // embeds it. `GetEntityPrimaryKeyIndexName` THROWS when the table has no PRIMARY KEY
2001
+ // constraint, and on PostgreSQL that is a legitimate shape: MJ's primary key can be a soft
2002
+ // key declared in metadata only. Asking unconditionally turned a SQL-Server requirement
2003
+ // (`CREATE FULLTEXT INDEX … KEY INDEX <name>`) into a precondition that no such table can
2004
+ // satisfy, so full-text search could never be generated for it — on a platform that builds
2005
+ // a GIN index over a tsvector and never looks at the name.
1561
2006
  let primaryKeyIndexName = '';
1562
- if (entity.FullTextIndexGenerated) {
2007
+ if (entity.FullTextIndexGenerated && this._dbProvider.FullTextIndexNeedsPrimaryKeyIndexName) {
1563
2008
  primaryKeyIndexName = await this.GetEntityPrimaryKeyIndexName(pool, entity);
1564
2009
  }
1565
- // If the function name is not set, save it to the DB
1566
- const functionName = entity.FullTextSearchFunction && entity.FullTextSearchFunction.length > 0
1567
- ? entity.FullTextSearchFunction
1568
- : `fnSearch${entity.CodeName}`;
1569
- if (entity.FullTextSearchFunctionGenerated && (!entity.FullTextSearchFunction || entity.FullTextSearchFunction.length === 0)) {
1570
- const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
1571
- const u = UserCache.Instance.Users[0];
1572
- if (!u)
1573
- throw new Error('Could not find the first user in the cache, cant generate the full text search function without a user');
1574
- const e = await md.GetEntityObject('MJ: Entities', u);
1575
- await e.Load(entity.ID);
1576
- e.FullTextSearchFunction = functionName;
1577
- if (!await e.Save())
1578
- throw new Error(`Could not update the FullTextSearchFunction for entity ${entity.Name}`);
1579
- }
1580
2010
  // Say what enabling full-text search costs, at the one moment the person who enabled it is
1581
2011
  // still in the room. The objects below are charged on every write to the table from here on
1582
2012
  // and are not removed by turning the entity's flags back off.
@@ -1584,8 +2014,48 @@ export class SQLCodeGenBase {
1584
2014
  if (costDisclosure) {
1585
2015
  LogWarning(` > ${costDisclosure}`);
1586
2016
  }
1587
- // Delegate SQL generation to the provider
2017
+ // Delegate SQL generation to the provider FIRST — the provider owns the
2018
+ // platform's naming scheme, and the name it used is what actually exists
2019
+ // in the database. PostgreSQL creates `fn_search_<snake(BaseTable)>`;
2020
+ // deriving the name here instead (the SQL Server `fnSearch<CodeName>`
2021
+ // form) recorded a function that never exists on PG, and runtime search
2022
+ // then called a name that was never created.
1588
2023
  const result = this._dbProvider.generateFullTextSearch(entity, searchFields, primaryKeyIndexName);
2024
+ const functionName = result.functionName && result.functionName.length > 0
2025
+ ? result.functionName
2026
+ : (entity.FullTextSearchFunction && entity.FullTextSearchFunction.length > 0
2027
+ ? entity.FullTextSearchFunction
2028
+ : `fnSearch${entity.CodeName}`);
2029
+ // Persist the provider-derived name whenever the stored one DIFFERS, not
2030
+ // only when it is empty. An empty-only condition can never correct a row
2031
+ // stamped with the wrong platform's scheme by an earlier run, because the
2032
+ // wrong name is still a non-empty one.
2033
+ if (entity.FullTextSearchFunctionGenerated && entity.FullTextSearchFunction !== functionName) {
2034
+ const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
2035
+ // Guard the ARRAY, not only its first element. An unrefreshed cache holds `[]` today, but
2036
+ // a holder carrying an older GenericDatabaseProvider leaves `_users` undefined, and
2037
+ // `.Users[0]` against that throws a bare `TypeError: Cannot read properties of undefined
2038
+ // (reading '0')` BEFORE the guard below can say anything at all. The declared type is
2039
+ // widened here because the runtime value is the thing being guarded.
2040
+ //
2041
+ // Fatal on purpose: the write-back is the ONLY thing that records the function name.
2042
+ // Skipping it would leave `Entity.FullTextSearchFunction` empty while the DDL still
2043
+ // creates the function, so CodeGen would report success and runtime search would look
2044
+ // for a name no row carries.
2045
+ const cachedUsers = UserCache.Instance.Users;
2046
+ const u = cachedUsers?.[0];
2047
+ if (!u)
2048
+ throw new Error(`Cannot record the full-text search function name for entity ${entity.Name}: the CodeGen user cache holds no users, ` +
2049
+ `so there is no user to write __mj.Entity.FullTextSearchFunction as. The cache is populated by the provider's ` +
2050
+ `SetupDataSource via UserCache.Instance.Refresh() — verify that it ran for this connection and that __mj.User has ` +
2051
+ `at least one row. To complete this run without the write-back, set FullTextSearchFunction to '${functionName}' on ` +
2052
+ `entity ${entity.Name}; that is the name CodeGen is trying to record, so the write-back becomes unnecessary.`);
2053
+ const e = await md.GetEntityObject('MJ: Entities', u);
2054
+ await e.Load(entity.ID);
2055
+ e.FullTextSearchFunction = functionName;
2056
+ if (!await e.Save())
2057
+ throw new Error(`Could not update the FullTextSearchFunction for entity ${entity.Name}`);
2058
+ }
1589
2059
  // Add permissions if function was generated
1590
2060
  if (entity.FullTextSearchFunctionGenerated) {
1591
2061
  result.sql += this.generateFullTextSearchFunctionPermissions(entity, functionName) + '\n\n' + this._dbProvider.BatchSeparator + '\n';
@@ -1681,9 +2151,18 @@ export class SQLCodeGenBase {
1681
2151
  /**
1682
2152
  * Detects self-referential foreign keys in an entity (e.g., ParentTaskID pointing back to Task table)
1683
2153
  * Returns array of field info objects representing recursive relationships
2154
+ *
2155
+ * A column that IS the entity's own primary key is excluded. It can carry a self-referencing
2156
+ * `RelatedEntityID` — FK auto-detection matches a `<prefix>_key`-style column to its own table
2157
+ * and does not exclude that table's own key — but "my parent is me" is not a hierarchy. The
2158
+ * generated recursive CTE then joins the key to itself and selects the same column three times,
2159
+ * which the database rejects outright: 15 entities on one Postgres instance failed to compile
2160
+ * with `column reference "tea_key" is ambiguous`. Nothing downstream can recover from that, and
2161
+ * a real hierarchy always parents on a DIFFERENT column, so excluding the key loses nothing.
1684
2162
  */
1685
2163
  detectRecursiveForeignKeys(entity) {
1686
2164
  const hierarchyFKs = entity.Fields.filter(field => field.RelatedEntityID != null &&
2165
+ !field.IsPrimaryKey &&
1687
2166
  UUIDsEqual(field.RelatedEntityID, entity.ID) &&
1688
2167
  !field.IsVirtual &&
1689
2168
  field.IsHierarchy === true);
@@ -1806,26 +2285,13 @@ export class SQLCodeGenBase {
1806
2285
  /**
1807
2286
  * Generates SELECT field expressions for IS-A parent entity columns.
1808
2287
  * Walks the ParentID chain upward, joining to each parent's base table, and includes
1809
- * non-PK, non-timestamp, non-virtual fields from each parent table.
2288
+ * the columns physically on each parent table ({@link InheritedParentColumns}).
1810
2289
  * Returns a string starting with ',\n' if there are parent fields, or '' if none.
1811
2290
  */
1812
2291
  generateParentEntityFieldSelects(entity) {
1813
- if (!entity.IsChildType)
1814
- return '';
1815
- const parentChain = entity.ParentChain;
1816
- if (parentChain.length === 0)
1817
- return '';
1818
- const fieldExpressions = [];
1819
- for (let i = 0; i < parentChain.length; i++) {
1820
- const parent = parentChain[i];
1821
- const alias = `__mj_isa_p${i + 1}`;
1822
- for (const field of parent.Fields) {
1823
- // Skip PKs (shared with child), timestamps, and virtual fields (view-computed)
1824
- if (field.IsPrimaryKey || field.Name.startsWith('__mj_') || field.IsVirtual)
1825
- continue;
1826
- fieldExpressions.push(` ${alias}.${this._dbProvider.Dialect.QuoteIdentifier(field.Name)}`);
1827
- }
1828
- }
2292
+ // Which parent columns qualify (PKs, __mj_ and view-only virtual fields are skipped;
2293
+ // computed columns are kept): see InheritedParentColumns.
2294
+ const fieldExpressions = InheritedParentColumns(entity).map(c => ` ${c.Alias}.${this._dbProvider.Dialect.QuoteIdentifier(c.Field.Name)}`);
1829
2295
  if (fieldExpressions.length === 0)
1830
2296
  return '';
1831
2297
  return ',\n' + fieldExpressions.join(',\n');
@@ -1899,14 +2365,15 @@ export class SQLCodeGenBase {
1899
2365
  // sites because generateBaseView concatenates this onto the view DDL and the phased
1900
2366
  // executor consumes it separately — both need it.
1901
2367
  const rawPermissions = this.generateViewPermissions(entity);
2368
+ const altPermissions = this.generateAlternateBaseViewsPermissionsSQL(entity);
1902
2369
  // The leading newline must stay OUTSIDE the guard. `generateViewPermissions` returns
1903
2370
  // "\nGRANT ..." and the view DDL it is concatenated onto ends in `GO`; wrapping the string
1904
2371
  // verbatim pulls that newline inside the sp_executesql literal and emits `GOIF OBJECT_ID`,
1905
2372
  // fusing the batch separator to the next statement. Non-layered entities keep the raw
1906
2373
  // string byte-for-byte so this cannot churn every other entity's generated SQL.
1907
- const permissions = entity.HasLayeredBaseView && rawPermissions.trim().length > 0
2374
+ const permissions = (entity.HasLayeredBaseView && rawPermissions.trim().length > 0
1908
2375
  ? '\n' + this.guardOnApplicationOwnedView(entity, rawPermissions.trim())
1909
- : rawPermissions;
2376
+ : rawPermissions) + altPermissions;
1910
2377
  // Detect recursive foreign keys and generate TVF joins and root field selects
1911
2378
  const recursiveFKs = this.detectRecursiveForeignKeys(entity);
1912
2379
  const rootFields = recursiveFKs.length > 0 ? this.generateRootFieldSelects(entity, recursiveFKs, classNameFirstChar) : '';
@@ -1923,8 +2390,16 @@ export class SQLCodeGenBase {
1923
2390
  rootFieldsSelect: rootFields,
1924
2391
  rootJoins: rootJoins,
1925
2392
  };
2393
+ let viewSQL = this._dbProvider.generateBaseView(context);
2394
+ if (!entity.HasLayeredBaseView && this._dbProvider.NeedsViewRefresh) {
2395
+ const altRefreshStatements = this.getAlternateBaseViewRefreshStatements(entity);
2396
+ if (altRefreshStatements.length > 0) {
2397
+ const separator = '\n' + this._dbProvider.BatchSeparator + '\n';
2398
+ viewSQL += separator + altRefreshStatements.join(separator);
2399
+ }
2400
+ }
1926
2401
  return {
1927
- viewSQL: this._dbProvider.generateBaseView(context),
2402
+ viewSQL,
1928
2403
  viewPermSQL: permissions,
1929
2404
  };
1930
2405
  }
@@ -1935,6 +2410,229 @@ export class SQLCodeGenBase {
1935
2410
  generateViewPermissions(entity) {
1936
2411
  return this._dbProvider.generateViewPermissions(entity);
1937
2412
  }
2413
+ /**
2414
+ * Validates that an alternate base view's `EffectiveSchemaName` and `ViewName`
2415
+ * (and its `ParentView`'s when present) are valid SQL identifiers before splicing
2416
+ * into generated DDL or catalog queries.
2417
+ */
2418
+ hasValidAlternateViewIdentifiers(entity, altView) {
2419
+ if (!IsValidSQLIdentifier(altView.EffectiveSchemaName) || !IsValidSQLIdentifier(altView.ViewName)) {
2420
+ logError(`[AlternateBaseView] Skipping alternate view '${altView.Name}' on entity '${entity.Name}': invalid SQL identifier '${altView.EffectiveSchemaName}.${altView.ViewName}'.`);
2421
+ return false;
2422
+ }
2423
+ if (altView.ParentView && (!IsValidSQLIdentifier(altView.ParentView.EffectiveSchemaName) || !IsValidSQLIdentifier(altView.ParentView.ViewName))) {
2424
+ logError(`[AlternateBaseView] Skipping alternate view '${altView.Name}' on entity '${entity.Name}': parent view has invalid SQL identifier '${altView.ParentView.EffectiveSchemaName}.${altView.ParentView.ViewName}'.`);
2425
+ return false;
2426
+ }
2427
+ return true;
2428
+ }
2429
+ /**
2430
+ * Returns all registered alternate base views with valid SQL identifiers for `entity`
2431
+ * (including `Status === 'Disabled'`), ordered topologically by `ParentID`.
2432
+ */
2433
+ getOrderedAllAlternateBaseViews(entity) {
2434
+ const views = (entity.AlternateBaseViews ?? []).filter((v) => this.hasValidAlternateViewIdentifiers(entity, v));
2435
+ return OrderAlternateBaseViewsTopologically(views);
2436
+ }
2437
+ /**
2438
+ * Returns usable (`Status !== 'Disabled'`) alternate base views for `entity`,
2439
+ * ordered topologically by `ParentID` so parent views precede derived child views.
2440
+ */
2441
+ getOrderedAlternateBaseViews(entity) {
2442
+ return this.getOrderedAllAlternateBaseViews(entity).filter((v) => v.Status !== 'Disabled');
2443
+ }
2444
+ /**
2445
+ * Builds guarded refresh/rebind statements for each registered alternate base view on `entity`
2446
+ * (including `Disabled` views so `Active` children of a `Disabled` parent and re-enabled views
2447
+ * never hold stale column metadata) in topological `ParentID` order.
2448
+ */
2449
+ getAlternateBaseViewRefreshStatements(entity) {
2450
+ if (entity.VirtualEntity) {
2451
+ return [];
2452
+ }
2453
+ const ordered = this.getOrderedAllAlternateBaseViews(entity);
2454
+ if (ordered.length === 0) {
2455
+ return [];
2456
+ }
2457
+ const statements = [];
2458
+ for (const altView of ordered) {
2459
+ const schema = altView.EffectiveSchemaName;
2460
+ const viewName = altView.ViewName;
2461
+ if (this._dbProvider.NeedsViewRefresh) {
2462
+ const refresh = this._dbProvider.generateViewRefreshSQL(schema, viewName);
2463
+ if (refresh.trim().length > 0) {
2464
+ statements.push(this._dbProvider.generateIfViewExistsSQL(schema, viewName, refresh.trim()));
2465
+ }
2466
+ }
2467
+ const innerViewName = altView.ParentView ? altView.ParentView.ViewName : entity.BaseView;
2468
+ const rebind = this._dbProvider.GenerateAlternateBaseViewRebindSQL(entity, schema, viewName, innerViewName);
2469
+ if (rebind.trim().length > 0) {
2470
+ statements.push(this._dbProvider.generateIfViewExistsSQL(schema, viewName, rebind.trim()));
2471
+ }
2472
+ }
2473
+ return statements;
2474
+ }
2475
+ /**
2476
+ * Generates guarded permission statements for each registered alternate base view on `entity`:
2477
+ * - Usable (`Active` / `Deprecated`) views receive `GenerateViewPermissionsForTarget` (REVOKE + GRANT SELECT + FLS DENY SELECT).
2478
+ * - `Disabled` views receive `GenerateDisabledViewRevokePermissionsForTarget` (REVOKE SELECT) so disabling a view revokes database read grants.
2479
+ */
2480
+ generateAlternateBaseViewsPermissionsSQL(entity) {
2481
+ const ordered = this.getOrderedAllAlternateBaseViews(entity);
2482
+ if (ordered.length === 0) {
2483
+ return '';
2484
+ }
2485
+ let sOutput = '';
2486
+ for (const altView of ordered) {
2487
+ const rawPerm = altView.Status === 'Disabled'
2488
+ ? this._dbProvider.GenerateDisabledViewRevokePermissionsForTarget(entity, altView.EffectiveSchemaName, altView.ViewName)
2489
+ : this._dbProvider.GenerateViewPermissionsForTarget(entity, altView.EffectiveSchemaName, altView.ViewName);
2490
+ if (rawPerm.trim().length > 0) {
2491
+ sOutput += '\n' + this._dbProvider.generateIfViewExistsSQL(altView.EffectiveSchemaName, altView.ViewName, rawPerm.trim());
2492
+ }
2493
+ }
2494
+ return sOutput;
2495
+ }
2496
+ /**
2497
+ * Warns about IS-A children outside this run's scope whose live view lacks a column their
2498
+ * in-scope parent's table now has (#4821). This run cannot regenerate those views: the child
2499
+ * belongs to another app, which must run CodeGen or ship a migration. Until it does, the child's
2500
+ * metadata (synced by that app's run) and its view disagree, and its saves fail.
2501
+ * Never fails the run; a failed catalog read is logged and ignored.
2502
+ */
2503
+ async WarnOnOutOfScopeISAChildDrift(pool, entities, excludeSchemas) {
2504
+ const children = OutOfScopeISAChildrenWithInScopeParent(entities, excludeSchemas);
2505
+ if (children.length === 0) {
2506
+ return [];
2507
+ }
2508
+ try {
2509
+ const esc = (s) => s.replace(/'/g, "''");
2510
+ const predicates = children.map(c => `(TABLE_SCHEMA = '${esc(c.SchemaName)}' AND TABLE_NAME = '${esc(c.GeneratedViewName)}')`);
2511
+ const sql = `SELECT TABLE_SCHEMA AS "TableSchema", TABLE_NAME AS "TableName", COLUMN_NAME AS "ColumnName"
2512
+ FROM INFORMATION_SCHEMA.COLUMNS
2513
+ WHERE ${predicates.join(' OR ')}`;
2514
+ const result = await pool.query(sql);
2515
+ const live = new Map();
2516
+ for (const row of result.recordset) {
2517
+ const key = `${row.TableSchema}.${row.TableName}`.toLowerCase();
2518
+ const cols = live.get(key) ?? new Set();
2519
+ cols.add(row.ColumnName.toLowerCase());
2520
+ live.set(key, cols);
2521
+ }
2522
+ const drift = FindOutOfScopeISAChildDrift(entities, excludeSchemas, live);
2523
+ for (const d of drift) {
2524
+ LogWarning(`IS-A child '${d.ChildName}' is outside this run's scope, and its view ${d.ChildSchema}.${d.ViewName} ` +
2525
+ `lacks column(s) its parent now has: ${d.MissingColumns.join(', ')}. ` +
2526
+ `Run CodeGen for schema '${d.ChildSchema}', or ship a migration there that regenerates the view; ` +
2527
+ `once the child's EntityField rows list the column, saves fail until the view has it.`);
2528
+ }
2529
+ return drift;
2530
+ }
2531
+ catch (e) {
2532
+ LogIf(configInfo.verboseOutput, `Could not check out-of-scope IS-A child views: ${e instanceof Error ? e.message : String(e)}`);
2533
+ return [];
2534
+ }
2535
+ }
2536
+ async validateAlternateBaseViewsForEntities(pool, entities) {
2537
+ if (!pool || typeof pool.query !== 'function') {
2538
+ return;
2539
+ }
2540
+ for (const entity of entities) {
2541
+ await this.validateAlternateBaseViews(pool, entity);
2542
+ }
2543
+ }
2544
+ /**
2545
+ * Audits each usable alternate base view on `entity` for column parity with `BaseView`,
2546
+ * catalog dependency on `BaseView` / `ParentView` (D10), and `CachePolicy = 'Default'`
2547
+ * safety (clock functions or external relation dependencies). Logs warnings via `LogWarning`.
2548
+ */
2549
+ async validateAlternateBaseViews(pool, entity) {
2550
+ if (!pool || typeof pool.query !== 'function') {
2551
+ return;
2552
+ }
2553
+ const ordered = this.getOrderedAlternateBaseViews(entity);
2554
+ if (ordered.length === 0) {
2555
+ return;
2556
+ }
2557
+ const baseViewColumns = entity.Fields.map((f) => f.Name);
2558
+ const registeredAltNames = new Set(this.getOrderedAllAlternateBaseViews(entity).map((v) => `${v.EffectiveSchemaName}.${v.ViewName}`.toLowerCase()));
2559
+ for (const altView of ordered) {
2560
+ await this.auditSingleAlternateBaseView(pool, entity, altView, baseViewColumns, registeredAltNames);
2561
+ }
2562
+ }
2563
+ async auditSingleAlternateBaseView(pool, entity, altView, baseViewColumns, registeredAltNames) {
2564
+ try {
2565
+ const facts = await this.fetchAlternateViewCatalogFacts(pool, entity, altView);
2566
+ const parentView = altView.ParentView;
2567
+ const warnings = EvaluateAlternateBaseViewParityAndSafety({
2568
+ entityName: entity.Name,
2569
+ entitySchemaName: entity.SchemaName,
2570
+ baseViewName: entity.BaseView,
2571
+ baseViewColumns,
2572
+ registeredAlternateViewNames: registeredAltNames,
2573
+ alternateView: {
2574
+ Name: altView.Name,
2575
+ EffectiveSchemaName: altView.EffectiveSchemaName,
2576
+ ViewName: altView.ViewName,
2577
+ CachePolicy: altView.CachePolicy,
2578
+ ParentView: parentView
2579
+ ? {
2580
+ Name: parentView.Name,
2581
+ EffectiveSchemaName: parentView.EffectiveSchemaName,
2582
+ ViewName: parentView.ViewName,
2583
+ }
2584
+ : undefined,
2585
+ },
2586
+ viewExists: facts.viewExists,
2587
+ viewColumns: facts.viewColumns,
2588
+ viewDefinition: facts.viewDefinition,
2589
+ dependencies: facts.dependencies,
2590
+ });
2591
+ for (const warning of warnings) {
2592
+ LogWarning(` ⚠️ ${warning}`);
2593
+ }
2594
+ }
2595
+ catch (e) {
2596
+ LogIf(configInfo.verboseOutput, `Could not audit alternate base view ${altView.Name} on ${entity.Name}: ${e}`);
2597
+ }
2598
+ }
2599
+ async fetchAlternateViewCatalogFacts(pool, entity, altView) {
2600
+ const colSQL = this._dbProvider.getViewColumnsSQL(altView.EffectiveSchemaName, altView.ViewName);
2601
+ const colResult = await pool.query(colSQL);
2602
+ const viewColumns = (colResult.recordset ?? [])
2603
+ .map((r) => String(r.FieldName ?? r.fieldname ?? ''))
2604
+ .filter((n) => n.length > 0);
2605
+ const viewExists = viewColumns.length > 0;
2606
+ let viewDefinition = null;
2607
+ let dependencies = [];
2608
+ if (viewExists) {
2609
+ try {
2610
+ const defSQL = this._dbProvider.getViewDefinitionSQL(altView.EffectiveSchemaName, altView.ViewName);
2611
+ const defRes = await pool.query(defSQL);
2612
+ viewDefinition = defRes.recordset?.[0]?.ViewDefinition ?? defRes.recordset?.[0]?.viewdefinition ?? null;
2613
+ }
2614
+ catch (err) {
2615
+ LogWarning(` ⚠️ [AlternateBaseView] Could not inspect view definition for ${altView.EffectiveSchemaName}.${altView.ViewName} on '${entity.Name}': ${err instanceof Error ? err.message : String(err)}`);
2616
+ }
2617
+ try {
2618
+ const depSQL = this._dbProvider.getViewDependenciesSQL(altView.EffectiveSchemaName, altView.ViewName);
2619
+ if (depSQL && depSQL.trim().length > 0) {
2620
+ const depRes = await pool.query(depSQL);
2621
+ dependencies = (depRes.recordset ?? [])
2622
+ .map((r) => ({
2623
+ ReferencedSchema: String(r.ReferencedSchema ?? r.referencedschema ?? ''),
2624
+ ReferencedObject: String(r.ReferencedObject ?? r.referencedobject ?? ''),
2625
+ ReferencedType: r.ReferencedType != null ? String(r.ReferencedType) : undefined,
2626
+ }))
2627
+ .filter((d) => d.ReferencedObject.length > 0);
2628
+ }
2629
+ }
2630
+ catch (err) {
2631
+ LogWarning(` ⚠️ [AlternateBaseView] Could not inspect catalog dependencies for ${altView.EffectiveSchemaName}.${altView.ViewName} on '${entity.Name}': ${err instanceof Error ? err.message : String(err)}`);
2632
+ }
2633
+ }
2634
+ return { viewExists, viewColumns, viewDefinition, dependencies };
2635
+ }
1938
2636
  /**
1939
2637
  * Emits the refresh + permission statements for an entity whose `BaseView` CodeGen does NOT
1940
2638
  * write — fully custom, or the application-owned outer half of a layered entity.
@@ -1970,7 +2668,11 @@ export class SQLCodeGenBase {
1970
2668
  sOutput += this.guardOnApplicationOwnedView(entity, rebindSQL.trim()) + separator;
1971
2669
  }
1972
2670
  }
1973
- return sOutput + permissionsHeader + this.guardOnApplicationOwnedView(entity, permissionsBody) + separator;
2671
+ for (const altRefresh of this.getAlternateBaseViewRefreshStatements(entity)) {
2672
+ sOutput += altRefresh + separator;
2673
+ }
2674
+ const altPermSQL = this.generateAlternateBaseViewsPermissionsSQL(entity);
2675
+ return sOutput + permissionsHeader + this.guardOnApplicationOwnedView(entity, permissionsBody) + altPermSQL + separator;
1974
2676
  }
1975
2677
  /**
1976
2678
  * Wraps SQL in an existence check on the application-owned `BaseView`, but only for a layered