@memberjunction/codegen-lib 6.3.0-edge.0 → 6.3.0-edge.1

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 (91) hide show
  1. package/README.md +37 -1
  2. package/dist/Config/config.d.ts +36 -0
  3. package/dist/Config/config.d.ts.map +1 -1
  4. package/dist/Config/config.js +10 -0
  5. package/dist/Config/config.js.map +1 -1
  6. package/dist/Database/codeGenDatabaseProvider.d.ts +7 -1
  7. package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
  8. package/dist/Database/codeGenDatabaseProvider.js +23 -1
  9. package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
  10. package/dist/Database/manage-metadata.d.ts +54 -15
  11. package/dist/Database/manage-metadata.d.ts.map +1 -1
  12. package/dist/Database/manage-metadata.js +306 -144
  13. package/dist/Database/manage-metadata.js.map +1 -1
  14. package/dist/Database/organic-key-sync.d.ts +70 -0
  15. package/dist/Database/organic-key-sync.d.ts.map +1 -0
  16. package/dist/Database/organic-key-sync.js +83 -0
  17. package/dist/Database/organic-key-sync.js.map +1 -0
  18. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +7 -0
  19. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
  20. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +74 -16
  21. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
  22. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js +14 -0
  23. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js.map +1 -1
  24. package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.d.ts +2 -0
  25. package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.d.ts.map +1 -0
  26. package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.js +36 -0
  27. package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.js.map +1 -0
  28. package/dist/Database/providers/postgresql/__tests__/PostgreSQLHierarchyFunctions.test.js +5 -0
  29. package/dist/Database/providers/postgresql/__tests__/PostgreSQLHierarchyFunctions.test.js.map +1 -1
  30. package/dist/Database/providers/postgresql/__tests__/SoftPrimaryKeyIndex.test.js +6 -0
  31. package/dist/Database/providers/postgresql/__tests__/SoftPrimaryKeyIndex.test.js.map +1 -1
  32. package/dist/Database/providers/postgresql/metadataSupportObjects.js +43 -11
  33. package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
  34. package/dist/Database/providers/postgresql/viewFallback.d.ts +25 -0
  35. package/dist/Database/providers/postgresql/viewFallback.d.ts.map +1 -1
  36. package/dist/Database/providers/postgresql/viewFallback.js +101 -48
  37. package/dist/Database/providers/postgresql/viewFallback.js.map +1 -1
  38. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +12 -2
  39. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
  40. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +96 -32
  41. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
  42. package/dist/Database/providers/sqlserver/__tests__/BaseViewEmissionGoldenMaster.test.js +4 -3
  43. package/dist/Database/providers/sqlserver/__tests__/BaseViewEmissionGoldenMaster.test.js.map +1 -1
  44. package/dist/Database/providers/sqlserver/__tests__/SQLServerCodeGenProvider.test.js +41 -0
  45. package/dist/Database/providers/sqlserver/__tests__/SQLServerCodeGenProvider.test.js.map +1 -1
  46. package/dist/Database/providers/sqlserver/__tests__/SoftPrimaryKeyIndex.test.js +6 -0
  47. package/dist/Database/providers/sqlserver/__tests__/SoftPrimaryKeyIndex.test.js.map +1 -1
  48. package/dist/Database/sql_codegen.d.ts +74 -2
  49. package/dist/Database/sql_codegen.d.ts.map +1 -1
  50. package/dist/Database/sql_codegen.js +536 -125
  51. package/dist/Database/sql_codegen.js.map +1 -1
  52. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts +49 -1
  53. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts.map +1 -1
  54. package/dist/Manifest/GenerateClassRegistrationsManifest.js +392 -60
  55. package/dist/Manifest/GenerateClassRegistrationsManifest.js.map +1 -1
  56. package/dist/Misc/advanced_generation.d.ts +15 -3
  57. package/dist/Misc/advanced_generation.d.ts.map +1 -1
  58. package/dist/Misc/advanced_generation.js +50 -3
  59. package/dist/Misc/advanced_generation.js.map +1 -1
  60. package/dist/Misc/createNewUser.js +4 -4
  61. package/dist/Misc/createNewUser.js.map +1 -1
  62. package/dist/Misc/entity_subclasses_codegen.d.ts +11 -4
  63. package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
  64. package/dist/Misc/entity_subclasses_codegen.js +46 -14
  65. package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
  66. package/dist/Misc/smart-field-decision.d.ts +126 -0
  67. package/dist/Misc/smart-field-decision.d.ts.map +1 -0
  68. package/dist/Misc/smart-field-decision.js +222 -0
  69. package/dist/Misc/smart-field-decision.js.map +1 -0
  70. package/dist/Misc/system_integrity.d.ts +9 -0
  71. package/dist/Misc/system_integrity.d.ts.map +1 -1
  72. package/dist/Misc/system_integrity.js +20 -1
  73. package/dist/Misc/system_integrity.js.map +1 -1
  74. package/dist/Misc/typed_query_codegen.d.ts +22 -8
  75. package/dist/Misc/typed_query_codegen.d.ts.map +1 -1
  76. package/dist/Misc/typed_query_codegen.js +23 -2
  77. package/dist/Misc/typed_query_codegen.js.map +1 -1
  78. package/dist/Misc/validator-text.d.ts +14 -5
  79. package/dist/Misc/validator-text.d.ts.map +1 -1
  80. package/dist/Misc/validator-text.js +42 -13
  81. package/dist/Misc/validator-text.js.map +1 -1
  82. package/dist/plugins/index.d.ts +10 -0
  83. package/dist/plugins/index.d.ts.map +1 -1
  84. package/dist/plugins/index.js +22 -2
  85. package/dist/plugins/index.js.map +1 -1
  86. package/dist/runCodeGen.d.ts +6 -0
  87. package/dist/runCodeGen.d.ts.map +1 -1
  88. package/dist/runCodeGen.js +12 -3
  89. package/dist/runCodeGen.js.map +1 -1
  90. package/dist/tsconfig.tsbuildinfo +1 -0
  91. package/package.json +30 -29
@@ -9,7 +9,7 @@ import { EntityInCustomBaseViewRefreshScope, ShouldEmitCascadeForRelatedEntity }
9
9
  import { ManageMetadataBase } from './manage-metadata.js';
10
10
  import { UserCache } from '@memberjunction/generic-database-provider';
11
11
  import { CombineFiles, LogIf } from '../Misc/util.js';
12
- import { MJGlobal, UUIDsEqual } from '@memberjunction/global';
12
+ import { MJGlobal, UUIDsEqual, NormalizeUUID } from '@memberjunction/global';
13
13
  import { SQLLogging } from '../Misc/sql_logging.js';
14
14
  import { TempBatchFile } from '../Misc/temp_batch_file.js';
15
15
  import { writeFileIfChanged as writeFileIfChangedShared } from '../Misc/file-write.js';
@@ -31,6 +31,207 @@ export function EntitiesNotInExcludedSchemas(entities, excludeSchemas) {
31
31
  export function entitiesNotInExcludedSchemas(entities, excludeSchemas) {
32
32
  return EntitiesNotInExcludedSchemas(entities, excludeSchemas);
33
33
  }
34
+ /**
35
+ * Maximum concurrent entities processed per wave during phased PostgreSQL code generation.
36
+ * Capped at 6 to bound concurrent pooled `pg.PoolClient` checkouts per wave well below
37
+ * the default 10-connection `pg.Pool` limit, leaving headroom for `42P16` fallback
38
+ * introspection queries and metadata reads.
39
+ */
40
+ export const MAX_PG_PHASED_WAVE_CONCURRENCY = 6;
41
+ /**
42
+ * Partitions entities into waves where all entities within each wave can be executed concurrently
43
+ * without SQL object creation or dependency conflicts on PostgreSQL.
44
+ *
45
+ * Conflict rules:
46
+ * 1. Direct FK / IS-A parent dependency: referencing entities run in later waves than referenced entities.
47
+ * 2. 2-hop shared-dependent conflict: two entities both joined into a third entity's view never share a wave.
48
+ * 3. Custom / layered / alternate base view entities are isolated into singleton waves.
49
+ * 4. Topological wave assignment ensures referenced views exist before dependent views update.
50
+ */
51
+ export function PartitionEntitiesIntoConflictFreeWaves(entities, maxWaveSize) {
52
+ if (entities.length === 0) {
53
+ return [];
54
+ }
55
+ if (maxWaveSize <= 1 || entities.length <= 1) {
56
+ return entities.map(e => [e]);
57
+ }
58
+ // Assign each entity an index 0..N-1 and map NormalizeUUID(e.ID) -> index
59
+ const idToIndex = new Map();
60
+ for (let i = 0; i < entities.length; i++) {
61
+ const e = entities[i];
62
+ if (e.ID) {
63
+ idToIndex.set(NormalizeUUID(e.ID), i);
64
+ }
65
+ }
66
+ // For each entity i, collect all referenced entity indices refs[i]
67
+ // i depends on j (j must be executed before or in an earlier wave than i)
68
+ const refs = entities.map(() => new Set());
69
+ for (let i = 0; i < entities.length; i++) {
70
+ const e = entities[i];
71
+ const eRefs = refs[i];
72
+ // Every f.RelatedEntityID on e.Fields
73
+ for (const f of e.Fields ?? []) {
74
+ if (f.RelatedEntityID) {
75
+ const j = idToIndex.get(NormalizeUUID(f.RelatedEntityID));
76
+ if (j !== undefined && j !== i) {
77
+ eRefs.add(j);
78
+ }
79
+ }
80
+ }
81
+ // e.ParentID
82
+ if (e.ParentID) {
83
+ const j = idToIndex.get(NormalizeUUID(e.ParentID));
84
+ if (j !== undefined && j !== i) {
85
+ eRefs.add(j);
86
+ }
87
+ }
88
+ // every p.ID in e.ParentChain ?? []
89
+ for (const p of e.ParentChain ?? []) {
90
+ if (p?.ID) {
91
+ const j = idToIndex.get(NormalizeUUID(p.ID));
92
+ if (j !== undefined && j !== i) {
93
+ eRefs.add(j);
94
+ }
95
+ }
96
+ }
97
+ }
98
+ // Build undirected conflicts: Array<Set<number>>
99
+ const conflicts = entities.map(() => new Set());
100
+ for (let i = 0; i < entities.length; i++) {
101
+ for (const j of refs[i]) {
102
+ conflicts[i].add(j);
103
+ conflicts[j].add(i);
104
+ }
105
+ }
106
+ // 2-hop shared-dependent edge:
107
+ // for each entity w, if w references both a and b, a and b conflict
108
+ for (let w = 0; w < entities.length; w++) {
109
+ const arr = Array.from(refs[w]);
110
+ for (let aIdx = 0; aIdx < arr.length; aIdx++) {
111
+ const a = arr[aIdx];
112
+ for (let bIdx = aIdx + 1; bIdx < arr.length; bIdx++) {
113
+ const b = arr[bIdx];
114
+ if (a !== b) {
115
+ conflicts[a].add(b);
116
+ conflicts[b].add(a);
117
+ }
118
+ }
119
+ }
120
+ }
121
+ // Custom / layered / alternate base view isolation
122
+ const isIsolated = (e) => {
123
+ return !e.BaseViewGenerated || e.HasLayeredBaseView || ((e.AlternateBaseViews?.length ?? 0) > 0);
124
+ };
125
+ // Topological + 2-hop conflict wave assignment using Kahn's algorithm over refs
126
+ // In refs: i references j => j must come before i (j is a dependency of i).
127
+ // inDegree[i] is the number of unplaced dependencies of i.
128
+ const inDegree = refs.map(r => r.size);
129
+ const dependentsOf = entities.map(() => []);
130
+ for (let i = 0; i < entities.length; i++) {
131
+ for (const j of refs[i]) {
132
+ dependentsOf[j].push(i);
133
+ }
134
+ }
135
+ const placed = new Set();
136
+ const waves = [];
137
+ const waveIndices = [];
138
+ const waveIsIsolated = [];
139
+ const entityWaveIndex = new Map();
140
+ while (placed.size < entities.length) {
141
+ // Ready candidates: unplaced entities with inDegree === 0
142
+ let readyCandidates = [];
143
+ for (let i = 0; i < entities.length; i++) {
144
+ if (!placed.has(i) && inDegree[i] === 0) {
145
+ readyCandidates.push(i);
146
+ }
147
+ }
148
+ // If cycle exists, break cycle deterministically by picking unplaced entity with smallest index
149
+ if (readyCandidates.length === 0) {
150
+ let bestIndex = -1;
151
+ let minDegree = Infinity;
152
+ for (let i = 0; i < entities.length; i++) {
153
+ if (!placed.has(i)) {
154
+ if (inDegree[i] < minDegree || (inDegree[i] === minDegree && (bestIndex === -1 || i < bestIndex))) {
155
+ minDegree = inDegree[i];
156
+ bestIndex = i;
157
+ }
158
+ }
159
+ }
160
+ readyCandidates = [bestIndex];
161
+ }
162
+ // Process ready candidates deterministically in index order
163
+ readyCandidates.sort((a, b) => a - b);
164
+ for (const curr of readyCandidates) {
165
+ if (placed.has(curr))
166
+ continue;
167
+ const e = entities[curr];
168
+ const isolated = isIsolated(e);
169
+ // minWave: must be strictly greater than wave index of any already-placed dependency j in refs[curr]
170
+ let minWave = 0;
171
+ for (const j of refs[curr]) {
172
+ const jWave = entityWaveIndex.get(j);
173
+ if (jWave !== undefined) {
174
+ minWave = Math.max(minWave, jWave + 1);
175
+ }
176
+ }
177
+ if (isolated) {
178
+ // Must be placed alone in a dedicated singleton wave [e]
179
+ // Find smallest w >= minWave that doesn't exist yet, or allocate new wave
180
+ let targetWave = minWave;
181
+ while (targetWave < waves.length) {
182
+ targetWave++;
183
+ }
184
+ waves[targetWave] = [e];
185
+ waveIndices[targetWave] = new Set([curr]);
186
+ waveIsIsolated[targetWave] = true;
187
+ entityWaveIndex.set(curr, targetWave);
188
+ }
189
+ else {
190
+ // Find smallest w >= minWave such that:
191
+ // 1. !waveIsIsolated[w]
192
+ // 2. waves[w].length < maxWaveSize
193
+ // 3. no entity member in waveIndices[w] conflicts with curr
194
+ let targetWave = minWave;
195
+ let found = false;
196
+ while (targetWave < waves.length) {
197
+ if (!waveIsIsolated[targetWave] && waves[targetWave].length < maxWaveSize) {
198
+ let hasConflict = false;
199
+ for (const member of waveIndices[targetWave]) {
200
+ if (conflicts[curr].has(member)) {
201
+ hasConflict = true;
202
+ break;
203
+ }
204
+ }
205
+ if (!hasConflict) {
206
+ found = true;
207
+ break;
208
+ }
209
+ }
210
+ targetWave++;
211
+ }
212
+ if (!found) {
213
+ waves[targetWave] = [e];
214
+ waveIndices[targetWave] = new Set([curr]);
215
+ waveIsIsolated[targetWave] = false;
216
+ }
217
+ else {
218
+ waves[targetWave].push(e);
219
+ waveIndices[targetWave].add(curr);
220
+ }
221
+ entityWaveIndex.set(curr, targetWave);
222
+ }
223
+ placed.add(curr);
224
+ for (const dep of dependentsOf[curr]) {
225
+ if (inDegree[dep] > 0) {
226
+ inDegree[dep]--;
227
+ }
228
+ }
229
+ }
230
+ }
231
+ return waves.filter(w => Array.isArray(w) && w.length > 0);
232
+ }
233
+ /** @deprecated Use {@link PartitionEntitiesIntoConflictFreeWaves}. */
234
+ export const partitionEntitiesIntoConflictFreeWaves = PartitionEntitiesIntoConflictFreeWaves;
34
235
  /**
35
236
  * The parent columns an IS-A child's generated base view selects, in parent-chain order and each
36
237
  * parent's field order. The child's view joins each parent's BASE TABLE, so a column qualifies only
@@ -254,6 +455,17 @@ export class SQLCodeGenBase {
254
455
  * {@link isRoutineDefinitionDrifted} to detect any other difference from the generated body.
255
456
  */
256
457
  this.existingRoutineDefinitions = null;
458
+ /**
459
+ * Map of `schema.view` (lowercased) to its live `OBJECT_DEFINITION` text on SQL Server,
460
+ * preloaded in one bulk query to eliminate per-entity round-trips in `checkBaseViewChangedInDB`.
461
+ */
462
+ this.existingBaseViewDefinitions = null;
463
+ /**
464
+ * Map of `schema.view` (lowercased) to its live column name Set (lowercased) on PostgreSQL,
465
+ * preloaded in one bulk query to eliminate per-entity round-trips in `checkBaseViewColumnsChangedPG`.
466
+ */
467
+ this.existingBaseViewColumnsPG = null;
468
+ this._bufferedWaveLogEntries = null;
257
469
  /**
258
470
  * `schema.routine` keys of CRUD routines whose live definition differed from the body generated
259
471
  * this run, so they were force-logged and re-executed. Reported once after generation.
@@ -342,12 +554,13 @@ export class SQLCodeGenBase {
342
554
  else {
343
555
  SucceedSpinner(`Custom SQL scripts completed (${(new Date().getTime() - startTime.getTime()) / 1000}s)`);
344
556
  }
345
- await this.loadExistingRoutines(pool, entities);
346
557
  // ALWAYS use the first filter where we only include entities that have IncludeInAPI = 1
347
558
  // Entities are already sorted by name in PostProcessEntityMetadata (see providerBase.ts)
348
559
  const baselineEntities = entities.filter(e => e.IncludeInAPI);
349
560
  // OPTIMIZATION: Use a Set for O(1) lookups instead of O(n) array finds to improve performance
350
561
  const includedEntities = EntitiesNotInExcludedSchemas(baselineEntities, configInfo.excludeSchemas);
562
+ await this.loadExistingRoutines(pool, entities);
563
+ await this.loadExistingBaseViews(pool, includedEntities);
351
564
  // Initialize temp batch files for each schema
352
565
  // These will be populated as SQL is generated and will be used for actual execution
353
566
  const schemas = Array.from(new Set(baselineEntities.map(e => e.SchemaName))).sort();
@@ -412,21 +625,19 @@ export class SQLCodeGenBase {
412
625
  const globalWillRegenerate = new Set(allBatchEntities
413
626
  .filter(e => !!e.BaseView)
414
627
  .map(e => `${e.SchemaName}.${e.BaseView}`));
415
- // PostgreSQL must serialize per-entity processing. Each PG entity's
416
- // phased execution (view → CRUD → permissions) issues
417
- // CREATE OR REPLACE VIEW with a 42P16 fallback that does
418
- // capture/DROP CASCADE/CREATE/restore via pg_depend. Running this
419
- // in parallel against entities with cross-references (e.g.
420
- // vwAIModels ←→ vwAIModelVendors, view + dependent function) hits
421
- // catalog-level deadlocks ("ERROR: deadlock detected") and the
422
- // deadlock victim's transaction rolls back leaving its dependents
423
- // dropped but never recreated — net effect: 11+ views silently
424
- // missing after one codegen run, then the next run crashes during
425
- // AI Engine init because vwAIModels is gone. SQL Server doesn't
426
- // hit this because its execution path is bulk-monolithic, not
427
- // phased per-entity.
628
+ // PostgreSQL executes entities in conflict-free waves via PartitionEntitiesIntoConflictFreeWaves,
629
+ // bounded by MAX_PG_PHASED_WAVE_CONCURRENCY. Within each wave, entities run concurrently
630
+ // across pooled clients, while RunExclusiveDropCascade serializes any 42P16 DROP VIEW ... CASCADE
631
+ // fallback transactions to prevent catalog deadlocks on pg_depend.
632
+ // When useProviderPhasedExecution is false, perEntityBatchSize is 1.
633
+ // Note that cascadeGenResult below remains batchSize: 1.
428
634
  const configuredBatch = configInfo.fileEmit?.sqlEntityBatchSize ?? 8;
429
635
  const perEntityBatchSize = configInfo.dbPlatform === 'postgresql' ? 1 : configuredBatch;
636
+ let entityWaves;
637
+ if (useProviderPhasedExecution && configuredBatch > 1) {
638
+ const maxWaveSize = Math.min(configuredBatch, MAX_PG_PHASED_WAVE_CONCURRENCY);
639
+ entityWaves = PartitionEntitiesIntoConflictFreeWaves(entitiesWithoutCascadeRegeneration, maxWaveSize);
640
+ }
430
641
  // Generate SQL for entities that don't need cascade delete regeneration
431
642
  const genResult = await this.GenerateAndExecuteEntitySQLToSeparateFiles({
432
643
  pool,
@@ -438,6 +649,7 @@ export class SQLCodeGenBase {
438
649
  skipExecution: perEntitySkipExecution,
439
650
  writeFiles: true,
440
651
  batchSize: perEntityBatchSize,
652
+ waves: entityWaves,
441
653
  enableSQLLoggingForNewOrModifiedEntities: true,
442
654
  willRegenerate: globalWillRegenerate
443
655
  }); // enable sql logging for NEW entities....
@@ -551,6 +763,9 @@ export class SQLCodeGenBase {
551
763
  else {
552
764
  SucceedSpinner('Custom base views refreshed');
553
765
  }
766
+ // Invalidate preloaded base view caches so late-phase regeneration reads fresh DB state
767
+ this.existingBaseViewDefinitions = null;
768
+ this.existingBaseViewColumnsPG = null;
554
769
  const manageMD = MJGlobal.Instance.ClassFactory.CreateInstance(ManageMetadataBase);
555
770
  // 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
556
771
  // we CAN skip the entity field values part because that wouldn't change from the first time we ran it
@@ -905,8 +1120,7 @@ export class SQLCodeGenBase {
905
1120
  * @param onlyPermissions If true, only the permissions files will be generated and executed, not the actual SQL files. Use this if you are simply setting permission changes but no actual changes to the entities have occured.
906
1121
  */
907
1122
  async GenerateAndExecuteEntitySQLToSeparateFiles(options) {
908
- if (!options.batchSize)
909
- options.batchSize = 5; // default to 5 if not specified
1123
+ const batchSize = options.batchSize ?? 5;
910
1124
  const files = [];
911
1125
  try {
912
1126
  const failedEntities = [];
@@ -920,33 +1134,68 @@ export class SQLCodeGenBase {
920
1134
  const willRegenerate = options.willRegenerate ?? new Set(options.entities.map(e => `${e.SchemaName}.${e.BaseView}`));
921
1135
  const phaseLabel = options.progressLabel ?? (options.onlyPermissions ? 'Applying permissions' : 'Generating SQL');
922
1136
  const phaseStart = Date.now();
923
- for (let i = 0; i < totalEntities; i += options.batchSize) {
924
- const batch = options.entities.slice(i, i + options.batchSize);
925
- this.reportEntityBatchProgress(phaseLabel, i, totalEntities, batch[0], phaseStart);
926
- const promises = batch.map(async (e) => {
927
- const pkeyField = e.Fields.find(f => f.IsPrimaryKey);
928
- if (!pkeyField) {
929
- logError(`SKIPPING SQL GENERATION: Entity ${e.Name} has no primary key field in metadata. If using soft primary keys, ensure metadata was refreshed after applySoftPKFKConfig().`);
930
- return { entity: e, result: { Success: false, Files: [] } };
1137
+ const waves = options.waves && options.waves.length > 0 ? options.waves : null;
1138
+ let processedEntities = 0;
1139
+ const batchIterator = waves
1140
+ ? waves.map(w => {
1141
+ const offset = processedEntities;
1142
+ processedEntities += w.length;
1143
+ return { batch: w, offset };
1144
+ })
1145
+ : Array.from({ length: Math.ceil(totalEntities / batchSize) }, (_, idx) => {
1146
+ const offset = idx * batchSize;
1147
+ return { batch: options.entities.slice(offset, offset + batchSize), offset };
1148
+ });
1149
+ for (const { batch, offset } of batchIterator) {
1150
+ if (batch.length === 0)
1151
+ continue;
1152
+ this.reportEntityBatchProgress(phaseLabel, offset, totalEntities, batch[0], phaseStart);
1153
+ const useBuffering = batch.length > 1;
1154
+ if (useBuffering) {
1155
+ this._bufferedWaveLogEntries = new Map();
1156
+ for (const e of batch) {
1157
+ this._bufferedWaveLogEntries.set(e.ID, []);
931
1158
  }
932
- const result = await this.GenerateAndExecuteSingleEntitySQLToSeparateFiles({
933
- pool: options.pool,
934
- entity: e,
935
- directory: options.directory,
936
- onlyPermissions: options.onlyPermissions,
937
- writeFiles: options.writeFiles,
938
- skipExecution: options.skipExecution,
939
- enableSQLLoggingForNewOrModifiedEntities: options.enableSQLLoggingForNewOrModifiedEntities,
940
- willRegenerate,
1159
+ }
1160
+ try {
1161
+ const promises = batch.map(async (e) => {
1162
+ const pkeyField = e.Fields.find(f => f.IsPrimaryKey);
1163
+ if (!pkeyField) {
1164
+ logError(`SKIPPING SQL GENERATION: Entity ${e.Name} has no primary key field in metadata. If using soft primary keys, ensure metadata was refreshed after applySoftPKFKConfig().`);
1165
+ return { entity: e, result: { Success: false, Files: [] } };
1166
+ }
1167
+ const result = await this.GenerateAndExecuteSingleEntitySQLToSeparateFiles({
1168
+ pool: options.pool,
1169
+ entity: e,
1170
+ directory: options.directory,
1171
+ onlyPermissions: options.onlyPermissions,
1172
+ writeFiles: options.writeFiles,
1173
+ skipExecution: options.skipExecution,
1174
+ enableSQLLoggingForNewOrModifiedEntities: options.enableSQLLoggingForNewOrModifiedEntities,
1175
+ willRegenerate,
1176
+ });
1177
+ return { entity: e, result };
941
1178
  });
942
- return { entity: e, result };
943
- });
944
- const results = await Promise.all(promises);
945
- results.forEach(({ entity, result }) => {
946
- if (!result.Success)
947
- failedEntities.push(entity);
948
- files.push(...result.Files); // add the files to the main files array
949
- });
1179
+ const results = await Promise.all(promises);
1180
+ results.forEach(({ entity, result }) => {
1181
+ if (!result.Success)
1182
+ failedEntities.push(entity);
1183
+ files.push(...result.Files); // add the files to the main files array
1184
+ });
1185
+ }
1186
+ finally {
1187
+ if (useBuffering && this._bufferedWaveLogEntries) {
1188
+ for (const e of batch) {
1189
+ const entries = this._bufferedWaveLogEntries.get(e.ID) ?? [];
1190
+ for (const entry of entries) {
1191
+ SQLLogging.appendToSQLLogFile(entry.Sql, entry.Description);
1192
+ TempBatchFile.appendToTempBatchFile(entry.Sql, entry.SchemaName);
1193
+ }
1194
+ this._bufferedWaveLogEntries.delete(e.ID);
1195
+ }
1196
+ this._bufferedWaveLogEntries = null;
1197
+ }
1198
+ }
950
1199
  }
951
1200
  // Batch summary — makes the full failure scope visible in one pass instead of
952
1201
  // forcing the operator to bisect across individually-logged per-entity errors.
@@ -1048,7 +1297,7 @@ export class SQLCodeGenBase {
1048
1297
  }
1049
1298
  async GenerateAndExecuteSingleEntitySQLToSeparateFiles(options) {
1050
1299
  try {
1051
- const { sql, permissionsSQL, files } = await this.GenerateSingleEntitySQLToSeparateFiles(options); // this creates the files and returns a single string with all the SQL we can then execute
1300
+ const { sql, permissionsSQL, files, phasedSQL } = await this.GenerateSingleEntitySQLToSeparateFiles(options); // this creates the files and returns a single string with all the SQL we can then execute
1052
1301
  if (options.skipExecution) {
1053
1302
  return { Success: true, Files: files };
1054
1303
  }
@@ -1059,7 +1308,7 @@ export class SQLCodeGenBase {
1059
1308
  // is explicitly gated on phase 1 success so we never create fn_*
1060
1309
  // against a missing or stale view rowtype.
1061
1310
  if (!options.onlyPermissions && this._dbProvider.executeEntityPhased) {
1062
- const phaseResult = await this.ExecuteEntityInPhases(options.pool, options.entity, options.willRegenerate);
1311
+ const phaseResult = await this.ExecuteEntityInPhases(options.pool, options.entity, options.willRegenerate, phasedSQL);
1063
1312
  if (!phaseResult.success) {
1064
1313
  const where = phaseResult.phase ?? 'unknown';
1065
1314
  logError(`Phased execution for ${options.entity.SchemaName}.${options.entity.Name} failed in phase "${where}": ${phaseResult.error?.message ?? '(no message)'}`);
@@ -1094,7 +1343,7 @@ export class SQLCodeGenBase {
1094
1343
  * here because it needs access to the internal generators; the provider
1095
1344
  * doesn't own context building for the view.
1096
1345
  */
1097
- async ExecuteEntityInPhases(pool, entity, willRegenerate) {
1346
+ async ExecuteEntityInPhases(pool, entity, willRegenerate, precomputed) {
1098
1347
  // External-data-source entities have no physical MJ table/view/sproc — their data is
1099
1348
  // proxied live. Skip all DDL generation/execution (mirrors the early-return in
1100
1349
  // generateSingleEntitySQLToSeparateFiles). Without this, the view phase would
@@ -1103,72 +1352,97 @@ export class SQLCodeGenBase {
1103
1352
  if (entity.ExternalDataSourceID) {
1104
1353
  return { success: true, phase: null };
1105
1354
  }
1106
- // Pieces needed for the phased executor. Empty string when the entity
1107
- // doesn't warrant that phase's DDL (e.g. virtual entities don't have
1108
- // views; entities with AllowCreateAPI=false don't get fn_create_*).
1109
- // Root-ID TVFs — entities with self-referencing ParentID FKs need a
1110
- // recursive helper function (fn_<table>_<field>_get_root_id) that the
1111
- // base view references. These MUST exist before phase 1 (view) runs;
1112
- // otherwise PG raises `function does not exist` and phase 2 (CRUD)
1113
- // gets gated off.
1114
- // A LAYERED entity still generates. `BaseViewGenerated = 0` means "do not write BaseView",
1115
- // and when GeneratedBaseViewName is set that is exactly the intent — the application owns
1116
- // BaseView while CodeGen keeps writing the inner view underneath it. Gating on
1117
- // BaseViewGenerated alone would skip the inner view and leave the custom layer selecting
1118
- // from an object that does not exist.
1119
- // One pass: overlay already applied → Pass 1 sees extra BaseView columns and logs
1120
- // EntityField INSERTs; Pass 2 DROPs/creates only GeneratedViewName, never the overlay.
1121
- const generatesView = (entity.BaseViewGenerated || entity.HasLayeredBaseView) && !entity.VirtualEntity;
1122
- const tvfSQL = generatesView ? this.generateRecursiveFKTVFs(entity) : '';
1123
- const viewPieces = generatesView
1124
- ? await this.GenerateBaseViewPieces(pool, entity)
1125
- : { viewSQL: '', viewPermSQL: '' };
1126
- const crudCreateSQL = entity.AllowCreateAPI && entity.spCreateGenerated && !entity.VirtualEntity
1127
- ? this.generateSPCreate(entity)
1128
- : '';
1129
- const crudUpdateSQL = entity.AllowUpdateAPI && entity.spUpdateGenerated && !entity.VirtualEntity
1130
- ? this.generateSPUpdate(entity)
1131
- : '';
1132
- const crudDeleteSQL = entity.AllowDeleteAPI && entity.spDeleteGenerated && !entity.VirtualEntity
1133
- ? await this.generateSPDelete(entity, pool)
1134
- : '';
1135
- // Full-text search DDL. Without its own phase the generated
1136
- // *.fulltext.generated.sql is written to disk and then never executed on
1137
- // any provider that implements executeEntityPhased — nothing in the
1138
- // phase list carried it. The search objects were therefore absent while
1139
- // applyPermissions still GRANTed EXECUTE on the search function, and the
1140
- // resulting `function does not exist` failed the whole CodeGen run.
1141
- // Generated here (not in the provider) because building it needs the
1142
- // internal generators and a pool round trip for the PK index name.
1143
- let ftsSQL = '';
1144
- if (entity.FullTextSearchEnabled && !entity.VirtualEntity) {
1145
- try {
1146
- const ft = await this.GenerateEntityFullTextSearchSQL(pool, entity);
1147
- ftsSQL = ft.sql;
1148
- }
1149
- catch (e) {
1150
- return {
1151
- success: false,
1152
- phase: 'fulltext-generate',
1153
- error: e instanceof Error ? e : new Error(String(e)),
1154
- };
1355
+ const onDependentViewUnrestored = (schema, viewName) => {
1356
+ this.existingBaseViewColumnsPG?.delete(`${schema.toLowerCase()}.${viewName.toLowerCase()}`);
1357
+ };
1358
+ let phaseResult;
1359
+ if (precomputed) {
1360
+ phaseResult = await this._dbProvider.executeEntityPhased({
1361
+ entity,
1362
+ tvfSQL: precomputed.TvfSQL,
1363
+ viewSQL: precomputed.ViewSQL,
1364
+ crudCreateSQL: precomputed.CrudCreateSQL,
1365
+ crudUpdateSQL: precomputed.CrudUpdateSQL,
1366
+ crudDeleteSQL: precomputed.CrudDeleteSQL,
1367
+ ftsSQL: precomputed.FtsSQL,
1368
+ viewPermSQL: precomputed.ViewPermSQL,
1369
+ willRegenerate,
1370
+ OnDependentViewUnrestored: onDependentViewUnrestored,
1371
+ });
1372
+ }
1373
+ else {
1374
+ // Pieces needed for the phased executor. Empty string when the entity
1375
+ // doesn't warrant that phase's DDL (e.g. virtual entities don't have
1376
+ // views; entities with AllowCreateAPI=false don't get fn_create_*).
1377
+ // Root-ID TVFs — entities with self-referencing ParentID FKs need a
1378
+ // recursive helper function (fn_<table>_<field>_get_root_id) that the
1379
+ // base view references. These MUST exist before phase 1 (view) runs;
1380
+ // otherwise PG raises `function does not exist` and phase 2 (CRUD)
1381
+ // gets gated off.
1382
+ // A LAYERED entity still generates. `BaseViewGenerated = 0` means "do not write BaseView",
1383
+ // and when GeneratedBaseViewName is set that is exactly the intent — the application owns
1384
+ // BaseView while CodeGen keeps writing the inner view underneath it. Gating on
1385
+ // BaseViewGenerated alone would skip the inner view and leave the custom layer selecting
1386
+ // from an object that does not exist.
1387
+ // One pass: overlay already applied → Pass 1 sees extra BaseView columns and logs
1388
+ // EntityField INSERTs; Pass 2 DROPs/creates only GeneratedViewName, never the overlay.
1389
+ const generatesView = (entity.BaseViewGenerated || entity.HasLayeredBaseView) && !entity.VirtualEntity;
1390
+ const tvfSQL = generatesView ? this.generateRecursiveFKTVFs(entity) : '';
1391
+ const viewPieces = generatesView
1392
+ ? await this.GenerateBaseViewPieces(pool, entity)
1393
+ : { viewSQL: '', viewPermSQL: '' };
1394
+ const crudCreateSQL = entity.AllowCreateAPI && entity.spCreateGenerated && !entity.VirtualEntity
1395
+ ? this.generateSPCreate(entity)
1396
+ : '';
1397
+ const crudUpdateSQL = entity.AllowUpdateAPI && entity.spUpdateGenerated && !entity.VirtualEntity
1398
+ ? this.generateSPUpdate(entity)
1399
+ : '';
1400
+ const crudDeleteSQL = entity.AllowDeleteAPI && entity.spDeleteGenerated && !entity.VirtualEntity
1401
+ ? await this.generateSPDelete(entity, pool)
1402
+ : '';
1403
+ // Full-text search DDL. Without its own phase the generated
1404
+ // *.fulltext.generated.sql is written to disk and then never executed on
1405
+ // any provider that implements executeEntityPhased — nothing in the
1406
+ // phase list carried it. The search objects were therefore absent while
1407
+ // applyPermissions still GRANTed EXECUTE on the search function, and the
1408
+ // resulting `function does not exist` failed the whole CodeGen run.
1409
+ // Generated here (not in the provider) because building it needs the
1410
+ // internal generators and a pool round trip for the PK index name.
1411
+ let ftsSQL = '';
1412
+ if (entity.FullTextSearchEnabled && !entity.VirtualEntity) {
1413
+ try {
1414
+ const ft = await this.GenerateEntityFullTextSearchSQL(pool, entity);
1415
+ ftsSQL = ft.sql;
1416
+ }
1417
+ catch (e) {
1418
+ return {
1419
+ success: false,
1420
+ phase: 'fulltext-generate',
1421
+ error: e instanceof Error ? e : new Error(String(e)),
1422
+ };
1423
+ }
1155
1424
  }
1425
+ phaseResult = await this._dbProvider.executeEntityPhased({
1426
+ entity,
1427
+ tvfSQL,
1428
+ viewSQL: viewPieces.viewSQL,
1429
+ crudCreateSQL,
1430
+ crudUpdateSQL,
1431
+ crudDeleteSQL,
1432
+ ftsSQL,
1433
+ viewPermSQL: viewPieces.viewPermSQL,
1434
+ willRegenerate,
1435
+ OnDependentViewUnrestored: onDependentViewUnrestored,
1436
+ });
1156
1437
  }
1157
- return this._dbProvider.executeEntityPhased({
1158
- entity,
1159
- tvfSQL,
1160
- viewSQL: viewPieces.viewSQL,
1161
- crudCreateSQL,
1162
- crudUpdateSQL,
1163
- crudDeleteSQL,
1164
- ftsSQL,
1165
- viewPermSQL: viewPieces.viewPermSQL,
1166
- willRegenerate,
1167
- });
1438
+ if (phaseResult.success && (entity.BaseViewGenerated || entity.HasLayeredBaseView) && !entity.VirtualEntity && this.existingBaseViewColumnsPG) {
1439
+ this.existingBaseViewColumnsPG.set(`${entity.SchemaName.toLowerCase()}.${entity.GeneratedViewName.toLowerCase()}`, new Set(entity.Fields.map(f => f.Name.toLowerCase())));
1440
+ }
1441
+ return phaseResult;
1168
1442
  }
1169
1443
  /** @deprecated Use {@link ExecuteEntityInPhases}. */
1170
- async executeEntityInPhases(pool, entity, willRegenerate) {
1171
- return this.ExecuteEntityInPhases(pool, entity, willRegenerate);
1444
+ async executeEntityInPhases(pool, entity, willRegenerate, precomputed) {
1445
+ return this.ExecuteEntityInPhases(pool, entity, willRegenerate, precomputed);
1172
1446
  }
1173
1447
  /**
1174
1448
  * Concatenates the hierarchy TVF SQL for every recursive ParentID-style FK
@@ -1227,9 +1501,16 @@ export class SQLCodeGenBase {
1227
1501
  if (configInfo.dbPlatform === 'postgresql') {
1228
1502
  return await this.checkBaseViewColumnsChangedPG(pool, entity, viewName);
1229
1503
  }
1230
- const viewDefSQL = this._dbProvider.getViewDefinitionSQL(entity.SchemaName, viewName);
1231
- const result = await pool.query(viewDefSQL);
1232
- const dbDefinition = result.recordset?.[0]?.ViewDefinition;
1504
+ let dbDefinition;
1505
+ if (this.existingBaseViewDefinitions != null) {
1506
+ const key = `${entity.SchemaName.toLowerCase()}.${viewName.toLowerCase()}`;
1507
+ dbDefinition = this.existingBaseViewDefinitions.get(key);
1508
+ }
1509
+ else {
1510
+ const viewDefSQL = this._dbProvider.getViewDefinitionSQL(entity.SchemaName, viewName);
1511
+ const result = await pool.query(viewDefSQL);
1512
+ dbDefinition = result.recordset?.[0]?.ViewDefinition;
1513
+ }
1233
1514
  if (!dbDefinition) {
1234
1515
  // View doesn't exist in the database. This happens when:
1235
1516
  // 1. The entity is brand new (handled by newEntityList — early return above)
@@ -1276,9 +1557,16 @@ export class SQLCodeGenBase {
1276
1557
  * @returns true if the view's column set differs from the entity's fields (or the view is missing)
1277
1558
  */
1278
1559
  async checkBaseViewColumnsChangedPG(pool, entity, viewName) {
1279
- const sql = `SELECT column_name FROM information_schema.columns WHERE table_schema = '${entity.SchemaName}' AND table_name = '${viewName}'`;
1280
- const result = await pool.query(sql);
1281
- const dbCols = new Set((result.recordset ?? []).map((r) => r.column_name.toLowerCase()));
1560
+ let dbCols;
1561
+ if (this.existingBaseViewColumnsPG != null) {
1562
+ const key = `${entity.SchemaName.toLowerCase()}.${viewName.toLowerCase()}`;
1563
+ dbCols = this.existingBaseViewColumnsPG.get(key) ?? new Set();
1564
+ }
1565
+ else {
1566
+ const sql = `SELECT column_name FROM information_schema.columns WHERE table_schema = '${entity.SchemaName}' AND table_name = '${viewName}'`;
1567
+ const result = await pool.query(sql);
1568
+ dbCols = new Set((result.recordset ?? []).map((r) => String(r.column_name ?? '').toLowerCase()));
1569
+ }
1282
1570
  // Empty set = the view does not exist → force-recreate (missing-view self-heal).
1283
1571
  if (dbCols.size === 0) {
1284
1572
  return true;
@@ -1370,8 +1658,17 @@ export class SQLCodeGenBase {
1370
1658
  }
1371
1659
  }
1372
1660
  if (shouldLog) {
1373
- SQLLogging.appendToSQLLogFile(sql, description);
1374
- TempBatchFile.appendToTempBatchFile(sql, entity.SchemaName);
1661
+ if (this._bufferedWaveLogEntries && this._bufferedWaveLogEntries.has(entity.ID)) {
1662
+ this._bufferedWaveLogEntries.get(entity.ID).push({
1663
+ Sql: sql,
1664
+ Description: description,
1665
+ SchemaName: entity.SchemaName,
1666
+ });
1667
+ }
1668
+ else {
1669
+ SQLLogging.appendToSQLLogFile(sql, description);
1670
+ TempBatchFile.appendToTempBatchFile(sql, entity.SchemaName);
1671
+ }
1375
1672
  }
1376
1673
  LogIf(configInfo.verboseOutput, `SQL Generated for ${entity.Name}: ${description}`);
1377
1674
  return shouldLog;
@@ -1555,6 +1852,13 @@ export class SQLCodeGenBase {
1555
1852
  fs.mkdirSync(schemaDirectory, { recursive: true }); // create the directory if it doesn't exist
1556
1853
  let sRet = '';
1557
1854
  let permissionsSQL = '';
1855
+ let precomputedTVFSQL = '';
1856
+ let precomputedViewSQL = '';
1857
+ let precomputedViewPermSQL = '';
1858
+ let precomputedCrudCreateSQL = '';
1859
+ let precomputedCrudUpdateSQL = '';
1860
+ let precomputedCrudDeleteSQL = '';
1861
+ let precomputedFtsSQL = '';
1558
1862
  // Tracks whether the base view SQL differs from what's in the database.
1559
1863
  // When true, we force-log the view, its permissions, and all SPs (which compile the view in)
1560
1864
  // so the migration log script can fully update target databases.
@@ -1609,16 +1913,25 @@ export class SQLCodeGenBase {
1609
1913
  const tvfFilePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('function', options.entity.SchemaName, fn.functionName, false, true));
1610
1914
  tvfEntries.push({ sql: fn.sql, filePath: tvfFilePath, fieldName: fn.fieldName, description: fn.description });
1611
1915
  // Add function SQL to output BEFORE the view
1612
- sRet += fn.sql + '\n' + this._dbProvider.BatchSeparator + '\n';
1916
+ const piece = fn.sql + '\n' + this._dbProvider.BatchSeparator + '\n';
1917
+ sRet += piece;
1918
+ precomputedTVFSQL += piece;
1613
1919
  }
1614
1920
  }
1615
1921
  }
1616
1922
  // Generate the base view (which may reference the TVFs created above)
1617
- const s = this.GenerateSingleEntitySQLFileHeader(options.entity, options.entity.GeneratedViewName) + await this.GenerateBaseView(options.pool, options.entity);
1923
+ const viewPieces = await this.GenerateBaseViewPieces(options.pool, options.entity);
1924
+ precomputedViewSQL = viewPieces.viewSQL;
1925
+ precomputedViewPermSQL = viewPieces.viewPermSQL;
1926
+ const viewBaseSQL = viewPieces.viewSQL + viewPieces.viewPermSQL;
1927
+ const s = this.GenerateSingleEntitySQLFileHeader(options.entity, options.entity.GeneratedViewName) + viewBaseSQL;
1618
1928
  // Compare generated view SQL against what's currently in the database.
1619
1929
  // If the SELECT body differs, force-log just this base view via the forceLog flag
1620
1930
  // so logging stays centralized in logSQLForNewOrModifiedEntity.
1621
1931
  baseViewChanged = await this.checkBaseViewChangedInDB(options.pool, options.entity, s);
1932
+ // The alternate-view rebinds are appended after the comparison so they never count
1933
+ // as a view change; see appendAlternateBaseViewRebindsForLog.
1934
+ const sLogged = this.appendAlternateBaseViewRebindsForLog(options.entity, s);
1622
1935
  // Now log TVFs with baseViewChanged as forceLog, ensuring they're included
1623
1936
  // in TempBatchFile whenever the view that depends on them is also included
1624
1937
  if (options.writeFiles) {
@@ -1630,15 +1943,15 @@ export class SQLCodeGenBase {
1630
1943
  }
1631
1944
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('view', options.entity.SchemaName, options.entity.GeneratedViewName, false, true));
1632
1945
  if (options.writeFiles) {
1633
- this.writeFileIfChanged(filePath, s);
1634
- const viewLogged = this.logSQLForNewOrModifiedEntity(options.entity, s, `Base View SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, baseViewChanged);
1946
+ this.writeFileIfChanged(filePath, sLogged);
1947
+ const viewLogged = this.logSQLForNewOrModifiedEntity(options.entity, sLogged, `Base View SQL for ${options.entity.Name}`, options.enableSQLLoggingForNewOrModifiedEntities, baseViewChanged);
1635
1948
  if (viewLogged && options.entity.HasLayeredBaseView) {
1636
1949
  this.layeredEntitiesWithLoggedInnerView.add(options.entity.Name);
1637
1950
  this.logLayeredOuterViewRefresh(options.entity);
1638
1951
  }
1639
1952
  files.push(filePath);
1640
1953
  }
1641
- sRet += s + '\n' + this._dbProvider.BatchSeparator + '\n';
1954
+ sRet += sLogged + '\n' + this._dbProvider.BatchSeparator + '\n';
1642
1955
  }
1643
1956
  // always generate permissions for the base view
1644
1957
  const permHeader = this.GenerateSingleEntitySQLFileHeader(options.entity, 'Permissions for ' + options.entity.BaseView);
@@ -1679,7 +1992,8 @@ export class SQLCodeGenBase {
1679
1992
  // forceRegeneration only forces regeneration of SPs where spCreateGenerated=true
1680
1993
  if (!options.onlyPermissions && options.entity.spCreateGenerated) {
1681
1994
  // generate the create SP
1682
- const s = this.GenerateSingleEntitySQLFileHeader(options.entity, spName) + this.generateSPCreate(options.entity);
1995
+ precomputedCrudCreateSQL = this.generateSPCreate(options.entity);
1996
+ const s = this.GenerateSingleEntitySQLFileHeader(options.entity, spName) + precomputedCrudCreateSQL;
1683
1997
  if (options.writeFiles) {
1684
1998
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, false, true));
1685
1999
  this.writeFileIfChanged(filePath, s);
@@ -1712,7 +2026,8 @@ export class SQLCodeGenBase {
1712
2026
  // forceRegeneration only forces regeneration of SPs where spUpdateGenerated=true
1713
2027
  if (!options.onlyPermissions && options.entity.spUpdateGenerated) {
1714
2028
  // generate the update SP
1715
- const s = this.GenerateSingleEntitySQLFileHeader(options.entity, spName) + this.generateSPUpdate(options.entity);
2029
+ precomputedCrudUpdateSQL = this.generateSPUpdate(options.entity);
2030
+ const s = this.GenerateSingleEntitySQLFileHeader(options.entity, spName) + precomputedCrudUpdateSQL;
1716
2031
  if (options.writeFiles) {
1717
2032
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, false, true));
1718
2033
  this.writeFileIfChanged(filePath, s);
@@ -1751,7 +2066,8 @@ export class SQLCodeGenBase {
1751
2066
  if (this.entitiesNeedingDeleteSPRegeneration.has(options.entity.ID)) {
1752
2067
  logStatus(` Regenerating ${spName} due to cascade dependency changes`);
1753
2068
  }
1754
- const s = this.GenerateSingleEntitySQLFileHeader(options.entity, spName) + await this.generateSPDelete(options.entity, options.pool);
2069
+ precomputedCrudDeleteSQL = await this.generateSPDelete(options.entity, options.pool);
2070
+ const s = this.GenerateSingleEntitySQLFileHeader(options.entity, spName) + precomputedCrudDeleteSQL;
1755
2071
  if (options.writeFiles) {
1756
2072
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, false, true));
1757
2073
  this.writeFileIfChanged(filePath, s);
@@ -1780,6 +2096,9 @@ export class SQLCodeGenBase {
1780
2096
  // always generate the code so we can get the function name from the below function call
1781
2097
  const ft = await this.GenerateEntityFullTextSearchSQL(options.pool, options.entity);
1782
2098
  if (!options.onlyPermissions) {
2099
+ if (options.entity.FullTextSearchEnabled && !options.entity.VirtualEntity) {
2100
+ precomputedFtsSQL = ft.sql;
2101
+ }
1783
2102
  // only write the actual sql out if we're not only generating permissions
1784
2103
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('full_text_search_function', options.entity.SchemaName, options.entity.BaseTable, false, true));
1785
2104
  if (options.writeFiles) {
@@ -1803,7 +2122,16 @@ export class SQLCodeGenBase {
1803
2122
  if (!options.entity.FullTextSearchFunctionGenerated)
1804
2123
  sRet += sP + '\n' + this._dbProvider.BatchSeparator + '\n';
1805
2124
  }
1806
- return { sql: sRet, permissionsSQL: permissionsSQL, files: files };
2125
+ const phasedSQL = options.onlyPermissions ? undefined : {
2126
+ TvfSQL: precomputedTVFSQL,
2127
+ ViewSQL: precomputedViewSQL,
2128
+ CrudCreateSQL: precomputedCrudCreateSQL,
2129
+ CrudUpdateSQL: precomputedCrudUpdateSQL,
2130
+ CrudDeleteSQL: options.entity.spDeleteGenerated ? precomputedCrudDeleteSQL : '',
2131
+ FtsSQL: precomputedFtsSQL,
2132
+ ViewPermSQL: precomputedViewPermSQL,
2133
+ };
2134
+ return { sql: sRet, permissionsSQL: permissionsSQL, files: files, phasedSQL };
1807
2135
  }
1808
2136
  catch (err) {
1809
2137
  logError(err);
@@ -1865,6 +2193,62 @@ export class SQLCodeGenBase {
1865
2193
  this.existingRoutineDefinitions = null;
1866
2194
  }
1867
2195
  }
2196
+ /**
2197
+ * Snapshot base view definitions (SQL Server) or column sets (PostgreSQL) in one bulk query
2198
+ * so `checkBaseViewChangedInDB` / `checkBaseViewColumnsChangedPG` perform O(1) in-memory checks
2199
+ * without 400+ per-entity database queries.
2200
+ */
2201
+ async loadExistingBaseViews(pool, entities) {
2202
+ this.existingBaseViewDefinitions = null;
2203
+ this.existingBaseViewColumnsPG = null;
2204
+ const schemas = [...new Set(entities.map((e) => e.SchemaName).filter((s) => !!s))];
2205
+ if (schemas.length === 0) {
2206
+ return;
2207
+ }
2208
+ const inList = schemas.map((s) => `'${s.replace(/'/g, "''")}'`).join(', ');
2209
+ try {
2210
+ if (this._dbProvider.PlatformKey === 'postgresql' || configInfo.dbPlatform === 'postgresql') {
2211
+ const sql = `SELECT table_schema, table_name, column_name FROM information_schema.columns WHERE table_schema IN (${inList})`;
2212
+ const result = await pool.query(sql);
2213
+ const colsMap = new Map();
2214
+ for (const row of (result.recordset ?? [])) {
2215
+ const schema = String(row.table_schema ?? '').toLowerCase();
2216
+ const table = String(row.table_name ?? '').toLowerCase();
2217
+ const col = String(row.column_name ?? '').toLowerCase();
2218
+ if (schema && table && col) {
2219
+ const key = `${schema}.${table}`;
2220
+ let set = colsMap.get(key);
2221
+ if (!set) {
2222
+ set = new Set();
2223
+ colsMap.set(key, set);
2224
+ }
2225
+ set.add(col);
2226
+ }
2227
+ }
2228
+ this.existingBaseViewColumnsPG = colsMap;
2229
+ }
2230
+ else if (this._dbProvider.PlatformKey === 'sqlserver') {
2231
+ const sql = `SELECT s.name AS schema_name, v.name AS view_name, OBJECT_DEFINITION(v.object_id) AS view_definition ` +
2232
+ `FROM sys.views v INNER JOIN sys.schemas s ON s.schema_id = v.schema_id WHERE s.name IN (${inList})`;
2233
+ const result = await pool.query(sql);
2234
+ const defsMap = new Map();
2235
+ for (const row of (result.recordset ?? [])) {
2236
+ const schema = String(row.schema_name ?? '').toLowerCase();
2237
+ const view = String(row.view_name ?? '').toLowerCase();
2238
+ const def = row.view_definition != null ? String(row.view_definition) : '';
2239
+ if (schema && view && def) {
2240
+ defsMap.set(`${schema}.${view}`, def);
2241
+ }
2242
+ }
2243
+ this.existingBaseViewDefinitions = defsMap;
2244
+ }
2245
+ }
2246
+ catch (e) {
2247
+ LogWarning(`Could not preload existing base view definitions: ${e instanceof Error ? e.message : String(e)}`);
2248
+ this.existingBaseViewDefinitions = null;
2249
+ this.existingBaseViewColumnsPG = null;
2250
+ }
2251
+ }
1868
2252
  isRoutineMissing(schema, routineName) {
1869
2253
  if (!this.existingRoutines) {
1870
2254
  return false;
@@ -2353,6 +2737,11 @@ export class SQLCodeGenBase {
2353
2737
  }
2354
2738
  return joins.join('\n');
2355
2739
  }
2740
+ /**
2741
+ * Generates the base view SQL including permissions.
2742
+ * Note: Subclasses should override {@link GenerateBaseViewPieces} instead of this method
2743
+ * so phased execution can run view creation and permissions in separate phases.
2744
+ */
2356
2745
  async GenerateBaseView(pool, entity) {
2357
2746
  const { viewSQL, viewPermSQL } = await this.GenerateBaseViewPieces(pool, entity);
2358
2747
  return viewSQL + viewPermSQL;
@@ -2435,6 +2824,28 @@ export class SQLCodeGenBase {
2435
2824
  viewPermSQL: permissions,
2436
2825
  };
2437
2826
  }
2827
+ /**
2828
+ * Appends the alternate-base-view rebind statements to the base view SQL that is written to the
2829
+ * view file and logged into the migration / bake capture (#6539).
2830
+ *
2831
+ * On platforms that refresh views (SQL Server) {@link GenerateBaseViewPieces} already folds these
2832
+ * statements into `viewSQL`, so `viewSQL` is returned unchanged. On platforms that do not
2833
+ * (PostgreSQL) the phased executor rebinds alternate views live, but nothing put the rebinds in
2834
+ * the logged SQL, so every release file and migrate-only install kept each `vw*Active` view at
2835
+ * its old column list. Layered entities get their rebinds from the layered refresh path instead.
2836
+ * `viewSQL` itself is left alone so the phased executor does not run the rebinds twice.
2837
+ */
2838
+ appendAlternateBaseViewRebindsForLog(entity, viewSQL) {
2839
+ if (this._dbProvider.NeedsViewRefresh || entity.HasLayeredBaseView) {
2840
+ return viewSQL;
2841
+ }
2842
+ const rebinds = this.getAlternateBaseViewRefreshStatements(entity);
2843
+ if (rebinds.length === 0) {
2844
+ return viewSQL;
2845
+ }
2846
+ const separator = '\n' + this._dbProvider.BatchSeparator + '\n';
2847
+ return viewSQL + separator + rebinds.join(separator);
2848
+ }
2438
2849
  /** @deprecated Use {@link GenerateBaseViewPieces}. */
2439
2850
  async generateBaseViewPieces(pool, entity) {
2440
2851
  return this.GenerateBaseViewPieces(pool, entity);
@@ -2768,7 +3179,7 @@ export class SQLCodeGenBase {
2768
3179
  const parts = pkFields.map(pk => dialect.CastToBoundedString(`${qi(classNameFirstChar)}.${qi(pk.Name)}`, 200));
2769
3180
  recordIdExpr = parts.join(` ${concat} '||' ${concat} `);
2770
3181
  }
2771
- sOutput += `LEFT OUTER JOIN\n ${qs(mjCoreSchema, 'vwRecordGeoCodes')} AS __mj_rgc\n ON\n __mj_rgc.${qi('EntityID')} = '${entity.ID}'\n AND __mj_rgc.${qi('RecordID')} = ${recordIdExpr}\n AND __mj_rgc.${qi('LocationType')} = 'Primary'`;
3182
+ sOutput += `LEFT OUTER JOIN\n ${qs(mjCoreSchema, 'RecordGeoCode')} AS __mj_rgc\n ON\n __mj_rgc.${qi('EntityID')} = '${entity.ID}'\n AND __mj_rgc.${qi('RecordID')} = ${recordIdExpr}\n AND __mj_rgc.${qi('LocationType')} = 'Primary'`;
2772
3183
  }
2773
3184
  sOutput += this.generateEmbeddedGeoJoins(entity, classNameFirstChar);
2774
3185
  return sOutput;