rawsql-ts 0.9.0-beta → 0.10.1-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.
- package/README.md +90 -7
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/models/SqlPrintToken.js +2 -0
- package/dist/esm/models/SqlPrintToken.js.map +1 -1
- package/dist/esm/models/ValueComponent.js +13 -12
- package/dist/esm/models/ValueComponent.js.map +1 -1
- package/dist/esm/parsers/SqlPrintTokenParser.js +24 -6
- package/dist/esm/parsers/SqlPrintTokenParser.js.map +1 -1
- package/dist/esm/transformers/PostgresArrayEntityCteBuilder.js +231 -0
- package/dist/esm/transformers/PostgresArrayEntityCteBuilder.js.map +1 -0
- package/dist/esm/transformers/PostgresJsonQueryBuilder.js +226 -0
- package/dist/esm/transformers/PostgresJsonQueryBuilder.js.map +1 -0
- package/dist/esm/transformers/PostgresObjectEntityCteBuilder.js +283 -0
- package/dist/esm/transformers/PostgresObjectEntityCteBuilder.js.map +1 -0
- package/dist/esm/transformers/SqlPrinter.js +9 -3
- package/dist/esm/transformers/SqlPrinter.js.map +1 -1
- package/dist/esm/types/index.d.ts +2 -0
- package/dist/esm/types/models/SqlPrintToken.d.ts +2 -0
- package/dist/esm/types/models/ValueComponent.d.ts +2 -2
- package/dist/esm/types/transformers/PostgresArrayEntityCteBuilder.d.ts +97 -0
- package/dist/esm/types/transformers/PostgresJsonQueryBuilder.d.ts +86 -0
- package/dist/esm/types/transformers/PostgresObjectEntityCteBuilder.d.ts +140 -0
- package/dist/esm/types/utils/SchemaManager.d.ts +132 -0
- package/dist/esm/utils/SchemaManager.js +194 -0
- package/dist/esm/utils/SchemaManager.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/models/SqlPrintToken.d.ts +2 -0
- package/dist/models/SqlPrintToken.js +2 -0
- package/dist/models/SqlPrintToken.js.map +1 -1
- package/dist/models/ValueComponent.d.ts +2 -2
- package/dist/models/ValueComponent.js +13 -12
- package/dist/models/ValueComponent.js.map +1 -1
- package/dist/parsers/SelectQueryParser.js +3 -14
- package/dist/parsers/SelectQueryParser.js.map +1 -1
- package/dist/parsers/SqlPrintTokenParser.js +25 -7
- package/dist/parsers/SqlPrintTokenParser.js.map +1 -1
- package/dist/transformers/PostgresArrayEntityCteBuilder.d.ts +97 -0
- package/dist/transformers/PostgresArrayEntityCteBuilder.js +235 -0
- package/dist/transformers/PostgresArrayEntityCteBuilder.js.map +1 -0
- package/dist/transformers/PostgresJsonQueryBuilder.d.ts +86 -0
- package/dist/transformers/PostgresJsonQueryBuilder.js +230 -0
- package/dist/transformers/PostgresJsonQueryBuilder.js.map +1 -0
- package/dist/transformers/PostgresObjectEntityCteBuilder.d.ts +140 -0
- package/dist/transformers/PostgresObjectEntityCteBuilder.js +287 -0
- package/dist/transformers/PostgresObjectEntityCteBuilder.js.map +1 -0
- package/dist/transformers/SqlFormatter.js +6 -1
- package/dist/transformers/SqlFormatter.js.map +1 -1
- package/dist/transformers/SqlPrinter.js +9 -3
- package/dist/transformers/SqlPrinter.js.map +1 -1
- package/dist/utils/SchemaManager.d.ts +132 -0
- package/dist/utils/SchemaManager.js +201 -0
- package/dist/utils/SchemaManager.js.map +1 -0
- package/package.json +1 -1
@@ -0,0 +1,226 @@
|
|
1
|
+
import { CommonTable, SourceAliasExpression, SelectItem, SelectClause, FromClause, SourceExpression, TableSource, WithClause, LimitClause } 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
|
+
import { PostgresObjectEntityCteBuilder } from './PostgresObjectEntityCteBuilder';
|
6
|
+
import { PostgresArrayEntityCteBuilder } from './PostgresArrayEntityCteBuilder';
|
7
|
+
/**
|
8
|
+
* PostgreSQL JSON query builder that transforms SimpleSelectQuery into queries
|
9
|
+
* that return JSON arrays or single JSON objects using PostgreSQL JSON functions.
|
10
|
+
*/
|
11
|
+
export class PostgresJsonQueryBuilder {
|
12
|
+
constructor() {
|
13
|
+
this.selectValueCollector = new SelectValueCollector(null);
|
14
|
+
this.objectEntityCteBuilder = new PostgresObjectEntityCteBuilder();
|
15
|
+
this.arrayEntityCteBuilder = new PostgresArrayEntityCteBuilder();
|
16
|
+
}
|
17
|
+
/**
|
18
|
+
* Validates the JSON mapping and the original query.
|
19
|
+
* @param query Original query to transform
|
20
|
+
* @param mapping JSON mapping configuration
|
21
|
+
*/
|
22
|
+
validateMapping(query, mapping) {
|
23
|
+
var _a, _b;
|
24
|
+
const collector = new SelectValueCollector();
|
25
|
+
const selectedValues = collector.collect(query);
|
26
|
+
// sv.name is the alias or derived name
|
27
|
+
const availableColumns = new Set(selectedValues.map(sv => sv.name));
|
28
|
+
// Check root entity columns
|
29
|
+
for (const jsonKey in mapping.rootEntity.columns) {
|
30
|
+
const sourceColumn = mapping.rootEntity.columns[jsonKey];
|
31
|
+
if (!availableColumns.has(sourceColumn)) {
|
32
|
+
throw new Error(`Validation Error: Column "${sourceColumn}" for JSON key "${jsonKey}" in root entity "${mapping.rootEntity.name}" not found in the query's select list.`);
|
33
|
+
}
|
34
|
+
}
|
35
|
+
// Check nested entity columns and parent-child relationships
|
36
|
+
const entityIds = new Set([mapping.rootEntity.id]);
|
37
|
+
const parentToChildrenMap = new Map();
|
38
|
+
mapping.nestedEntities.forEach(ne => {
|
39
|
+
entityIds.add(ne.id);
|
40
|
+
if (!parentToChildrenMap.has(ne.parentId)) {
|
41
|
+
parentToChildrenMap.set(ne.parentId, []);
|
42
|
+
}
|
43
|
+
parentToChildrenMap.get(ne.parentId).push(ne.id);
|
44
|
+
});
|
45
|
+
for (const entity of mapping.nestedEntities) {
|
46
|
+
if (!entityIds.has(entity.parentId)) {
|
47
|
+
throw new Error(`Validation Error: Parent entity with ID "${entity.parentId}" for nested entity "${entity.name}" (ID: ${entity.id}) not found.`);
|
48
|
+
}
|
49
|
+
for (const jsonKey in entity.columns) {
|
50
|
+
const sourceColumn = entity.columns[jsonKey];
|
51
|
+
if (!availableColumns.has(sourceColumn)) {
|
52
|
+
throw new Error(`Validation Error: Column "${sourceColumn}" for JSON key "${jsonKey}" in nested entity "${entity.name}" (ID: ${entity.id}) not found in the query's select list.`);
|
53
|
+
}
|
54
|
+
}
|
55
|
+
}
|
56
|
+
// Validate: An entity should not have multiple direct array children.
|
57
|
+
// Validate: Child propertyNames under a single parent must be unique.
|
58
|
+
const allParentIds = new Set([mapping.rootEntity.id, ...mapping.nestedEntities.map(ne => ne.parentId)]);
|
59
|
+
for (const parentId of allParentIds) {
|
60
|
+
const directChildren = mapping.nestedEntities.filter(ne => ne.parentId === parentId);
|
61
|
+
const directArrayChildrenCount = directChildren.filter(c => c.relationshipType === 'array').length;
|
62
|
+
if (directArrayChildrenCount > 1) {
|
63
|
+
const parentName = parentId === mapping.rootEntity.id ? mapping.rootEntity.name : (_a = mapping.nestedEntities.find(ne => ne.id === parentId)) === null || _a === void 0 ? void 0 : _a.name;
|
64
|
+
throw new Error(`Validation Error: Parent entity "${parentName}" (ID: ${parentId}) has multiple direct array children. This is not supported.`);
|
65
|
+
}
|
66
|
+
const propertyNames = new Set();
|
67
|
+
for (const child of directChildren) {
|
68
|
+
if (propertyNames.has(child.propertyName)) {
|
69
|
+
const parentName = parentId === mapping.rootEntity.id ? mapping.rootEntity.name : (_b = mapping.nestedEntities.find(ne => ne.id === parentId)) === null || _b === void 0 ? void 0 : _b.name;
|
70
|
+
throw new Error(`Validation Error: Parent entity "${parentName}" (ID: ${parentId}) has duplicate property name "${child.propertyName}" for its children.`);
|
71
|
+
}
|
72
|
+
propertyNames.add(child.propertyName);
|
73
|
+
}
|
74
|
+
}
|
75
|
+
}
|
76
|
+
/**
|
77
|
+
* Build JSON query from original query and mapping configuration.
|
78
|
+
* @param originalQuery Original query to transform
|
79
|
+
* @param mapping JSON mapping configuration
|
80
|
+
* @returns Transformed query with JSON aggregation
|
81
|
+
*/
|
82
|
+
buildJsonQuery(originalQuery, mapping) {
|
83
|
+
return this.buildJsonWithCteStrategy(originalQuery, mapping);
|
84
|
+
}
|
85
|
+
/**
|
86
|
+
* Build JSON query from original query and mapping configuration.
|
87
|
+
* @deprecated Use buildJsonQuery instead. This method will be removed in a future version.
|
88
|
+
* @param originalQuery Original query to transform
|
89
|
+
* @param mapping JSON mapping configuration
|
90
|
+
* @returns Transformed query with JSON aggregation
|
91
|
+
*/
|
92
|
+
buildJson(originalQuery, mapping) {
|
93
|
+
console.warn('buildJson is deprecated. Use buildJsonQuery instead.');
|
94
|
+
return this.buildJsonQuery(originalQuery, mapping);
|
95
|
+
}
|
96
|
+
/**
|
97
|
+
* Builds the JSON structure using a unified CTE-based strategy.
|
98
|
+
* @param originalQuery Original query
|
99
|
+
* @param mapping JSON mapping configuration
|
100
|
+
* @returns Query with CTE-based JSON aggregation
|
101
|
+
*/
|
102
|
+
buildJsonWithCteStrategy(originalQuery, mapping) {
|
103
|
+
this.validateMapping(originalQuery, mapping);
|
104
|
+
// Step 1: Create the initial CTE from the original query
|
105
|
+
const { initialCte, initialCteAlias } = this.createInitialCte(originalQuery);
|
106
|
+
let ctesForProcessing = [initialCte];
|
107
|
+
let currentAliasToBuildUpon = initialCteAlias;
|
108
|
+
// Step 2: Prepare entity information
|
109
|
+
const allEntities = new Map();
|
110
|
+
allEntities.set(mapping.rootEntity.id, Object.assign(Object.assign({}, mapping.rootEntity), { isRoot: true, propertyName: mapping.rootName }));
|
111
|
+
mapping.nestedEntities.forEach(ne => allEntities.set(ne.id, Object.assign(Object.assign({}, ne), { isRoot: false, propertyName: ne.propertyName }))); // Step 2.5: Build CTEs for object entities using dedicated builder
|
112
|
+
const objectEntityResult = this.objectEntityCteBuilder.buildObjectEntityCtes(initialCte, allEntities, mapping);
|
113
|
+
// Important: Replace the entire CTE list with the result from object entity builder
|
114
|
+
// The object entity builder returns all CTEs including the initial one
|
115
|
+
ctesForProcessing = objectEntityResult.ctes;
|
116
|
+
currentAliasToBuildUpon = objectEntityResult.lastCteAlias;
|
117
|
+
// Step 3: Build CTEs for array entities using dedicated builder
|
118
|
+
const arrayCteBuildResult = this.arrayEntityCteBuilder.buildArrayEntityCtes(ctesForProcessing, currentAliasToBuildUpon, allEntities, mapping);
|
119
|
+
ctesForProcessing = arrayCteBuildResult.updatedCtes;
|
120
|
+
currentAliasToBuildUpon = arrayCteBuildResult.lastCteAlias;
|
121
|
+
// Step 4: Build the final SELECT query using all generated CTEs
|
122
|
+
return this.buildFinalSelectQuery(ctesForProcessing, currentAliasToBuildUpon, allEntities, mapping);
|
123
|
+
}
|
124
|
+
/**
|
125
|
+
* Creates the initial Common Table Expression (CTE) from the original query.
|
126
|
+
* @param originalQuery The base SimpleSelectQuery.
|
127
|
+
* @returns An object containing the initial CTE and its alias.
|
128
|
+
*/
|
129
|
+
createInitialCte(originalQuery) {
|
130
|
+
const originCteAlias = "origin_query";
|
131
|
+
const originCte = new CommonTable(originalQuery, new SourceAliasExpression(originCteAlias, null), null);
|
132
|
+
return { initialCte: originCte, initialCteAlias: originCteAlias };
|
133
|
+
}
|
134
|
+
/**
|
135
|
+
* Builds the final SELECT query that constructs the root JSON object (or array of objects).
|
136
|
+
* This query uses all previously generated CTEs.
|
137
|
+
* @param finalCtesList The complete list of all CTEs (initial and array CTEs).
|
138
|
+
* @param lastCteAliasForFromClause Alias of the final CTE from which the root object will be built.
|
139
|
+
* @param allEntities Map of all processable entities.
|
140
|
+
* @param mapping JSON mapping configuration.
|
141
|
+
* @returns The final SimpleSelectQuery.
|
142
|
+
*/
|
143
|
+
buildFinalSelectQuery(finalCtesList, lastCteAliasForFromClause, allEntities, mapping) {
|
144
|
+
const currentCtes = [...finalCtesList];
|
145
|
+
// Define rootObjectCteAlias outside of if block
|
146
|
+
const rootObjectCteAlias = `cte_root_${mapping.rootName.toLowerCase().replace(/[^a-z0-9_]/g, '_')}`;
|
147
|
+
const rootEntity = allEntities.get(mapping.rootEntity.id);
|
148
|
+
if (!rootEntity) {
|
149
|
+
throw new Error(`Root entity ${mapping.rootEntity.id} not found`);
|
150
|
+
}
|
151
|
+
if (mapping.resultFormat === "array" || !mapping.resultFormat) {
|
152
|
+
// Step 4.1a: Create a CTE that wraps the final result as the root object
|
153
|
+
// No alias needed for single table SELECT
|
154
|
+
const rootObjectBuilderExpression = this.buildEntityJsonObject(rootEntity, null, // No source alias for single table
|
155
|
+
mapping.nestedEntities, allEntities, mapping.useJsonb);
|
156
|
+
const rootObjectSelectItem = new SelectItem(rootObjectBuilderExpression, mapping.rootName);
|
157
|
+
const rootObjectCte = new CommonTable(new SimpleSelectQuery({
|
158
|
+
selectClause: new SelectClause([rootObjectSelectItem]),
|
159
|
+
fromClause: new FromClause(new SourceExpression(new TableSource(null, new IdentifierString(lastCteAliasForFromClause)), null // No alias
|
160
|
+
), null),
|
161
|
+
}), new SourceAliasExpression(rootObjectCteAlias, null), null);
|
162
|
+
currentCtes.push(rootObjectCte);
|
163
|
+
// Step 4.1b: Aggregate all the root objects
|
164
|
+
const aggregationFunc = mapping.useJsonb ? "jsonb_agg" : "json_agg";
|
165
|
+
const aggregateExpression = new FunctionCall(null, new RawString(aggregationFunc), new ValueList([new ColumnReference(null, new IdentifierString(mapping.rootName))]), null);
|
166
|
+
return new SimpleSelectQuery({
|
167
|
+
withClause: new WithClause(false, currentCtes),
|
168
|
+
selectClause: new SelectClause([
|
169
|
+
new SelectItem(aggregateExpression, `${mapping.rootName}_array`)
|
170
|
+
]),
|
171
|
+
fromClause: new FromClause(new SourceExpression(new TableSource(null, new IdentifierString(rootObjectCteAlias)), null), null),
|
172
|
+
});
|
173
|
+
}
|
174
|
+
else {
|
175
|
+
// For a single object result, create root object CTE without alias
|
176
|
+
const rootObjectBuilderExpression = this.buildEntityJsonObject(rootEntity, null, // No source alias for single table
|
177
|
+
mapping.nestedEntities, allEntities, mapping.useJsonb);
|
178
|
+
const rootObjectSelectItem = new SelectItem(rootObjectBuilderExpression, mapping.rootName);
|
179
|
+
const rootObjectCte = new CommonTable(new SimpleSelectQuery({
|
180
|
+
selectClause: new SelectClause([rootObjectSelectItem]),
|
181
|
+
fromClause: new FromClause(new SourceExpression(new TableSource(null, new IdentifierString(lastCteAliasForFromClause)), null // No alias
|
182
|
+
), null),
|
183
|
+
}), new SourceAliasExpression(rootObjectCteAlias, null), null);
|
184
|
+
currentCtes.push(rootObjectCte);
|
185
|
+
// Select directly from the root_object_cte with LIMIT 1
|
186
|
+
return new SimpleSelectQuery({
|
187
|
+
withClause: new WithClause(false, currentCtes),
|
188
|
+
selectClause: new SelectClause([
|
189
|
+
new SelectItem(new ColumnReference(null, new IdentifierString(mapping.rootName)), mapping.rootName)
|
190
|
+
]),
|
191
|
+
fromClause: new FromClause(new SourceExpression(new TableSource(null, new IdentifierString(rootObjectCteAlias)), null), null),
|
192
|
+
limitClause: new LimitClause(new LiteralValue(1)) // Correctly use LimitClause
|
193
|
+
});
|
194
|
+
}
|
195
|
+
}
|
196
|
+
/**
|
197
|
+
* Build JSON object for entity, using parent JSON columns when available
|
198
|
+
*/
|
199
|
+
buildEntityJsonObject(entity, sourceAlias, nestedEntities, allEntities, useJsonb = false) {
|
200
|
+
const jsonBuildFunction = useJsonb ? "jsonb_build_object" : "json_build_object";
|
201
|
+
const args = []; // Add the entity's own columns
|
202
|
+
Object.entries(entity.columns).forEach(([jsonKey, sqlColumn]) => {
|
203
|
+
args.push(new LiteralValue(jsonKey));
|
204
|
+
args.push(new ColumnReference(null, new IdentifierString(sqlColumn)));
|
205
|
+
});
|
206
|
+
// Find and process child entities (both object and array types)
|
207
|
+
const childEntities = nestedEntities.filter((ne) => ne.parentId === entity.id);
|
208
|
+
childEntities.forEach((childEntity) => {
|
209
|
+
const child = allEntities.get(childEntity.id);
|
210
|
+
if (!child)
|
211
|
+
return;
|
212
|
+
args.push(new LiteralValue(childEntity.propertyName));
|
213
|
+
if (childEntity.relationshipType === "object") {
|
214
|
+
// For object relationships, use pre-computed JSON column
|
215
|
+
const jsonColumnName = `${child.name.toLowerCase()}_json`;
|
216
|
+
args.push(new ColumnReference(null, new IdentifierString(jsonColumnName)));
|
217
|
+
}
|
218
|
+
else if (childEntity.relationshipType === "array") {
|
219
|
+
// For array relationships, use the column directly
|
220
|
+
args.push(new ColumnReference(null, new IdentifierString(childEntity.propertyName)));
|
221
|
+
}
|
222
|
+
});
|
223
|
+
return new FunctionCall(null, new RawString(jsonBuildFunction), new ValueList(args), null);
|
224
|
+
}
|
225
|
+
}
|
226
|
+
//# sourceMappingURL=PostgresJsonQueryBuilder.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"PostgresJsonQueryBuilder.js","sourceRoot":"","sources":["../../../src/transformers/PostgresJsonQueryBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,qBAAqB,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,EAAE,gBAAgB,EAAE,WAAW,EAAiB,UAAU,EAAkB,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACnM,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAE,gBAAgB,EAAkB,eAAe,EAAE,YAAY,EAAE,SAAS,EAAE,YAAY,EAA0E,SAAS,EAAmB,MAAM,0BAA0B,CAAC;AACxO,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,8BAA8B,EAAqB,MAAM,kCAAkC,CAAC;AACrG,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AA0BhF;;;GAGG;AACH,MAAM,OAAO,wBAAwB;IAG6B;QAC1D,IAAI,CAAC,oBAAoB,GAAG,IAAI,oBAAoB,CAAC,IAAI,CAAC,CAAC;QAC3D,IAAI,CAAC,sBAAsB,GAAG,IAAI,8BAA8B,EAAE,CAAC;QACnE,IAAI,CAAC,qBAAq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W,CAAC,gBAAgB,KAAK,QAAQ,EAAE,CAAC;gBACnG,yDAAyD;gBACzD,MAAM,cAAc,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,WAAW,EAAE,OAAO,CAAC;gBAC1D,IAAI,CAAC,IAAI,CAAC,IAAI,eAAe,CAAC,IAAI,EAAE,IAAI,gBAAgB,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;YAC/E,CAAC;iBAAM,IAAI,WAAW,CAAC,gBAAgB,KAAK,OAAO,EAAE,CAAC;gBAClD,mDAAmD;gBACnD,IAAI,CAAC,IAAI,CAAC,IAAI,eAAe,CAAC,IAAI,EAAE,IAAI,gBAAgB,CAAC,WAAW,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;YACzF,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI,YAAY,CAAC,IAAI,EAAE,IAAI,SAAS,CAAC,iBAAiB,CAAC,EAAE,IAAI,SAAS,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;IAC/F,CAAC;CACJ"}
|
@@ -0,0 +1,283 @@
|
|
1
|
+
import { CommonTable, SourceAliasExpression, SelectItem, SelectClause, FromClause, SourceExpression, TableSource } from '../models/Clause';
|
2
|
+
import { SimpleSelectQuery } from '../models/SimpleSelectQuery';
|
3
|
+
import { IdentifierString, ColumnReference, FunctionCall, ValueList, LiteralValue, BinaryExpression, CaseExpression, SwitchCaseArgument, CaseKeyValuePair, RawString } from '../models/ValueComponent';
|
4
|
+
/**
|
5
|
+
* PostgreSQL-specific builder for creating CTEs for object entities (object relationships).
|
6
|
+
* This class handles the creation of CTEs that build JSON/JSONB objects for object entities,
|
7
|
+
* processing them from the deepest level up to ensure proper dependency ordering.
|
8
|
+
*
|
9
|
+
* Features:
|
10
|
+
* - Depth-based CTE naming (cte_object_depth_N)
|
11
|
+
* - NULL handling for entity columns
|
12
|
+
* - JSONB/JSON object construction
|
13
|
+
* - Hierarchical processing of nested objects
|
14
|
+
*
|
15
|
+
* Why depth calculation is critical:
|
16
|
+
* 1. Object entities can be nested at multiple levels. We must process the deepest
|
17
|
+
* (most distant) objects first to ensure their JSON representations are available
|
18
|
+
* when building their parent entities.
|
19
|
+
* 2. Object entity processing is essentially a column compression operation. Entities
|
20
|
+
* at the same depth level can be processed simultaneously since they don't depend
|
21
|
+
* on each other.
|
22
|
+
*
|
23
|
+
* Example hierarchy:
|
24
|
+
* Order (root, depth 0)
|
25
|
+
* └─ Customer (depth 1)
|
26
|
+
* └─ Address (depth 2)
|
27
|
+
* └─ Shipping (depth 1)
|
28
|
+
* └─ Carrier (depth 2)
|
29
|
+
*
|
30
|
+
* Processing order: depth 2 → depth 1 → depth 0
|
31
|
+
*/
|
32
|
+
export class PostgresObjectEntityCteBuilder {
|
33
|
+
buildObjectEntityCtes(initialCte, allEntities, mapping) {
|
34
|
+
const ctes = [initialCte];
|
35
|
+
let previousCteAlias = initialCte.aliasExpression.table.name; // Collect and sort object entities by depth
|
36
|
+
const objectEntityInfos = this.collectAndSortObjectEntities(mapping, allEntities);
|
37
|
+
// Group entities by depth
|
38
|
+
const entitiesByDepth = this.groupEntitiesByDepth(objectEntityInfos);
|
39
|
+
// Process each depth level, starting from the deepest
|
40
|
+
const depths = Array.from(entitiesByDepth.keys()).sort((a, b) => b - a);
|
41
|
+
for (const depth of depths) {
|
42
|
+
const entitiesAtDepth = entitiesByDepth.get(depth);
|
43
|
+
const cteAlias = `${PostgresObjectEntityCteBuilder.CTE_OBJECT_PREFIX}${depth}`;
|
44
|
+
// Build CTE for all entities at this depth
|
45
|
+
const cte = this.buildDepthCte(entitiesAtDepth, previousCteAlias, cteAlias, mapping, allEntities);
|
46
|
+
ctes.push(cte);
|
47
|
+
previousCteAlias = cteAlias;
|
48
|
+
}
|
49
|
+
return { ctes, lastCteAlias: previousCteAlias };
|
50
|
+
} /**
|
51
|
+
* Collect all object entities and calculate their depth from root.
|
52
|
+
*
|
53
|
+
* Depth calculation is crucial because:
|
54
|
+
* - It determines the processing order (deepest first)
|
55
|
+
* - It ensures dependencies are resolved before an entity is processed
|
56
|
+
* - It allows parallel processing of entities at the same depth level
|
57
|
+
*
|
58
|
+
* @param mapping The JSON mapping configuration
|
59
|
+
* @param allEntities Map of all entities in the mapping
|
60
|
+
* @returns Array of object entity information with calculated depths
|
61
|
+
*/
|
62
|
+
collectAndSortObjectEntities(mapping, allEntities) {
|
63
|
+
const objectInfos = [];
|
64
|
+
// Helper function to calculate actual object nesting depth for a given OBJECT entity
|
65
|
+
const calculateActualObjectNestingDepth = (entityIdOfObject) => {
|
66
|
+
const initialEntity = allEntities.get(entityIdOfObject);
|
67
|
+
if (!initialEntity) {
|
68
|
+
throw new Error(`Entity ${entityIdOfObject} not found for depth calculation.`);
|
69
|
+
}
|
70
|
+
// If the object itself is root, its depth is 0. (This function should ideally be called for nested entities, not the root itself as a "parent CTE" subject)
|
71
|
+
if (initialEntity.isRoot)
|
72
|
+
return 0;
|
73
|
+
// If the object is not root and has no parentId, it's considered a top-level object, depth 1.
|
74
|
+
if (!initialEntity.parentId) {
|
75
|
+
return 1;
|
76
|
+
}
|
77
|
+
let currentParentIdInHierarchy = initialEntity.parentId;
|
78
|
+
let calculatedObjectDepth = 0;
|
79
|
+
const visitedInPath = new Set();
|
80
|
+
visitedInPath.add(entityIdOfObject); // Add the starting object itself to detect cycles
|
81
|
+
while (currentParentIdInHierarchy) {
|
82
|
+
if (visitedInPath.has(currentParentIdInHierarchy)) {
|
83
|
+
throw new Error(`Circular dependency detected: ${currentParentIdInHierarchy} already visited in path for ${entityIdOfObject}`);
|
84
|
+
}
|
85
|
+
visitedInPath.add(currentParentIdInHierarchy);
|
86
|
+
const parentEntityData = allEntities.get(currentParentIdInHierarchy);
|
87
|
+
if (!parentEntityData) {
|
88
|
+
throw new Error(`Parent entity ${currentParentIdInHierarchy} not found during depth calculation for ${entityIdOfObject}`);
|
89
|
+
}
|
90
|
+
let parentIsConsideredAnObjectForNesting = false;
|
91
|
+
if (parentEntityData.isRoot) {
|
92
|
+
parentIsConsideredAnObjectForNesting = true; // Root counts as an object ancestor
|
93
|
+
}
|
94
|
+
else {
|
95
|
+
// For non-root parents, find their definition in nestedEntities to check their type
|
96
|
+
const parentDefinition = mapping.nestedEntities.find(ne => ne.id === currentParentIdInHierarchy);
|
97
|
+
if (parentDefinition) {
|
98
|
+
if (parentDefinition.relationshipType === "object") {
|
99
|
+
parentIsConsideredAnObjectForNesting = true;
|
100
|
+
}
|
101
|
+
// If parentDefinition.relationshipType === "array", it's not an object ancestor for depth counting
|
102
|
+
}
|
103
|
+
else {
|
104
|
+
// This implies currentParentIdInHierarchy refers to an entity not defined as root or in nestedEntities
|
105
|
+
// This should ideally not happen with a consistent mapping.
|
106
|
+
throw new Error(`Parent entity ${currentParentIdInHierarchy} (ancestor of ${entityIdOfObject}) has no definition in mapping.nestedEntities and is not root.`);
|
107
|
+
}
|
108
|
+
}
|
109
|
+
if (parentIsConsideredAnObjectForNesting) {
|
110
|
+
calculatedObjectDepth++;
|
111
|
+
}
|
112
|
+
if (parentEntityData.isRoot) {
|
113
|
+
break; // Stop when the root is processed as the highest object ancestor
|
114
|
+
}
|
115
|
+
currentParentIdInHierarchy = parentEntityData.parentId; // Move to the next ancestor
|
116
|
+
}
|
117
|
+
return calculatedObjectDepth;
|
118
|
+
};
|
119
|
+
mapping.nestedEntities.forEach(nestedEntity => {
|
120
|
+
if (nestedEntity.relationshipType === "object") {
|
121
|
+
const entity = allEntities.get(nestedEntity.id);
|
122
|
+
// Ensure we don't process the root entity itself as a "parent" CTE,
|
123
|
+
// and that the entity actually exists.
|
124
|
+
if (entity && !entity.isRoot) {
|
125
|
+
objectInfos.push({
|
126
|
+
entity,
|
127
|
+
depth: calculateActualObjectNestingDepth(nestedEntity.id)
|
128
|
+
});
|
129
|
+
}
|
130
|
+
}
|
131
|
+
});
|
132
|
+
// The existing grouping and sorting by depth (b - a for descending) should still work correctly
|
133
|
+
// as it processes deepest levels first, regardless of the absolute depth numbers.
|
134
|
+
return objectInfos;
|
135
|
+
}
|
136
|
+
/**
|
137
|
+
* Group entities by their depth level.
|
138
|
+
*
|
139
|
+
* Grouping by depth allows us to:
|
140
|
+
* - Process all entities at the same level in a single CTE
|
141
|
+
* - Optimize query performance by reducing the number of CTEs
|
142
|
+
* - Maintain clear dependency ordering
|
143
|
+
*
|
144
|
+
* @param parentInfos Array of parent entity information with depths
|
145
|
+
* @returns Map of depth level to entities at that depth
|
146
|
+
*/ groupEntitiesByDepth(objectInfos) {
|
147
|
+
const entitiesByDepth = new Map();
|
148
|
+
objectInfos.forEach(info => {
|
149
|
+
const depth = info.depth;
|
150
|
+
if (!entitiesByDepth.has(depth)) {
|
151
|
+
entitiesByDepth.set(depth, []);
|
152
|
+
}
|
153
|
+
entitiesByDepth.get(depth).push(info);
|
154
|
+
});
|
155
|
+
return entitiesByDepth;
|
156
|
+
}
|
157
|
+
/**
|
158
|
+
* Build a CTE that processes all entities at a specific depth level
|
159
|
+
*/
|
160
|
+
buildDepthCte(entitiesAtDepth, previousCteAlias, cteAlias, mapping, allEntities) {
|
161
|
+
// Build SELECT items: * and JSON objects for all entities at this depth
|
162
|
+
const selectItems = [
|
163
|
+
// Select all columns from previous CTE
|
164
|
+
new SelectItem(new ColumnReference(null, new IdentifierString(PostgresObjectEntityCteBuilder.WILDCARD_COLUMN)))
|
165
|
+
];
|
166
|
+
// Process each entity at this depth
|
167
|
+
for (const { entity } of entitiesAtDepth) {
|
168
|
+
const jsonColumn = this.buildEntityJsonColumn(entity, mapping, allEntities);
|
169
|
+
selectItems.push(jsonColumn);
|
170
|
+
}
|
171
|
+
// Create CTE that selects from previous CTE
|
172
|
+
const cteSelect = new SimpleSelectQuery({
|
173
|
+
selectClause: new SelectClause(selectItems),
|
174
|
+
fromClause: new FromClause(new SourceExpression(new TableSource(null, new IdentifierString(previousCteAlias)), null), null)
|
175
|
+
});
|
176
|
+
return new CommonTable(cteSelect, new SourceAliasExpression(cteAlias, null), null);
|
177
|
+
}
|
178
|
+
/**
|
179
|
+
* Build JSON column for a single entity with NULL handling
|
180
|
+
*/
|
181
|
+
buildEntityJsonColumn(entity, mapping, allEntities) {
|
182
|
+
// Build JSON object arguments and NULL checks
|
183
|
+
const { jsonObjectArgs, nullChecks } = this.prepareEntityColumns(entity);
|
184
|
+
// Add child object relationships
|
185
|
+
this.addChildObjectRelationships(entity, jsonObjectArgs, mapping, allEntities);
|
186
|
+
// Create JSON object
|
187
|
+
const jsonObject = this.createJsonObject(jsonObjectArgs, mapping.useJsonb);
|
188
|
+
// Build NULL condition and CASE expression
|
189
|
+
const nullCondition = this.buildNullCondition(nullChecks);
|
190
|
+
const caseExpr = this.createCaseExpression(nullCondition, jsonObject);
|
191
|
+
// Add JSON object as named column
|
192
|
+
const jsonColumnName = `${entity.name.toLowerCase()}${PostgresObjectEntityCteBuilder.JSON_COLUMN_SUFFIX}`;
|
193
|
+
return new SelectItem(caseExpr, jsonColumnName);
|
194
|
+
}
|
195
|
+
/**
|
196
|
+
* Prepare entity columns and NULL checks.
|
197
|
+
*
|
198
|
+
* This method extracts column data and creates NULL checks for each column.
|
199
|
+
* The NULL checking is essential for handling outer joins correctly.
|
200
|
+
*
|
201
|
+
* In outer join scenarios, when there's no matching row in the joined table,
|
202
|
+
* all columns from that table will be NULL. Instead of creating an empty object
|
203
|
+
* with all NULL properties (e.g., {id: null, name: null, email: null}),
|
204
|
+
* we want to represent the absence of the entity as NULL itself.
|
205
|
+
*
|
206
|
+
* This ensures cleaner JSON output where missing relationships are represented
|
207
|
+
* as NULL rather than objects with all NULL fields.
|
208
|
+
*
|
209
|
+
* @param entity The entity whose columns are being processed
|
210
|
+
* @returns Object containing arrays of JSON object arguments and NULL check conditions
|
211
|
+
*/
|
212
|
+
prepareEntityColumns(entity) {
|
213
|
+
const jsonObjectArgs = [];
|
214
|
+
const nullChecks = [];
|
215
|
+
Object.entries(entity.columns).forEach(([jsonKey, sqlColumn]) => {
|
216
|
+
jsonObjectArgs.push(new LiteralValue(jsonKey));
|
217
|
+
jsonObjectArgs.push(new ColumnReference(null, new IdentifierString(sqlColumn)));
|
218
|
+
// Collect NULL checks for each column
|
219
|
+
nullChecks.push(new BinaryExpression(new ColumnReference(null, new IdentifierString(sqlColumn)), "is", new LiteralValue(null)));
|
220
|
+
});
|
221
|
+
return { jsonObjectArgs, nullChecks };
|
222
|
+
}
|
223
|
+
/**
|
224
|
+
* Add child object relationships to JSON object arguments.
|
225
|
+
*
|
226
|
+
* This method processes nested object-type entities that are direct children of the current entity.
|
227
|
+
* For each child entity, it adds the property name and corresponding JSON column reference
|
228
|
+
* to the arguments array that will be used to build the parent's JSON object.
|
229
|
+
*
|
230
|
+
* The child JSON columns are expected to already exist in the data source (created by deeper
|
231
|
+
* level CTEs), as we process from the deepest level up to the root.
|
232
|
+
*
|
233
|
+
* Note: In this context, "child" refers to entities that have an object relationship (0..1)
|
234
|
+
* with their parent. From a data perspective, these are typically entities referenced via
|
235
|
+
* foreign keys, representing "parent" entities in traditional database terminology.
|
236
|
+
*
|
237
|
+
* @param entity The current entity being processed
|
238
|
+
* @param jsonObjectArgs Array to which JSON object arguments will be added
|
239
|
+
* @param mapping The JSON mapping configuration
|
240
|
+
* @param allEntities Map of all entities in the mapping
|
241
|
+
*/
|
242
|
+
addChildObjectRelationships(entity, jsonObjectArgs, mapping, allEntities) {
|
243
|
+
const childEntities = mapping.nestedEntities.filter(ne => ne.parentId === entity.id && ne.relationshipType === "object");
|
244
|
+
childEntities.forEach(childEntity => {
|
245
|
+
const child = allEntities.get(childEntity.id);
|
246
|
+
if (child) {
|
247
|
+
jsonObjectArgs.push(new LiteralValue(childEntity.propertyName));
|
248
|
+
const jsonColumnName = `${child.name.toLowerCase()}${PostgresObjectEntityCteBuilder.JSON_COLUMN_SUFFIX}`;
|
249
|
+
jsonObjectArgs.push(new ColumnReference(null, new IdentifierString(jsonColumnName)));
|
250
|
+
}
|
251
|
+
});
|
252
|
+
}
|
253
|
+
/**
|
254
|
+
* Create JSON object function call
|
255
|
+
*/
|
256
|
+
createJsonObject(args, useJsonb = false) {
|
257
|
+
const jsonBuildFunction = useJsonb ? "jsonb_build_object" : "json_build_object";
|
258
|
+
return new FunctionCall(null, new RawString(jsonBuildFunction), new ValueList(args), null);
|
259
|
+
}
|
260
|
+
/**
|
261
|
+
* Build NULL condition from NULL checks
|
262
|
+
*/
|
263
|
+
buildNullCondition(nullChecks) {
|
264
|
+
return nullChecks.reduce((acc, check) => acc ? new BinaryExpression(acc, "and", check) : check);
|
265
|
+
}
|
266
|
+
/**
|
267
|
+
* Create CASE expression with NULL handling
|
268
|
+
*/
|
269
|
+
createCaseExpression(nullCondition, jsonObject) {
|
270
|
+
return new CaseExpression(null, new SwitchCaseArgument([new CaseKeyValuePair(nullCondition, new LiteralValue(null))], jsonObject // ELSE return the JSON object
|
271
|
+
));
|
272
|
+
}
|
273
|
+
}
|
274
|
+
PostgresObjectEntityCteBuilder.JSON_COLUMN_SUFFIX = '_json';
|
275
|
+
PostgresObjectEntityCteBuilder.CTE_OBJECT_PREFIX = 'cte_object_depth_';
|
276
|
+
PostgresObjectEntityCteBuilder.WILDCARD_COLUMN = '*'; /**
|
277
|
+
* Build CTEs for all object entities in the correct dependency order
|
278
|
+
* @param initialCte The starting CTE containing all raw data
|
279
|
+
* @param allEntities Map of all entities in the mapping
|
280
|
+
* @param mapping The JSON mapping configuration
|
281
|
+
* @returns Array of CTEs and the alias of the last CTE created
|
282
|
+
*/
|
283
|
+
//# sourceMappingURL=PostgresObjectEntityCteBuilder.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"PostgresObjectEntityCteBuilder.js","sourceRoot":"","sources":["../../../src/transformers/PostgresObjectEntityCteBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,qBAAqB,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC3I,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B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uerySource,
|
35
|
-
SqlPrintTokenContainerType.BinarySelectQueryOperator,
|
36
|
-
SqlPrintTokenContainerType.
|
37
|
-
SqlPrintTokenContainerType.
|
35
|
+
SqlPrintTokenContainerType.BinarySelectQueryOperator, SqlPrintTokenContainerType.Values,
|
36
|
+
SqlPrintTokenContainerType.WithClause,
|
37
|
+
SqlPrintTokenContainerType.SwitchCaseArgument,
|
38
|
+
SqlPrintTokenContainerType.CaseKeyValuePair,
|
39
|
+
SqlPrintTokenContainerType.CaseThenValue,
|
40
|
+
SqlPrintTokenContainerType.ElseClause,
|
41
|
+
SqlPrintTokenContainerType.CaseElseValue
|
42
|
+
// CaseExpression, SwitchCaseArgument, CaseKeyValuePair, and ElseClause
|
43
|
+
// are not included by default to maintain backward compatibility with tests
|
38
44
|
//SqlPrintTokenContainerType.CommonTable
|
39
45
|
]);
|
40
46
|
}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"SqlPrinter.js","sourceRoot":"","sources":["../../../src/transformers/SqlPrinter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,iBAAiB,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AACvG,OAAO,EAAoB,WAAW,EAAiB,MAAM,eAAe,CAAC;AAkB7E;;GAEG;AACH,MAAM,OAAO,UAAU;IAkBnB;;OAEG;IACH,YAAY,OAQX;;QACG,IAAI,CAAC,UAAU,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,mCAAI,EAAE,CAAC;QAC5C,IAAI,CAAC,UAAU,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,mCAAI,CAAC,CAAC;QAE3C,8FAA8F;QAC9F,0EAA0E;QAC1E,IAAI,CAAC,OAAO,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,OAAO,mCAAI,GAAG,CAAC;QAEvC,IAAI,CAAC,UAAU,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,O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E,CAAC,EAAE,EAAE,CAAC;gBAClD,MAAM,YAAY,GAAG,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;gBAC5C,IAAI,CAAC,WAAW,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;YAC1C,CAAC;QACL,CAAC;QAED,IAAI,UAAU,GAAG,KAAK,CAAC;QAEvB,kBAAkB;QAClB,IAAI,IAAI,CAAC,OAAO,KAAK,GAAG,IAAI,OAAO,CAAC,IAAI,KAAK,EAAE,IAAI,IAAI,CAAC,yBAAyB,CAAC,GAAG,CAAC,KAAK,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC,oBAAoB;YAC9H,UAAU,EAAE,CAAC;YACb,IAAI,CAAC,WAAW,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC;QAC/C,CAAC;QAED,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAChD,MAAM,KAAK,GAAG,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;YACnC,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;QACxC,CAAC;QAED,oBAAoB;QACpB,IAAI,UAAU,KAAK,KAAK,EAAE,CAAC;YACvB,IAAI,CAAC,WAAW,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;QAC1C,CAAC;IACL,CAAC;CACJ"}
|
@@ -8,6 +8,7 @@ export * from './transformers/CTECollector';
|
|
8
8
|
export * from './transformers/CTENormalizer';
|
9
9
|
export * from './transformers/Formatter';
|
10
10
|
export * from './transformers/SqlFormatter';
|
11
|
+
export * from './transformers/PostgresJsonQueryBuilder';
|
11
12
|
export * from './transformers/QueryBuilder';
|
12
13
|
export * from './transformers/SelectValueCollector';
|
13
14
|
export * from './transformers/SelectableColumnCollector';
|
@@ -17,3 +18,4 @@ export * from './transformers/UpstreamSelectQueryFinder';
|
|
17
18
|
export * from './transformers/SchemaCollector';
|
18
19
|
export * from './transformers/SqlParamInjector';
|
19
20
|
export * from './utils/SqlSchemaValidator';
|
21
|
+
export * from './utils/SchemaManager';
|
@@ -27,6 +27,8 @@ export declare enum SqlPrintTokenContainerType {
|
|
27
27
|
SwitchCaseArgument = "SwitchCaseArgument",
|
28
28
|
ElseClause = "ElseClause",
|
29
29
|
CaseKeyValuePair = "CaseKeyValuePair",
|
30
|
+
CaseThenValue = "CaseThenValue",
|
31
|
+
CaseElseValue = "CaseElseValue",
|
30
32
|
ParenExpression = "ParenExpression",
|
31
33
|
CastExpression = "CastExpression",
|
32
34
|
CaseExpression = "CaseExpression",
|
@@ -32,7 +32,7 @@ export declare class FunctionCall extends SqlComponent {
|
|
32
32
|
qualifiedName: QualifiedName;
|
33
33
|
argument: ValueComponent | null;
|
34
34
|
over: OverExpression | null;
|
35
|
-
constructor(namespaces: string[] | IdentifierString[] | null, name: string | RawString | IdentifierString, argument: ValueComponent | null, over: OverExpression | null);
|
35
|
+
constructor(namespaces: string | string[] | IdentifierString[] | null, name: string | RawString | IdentifierString, argument: ValueComponent | null, over: OverExpression | null);
|
36
36
|
/**
|
37
37
|
* For backward compatibility: returns the namespaces as IdentifierString[] | null (readonly)
|
38
38
|
*/
|
@@ -195,7 +195,7 @@ export declare class QualifiedName extends SqlComponent {
|
|
195
195
|
namespaces: IdentifierString[] | null;
|
196
196
|
/** The actual name (e.g. table, function, type, column) */
|
197
197
|
name: RawString | IdentifierString;
|
198
|
-
constructor(namespaces: string[] | IdentifierString[] | null, name: string | RawString | IdentifierString);
|
198
|
+
constructor(namespaces: string | string[] | IdentifierString[] | null, name: string | RawString | IdentifierString);
|
199
199
|
/** Returns the full qualified name as a string (dot-separated) */
|
200
200
|
toString(): string;
|
201
201
|
}
|