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
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Unified JSON mapping converter that handles all supported formats
3
+ * and provides a single interface for mapping transformations.
4
+ */
5
+ import { JsonMapping } from './PostgresJsonQueryBuilder';
6
+ import { ModelDrivenJsonMapping } from './ModelDrivenJsonMapping';
7
+ import { EnhancedJsonMapping, LegacyJsonMapping, TypeProtectionConfig } from './EnhancedJsonMapping';
8
+ /**
9
+ * Input format types that the converter can handle.
10
+ */
11
+ export type JsonMappingInput = EnhancedJsonMapping | ModelDrivenJsonMapping | LegacyJsonMapping;
12
+ /**
13
+ * Format detection result.
14
+ */
15
+ export type MappingFormat = 'enhanced' | 'model-driven' | 'legacy';
16
+ /**
17
+ * Conversion result with metadata.
18
+ */
19
+ export interface ConversionResult {
20
+ /** Detected input format */
21
+ format: MappingFormat;
22
+ /** Converted legacy mapping for PostgresJsonQueryBuilder */
23
+ mapping: JsonMapping;
24
+ /** Type protection configuration */
25
+ typeProtection: TypeProtectionConfig;
26
+ /** Original input for reference */
27
+ originalInput: JsonMappingInput;
28
+ /** Additional metadata */
29
+ metadata?: {
30
+ typeInfo?: {
31
+ interface: string;
32
+ importPath: string;
33
+ generics?: string[];
34
+ };
35
+ version?: string;
36
+ description?: string;
37
+ };
38
+ }
39
+ /**
40
+ * Unified JSON mapping converter that handles all supported formats using the Strategy pattern.
41
+ *
42
+ * This converter automatically detects the input format and applies the appropriate conversion
43
+ * strategy to transform any supported JSON mapping format into a standardized result.
44
+ *
45
+ * **Supported Formats:**
46
+ * - **Enhanced**: Rich format with metadata, type protection, and advanced column configurations
47
+ * - **Model-Driven**: TypeScript interface-based mapping with structured field definitions
48
+ * - **Legacy**: Simple format compatible with PostgresJsonQueryBuilder
49
+ *
50
+ * **Usage:**
51
+ * ```typescript
52
+ * const converter = new JsonMappingConverter();
53
+ * const result = converter.convert(someMapping);
54
+ * const legacyMapping = converter.toLegacyMapping(someMapping);
55
+ * ```
56
+ *
57
+ * @public
58
+ */
59
+ export declare class JsonMappingConverter {
60
+ /** Ordered list of conversion strategies, checked in priority order */
61
+ private strategies;
62
+ /**
63
+ * Creates a new JsonMappingConverter with all supported strategies.
64
+ *
65
+ * Strategies are checked in order of specificity:
66
+ * 1. Enhanced format (most feature-rich)
67
+ * 2. Model-driven format (TypeScript-based)
68
+ * 3. Legacy format (fallback)
69
+ */
70
+ constructor();
71
+ /**
72
+ * Detects the format of the input mapping without performing conversion.
73
+ *
74
+ * This method uses the same strategy pattern as conversion but only returns
75
+ * the detected format type for inspection purposes.
76
+ *
77
+ * @param input - The JSON mapping to analyze
78
+ * @returns The detected mapping format type
79
+ *
80
+ * @throws {Error} When input format is not supported by any strategy
81
+ *
82
+ * @example
83
+ * ```typescript
84
+ * const format = converter.detectFormat(myMapping);
85
+ * console.log(`Detected format: ${format}`); // "enhanced", "model-driven", or "legacy"
86
+ * ```
87
+ */
88
+ detectFormat(input: JsonMappingInput): MappingFormat;
89
+ /**
90
+ * Converts any supported JSON mapping format to a comprehensive result with metadata.
91
+ *
92
+ * This is the primary conversion method that performs format detection and transformation
93
+ * in a single operation. The result includes the legacy mapping, type protection configuration,
94
+ * and metadata about the conversion process.
95
+ *
96
+ * @param input - The JSON mapping in any supported format (Enhanced, Model-Driven, or Legacy)
97
+ * @returns Complete conversion result with mapping, metadata, and type protection
98
+ *
99
+ * @throws {Error} When the input format is not recognized by any strategy
100
+ *
101
+ * @example
102
+ * ```typescript
103
+ * const result = converter.convert(enhancedMapping);
104
+ * console.log(`Format: ${result.format}`);
105
+ * console.log(`Type protection: ${result.typeProtection.protectedStringFields.length} fields`);
106
+ *
107
+ * // Use the converted mapping
108
+ * const queryBuilder = new PostgresJsonQueryBuilder(result.mapping);
109
+ * ```
110
+ *
111
+ * @see {@link toLegacyMapping} For simple mapping extraction
112
+ * @see {@link getTypeProtection} For type protection only
113
+ */
114
+ convert(input: JsonMappingInput): ConversionResult;
115
+ /**
116
+ * Extracts only the legacy JsonMapping for direct use with PostgresJsonQueryBuilder.
117
+ *
118
+ * This convenience method performs the full conversion but returns only the mapping portion,
119
+ * discarding metadata and type protection information. Use this when you only need
120
+ * the mapping for query building and don't require additional metadata.
121
+ *
122
+ * @param input - The JSON mapping in any supported format
123
+ * @returns Legacy-format JsonMapping ready for PostgresJsonQueryBuilder
124
+ *
125
+ * @throws {Error} When the input format is not supported
126
+ *
127
+ * @example
128
+ * ```typescript
129
+ * const legacyMapping = converter.toLegacyMapping(modelDrivenMapping);
130
+ * const queryBuilder = new PostgresJsonQueryBuilder(legacyMapping);
131
+ * const query = queryBuilder.build(selectQuery);
132
+ * ```
133
+ *
134
+ * @see {@link convert} For full conversion with metadata
135
+ */
136
+ toLegacyMapping(input: JsonMappingInput): JsonMapping;
137
+ /**
138
+ * Extracts type protection configuration for runtime type checking.
139
+ *
140
+ * Type protection helps identify fields that should be treated as strings
141
+ * to prevent injection attacks or type coercion issues. This is particularly
142
+ * useful when working with user input or external data sources.
143
+ *
144
+ * @param input - The JSON mapping in any supported format
145
+ * @returns Type protection configuration with protected field definitions
146
+ *
147
+ * @throws {Error} When the input format is not supported
148
+ *
149
+ * @example
150
+ * ```typescript
151
+ * const typeProtection = converter.getTypeProtection(enhancedMapping);
152
+ *
153
+ * // Apply type protection during data processing
154
+ * for (const field of typeProtection.protectedStringFields) {
155
+ * if (typeof data[field] !== 'string') {
156
+ * data[field] = String(data[field]);
157
+ * }
158
+ * }
159
+ * ```
160
+ */
161
+ getTypeProtection(input: JsonMappingInput): TypeProtectionConfig;
162
+ /**
163
+ * Validates that the input mapping is well-formed and can be successfully converted.
164
+ *
165
+ * This method performs comprehensive validation without attempting conversion,
166
+ * returning an array of error messages for any issues found. An empty array
167
+ * indicates the mapping is valid and ready for conversion.
168
+ *
169
+ * **Validation Checks:**
170
+ * - Basic structure validation (object type, required fields)
171
+ * - Format-specific validation (Enhanced, Model-Driven, Legacy)
172
+ * - Column configuration validation
173
+ * - Type protection configuration validation
174
+ *
175
+ * @param input - The JSON mapping to validate
176
+ * @returns Array of validation error messages (empty if valid)
177
+ *
178
+ * @example
179
+ * ```typescript
180
+ * const errors = converter.validate(suspiciousMapping);
181
+ * if (errors.length > 0) {
182
+ * console.error('Validation failed:', errors);
183
+ * throw new Error(`Invalid mapping: ${errors.join(', ')}`);
184
+ * }
185
+ *
186
+ * // Safe to convert
187
+ * const result = converter.convert(suspiciousMapping);
188
+ * ```
189
+ *
190
+ * @see {@link convert} Performs conversion after implicit validation
191
+ */
192
+ validate(input: JsonMappingInput): string[];
193
+ /**
194
+ * Creates a new enhanced mapping from legacy mapping.
195
+ */
196
+ upgradeToEnhanced(legacy: LegacyJsonMapping, typeInfo?: {
197
+ interface: string;
198
+ importPath: string;
199
+ }): EnhancedJsonMapping;
200
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Unified JSON Mapping processor that supports both legacy and model-driven formats.
3
+ *
4
+ * @deprecated Use JsonMappingConverter instead. This module is kept for backward compatibility.
5
+ * This module provides backward compatibility while encouraging migration to the model-driven format.
6
+ * It automatically detects the input format and normalizes to a consistent internal representation.
7
+ */
8
+ import { JsonMapping } from './PostgresJsonQueryBuilder';
9
+ import { ModelDrivenJsonMapping } from './ModelDrivenJsonMapping';
10
+ /**
11
+ * Unified mapping format that can handle both legacy and model-driven inputs.
12
+ */
13
+ export interface UnifiedMappingInput {
14
+ typeInfo?: {
15
+ interface: string;
16
+ importPath: string;
17
+ };
18
+ structure?: any;
19
+ protectedStringFields?: string[];
20
+ rootName?: string;
21
+ rootEntity?: any;
22
+ nestedEntities?: any[];
23
+ columns?: any;
24
+ relationships?: any;
25
+ }
26
+ /**
27
+ * Result of mapping format detection and conversion.
28
+ */
29
+ export interface MappingProcessResult {
30
+ format: 'model-driven' | 'unified' | 'legacy';
31
+ jsonMapping: JsonMapping;
32
+ originalInput: UnifiedMappingInput;
33
+ metadata?: {
34
+ typeInfo?: {
35
+ interface: string;
36
+ importPath: string;
37
+ };
38
+ protectedStringFields?: string[];
39
+ typeProtection?: any;
40
+ };
41
+ }
42
+ /**
43
+ * Detects the format of a JSON mapping configuration.
44
+ *
45
+ * @param input - The mapping configuration to analyze
46
+ * @returns The detected format type
47
+ */
48
+ export declare function detectMappingFormat(input: UnifiedMappingInput): 'model-driven' | 'unified' | 'legacy';
49
+ /**
50
+ * Main processor that unifies all JSON mapping formats into a consistent JsonMapping.
51
+ *
52
+ * @deprecated Use JsonMappingConverter.convert() instead.
53
+ *
54
+ * Features:
55
+ * - Automatic format detection
56
+ * - Backward compatibility with all existing formats
57
+ * - Metadata preservation for advanced features
58
+ * - Zero external dependencies
59
+ *
60
+ * @param input - Any supported JSON mapping format
61
+ * @returns Unified processing result with JsonMapping and metadata
62
+ */
63
+ export declare function processJsonMapping(input: UnifiedMappingInput): MappingProcessResult;
64
+ /**
65
+ * Convenience function for direct JsonMapping extraction.
66
+ *
67
+ * @deprecated Use JsonMappingConverter.toLegacyMapping() instead.
68
+ *
69
+ * @param input - Any supported JSON mapping format
70
+ * @returns JsonMapping ready for use with PostgresJsonQueryBuilder
71
+ */
72
+ export declare function unifyJsonMapping(input: UnifiedMappingInput): JsonMapping;
73
+ /**
74
+ * Type guard to check if input uses model-driven format.
75
+ *
76
+ * @param input - Mapping input to check
77
+ * @returns True if input is model-driven format
78
+ */
79
+ export declare function isModelDrivenFormat(input: UnifiedMappingInput): input is ModelDrivenJsonMapping;
80
+ /**
81
+ * Type guard to check if input uses unified format.
82
+ *
83
+ * @param input - Mapping input to check
84
+ * @returns True if input is unified format
85
+ */
86
+ export declare function isUnifiedFormat(input: UnifiedMappingInput): boolean;
87
+ /**
88
+ * Type guard to check if input uses legacy format.
89
+ *
90
+ * @param input - Mapping input to check
91
+ * @returns True if input is legacy format
92
+ */
93
+ export declare function isLegacyFormat(input: UnifiedMappingInput): boolean;
94
+ /**
95
+ * Migration helper that suggests upgrading to model-driven format.
96
+ *
97
+ * @param input - Current mapping configuration
98
+ * @returns Suggestions for migration (if applicable)
99
+ */
100
+ export declare function suggestModelDrivenMigration(input: UnifiedMappingInput): string[];
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Model-driven JSON mapping structure that mirrors TypeScript model definitions.
3
+ * This approach provides intuitive, hierarchical mapping that closely resembles the target data structure.
4
+ */
5
+ import { JsonMapping } from './PostgresJsonQueryBuilder';
6
+ /**
7
+ * Supported field types for database column mapping.
8
+ */
9
+ export type FieldType = 'string' | 'number' | 'boolean' | 'object' | 'array' | 'auto';
10
+ /**
11
+ * Field mapping configuration that can be either a simple column name or enhanced mapping with type control.
12
+ */
13
+ export type FieldMapping = string | {
14
+ column: string;
15
+ type?: FieldType;
16
+ } | {
17
+ from: string;
18
+ type?: FieldType;
19
+ };
20
+ /**
21
+ * Nested object or array structure definition.
22
+ */
23
+ export interface NestedStructure {
24
+ type: 'object' | 'array';
25
+ from: string;
26
+ structure: StructureFields;
27
+ }
28
+ /**
29
+ * Structure fields can contain either field mappings or nested structures.
30
+ */
31
+ export type StructureFields = {
32
+ [key: string]: FieldMapping | NestedStructure;
33
+ };
34
+ /**
35
+ * Model-driven JSON mapping that mirrors TypeScript interface structure.
36
+ * This design makes it easy to understand the relationship between models and database columns.
37
+ */
38
+ export interface ModelDrivenJsonMapping {
39
+ typeInfo: {
40
+ interface: string;
41
+ importPath: string;
42
+ };
43
+ structure: StructureFields;
44
+ }
45
+ /**
46
+ * Type protection configuration extracted from the model-driven mapping.
47
+ */
48
+ export interface TypeProtectionConfig {
49
+ protectedStringFields: string[];
50
+ }
51
+ /**
52
+ * Convert a model-driven JSON mapping to the traditional JsonMapping format.
53
+ * This enables backward compatibility with existing PostgresJsonQueryBuilder.
54
+ */
55
+ export declare function convertModelDrivenMapping(modelMapping: ModelDrivenJsonMapping): {
56
+ jsonMapping: JsonMapping;
57
+ typeProtection: TypeProtectionConfig;
58
+ };
59
+ /**
60
+ * Validate that a model-driven mapping structure is well-formed.
61
+ */
62
+ export declare function validateModelDrivenMapping(mapping: ModelDrivenJsonMapping): string[];
@@ -1,97 +1,138 @@
1
1
  import { CommonTable } from '../models/Clause';
2
2
  import { JsonMapping } from './PostgresJsonQueryBuilder';
3
- import { ProcessableEntity } from './PostgresObjectEntityCteBuilder';
3
+ import { ProcessableEntity, JsonColumnMapping } from './PostgresObjectEntityCteBuilder';
4
4
  /**
5
- * PostgreSQL-specific builder for creating CTEs for array entities (array relationships).
6
- * This class handles the creation of CTEs that build JSON/JSONB arrays for child entities,
7
- * processing them from the deepest level up to ensure proper dependency ordering.
5
+ * Builds CTEs for array entities using depth-first processing and row compression.
8
6
  *
9
- * Features:
10
- * - Depth-based CTE naming (cte_array_depth_N)
11
- * - Row compression using GROUP BY operations
12
- * - JSONB/JSON array aggregation
13
- * - Hierarchical processing of nested arrays
14
- * - Column exclusion to avoid duplication
15
- *
16
- * Why depth calculation is critical:
17
- * 1. Array entities can be nested at multiple levels. We must process the deepest
18
- * (most distant) arrays first to ensure their JSON representations are available
19
- * when building their parent arrays.
20
- * 2. Array entity processing is essentially a row compression operation using GROUP BY.
21
- * Unlike parent entities which use column compression, arrays require grouping
22
- * to aggregate multiple rows into JSON arrays.
23
- *
24
- * Example hierarchy:
25
- * Order (root, depth 0)
26
- * └─ Items (array, depth 1)
27
- * └─ Details (array, depth 2)
28
- *
29
- * Processing order: depth 2 → depth 1 → depth 0
7
+ * Core concepts:
8
+ * - Column Compression: OBJECT relationships (user_id, user_name → user_json)
9
+ * - Row Compression: ARRAY relationships (multiple rows → JSON array via GROUP BY)
10
+ * - Depth-First: Process deepest arrays first for dependency ordering
11
+ * - GROUP BY Exclusion: Exclude array-internal columns to prevent over-grouping
30
12
  */
31
13
  export declare class PostgresArrayEntityCteBuilder {
32
14
  private static readonly CTE_ARRAY_PREFIX;
15
+ private static readonly JSON_FUNCTIONS;
33
16
  /**
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
17
+ * Builds CTEs for all array entities using depth-first processing.
18
+ * Collects arrays by depth, processes deepest first, chains CTEs.
19
+ *
20
+ * @param ctesSoFar Array of CTEs built so far
21
+ * @param aliasOfCteToBuildUpon Alias of the CTE to build upon
37
22
  * @param allEntities Map of all entities in the mapping
38
23
  * @param mapping The JSON mapping configuration
39
- * @returns Object containing the updated list of all CTEs and the alias of the last CTE created
24
+ * @param columnMappings Optional mappings from object entity IDs to generated JSON column names
25
+ * @returns Object containing updated CTEs and last CTE alias
40
26
  */
41
- buildArrayEntityCtes(ctesSoFar: CommonTable[], aliasOfCteToBuildUpon: string, allEntities: Map<string, ProcessableEntity>, mapping: JsonMapping): {
27
+ buildArrayEntityCtes(ctesSoFar: CommonTable[], aliasOfCteToBuildUpon: string, allEntities: Map<string, ProcessableEntity>, mapping: JsonMapping, columnMappings?: JsonColumnMapping[]): {
42
28
  updatedCtes: CommonTable[];
43
29
  lastCteAlias: string;
44
30
  };
45
31
  /**
46
- * Collect all array entities and calculate their depth from root.
47
- *
48
- * Depth calculation ensures proper processing order where deeper nested
49
- * arrays are processed first, making their aggregated data available
50
- * for parent array processing.
32
+ * Collects array entities and calculates depth for dependency ordering.
33
+ * Depth = distance from root. Deeper arrays processed first.
51
34
  *
52
35
  * @param mapping The JSON mapping configuration
53
36
  * @param allEntities Map of all entities in the mapping
54
- * @returns Array of array entity information with calculated depths, sorted deepest first
37
+ * @returns Array of array entity information with depths, sorted deepest first
55
38
  */
56
39
  private collectAndSortArrayEntities;
57
40
  /**
58
- * Group array entities by their depth level.
59
- *
60
- * Grouping by depth allows us to:
61
- * - Process all entities at the same level in a single CTE
62
- * - Optimize query performance by reducing the number of CTEs
63
- * - Maintain clear dependency ordering
41
+ * Groups array entities by depth level for batch processing.
64
42
  *
65
43
  * @param arrayInfos Array of array entity information with depths
66
44
  * @returns Map of depth level to entities at that depth
67
45
  */
68
46
  private groupEntitiesByDepth;
69
47
  /**
70
- * Build a CTE that processes all array entities at a specific depth level.
71
- *
72
- * This method creates a single CTE that aggregates multiple array entities
73
- * at the same depth, using GROUP BY to compress rows into JSON arrays.
48
+ * Builds CTE for specific depth level using row compression.
49
+ * Uses GROUP BY to aggregate multiple rows into JSON arrays.
50
+ * Excludes array-internal columns from GROUP BY to prevent over-grouping.
74
51
  *
75
52
  * @param infos Array entities at this depth level
76
53
  * @param currentCteAlias Alias of the CTE to build upon
77
54
  * @param currentCtes All CTEs built so far
78
55
  * @param depth Current depth level being processed
79
56
  * @param mapping JSON mapping configuration
57
+ * @param columnMappings Optional mappings from object entity IDs to generated JSON column names
80
58
  * @returns The new CTE and its alias
81
59
  */
82
60
  private buildDepthCte;
83
61
  /**
84
- * Build JSON aggregation function for an array entity.
85
- *
86
- * This method creates a jsonb_agg or json_agg function call that aggregates
87
- * the entity's columns into a JSON array. It also handles nested relationships
88
- * by including child entity properties in the JSON object.
62
+ * Creates jsonb_agg function for array entity.
63
+ * Handles entity columns and nested child relationships.
64
+ * Uses originalPropertyName to avoid sequential numbering.
89
65
  *
90
66
  * @param entity The array entity being processed
91
67
  * @param nestedEntities All nested entities from the mapping
92
68
  * @param allEntities Map of all entities (not used in current implementation)
93
- * @param useJsonb Whether to use JSONB functions
69
+ * @param columnMappings Mappings from object entity IDs to generated JSON column names
94
70
  * @returns Object containing the JSON aggregation function
95
71
  */
96
72
  private buildAggregationDetailsForArrayEntity;
73
+ /**
74
+ * Collects array entity columns by depth for GROUP BY exclusion strategy.
75
+ *
76
+ * @param mapping The JSON mapping configuration containing all entities
77
+ * @param currentDepth The current aggregation depth being processed
78
+ * @returns A map where keys are depth levels and values are sets of column names
79
+ */
80
+ private collectArrayEntityColumnsByDepth;
81
+ /**
82
+ * Calculates entity depth by traversing up to root.
83
+ *
84
+ * @param entity The entity to calculate depth for
85
+ * @param mapping The JSON mapping containing all entities
86
+ * @returns The depth level (0 for root level, 1 for first level, etc.)
87
+ */
88
+ private calculateEntityDepth;
89
+ /**
90
+ * Adds entity columns to depth set.
91
+ *
92
+ * @param entity The entity whose columns should be added
93
+ * @param depth The depth level to add columns to
94
+ * @param arrayEntitiesByDepth The map to update
95
+ */
96
+ private addEntityColumnsToDepthSet;
97
+ /**
98
+ * Recursively collects columns from descendant entities.
99
+ *
100
+ * @param parentEntityId The ID of the parent entity
101
+ * @param targetDepth The depth level to assign collected columns to
102
+ * @param mapping The JSON mapping containing all entities
103
+ * @param arrayEntitiesByDepth The map to update with collected columns
104
+ */
105
+ private collectDescendantColumns;
106
+ /**
107
+ * Implements GROUP BY exclusion strategy for array aggregation.
108
+ * Excludes current array columns and array-internal object JSON columns.
109
+ *
110
+ * @param prevSelects SELECT variables from the previous CTE
111
+ * @param arrayColumns Columns that are being aggregated (should be excluded from GROUP BY)
112
+ * @param arrayEntitiesByDepth Map of depth levels to their column sets
113
+ * @param currentDepth The current aggregation depth being processed
114
+ * @param selectItems Output array for SELECT items
115
+ * @param groupByItems Output array for GROUP BY items
116
+ * @param arrayInternalObjectColumns JSON columns from objects within arrays being processed
117
+ */
118
+ private processSelectVariablesForGroupBy;
119
+ /**
120
+ * Determines if column should be included in GROUP BY clause.
121
+ * Applies depth-based filtering and special handling for JSON columns.
122
+ *
123
+ * @param columnName The name of the column to evaluate
124
+ * @param arrayEntitiesByDepth Map of depth levels to their column sets
125
+ * @param currentDepth The current aggregation depth
126
+ * @returns True if the column should be included in GROUP BY, false otherwise
127
+ */
128
+ private shouldIncludeColumnInGroupBy;
129
+ /**
130
+ * Applies heuristics for entity JSON column inclusion in GROUP BY.
131
+ * Uses entity numbering patterns to identify deeply nested entities.
132
+ *
133
+ * @param columnName The JSON column name (expected format: entity_N_json)
134
+ * @param currentDepth The current aggregation depth
135
+ * @returns True if the JSON column should be included, false otherwise
136
+ */
137
+ private shouldIncludeJsonColumn;
97
138
  }
@@ -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.
@@ -14,6 +14,23 @@ export interface ProcessableEntity {
14
14
  parentId?: string;
15
15
  relationshipType?: "object" | "array";
16
16
  }
17
+ /**
18
+ * JSON column mapping information
19
+ */
20
+ export interface JsonColumnMapping {
21
+ entityId: string;
22
+ entityName: string;
23
+ generatedColumnName: string;
24
+ depth: number;
25
+ }
26
+ /**
27
+ * Result from CTE builder including column mappings
28
+ */
29
+ export interface CteBuilderResult {
30
+ ctes: CommonTable[];
31
+ lastCteAlias: string;
32
+ columnMappings: JsonColumnMapping[];
33
+ }
17
34
  /**
18
35
  * PostgreSQL-specific builder for creating CTEs for object entities (object relationships).
19
36
  * This class handles the creation of CTEs that build JSON/JSONB objects for object entities,
@@ -43,19 +60,23 @@ export interface ProcessableEntity {
43
60
  * Processing order: depth 2 → depth 1 → depth 0
44
61
  */
45
62
  export declare class PostgresObjectEntityCteBuilder {
46
- private static readonly JSON_COLUMN_SUFFIX;
47
63
  private static readonly CTE_OBJECT_PREFIX;
48
- private static readonly WILDCARD_COLUMN; /**
64
+ private static readonly WILDCARD_COLUMN;
65
+ private jsonColumnCounter;
66
+ private entityToJsonColumnMap;
67
+ private columnMappings;
68
+ /**
49
69
  * Build CTEs for all object entities in the correct dependency order
50
70
  * @param initialCte The starting CTE containing all raw data
51
71
  * @param allEntities Map of all entities in the mapping
52
72
  * @param mapping The JSON mapping configuration
53
73
  * @returns Array of CTEs and the alias of the last CTE created
54
74
  */
55
- buildObjectEntityCtes(initialCte: CommonTable, allEntities: Map<string, ProcessableEntity>, mapping: JsonMapping): {
56
- ctes: CommonTable[];
57
- lastCteAlias: string;
58
- }; /**
75
+ buildObjectEntityCtes(initialCte: CommonTable, allEntities: Map<string, ProcessableEntity>, mapping: JsonMapping): CteBuilderResult;
76
+ /**
77
+ * Generate unique JSON column name with entity name and counter
78
+ */
79
+ private generateUniqueJsonColumnName; /**
59
80
  * Collect all object entities and calculate their depth from root.
60
81
  *
61
82
  * Depth calculation is crucial because:
@@ -87,6 +108,10 @@ export declare class PostgresObjectEntityCteBuilder {
87
108
  * Build JSON column for a single entity with NULL handling
88
109
  */
89
110
  private buildEntityJsonColumn;
111
+ /**
112
+ * Calculate approximate depth for an entity (for mapping purposes)
113
+ */
114
+ private calculateApproximateDepth;
90
115
  /**
91
116
  * Prepare entity columns and NULL checks.
92
117
  *
@@ -20,12 +20,23 @@ import { SqlComponent, SqlComponentVisitor } from "../models/SqlComponent";
20
20
  import { ValueComponent } from "../models/ValueComponent";
21
21
  import { TableColumnResolver } from "./TableColumnResolver";
22
22
  /**
23
- * A visitor that collects all ColumnReference instances from a SQL query structure.
23
+ * A visitor that collects all ColumnReference instances from SimpleSelectQuery structures.
24
24
  * This visitor scans through all clauses and collects all unique ColumnReference objects.
25
25
  * It does not scan Common Table Expressions (CTEs) or subqueries.
26
26
  *
27
- * Important: Only collects column references to tables defined in the root FROM/JOIN clauses,
28
- * as these are the only columns that can be directly referenced in the query.
27
+ * IMPORTANT: This collector only supports SimpleSelectQuery. BinarySelectQuery
28
+ * (UNION/INTERSECT/EXCEPT) will throw an error and should be decomposed into
29
+ * individual SimpleSelectQuery branches before using this collector.
30
+ *
31
+ * Behavioral notes:
32
+ * - Only collects column references to tables defined in the root FROM/JOIN clauses
33
+ * - For aliased columns (e.g., 'title as name'), collects both the original column
34
+ * reference ('title') AND the alias ('name') to enable complete dependency tracking
35
+ *
36
+ * Use cases:
37
+ * - Dependency analysis and schema migration tools
38
+ * - Column usage tracking within individual SELECT branches
39
+ * - Security analysis for column-level access control
29
40
  */
30
41
  export declare class SelectableColumnCollector implements SqlComponentVisitor<void> {
31
42
  private handlers;