@memberjunction/codegen-lib 6.2.2 → 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 (117) hide show
  1. package/README.md +38 -1
  2. package/dist/Angular/angular-codegen.js +1 -1
  3. package/dist/Config/config.d.ts +46 -0
  4. package/dist/Config/config.d.ts.map +1 -1
  5. package/dist/Config/config.js +17 -0
  6. package/dist/Config/config.js.map +1 -1
  7. package/dist/Database/codeGenDatabaseProvider.d.ts +7 -1
  8. package/dist/Database/codeGenDatabaseProvider.d.ts.map +1 -1
  9. package/dist/Database/codeGenDatabaseProvider.js +23 -1
  10. package/dist/Database/codeGenDatabaseProvider.js.map +1 -1
  11. package/dist/Database/config-retraction.d.ts +126 -0
  12. package/dist/Database/config-retraction.d.ts.map +1 -0
  13. package/dist/Database/config-retraction.js +151 -0
  14. package/dist/Database/config-retraction.js.map +1 -0
  15. package/dist/Database/manage-metadata.d.ts +196 -21
  16. package/dist/Database/manage-metadata.d.ts.map +1 -1
  17. package/dist/Database/manage-metadata.js +911 -259
  18. package/dist/Database/manage-metadata.js.map +1 -1
  19. package/dist/Database/organic-key-sync.d.ts +70 -0
  20. package/dist/Database/organic-key-sync.d.ts.map +1 -0
  21. package/dist/Database/organic-key-sync.js +83 -0
  22. package/dist/Database/organic-key-sync.js.map +1 -0
  23. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts +7 -0
  24. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.d.ts.map +1 -1
  25. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js +83 -19
  26. package/dist/Database/providers/postgresql/PostgreSQLCodeGenProvider.js.map +1 -1
  27. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js +14 -0
  28. package/dist/Database/providers/postgresql/__tests__/MetadataSupportObjectsDDL.test.js.map +1 -1
  29. package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.d.ts +2 -0
  30. package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.d.ts.map +1 -0
  31. package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.js +36 -0
  32. package/dist/Database/providers/postgresql/__tests__/NullableKeyReselect.test.js.map +1 -0
  33. package/dist/Database/providers/postgresql/__tests__/PostgreSQLHierarchyFunctions.test.js +5 -0
  34. package/dist/Database/providers/postgresql/__tests__/PostgreSQLHierarchyFunctions.test.js.map +1 -1
  35. package/dist/Database/providers/postgresql/__tests__/SoftPrimaryKeyIndex.test.js +6 -0
  36. package/dist/Database/providers/postgresql/__tests__/SoftPrimaryKeyIndex.test.js.map +1 -1
  37. package/dist/Database/providers/postgresql/metadataSupportObjects.js +64 -18
  38. package/dist/Database/providers/postgresql/metadataSupportObjects.js.map +1 -1
  39. package/dist/Database/providers/postgresql/viewFallback.d.ts +25 -0
  40. package/dist/Database/providers/postgresql/viewFallback.d.ts.map +1 -1
  41. package/dist/Database/providers/postgresql/viewFallback.js +101 -48
  42. package/dist/Database/providers/postgresql/viewFallback.js.map +1 -1
  43. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts +12 -2
  44. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.d.ts.map +1 -1
  45. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js +106 -36
  46. package/dist/Database/providers/sqlserver/SQLServerCodeGenProvider.js.map +1 -1
  47. package/dist/Database/providers/sqlserver/__tests__/BaseViewEmissionGoldenMaster.test.js +65 -7
  48. package/dist/Database/providers/sqlserver/__tests__/BaseViewEmissionGoldenMaster.test.js.map +1 -1
  49. package/dist/Database/providers/sqlserver/__tests__/BaseViewRegenDecision.test.js +30 -3
  50. package/dist/Database/providers/sqlserver/__tests__/BaseViewRegenDecision.test.js.map +1 -1
  51. package/dist/Database/providers/sqlserver/__tests__/SQLServerCodeGenProvider.test.js +41 -0
  52. package/dist/Database/providers/sqlserver/__tests__/SQLServerCodeGenProvider.test.js.map +1 -1
  53. package/dist/Database/providers/sqlserver/__tests__/SoftPrimaryKeyIndex.test.js +6 -0
  54. package/dist/Database/providers/sqlserver/__tests__/SoftPrimaryKeyIndex.test.js.map +1 -1
  55. package/dist/Database/sqlPassFailures.d.ts +26 -0
  56. package/dist/Database/sqlPassFailures.d.ts.map +1 -0
  57. package/dist/Database/sqlPassFailures.js +15 -0
  58. package/dist/Database/sqlPassFailures.js.map +1 -0
  59. package/dist/Database/sql_codegen.d.ts +85 -2
  60. package/dist/Database/sql_codegen.d.ts.map +1 -1
  61. package/dist/Database/sql_codegen.js +573 -128
  62. package/dist/Database/sql_codegen.js.map +1 -1
  63. package/dist/Database/unique-key-sets.d.ts +71 -0
  64. package/dist/Database/unique-key-sets.d.ts.map +1 -0
  65. package/dist/Database/unique-key-sets.js +140 -0
  66. package/dist/Database/unique-key-sets.js.map +1 -0
  67. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts +49 -1
  68. package/dist/Manifest/GenerateClassRegistrationsManifest.d.ts.map +1 -1
  69. package/dist/Manifest/GenerateClassRegistrationsManifest.js +392 -60
  70. package/dist/Manifest/GenerateClassRegistrationsManifest.js.map +1 -1
  71. package/dist/Misc/advanced_generation.d.ts +15 -3
  72. package/dist/Misc/advanced_generation.d.ts.map +1 -1
  73. package/dist/Misc/advanced_generation.js +50 -3
  74. package/dist/Misc/advanced_generation.js.map +1 -1
  75. package/dist/Misc/createNewUser.js +4 -4
  76. package/dist/Misc/createNewUser.js.map +1 -1
  77. package/dist/Misc/entity_subclasses_codegen.d.ts +11 -4
  78. package/dist/Misc/entity_subclasses_codegen.d.ts.map +1 -1
  79. package/dist/Misc/entity_subclasses_codegen.js +46 -14
  80. package/dist/Misc/entity_subclasses_codegen.js.map +1 -1
  81. package/dist/Misc/file-write.d.ts.map +1 -1
  82. package/dist/Misc/file-write.js +16 -10
  83. package/dist/Misc/file-write.js.map +1 -1
  84. package/dist/Misc/smart-field-decision.d.ts +126 -0
  85. package/dist/Misc/smart-field-decision.d.ts.map +1 -0
  86. package/dist/Misc/smart-field-decision.js +222 -0
  87. package/dist/Misc/smart-field-decision.js.map +1 -0
  88. package/dist/Misc/sql_logging.d.ts +3 -1
  89. package/dist/Misc/sql_logging.d.ts.map +1 -1
  90. package/dist/Misc/sql_logging.js +4 -2
  91. package/dist/Misc/sql_logging.js.map +1 -1
  92. package/dist/Misc/system_integrity.d.ts +37 -0
  93. package/dist/Misc/system_integrity.d.ts.map +1 -1
  94. package/dist/Misc/system_integrity.js +74 -8
  95. package/dist/Misc/system_integrity.js.map +1 -1
  96. package/dist/Misc/typed_query_codegen.d.ts +144 -0
  97. package/dist/Misc/typed_query_codegen.d.ts.map +1 -0
  98. package/dist/Misc/typed_query_codegen.js +747 -0
  99. package/dist/Misc/typed_query_codegen.js.map +1 -0
  100. package/dist/Misc/validator-text.d.ts +14 -5
  101. package/dist/Misc/validator-text.d.ts.map +1 -1
  102. package/dist/Misc/validator-text.js +42 -13
  103. package/dist/Misc/validator-text.js.map +1 -1
  104. package/dist/index.d.ts +2 -0
  105. package/dist/index.d.ts.map +1 -1
  106. package/dist/index.js +2 -0
  107. package/dist/index.js.map +1 -1
  108. package/dist/plugins/index.d.ts +10 -0
  109. package/dist/plugins/index.d.ts.map +1 -1
  110. package/dist/plugins/index.js +22 -2
  111. package/dist/plugins/index.js.map +1 -1
  112. package/dist/runCodeGen.d.ts +6 -0
  113. package/dist/runCodeGen.d.ts.map +1 -1
  114. package/dist/runCodeGen.js +75 -16
  115. package/dist/runCodeGen.js.map +1 -1
  116. package/dist/tsconfig.tsbuildinfo +1 -0
  117. 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.
@@ -265,6 +477,12 @@ export class SQLCodeGenBase {
265
477
  * entity is on neither the new nor the modified list (the inner view changed on its own).
266
478
  */
267
479
  this.layeredEntitiesWithLoggedInnerView = new Set();
480
+ /**
481
+ * Every failure recorded by the current {@link ManageSQLScriptsAndExecution} pass, each tied to
482
+ * its entity where it has one. The CRUD self-heal in `runCodeGen` reads this to clear the
483
+ * SQL-pass failure only when it repaired every entry.
484
+ */
485
+ this.sqlPassFailures = [];
268
486
  /**
269
487
  * Names of LAYERED entities whose outer-view refresh was written right after their inner view
270
488
  * ({@link logLayeredOuterViewRefresh}). STEP 2(f) does not log their refresh a second time.
@@ -280,12 +498,21 @@ export class SQLCodeGenBase {
280
498
  set DBProvider(value) {
281
499
  this._dbProvider = value;
282
500
  }
501
+ /** The failures recorded by the last {@link ManageSQLScriptsAndExecution} pass. */
502
+ get SQLPassFailures() {
503
+ return this.sqlPassFailures;
504
+ }
505
+ /** Records a failure of a step that has no single entity, such as a custom SQL script. */
506
+ RecordSQLPassStepFailure(step, message) {
507
+ this.sqlPassFailures.push({ Step: step, EntityName: null, Message: message });
508
+ }
283
509
  async ManageSQLScriptsAndExecution(pool, entities, directory, currentUser) {
284
510
  try {
285
511
  this.existingRoutines = null;
286
512
  this.existingRoutineDefinitions = null;
287
513
  this.driftedRoutines = new Set();
288
514
  this.layeredEntitiesWithLoggedInnerView = new Set();
515
+ this.sqlPassFailures = [];
289
516
  this.layeredEntitiesWithInlineRefresh = new Set();
290
517
  // Build list of entities qualified for forced regeneration if entityWhereClause is provided
291
518
  if (configInfo.forceRegeneration?.enabled && configInfo.forceRegeneration?.entityWhereClause) {
@@ -322,16 +549,18 @@ export class SQLCodeGenBase {
322
549
  const beforeScriptsSucceeded = await this.RunCustomSQLScripts(pool, 'before-sql');
323
550
  if (!beforeScriptsSucceeded) {
324
551
  FailSpinner('Failed to run custom SQL scripts');
552
+ this.RecordSQLPassStepFailure('before-sql scripts', 'One or more before-sql scripts failed');
325
553
  }
326
554
  else {
327
555
  SucceedSpinner(`Custom SQL scripts completed (${(new Date().getTime() - startTime.getTime()) / 1000}s)`);
328
556
  }
329
- await this.loadExistingRoutines(pool, entities);
330
557
  // ALWAYS use the first filter where we only include entities that have IncludeInAPI = 1
331
558
  // Entities are already sorted by name in PostProcessEntityMetadata (see providerBase.ts)
332
559
  const baselineEntities = entities.filter(e => e.IncludeInAPI);
333
560
  // OPTIMIZATION: Use a Set for O(1) lookups instead of O(n) array finds to improve performance
334
561
  const includedEntities = EntitiesNotInExcludedSchemas(baselineEntities, configInfo.excludeSchemas);
562
+ await this.loadExistingRoutines(pool, entities);
563
+ await this.loadExistingBaseViews(pool, includedEntities);
335
564
  // Initialize temp batch files for each schema
336
565
  // These will be populated as SQL is generated and will be used for actual execution
337
566
  const schemas = Array.from(new Set(baselineEntities.map(e => e.SchemaName))).sort();
@@ -396,21 +625,19 @@ export class SQLCodeGenBase {
396
625
  const globalWillRegenerate = new Set(allBatchEntities
397
626
  .filter(e => !!e.BaseView)
398
627
  .map(e => `${e.SchemaName}.${e.BaseView}`));
399
- // PostgreSQL must serialize per-entity processing. Each PG entity's
400
- // phased execution (view → CRUD → permissions) issues
401
- // CREATE OR REPLACE VIEW with a 42P16 fallback that does
402
- // capture/DROP CASCADE/CREATE/restore via pg_depend. Running this
403
- // in parallel against entities with cross-references (e.g.
404
- // vwAIModels ←→ vwAIModelVendors, view + dependent function) hits
405
- // catalog-level deadlocks ("ERROR: deadlock detected") and the
406
- // deadlock victim's transaction rolls back leaving its dependents
407
- // dropped but never recreated — net effect: 11+ views silently
408
- // missing after one codegen run, then the next run crashes during
409
- // AI Engine init because vwAIModels is gone. SQL Server doesn't
410
- // hit this because its execution path is bulk-monolithic, not
411
- // 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.
412
634
  const configuredBatch = configInfo.fileEmit?.sqlEntityBatchSize ?? 8;
413
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
+ }
414
641
  // Generate SQL for entities that don't need cascade delete regeneration
415
642
  const genResult = await this.GenerateAndExecuteEntitySQLToSeparateFiles({
416
643
  pool,
@@ -422,6 +649,7 @@ export class SQLCodeGenBase {
422
649
  skipExecution: perEntitySkipExecution,
423
650
  writeFiles: true,
424
651
  batchSize: perEntityBatchSize,
652
+ waves: entityWaves,
425
653
  enableSQLLoggingForNewOrModifiedEntities: true,
426
654
  willRegenerate: globalWillRegenerate
427
655
  }); // enable sql logging for NEW entities....
@@ -504,6 +732,7 @@ export class SQLCodeGenBase {
504
732
  let overallSuccess = entityGenSuccess && beforeScriptsSucceeded;
505
733
  if (!executionSuccess) {
506
734
  FailSpinner('Failed to execute entity SQL files');
735
+ this.RecordSQLPassStepFailure('Executing entity SQL files', 'One or more entity SQL files had failed batches');
507
736
  TempBatchFile.cleanup(); // Cleanup on error
508
737
  overallSuccess = false;
509
738
  // Continue to manage entity fields metadata even after SQL execution failure.
@@ -528,11 +757,15 @@ export class SQLCodeGenBase {
528
757
  StartSpinner('Refreshing custom base views...');
529
758
  if (!await this.RefreshCustomBaseViewsLive(pool, includedEntities)) {
530
759
  FailSpinner('Failed to refresh one or more custom base views');
760
+ this.RecordSQLPassStepFailure('Refreshing custom base views', 'One or more custom base views failed to refresh');
531
761
  overallSuccess = false;
532
762
  }
533
763
  else {
534
764
  SucceedSpinner('Custom base views refreshed');
535
765
  }
766
+ // Invalidate preloaded base view caches so late-phase regeneration reads fresh DB state
767
+ this.existingBaseViewDefinitions = null;
768
+ this.existingBaseViewColumnsPG = null;
536
769
  const manageMD = MJGlobal.Instance.ClassFactory.CreateInstance(ManageMetadataBase);
537
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
538
771
  // we CAN skip the entity field values part because that wouldn't change from the first time we ran it
@@ -568,6 +801,7 @@ export class SQLCodeGenBase {
568
801
  StartSpinner('Managing entity fields metadata...');
569
802
  if (!await manageMD.manageEntityFields(pool, configInfo.excludeSchemas, true, true, currentUser, false, false, pass2EntityFilter)) {
570
803
  FailSpinner('Failed to manage entity fields');
804
+ this.RecordSQLPassStepFailure('Managing entity fields', 'Entity field sync after SQL generation failed');
571
805
  overallSuccess = false;
572
806
  }
573
807
  else {
@@ -577,6 +811,7 @@ export class SQLCodeGenBase {
577
811
  // STEP 3.1 - stale One To Many relationships (#2071). Runs after Pass 2's unscoped field prune,
578
812
  // so the fields of dropped FK columns are gone. Report-only unless cleanupStaleRelationships is set.
579
813
  if (!await this.CleanupStaleRelationships(pool, manageMD)) {
814
+ this.RecordSQLPassStepFailure('Cleaning up stale relationships', 'Stale One To Many relationship cleanup failed');
580
815
  overallSuccess = false;
581
816
  }
582
817
  // STEP 3.5 - Late-phase view regeneration
@@ -638,6 +873,7 @@ export class SQLCodeGenBase {
638
873
  const step4StartTime = new Date();
639
874
  if (!await this.ApplyPermissions(pool, directory, includedEntities)) {
640
875
  FailSpinner('Failed to apply permissions');
876
+ this.RecordSQLPassStepFailure('Applying permissions', 'One or more permissions files failed');
641
877
  overallSuccess = false;
642
878
  }
643
879
  else {
@@ -652,6 +888,7 @@ export class SQLCodeGenBase {
652
888
  const step5StartTime = new Date();
653
889
  if (!await this.RunCustomSQLScripts(pool, 'after-sql')) {
654
890
  FailSpinner('Failed to run post-generation SQL scripts');
891
+ this.RecordSQLPassStepFailure('after-sql scripts', 'One or more after-sql scripts failed');
655
892
  overallSuccess = false;
656
893
  }
657
894
  else {
@@ -663,12 +900,18 @@ export class SQLCodeGenBase {
663
900
  // now - we need to tell our metadata object to refresh itself
664
901
  const md = new Metadata(); // global-provider-ok: codegen runs offline against a single provider
665
902
  await md.Refresh();
903
+ // A failure that set overallSuccess without recording itself still needs an entry, or
904
+ // the self-heal would find nothing left unrepaired and clear the pass's failure.
905
+ if (!overallSuccess && this.sqlPassFailures.length === 0) {
906
+ this.RecordSQLPassStepFailure('SQL pass', 'SQL generation/execution reported a failure');
907
+ }
666
908
  // Advisory only: an out-of-scope IS-A child's view is another app's to regenerate.
667
909
  await this.WarnOnOutOfScopeISAChildDrift(pool, md.Entities, configInfo.excludeSchemas ?? []);
668
910
  return overallSuccess;
669
911
  }
670
912
  catch (err) {
671
913
  logError(err);
914
+ this.RecordSQLPassStepFailure('SQL pass', `SQL generation/execution threw: ${err instanceof Error ? err.message : String(err)}`);
672
915
  // Clean up temp batch files on error
673
916
  TempBatchFile.cleanup();
674
917
  return false;
@@ -877,8 +1120,7 @@ export class SQLCodeGenBase {
877
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.
878
1121
  */
879
1122
  async GenerateAndExecuteEntitySQLToSeparateFiles(options) {
880
- if (!options.batchSize)
881
- options.batchSize = 5; // default to 5 if not specified
1123
+ const batchSize = options.batchSize ?? 5;
882
1124
  const files = [];
883
1125
  try {
884
1126
  const failedEntities = [];
@@ -892,33 +1134,68 @@ export class SQLCodeGenBase {
892
1134
  const willRegenerate = options.willRegenerate ?? new Set(options.entities.map(e => `${e.SchemaName}.${e.BaseView}`));
893
1135
  const phaseLabel = options.progressLabel ?? (options.onlyPermissions ? 'Applying permissions' : 'Generating SQL');
894
1136
  const phaseStart = Date.now();
895
- for (let i = 0; i < totalEntities; i += options.batchSize) {
896
- const batch = options.entities.slice(i, i + options.batchSize);
897
- this.reportEntityBatchProgress(phaseLabel, i, totalEntities, batch[0], phaseStart);
898
- const promises = batch.map(async (e) => {
899
- const pkeyField = e.Fields.find(f => f.IsPrimaryKey);
900
- if (!pkeyField) {
901
- 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().`);
902
- 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, []);
903
1158
  }
904
- const result = await this.GenerateAndExecuteSingleEntitySQLToSeparateFiles({
905
- pool: options.pool,
906
- entity: e,
907
- directory: options.directory,
908
- onlyPermissions: options.onlyPermissions,
909
- writeFiles: options.writeFiles,
910
- skipExecution: options.skipExecution,
911
- enableSQLLoggingForNewOrModifiedEntities: options.enableSQLLoggingForNewOrModifiedEntities,
912
- 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 };
913
1178
  });
914
- return { entity: e, result };
915
- });
916
- const results = await Promise.all(promises);
917
- results.forEach(({ entity, result }) => {
918
- if (!result.Success)
919
- failedEntities.push(entity);
920
- files.push(...result.Files); // add the files to the main files array
921
- });
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
+ }
922
1199
  }
923
1200
  // Batch summary — makes the full failure scope visible in one pass instead of
924
1201
  // forcing the operator to bisect across individually-logged per-entity errors.
@@ -929,11 +1206,15 @@ export class SQLCodeGenBase {
929
1206
  .map(e => ` - ${e.SchemaName}.${e.Name}`)
930
1207
  .join('\n');
931
1208
  logError(`SQL generation/execution failed for ${failedEntities.length} of ${totalEntities} entity(ies):\n${list}`);
1209
+ for (const e of failedEntities) {
1210
+ this.sqlPassFailures.push({ Step: phaseLabel, EntityName: e.Name, Message: `SQL generation/execution failed for ${e.SchemaName}.${e.Name}` });
1211
+ }
932
1212
  }
933
1213
  return { Success: failedEntities.length === 0, Files: files };
934
1214
  }
935
1215
  catch (err) {
936
1216
  logError(err);
1217
+ this.RecordSQLPassStepFailure('Generating entity SQL', `Entity SQL generation threw: ${err instanceof Error ? err.message : String(err)}`);
937
1218
  return { Success: false, Files: files };
938
1219
  }
939
1220
  }
@@ -1016,7 +1297,7 @@ export class SQLCodeGenBase {
1016
1297
  }
1017
1298
  async GenerateAndExecuteSingleEntitySQLToSeparateFiles(options) {
1018
1299
  try {
1019
- 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
1020
1301
  if (options.skipExecution) {
1021
1302
  return { Success: true, Files: files };
1022
1303
  }
@@ -1027,7 +1308,7 @@ export class SQLCodeGenBase {
1027
1308
  // is explicitly gated on phase 1 success so we never create fn_*
1028
1309
  // against a missing or stale view rowtype.
1029
1310
  if (!options.onlyPermissions && this._dbProvider.executeEntityPhased) {
1030
- const phaseResult = await this.ExecuteEntityInPhases(options.pool, options.entity, options.willRegenerate);
1311
+ const phaseResult = await this.ExecuteEntityInPhases(options.pool, options.entity, options.willRegenerate, phasedSQL);
1031
1312
  if (!phaseResult.success) {
1032
1313
  const where = phaseResult.phase ?? 'unknown';
1033
1314
  logError(`Phased execution for ${options.entity.SchemaName}.${options.entity.Name} failed in phase "${where}": ${phaseResult.error?.message ?? '(no message)'}`);
@@ -1062,7 +1343,7 @@ export class SQLCodeGenBase {
1062
1343
  * here because it needs access to the internal generators; the provider
1063
1344
  * doesn't own context building for the view.
1064
1345
  */
1065
- async ExecuteEntityInPhases(pool, entity, willRegenerate) {
1346
+ async ExecuteEntityInPhases(pool, entity, willRegenerate, precomputed) {
1066
1347
  // External-data-source entities have no physical MJ table/view/sproc — their data is
1067
1348
  // proxied live. Skip all DDL generation/execution (mirrors the early-return in
1068
1349
  // generateSingleEntitySQLToSeparateFiles). Without this, the view phase would
@@ -1071,72 +1352,97 @@ export class SQLCodeGenBase {
1071
1352
  if (entity.ExternalDataSourceID) {
1072
1353
  return { success: true, phase: null };
1073
1354
  }
1074
- // Pieces needed for the phased executor. Empty string when the entity
1075
- // doesn't warrant that phase's DDL (e.g. virtual entities don't have
1076
- // views; entities with AllowCreateAPI=false don't get fn_create_*).
1077
- // Root-ID TVFs — entities with self-referencing ParentID FKs need a
1078
- // recursive helper function (fn_<table>_<field>_get_root_id) that the
1079
- // base view references. These MUST exist before phase 1 (view) runs;
1080
- // otherwise PG raises `function does not exist` and phase 2 (CRUD)
1081
- // gets gated off.
1082
- // A LAYERED entity still generates. `BaseViewGenerated = 0` means "do not write BaseView",
1083
- // and when GeneratedBaseViewName is set that is exactly the intent — the application owns
1084
- // BaseView while CodeGen keeps writing the inner view underneath it. Gating on
1085
- // BaseViewGenerated alone would skip the inner view and leave the custom layer selecting
1086
- // from an object that does not exist.
1087
- // One pass: overlay already applied → Pass 1 sees extra BaseView columns and logs
1088
- // EntityField INSERTs; Pass 2 DROPs/creates only GeneratedViewName, never the overlay.
1089
- const generatesView = (entity.BaseViewGenerated || entity.HasLayeredBaseView) && !entity.VirtualEntity;
1090
- const tvfSQL = generatesView ? this.generateRecursiveFKTVFs(entity) : '';
1091
- const viewPieces = generatesView
1092
- ? await this.GenerateBaseViewPieces(pool, entity)
1093
- : { viewSQL: '', viewPermSQL: '' };
1094
- const crudCreateSQL = entity.AllowCreateAPI && entity.spCreateGenerated && !entity.VirtualEntity
1095
- ? this.generateSPCreate(entity)
1096
- : '';
1097
- const crudUpdateSQL = entity.AllowUpdateAPI && entity.spUpdateGenerated && !entity.VirtualEntity
1098
- ? this.generateSPUpdate(entity)
1099
- : '';
1100
- const crudDeleteSQL = entity.AllowDeleteAPI && entity.spDeleteGenerated && !entity.VirtualEntity
1101
- ? await this.generateSPDelete(entity, pool)
1102
- : '';
1103
- // Full-text search DDL. Without its own phase the generated
1104
- // *.fulltext.generated.sql is written to disk and then never executed on
1105
- // any provider that implements executeEntityPhased — nothing in the
1106
- // phase list carried it. The search objects were therefore absent while
1107
- // applyPermissions still GRANTed EXECUTE on the search function, and the
1108
- // resulting `function does not exist` failed the whole CodeGen run.
1109
- // Generated here (not in the provider) because building it needs the
1110
- // internal generators and a pool round trip for the PK index name.
1111
- let ftsSQL = '';
1112
- if (entity.FullTextSearchEnabled && !entity.VirtualEntity) {
1113
- try {
1114
- const ft = await this.GenerateEntityFullTextSearchSQL(pool, entity);
1115
- ftsSQL = ft.sql;
1116
- }
1117
- catch (e) {
1118
- return {
1119
- success: false,
1120
- phase: 'fulltext-generate',
1121
- error: e instanceof Error ? e : new Error(String(e)),
1122
- };
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
+ }
1123
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
+ });
1124
1437
  }
1125
- return this._dbProvider.executeEntityPhased({
1126
- entity,
1127
- tvfSQL,
1128
- viewSQL: viewPieces.viewSQL,
1129
- crudCreateSQL,
1130
- crudUpdateSQL,
1131
- crudDeleteSQL,
1132
- ftsSQL,
1133
- viewPermSQL: viewPieces.viewPermSQL,
1134
- willRegenerate,
1135
- });
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;
1136
1442
  }
1137
1443
  /** @deprecated Use {@link ExecuteEntityInPhases}. */
1138
- async executeEntityInPhases(pool, entity, willRegenerate) {
1139
- return this.ExecuteEntityInPhases(pool, entity, willRegenerate);
1444
+ async executeEntityInPhases(pool, entity, willRegenerate, precomputed) {
1445
+ return this.ExecuteEntityInPhases(pool, entity, willRegenerate, precomputed);
1140
1446
  }
1141
1447
  /**
1142
1448
  * Concatenates the hierarchy TVF SQL for every recursive ParentID-style FK
@@ -1195,9 +1501,16 @@ export class SQLCodeGenBase {
1195
1501
  if (configInfo.dbPlatform === 'postgresql') {
1196
1502
  return await this.checkBaseViewColumnsChangedPG(pool, entity, viewName);
1197
1503
  }
1198
- const viewDefSQL = this._dbProvider.getViewDefinitionSQL(entity.SchemaName, viewName);
1199
- const result = await pool.query(viewDefSQL);
1200
- 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
+ }
1201
1514
  if (!dbDefinition) {
1202
1515
  // View doesn't exist in the database. This happens when:
1203
1516
  // 1. The entity is brand new (handled by newEntityList — early return above)
@@ -1244,9 +1557,16 @@ export class SQLCodeGenBase {
1244
1557
  * @returns true if the view's column set differs from the entity's fields (or the view is missing)
1245
1558
  */
1246
1559
  async checkBaseViewColumnsChangedPG(pool, entity, viewName) {
1247
- const sql = `SELECT column_name FROM information_schema.columns WHERE table_schema = '${entity.SchemaName}' AND table_name = '${viewName}'`;
1248
- const result = await pool.query(sql);
1249
- 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
+ }
1250
1570
  // Empty set = the view does not exist → force-recreate (missing-view self-heal).
1251
1571
  if (dbCols.size === 0) {
1252
1572
  return true;
@@ -1338,8 +1658,17 @@ export class SQLCodeGenBase {
1338
1658
  }
1339
1659
  }
1340
1660
  if (shouldLog) {
1341
- SQLLogging.appendToSQLLogFile(sql, description);
1342
- 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
+ }
1343
1672
  }
1344
1673
  LogIf(configInfo.verboseOutput, `SQL Generated for ${entity.Name}: ${description}`);
1345
1674
  return shouldLog;
@@ -1523,6 +1852,13 @@ export class SQLCodeGenBase {
1523
1852
  fs.mkdirSync(schemaDirectory, { recursive: true }); // create the directory if it doesn't exist
1524
1853
  let sRet = '';
1525
1854
  let permissionsSQL = '';
1855
+ let precomputedTVFSQL = '';
1856
+ let precomputedViewSQL = '';
1857
+ let precomputedViewPermSQL = '';
1858
+ let precomputedCrudCreateSQL = '';
1859
+ let precomputedCrudUpdateSQL = '';
1860
+ let precomputedCrudDeleteSQL = '';
1861
+ let precomputedFtsSQL = '';
1526
1862
  // Tracks whether the base view SQL differs from what's in the database.
1527
1863
  // When true, we force-log the view, its permissions, and all SPs (which compile the view in)
1528
1864
  // so the migration log script can fully update target databases.
@@ -1577,16 +1913,25 @@ export class SQLCodeGenBase {
1577
1913
  const tvfFilePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('function', options.entity.SchemaName, fn.functionName, false, true));
1578
1914
  tvfEntries.push({ sql: fn.sql, filePath: tvfFilePath, fieldName: fn.fieldName, description: fn.description });
1579
1915
  // Add function SQL to output BEFORE the view
1580
- sRet += fn.sql + '\n' + this._dbProvider.BatchSeparator + '\n';
1916
+ const piece = fn.sql + '\n' + this._dbProvider.BatchSeparator + '\n';
1917
+ sRet += piece;
1918
+ precomputedTVFSQL += piece;
1581
1919
  }
1582
1920
  }
1583
1921
  }
1584
1922
  // Generate the base view (which may reference the TVFs created above)
1585
- 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;
1586
1928
  // Compare generated view SQL against what's currently in the database.
1587
1929
  // If the SELECT body differs, force-log just this base view via the forceLog flag
1588
1930
  // so logging stays centralized in logSQLForNewOrModifiedEntity.
1589
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);
1590
1935
  // Now log TVFs with baseViewChanged as forceLog, ensuring they're included
1591
1936
  // in TempBatchFile whenever the view that depends on them is also included
1592
1937
  if (options.writeFiles) {
@@ -1598,15 +1943,15 @@ export class SQLCodeGenBase {
1598
1943
  }
1599
1944
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('view', options.entity.SchemaName, options.entity.GeneratedViewName, false, true));
1600
1945
  if (options.writeFiles) {
1601
- this.writeFileIfChanged(filePath, s);
1602
- 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);
1603
1948
  if (viewLogged && options.entity.HasLayeredBaseView) {
1604
1949
  this.layeredEntitiesWithLoggedInnerView.add(options.entity.Name);
1605
1950
  this.logLayeredOuterViewRefresh(options.entity);
1606
1951
  }
1607
1952
  files.push(filePath);
1608
1953
  }
1609
- sRet += s + '\n' + this._dbProvider.BatchSeparator + '\n';
1954
+ sRet += sLogged + '\n' + this._dbProvider.BatchSeparator + '\n';
1610
1955
  }
1611
1956
  // always generate permissions for the base view
1612
1957
  const permHeader = this.GenerateSingleEntitySQLFileHeader(options.entity, 'Permissions for ' + options.entity.BaseView);
@@ -1647,7 +1992,8 @@ export class SQLCodeGenBase {
1647
1992
  // forceRegeneration only forces regeneration of SPs where spCreateGenerated=true
1648
1993
  if (!options.onlyPermissions && options.entity.spCreateGenerated) {
1649
1994
  // generate the create SP
1650
- 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;
1651
1997
  if (options.writeFiles) {
1652
1998
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, false, true));
1653
1999
  this.writeFileIfChanged(filePath, s);
@@ -1680,7 +2026,8 @@ export class SQLCodeGenBase {
1680
2026
  // forceRegeneration only forces regeneration of SPs where spUpdateGenerated=true
1681
2027
  if (!options.onlyPermissions && options.entity.spUpdateGenerated) {
1682
2028
  // generate the update SP
1683
- 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;
1684
2031
  if (options.writeFiles) {
1685
2032
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, false, true));
1686
2033
  this.writeFileIfChanged(filePath, s);
@@ -1719,7 +2066,8 @@ export class SQLCodeGenBase {
1719
2066
  if (this.entitiesNeedingDeleteSPRegeneration.has(options.entity.ID)) {
1720
2067
  logStatus(` Regenerating ${spName} due to cascade dependency changes`);
1721
2068
  }
1722
- 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;
1723
2071
  if (options.writeFiles) {
1724
2072
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('sp', options.entity.SchemaName, spName, false, true));
1725
2073
  this.writeFileIfChanged(filePath, s);
@@ -1748,6 +2096,9 @@ export class SQLCodeGenBase {
1748
2096
  // always generate the code so we can get the function name from the below function call
1749
2097
  const ft = await this.GenerateEntityFullTextSearchSQL(options.pool, options.entity);
1750
2098
  if (!options.onlyPermissions) {
2099
+ if (options.entity.FullTextSearchEnabled && !options.entity.VirtualEntity) {
2100
+ precomputedFtsSQL = ft.sql;
2101
+ }
1751
2102
  // only write the actual sql out if we're not only generating permissions
1752
2103
  const filePath = path.join(options.directory, this.SQLUtilityObject.getDBObjectFileName('full_text_search_function', options.entity.SchemaName, options.entity.BaseTable, false, true));
1753
2104
  if (options.writeFiles) {
@@ -1771,7 +2122,16 @@ export class SQLCodeGenBase {
1771
2122
  if (!options.entity.FullTextSearchFunctionGenerated)
1772
2123
  sRet += sP + '\n' + this._dbProvider.BatchSeparator + '\n';
1773
2124
  }
1774
- 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 };
1775
2135
  }
1776
2136
  catch (err) {
1777
2137
  logError(err);
@@ -1833,6 +2193,62 @@ export class SQLCodeGenBase {
1833
2193
  this.existingRoutineDefinitions = null;
1834
2194
  }
1835
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
+ }
1836
2252
  isRoutineMissing(schema, routineName) {
1837
2253
  if (!this.existingRoutines) {
1838
2254
  return false;
@@ -2321,6 +2737,11 @@ export class SQLCodeGenBase {
2321
2737
  }
2322
2738
  return joins.join('\n');
2323
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
+ */
2324
2745
  async GenerateBaseView(pool, entity) {
2325
2746
  const { viewSQL, viewPermSQL } = await this.GenerateBaseViewPieces(pool, entity);
2326
2747
  return viewSQL + viewPermSQL;
@@ -2403,6 +2824,28 @@ export class SQLCodeGenBase {
2403
2824
  viewPermSQL: permissions,
2404
2825
  };
2405
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
+ }
2406
2849
  /** @deprecated Use {@link GenerateBaseViewPieces}. */
2407
2850
  async generateBaseViewPieces(pool, entity) {
2408
2851
  return this.GenerateBaseViewPieces(pool, entity);
@@ -2707,7 +3150,9 @@ export class SQLCodeGenBase {
2707
3150
  // sidesteps the self-reference problem when the FK is a self-FK.
2708
3151
  const useView = ef._RelatedEntityNameFieldIsVirtual && !ef._RelatedEntityNameFieldIsComputed;
2709
3152
  const relatedTable = useView ? ef.RelatedEntityBaseView : ef.RelatedEntityBaseTable;
2710
- sOutput += `${ef.AllowsNull ? 'LEFT OUTER' : 'INNER'} JOIN\n ${qs(ef.RelatedEntitySchemaName, relatedTable)} AS ${ef._RelatedEntityTableAlias}\n ON\n ${qi(classNameFirstChar)}.${qi(ef.Name)} = ${ef._RelatedEntityTableAlias}.${qi(ef.RelatedEntityFieldName)}`;
3153
+ // Always LEFT OUTER (#4533): this join only fetches a display label, so a
3154
+ // missing or unmatched related row must yield a NULL label, never drop the row.
3155
+ sOutput += `LEFT OUTER JOIN\n ${qs(ef.RelatedEntitySchemaName, relatedTable)} AS ${ef._RelatedEntityTableAlias}\n ON\n ${qi(classNameFirstChar)}.${qi(ef.Name)} = ${ef._RelatedEntityTableAlias}.${qi(ef.RelatedEntityFieldName)}`;
2711
3156
  }
2712
3157
  }
2713
3158
  // Geo WRITE source: RecordGeoCode JOIN only when there are writable Geo* fields
@@ -2734,7 +3179,7 @@ export class SQLCodeGenBase {
2734
3179
  const parts = pkFields.map(pk => dialect.CastToBoundedString(`${qi(classNameFirstChar)}.${qi(pk.Name)}`, 200));
2735
3180
  recordIdExpr = parts.join(` ${concat} '||' ${concat} `);
2736
3181
  }
2737
- 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'`;
2738
3183
  }
2739
3184
  sOutput += this.generateEmbeddedGeoJoins(entity, classNameFirstChar);
2740
3185
  return sOutput;
@@ -2790,8 +3235,8 @@ export class SQLCodeGenBase {
2790
3235
  const alias = `__mj_emb_${spec.foreignKeyField}`;
2791
3236
  const schema = spec.relatedSchemaName || related.SchemaName;
2792
3237
  const table = spec.relatedBaseTable || related.BaseTable;
2793
- const joinKind = spec.allowsNull ? 'LEFT OUTER' : 'INNER';
2794
- joins.push(`${joinKind} JOIN\n ${qs(schema, table)} AS ${alias}\n ON\n ${qi(classNameFirstChar)}.${qi(spec.foreignKeyField)} = ${alias}.${qi(related.FirstPrimaryKey.Name)}`); // first-pk-ok: FK target — a single FK column joins to the related entity's single key
3238
+ // Display-only join: LEFT OUTER so an unmatched related row never drops the parent row (#4533).
3239
+ joins.push(`LEFT OUTER JOIN\n ${qs(schema, table)} AS ${alias}\n ON\n ${qi(classNameFirstChar)}.${qi(spec.foreignKeyField)} = ${alias}.${qi(related.FirstPrimaryKey.Name)}`); // first-pk-ok: FK target — a single FK column joins to the related entity's single key
2795
3240
  selects.push(` ${alias}.${qi(latF.Name)} AS ${qi(spec.lat)},\n ${alias}.${qi(lngF.Name)} AS ${qi(spec.lng)}`);
2796
3241
  }
2797
3242
  return { select: selects.join(',\n'), joins: joins.join('\n') };