@memberjunction/codegen-lib 6.2.0-edge.5 → 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.
- package/dist/Config/config.d.ts +126 -0
- package/dist/Config/config.d.ts.map +1 -1
- package/dist/Config/config.js +48 -2
- package/dist/Config/config.js.map +1 -1
- package/dist/Database/codeGenDatabaseProvider.d.ts +87 -4
- package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
- package/dist/Database/codeGenDatabaseProvider.js +133 -1
- package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
- package/dist/Database/manage-metadata.d.ts +121 -6
- package/dist/Database/manage-metadata.d.ts.map +1 -1
- package/dist/Database/manage-metadata.js +338 -58
- package/dist/Database/manage-metadata.js.map +1 -1
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +25 -5
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +135 -26
- package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
- package/dist/Database/providers/postgresql/metadataSupportObjects.js +45 -6
- package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +40 -12
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +127 -53
- package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
- package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts +47 -0
- package/dist/Database/providers/sqlserver/sqlServerDefaultValues.d.ts.map +1 -0
- package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js +167 -0
- package/dist/Database/providers/sqlserver/sqlServerDefaultValues.js.map +1 -0
- package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts +31 -0
- package/dist/Database/providers/sqlserver/sqlServerScriptText.d.ts.map +1 -0
- package/dist/Database/providers/sqlserver/sqlServerScriptText.js +116 -0
- package/dist/Database/providers/sqlserver/sqlServerScriptText.js.map +1 -0
- package/dist/Database/sql.d.ts +13 -0
- package/dist/Database/sql.d.ts.map +1 -1
- package/dist/Database/sql.js +39 -8
- package/dist/Database/sql.js.map +1 -1
- package/dist/Database/sql_codegen.d.ts +138 -4
- package/dist/Database/sql_codegen.d.ts.map +1 -1
- package/dist/Database/sql_codegen.js +585 -44
- package/dist/Database/sql_codegen.js.map +1 -1
- package/dist/Misc/system_integrity.d.ts +48 -0
- package/dist/Misc/system_integrity.d.ts.map +1 -1
- package/dist/Misc/system_integrity.js +151 -75
- package/dist/Misc/system_integrity.js.map +1 -1
- package/dist/runCodeGen.d.ts +21 -3
- package/dist/runCodeGen.d.ts.map +1 -1
- package/dist/runCodeGen.js +114 -44
- package/dist/runCodeGen.js.map +1 -1
- 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
|
|
@@ -82,9 +182,21 @@ export class SQLCodeGenBase {
|
|
|
82
182
|
/**
|
|
83
183
|
* Map of `schema.routine` (lowercased) to its live `OBJECT_DEFINITION` text on SQL Server,
|
|
84
184
|
* used by {@link isRoutineSaveReturnModeChanged} to detect when `Entity.Configuration.SaveReturnMode`
|
|
85
|
-
* changed via `mj sync push` without a physical table/column change
|
|
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.
|
|
86
187
|
*/
|
|
87
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();
|
|
88
200
|
}
|
|
89
201
|
get SQLUtilityObject() {
|
|
90
202
|
return this._sqlUtilityObject;
|
|
@@ -99,6 +211,8 @@ export class SQLCodeGenBase {
|
|
|
99
211
|
try {
|
|
100
212
|
this.existingRoutines = null;
|
|
101
213
|
this.existingRoutineDefinitions = null;
|
|
214
|
+
this.driftedRoutines = new Set();
|
|
215
|
+
this.layeredEntitiesWithLoggedInnerView = new Set();
|
|
102
216
|
// Build list of entities qualified for forced regeneration if entityWhereClause is provided
|
|
103
217
|
if (configInfo.forceRegeneration?.enabled && configInfo.forceRegeneration?.entityWhereClause) {
|
|
104
218
|
this.filterEntitiesQualifiedForRegeneration = true; // Enable filtering
|
|
@@ -129,11 +243,15 @@ export class SQLCodeGenBase {
|
|
|
129
243
|
// objects like spCreate for a given entity might reference the vw for that entity
|
|
130
244
|
StartSpinner('Running custom SQL scripts...');
|
|
131
245
|
const startTime = new Date();
|
|
132
|
-
|
|
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) {
|
|
133
250
|
FailSpinner('Failed to run custom SQL scripts');
|
|
134
|
-
return false;
|
|
135
251
|
}
|
|
136
|
-
|
|
252
|
+
else {
|
|
253
|
+
SucceedSpinner(`Custom SQL scripts completed (${(new Date().getTime() - startTime.getTime()) / 1000}s)`);
|
|
254
|
+
}
|
|
137
255
|
await this.loadExistingRoutines(pool, entities);
|
|
138
256
|
// ALWAYS use the first filter where we only include entities that have IncludeInAPI = 1
|
|
139
257
|
// Entities are already sorted by name in PostProcessEntityMetadata (see providerBase.ts)
|
|
@@ -307,7 +425,7 @@ export class SQLCodeGenBase {
|
|
|
307
425
|
}
|
|
308
426
|
// Initialize from entityGenSuccess so any per-batch failures from
|
|
309
427
|
// STEP 2(b)/(c) carry forward instead of being lost. Bug 2 fix.
|
|
310
|
-
let overallSuccess = entityGenSuccess;
|
|
428
|
+
let overallSuccess = entityGenSuccess && beforeScriptsSucceeded;
|
|
311
429
|
if (!executionSuccess) {
|
|
312
430
|
FailSpinner('Failed to execute entity SQL files');
|
|
313
431
|
TempBatchFile.cleanup(); // Cleanup on error
|
|
@@ -320,6 +438,22 @@ export class SQLCodeGenBase {
|
|
|
320
438
|
const step2eEndTime = new Date();
|
|
321
439
|
SucceedSpinner(`SQL execution completed (${(step2eEndTime.getTime() - step2eStartTime.getTime()) / 1000}s)`);
|
|
322
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
|
+
}
|
|
323
457
|
const manageMD = MJGlobal.Instance.ClassFactory.CreateInstance(ManageMetadataBase);
|
|
324
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
|
|
325
459
|
// we CAN skip the entity field values part because that wouldn't change from the first time we ran it
|
|
@@ -327,7 +461,11 @@ export class SQLCodeGenBase {
|
|
|
327
461
|
//
|
|
328
462
|
// Pass 1 (in manage-metadata.ts) already discovered all changes and populated _newEntityList ∪ _modifiedEntityList.
|
|
329
463
|
// 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
|
|
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.
|
|
331
469
|
// forceRegeneration override skips the scoping so all entities get reprocessed (used when prompts change, etc.).
|
|
332
470
|
//
|
|
333
471
|
// The two lists only ever contain entities something changed on during THIS run, so an
|
|
@@ -335,6 +473,8 @@ export class SQLCodeGenBase {
|
|
|
335
473
|
// record forms stay broken until someone runs forceRegeneration over the whole database.
|
|
336
474
|
// The drift probe closes that: it asks the catalog which entities have a view-only
|
|
337
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.
|
|
338
478
|
const driftEntities = configInfo.forceRegeneration?.enabled
|
|
339
479
|
? []
|
|
340
480
|
: await manageMD.FindVirtualFieldDriftEntities(pool, configInfo.excludeSchemas);
|
|
@@ -344,6 +484,7 @@ export class SQLCodeGenBase {
|
|
|
344
484
|
...ManageMetadataBase.newEntityList,
|
|
345
485
|
...ManageMetadataBase.modifiedEntityList,
|
|
346
486
|
...driftEntities,
|
|
487
|
+
...this.layeredEntitiesWithLoggedInnerView,
|
|
347
488
|
])];
|
|
348
489
|
StartSpinner('Managing entity fields metadata...');
|
|
349
490
|
if (!await manageMD.manageEntityFields(pool, configInfo.excludeSchemas, true, true, currentUser, false, false, pass2EntityFilter)) {
|
|
@@ -421,6 +562,7 @@ export class SQLCodeGenBase {
|
|
|
421
562
|
// STEP 4.5 - Emit sp_refreshview for modified custom base view entities into the
|
|
422
563
|
// migration log file so other environments pick up schema changes automatically.
|
|
423
564
|
this.emitCustomBaseViewRefreshes();
|
|
565
|
+
await this.validateAlternateBaseViewsForEntities(pool, includedEntities);
|
|
424
566
|
// STEP 5 - execute any custom SQL scripts that should run afterwards
|
|
425
567
|
StartSpinner('Running post-generation SQL scripts...');
|
|
426
568
|
const step5StartTime = new Date();
|
|
@@ -785,12 +927,17 @@ export class SQLCodeGenBase {
|
|
|
785
927
|
logError(`Phased execution for ${options.entity.SchemaName}.${options.entity.Name} failed in phase "${where}": ${phaseResult.error?.message ?? '(no message)'}`);
|
|
786
928
|
return { Success: false, Files: files };
|
|
787
929
|
}
|
|
930
|
+
await this.validateAlternateBaseViews(options.pool, options.entity);
|
|
788
931
|
return { Success: true, Files: files };
|
|
789
932
|
}
|
|
790
933
|
// Fallback: original monolithic path (SQL Server; also the path when
|
|
791
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
|
+
}
|
|
792
939
|
return {
|
|
793
|
-
Success:
|
|
940
|
+
Success: execSuccess,
|
|
794
941
|
Files: files
|
|
795
942
|
};
|
|
796
943
|
}
|
|
@@ -847,6 +994,28 @@ export class SQLCodeGenBase {
|
|
|
847
994
|
const crudDeleteSQL = entity.AllowDeleteAPI && entity.spDeleteGenerated && !entity.VirtualEntity
|
|
848
995
|
? await this.generateSPDelete(entity, pool)
|
|
849
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
|
+
}
|
|
850
1019
|
return this._dbProvider.executeEntityPhased({
|
|
851
1020
|
entity,
|
|
852
1021
|
tvfSQL,
|
|
@@ -854,6 +1023,7 @@ export class SQLCodeGenBase {
|
|
|
854
1023
|
crudCreateSQL,
|
|
855
1024
|
crudUpdateSQL,
|
|
856
1025
|
crudDeleteSQL,
|
|
1026
|
+
ftsSQL,
|
|
857
1027
|
viewPermSQL: viewPieces.viewPermSQL,
|
|
858
1028
|
willRegenerate,
|
|
859
1029
|
});
|
|
@@ -1005,6 +1175,11 @@ export class SQLCodeGenBase {
|
|
|
1005
1175
|
// Normalize whitespace for fair comparison: collapse runs of whitespace to single space
|
|
1006
1176
|
return body.replace(/\s+/g, ' ').trim();
|
|
1007
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
|
+
*/
|
|
1008
1183
|
logSQLForNewOrModifiedEntity(entity, sql, description, logSql = false, forceLog = false) {
|
|
1009
1184
|
// Check if we should log this SQL
|
|
1010
1185
|
let shouldLog = forceLog;
|
|
@@ -1061,6 +1236,7 @@ export class SQLCodeGenBase {
|
|
|
1061
1236
|
TempBatchFile.appendToTempBatchFile(sql, entity.SchemaName);
|
|
1062
1237
|
}
|
|
1063
1238
|
LogIf(configInfo.verboseOutput, `SQL Generated for ${entity.Name}: ${description}`);
|
|
1239
|
+
return shouldLog;
|
|
1064
1240
|
}
|
|
1065
1241
|
/**
|
|
1066
1242
|
* Emits sp_refreshview statements into the migration log file for modified custom base view
|
|
@@ -1079,6 +1255,69 @@ export class SQLCodeGenBase {
|
|
|
1079
1255
|
const refreshSQL = this.buildCustomBaseViewRefreshSQL(qualifyingEntities);
|
|
1080
1256
|
SQLLogging.appendToSQLLogFile(refreshSQL, 'Refresh custom base views for modified entities so schema changes are picked up');
|
|
1081
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
|
+
}
|
|
1082
1321
|
/**
|
|
1083
1322
|
* Returns entities from the modified and new entity lists that have custom base views
|
|
1084
1323
|
* (BaseViewGenerated === false), are included in the API, and are not virtual.
|
|
@@ -1115,8 +1354,9 @@ export class SQLCodeGenBase {
|
|
|
1115
1354
|
return entities
|
|
1116
1355
|
.map(e => {
|
|
1117
1356
|
const outer = this._dbProvider.generateViewRefreshSQL(e.SchemaName, e.BaseView);
|
|
1357
|
+
const altSteps = this.getAlternateBaseViewRefreshStatements(e);
|
|
1118
1358
|
if (!e.HasLayeredBaseView) {
|
|
1119
|
-
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
|
|
1120
1360
|
}
|
|
1121
1361
|
const inner = this._dbProvider.generateViewRefreshSQL(e.SchemaName, e.GeneratedViewName);
|
|
1122
1362
|
const rebind = this._dbProvider.generateLayeredOuterRebindSQL(e);
|
|
@@ -1126,7 +1366,7 @@ export class SQLCodeGenBase {
|
|
|
1126
1366
|
const rebindSql = rebind.trim().length > 0
|
|
1127
1367
|
? this.guardOnApplicationOwnedView(e, rebind.trim())
|
|
1128
1368
|
: '';
|
|
1129
|
-
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');
|
|
1130
1370
|
})
|
|
1131
1371
|
.join('\n');
|
|
1132
1372
|
}
|
|
@@ -1226,7 +1466,10 @@ export class SQLCodeGenBase {
|
|
|
1226
1466
|
const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('view', options.entity.SchemaName, options.entity.GeneratedViewName, false, true));
|
|
1227
1467
|
if (options.writeFiles) {
|
|
1228
1468
|
this.writeFileIfChanged(filePath, s);
|
|
1229
|
-
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
|
+
}
|
|
1230
1473
|
files.push(filePath);
|
|
1231
1474
|
}
|
|
1232
1475
|
sRet += s + '\n' + this._dbProvider.BatchSeparator + '\n';
|
|
@@ -1239,9 +1482,10 @@ export class SQLCodeGenBase {
|
|
|
1239
1482
|
// pass. This copy is what gets written to the permissions FILE and logged into the
|
|
1240
1483
|
// migration, so leaving it unguarded would fail on other environments even though the
|
|
1241
1484
|
// executed copy (generateCustomBaseViewRefreshAndPermissions, below) is guarded.
|
|
1242
|
-
const
|
|
1485
|
+
const altPermBody = this.generateAlternateBaseViewsPermissionsSQL(options.entity);
|
|
1486
|
+
const permBody = (options.entity.HasLayeredBaseView && rawPermBody.trim().length > 0
|
|
1243
1487
|
? '\n' + this.guardOnApplicationOwnedView(options.entity, rawPermBody.trim())
|
|
1244
|
-
: rawPermBody;
|
|
1488
|
+
: rawPermBody) + altPermBody;
|
|
1245
1489
|
const s = permHeader + permBody;
|
|
1246
1490
|
if (s.length > 0)
|
|
1247
1491
|
permissionsSQL += s + '\n' + this._dbProvider.BatchSeparator + '\n';
|
|
@@ -1263,6 +1507,8 @@ export class SQLCodeGenBase {
|
|
|
1263
1507
|
// CREATE SP
|
|
1264
1508
|
if (options.entity.AllowCreateAPI && !options.entity.VirtualEntity) {
|
|
1265
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);
|
|
1266
1512
|
// Only generate if spCreateGenerated is true (respects custom SPs where it's false)
|
|
1267
1513
|
// forceRegeneration only forces regeneration of SPs where spCreateGenerated=true
|
|
1268
1514
|
if (!options.onlyPermissions && options.entity.spCreateGenerated) {
|
|
@@ -1271,7 +1517,8 @@ export class SQLCodeGenBase {
|
|
|
1271
1517
|
if (options.writeFiles) {
|
|
1272
1518
|
const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, false, true));
|
|
1273
1519
|
this.writeFileIfChanged(filePath, s);
|
|
1274
|
-
|
|
1520
|
+
routineForceLog = this.forceLogForRoutine(options.entity, spName, baseViewChanged, s);
|
|
1521
|
+
this.logSQLForNewOrModifiedEntity(options.entity, s, `spCreate SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
|
|
1275
1522
|
files.push(filePath);
|
|
1276
1523
|
}
|
|
1277
1524
|
sRet += s + '\n' + this._dbProvider.BatchSeparator + '\n';
|
|
@@ -1282,7 +1529,7 @@ export class SQLCodeGenBase {
|
|
|
1282
1529
|
if (options.writeFiles) {
|
|
1283
1530
|
const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, true, true));
|
|
1284
1531
|
this.writeFileIfChanged(filePath, s);
|
|
1285
|
-
this.logSQLForNewOrModifiedEntity(options.entity, s, `spCreate Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities,
|
|
1532
|
+
this.logSQLForNewOrModifiedEntity(options.entity, s, `spCreate Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
|
|
1286
1533
|
files.push(filePath);
|
|
1287
1534
|
}
|
|
1288
1535
|
// now, append the permissions to the return string IF we did NOT generate the proc - because if we generated the proc, that
|
|
@@ -1293,6 +1540,8 @@ export class SQLCodeGenBase {
|
|
|
1293
1540
|
// UPDATE SP
|
|
1294
1541
|
if (options.entity.AllowUpdateAPI && !options.entity.VirtualEntity) {
|
|
1295
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);
|
|
1296
1545
|
// Only generate if spUpdateGenerated is true (respects custom SPs where it's false)
|
|
1297
1546
|
// forceRegeneration only forces regeneration of SPs where spUpdateGenerated=true
|
|
1298
1547
|
if (!options.onlyPermissions && options.entity.spUpdateGenerated) {
|
|
@@ -1301,7 +1550,8 @@ export class SQLCodeGenBase {
|
|
|
1301
1550
|
if (options.writeFiles) {
|
|
1302
1551
|
const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, false, true));
|
|
1303
1552
|
this.writeFileIfChanged(filePath, s);
|
|
1304
|
-
|
|
1553
|
+
routineForceLog = this.forceLogForRoutine(options.entity, spName, baseViewChanged, s);
|
|
1554
|
+
this.logSQLForNewOrModifiedEntity(options.entity, s, `spUpdate SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
|
|
1305
1555
|
files.push(filePath);
|
|
1306
1556
|
}
|
|
1307
1557
|
sRet += s + '\n' + this._dbProvider.BatchSeparator + '\n';
|
|
@@ -1312,7 +1562,7 @@ export class SQLCodeGenBase {
|
|
|
1312
1562
|
if (options.writeFiles) {
|
|
1313
1563
|
const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, true, true));
|
|
1314
1564
|
this.writeFileIfChanged(filePath, s);
|
|
1315
|
-
this.logSQLForNewOrModifiedEntity(options.entity, s, `spUpdate Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities,
|
|
1565
|
+
this.logSQLForNewOrModifiedEntity(options.entity, s, `spUpdate Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
|
|
1316
1566
|
files.push(filePath);
|
|
1317
1567
|
}
|
|
1318
1568
|
// now, append the permissions to the return string IF we did NOT generate the proc - because if we generated the proc, that
|
|
@@ -1323,6 +1573,8 @@ export class SQLCodeGenBase {
|
|
|
1323
1573
|
// DELETE SP
|
|
1324
1574
|
if (options.entity.AllowDeleteAPI && !options.entity.VirtualEntity) {
|
|
1325
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);
|
|
1326
1578
|
// Only generate if spDeleteGenerated is true (respects custom SPs where it's false)
|
|
1327
1579
|
// OR if this entity has cascade delete dependencies that require regeneration
|
|
1328
1580
|
// forceRegeneration only forces regeneration of SPs where spDeleteGenerated=true
|
|
@@ -1337,7 +1589,8 @@ export class SQLCodeGenBase {
|
|
|
1337
1589
|
if (options.writeFiles) {
|
|
1338
1590
|
const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, false, true));
|
|
1339
1591
|
this.writeFileIfChanged(filePath, s);
|
|
1340
|
-
|
|
1592
|
+
routineForceLog = this.forceLogForRoutine(options.entity, spName, baseViewChanged, s);
|
|
1593
|
+
this.logSQLForNewOrModifiedEntity(options.entity, s, `spDelete SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
|
|
1341
1594
|
files.push(filePath);
|
|
1342
1595
|
}
|
|
1343
1596
|
sRet += s + '\n' + this._dbProvider.BatchSeparator + '\n';
|
|
@@ -1348,7 +1601,7 @@ export class SQLCodeGenBase {
|
|
|
1348
1601
|
if (options.writeFiles) {
|
|
1349
1602
|
const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, true, true));
|
|
1350
1603
|
this.writeFileIfChanged(filePath, s);
|
|
1351
|
-
this.logSQLForNewOrModifiedEntity(options.entity, s, `spDelete Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities,
|
|
1604
|
+
this.logSQLForNewOrModifiedEntity(options.entity, s, `spDelete Permissions for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, routineForceLog);
|
|
1352
1605
|
files.push(filePath);
|
|
1353
1606
|
}
|
|
1354
1607
|
// now, append the permissions to the return string IF we did NOT generate the proc - because if we generated the proc, that
|
|
@@ -1478,10 +1731,62 @@ export class SQLCodeGenBase {
|
|
|
1478
1731
|
}
|
|
1479
1732
|
return !selectsFromBaseView;
|
|
1480
1733
|
}
|
|
1481
|
-
|
|
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) {
|
|
1482
1776
|
return baseViewChanged ||
|
|
1483
1777
|
this.isRoutineMissing(entity.SchemaName, routineName) ||
|
|
1484
|
-
this.isRoutineSaveReturnModeChanged(entity, 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}`);
|
|
1485
1790
|
}
|
|
1486
1791
|
GetEntityPermissionFileNames(entity) {
|
|
1487
1792
|
const files = [];
|
|
@@ -1557,26 +1862,17 @@ export class SQLCodeGenBase {
|
|
|
1557
1862
|
throw new Error(`FullTextIndexGenerated is true for entity ${entity.Name}, but no fields are marked as FullTextSearchEnabled`);
|
|
1558
1863
|
if (entity.FullTextSearchFunctionGenerated && searchFields.length === 0)
|
|
1559
1864
|
throw new Error(`FullTextSearchFunctionGenerated is true for entity ${entity.Name}, but no fields are marked as FullTextSearchEnabled`);
|
|
1560
|
-
// Get the primary key index name
|
|
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.
|
|
1561
1872
|
let primaryKeyIndexName = '';
|
|
1562
|
-
if (entity.FullTextIndexGenerated) {
|
|
1873
|
+
if (entity.FullTextIndexGenerated && this._dbProvider.FullTextIndexNeedsPrimaryKeyIndexName) {
|
|
1563
1874
|
primaryKeyIndexName = await this.GetEntityPrimaryKeyIndexName(pool, entity);
|
|
1564
1875
|
}
|
|
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
1876
|
// Say what enabling full-text search costs, at the one moment the person who enabled it is
|
|
1581
1877
|
// still in the room. The objects below are charged on every write to the table from here on
|
|
1582
1878
|
// and are not removed by turning the entity's flags back off.
|
|
@@ -1584,8 +1880,48 @@ export class SQLCodeGenBase {
|
|
|
1584
1880
|
if (costDisclosure) {
|
|
1585
1881
|
LogWarning(` > ${costDisclosure}`);
|
|
1586
1882
|
}
|
|
1587
|
-
// Delegate SQL generation to the provider
|
|
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.
|
|
1588
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) {
|
|
1900
|
+
const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
|
|
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];
|
|
1913
|
+
if (!u)
|
|
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.`);
|
|
1919
|
+
const e = await md.GetEntityObject('MJ: Entities', u);
|
|
1920
|
+
await e.Load(entity.ID);
|
|
1921
|
+
e.FullTextSearchFunction = functionName;
|
|
1922
|
+
if (!await e.Save())
|
|
1923
|
+
throw new Error(`Could not update the FullTextSearchFunction for entity ${entity.Name}`);
|
|
1924
|
+
}
|
|
1589
1925
|
// Add permissions if function was generated
|
|
1590
1926
|
if (entity.FullTextSearchFunctionGenerated) {
|
|
1591
1927
|
result.sql += this.generateFullTextSearchFunctionPermissions(entity, functionName) + '\n\n' + this._dbProvider.BatchSeparator + '\n';
|
|
@@ -1681,9 +2017,18 @@ export class SQLCodeGenBase {
|
|
|
1681
2017
|
/**
|
|
1682
2018
|
* Detects self-referential foreign keys in an entity (e.g., ParentTaskID pointing back to Task table)
|
|
1683
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.
|
|
1684
2028
|
*/
|
|
1685
2029
|
detectRecursiveForeignKeys(entity) {
|
|
1686
2030
|
const hierarchyFKs = entity.Fields.filter(field => field.RelatedEntityID != null &&
|
|
2031
|
+
!field.IsPrimaryKey &&
|
|
1687
2032
|
UUIDsEqual(field.RelatedEntityID, entity.ID) &&
|
|
1688
2033
|
!field.IsVirtual &&
|
|
1689
2034
|
field.IsHierarchy === true);
|
|
@@ -1899,14 +2244,15 @@ export class SQLCodeGenBase {
|
|
|
1899
2244
|
// sites because generateBaseView concatenates this onto the view DDL and the phased
|
|
1900
2245
|
// executor consumes it separately — both need it.
|
|
1901
2246
|
const rawPermissions = this.generateViewPermissions(entity);
|
|
2247
|
+
const altPermissions = this.generateAlternateBaseViewsPermissionsSQL(entity);
|
|
1902
2248
|
// The leading newline must stay OUTSIDE the guard. `generateViewPermissions` returns
|
|
1903
2249
|
// "\nGRANT ..." and the view DDL it is concatenated onto ends in `GO`; wrapping the string
|
|
1904
2250
|
// verbatim pulls that newline inside the sp_executesql literal and emits `GOIF OBJECT_ID`,
|
|
1905
2251
|
// fusing the batch separator to the next statement. Non-layered entities keep the raw
|
|
1906
2252
|
// string byte-for-byte so this cannot churn every other entity's generated SQL.
|
|
1907
|
-
const permissions = entity.HasLayeredBaseView && rawPermissions.trim().length > 0
|
|
2253
|
+
const permissions = (entity.HasLayeredBaseView && rawPermissions.trim().length > 0
|
|
1908
2254
|
? '\n' + this.guardOnApplicationOwnedView(entity, rawPermissions.trim())
|
|
1909
|
-
: rawPermissions;
|
|
2255
|
+
: rawPermissions) + altPermissions;
|
|
1910
2256
|
// Detect recursive foreign keys and generate TVF joins and root field selects
|
|
1911
2257
|
const recursiveFKs = this.detectRecursiveForeignKeys(entity);
|
|
1912
2258
|
const rootFields = recursiveFKs.length > 0 ? this.generateRootFieldSelects(entity, recursiveFKs, classNameFirstChar) : '';
|
|
@@ -1923,8 +2269,16 @@ export class SQLCodeGenBase {
|
|
|
1923
2269
|
rootFieldsSelect: rootFields,
|
|
1924
2270
|
rootJoins: rootJoins,
|
|
1925
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
|
+
}
|
|
1926
2280
|
return {
|
|
1927
|
-
viewSQL
|
|
2281
|
+
viewSQL,
|
|
1928
2282
|
viewPermSQL: permissions,
|
|
1929
2283
|
};
|
|
1930
2284
|
}
|
|
@@ -1935,6 +2289,189 @@ export class SQLCodeGenBase {
|
|
|
1935
2289
|
generateViewPermissions(entity) {
|
|
1936
2290
|
return this._dbProvider.generateViewPermissions(entity);
|
|
1937
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
|
+
}
|
|
1938
2475
|
/**
|
|
1939
2476
|
* Emits the refresh + permission statements for an entity whose `BaseView` CodeGen does NOT
|
|
1940
2477
|
* write — fully custom, or the application-owned outer half of a layered entity.
|
|
@@ -1970,7 +2507,11 @@ export class SQLCodeGenBase {
|
|
|
1970
2507
|
sOutput += this.guardOnApplicationOwnedView(entity, rebindSQL.trim()) + separator;
|
|
1971
2508
|
}
|
|
1972
2509
|
}
|
|
1973
|
-
|
|
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;
|
|
1974
2515
|
}
|
|
1975
2516
|
/**
|
|
1976
2517
|
* Wraps SQL in an existence check on the application-owned `BaseView`, but only for a layered
|