rawsql-ts 0.11.18-beta → 0.11.20-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 (34) hide show
  1. package/README.md +62 -0
  2. package/dist/esm/index.js +3 -0
  3. package/dist/esm/index.js.map +1 -1
  4. package/dist/esm/index.min.js +25 -25
  5. package/dist/esm/index.min.js.map +4 -4
  6. package/dist/esm/src/index.d.ts +3 -0
  7. package/dist/esm/src/index.js +3 -0
  8. package/dist/esm/src/index.js.map +1 -1
  9. package/dist/esm/src/transformers/CTERenamer.d.ts +144 -0
  10. package/dist/esm/src/transformers/CTERenamer.js +342 -0
  11. package/dist/esm/src/transformers/CTERenamer.js.map +1 -0
  12. package/dist/esm/src/transformers/ColumnReferenceCollector.d.ts +162 -0
  13. package/dist/esm/src/transformers/ColumnReferenceCollector.js +464 -0
  14. package/dist/esm/src/transformers/ColumnReferenceCollector.js.map +1 -0
  15. package/dist/esm/src/transformers/SelectableColumnCollector.d.ts +94 -9
  16. package/dist/esm/src/transformers/SelectableColumnCollector.js +227 -40
  17. package/dist/esm/src/transformers/SelectableColumnCollector.js.map +1 -1
  18. package/dist/esm/tsconfig.browser.tsbuildinfo +1 -1
  19. package/dist/index.min.js +25 -25
  20. package/dist/index.min.js.map +4 -4
  21. package/dist/src/index.d.ts +3 -0
  22. package/dist/src/index.js +5 -1
  23. package/dist/src/index.js.map +1 -1
  24. package/dist/src/transformers/CTERenamer.d.ts +144 -0
  25. package/dist/src/transformers/CTERenamer.js +346 -0
  26. package/dist/src/transformers/CTERenamer.js.map +1 -0
  27. package/dist/src/transformers/ColumnReferenceCollector.d.ts +162 -0
  28. package/dist/src/transformers/ColumnReferenceCollector.js +468 -0
  29. package/dist/src/transformers/ColumnReferenceCollector.js.map +1 -0
  30. package/dist/src/transformers/SelectableColumnCollector.d.ts +94 -9
  31. package/dist/src/transformers/SelectableColumnCollector.js +225 -38
  32. package/dist/src/transformers/SelectableColumnCollector.js.map +1 -1
  33. package/dist/tsconfig.tsbuildinfo +1 -1
  34. package/package.json +1 -1
@@ -12,12 +12,15 @@ export * from './transformers/CTEDisabler';
12
12
  export * from './transformers/CTEDependencyAnalyzer';
13
13
  export * from './transformers/CTEQueryDecomposer';
14
14
  export * from './transformers/CTEComposer';
15
+ export * from './transformers/CTERenamer';
16
+ export * from './transformers/ColumnReferenceCollector';
15
17
  export * from './transformers/Formatter';
16
18
  export * from './transformers/SqlFormatter';
17
19
  export * from './transformers/PostgresJsonQueryBuilder';
18
20
  export * from './transformers/QueryBuilder';
19
21
  export * from './transformers/SelectValueCollector';
20
22
  export * from './transformers/SelectableColumnCollector';
23
+ export { DuplicateDetectionMode } from './transformers/SelectableColumnCollector';
21
24
  export * from './transformers/TableColumnResolver';
22
25
  export * from './transformers/TableSourceCollector';
23
26
  export * from './transformers/JsonMappingConverter';
@@ -13,12 +13,15 @@ export * from './transformers/CTEDisabler';
13
13
  export * from './transformers/CTEDependencyAnalyzer';
14
14
  export * from './transformers/CTEQueryDecomposer';
15
15
  export * from './transformers/CTEComposer';
16
+ export * from './transformers/CTERenamer';
17
+ export * from './transformers/ColumnReferenceCollector';
16
18
  export * from './transformers/Formatter';
17
19
  export * from './transformers/SqlFormatter';
18
20
  export * from './transformers/PostgresJsonQueryBuilder';
19
21
  export * from './transformers/QueryBuilder'; // old name:QueryConverter
20
22
  export * from './transformers/SelectValueCollector';
21
23
  export * from './transformers/SelectableColumnCollector';
24
+ export { DuplicateDetectionMode } from './transformers/SelectableColumnCollector';
22
25
  export * from './transformers/TableColumnResolver';
23
26
  export * from './transformers/TableSourceCollector';
24
27
  export * from './transformers/JsonMappingConverter';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA,oCAAoC;AACpC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,6BAA6B,CAAC;AAE5C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,sBAAsB,CAAC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AAC;AAEnD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,uBAAuB,CAAC;AACtC,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AAGrC,oEAAoE"}
@@ -0,0 +1,144 @@
1
+ import { SelectQuery } from "../models/SelectQuery";
2
+ /**
3
+ * A utility class for renaming Common Table Expressions (CTEs) in SQL queries.
4
+ *
5
+ * This class provides functionality to safely rename CTEs while automatically updating
6
+ * all column references and table references throughout the query, including within
7
+ * nested CTE definitions and subqueries.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { CTERenamer, SelectQueryParser } from 'rawsql-ts';
12
+ *
13
+ * const sql = `
14
+ * WITH user_data AS (
15
+ * SELECT id, name FROM users
16
+ * ),
17
+ * order_summary AS (
18
+ * SELECT user_data.id, COUNT(*) as order_count
19
+ * FROM user_data
20
+ * JOIN orders ON user_data.id = orders.user_id
21
+ * GROUP BY user_data.id
22
+ * )
23
+ * SELECT * FROM order_summary
24
+ * `;
25
+ *
26
+ * const query = SelectQueryParser.parse(sql);
27
+ * const renamer = new CTERenamer();
28
+ *
29
+ * // Rename 'user_data' to 'customer_data'
30
+ * renamer.renameCTE(query, 'user_data', 'customer_data');
31
+ *
32
+ * // All references are automatically updated:
33
+ * // - CTE definition: WITH customer_data AS (...)
34
+ * // - Column references: customer_data.id
35
+ * // - Table references: FROM customer_data
36
+ * ```
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * // Error handling
41
+ * try {
42
+ * renamer.renameCTE(query, 'nonexistent_cte', 'new_name');
43
+ * } catch (error) {
44
+ * console.error(error.message); // "CTE 'nonexistent_cte' does not exist"
45
+ * }
46
+ *
47
+ * try {
48
+ * renamer.renameCTE(query, 'existing_cte', 'already_exists');
49
+ * } catch (error) {
50
+ * console.error(error.message); // "CTE 'already_exists' already exists"
51
+ * }
52
+ * ```
53
+ *
54
+ * @since 0.11.16
55
+ */
56
+ export declare class CTERenamer {
57
+ private dependencyAnalyzer;
58
+ private columnReferenceCollector;
59
+ private tableSourceCollector;
60
+ /**
61
+ * Creates a new instance of CTERenamer.
62
+ *
63
+ * The constructor initializes internal collectors and analyzers needed for
64
+ * comprehensive CTE renaming operations.
65
+ */
66
+ constructor();
67
+ /**
68
+ * Renames a Common Table Expression (CTE) and updates all references to it.
69
+ *
70
+ * This method performs a comprehensive rename operation that includes:
71
+ * - Updating the CTE definition name in the WITH clause
72
+ * - Updating all column references (e.g., `old_name.column` → `new_name.column`)
73
+ * - Updating all table references in FROM and JOIN clauses
74
+ * - Processing references within nested CTEs and subqueries
75
+ *
76
+ * @param query - The SQL query containing the CTE to rename. Can be either SimpleSelectQuery or BinarySelectQuery (UNION/INTERSECT/EXCEPT).
77
+ * @param oldName - The current name of the CTE to rename.
78
+ * @param newName - The new name for the CTE.
79
+ *
80
+ * @throws {Error} When the specified CTE does not exist in the query.
81
+ * @throws {Error} When a CTE with the new name already exists.
82
+ * @throws {Error} When the query type is not supported (not a SelectQuery).
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * const renamer = new CTERenamer();
87
+ *
88
+ * // Basic usage
89
+ * renamer.renameCTE(query, 'old_cte_name', 'new_cte_name');
90
+ *
91
+ * // With error handling
92
+ * try {
93
+ * renamer.renameCTE(query, 'user_data', 'customer_data');
94
+ * } catch (error) {
95
+ * if (error.message.includes('does not exist')) {
96
+ * console.log('CTE not found');
97
+ * } else if (error.message.includes('already exists')) {
98
+ * console.log('Name conflict');
99
+ * }
100
+ * }
101
+ * ```
102
+ *
103
+ * @since 0.11.16
104
+ */
105
+ renameCTE(query: SelectQuery, oldName: string, newName: string): void;
106
+ /**
107
+ * Validates input parameters for CTE renaming.
108
+ */
109
+ private validateInputs;
110
+ /**
111
+ * Handles CTE renaming for SimpleSelectQuery.
112
+ */
113
+ private renameInSimpleQuery;
114
+ /**
115
+ * Handles CTE renaming for BinarySelectQuery.
116
+ */
117
+ private renameInBinaryQuery;
118
+ /**
119
+ * Recursively handles CTE renaming for any SelectQuery type.
120
+ */
121
+ private renameInSelectQuery;
122
+ /**
123
+ * Renames the CTE definition in the WITH clause.
124
+ */
125
+ private renameCTEDefinition;
126
+ /**
127
+ * Updates all references to the old CTE name (column references and table sources).
128
+ */
129
+ private updateAllReferences;
130
+ /**
131
+ * Updates table sources within CTE definitions that reference the old CTE name.
132
+ * This method manually traverses CTE internals to avoid infinite recursion
133
+ * that occurs when using TableSourceCollector with selectableOnly=false.
134
+ */
135
+ private updateTableSourcesInCTEs;
136
+ /**
137
+ * Updates table sources in a specific query (used for CTE internals).
138
+ */
139
+ private updateTableSourcesInQuery;
140
+ /**
141
+ * Updates a specific table source if it matches the old CTE name.
142
+ */
143
+ private updateTableSource;
144
+ }
@@ -0,0 +1,342 @@
1
+ import { SimpleSelectQuery } from "../models/SimpleSelectQuery";
2
+ import { BinarySelectQuery } from "../models/BinarySelectQuery";
3
+ import { CTEDependencyAnalyzer } from "./CTEDependencyAnalyzer";
4
+ import { TableSourceCollector } from "./TableSourceCollector";
5
+ import { ColumnReferenceCollector } from "./ColumnReferenceCollector";
6
+ import { ColumnReference } from "../models/ValueComponent";
7
+ /**
8
+ * Error messages for CTE renaming operations.
9
+ */
10
+ const ERROR_MESSAGES = {
11
+ nullQuery: 'Query cannot be null or undefined',
12
+ invalidOldName: 'Old CTE name must be a non-empty string',
13
+ invalidNewName: 'New CTE name must be a non-empty string',
14
+ sameNames: 'Old and new CTE names cannot be the same',
15
+ unsupportedQuery: 'Unsupported query type for CTE renaming',
16
+ cteNotExists: (name) => `CTE '${name}' does not exist`,
17
+ cteAlreadyExists: (name) => `CTE '${name}' already exists`,
18
+ cteNotFound: (name) => `CTE '${name}' not found`,
19
+ };
20
+ /**
21
+ * A utility class for renaming Common Table Expressions (CTEs) in SQL queries.
22
+ *
23
+ * This class provides functionality to safely rename CTEs while automatically updating
24
+ * all column references and table references throughout the query, including within
25
+ * nested CTE definitions and subqueries.
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * import { CTERenamer, SelectQueryParser } from 'rawsql-ts';
30
+ *
31
+ * const sql = `
32
+ * WITH user_data AS (
33
+ * SELECT id, name FROM users
34
+ * ),
35
+ * order_summary AS (
36
+ * SELECT user_data.id, COUNT(*) as order_count
37
+ * FROM user_data
38
+ * JOIN orders ON user_data.id = orders.user_id
39
+ * GROUP BY user_data.id
40
+ * )
41
+ * SELECT * FROM order_summary
42
+ * `;
43
+ *
44
+ * const query = SelectQueryParser.parse(sql);
45
+ * const renamer = new CTERenamer();
46
+ *
47
+ * // Rename 'user_data' to 'customer_data'
48
+ * renamer.renameCTE(query, 'user_data', 'customer_data');
49
+ *
50
+ * // All references are automatically updated:
51
+ * // - CTE definition: WITH customer_data AS (...)
52
+ * // - Column references: customer_data.id
53
+ * // - Table references: FROM customer_data
54
+ * ```
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * // Error handling
59
+ * try {
60
+ * renamer.renameCTE(query, 'nonexistent_cte', 'new_name');
61
+ * } catch (error) {
62
+ * console.error(error.message); // "CTE 'nonexistent_cte' does not exist"
63
+ * }
64
+ *
65
+ * try {
66
+ * renamer.renameCTE(query, 'existing_cte', 'already_exists');
67
+ * } catch (error) {
68
+ * console.error(error.message); // "CTE 'already_exists' already exists"
69
+ * }
70
+ * ```
71
+ *
72
+ * @since 0.11.16
73
+ */
74
+ export class CTERenamer {
75
+ /**
76
+ * Creates a new instance of CTERenamer.
77
+ *
78
+ * The constructor initializes internal collectors and analyzers needed for
79
+ * comprehensive CTE renaming operations.
80
+ */
81
+ constructor() {
82
+ this.dependencyAnalyzer = new CTEDependencyAnalyzer();
83
+ this.columnReferenceCollector = new ColumnReferenceCollector();
84
+ this.tableSourceCollector = new TableSourceCollector(); // Use default selectableOnly=true to avoid infinite recursion
85
+ }
86
+ /**
87
+ * Renames a Common Table Expression (CTE) and updates all references to it.
88
+ *
89
+ * This method performs a comprehensive rename operation that includes:
90
+ * - Updating the CTE definition name in the WITH clause
91
+ * - Updating all column references (e.g., `old_name.column` → `new_name.column`)
92
+ * - Updating all table references in FROM and JOIN clauses
93
+ * - Processing references within nested CTEs and subqueries
94
+ *
95
+ * @param query - The SQL query containing the CTE to rename. Can be either SimpleSelectQuery or BinarySelectQuery (UNION/INTERSECT/EXCEPT).
96
+ * @param oldName - The current name of the CTE to rename.
97
+ * @param newName - The new name for the CTE.
98
+ *
99
+ * @throws {Error} When the specified CTE does not exist in the query.
100
+ * @throws {Error} When a CTE with the new name already exists.
101
+ * @throws {Error} When the query type is not supported (not a SelectQuery).
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * const renamer = new CTERenamer();
106
+ *
107
+ * // Basic usage
108
+ * renamer.renameCTE(query, 'old_cte_name', 'new_cte_name');
109
+ *
110
+ * // With error handling
111
+ * try {
112
+ * renamer.renameCTE(query, 'user_data', 'customer_data');
113
+ * } catch (error) {
114
+ * if (error.message.includes('does not exist')) {
115
+ * console.log('CTE not found');
116
+ * } else if (error.message.includes('already exists')) {
117
+ * console.log('Name conflict');
118
+ * }
119
+ * }
120
+ * ```
121
+ *
122
+ * @since 0.11.16
123
+ */
124
+ renameCTE(query, oldName, newName) {
125
+ // Input validation
126
+ this.validateInputs(query, oldName, newName);
127
+ // Sanitize input names
128
+ const sanitizedOldName = oldName.trim();
129
+ const sanitizedNewName = newName.trim();
130
+ if (query instanceof SimpleSelectQuery) {
131
+ this.renameInSimpleQuery(query, sanitizedOldName, sanitizedNewName);
132
+ }
133
+ else if (query instanceof BinarySelectQuery) {
134
+ this.renameInBinaryQuery(query, sanitizedOldName, sanitizedNewName);
135
+ }
136
+ else {
137
+ throw new Error(ERROR_MESSAGES.unsupportedQuery);
138
+ }
139
+ }
140
+ /**
141
+ * Validates input parameters for CTE renaming.
142
+ */
143
+ validateInputs(query, oldName, newName) {
144
+ if (!query) {
145
+ throw new Error(ERROR_MESSAGES.nullQuery);
146
+ }
147
+ if (!oldName || typeof oldName !== 'string' || oldName.trim() === '') {
148
+ throw new Error(ERROR_MESSAGES.invalidOldName);
149
+ }
150
+ if (!newName || typeof newName !== 'string' || newName.trim() === '') {
151
+ throw new Error(ERROR_MESSAGES.invalidNewName);
152
+ }
153
+ if (oldName.trim() === newName.trim()) {
154
+ throw new Error(ERROR_MESSAGES.sameNames);
155
+ }
156
+ }
157
+ /**
158
+ * Handles CTE renaming for SimpleSelectQuery.
159
+ */
160
+ renameInSimpleQuery(query, oldName, newName) {
161
+ // Get available CTE names
162
+ const availableCTEs = query.getCTENames();
163
+ // Check if CTE exists
164
+ if (!availableCTEs.includes(oldName)) {
165
+ throw new Error(ERROR_MESSAGES.cteNotExists(oldName));
166
+ }
167
+ // Check for name conflicts
168
+ if (availableCTEs.includes(newName)) {
169
+ throw new Error(ERROR_MESSAGES.cteAlreadyExists(newName));
170
+ }
171
+ // Rename CTE definition
172
+ this.renameCTEDefinition(query, oldName, newName);
173
+ // Update all references
174
+ this.updateAllReferences(query, oldName, newName);
175
+ }
176
+ /**
177
+ * Handles CTE renaming for BinarySelectQuery.
178
+ */
179
+ renameInBinaryQuery(query, oldName, newName) {
180
+ // Use toSimpleQuery() only for WITH clause inspection (not for writing back)
181
+ const withClauseQuery = query.toSimpleQuery();
182
+ // Get available CTE names from the converted query
183
+ let availableCTEs = [];
184
+ if (withClauseQuery.withClause && withClauseQuery.withClause.tables) {
185
+ availableCTEs = withClauseQuery.withClause.tables.map(cte => cte.aliasExpression.table.name);
186
+ }
187
+ // Check if CTE exists
188
+ if (!availableCTEs.includes(oldName)) {
189
+ throw new Error(ERROR_MESSAGES.cteNotExists(oldName));
190
+ }
191
+ // Check for name conflicts
192
+ if (availableCTEs.includes(newName)) {
193
+ throw new Error(ERROR_MESSAGES.cteAlreadyExists(newName));
194
+ }
195
+ // Rename CTE definition in the converted query (this affects the original BinarySelectQuery)
196
+ this.renameCTEDefinition(withClauseQuery, oldName, newName);
197
+ // Add withClause to original BinarySelectQuery and left query for proper formatting
198
+ if (withClauseQuery.withClause) {
199
+ query.withClause = withClauseQuery.withClause;
200
+ // Also add to left query so formatter can display it
201
+ if (query.left instanceof SimpleSelectQuery) {
202
+ query.left.withClause = withClauseQuery.withClause;
203
+ }
204
+ }
205
+ // Recursively update references in left and right branches
206
+ this.renameInSelectQuery(query.left, oldName, newName);
207
+ this.renameInSelectQuery(query.right, oldName, newName);
208
+ }
209
+ /**
210
+ * Recursively handles CTE renaming for any SelectQuery type.
211
+ */
212
+ renameInSelectQuery(query, oldName, newName) {
213
+ if (query instanceof SimpleSelectQuery) {
214
+ // For SimpleSelectQuery, only update references (not CTE definitions)
215
+ this.updateAllReferences(query, oldName, newName);
216
+ }
217
+ else if (query instanceof BinarySelectQuery) {
218
+ // Recursively process left and right branches
219
+ this.renameInSelectQuery(query.left, oldName, newName);
220
+ this.renameInSelectQuery(query.right, oldName, newName);
221
+ }
222
+ // ValuesQuery: do nothing
223
+ }
224
+ /**
225
+ * Renames the CTE definition in the WITH clause.
226
+ */
227
+ renameCTEDefinition(query, oldName, newName) {
228
+ if (!query.withClause || !query.withClause.tables) {
229
+ throw new Error(ERROR_MESSAGES.cteNotFound(oldName));
230
+ }
231
+ const cteToRename = query.withClause.tables.find(cte => cte.aliasExpression.table.name === oldName);
232
+ if (!cteToRename) {
233
+ throw new Error(ERROR_MESSAGES.cteNotFound(oldName));
234
+ }
235
+ cteToRename.aliasExpression.table.name = newName;
236
+ }
237
+ /**
238
+ * Updates all references to the old CTE name (column references and table sources).
239
+ */
240
+ updateAllReferences(query, oldName, newName) {
241
+ // Collect all column references from the query (including CTE internals)
242
+ const columnReferences = this.columnReferenceCollector.collect(query);
243
+ // Update all column references that reference the old CTE name
244
+ for (const columnRef of columnReferences) {
245
+ // Check namespaces for the old CTE name
246
+ if (columnRef.namespaces && columnRef.namespaces.length > 0) {
247
+ // Check if any namespace matches the old CTE name
248
+ for (const namespace of columnRef.namespaces) {
249
+ if (namespace.name === oldName) {
250
+ namespace.name = newName;
251
+ break;
252
+ }
253
+ }
254
+ }
255
+ }
256
+ // Update table sources in the main query
257
+ const tableSources = this.tableSourceCollector.collect(query);
258
+ for (const tableSource of tableSources) {
259
+ if (tableSource.getSourceName() === oldName) {
260
+ if (tableSource.qualifiedName.name instanceof ColumnReference) {
261
+ // Handle ColumnReference case if needed
262
+ }
263
+ else if ('name' in tableSource.qualifiedName.name) {
264
+ // Handle IdentifierString
265
+ tableSource.qualifiedName.name.name = newName;
266
+ }
267
+ else {
268
+ // Handle RawString
269
+ tableSource.qualifiedName.name.value = newName;
270
+ }
271
+ }
272
+ }
273
+ // Update table sources that reference the old CTE name within CTEs
274
+ this.updateTableSourcesInCTEs(query, oldName, newName);
275
+ }
276
+ /**
277
+ * Updates table sources within CTE definitions that reference the old CTE name.
278
+ * This method manually traverses CTE internals to avoid infinite recursion
279
+ * that occurs when using TableSourceCollector with selectableOnly=false.
280
+ */
281
+ updateTableSourcesInCTEs(query, oldName, newName) {
282
+ if (!query.withClause || !query.withClause.tables) {
283
+ return;
284
+ }
285
+ // Traverse each CTE and update table sources in their FROM clauses
286
+ for (const cte of query.withClause.tables) {
287
+ this.updateTableSourcesInQuery(cte.query, oldName, newName);
288
+ }
289
+ }
290
+ /**
291
+ * Updates table sources in a specific query (used for CTE internals).
292
+ */
293
+ updateTableSourcesInQuery(query, oldName, newName) {
294
+ // Update FROM clause
295
+ if (query.fromClause && query.fromClause.source.datasource) {
296
+ this.updateTableSource(query.fromClause.source.datasource, oldName, newName);
297
+ }
298
+ // Update JOIN clauses
299
+ if (query.fromClause && query.fromClause.joins) {
300
+ for (const join of query.fromClause.joins) {
301
+ if (join.source.datasource) {
302
+ this.updateTableSource(join.source.datasource, oldName, newName);
303
+ }
304
+ }
305
+ }
306
+ }
307
+ /**
308
+ * Updates a specific table source if it matches the old CTE name.
309
+ */
310
+ updateTableSource(datasource, oldName, newName) {
311
+ // Type guard and null checks for security
312
+ if (!datasource || typeof datasource !== 'object') {
313
+ return;
314
+ }
315
+ const source = datasource;
316
+ // Safely check if this is a TableSource
317
+ if (typeof source.getSourceName === 'function') {
318
+ try {
319
+ const sourceName = source.getSourceName();
320
+ if (sourceName === oldName && source.qualifiedName && typeof source.qualifiedName === 'object') {
321
+ const qualifiedName = source.qualifiedName;
322
+ if (qualifiedName.name && typeof qualifiedName.name === 'object') {
323
+ const nameObj = qualifiedName.name;
324
+ if ('name' in nameObj && typeof nameObj.name === 'string') {
325
+ // Handle IdentifierString
326
+ nameObj.name = newName;
327
+ }
328
+ else if ('value' in nameObj && typeof nameObj.value === 'string') {
329
+ // Handle RawString
330
+ nameObj.value = newName;
331
+ }
332
+ }
333
+ }
334
+ }
335
+ catch (error) {
336
+ // Safely handle any unexpected errors during table source update
337
+ console.warn('Warning: Failed to update table source:', error);
338
+ }
339
+ }
340
+ }
341
+ }
342
+ //# sourceMappingURL=CTERenamer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CTERenamer.js","sourceRoot":"","sources":["../../../../src/transformers/CTERenamer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAEhE,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAE3D;;GAEG;AACH,MAAM,cAAc,GAAG;IACnB,SAAS,EAAE,mCAAmC;IAC9C,cAAc,EAAE,yCAAyC;IACzD,cAAc,EAAE,yCAAyC;IACzD,SAAS,EAAE,0CAA0C;IACrD,gBAAgB,EAAE,yCAAyC;IAC3D,YAAY,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,QAAQ,IAAI,kBAAkB;IAC9D,gBAAgB,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,QAAQ,IAAI,kBAAkB;IAClE,WAAW,EAAE,CAAC,IAA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