Skip to content

Commit

Permalink
Sanitize Symbol names for unambiguous plans
Browse files Browse the repository at this point in the history
  • Loading branch information
findepi committed Mar 22, 2024
1 parent 84f8c05 commit 5c19d1c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
12 changes: 11 additions & 1 deletion core/trino-main/src/main/java/io/trino/sql/planner/Symbol.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,25 @@
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.base.CharMatcher;
import io.trino.spi.type.Type;
import io.trino.sql.ir.Expression;
import io.trino.sql.ir.Reference;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;

@JsonSerialize(keyUsing = SymbolKeySerializer.class)
public class Symbol
implements Comparable<Symbol>
{
// Allow limited set of characters in symbol names to avoid ambiguities in the rendered plans.
public static final CharMatcher SYMBOL_NAME_MATCHER = CharMatcher.inRange('a', 'z')
.or(CharMatcher.inRange('A', 'Z'))
.or(CharMatcher.inRange('0', '9'))
.or(CharMatcher.anyOf("[]:_$"))
.precomputed();

private final String name;
private final Type type;

Expand All @@ -40,8 +49,9 @@ public static Symbol from(Expression expression)
@JsonCreator
public Symbol(Type type, String name)
{
requireNonNull(name, "name is null");
requireNonNull(type, "type is null");
checkArgument(!name.isEmpty(), "name cannot be empty");
checkArgument(SYMBOL_NAME_MATCHER.matchesAllOf(name), "Invalid characters in symbol name: [%s]", name);
this.type = type;
this.name = name;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
import java.util.HashMap;
import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;
import static io.trino.sql.planner.Symbol.SYMBOL_NAME_MATCHER;
import static java.util.Locale.ENGLISH;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toMap;
Expand Down Expand Up @@ -85,9 +87,10 @@ public Symbol newSymbol(String nameHint, Type type, @Nullable String suffix)
}
}

String unique = nameHint;
String unique = SYMBOL_NAME_MATCHER.retainFrom(nameHint);

if (suffix != null) {
checkArgument(SYMBOL_NAME_MATCHER.matchesAllOf(suffix), "Invalid characters in symbol suffix: [%s]", suffix);
unique = unique + "$" + suffix;
}

Expand Down

0 comments on commit 5c19d1c

Please sign in to comment.