rawsql-ts 0.11.0-beta → 0.11.2-beta

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 (110) hide show
  1. package/README.md +1 -3
  2. package/dist/esm/index.js +8 -1
  3. package/dist/esm/index.js.map +1 -1
  4. package/dist/esm/index.min.js +47 -13
  5. package/dist/esm/index.min.js.map +4 -4
  6. package/dist/esm/src/index.js +8 -1
  7. package/dist/esm/src/index.js.map +1 -1
  8. package/dist/esm/src/parsers/ValueParser.js +86 -4
  9. package/dist/esm/src/parsers/ValueParser.js.map +1 -1
  10. package/dist/esm/src/tokenReaders/OperatorTokenReader.js +4 -0
  11. package/dist/esm/src/tokenReaders/OperatorTokenReader.js.map +1 -1
  12. package/dist/esm/src/transformers/CTEDependencyTracer.js +249 -0
  13. package/dist/esm/src/transformers/CTEDependencyTracer.js.map +1 -0
  14. package/dist/esm/src/transformers/DynamicQueryBuilder.js.map +1 -1
  15. package/dist/esm/src/transformers/EnhancedJsonMapping.js +217 -0
  16. package/dist/esm/src/transformers/EnhancedJsonMapping.js.map +1 -0
  17. package/dist/esm/src/transformers/JsonMappingConverter.js +388 -0
  18. package/dist/esm/src/transformers/JsonMappingConverter.js.map +1 -0
  19. package/dist/esm/src/transformers/JsonMappingUnifier.js +207 -0
  20. package/dist/esm/src/transformers/JsonMappingUnifier.js.map +1 -0
  21. package/dist/esm/src/transformers/ModelDrivenJsonMapping.js +115 -0
  22. package/dist/esm/src/transformers/ModelDrivenJsonMapping.js.map +1 -0
  23. package/dist/esm/src/transformers/PostgresArrayEntityCteBuilder.js +293 -70
  24. package/dist/esm/src/transformers/PostgresArrayEntityCteBuilder.js.map +1 -1
  25. package/dist/esm/src/transformers/PostgresJsonQueryBuilder.js +26 -15
  26. package/dist/esm/src/transformers/PostgresJsonQueryBuilder.js.map +1 -1
  27. package/dist/esm/src/transformers/PostgresObjectEntityCteBuilder.js +75 -15
  28. package/dist/esm/src/transformers/PostgresObjectEntityCteBuilder.js.map +1 -1
  29. package/dist/esm/src/transformers/SelectableColumnCollector.js +17 -5
  30. package/dist/esm/src/transformers/SelectableColumnCollector.js.map +1 -1
  31. package/dist/esm/src/transformers/SqlParamInjector.js +189 -108
  32. package/dist/esm/src/transformers/SqlParamInjector.js.map +1 -1
  33. package/dist/esm/src/transformers/UnifiedJsonMapping.js +2 -4
  34. package/dist/esm/src/transformers/UnifiedJsonMapping.js.map +1 -1
  35. package/dist/esm/src/transformers/UpstreamSelectQueryFinder.js +51 -3
  36. package/dist/esm/src/transformers/UpstreamSelectQueryFinder.js.map +1 -1
  37. package/dist/esm/src/utils/OperatorPrecedence.js +3 -1
  38. package/dist/esm/src/utils/OperatorPrecedence.js.map +1 -1
  39. package/dist/esm/src/utils/SchemaManager.js +0 -1
  40. package/dist/esm/src/utils/SchemaManager.js.map +1 -1
  41. package/dist/esm/tsconfig.browser.tsbuildinfo +1 -1
  42. package/dist/esm/types/src/index.d.ts +8 -1
  43. package/dist/esm/types/src/parsers/ValueParser.d.ts +8 -0
  44. package/dist/esm/types/src/transformers/CTEDependencyTracer.d.ts +58 -0
  45. package/dist/esm/types/src/transformers/DynamicQueryBuilder.d.ts +6 -0
  46. package/dist/esm/types/src/transformers/EnhancedJsonMapping.d.ts +194 -0
  47. package/dist/esm/types/src/transformers/JsonMappingConverter.d.ts +200 -0
  48. package/dist/esm/types/src/transformers/JsonMappingUnifier.d.ts +100 -0
  49. package/dist/esm/types/src/transformers/ModelDrivenJsonMapping.d.ts +62 -0
  50. package/dist/esm/types/src/transformers/PostgresArrayEntityCteBuilder.d.ts +93 -52
  51. package/dist/esm/types/src/transformers/PostgresJsonQueryBuilder.d.ts +3 -3
  52. package/dist/esm/types/src/transformers/PostgresObjectEntityCteBuilder.d.ts +31 -6
  53. package/dist/esm/types/src/transformers/SelectableColumnCollector.d.ts +14 -3
  54. package/dist/esm/types/src/transformers/SqlParamInjector.d.ts +48 -0
  55. package/dist/esm/types/src/transformers/UnifiedJsonMapping.d.ts +0 -1
  56. package/dist/esm/types/src/transformers/UpstreamSelectQueryFinder.d.ts +13 -1
  57. package/dist/index.min.js +47 -13
  58. package/dist/index.min.js.map +4 -4
  59. package/dist/src/index.d.ts +8 -1
  60. package/dist/src/index.js +15 -1
  61. package/dist/src/index.js.map +1 -1
  62. package/dist/src/parsers/ValueParser.d.ts +8 -0
  63. package/dist/src/parsers/ValueParser.js +86 -4
  64. package/dist/src/parsers/ValueParser.js.map +1 -1
  65. package/dist/src/tokenReaders/OperatorTokenReader.js +4 -0
  66. package/dist/src/tokenReaders/OperatorTokenReader.js.map +1 -1
  67. package/dist/src/transformers/CTEDependencyTracer.d.ts +58 -0
  68. package/dist/src/transformers/CTEDependencyTracer.js +253 -0
  69. package/dist/src/transformers/CTEDependencyTracer.js.map +1 -0
  70. package/dist/src/transformers/DynamicQueryBuilder.d.ts +6 -0
  71. package/dist/src/transformers/DynamicQueryBuilder.js.map +1 -1
  72. package/dist/src/transformers/EnhancedJsonMapping.d.ts +194 -0
  73. package/dist/src/transformers/EnhancedJsonMapping.js +223 -0
  74. package/dist/src/transformers/EnhancedJsonMapping.js.map +1 -0
  75. package/dist/src/transformers/JsonMappingConverter.d.ts +200 -0
  76. package/dist/src/transformers/JsonMappingConverter.js +392 -0
  77. package/dist/src/transformers/JsonMappingConverter.js.map +1 -0
  78. package/dist/src/transformers/JsonMappingUnifier.d.ts +100 -0
  79. package/dist/src/transformers/JsonMappingUnifier.js +216 -0
  80. package/dist/src/transformers/JsonMappingUnifier.js.map +1 -0
  81. package/dist/src/transformers/ModelDrivenJsonMapping.d.ts +62 -0
  82. package/dist/src/transformers/ModelDrivenJsonMapping.js +122 -0
  83. package/dist/src/transformers/ModelDrivenJsonMapping.js.map +1 -0
  84. package/dist/src/transformers/PostgresArrayEntityCteBuilder.d.ts +93 -52
  85. package/dist/src/transformers/PostgresArrayEntityCteBuilder.js +293 -70
  86. package/dist/src/transformers/PostgresArrayEntityCteBuilder.js.map +1 -1
  87. package/dist/src/transformers/PostgresJsonQueryBuilder.d.ts +3 -3
  88. package/dist/src/transformers/PostgresJsonQueryBuilder.js +26 -15
  89. package/dist/src/transformers/PostgresJsonQueryBuilder.js.map +1 -1
  90. package/dist/src/transformers/PostgresObjectEntityCteBuilder.d.ts +31 -6
  91. package/dist/src/transformers/PostgresObjectEntityCteBuilder.js +75 -15
  92. package/dist/src/transformers/PostgresObjectEntityCteBuilder.js.map +1 -1
  93. package/dist/src/transformers/SelectableColumnCollector.d.ts +14 -3
  94. package/dist/src/transformers/SelectableColumnCollector.js +17 -5
  95. package/dist/src/transformers/SelectableColumnCollector.js.map +1 -1
  96. package/dist/src/transformers/SqlParamInjector.d.ts +48 -0
  97. package/dist/src/transformers/SqlParamInjector.js +189 -108
  98. package/dist/src/transformers/SqlParamInjector.js.map +1 -1
  99. package/dist/src/transformers/UnifiedJsonMapping.d.ts +0 -1
  100. package/dist/src/transformers/UnifiedJsonMapping.js +2 -4
  101. package/dist/src/transformers/UnifiedJsonMapping.js.map +1 -1
  102. package/dist/src/transformers/UpstreamSelectQueryFinder.d.ts +13 -1
  103. package/dist/src/transformers/UpstreamSelectQueryFinder.js +51 -3
  104. package/dist/src/transformers/UpstreamSelectQueryFinder.js.map +1 -1
  105. package/dist/src/utils/OperatorPrecedence.js +3 -1
  106. package/dist/src/utils/OperatorPrecedence.js.map +1 -1
  107. package/dist/src/utils/SchemaManager.js +0 -1
  108. package/dist/src/utils/SchemaManager.js.map +1 -1
  109. package/dist/tsconfig.tsbuildinfo +1 -1
  110. package/package.json +2 -2
@@ -3,42 +3,27 @@ import { SimpleSelectQuery } from '../models/SimpleSelectQuery';
3
3
  import { IdentifierString, ColumnReference, FunctionCall, ValueList, LiteralValue, RawString } from '../models/ValueComponent';
4
4
  import { SelectValueCollector } from './SelectValueCollector';
5
5
  /**
6
- * PostgreSQL-specific builder for creating CTEs for array entities (array relationships).
7
- * This class handles the creation of CTEs that build JSON/JSONB arrays for child entities,
8
- * processing them from the deepest level up to ensure proper dependency ordering.
6
+ * Builds CTEs for array entities using depth-first processing and row compression.
9
7
  *
10
- * Features:
11
- * - Depth-based CTE naming (cte_array_depth_N)
12
- * - Row compression using GROUP BY operations
13
- * - JSONB/JSON array aggregation
14
- * - Hierarchical processing of nested arrays
15
- * - Column exclusion to avoid duplication
16
- *
17
- * Why depth calculation is critical:
18
- * 1. Array entities can be nested at multiple levels. We must process the deepest
19
- * (most distant) arrays first to ensure their JSON representations are available
20
- * when building their parent arrays.
21
- * 2. Array entity processing is essentially a row compression operation using GROUP BY.
22
- * Unlike parent entities which use column compression, arrays require grouping
23
- * to aggregate multiple rows into JSON arrays.
24
- *
25
- * Example hierarchy:
26
- * Order (root, depth 0)
27
- * └─ Items (array, depth 1)
28
- * └─ Details (array, depth 2)
29
- *
30
- * Processing order: depth 2 → depth 1 → depth 0
8
+ * Core concepts:
9
+ * - Column Compression: OBJECT relationships (user_id, user_name → user_json)
10
+ * - Row Compression: ARRAY relationships (multiple rows → JSON array via GROUP BY)
11
+ * - Depth-First: Process deepest arrays first for dependency ordering
12
+ * - GROUP BY Exclusion: Exclude array-internal columns to prevent over-grouping
31
13
  */
32
14
  export class PostgresArrayEntityCteBuilder {
33
15
  /**
34
- * Build CTEs for all array entities in the correct dependency order
35
- * @param ctesSoFar Array of CTEs built so far (starts with the initial CTE)
36
- * @param aliasOfCteToBuildUpon Alias of the CTE from which the current array CTE will select
16
+ * Builds CTEs for all array entities using depth-first processing.
17
+ * Collects arrays by depth, processes deepest first, chains CTEs.
18
+ *
19
+ * @param ctesSoFar Array of CTEs built so far
20
+ * @param aliasOfCteToBuildUpon Alias of the CTE to build upon
37
21
  * @param allEntities Map of all entities in the mapping
38
22
  * @param mapping The JSON mapping configuration
39
- * @returns Object containing the updated list of all CTEs and the alias of the last CTE created
23
+ * @param columnMappings Optional mappings from object entity IDs to generated JSON column names
24
+ * @returns Object containing updated CTEs and last CTE alias
40
25
  */
41
- buildArrayEntityCtes(ctesSoFar, aliasOfCteToBuildUpon, allEntities, mapping) {
26
+ buildArrayEntityCtes(ctesSoFar, aliasOfCteToBuildUpon, allEntities, mapping, columnMappings) {
42
27
  let currentCtes = [...ctesSoFar];
43
28
  let currentCteAlias = aliasOfCteToBuildUpon;
44
29
  // Collect and sort array entities by depth
@@ -53,22 +38,19 @@ export class PostgresArrayEntityCteBuilder {
53
38
  for (const depth of depths) {
54
39
  const infos = entitiesByDepth.get(depth);
55
40
  // Build CTE for all entities at this depth
56
- const { cte, newCteAlias } = this.buildDepthCte(infos, currentCteAlias, currentCtes, depth, mapping);
41
+ const { cte, newCteAlias } = this.buildDepthCte(infos, currentCteAlias, currentCtes, depth, mapping, columnMappings);
57
42
  currentCtes.push(cte);
58
43
  currentCteAlias = newCteAlias;
59
44
  }
60
45
  return { updatedCtes: currentCtes, lastCteAlias: currentCteAlias };
61
46
  }
62
47
  /**
63
- * Collect all array entities and calculate their depth from root.
64
- *
65
- * Depth calculation ensures proper processing order where deeper nested
66
- * arrays are processed first, making their aggregated data available
67
- * for parent array processing.
48
+ * Collects array entities and calculates depth for dependency ordering.
49
+ * Depth = distance from root. Deeper arrays processed first.
68
50
  *
69
51
  * @param mapping The JSON mapping configuration
70
52
  * @param allEntities Map of all entities in the mapping
71
- * @returns Array of array entity information with calculated depths, sorted deepest first
53
+ * @returns Array of array entity information with depths, sorted deepest first
72
54
  */
73
55
  collectAndSortArrayEntities(mapping, allEntities) {
74
56
  const arrayEntityInfos = [];
@@ -110,12 +92,7 @@ export class PostgresArrayEntityCteBuilder {
110
92
  return arrayEntityInfos;
111
93
  }
112
94
  /**
113
- * Group array entities by their depth level.
114
- *
115
- * Grouping by depth allows us to:
116
- * - Process all entities at the same level in a single CTE
117
- * - Optimize query performance by reducing the number of CTEs
118
- * - Maintain clear dependency ordering
95
+ * Groups array entities by depth level for batch processing.
119
96
  *
120
97
  * @param arrayInfos Array of array entity information with depths
121
98
  * @returns Map of depth level to entities at that depth
@@ -132,44 +109,79 @@ export class PostgresArrayEntityCteBuilder {
132
109
  return entitiesByDepth;
133
110
  }
134
111
  /**
135
- * Build a CTE that processes all array entities at a specific depth level.
136
- *
137
- * This method creates a single CTE that aggregates multiple array entities
138
- * at the same depth, using GROUP BY to compress rows into JSON arrays.
112
+ * Builds CTE for specific depth level using row compression.
113
+ * Uses GROUP BY to aggregate multiple rows into JSON arrays.
114
+ * Excludes array-internal columns from GROUP BY to prevent over-grouping.
139
115
  *
140
116
  * @param infos Array entities at this depth level
141
117
  * @param currentCteAlias Alias of the CTE to build upon
142
118
  * @param currentCtes All CTEs built so far
143
119
  * @param depth Current depth level being processed
144
120
  * @param mapping JSON mapping configuration
121
+ * @param columnMappings Optional mappings from object entity IDs to generated JSON column names
145
122
  * @returns The new CTE and its alias
146
123
  */
147
- buildDepthCte(infos, currentCteAlias, currentCtes, depth, mapping) {
124
+ buildDepthCte(infos, currentCteAlias, currentCtes, depth, mapping, columnMappings) {
148
125
  var _a;
149
126
  // Collect columns that will be compressed into arrays
127
+ // This includes both direct columns and columns from nested entities within the array
150
128
  const arrayColumns = new Set();
151
129
  infos.forEach(info => {
130
+ // Add direct columns from the array entity
152
131
  Object.values(info.entity.columns).forEach(col => arrayColumns.add(col));
132
+ // Also add columns from all nested entities within this array entity
133
+ const collectNestedColumns = (parentEntityId) => {
134
+ mapping.nestedEntities
135
+ .filter(nestedEntity => nestedEntity.parentId === parentEntityId)
136
+ .forEach(nestedEntity => {
137
+ Object.values(nestedEntity.columns).forEach(column => {
138
+ const columnName = typeof column === 'string' ? column : column.column;
139
+ arrayColumns.add(columnName);
140
+ });
141
+ // Recursively collect from deeper nested entities
142
+ collectNestedColumns(nestedEntity.id);
143
+ });
144
+ };
145
+ collectNestedColumns(info.entity.id);
153
146
  });
154
147
  // Get columns from previous CTE
155
148
  const prevCte = (_a = currentCtes.find(c => c.aliasExpression.table.name === currentCteAlias)) === null || _a === void 0 ? void 0 : _a.query;
156
149
  if (!prevCte) {
157
150
  throw new Error(`CTE not found: ${currentCteAlias}`);
158
151
  }
159
- const prevSelects = new SelectValueCollector(null, currentCtes).collect(prevCte);
160
- // Build SELECT items: columns that are NOT being compressed (for GROUP BY)
152
+ const prevSelects = new SelectValueCollector(null, currentCtes).collect(prevCte); // Build SELECT items: columns that are NOT being compressed (for GROUP BY)
161
153
  const groupByItems = [];
162
154
  const selectItems = [];
163
- prevSelects.forEach(sv => {
164
- if (!arrayColumns.has(sv.name)) {
165
- selectItems.push(new SelectItem(new ColumnReference(null, new IdentifierString(sv.name)), sv.name));
166
- groupByItems.push(new ColumnReference(null, new IdentifierString(sv.name)));
167
- }
155
+ // Get columns from the current level's array entities that will be aggregated
156
+ // These should be included in GROUP BY since they're being processed at this level
157
+ const currentLevelArrayColumns = new Set();
158
+ infos.forEach(info => {
159
+ Object.values(info.entity.columns).forEach(col => currentLevelArrayColumns.add(col));
168
160
  });
161
+ // Collect array entity columns organized by depth for GROUP BY exclusion strategy
162
+ const arrayEntityColumns = this.collectArrayEntityColumnsByDepth(mapping, depth);
163
+ // Identify JSON columns from objects within the arrays being processed at this depth
164
+ const arrayInternalObjectColumns = new Set();
165
+ if (columnMappings) {
166
+ infos.forEach(info => {
167
+ // Find all object-type nested entities within this array entity
168
+ mapping.nestedEntities
169
+ .filter(ne => ne.parentId === info.entity.id && ne.relationshipType === "object")
170
+ .forEach(objectEntity => {
171
+ // Find the corresponding JSON column mapping for this object entity
172
+ const columnMapping = columnMappings.find(cm => cm.entityId === objectEntity.id);
173
+ if (columnMapping) {
174
+ arrayInternalObjectColumns.add(columnMapping.generatedColumnName);
175
+ }
176
+ });
177
+ });
178
+ }
179
+ // Process existing SELECT variables to determine which should be included in GROUP BY
180
+ this.processSelectVariablesForGroupBy(prevSelects, arrayColumns, arrayEntityColumns, depth, selectItems, groupByItems, arrayInternalObjectColumns);
169
181
  // Add JSON aggregation columns for each array entity at this depth
170
182
  for (const info of infos) {
171
183
  const agg = this.buildAggregationDetailsForArrayEntity(info.entity, mapping.nestedEntities, new Map(), // allEntities - not needed for array aggregation
172
- mapping.useJsonb);
184
+ columnMappings);
173
185
  selectItems.push(new SelectItem(agg.jsonAgg, info.entity.propertyName));
174
186
  }
175
187
  // Create the new CTE
@@ -183,21 +195,19 @@ export class PostgresArrayEntityCteBuilder {
183
195
  return { cte, newCteAlias: cteAlias };
184
196
  }
185
197
  /**
186
- * Build JSON aggregation function for an array entity.
187
- *
188
- * This method creates a jsonb_agg or json_agg function call that aggregates
189
- * the entity's columns into a JSON array. It also handles nested relationships
190
- * by including child entity properties in the JSON object.
198
+ * Creates jsonb_agg function for array entity.
199
+ * Handles entity columns and nested child relationships.
200
+ * Uses originalPropertyName to avoid sequential numbering.
191
201
  *
192
202
  * @param entity The array entity being processed
193
203
  * @param nestedEntities All nested entities from the mapping
194
204
  * @param allEntities Map of all entities (not used in current implementation)
195
- * @param useJsonb Whether to use JSONB functions
205
+ * @param columnMappings Mappings from object entity IDs to generated JSON column names
196
206
  * @returns Object containing the JSON aggregation function
197
207
  */
198
- buildAggregationDetailsForArrayEntity(entity, nestedEntities, allEntities, useJsonb = false) {
199
- // Build JSON object for array elements
200
- const jsonBuildFunction = useJsonb ? "jsonb_build_object" : "json_build_object";
208
+ buildAggregationDetailsForArrayEntity(entity, nestedEntities, allEntities, columnMappings) {
209
+ // Build JSON object for array elements using JSONB functions
210
+ const jsonBuildFunction = PostgresArrayEntityCteBuilder.JSON_FUNCTIONS.BUILD_OBJECT;
201
211
  const args = [];
202
212
  // Add the entity's own columns
203
213
  Object.entries(entity.columns).forEach(([jsonKey, sqlColumn]) => {
@@ -207,11 +217,54 @@ export class PostgresArrayEntityCteBuilder {
207
217
  // Find and process child entities (both object and array types)
208
218
  const childEntities = nestedEntities.filter((ne) => ne.parentId === entity.id);
209
219
  childEntities.forEach((childEntity) => {
210
- args.push(new LiteralValue(childEntity.propertyName));
220
+ // Use originalPropertyName if available to avoid sequential numbering in final JSON
221
+ const propertyNameForJson = childEntity.originalPropertyName || childEntity.propertyName;
222
+ args.push(new LiteralValue(propertyNameForJson));
211
223
  if (childEntity.relationshipType === "object") {
212
- // For object relationships, use pre-computed JSON column
213
- const jsonColumnName = `${childEntity.name.toLowerCase()}_json`;
214
- args.push(new ColumnReference(null, new IdentifierString(jsonColumnName)));
224
+ // For object relationships, use pre-computed JSON column from column mappings
225
+ if (!columnMappings) {
226
+ throw new Error(`❌ PostgresArrayEntityCteBuilder Error: Column mappings not provided\n` +
227
+ `\n` +
228
+ `🔍 Details:\n` +
229
+ ` - Entity ID: ${childEntity.id}\n` +
230
+ ` - Entity Name: ${childEntity.name || 'unknown'}\n` +
231
+ ` - Property Name: ${childEntity.propertyName}\n` +
232
+ ` - Relationship Type: ${childEntity.relationshipType}\n` +
233
+ `\n` +
234
+ `💡 Solution:\n` +
235
+ ` Column mappings are required for hybrid JSON column naming.\n` +
236
+ ` This error indicates that PostgresObjectEntityCteBuilder did not\n` +
237
+ ` pass column mappings to PostgresArrayEntityCteBuilder.\n` +
238
+ `\n` +
239
+ `🔧 Check:\n` +
240
+ ` 1. Ensure PostgresJsonQueryBuilder.buildJsonWithCteStrategy() passes columnMappings\n` +
241
+ ` 2. Verify PostgresObjectEntityCteBuilder.buildObjectEntityCtes() returns columnMappings\n` +
242
+ ` 3. Check that Model-driven mapping conversion generates unique entity IDs`);
243
+ }
244
+ const mapping = columnMappings.find(m => m.entityId === childEntity.id);
245
+ if (!mapping) {
246
+ const availableMappings = columnMappings.map(m => `${m.entityId} → ${m.generatedColumnName}`).join(', ');
247
+ throw new Error(`❌ PostgresArrayEntityCteBuilder Error: Column mapping not found\n` +
248
+ `\n` +
249
+ `🔍 Details:\n` +
250
+ ` - Looking for Entity ID: ${childEntity.id}\n` +
251
+ ` - Entity Name: ${childEntity.name || 'unknown'}\n` +
252
+ ` - Property Name: ${childEntity.propertyName}\n` +
253
+ ` - Relationship Type: ${childEntity.relationshipType}\n` +
254
+ `\n` +
255
+ `📋 Available Mappings:\n` +
256
+ ` ${availableMappings || 'None'}\n` +
257
+ `\n` +
258
+ `💡 Solution:\n` +
259
+ ` Entity IDs must match between mapping generation and usage.\n` +
260
+ ` This suggests a mismatch in entity ID generation or processing.\n` +
261
+ `\n` +
262
+ `🔧 Check:\n` +
263
+ ` 1. Model-driven mapping conversion generates consistent entity IDs\n` +
264
+ ` 2. PostgresObjectEntityCteBuilder processes all entities correctly\n` +
265
+ ` 3. Entity hierarchy and parentId relationships are correct`);
266
+ }
267
+ args.push(new ColumnReference(null, new IdentifierString(mapping.generatedColumnName)));
215
268
  }
216
269
  else if (childEntity.relationshipType === "array") {
217
270
  // For array relationships, use the column directly
@@ -220,12 +273,182 @@ export class PostgresArrayEntityCteBuilder {
220
273
  });
221
274
  // Create JSON object
222
275
  const jsonObject = new FunctionCall(null, new RawString(jsonBuildFunction), new ValueList(args), null);
223
- // Create JSON aggregation
224
- const jsonAggFunction = useJsonb ? "jsonb_agg" : "json_agg";
276
+ // Create JSON aggregation using JSONB with NULL filtering
277
+ // Use FILTER clause to exclude rows where primary key is NULL (no actual data)
278
+ const jsonAggFunction = PostgresArrayEntityCteBuilder.JSON_FUNCTIONS.AGGREGATE;
279
+ // Find the primary column (typically the first column) to use for NULL filtering
280
+ const primaryColumn = Object.values(entity.columns)[0];
281
+ // For now, create standard jsonb_agg and handle NULL filtering in post-processing
282
+ // TODO: Implement proper FILTER clause support in SQL AST
225
283
  const jsonAgg = new FunctionCall(null, new RawString(jsonAggFunction), new ValueList([jsonObject]), null);
226
284
  return { jsonAgg };
227
285
  }
286
+ /**
287
+ * Collects array entity columns by depth for GROUP BY exclusion strategy.
288
+ *
289
+ * @param mapping The JSON mapping configuration containing all entities
290
+ * @param currentDepth The current aggregation depth being processed
291
+ * @returns A map where keys are depth levels and values are sets of column names
292
+ */
293
+ collectArrayEntityColumnsByDepth(mapping, currentDepth) {
294
+ const arrayEntitiesByDepth = new Map(); // Initialize depth maps for current and deeper levels
295
+ // Use a reasonable maximum depth limit to avoid infinite loops
296
+ const maxDepth = Math.max(currentDepth + 3, 5);
297
+ for (let d = currentDepth; d <= maxDepth; d++) {
298
+ arrayEntitiesByDepth.set(d, new Set());
299
+ }
300
+ // Process all array entities to collect their columns by depth
301
+ mapping.nestedEntities
302
+ .filter(entity => entity.relationshipType === 'array')
303
+ .forEach(entity => {
304
+ // Calculate entity depth in the hierarchy
305
+ const entityDepth = this.calculateEntityDepth(entity, mapping);
306
+ if (!arrayEntitiesByDepth.has(entityDepth)) {
307
+ arrayEntitiesByDepth.set(entityDepth, new Set());
308
+ }
309
+ // Add direct columns from the array entity
310
+ this.addEntityColumnsToDepthSet(entity, entityDepth, arrayEntitiesByDepth);
311
+ // Collect columns from all descendant entities recursively
312
+ this.collectDescendantColumns(entity.id, entityDepth, mapping, arrayEntitiesByDepth);
313
+ });
314
+ return arrayEntitiesByDepth;
315
+ }
316
+ /**
317
+ * Calculates entity depth by traversing up to root.
318
+ *
319
+ * @param entity The entity to calculate depth for
320
+ * @param mapping The JSON mapping containing all entities
321
+ * @returns The depth level (0 for root level, 1 for first level, etc.)
322
+ */
323
+ calculateEntityDepth(entity, mapping) {
324
+ let entityDepth = 0;
325
+ let currentEntity = entity;
326
+ while (currentEntity.parentId && currentEntity.parentId !== mapping.rootEntity.id) {
327
+ entityDepth++;
328
+ currentEntity = mapping.nestedEntities.find(e => e.id === currentEntity.parentId) || currentEntity;
329
+ }
330
+ return entityDepth;
331
+ }
332
+ /**
333
+ * Adds entity columns to depth set.
334
+ *
335
+ * @param entity The entity whose columns should be added
336
+ * @param depth The depth level to add columns to
337
+ * @param arrayEntitiesByDepth The map to update
338
+ */
339
+ addEntityColumnsToDepthSet(entity, depth, arrayEntitiesByDepth) {
340
+ Object.values(entity.columns).forEach(column => {
341
+ const columnName = typeof column === 'string' ? column : column.column;
342
+ arrayEntitiesByDepth.get(depth).add(columnName);
343
+ });
344
+ }
345
+ /**
346
+ * Recursively collects columns from descendant entities.
347
+ *
348
+ * @param parentEntityId The ID of the parent entity
349
+ * @param targetDepth The depth level to assign collected columns to
350
+ * @param mapping The JSON mapping containing all entities
351
+ * @param arrayEntitiesByDepth The map to update with collected columns
352
+ */
353
+ collectDescendantColumns(parentEntityId, targetDepth, mapping, arrayEntitiesByDepth) {
354
+ mapping.nestedEntities
355
+ .filter(nestedEntity => nestedEntity.parentId === parentEntityId)
356
+ .forEach(nestedEntity => {
357
+ // Add all columns from this descendant to the target depth
358
+ this.addEntityColumnsToDepthSet(nestedEntity, targetDepth, arrayEntitiesByDepth);
359
+ // Recursively collect from deeper nested entities
360
+ this.collectDescendantColumns(nestedEntity.id, targetDepth, mapping, arrayEntitiesByDepth);
361
+ });
362
+ }
363
+ /**
364
+ * Implements GROUP BY exclusion strategy for array aggregation.
365
+ * Excludes current array columns and array-internal object JSON columns.
366
+ *
367
+ * @param prevSelects SELECT variables from the previous CTE
368
+ * @param arrayColumns Columns that are being aggregated (should be excluded from GROUP BY)
369
+ * @param arrayEntitiesByDepth Map of depth levels to their column sets
370
+ * @param currentDepth The current aggregation depth being processed
371
+ * @param selectItems Output array for SELECT items
372
+ * @param groupByItems Output array for GROUP BY items
373
+ * @param arrayInternalObjectColumns JSON columns from objects within arrays being processed
374
+ */
375
+ processSelectVariablesForGroupBy(prevSelects, arrayColumns, arrayEntitiesByDepth, currentDepth, selectItems, groupByItems, arrayInternalObjectColumns) {
376
+ prevSelects.forEach(sv => {
377
+ if (!arrayColumns.has(sv.name)) {
378
+ // Exclude JSON columns from objects within arrays being processed
379
+ if (arrayInternalObjectColumns && arrayInternalObjectColumns.has(sv.name)) {
380
+ // Skip this column - it's an object within the array being aggregated
381
+ return;
382
+ }
383
+ const shouldInclude = this.shouldIncludeColumnInGroupBy(sv.name, arrayEntitiesByDepth, currentDepth);
384
+ if (shouldInclude) {
385
+ selectItems.push(new SelectItem(new ColumnReference(null, new IdentifierString(sv.name)), sv.name));
386
+ // Exclude JSON columns from GROUP BY as PostgreSQL doesn't support equality operators for JSON type
387
+ if (!sv.name.endsWith('_json')) {
388
+ groupByItems.push(new ColumnReference(null, new IdentifierString(sv.name)));
389
+ }
390
+ }
391
+ }
392
+ });
393
+ }
394
+ /**
395
+ * Determines if column should be included in GROUP BY clause.
396
+ * Applies depth-based filtering and special handling for JSON columns.
397
+ *
398
+ * @param columnName The name of the column to evaluate
399
+ * @param arrayEntitiesByDepth Map of depth levels to their column sets
400
+ * @param currentDepth The current aggregation depth
401
+ * @returns True if the column should be included in GROUP BY, false otherwise
402
+ */
403
+ shouldIncludeColumnInGroupBy(columnName, arrayEntitiesByDepth, currentDepth) {
404
+ const isJsonColumn = columnName.endsWith('_json');
405
+ let shouldInclude = true;
406
+ // Check if this column belongs to array entities at current depth or deeper
407
+ // These columns are being aggregated and should not be in GROUP BY
408
+ for (const [entityDepth, columns] of arrayEntitiesByDepth.entries()) {
409
+ if (entityDepth >= currentDepth && columns.has(columnName)) {
410
+ shouldInclude = false;
411
+ break;
412
+ }
413
+ }
414
+ // Critical: JSON columns from objects within arrays being processed
415
+ // must be excluded from GROUP BY as they are aggregated within the array
416
+ if (isJsonColumn) {
417
+ // Legacy handling for entity_ prefixed JSON columns
418
+ if (columnName.startsWith('entity_')) {
419
+ shouldInclude = this.shouldIncludeJsonColumn(columnName, currentDepth);
420
+ }
421
+ }
422
+ return shouldInclude;
423
+ }
424
+ /**
425
+ * Applies heuristics for entity JSON column inclusion in GROUP BY.
426
+ * Uses entity numbering patterns to identify deeply nested entities.
427
+ *
428
+ * @param columnName The JSON column name (expected format: entity_N_json)
429
+ * @param currentDepth The current aggregation depth
430
+ * @returns True if the JSON column should be included, false otherwise
431
+ */
432
+ shouldIncludeJsonColumn(columnName, currentDepth) {
433
+ const entityMatch = columnName.match(/entity_(\d+)_json/);
434
+ if (!entityMatch) {
435
+ return true;
436
+ }
437
+ // For depth > 0, exclude JSON columns from highly nested entities
438
+ // This heuristic assumes entities with higher numbers are more deeply nested
439
+ if (currentDepth > 0) {
440
+ const entityNumber = parseInt(entityMatch[1]);
441
+ // Entities with numbers > 2 are typically nested within arrays and should be excluded
442
+ return entityNumber <= 2;
443
+ }
444
+ return true;
445
+ }
228
446
  }
229
447
  // Constants for consistent naming conventions
230
448
  PostgresArrayEntityCteBuilder.CTE_ARRAY_PREFIX = 'cte_array_depth_';
449
+ // JSON function names for PostgreSQL aggregation
450
+ PostgresArrayEntityCteBuilder.JSON_FUNCTIONS = {
451
+ BUILD_OBJECT: 'jsonb_build_object',
452
+ AGGREGATE: 'jsonb_agg'
453
+ };
231
454
  //# sourceMappingURL=PostgresArrayEntityCteBuilder.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"PostgresArrayEntityCteBuilder.js","sourceRoot":"","sources":["../../../../src/transformers/PostgresArrayEntityCteBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,qBAAqB,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,EAAE,gBAAgB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAC1J,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAE,gBAAgB,EAAkB,eAAe,EAAE,YAAY,EAAE,SAAS,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAG/I,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAY9D;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,OAAO,6BAA6B;IAItC;;;;;;;OAOG;IACI,oBAAoB,CACvB,SAAwB,EACxB,qBAA6B,EAC7B,WAA2C,EAC3C,OAAoB;QAEpB,IAAI,WAAW,GAAG,CAAC,GAAG,SAAS,CAAC,CAAC;QACjC,IAAI,eAAe,GAAG,qBAAqB,CAAC;QAE5C,2CAA2C;QAC3C,MAAM,gBAAgB,GAAG,IAAI,CAAC,2BAA2B,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;QAEhF,IAAI,gBAAgB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAChC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,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CAAC,EAAE,CAAC;gBACnC,aAAa,GAAG,IAAI,CAAC,uBAAuB,CAAC,UAAU,EAAE,YAAY,CAAC,CAAC;YAC3E,CAAC;QACL,CAAC;QAED,OAAO,aAAa,CAAC;IACzB,CAAC;IAED;;;;;;;OAOG;IACK,uBAAuB,CAAC,UAAkB,EAAE,YAAoB;QACpE,MAAM,WAAW,GAAG,UAAU,CAAC,KAAK,CAAC,mBAAmB,CAAC,CAAC;QAC1D,IAAI,CAAC,WAAW,EAAE,CAAC;YACf,OAAO,IAAI,CAAC;QAChB,CAAC;QAED,kEAAkE;QAClE,6EAA6E;QAC7E,IAAI,YAAY,GAAG,CAAC,EAAE,CAAC;YACnB,MAAM,YAAY,GAAG,QAAQ,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;YAC9C,sFAAsF;YACtF,OAAO,YAAY,IAAI,CAAC,CAAC;QAC7B,CAAC;QAED,OAAO,IAAI,CAAC;IAChB,CAAC;;AAxkBD,8CAA8C;AACtB,8CAAgB,GAAG,kBAAkB,CAAC;AAE9D,iDAAiD;AACzB,4CAAc,GAAG;IACrC,YAAY,EAAE,oBAAoB;IAClC,SAAS,EAAE,WAAW;CAChB,CAAC"}
@@ -77,7 +77,13 @@ export class PostgresJsonQueryBuilder {
77
77
  }
78
78
  }
79
79
  }
80
- buildJsonQuery(originalQuery, mapping) {
80
+ buildJsonQuery(originalQuery, mapping, options) {
81
+ // Check jsonb option - must be true (or undefined/default) for GROUP BY compatibility
82
+ if ((options === null || options === void 0 ? void 0 : options.jsonb) === false) {
83
+ throw new Error('JSONB must be enabled for PostgreSQL GROUP BY compatibility. ' +
84
+ 'JSON type cannot be used in GROUP BY clauses. ' +
85
+ 'Please set jsonb: true or omit the jsonb option (defaults to true).');
86
+ }
81
87
  // Convert any SelectQuery to SimpleSelectQuery using QueryBuilder
82
88
  const simpleQuery = originalQuery instanceof SimpleSelectQuery
83
89
  ? originalQuery
@@ -116,12 +122,14 @@ export class PostgresJsonQueryBuilder {
116
122
  // The object entity builder returns all CTEs including the initial one
117
123
  ctesForProcessing = objectEntityResult.ctes;
118
124
  currentAliasToBuildUpon = objectEntityResult.lastCteAlias;
125
+ // Store column mappings for later use
126
+ const columnMappings = objectEntityResult.columnMappings;
119
127
  // Step 3: Build CTEs for array entities using dedicated builder
120
- const arrayCteBuildResult = this.arrayEntityCteBuilder.buildArrayEntityCtes(ctesForProcessing, currentAliasToBuildUpon, allEntities, mapping);
128
+ const arrayCteBuildResult = this.arrayEntityCteBuilder.buildArrayEntityCtes(ctesForProcessing, currentAliasToBuildUpon, allEntities, mapping, columnMappings);
121
129
  ctesForProcessing = arrayCteBuildResult.updatedCtes;
122
130
  currentAliasToBuildUpon = arrayCteBuildResult.lastCteAlias;
123
131
  // Step 4: Build the final SELECT query using all generated CTEs
124
- return this.buildFinalSelectQuery(ctesForProcessing, currentAliasToBuildUpon, allEntities, mapping);
132
+ return this.buildFinalSelectQuery(ctesForProcessing, currentAliasToBuildUpon, allEntities, mapping, columnMappings);
125
133
  }
126
134
  /**
127
135
  * Creates the initial Common Table Expression (CTE) from the original query.
@@ -142,7 +150,7 @@ export class PostgresJsonQueryBuilder {
142
150
  * @param mapping JSON mapping configuration.
143
151
  * @returns The final SimpleSelectQuery.
144
152
  */
145
- buildFinalSelectQuery(finalCtesList, lastCteAliasForFromClause, allEntities, mapping) {
153
+ buildFinalSelectQuery(finalCtesList, lastCteAliasForFromClause, allEntities, mapping, columnMappings) {
146
154
  const currentCtes = [...finalCtesList];
147
155
  // Define rootObjectCteAlias outside of if block
148
156
  const rootObjectCteAlias = `cte_root_${mapping.rootName.toLowerCase().replace(/[^a-z0-9_]/g, '_')}`;
@@ -151,10 +159,9 @@ export class PostgresJsonQueryBuilder {
151
159
  throw new Error(`Root entity ${mapping.rootEntity.id} not found`);
152
160
  }
153
161
  if (mapping.resultFormat === "array" || !mapping.resultFormat) {
154
- // Step 4.1a: Create a CTE that wraps the final result as the root object
155
- // No alias needed for single table SELECT
162
+ // Step 4.1a: Create a CTE that wraps the final result as the root object // No alias needed for single table SELECT
156
163
  const rootObjectBuilderExpression = this.buildEntityJsonObject(rootEntity, null, // No source alias for single table
157
- mapping.nestedEntities, allEntities, mapping.useJsonb);
164
+ mapping.nestedEntities, allEntities, columnMappings);
158
165
  const rootObjectSelectItem = new SelectItem(rootObjectBuilderExpression, mapping.rootName);
159
166
  const rootObjectCte = new CommonTable(new SimpleSelectQuery({
160
167
  selectClause: new SelectClause([rootObjectSelectItem]),
@@ -163,7 +170,7 @@ export class PostgresJsonQueryBuilder {
163
170
  }), new SourceAliasExpression(rootObjectCteAlias, null), null);
164
171
  currentCtes.push(rootObjectCte);
165
172
  // Step 4.1b: Aggregate all the root objects
166
- const aggregationFunc = mapping.useJsonb ? "jsonb_agg" : "json_agg";
173
+ const aggregationFunc = "jsonb_agg"; // Always use JSONB
167
174
  const aggregateExpression = new FunctionCall(null, new RawString(aggregationFunc), new ValueList([new ColumnReference(null, new IdentifierString(mapping.rootName))]), null);
168
175
  return new SimpleSelectQuery({
169
176
  withClause: new WithClause(false, currentCtes),
@@ -176,7 +183,7 @@ export class PostgresJsonQueryBuilder {
176
183
  else {
177
184
  // For a single object result, create root object CTE without alias
178
185
  const rootObjectBuilderExpression = this.buildEntityJsonObject(rootEntity, null, // No source alias for single table
179
- mapping.nestedEntities, allEntities, mapping.useJsonb);
186
+ mapping.nestedEntities, allEntities, columnMappings);
180
187
  const rootObjectSelectItem = new SelectItem(rootObjectBuilderExpression, mapping.rootName);
181
188
  const rootObjectCte = new CommonTable(new SimpleSelectQuery({
182
189
  selectClause: new SelectClause([rootObjectSelectItem]),
@@ -198,9 +205,10 @@ export class PostgresJsonQueryBuilder {
198
205
  /**
199
206
  * Build JSON object for entity, using parent JSON columns when available
200
207
  */
201
- buildEntityJsonObject(entity, sourceAlias, nestedEntities, allEntities, useJsonb = false) {
202
- const jsonBuildFunction = useJsonb ? "jsonb_build_object" : "json_build_object";
203
- const args = []; // Add the entity's own columns
208
+ buildEntityJsonObject(entity, sourceAlias, nestedEntities, allEntities, columnMappings) {
209
+ const jsonBuildFunction = "jsonb_build_object";
210
+ const args = [];
211
+ // Add the entity's own columns
204
212
  Object.entries(entity.columns).forEach(([jsonKey, columnDef]) => {
205
213
  // Handle both string and object formats
206
214
  const sqlColumn = typeof columnDef === 'string' ? columnDef : columnDef.column;
@@ -215,9 +223,12 @@ export class PostgresJsonQueryBuilder {
215
223
  return;
216
224
  args.push(new LiteralValue(childEntity.propertyName));
217
225
  if (childEntity.relationshipType === "object") {
218
- // For object relationships, use pre-computed JSON column
219
- const jsonColumnName = `${child.name.toLowerCase()}_json`;
220
- args.push(new ColumnReference(null, new IdentifierString(jsonColumnName)));
226
+ // For object relationships, use pre-computed JSON column from column mappings
227
+ const mapping = columnMappings.find(m => m.entityId === child.id);
228
+ if (!mapping) {
229
+ throw new Error(`Column mapping not found for entity: ${child.id}`);
230
+ }
231
+ args.push(new ColumnReference(null, new IdentifierString(mapping.generatedColumnName)));
221
232
  }
222
233
  else if (childEntity.relationshipType === "array") {
223
234
  // For array relationships, use the column directly