Skip to content

Commit

Permalink
Disallow duplicate CTE aliases (#13664)
Browse files Browse the repository at this point in the history
  • Loading branch information
yashmayya authored Jul 19, 2024
1 parent 205a75d commit 2ccfa74
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
package org.apache.pinot.query.validate;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
Expand All @@ -32,10 +33,13 @@
import org.apache.calcite.sql.SqlNodeList;
import org.apache.calcite.sql.SqlOperatorTable;
import org.apache.calcite.sql.SqlSelect;
import org.apache.calcite.sql.SqlWith;
import org.apache.calcite.sql.SqlWithItem;
import org.apache.calcite.sql.validate.SelectScope;
import org.apache.calcite.sql.validate.SqlConformanceEnum;
import org.apache.calcite.sql.validate.SqlValidatorCatalogReader;
import org.apache.calcite.sql.validate.SqlValidatorImpl;
import org.apache.calcite.sql.validate.SqlValidatorScope;


/**
Expand Down Expand Up @@ -147,4 +151,20 @@ protected void addToSelectList(List<SqlNode> list, Set<String> aliases,
}
super.addToSelectList(list, aliases, fieldList, exp, scope, includeSystemVars);
}

@Override
public void validateWith(SqlWith with, SqlValidatorScope scope) {
Set<String> withNames = new HashSet<>();

for (SqlNode sqlWithItem : with.withList) {
for (String name : ((SqlWithItem) sqlWithItem).name.names) {
if (withNames.contains(name)) {
throw new RuntimeException("Duplicate alias in WITH: '" + name + "' at " + sqlWithItem.getParserPosition());
}
withNames.add(name);
}
}

super.validateWith(with, scope);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,13 @@ public void testGetTableNamesForQuery() {
assertEquals(tableNames.get(0), "a");
}

@Test
public void testDuplicateWithAlias() {
String query = "WITH tmp AS (SELECT * FROM a LIMIT 1), tmp AS (SELECT * FROM a LIMIT 2) SELECT * FROM tmp";
RuntimeException e = expectThrows(RuntimeException.class, () -> _queryEnvironment.getTableNamesForQuery(query));
assertTrue(e.getCause().getMessage().contains("Duplicate alias in WITH: 'tmp'"));
}

// --------------------------------------------------------------------------
// Test Utils.
// --------------------------------------------------------------------------
Expand Down

0 comments on commit 2ccfa74

Please sign in to comment.