diff --git a/beeline/src/java/org/apache/hive/beeline/Commands.java b/beeline/src/java/org/apache/hive/beeline/Commands.java index 80703fffc234be2df56c6fca590b7d22821c455b..b169e7e4d97cb2253a0e8117239413eebc25ca40 100644 --- a/beeline/src/java/org/apache/hive/beeline/Commands.java +++ b/beeline/src/java/org/apache/hive/beeline/Commands.java @@ -22,6 +22,7 @@ */ package org.apache.hive.beeline; +import com.google.common.annotations.VisibleForTesting; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.conf.HiveVariableSource; import org.apache.hadoop.hive.conf.SystemVariables; @@ -1028,7 +1029,32 @@ private boolean executeInternal(String sql, boolean call) { return true; } + @VisibleForTesting + String removeComments(String line) { + if (line == null || line.isEmpty()) return line; + + StringBuilder builder = new StringBuilder(); + boolean quoted = false; + for (int index = 0; index < line.length(); index++) { + char letter = line.charAt(index); + if (letter == '\'' || letter == '"') { + quoted = !quoted; + builder.append(letter); + } else if (quoted) { + builder.append(letter); + } else if (index >= line.length() - 1 || (line.charAt(index) != line.charAt(index + 1))) { + builder.append(letter); + } else { + return builder.toString().trim(); + } + } + + return builder.toString().trim(); + } + public String handleMultiLineCmd(String line) throws IOException { + line = removeComments(line); + //When using -e, console reader is not initialized and command is a single line while (beeLine.getConsoleReader() != null && !(line.trim().endsWith(";")) && beeLine.getOpts() .isAllowMultiLineCommand()) { diff --git a/beeline/src/test/org/apache/hive/beeline/TestCommands.java b/beeline/src/test/org/apache/hive/beeline/TestCommands.java index 5c8b2d6d8c5cf864ec3af17dfb2cbfc47f25533c..29de7e3cf29b89adf93672f5e7ac2fa4e2e45b58 100644 --- a/beeline/src/test/org/apache/hive/beeline/TestCommands.java +++ b/beeline/src/test/org/apache/hive/beeline/TestCommands.java @@ -32,5 +32,15 @@ public void testLinesEndingWithComments() { Commands commands = new Commands(beeline); assertEquals("show tables;", commands.removeComments("show tables;")); + assertEquals("show tables;", commands.removeComments("show tables; --comments")); + assertEquals("show tables;", commands.removeComments("show tables; -------comments")); + assertEquals("show tables;", commands.removeComments("show tables; -------comments;one;two;three;;;;")); + assertEquals("show", commands.removeComments("show-- tables; -------comments")); + assertEquals("show", commands.removeComments("show --tables; -------comments")); + assertEquals("s", commands.removeComments("s--how --tables; -------comments")); + assertEquals("", commands.removeComments("-- show tables; -------comments")); + + assertEquals("\"show tables\"", commands.removeComments("\"show tables\" --comments")); + assertEquals("\"show --comments tables\"", commands.removeComments("\"show --comments tables\" --comments")); } }