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