rawsql-ts 0.20.0 → 0.21.0

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 (83) hide show
  1. package/README.md +12 -13
  2. package/dist/esm/index.d.ts +1 -11
  3. package/dist/esm/index.js +1 -11
  4. package/dist/esm/index.js.map +1 -1
  5. package/dist/esm/index.min.js +3 -39
  6. package/dist/esm/index.min.js.map +3 -3
  7. package/dist/esm/transformers/DynamicQueryBuilder.d.ts +4 -27
  8. package/dist/esm/transformers/DynamicQueryBuilder.js +10 -27
  9. package/dist/esm/transformers/DynamicQueryBuilder.js.map +1 -1
  10. package/dist/esm/transformers/SSSQLFilterBuilder.js +2 -1
  11. package/dist/esm/transformers/SSSQLFilterBuilder.js.map +1 -1
  12. package/dist/esm/utils/SchemaManager.d.ts +3 -19
  13. package/dist/esm/utils/SchemaManager.js +2 -62
  14. package/dist/esm/utils/SchemaManager.js.map +1 -1
  15. package/dist/index.js +2 -18
  16. package/dist/index.js.map +1 -1
  17. package/dist/index.min.js +3 -39
  18. package/dist/index.min.js.map +3 -3
  19. package/dist/src/index.d.ts +1 -11
  20. package/dist/src/transformers/DynamicQueryBuilder.d.ts +4 -27
  21. package/dist/src/utils/SchemaManager.d.ts +3 -19
  22. package/dist/transformers/DynamicQueryBuilder.js +10 -27
  23. package/dist/transformers/DynamicQueryBuilder.js.map +1 -1
  24. package/dist/transformers/SSSQLFilterBuilder.js +2 -1
  25. package/dist/transformers/SSSQLFilterBuilder.js.map +1 -1
  26. package/dist/tsconfig.browser.tsbuildinfo +1 -1
  27. package/dist/utils/SchemaManager.js +2 -63
  28. package/dist/utils/SchemaManager.js.map +1 -1
  29. package/package.json +10 -2
  30. package/dist/esm/transformers/EnhancedJsonMapping.d.ts +0 -194
  31. package/dist/esm/transformers/EnhancedJsonMapping.js +0 -217
  32. package/dist/esm/transformers/EnhancedJsonMapping.js.map +0 -1
  33. package/dist/esm/transformers/JsonMappingConverter.d.ts +0 -200
  34. package/dist/esm/transformers/JsonMappingConverter.js +0 -388
  35. package/dist/esm/transformers/JsonMappingConverter.js.map +0 -1
  36. package/dist/esm/transformers/JsonMappingUnifier.d.ts +0 -100
  37. package/dist/esm/transformers/JsonMappingUnifier.js +0 -207
  38. package/dist/esm/transformers/JsonMappingUnifier.js.map +0 -1
  39. package/dist/esm/transformers/ModelDrivenJsonMapping.d.ts +0 -62
  40. package/dist/esm/transformers/ModelDrivenJsonMapping.js +0 -115
  41. package/dist/esm/transformers/ModelDrivenJsonMapping.js.map +0 -1
  42. package/dist/esm/transformers/PostgresArrayEntityCteBuilder.d.ts +0 -138
  43. package/dist/esm/transformers/PostgresArrayEntityCteBuilder.js +0 -454
  44. package/dist/esm/transformers/PostgresArrayEntityCteBuilder.js.map +0 -1
  45. package/dist/esm/transformers/PostgresJsonQueryBuilder.d.ts +0 -88
  46. package/dist/esm/transformers/PostgresJsonQueryBuilder.js +0 -241
  47. package/dist/esm/transformers/PostgresJsonQueryBuilder.js.map +0 -1
  48. package/dist/esm/transformers/PostgresObjectEntityCteBuilder.d.ts +0 -165
  49. package/dist/esm/transformers/PostgresObjectEntityCteBuilder.js +0 -343
  50. package/dist/esm/transformers/PostgresObjectEntityCteBuilder.js.map +0 -1
  51. package/dist/esm/transformers/TypeTransformationPostProcessor.d.ts +0 -108
  52. package/dist/esm/transformers/TypeTransformationPostProcessor.js +0 -354
  53. package/dist/esm/transformers/TypeTransformationPostProcessor.js.map +0 -1
  54. package/dist/esm/utils/JsonSchemaValidator.d.ts +0 -81
  55. package/dist/esm/utils/JsonSchemaValidator.js +0 -211
  56. package/dist/esm/utils/JsonSchemaValidator.js.map +0 -1
  57. package/dist/src/transformers/EnhancedJsonMapping.d.ts +0 -194
  58. package/dist/src/transformers/JsonMappingConverter.d.ts +0 -200
  59. package/dist/src/transformers/JsonMappingUnifier.d.ts +0 -100
  60. package/dist/src/transformers/ModelDrivenJsonMapping.d.ts +0 -62
  61. package/dist/src/transformers/PostgresArrayEntityCteBuilder.d.ts +0 -138
  62. package/dist/src/transformers/PostgresJsonQueryBuilder.d.ts +0 -88
  63. package/dist/src/transformers/PostgresObjectEntityCteBuilder.d.ts +0 -165
  64. package/dist/src/transformers/TypeTransformationPostProcessor.d.ts +0 -108
  65. package/dist/src/utils/JsonSchemaValidator.d.ts +0 -81
  66. package/dist/transformers/EnhancedJsonMapping.js +0 -223
  67. package/dist/transformers/EnhancedJsonMapping.js.map +0 -1
  68. package/dist/transformers/JsonMappingConverter.js +0 -392
  69. package/dist/transformers/JsonMappingConverter.js.map +0 -1
  70. package/dist/transformers/JsonMappingUnifier.js +0 -216
  71. package/dist/transformers/JsonMappingUnifier.js.map +0 -1
  72. package/dist/transformers/ModelDrivenJsonMapping.js +0 -122
  73. package/dist/transformers/ModelDrivenJsonMapping.js.map +0 -1
  74. package/dist/transformers/PostgresArrayEntityCteBuilder.js +0 -458
  75. package/dist/transformers/PostgresArrayEntityCteBuilder.js.map +0 -1
  76. package/dist/transformers/PostgresJsonQueryBuilder.js +0 -245
  77. package/dist/transformers/PostgresJsonQueryBuilder.js.map +0 -1
  78. package/dist/transformers/PostgresObjectEntityCteBuilder.js +0 -347
  79. package/dist/transformers/PostgresObjectEntityCteBuilder.js.map +0 -1
  80. package/dist/transformers/TypeTransformationPostProcessor.js +0 -363
  81. package/dist/transformers/TypeTransformationPostProcessor.js.map +0 -1
  82. package/dist/utils/JsonSchemaValidator.js +0 -215
  83. package/dist/utils/JsonSchemaValidator.js.map +0 -1
@@ -1,454 +0,0 @@
1
- import { CommonTable, SourceAliasExpression, SelectItem, SelectClause, FromClause, SourceExpression, TableSource, GroupByClause } from '../models/Clause';
2
- import { SimpleSelectQuery } from '../models/SimpleSelectQuery';
3
- import { IdentifierString, ColumnReference, FunctionCall, ValueList, LiteralValue, RawString } from '../models/ValueComponent';
4
- import { SelectValueCollector } from './SelectValueCollector';
5
- /**
6
- * Builds CTEs for array entities using depth-first processing and row compression.
7
- *
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
13
- */
14
- export class PostgresArrayEntityCteBuilder {
15
- /**
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
21
- * @param allEntities Map of all entities in the mapping
22
- * @param mapping The JSON mapping configuration
23
- * @param columnMappings Optional mappings from object entity IDs to generated JSON column names
24
- * @returns Object containing updated CTEs and last CTE alias
25
- */
26
- buildArrayEntityCtes(ctesSoFar, aliasOfCteToBuildUpon, allEntities, mapping, columnMappings) {
27
- let currentCtes = [...ctesSoFar];
28
- let currentCteAlias = aliasOfCteToBuildUpon;
29
- // Collect and sort array entities by depth
30
- const sortedArrayInfos = this.collectAndSortArrayEntities(mapping, allEntities);
31
- if (sortedArrayInfos.length === 0) {
32
- return { updatedCtes: currentCtes, lastCteAlias: currentCteAlias };
33
- }
34
- // Group array entities by depth level for batch processing
35
- const entitiesByDepth = this.groupEntitiesByDepth(sortedArrayInfos);
36
- // Process from deepest to shallowest (depth-first)
37
- const depths = Array.from(entitiesByDepth.keys()).sort((a, b) => b - a);
38
- for (const depth of depths) {
39
- const infos = entitiesByDepth.get(depth);
40
- // Build CTE for all entities at this depth
41
- const { cte, newCteAlias } = this.buildDepthCte(infos, currentCteAlias, currentCtes, depth, mapping, columnMappings);
42
- currentCtes.push(cte);
43
- currentCteAlias = newCteAlias;
44
- }
45
- return { updatedCtes: currentCtes, lastCteAlias: currentCteAlias };
46
- }
47
- /**
48
- * Collects array entities and calculates depth for dependency ordering.
49
- * Depth = distance from root. Deeper arrays processed first.
50
- *
51
- * @param mapping The JSON mapping configuration
52
- * @param allEntities Map of all entities in the mapping
53
- * @returns Array of array entity information with depths, sorted deepest first
54
- */
55
- collectAndSortArrayEntities(mapping, allEntities) {
56
- const arrayEntityInfos = [];
57
- // Helper function to calculate depth for an entity
58
- const getDepth = (entityId) => {
59
- const entity = allEntities.get(entityId);
60
- if (!entity || entity.isRoot)
61
- return 0;
62
- if (!entity.parentId)
63
- return 1;
64
- return 1 + getDepth(entity.parentId);
65
- };
66
- // Collect all array-type nested entities
67
- mapping.nestedEntities.forEach(ne => {
68
- if (ne.relationshipType === "array") {
69
- const currentArrayEntity = allEntities.get(ne.id);
70
- const parentEntity = allEntities.get(ne.parentId);
71
- if (!currentArrayEntity || !parentEntity) {
72
- throw new Error(`Configuration error: Array entity '${ne.id}' or its parent '${ne.parentId}' not found.`);
73
- }
74
- // Determine the linking column from parent entity
75
- // This assumes the first column of the parent is a suitable key for linking.
76
- // More robust linking might require explicit configuration in the mapping.
77
- const parentSqlColumns = Object.values(parentEntity.columns);
78
- if (parentSqlColumns.length === 0) {
79
- throw new Error(`Configuration error: Parent entity '${parentEntity.name}' (ID: ${parentEntity.id}) must have at least one column defined to serve as a linking key for child array '${ne.name}'.`);
80
- }
81
- const parentIdColumnSqlName = parentSqlColumns[0];
82
- arrayEntityInfos.push({
83
- entity: currentArrayEntity,
84
- parentEntity: parentEntity,
85
- parentIdColumnSqlName: parentIdColumnSqlName,
86
- depth: getDepth(ne.id)
87
- });
88
- }
89
- });
90
- // Sort by depth, deepest arrays (higher depth number) processed first (bottom-up for arrays)
91
- arrayEntityInfos.sort((a, b) => b.depth - a.depth);
92
- return arrayEntityInfos;
93
- }
94
- /**
95
- * Groups array entities by depth level for batch processing.
96
- *
97
- * @param arrayInfos Array of array entity information with depths
98
- * @returns Map of depth level to entities at that depth
99
- */
100
- groupEntitiesByDepth(arrayInfos) {
101
- const entitiesByDepth = new Map();
102
- arrayInfos.forEach(info => {
103
- const depth = info.depth;
104
- if (!entitiesByDepth.has(depth)) {
105
- entitiesByDepth.set(depth, []);
106
- }
107
- entitiesByDepth.get(depth).push(info);
108
- });
109
- return entitiesByDepth;
110
- }
111
- /**
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.
115
- *
116
- * @param infos Array entities at this depth level
117
- * @param currentCteAlias Alias of the CTE to build upon
118
- * @param currentCtes All CTEs built so far
119
- * @param depth Current depth level being processed
120
- * @param mapping JSON mapping configuration
121
- * @param columnMappings Optional mappings from object entity IDs to generated JSON column names
122
- * @returns The new CTE and its alias
123
- */
124
- buildDepthCte(infos, currentCteAlias, currentCtes, depth, mapping, columnMappings) {
125
- var _a;
126
- // Collect columns that will be compressed into arrays
127
- // This includes both direct columns and columns from nested entities within the array
128
- const arrayColumns = new Set();
129
- infos.forEach(info => {
130
- // Add direct columns from the array entity
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);
146
- });
147
- // Get columns from previous CTE
148
- const prevCte = (_a = currentCtes.find(c => c.aliasExpression.table.name === currentCteAlias)) === null || _a === void 0 ? void 0 : _a.query;
149
- if (!prevCte) {
150
- throw new Error(`CTE not found: ${currentCteAlias}`);
151
- }
152
- const prevSelects = new SelectValueCollector(null, currentCtes).collect(prevCte); // Build SELECT items: columns that are NOT being compressed (for GROUP BY)
153
- const groupByItems = [];
154
- const selectItems = [];
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));
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);
181
- // Add JSON aggregation columns for each array entity at this depth
182
- for (const info of infos) {
183
- const agg = this.buildAggregationDetailsForArrayEntity(info.entity, mapping.nestedEntities, new Map(), // allEntities - not needed for array aggregation
184
- columnMappings);
185
- selectItems.push(new SelectItem(agg.jsonAgg, info.entity.propertyName));
186
- }
187
- // Create the new CTE
188
- const cteAlias = `${PostgresArrayEntityCteBuilder.CTE_ARRAY_PREFIX}${depth}`;
189
- const cteSelect = new SimpleSelectQuery({
190
- selectClause: new SelectClause(selectItems),
191
- fromClause: new FromClause(new SourceExpression(new TableSource(null, new IdentifierString(currentCteAlias)), null), null),
192
- groupByClause: groupByItems.length > 0 ? new GroupByClause(groupByItems) : null,
193
- });
194
- const cte = new CommonTable(cteSelect, new SourceAliasExpression(cteAlias, null), null);
195
- return { cte, newCteAlias: cteAlias };
196
- }
197
- /**
198
- * Creates jsonb_agg function for array entity.
199
- * Handles entity columns and nested child relationships.
200
- * Uses originalPropertyName to avoid sequential numbering.
201
- *
202
- * @param entity The array entity being processed
203
- * @param nestedEntities All nested entities from the mapping
204
- * @param allEntities Map of all entities (not used in current implementation)
205
- * @param columnMappings Mappings from object entity IDs to generated JSON column names
206
- * @returns Object containing the JSON aggregation function
207
- */
208
- buildAggregationDetailsForArrayEntity(entity, nestedEntities, allEntities, columnMappings) {
209
- // Build JSON object for array elements using JSONB functions
210
- const jsonBuildFunction = PostgresArrayEntityCteBuilder.JSON_FUNCTIONS.BUILD_OBJECT;
211
- const args = [];
212
- // Add the entity's own columns
213
- Object.entries(entity.columns).forEach(([jsonKey, sqlColumn]) => {
214
- args.push(new LiteralValue(jsonKey, undefined, true));
215
- args.push(new ColumnReference(null, new IdentifierString(sqlColumn)));
216
- });
217
- // Find and process child entities (both object and array types)
218
- const childEntities = nestedEntities.filter((ne) => ne.parentId === entity.id);
219
- childEntities.forEach((childEntity) => {
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, undefined, true));
223
- if (childEntity.relationshipType === "object") {
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)));
268
- }
269
- else if (childEntity.relationshipType === "array") {
270
- // For array relationships, use the column directly
271
- args.push(new ColumnReference(null, new IdentifierString(childEntity.propertyName)));
272
- }
273
- });
274
- // Create JSON object
275
- const jsonObject = new FunctionCall(null, new RawString(jsonBuildFunction), new ValueList(args), null);
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
283
- const jsonAgg = new FunctionCall(null, new RawString(jsonAggFunction), new ValueList([jsonObject]), null);
284
- return { jsonAgg };
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
- }
446
- }
447
- // Constants for consistent naming conventions
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
- };
454
- //# sourceMappingURL=PostgresArrayEntityCteBuilder.js.map
@@ -1 +0,0 @@
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,EAA6B,MAAM,0BAA0B,CAAC;AAG1K,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAY9D;;;;;;;;GAQG;AACH,MAAM,OAAO,6BAA6B;IAUtC;;;;;;;;;;OAUG;IACI,oBAAoB,CACvB,SAAwB,EACxB,qBAA6B,EAC7B,WAA2C,EAC3C,OAAoB,EACpB,cAAoC;QAEpC,IAAI,WAAW,GAAG,CAAC,GAAG,SAAS,CAAC,CAAC;QACjC,IAAI,eAAe,GAAG,qBAAqB,CAAC;QAE5C,2CAA2C;QA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C;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"}
@@ -1,88 +0,0 @@
1
- import { SimpleSelectQuery } from '../models/SimpleSelectQuery';
2
- import { SelectQuery } from '../models/SelectQuery';
3
- import { QueryBuildOptions } from './DynamicQueryBuilder';
4
- /**
5
- * Universal JSON mapping definition for creating any level of JSON structures.
6
- * Supports flat arrays, nested objects, and unlimited hierarchical structures.
7
- */
8
- export interface JsonMapping {
9
- rootName: string;
10
- rootEntity: {
11
- id: string;
12
- name: string;
13
- columns: {
14
- [jsonKey: string]: string;
15
- };
16
- };
17
- nestedEntities: Array<{
18
- id: string;
19
- name: string;
20
- parentId: string;
21
- propertyName: string;
22
- relationshipType?: "object" | "array";
23
- columns: {
24
- [jsonKey: string]: string;
25
- };
26
- }>;
27
- resultFormat?: "array" | "single";
28
- emptyResult?: string;
29
- }
30
- /**
31
- * PostgreSQL JSON query builder that transforms SimpleSelectQuery into queries
32
- * that return JSON arrays or single JSON objects using PostgreSQL JSON functions.
33
- */
34
- export declare class PostgresJsonQueryBuilder {
35
- private selectValueCollector;
36
- private objectEntityCteBuilder;
37
- private arrayEntityCteBuilder;
38
- constructor();
39
- /**
40
- * Validates the JSON mapping and the original query.
41
- * @param query Original query to transform
42
- * @param mapping JSON mapping configuration
43
- */
44
- private validateMapping;
45
- /**
46
- * Build JSON query from original query and mapping configuration.
47
- * @param originalQuery Original query to transform (can be any SelectQuery type)
48
- * @param mapping JSON mapping configuration
49
- * @returns Transformed query with JSON aggregation
50
- */
51
- buildJsonQuery(originalQuery: SelectQuery, mapping: JsonMapping, options?: QueryBuildOptions): SimpleSelectQuery;
52
- buildJsonQuery(originalQuery: SimpleSelectQuery, mapping: JsonMapping, options?: QueryBuildOptions): SimpleSelectQuery;
53
- /**
54
- * Build JSON query from original query and mapping configuration.
55
- * @deprecated Use buildJsonQuery instead. This method will be removed in a future version.
56
- * @param originalQuery Original query to transform
57
- * @param mapping JSON mapping configuration
58
- * @returns Transformed query with JSON aggregation
59
- */
60
- buildJson(originalQuery: SimpleSelectQuery, mapping: JsonMapping): SimpleSelectQuery;
61
- /**
62
- * Builds the JSON structure using a unified CTE-based strategy.
63
- * @param originalQuery Original query
64
- * @param mapping JSON mapping configuration
65
- * @returns Query with CTE-based JSON aggregation
66
- */
67
- private buildJsonWithCteStrategy;
68
- /**
69
- * Creates the initial Common Table Expression (CTE) from the original query.
70
- * @param originalQuery The base SimpleSelectQuery.
71
- * @returns An object containing the initial CTE and its alias.
72
- */
73
- private createInitialCte;
74
- /**
75
- * Builds the final SELECT query that constructs the root JSON object (or array of objects).
76
- * This query uses all previously generated CTEs.
77
- * @param finalCtesList The complete list of all CTEs (initial and array CTEs).
78
- * @param lastCteAliasForFromClause Alias of the final CTE from which the root object will be built.
79
- * @param allEntities Map of all processable entities.
80
- * @param mapping JSON mapping configuration.
81
- * @returns The final SimpleSelectQuery.
82
- */
83
- private buildFinalSelectQuery;
84
- /**
85
- * Build JSON object for entity, using parent JSON columns when available
86
- */
87
- private buildEntityJsonObject;
88
- }