Skip to content

Commit ae52c9e

Browse files
Fixed invalid alias usage for WITH in case of subquery
1 parent 26fc6b0 commit ae52c9e

File tree

3 files changed

+14
-6
lines changed

3 files changed

+14
-6
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22

33
All notable changes to this project will be documented in this file.
44

5+
## v1.7.3 - 2023-01-26
6+
7+
### Fixed
8+
- Fixed invalid alias usage for WITH in case of subquery
9+
510
## v1.7.2 - 2023-01-01
611

712
### Fixed

__tests__/Query.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -481,7 +481,7 @@ describe('Query', () => {
481481
.orderBy([['table_disk_usage', 'DESC']])
482482
.limit(10)
483483
.generateSql();
484-
expect(sql).toBe(`WITH (WITH 2022-12-11 AS some_date SELECT sum(bytes) FROM system.parts WHERE active = 1) AS alias SELECT (sum(bytes) / total_disk_usage) * 100 AS table_disk_usage, table FROM system.parts GROUP BY table ORDER BY table_disk_usage DESC LIMIT 10`);
484+
expect(sql).toBe(`WITH alias AS (WITH 2022-12-11 AS some_date SELECT sum(bytes) FROM system.parts WHERE active = 1) SELECT (sum(bytes) / total_disk_usage) * 100 AS table_disk_usage, table FROM system.parts GROUP BY table ORDER BY table_disk_usage DESC LIMIT 10`);
485485
});
486486

487487
it('Using WITH within WITH as list of params', () => {

src/Query.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -197,19 +197,22 @@ export class Query extends FilterableQuery {
197197
}
198198
}
199199
preparedWithPart = `WITH ${withChunks.join(', ')}`;
200+
if (alias) {
201+
preparedWithPart += ` AS ${alias}`;
202+
}
200203
} else if (typeof withPart === 'string') {
201204
preparedWithPart = `WITH '${withPart}'`;
205+
if (alias) {
206+
preparedWithPart += ` AS ${alias}`;
207+
}
202208
} else if (withPart instanceof Query) {
203209
const hasInnerWithStatement = withPart.withPart[0];
204210
if (hasInnerWithStatement) {
205-
preparedWithPart = `WITH (${withPart.generateSql()})`;
211+
preparedWithPart = `WITH ${(alias ? `${alias} AS` : '')} (${withPart.generateSql()})`;
206212
} else {
207-
preparedWithPart = `WITH ${withPart.generateSql()}`;
213+
preparedWithPart = `WITH ${(alias ? `${alias} AS` : '')} ${withPart.generateSql()}`;
208214
}
209215
}
210-
if (alias) {
211-
preparedWithPart = `${preparedWithPart} AS ${alias}`;
212-
}
213216
sql = `${preparedWithPart} ${sql}`;
214217
} else {
215218
if (this.aliasPart) {

0 commit comments

Comments
 (0)